15 #define DEBUG_ERROR_MESSAGES 0
16 #define DEBUG_COLOR_GRAPH 0
18 #define DEBUG_CONSISTENCY 1
20 #warning "FIXME boundary cases with small types in larger registers"
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
850 #define REGISTER_BITS 28
851 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
852 #define TEMPLATE_BITS 6
853 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
856 #define REG_UNNEEDED 1
857 #define REG_VIRT0 (MAX_REGISTERS + 0)
858 #define REG_VIRT1 (MAX_REGISTERS + 1)
859 #define REG_VIRT2 (MAX_REGISTERS + 2)
860 #define REG_VIRT3 (MAX_REGISTERS + 3)
861 #define REG_VIRT4 (MAX_REGISTERS + 4)
862 #define REG_VIRT5 (MAX_REGISTERS + 5)
864 /* Provision for 8 register classes */
865 #define REG_MASK (MAX_VIRT_REGISTERS -1)
866 #define ID_REG(ID) ((ID) & REG_MASK)
867 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
869 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
870 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
871 static void arch_reg_equivs(
872 struct compile_state *state, unsigned *equiv, int reg);
873 static int arch_select_free_register(
874 struct compile_state *state, char *used, int classes);
875 static unsigned arch_regc_size(struct compile_state *state, int class);
876 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
877 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
878 static const char *arch_reg_str(int reg);
879 static struct reg_info arch_reg_constraint(
880 struct compile_state *state, struct type *type, const char *constraint);
881 static struct reg_info arch_reg_clobber(
882 struct compile_state *state, const char *clobber);
883 static struct reg_info arch_reg_lhs(struct compile_state *state,
884 struct triple *ins, int index);
885 static struct reg_info arch_reg_rhs(struct compile_state *state,
886 struct triple *ins, int index);
887 static struct triple *transform_to_arch_instruction(
888 struct compile_state *state, struct triple *ins);
892 #define DEBUG_ABORT_ON_ERROR 0x0001
893 #define DEBUG_INTERMEDIATE_CODE 0x0002
894 #define DEBUG_CONTROL_FLOW 0x0004
895 #define DEBUG_BASIC_BLOCKS 0x0008
896 #define DEBUG_FDOMINATORS 0x0010
897 #define DEBUG_RDOMINATORS 0x0020
898 #define DEBUG_TRIPLES 0x0040
899 #define DEBUG_INTERFERENCE 0x0080
900 #define DEBUG_ARCH_CODE 0x0100
901 #define DEBUG_CODE_ELIMINATION 0x0200
902 #define DEBUG_INSERTED_COPIES 0x0400
904 #define GLOBAL_SCOPE_DEPTH 1
906 static void compile_file(struct compile_state *old_state, const char *filename, int local);
908 static void do_cleanup(struct compile_state *state)
911 fclose(state->output);
912 unlink(state->ofilename);
916 static int get_col(struct file_state *file)
920 ptr = file->line_start;
922 for(col = 0; ptr < end; ptr++) {
927 col = (col & ~7) + 8;
933 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
937 fprintf(fp, "%s:%d.%d: ",
938 triple->filename, triple->line, triple->col);
944 col = get_col(state->file);
945 fprintf(fp, "%s:%d.%d: ",
946 state->file->basename, state->file->line, col);
949 static void __internal_error(struct compile_state *state, struct triple *ptr,
954 loc(stderr, state, ptr);
956 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
958 fprintf(stderr, "Internal compiler error: ");
959 vfprintf(stderr, fmt, args);
960 fprintf(stderr, "\n");
967 static void __internal_warning(struct compile_state *state, struct triple *ptr,
972 loc(stderr, state, ptr);
973 fprintf(stderr, "Internal compiler warning: ");
974 vfprintf(stderr, fmt, args);
975 fprintf(stderr, "\n");
981 static void __error(struct compile_state *state, struct triple *ptr,
986 loc(stderr, state, ptr);
987 vfprintf(stderr, fmt, args);
989 fprintf(stderr, "\n");
991 if (state->debug & DEBUG_ABORT_ON_ERROR) {
997 static void __warning(struct compile_state *state, struct triple *ptr,
1001 va_start(args, fmt);
1002 loc(stderr, state, ptr);
1003 fprintf(stderr, "warning: ");
1004 vfprintf(stderr, fmt, args);
1005 fprintf(stderr, "\n");
1009 #if DEBUG_ERROR_MESSAGES
1010 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1011 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1012 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1013 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1015 # define internal_error __internal_error
1016 # define internal_warning __internal_warning
1017 # define error __error
1018 # define warning __warning
1020 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1022 static void valid_op(struct compile_state *state, int op)
1024 char *fmt = "invalid op: %d";
1026 internal_error(state, 0, fmt, op);
1029 internal_error(state, 0, fmt, op);
1033 static void valid_ins(struct compile_state *state, struct triple *ptr)
1035 valid_op(state, ptr->op);
1038 static void process_trigraphs(struct compile_state *state)
1040 char *src, *dest, *end;
1041 struct file_state *file;
1043 src = dest = file->buf;
1044 end = file->buf + file->size;
1045 while((end - src) >= 3) {
1046 if ((src[0] == '?') && (src[1] == '?')) {
1049 case '=': c = '#'; break;
1050 case '/': c = '\\'; break;
1051 case '\'': c = '^'; break;
1052 case '(': c = '['; break;
1053 case ')': c = ']'; break;
1054 case '!': c = '!'; break;
1055 case '<': c = '{'; break;
1056 case '>': c = '}'; break;
1057 case '-': c = '~'; break;
1074 file->size = dest - file->buf;
1077 static void splice_lines(struct compile_state *state)
1079 char *src, *dest, *end;
1080 struct file_state *file;
1082 src = dest = file->buf;
1083 end = file->buf + file->size;
1084 while((end - src) >= 2) {
1085 if ((src[0] == '\\') && (src[1] == '\n')) {
1095 file->size = dest - file->buf;
1098 static struct type void_type;
1099 static void use_triple(struct triple *used, struct triple *user)
1101 struct triple_set **ptr, *new;
1108 if ((*ptr)->member == user) {
1111 ptr = &(*ptr)->next;
1113 /* Append new to the head of the list,
1114 * copy_func and rename_block_variables
1117 new = xcmalloc(sizeof(*new), "triple_set");
1119 new->next = used->use;
1123 static void unuse_triple(struct triple *used, struct triple *unuser)
1125 struct triple_set *use, **ptr;
1132 if (use->member == unuser) {
1142 static void push_triple(struct triple *used, struct triple *user)
1144 struct triple_set *new;
1149 /* Append new to the head of the list,
1150 * it's the only sensible behavoir for a stack.
1152 new = xcmalloc(sizeof(*new), "triple_set");
1154 new->next = used->use;
1158 static void pop_triple(struct triple *used, struct triple *unuser)
1160 struct triple_set *use, **ptr;
1164 if (use->member == unuser) {
1167 /* Only free one occurance from the stack */
1177 /* The zero triple is used as a place holder when we are removing pointers
1178 * from a triple. Having allows certain sanity checks to pass even
1179 * when the original triple that was pointed to is gone.
1181 static struct triple zero_triple = {
1182 .next = &zero_triple,
1183 .prev = &zero_triple,
1186 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1187 .id = -1, /* An invalid id */
1188 .u = { .cval = 0, },
1189 .filename = __FILE__,
1192 .param { [0] = 0, [1] = 0, },
1196 static unsigned short triple_sizes(struct compile_state *state,
1197 int op, struct type *type, int lhs_wanted, int rhs_wanted)
1199 int lhs, rhs, misc, targ;
1200 valid_op(state, op);
1201 lhs = table_ops[op].lhs;
1202 rhs = table_ops[op].rhs;
1203 misc = table_ops[op].misc;
1204 targ = table_ops[op].targ;
1207 if (op == OP_CALL) {
1210 param = type->right;
1211 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1213 param = param->right;
1215 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1219 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1220 lhs = type->left->elements;
1223 else if (op == OP_VAL_VEC) {
1224 rhs = type->elements;
1226 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1229 else if (op == OP_ASM) {
1233 if ((rhs < 0) || (rhs > MAX_RHS)) {
1234 internal_error(state, 0, "bad rhs");
1236 if ((lhs < 0) || (lhs > MAX_LHS)) {
1237 internal_error(state, 0, "bad lhs");
1239 if ((misc < 0) || (misc > MAX_MISC)) {
1240 internal_error(state, 0, "bad misc");
1242 if ((targ < 0) || (targ > MAX_TARG)) {
1243 internal_error(state, 0, "bad targs");
1245 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1248 static struct triple *alloc_triple(struct compile_state *state,
1249 int op, struct type *type, int lhs, int rhs,
1250 const char *filename, int line, int col)
1252 size_t size, sizes, extra_count, min_count;
1254 sizes = triple_sizes(state, op, type, lhs, rhs);
1256 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1257 extra_count = TRIPLE_SIZE(sizes);
1258 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1260 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1261 ret = xcmalloc(size, "tripple");
1267 ret->filename = filename;
1273 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1276 int src_lhs, src_rhs, src_size;
1277 src_lhs = TRIPLE_LHS(src->sizes);
1278 src_rhs = TRIPLE_RHS(src->sizes);
1279 src_size = TRIPLE_SIZE(src->sizes);
1280 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1281 src->filename, src->line, src->col);
1282 memcpy(dup, src, sizeof(*src));
1283 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1287 static struct triple *new_triple(struct compile_state *state,
1288 int op, struct type *type, int lhs, int rhs)
1291 const char *filename;
1297 filename = state->file->basename;
1298 line = state->file->line;
1299 col = get_col(state->file);
1301 ret = alloc_triple(state, op, type, lhs, rhs,
1302 filename, line, col);
1306 static struct triple *build_triple(struct compile_state *state,
1307 int op, struct type *type, struct triple *left, struct triple *right,
1308 const char *filename, int line, int col)
1312 ret = alloc_triple(state, op, type, -1, -1, filename, line, col);
1313 count = TRIPLE_SIZE(ret->sizes);
1315 ret->param[0] = left;
1318 ret->param[1] = right;
1323 static struct triple *triple(struct compile_state *state,
1324 int op, struct type *type, struct triple *left, struct triple *right)
1328 ret = new_triple(state, op, type, -1, -1);
1329 count = TRIPLE_SIZE(ret->sizes);
1331 ret->param[0] = left;
1334 ret->param[1] = right;
1339 static struct triple *branch(struct compile_state *state,
1340 struct triple *targ, struct triple *test)
1343 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1347 TARG(ret, 0) = targ;
1348 /* record the branch target was used */
1349 if (!targ || (targ->op != OP_LABEL)) {
1350 internal_error(state, 0, "branch not to label");
1351 use_triple(targ, ret);
1357 static void insert_triple(struct compile_state *state,
1358 struct triple *first, struct triple *ptr)
1361 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1362 internal_error(state, ptr, "expression already used");
1365 ptr->prev = first->prev;
1366 ptr->prev->next = ptr;
1367 ptr->next->prev = ptr;
1368 if ((ptr->prev->op == OP_BRANCH) &&
1369 TRIPLE_RHS(ptr->prev->sizes)) {
1370 unuse_triple(first, ptr->prev);
1371 use_triple(ptr, ptr->prev);
1376 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1378 /* This function is used to determine if u.block
1379 * is utilized to store the current block number.
1382 valid_ins(state, ins);
1383 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1384 return stores_block;
1387 static struct block *block_of_triple(struct compile_state *state,
1390 struct triple *first;
1391 first = RHS(state->main_function, 0);
1392 while(ins != first && !triple_stores_block(state, ins)) {
1393 if (ins == ins->prev) {
1394 internal_error(state, 0, "ins == ins->prev?");
1398 if (!triple_stores_block(state, ins)) {
1399 internal_error(state, ins, "Cannot find block");
1401 return ins->u.block;
1404 static struct triple *pre_triple(struct compile_state *state,
1405 struct triple *base,
1406 int op, struct type *type, struct triple *left, struct triple *right)
1408 struct block *block;
1410 block = block_of_triple(state, base);
1411 ret = build_triple(state, op, type, left, right,
1412 base->filename, base->line, base->col);
1413 if (triple_stores_block(state, ret)) {
1414 ret->u.block = block;
1416 insert_triple(state, base, ret);
1417 if (block->first == base) {
1423 static struct triple *post_triple(struct compile_state *state,
1424 struct triple *base,
1425 int op, struct type *type, struct triple *left, struct triple *right)
1427 struct block *block;
1429 block = block_of_triple(state, base);
1430 ret = build_triple(state, op, type, left, right,
1431 base->filename, base->line, base->col);
1432 if (triple_stores_block(state, ret)) {
1433 ret->u.block = block;
1435 insert_triple(state, base->next, ret);
1436 if (block->last == base) {
1442 static struct triple *label(struct compile_state *state)
1444 /* Labels don't get a type */
1445 struct triple *result;
1446 result = triple(state, OP_LABEL, &void_type, 0, 0);
1450 static void display_triple(FILE *fp, struct triple *ins)
1452 if (ins->op == OP_INTCONST) {
1453 fprintf(fp, "(%p) %3d %-2d %-10s <0x%08lx> @ %s:%d.%d\n",
1454 ins, ID_REG(ins->id), ins->template_id, tops(ins->op),
1456 ins->filename, ins->line, ins->col);
1458 else if (ins->op == OP_ADDRCONST) {
1459 fprintf(fp, "(%p) %3d %-2d %-10s %-10p <0x%08lx> @ %s:%d.%d\n",
1460 ins, ID_REG(ins->id), ins->template_id, tops(ins->op),
1461 MISC(ins, 0), ins->u.cval,
1462 ins->filename, ins->line, ins->col);
1466 fprintf(fp, "(%p) %3d %-2d %-10s",
1467 ins, ID_REG(ins->id), ins->template_id, tops(ins->op));
1468 count = TRIPLE_SIZE(ins->sizes);
1469 for(i = 0; i < count; i++) {
1470 fprintf(fp, " %-10p", ins->param[i]);
1475 fprintf(fp, " @ %s:%d.%d\n",
1476 ins->filename, ins->line, ins->col);
1481 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1483 /* Does the triple have no side effects.
1484 * I.e. Rexecuting the triple with the same arguments
1485 * gives the same value.
1488 valid_ins(state, ins);
1489 pure = PURE_BITS(table_ops[ins->op].flags);
1490 if ((pure != PURE) && (pure != IMPURE)) {
1491 internal_error(state, 0, "Purity of %s not known\n",
1494 return pure == PURE;
1497 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1499 /* This function is used to determine which triples need
1503 valid_ins(state, ins);
1504 is_branch = (table_ops[ins->op].targ != 0);
1508 static int triple_is_def(struct compile_state *state, struct triple *ins)
1510 /* This function is used to determine which triples need
1514 valid_ins(state, ins);
1515 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1519 static struct triple **triple_iter(struct compile_state *state,
1520 size_t count, struct triple **vector,
1521 struct triple *ins, struct triple **last)
1523 struct triple **ret;
1529 else if ((last >= vector) && (last < (vector + count - 1))) {
1537 static struct triple **triple_lhs(struct compile_state *state,
1538 struct triple *ins, struct triple **last)
1540 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1544 static struct triple **triple_rhs(struct compile_state *state,
1545 struct triple *ins, struct triple **last)
1547 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1551 static struct triple **triple_misc(struct compile_state *state,
1552 struct triple *ins, struct triple **last)
1554 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1558 static struct triple **triple_targ(struct compile_state *state,
1559 struct triple *ins, struct triple **last)
1562 struct triple **ret, **vector;
1564 count = TRIPLE_TARG(ins->sizes);
1565 vector = &TARG(ins, 0);
1570 else if ((last >= vector) && (last < (vector + count - 1))) {
1573 else if ((last == (vector + count - 1)) &&
1574 TRIPLE_RHS(ins->sizes)) {
1582 static void verify_use(struct compile_state *state,
1583 struct triple *user, struct triple *used)
1586 size = TRIPLE_SIZE(user->sizes);
1587 for(i = 0; i < size; i++) {
1588 if (user->param[i] == used) {
1592 if (triple_is_branch(state, user)) {
1593 if (user->next == used) {
1598 internal_error(state, user, "%s(%p) does not use %s(%p)",
1599 tops(user->op), user, tops(used->op), used);
1603 static int find_rhs_use(struct compile_state *state,
1604 struct triple *user, struct triple *used)
1606 struct triple **param;
1608 verify_use(state, user, used);
1609 size = TRIPLE_RHS(user->sizes);
1610 param = &RHS(user, 0);
1611 for(i = 0; i < size; i++) {
1612 if (param[i] == used) {
1619 static void free_triple(struct compile_state *state, struct triple *ptr)
1622 size = sizeof(*ptr) - sizeof(ptr->param) +
1623 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1624 ptr->prev->next = ptr->next;
1625 ptr->next->prev = ptr->prev;
1627 internal_error(state, ptr, "ptr->use != 0");
1629 memset(ptr, -1, size);
1633 static void release_triple(struct compile_state *state, struct triple *ptr)
1635 struct triple_set *set, *next;
1636 struct triple **expr;
1637 /* Remove ptr from use chains where it is the user */
1638 expr = triple_rhs(state, ptr, 0);
1639 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1641 unuse_triple(*expr, ptr);
1644 expr = triple_lhs(state, ptr, 0);
1645 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1647 unuse_triple(*expr, ptr);
1650 expr = triple_misc(state, ptr, 0);
1651 for(; expr; expr = triple_misc(state, ptr, expr)) {
1653 unuse_triple(*expr, ptr);
1656 expr = triple_targ(state, ptr, 0);
1657 for(; expr; expr = triple_targ(state, ptr, expr)) {
1659 unuse_triple(*expr, ptr);
1662 /* Reomve ptr from use chains where it is used */
1663 for(set = ptr->use; set; set = next) {
1665 expr = triple_rhs(state, set->member, 0);
1666 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1668 *expr = &zero_triple;
1671 expr = triple_lhs(state, set->member, 0);
1672 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1674 *expr = &zero_triple;
1677 expr = triple_misc(state, set->member, 0);
1678 for(; expr; expr = triple_misc(state, set->member, expr)) {
1680 *expr = &zero_triple;
1683 expr = triple_targ(state, set->member, 0);
1684 for(; expr; expr = triple_targ(state, set->member, expr)) {
1686 *expr = &zero_triple;
1689 unuse_triple(ptr, set->member);
1691 free_triple(state, ptr);
1694 static void print_triple(struct compile_state *state, struct triple *ptr);
1696 #define TOK_UNKNOWN 0
1699 #define TOK_LBRACE 3
1700 #define TOK_RBRACE 4
1704 #define TOK_LBRACKET 8
1705 #define TOK_RBRACKET 9
1706 #define TOK_LPAREN 10
1707 #define TOK_RPAREN 11
1712 #define TOK_TIMESEQ 16
1713 #define TOK_DIVEQ 17
1714 #define TOK_MODEQ 18
1715 #define TOK_PLUSEQ 19
1716 #define TOK_MINUSEQ 20
1719 #define TOK_ANDEQ 23
1720 #define TOK_XOREQ 24
1723 #define TOK_NOTEQ 27
1724 #define TOK_QUEST 28
1725 #define TOK_LOGOR 29
1726 #define TOK_LOGAND 30
1730 #define TOK_LESSEQ 34
1731 #define TOK_MOREEQ 35
1735 #define TOK_MINUS 39
1738 #define TOK_PLUSPLUS 42
1739 #define TOK_MINUSMINUS 43
1741 #define TOK_ARROW 45
1743 #define TOK_TILDE 47
1744 #define TOK_LIT_STRING 48
1745 #define TOK_LIT_CHAR 49
1746 #define TOK_LIT_INT 50
1747 #define TOK_LIT_FLOAT 51
1748 #define TOK_MACRO 52
1749 #define TOK_CONCATENATE 53
1751 #define TOK_IDENT 54
1752 #define TOK_STRUCT_NAME 55
1753 #define TOK_ENUM_CONST 56
1754 #define TOK_TYPE_NAME 57
1757 #define TOK_BREAK 59
1760 #define TOK_CONST 62
1761 #define TOK_CONTINUE 63
1762 #define TOK_DEFAULT 64
1764 #define TOK_DOUBLE 66
1767 #define TOK_EXTERN 69
1768 #define TOK_FLOAT 70
1772 #define TOK_INLINE 74
1775 #define TOK_REGISTER 77
1776 #define TOK_RESTRICT 78
1777 #define TOK_RETURN 79
1778 #define TOK_SHORT 80
1779 #define TOK_SIGNED 81
1780 #define TOK_SIZEOF 82
1781 #define TOK_STATIC 83
1782 #define TOK_STRUCT 84
1783 #define TOK_SWITCH 85
1784 #define TOK_TYPEDEF 86
1785 #define TOK_UNION 87
1786 #define TOK_UNSIGNED 88
1788 #define TOK_VOLATILE 90
1789 #define TOK_WHILE 91
1791 #define TOK_ATTRIBUTE 93
1792 #define TOK_ALIGNOF 94
1793 #define TOK_FIRST_KEYWORD TOK_AUTO
1794 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1796 #define TOK_DEFINE 100
1797 #define TOK_UNDEF 101
1798 #define TOK_INCLUDE 102
1799 #define TOK_LINE 103
1800 #define TOK_ERROR 104
1801 #define TOK_WARNING 105
1802 #define TOK_PRAGMA 106
1803 #define TOK_IFDEF 107
1804 #define TOK_IFNDEF 108
1805 #define TOK_ELIF 109
1806 #define TOK_ENDIF 110
1808 #define TOK_FIRST_MACRO TOK_DEFINE
1809 #define TOK_LAST_MACRO TOK_ENDIF
1813 static const char *tokens[] = {
1814 [TOK_UNKNOWN ] = "unknown",
1815 [TOK_SPACE ] = ":space:",
1817 [TOK_LBRACE ] = "{",
1818 [TOK_RBRACE ] = "}",
1822 [TOK_LBRACKET ] = "[",
1823 [TOK_RBRACKET ] = "]",
1824 [TOK_LPAREN ] = "(",
1825 [TOK_RPAREN ] = ")",
1827 [TOK_DOTS ] = "...",
1830 [TOK_TIMESEQ ] = "*=",
1831 [TOK_DIVEQ ] = "/=",
1832 [TOK_MODEQ ] = "%=",
1833 [TOK_PLUSEQ ] = "+=",
1834 [TOK_MINUSEQ ] = "-=",
1835 [TOK_SLEQ ] = "<<=",
1836 [TOK_SREQ ] = ">>=",
1837 [TOK_ANDEQ ] = "&=",
1838 [TOK_XOREQ ] = "^=",
1841 [TOK_NOTEQ ] = "!=",
1843 [TOK_LOGOR ] = "||",
1844 [TOK_LOGAND ] = "&&",
1848 [TOK_LESSEQ ] = "<=",
1849 [TOK_MOREEQ ] = ">=",
1856 [TOK_PLUSPLUS ] = "++",
1857 [TOK_MINUSMINUS ] = "--",
1859 [TOK_ARROW ] = "->",
1862 [TOK_LIT_STRING ] = ":string:",
1863 [TOK_IDENT ] = ":ident:",
1864 [TOK_TYPE_NAME ] = ":typename:",
1865 [TOK_LIT_CHAR ] = ":char:",
1866 [TOK_LIT_INT ] = ":integer:",
1867 [TOK_LIT_FLOAT ] = ":float:",
1869 [TOK_CONCATENATE ] = "##",
1871 [TOK_AUTO ] = "auto",
1872 [TOK_BREAK ] = "break",
1873 [TOK_CASE ] = "case",
1874 [TOK_CHAR ] = "char",
1875 [TOK_CONST ] = "const",
1876 [TOK_CONTINUE ] = "continue",
1877 [TOK_DEFAULT ] = "default",
1879 [TOK_DOUBLE ] = "double",
1880 [TOK_ELSE ] = "else",
1881 [TOK_ENUM ] = "enum",
1882 [TOK_EXTERN ] = "extern",
1883 [TOK_FLOAT ] = "float",
1885 [TOK_GOTO ] = "goto",
1887 [TOK_INLINE ] = "inline",
1889 [TOK_LONG ] = "long",
1890 [TOK_REGISTER ] = "register",
1891 [TOK_RESTRICT ] = "restrict",
1892 [TOK_RETURN ] = "return",
1893 [TOK_SHORT ] = "short",
1894 [TOK_SIGNED ] = "signed",
1895 [TOK_SIZEOF ] = "sizeof",
1896 [TOK_STATIC ] = "static",
1897 [TOK_STRUCT ] = "struct",
1898 [TOK_SWITCH ] = "switch",
1899 [TOK_TYPEDEF ] = "typedef",
1900 [TOK_UNION ] = "union",
1901 [TOK_UNSIGNED ] = "unsigned",
1902 [TOK_VOID ] = "void",
1903 [TOK_VOLATILE ] = "volatile",
1904 [TOK_WHILE ] = "while",
1906 [TOK_ATTRIBUTE ] = "__attribute__",
1907 [TOK_ALIGNOF ] = "__alignof__",
1909 [TOK_DEFINE ] = "define",
1910 [TOK_UNDEF ] = "undef",
1911 [TOK_INCLUDE ] = "include",
1912 [TOK_LINE ] = "line",
1913 [TOK_ERROR ] = "error",
1914 [TOK_WARNING ] = "warning",
1915 [TOK_PRAGMA ] = "pragma",
1916 [TOK_IFDEF ] = "ifdef",
1917 [TOK_IFNDEF ] = "ifndef",
1918 [TOK_ELIF ] = "elif",
1919 [TOK_ENDIF ] = "endif",
1924 static unsigned int hash(const char *str, int str_len)
1928 end = str + str_len;
1930 for(; str < end; str++) {
1931 hash = (hash *263) + *str;
1933 hash = hash & (HASH_TABLE_SIZE -1);
1937 static struct hash_entry *lookup(
1938 struct compile_state *state, const char *name, int name_len)
1940 struct hash_entry *entry;
1942 index = hash(name, name_len);
1943 entry = state->hash_table[index];
1945 ((entry->name_len != name_len) ||
1946 (memcmp(entry->name, name, name_len) != 0))) {
1947 entry = entry->next;
1951 /* Get a private copy of the name */
1952 new_name = xmalloc(name_len + 1, "hash_name");
1953 memcpy(new_name, name, name_len);
1954 new_name[name_len] = '\0';
1956 /* Create a new hash entry */
1957 entry = xcmalloc(sizeof(*entry), "hash_entry");
1958 entry->next = state->hash_table[index];
1959 entry->name = new_name;
1960 entry->name_len = name_len;
1962 /* Place the new entry in the hash table */
1963 state->hash_table[index] = entry;
1968 static void ident_to_keyword(struct compile_state *state, struct token *tk)
1970 struct hash_entry *entry;
1972 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
1973 (entry->tok == TOK_ENUM_CONST) ||
1974 ((entry->tok >= TOK_FIRST_KEYWORD) &&
1975 (entry->tok <= TOK_LAST_KEYWORD)))) {
1976 tk->tok = entry->tok;
1980 static void ident_to_macro(struct compile_state *state, struct token *tk)
1982 struct hash_entry *entry;
1985 (entry->tok >= TOK_FIRST_MACRO) &&
1986 (entry->tok <= TOK_LAST_MACRO)) {
1987 tk->tok = entry->tok;
1991 static void hash_keyword(
1992 struct compile_state *state, const char *keyword, int tok)
1994 struct hash_entry *entry;
1995 entry = lookup(state, keyword, strlen(keyword));
1996 if (entry && entry->tok != TOK_UNKNOWN) {
1997 die("keyword %s already hashed", keyword);
2003 struct compile_state *state, struct hash_entry *ident,
2004 struct symbol **chain, struct triple *def, struct type *type)
2007 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2008 error(state, 0, "%s already defined", ident->name);
2010 sym = xcmalloc(sizeof(*sym), "symbol");
2014 sym->scope_depth = state->scope_depth;
2019 static void start_scope(struct compile_state *state)
2021 state->scope_depth++;
2024 static void end_scope_syms(struct symbol **chain, int depth)
2026 struct symbol *sym, *next;
2028 while(sym && (sym->scope_depth == depth)) {
2036 static void end_scope(struct compile_state *state)
2040 /* Walk through the hash table and remove all symbols
2041 * in the current scope.
2043 depth = state->scope_depth;
2044 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2045 struct hash_entry *entry;
2046 entry = state->hash_table[i];
2048 end_scope_syms(&entry->sym_label, depth);
2049 end_scope_syms(&entry->sym_struct, depth);
2050 end_scope_syms(&entry->sym_ident, depth);
2051 entry = entry->next;
2054 state->scope_depth = depth - 1;
2057 static void register_keywords(struct compile_state *state)
2059 hash_keyword(state, "auto", TOK_AUTO);
2060 hash_keyword(state, "break", TOK_BREAK);
2061 hash_keyword(state, "case", TOK_CASE);
2062 hash_keyword(state, "char", TOK_CHAR);
2063 hash_keyword(state, "const", TOK_CONST);
2064 hash_keyword(state, "continue", TOK_CONTINUE);
2065 hash_keyword(state, "default", TOK_DEFAULT);
2066 hash_keyword(state, "do", TOK_DO);
2067 hash_keyword(state, "double", TOK_DOUBLE);
2068 hash_keyword(state, "else", TOK_ELSE);
2069 hash_keyword(state, "enum", TOK_ENUM);
2070 hash_keyword(state, "extern", TOK_EXTERN);
2071 hash_keyword(state, "float", TOK_FLOAT);
2072 hash_keyword(state, "for", TOK_FOR);
2073 hash_keyword(state, "goto", TOK_GOTO);
2074 hash_keyword(state, "if", TOK_IF);
2075 hash_keyword(state, "inline", TOK_INLINE);
2076 hash_keyword(state, "int", TOK_INT);
2077 hash_keyword(state, "long", TOK_LONG);
2078 hash_keyword(state, "register", TOK_REGISTER);
2079 hash_keyword(state, "restrict", TOK_RESTRICT);
2080 hash_keyword(state, "return", TOK_RETURN);
2081 hash_keyword(state, "short", TOK_SHORT);
2082 hash_keyword(state, "signed", TOK_SIGNED);
2083 hash_keyword(state, "sizeof", TOK_SIZEOF);
2084 hash_keyword(state, "static", TOK_STATIC);
2085 hash_keyword(state, "struct", TOK_STRUCT);
2086 hash_keyword(state, "switch", TOK_SWITCH);
2087 hash_keyword(state, "typedef", TOK_TYPEDEF);
2088 hash_keyword(state, "union", TOK_UNION);
2089 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2090 hash_keyword(state, "void", TOK_VOID);
2091 hash_keyword(state, "volatile", TOK_VOLATILE);
2092 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2093 hash_keyword(state, "while", TOK_WHILE);
2094 hash_keyword(state, "asm", TOK_ASM);
2095 hash_keyword(state, "__asm__", TOK_ASM);
2096 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2097 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2100 static void register_macro_keywords(struct compile_state *state)
2102 hash_keyword(state, "define", TOK_DEFINE);
2103 hash_keyword(state, "undef", TOK_UNDEF);
2104 hash_keyword(state, "include", TOK_INCLUDE);
2105 hash_keyword(state, "line", TOK_LINE);
2106 hash_keyword(state, "error", TOK_ERROR);
2107 hash_keyword(state, "warning", TOK_WARNING);
2108 hash_keyword(state, "pragma", TOK_PRAGMA);
2109 hash_keyword(state, "ifdef", TOK_IFDEF);
2110 hash_keyword(state, "ifndef", TOK_IFNDEF);
2111 hash_keyword(state, "elif", TOK_ELIF);
2112 hash_keyword(state, "endif", TOK_ENDIF);
2115 static int spacep(int c)
2131 static int digitp(int c)
2135 case '0': case '1': case '2': case '3': case '4':
2136 case '5': case '6': case '7': case '8': case '9':
2143 static int hexdigitp(int c)
2147 case '0': case '1': case '2': case '3': case '4':
2148 case '5': case '6': case '7': case '8': case '9':
2149 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2150 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2156 static int hexdigval(int c)
2159 if ((c >= '0') && (c <= '9')) {
2162 else if ((c >= 'A') && (c <= 'F')) {
2163 val = 10 + (c - 'A');
2165 else if ((c >= 'a') && (c <= 'f')) {
2166 val = 10 + (c - 'a');
2171 static int octdigitp(int c)
2175 case '0': case '1': case '2': case '3':
2176 case '4': case '5': case '6': case '7':
2182 static int octdigval(int c)
2185 if ((c >= '0') && (c <= '7')) {
2191 static int letterp(int c)
2195 case 'a': case 'b': case 'c': case 'd': case 'e':
2196 case 'f': case 'g': case 'h': case 'i': case 'j':
2197 case 'k': case 'l': case 'm': case 'n': case 'o':
2198 case 'p': case 'q': case 'r': case 's': case 't':
2199 case 'u': case 'v': case 'w': case 'x': case 'y':
2201 case 'A': case 'B': case 'C': case 'D': case 'E':
2202 case 'F': case 'G': case 'H': case 'I': case 'J':
2203 case 'K': case 'L': case 'M': case 'N': case 'O':
2204 case 'P': case 'Q': case 'R': case 'S': case 'T':
2205 case 'U': case 'V': case 'W': case 'X': case 'Y':
2214 static int char_value(struct compile_state *state,
2215 const signed char **strp, const signed char *end)
2217 const signed char *str;
2221 if ((c == '\\') && (str < end)) {
2223 case 'n': c = '\n'; str++; break;
2224 case 't': c = '\t'; str++; break;
2225 case 'v': c = '\v'; str++; break;
2226 case 'b': c = '\b'; str++; break;
2227 case 'r': c = '\r'; str++; break;
2228 case 'f': c = '\f'; str++; break;
2229 case 'a': c = '\a'; str++; break;
2230 case '\\': c = '\\'; str++; break;
2231 case '?': c = '?'; str++; break;
2232 case '\'': c = '\''; str++; break;
2233 case '"': c = '"'; break;
2237 while((str < end) && hexdigitp(*str)) {
2239 c += hexdigval(*str);
2243 case '0': case '1': case '2': case '3':
2244 case '4': case '5': case '6': case '7':
2246 while((str < end) && octdigitp(*str)) {
2248 c += octdigval(*str);
2253 error(state, 0, "Invalid character constant");
2261 static char *after_digits(char *ptr, char *end)
2263 while((ptr < end) && digitp(*ptr)) {
2269 static char *after_octdigits(char *ptr, char *end)
2271 while((ptr < end) && octdigitp(*ptr)) {
2277 static char *after_hexdigits(char *ptr, char *end)
2279 while((ptr < end) && hexdigitp(*ptr)) {
2285 static void save_string(struct compile_state *state,
2286 struct token *tk, char *start, char *end, const char *id)
2290 /* Create a private copy of the string */
2291 str_len = end - start + 1;
2292 str = xmalloc(str_len + 1, id);
2293 memcpy(str, start, str_len);
2294 str[str_len] = '\0';
2296 /* Store the copy in the token */
2298 tk->str_len = str_len;
2300 static void next_token(struct compile_state *state, int index)
2302 struct file_state *file;
2310 tk = &state->token[index];
2313 token = tokp = file->pos;
2314 end = file->buf + file->size;
2321 if ((tokp + 1) < end) {
2325 if ((tokp + 2) < end) {
2329 if ((tokp + 3) < end) {
2337 else if (spacep(c)) {
2339 while ((tokp < end) && spacep(c)) {
2342 file->line_start = tokp + 1;
2351 else if ((c == '/') && (c1 == '/')) {
2353 for(tokp += 2; tokp < end; tokp++) {
2357 file->line_start = tokp +1;
2363 else if ((c == '/') && (c1 == '*')) {
2367 line_start = file->line_start;
2368 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2372 line_start = tokp +1;
2374 else if ((c == '*') && (tokp[1] == '/')) {
2380 if (tok == TOK_UNKNOWN) {
2381 error(state, 0, "unterminated comment");
2384 file->line_start = line_start;
2386 /* string constants */
2387 else if ((c == '"') ||
2388 ((c == 'L') && (c1 == '"'))) {
2393 line_start = file->line_start;
2399 for(tokp += 1; tokp < end; tokp++) {
2403 line_start = tokp + 1;
2405 else if ((c == '\\') && (tokp +1 < end)) {
2408 else if (c == '"') {
2409 tok = TOK_LIT_STRING;
2413 if (tok == TOK_UNKNOWN) {
2414 error(state, 0, "unterminated string constant");
2416 if (line != file->line) {
2417 warning(state, 0, "multiline string constant");
2420 file->line_start = line_start;
2422 /* Save the string value */
2423 save_string(state, tk, token, tokp, "literal string");
2425 /* character constants */
2426 else if ((c == '\'') ||
2427 ((c == 'L') && (c1 == '\''))) {
2432 line_start = file->line_start;
2438 for(tokp += 1; tokp < end; tokp++) {
2442 line_start = tokp + 1;
2444 else if ((c == '\\') && (tokp +1 < end)) {
2447 else if (c == '\'') {
2452 if (tok == TOK_UNKNOWN) {
2453 error(state, 0, "unterminated character constant");
2455 if (line != file->line) {
2456 warning(state, 0, "multiline character constant");
2459 file->line_start = line_start;
2461 /* Save the character value */
2462 save_string(state, tk, token, tokp, "literal character");
2464 /* integer and floating constants
2470 * Floating constants
2471 * {digits}.{digits}[Ee][+-]?{digits}
2473 * {digits}[Ee][+-]?{digits}
2474 * .{digits}[Ee][+-]?{digits}
2478 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2483 next = after_digits(tokp, end);
2488 if (next[0] == '.') {
2489 new = after_digits(next, end);
2490 is_float = (new != next);
2493 if ((next[0] == 'e') || (next[0] == 'E')) {
2494 if (((next + 1) < end) &&
2495 ((next[1] == '+') || (next[1] == '-'))) {
2498 new = after_digits(next, end);
2499 is_float = (new != next);
2503 tok = TOK_LIT_FLOAT;
2504 if ((next < end) && (
2513 if (!is_float && digitp(c)) {
2515 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2516 next = after_hexdigits(tokp + 2, end);
2518 else if (c == '0') {
2519 next = after_octdigits(tokp, end);
2522 next = after_digits(tokp, end);
2524 /* crazy integer suffixes */
2526 ((next[0] == 'u') || (next[0] == 'U'))) {
2529 ((next[0] == 'l') || (next[0] == 'L'))) {
2533 else if ((next < end) &&
2534 ((next[0] == 'l') || (next[0] == 'L'))) {
2537 ((next[0] == 'u') || (next[0] == 'U'))) {
2544 /* Save the integer/floating point value */
2545 save_string(state, tk, token, tokp, "literal number");
2548 else if (letterp(c)) {
2550 for(tokp += 1; tokp < end; tokp++) {
2552 if (!letterp(c) && !digitp(c)) {
2557 tk->ident = lookup(state, token, tokp +1 - token);
2559 /* C99 alternate macro characters */
2560 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2562 tok = TOK_CONCATENATE;
2564 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2565 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2566 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2567 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2568 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2569 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2570 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2571 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2572 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2573 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2574 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2575 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2576 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2577 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2578 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2579 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2580 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2581 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2582 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2583 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2584 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2585 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2586 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2587 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2588 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2589 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2590 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2591 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2592 else if (c == ';') { tok = TOK_SEMI; }
2593 else if (c == '{') { tok = TOK_LBRACE; }
2594 else if (c == '}') { tok = TOK_RBRACE; }
2595 else if (c == ',') { tok = TOK_COMMA; }
2596 else if (c == '=') { tok = TOK_EQ; }
2597 else if (c == ':') { tok = TOK_COLON; }
2598 else if (c == '[') { tok = TOK_LBRACKET; }
2599 else if (c == ']') { tok = TOK_RBRACKET; }
2600 else if (c == '(') { tok = TOK_LPAREN; }
2601 else if (c == ')') { tok = TOK_RPAREN; }
2602 else if (c == '*') { tok = TOK_STAR; }
2603 else if (c == '>') { tok = TOK_MORE; }
2604 else if (c == '<') { tok = TOK_LESS; }
2605 else if (c == '?') { tok = TOK_QUEST; }
2606 else if (c == '|') { tok = TOK_OR; }
2607 else if (c == '&') { tok = TOK_AND; }
2608 else if (c == '^') { tok = TOK_XOR; }
2609 else if (c == '+') { tok = TOK_PLUS; }
2610 else if (c == '-') { tok = TOK_MINUS; }
2611 else if (c == '/') { tok = TOK_DIV; }
2612 else if (c == '%') { tok = TOK_MOD; }
2613 else if (c == '!') { tok = TOK_BANG; }
2614 else if (c == '.') { tok = TOK_DOT; }
2615 else if (c == '~') { tok = TOK_TILDE; }
2616 else if (c == '#') { tok = TOK_MACRO; }
2617 if (tok == TOK_MACRO) {
2618 /* Only match preprocessor directives at the start of a line */
2620 for(ptr = file->line_start; spacep(*ptr); ptr++)
2626 if (tok == TOK_UNKNOWN) {
2627 error(state, 0, "unknown token");
2630 file->pos = tokp + 1;
2632 if (tok == TOK_IDENT) {
2633 ident_to_keyword(state, tk);
2635 /* Don't return space tokens. */
2636 if (tok == TOK_SPACE) {
2641 static void compile_macro(struct compile_state *state, struct token *tk)
2643 struct file_state *file;
2644 struct hash_entry *ident;
2646 file = xmalloc(sizeof(*file), "file_state");
2647 file->basename = xstrdup(tk->ident->name);
2648 file->dirname = xstrdup("");
2649 file->size = ident->sym_define->buf_len;
2650 file->buf = xmalloc(file->size +2, file->basename);
2651 memcpy(file->buf, ident->sym_define->buf, file->size);
2652 file->buf[file->size] = '\n';
2653 file->buf[file->size + 1] = '\0';
2654 file->pos = file->buf;
2655 file->line_start = file->pos;
2657 file->prev = state->file;
2662 static int mpeek(struct compile_state *state, int index)
2666 tk = &state->token[index + 1];
2667 if (tk->tok == -1) {
2668 next_token(state, index + 1);
2672 if ((tk->tok == TOK_EOF) &&
2673 (state->file != state->macro_file) &&
2674 (state->file->prev)) {
2675 struct file_state *file = state->file;
2676 state->file = file->prev;
2677 /* file->basename is used keep it */
2678 xfree(file->dirname);
2681 next_token(state, index + 1);
2684 else if (tk->ident && tk->ident->sym_define) {
2685 compile_macro(state, tk);
2686 next_token(state, index + 1);
2690 /* Don't show the token on the next line */
2691 if (state->macro_line < state->macro_file->line) {
2694 return state->token[index +1].tok;
2697 static void meat(struct compile_state *state, int index, int tok)
2701 next_tok = mpeek(state, index);
2702 if (next_tok != tok) {
2703 const char *name1, *name2;
2704 name1 = tokens[next_tok];
2706 if (next_tok == TOK_IDENT) {
2707 name2 = state->token[index + 1].ident->name;
2709 error(state, 0, "found %s %s expected %s",
2710 name1, name2, tokens[tok]);
2712 /* Free the old token value */
2713 if (state->token[index].str_len) {
2714 memset((void *)(state->token[index].val.str), -1,
2715 state->token[index].str_len);
2716 xfree(state->token[index].val.str);
2718 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2719 state->token[i] = state->token[i + 1];
2721 memset(&state->token[i], 0, sizeof(state->token[i]));
2722 state->token[i].tok = -1;
2725 static long_t mcexpr(struct compile_state *state, int index);
2727 static long_t mprimary_expr(struct compile_state *state, int index)
2731 tok = mpeek(state, index);
2732 while(state->token[index + 1].ident &&
2733 state->token[index + 1].ident->sym_define) {
2734 meat(state, index, tok);
2735 compile_macro(state, &state->token[index]);
2736 tok = mpeek(state, index);
2740 meat(state, index, TOK_LPAREN);
2741 val = mcexpr(state, index);
2742 meat(state, index, TOK_RPAREN);
2747 meat(state, index, TOK_LIT_INT);
2749 val = strtol(state->token[index].val.str, &end, 0);
2750 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2751 (errno == ERANGE)) {
2752 error(state, 0, "Integer constant to large");
2757 meat(state, index, TOK_LIT_INT);
2762 static long_t munary_expr(struct compile_state *state, int index)
2765 switch(mpeek(state, index)) {
2767 meat(state, index, TOK_PLUS);
2768 val = munary_expr(state, index);
2772 meat(state, index, TOK_MINUS);
2773 val = munary_expr(state, index);
2777 meat(state, index, TOK_BANG);
2778 val = munary_expr(state, index);
2782 meat(state, index, TOK_BANG);
2783 val = munary_expr(state, index);
2787 val = mprimary_expr(state, index);
2793 static long_t mmul_expr(struct compile_state *state, int index)
2797 val = munary_expr(state, index);
2801 switch(mpeek(state, index)) {
2803 meat(state, index, TOK_STAR);
2804 right = munary_expr(state, index);
2808 meat(state, index, TOK_DIV);
2809 right = munary_expr(state, index);
2813 meat(state, index, TOK_MOD);
2814 right = munary_expr(state, index);
2826 static long_t madd_expr(struct compile_state *state, int index)
2830 val = mmul_expr(state, index);
2834 switch(mpeek(state, index)) {
2836 meat(state, index, TOK_PLUS);
2837 right = mmul_expr(state, index);
2841 meat(state, index, TOK_MINUS);
2842 right = mmul_expr(state, index);
2854 static long_t mshift_expr(struct compile_state *state, int index)
2858 val = madd_expr(state, index);
2862 switch(mpeek(state, index)) {
2864 meat(state, index, TOK_SL);
2865 right = madd_expr(state, index);
2869 meat(state, index, TOK_SR);
2870 right = madd_expr(state, index);
2882 static long_t mrel_expr(struct compile_state *state, int index)
2886 val = mshift_expr(state, index);
2890 switch(mpeek(state, index)) {
2892 meat(state, index, TOK_LESS);
2893 right = mshift_expr(state, index);
2897 meat(state, index, TOK_MORE);
2898 right = mshift_expr(state, index);
2902 meat(state, index, TOK_LESSEQ);
2903 right = mshift_expr(state, index);
2907 meat(state, index, TOK_MOREEQ);
2908 right = mshift_expr(state, index);
2919 static long_t meq_expr(struct compile_state *state, int index)
2923 val = mrel_expr(state, index);
2927 switch(mpeek(state, index)) {
2929 meat(state, index, TOK_EQEQ);
2930 right = mrel_expr(state, index);
2934 meat(state, index, TOK_NOTEQ);
2935 right = mrel_expr(state, index);
2946 static long_t mand_expr(struct compile_state *state, int index)
2949 val = meq_expr(state, index);
2950 if (mpeek(state, index) == TOK_AND) {
2952 meat(state, index, TOK_AND);
2953 right = meq_expr(state, index);
2959 static long_t mxor_expr(struct compile_state *state, int index)
2962 val = mand_expr(state, index);
2963 if (mpeek(state, index) == TOK_XOR) {
2965 meat(state, index, TOK_XOR);
2966 right = mand_expr(state, index);
2972 static long_t mor_expr(struct compile_state *state, int index)
2975 val = mxor_expr(state, index);
2976 if (mpeek(state, index) == TOK_OR) {
2978 meat(state, index, TOK_OR);
2979 right = mxor_expr(state, index);
2985 static long_t mland_expr(struct compile_state *state, int index)
2988 val = mor_expr(state, index);
2989 if (mpeek(state, index) == TOK_LOGAND) {
2991 meat(state, index, TOK_LOGAND);
2992 right = mor_expr(state, index);
2997 static long_t mlor_expr(struct compile_state *state, int index)
3000 val = mland_expr(state, index);
3001 if (mpeek(state, index) == TOK_LOGOR) {
3003 meat(state, index, TOK_LOGOR);
3004 right = mland_expr(state, index);
3010 static long_t mcexpr(struct compile_state *state, int index)
3012 return mlor_expr(state, index);
3014 static void preprocess(struct compile_state *state, int index)
3016 /* Doing much more with the preprocessor would require
3017 * a parser and a major restructuring.
3018 * Postpone that for later.
3020 struct file_state *file;
3026 tk = &state->token[index];
3027 state->macro_line = line = file->line;
3028 state->macro_file = file;
3030 next_token(state, index);
3031 ident_to_macro(state, tk);
3032 if (tk->tok == TOK_IDENT) {
3033 error(state, 0, "undefined preprocessing directive `%s'",
3040 if (state->if_value < 0) {
3043 warning(state, 0, "Ignoring preprocessor directive: %s",
3047 error(state, 0, "#elif not supported");
3048 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3049 if (state->if_depth == 0) {
3050 error(state, 0, "#elif without #if");
3052 /* If the #if was taken the #elif just disables the following code */
3053 if (state->if_value >= 0) {
3054 state->if_value = - state->if_value;
3056 /* If the previous #if was not taken see if the #elif enables the
3059 else if ((state->if_value < 0) &&
3060 (state->if_depth == - state->if_value))
3062 if (mcexpr(state, index) != 0) {
3063 state->if_value = state->if_depth;
3066 state->if_value = - state->if_depth;
3072 if (state->if_value < 0) {
3075 if (mcexpr(state, index) != 0) {
3076 state->if_value = state->if_depth;
3079 state->if_value = - state->if_depth;
3084 if (state->if_value < 0) {
3087 next_token(state, index);
3088 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3089 error(state, 0, "Invalid macro name");
3091 if (tk->ident->sym_define == 0) {
3092 state->if_value = state->if_depth;
3095 state->if_value = - state->if_depth;
3100 if (state->if_value < 0) {
3103 next_token(state, index);
3104 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3105 error(state, 0, "Invalid macro name");
3107 if (tk->ident->sym_define != 0) {
3108 state->if_value = state->if_depth;
3111 state->if_value = - state->if_depth;
3115 if (state->if_depth == 0) {
3116 error(state, 0, "#else without #if");
3118 if ((state->if_value >= 0) ||
3119 ((state->if_value < 0) &&
3120 (state->if_depth == -state->if_value)))
3122 state->if_value = - state->if_value;
3126 if (state->if_depth == 0) {
3127 error(state, 0, "#endif without #if");
3129 if ((state->if_value >= 0) ||
3130 ((state->if_value < 0) &&
3131 (state->if_depth == -state->if_value)))
3133 state->if_value = state->if_depth - 1;
3139 struct hash_entry *ident;
3140 struct macro *macro;
3143 if (state->if_value < 0) /* quit early when #if'd out */
3146 meat(state, index, TOK_IDENT);
3150 if (*file->pos == '(') {
3151 #warning "FIXME macros with arguments not supported"
3152 error(state, 0, "Macros with arguments not supported");
3155 /* Find the end of the line to get an estimate of
3156 * the macro's length.
3158 for(ptr = file->pos; *ptr != '\n'; ptr++)
3161 if (ident->sym_define != 0) {
3162 error(state, 0, "macro %s already defined\n", ident->name);
3164 macro = xmalloc(sizeof(*macro), "macro");
3165 macro->ident = ident;
3166 macro->buf_len = ptr - file->pos +1;
3167 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3169 memcpy(macro->buf, file->pos, macro->buf_len);
3170 macro->buf[macro->buf_len] = '\n';
3171 macro->buf[macro->buf_len +1] = '\0';
3173 ident->sym_define = macro;
3180 /* Find the end of the line */
3181 for(end = file->pos; *end != '\n'; end++)
3183 len = (end - file->pos);
3184 if (state->if_value >= 0) {
3185 error(state, 0, "%*.*s", len, len, file->pos);
3194 /* Find the end of the line */
3195 for(end = file->pos; *end != '\n'; end++)
3197 len = (end - file->pos);
3198 if (state->if_value >= 0) {
3199 warning(state, 0, "%*.*s", len, len, file->pos);
3211 next_token(state, index);
3212 if (tk->tok == TOK_LIT_STRING) {
3215 name = xmalloc(tk->str_len, "include");
3216 token = tk->val.str +1;
3217 name_len = tk->str_len -2;
3218 if (*token == '"') {
3222 memcpy(name, token, name_len);
3223 name[name_len] = '\0';
3226 else if (tk->tok == TOK_LESS) {
3229 for(end = start; *end != '\n'; end++) {
3235 error(state, 0, "Unterminated included directive");
3237 name = xmalloc(end - start + 1, "include");
3238 memcpy(name, start, end - start);
3239 name[end - start] = '\0';
3244 error(state, 0, "Invalid include directive");
3246 /* Error if there are any characters after the include */
3247 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3248 if (!isspace(*ptr)) {
3249 error(state, 0, "garbage after include directive");
3252 if (state->if_value >= 0) {
3253 compile_file(state, name, local);
3256 next_token(state, index);
3260 /* Ignore # without a following ident */
3261 if (tk->tok == TOK_IDENT) {
3262 error(state, 0, "Invalid preprocessor directive: %s",
3267 /* Consume the rest of the macro line */
3269 tok = mpeek(state, index);
3270 meat(state, index, tok);
3271 } while(tok != TOK_EOF);
3275 static void token(struct compile_state *state, int index)
3277 struct file_state *file;
3281 tk = &state->token[index];
3282 next_token(state, index);
3286 if (tk->tok == TOK_EOF && file->prev) {
3287 state->file = file->prev;
3288 /* file->basename is used keep it */
3289 xfree(file->dirname);
3292 next_token(state, index);
3295 else if (tk->tok == TOK_MACRO) {
3296 preprocess(state, index);
3299 else if (tk->ident && tk->ident->sym_define) {
3300 compile_macro(state, tk);
3301 next_token(state, index);
3304 else if (state->if_value < 0) {
3305 next_token(state, index);
3311 static int peek(struct compile_state *state)
3313 if (state->token[1].tok == -1) {
3316 return state->token[1].tok;
3319 static int peek2(struct compile_state *state)
3321 if (state->token[1].tok == -1) {
3324 if (state->token[2].tok == -1) {
3327 return state->token[2].tok;
3330 static void eat(struct compile_state *state, int tok)
3334 next_tok = peek(state);
3335 if (next_tok != tok) {
3336 const char *name1, *name2;
3337 name1 = tokens[next_tok];
3339 if (next_tok == TOK_IDENT) {
3340 name2 = state->token[1].ident->name;
3342 error(state, 0, "\tfound %s %s expected %s",
3343 name1, name2 ,tokens[tok]);
3345 /* Free the old token value */
3346 if (state->token[0].str_len) {
3347 xfree((void *)(state->token[0].val.str));
3349 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3350 state->token[i] = state->token[i + 1];
3352 memset(&state->token[i], 0, sizeof(state->token[i]));
3353 state->token[i].tok = -1;
3356 #warning "FIXME do not hardcode the include paths"
3357 static char *include_paths[] = {
3358 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3359 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3360 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3364 static void compile_file(struct compile_state *state, const char *filename, int local)
3367 const char *subdir, *base;
3369 struct file_state *file;
3371 file = xmalloc(sizeof(*file), "file_state");
3373 base = strrchr(filename, '/');
3376 subdir_len = base - filename;
3383 basename = xmalloc(strlen(base) +1, "basename");
3384 strcpy(basename, base);
3385 file->basename = basename;
3387 if (getcwd(cwd, sizeof(cwd)) == 0) {
3388 die("cwd buffer to small");
3391 if (subdir[0] == '/') {
3392 file->dirname = xmalloc(subdir_len + 1, "dirname");
3393 memcpy(file->dirname, subdir, subdir_len);
3394 file->dirname[subdir_len] = '\0';
3400 /* Find the appropriate directory... */
3402 if (!state->file && exists(cwd, filename)) {
3405 if (local && state->file && exists(state->file->dirname, filename)) {
3406 dir = state->file->dirname;
3408 for(path = include_paths; !dir && *path; path++) {
3409 if (exists(*path, filename)) {
3414 error(state, 0, "Cannot find `%s'\n", filename);
3416 dirlen = strlen(dir);
3417 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3418 memcpy(file->dirname, dir, dirlen);
3419 file->dirname[dirlen] = '/';
3420 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3421 file->dirname[dirlen + 1 + subdir_len] = '\0';
3423 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3426 file->pos = file->buf;
3427 file->line_start = file->pos;
3430 file->prev = state->file;
3433 process_trigraphs(state);
3434 splice_lines(state);
3437 /* Type helper functions */
3439 static struct type *new_type(
3440 unsigned int type, struct type *left, struct type *right)
3442 struct type *result;
3443 result = xmalloc(sizeof(*result), "type");
3444 result->type = type;
3445 result->left = left;
3446 result->right = right;
3447 result->field_ident = 0;
3448 result->type_ident = 0;
3452 static struct type *clone_type(unsigned int specifiers, struct type *old)
3454 struct type *result;
3455 result = xmalloc(sizeof(*result), "type");
3456 memcpy(result, old, sizeof(*result));
3457 result->type &= TYPE_MASK;
3458 result->type |= specifiers;
3462 #define SIZEOF_SHORT 2
3463 #define SIZEOF_INT 4
3464 #define SIZEOF_LONG (sizeof(long_t))
3466 #define ALIGNOF_SHORT 2
3467 #define ALIGNOF_INT 4
3468 #define ALIGNOF_LONG (sizeof(long_t))
3470 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3471 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3472 static inline ulong_t mask_uint(ulong_t x)
3474 if (SIZEOF_INT < SIZEOF_LONG) {
3475 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3480 #define MASK_UINT(X) (mask_uint(X))
3481 #define MASK_ULONG(X) (X)
3483 static struct type void_type = { .type = TYPE_VOID };
3484 static struct type char_type = { .type = TYPE_CHAR };
3485 static struct type uchar_type = { .type = TYPE_UCHAR };
3486 static struct type short_type = { .type = TYPE_SHORT };
3487 static struct type ushort_type = { .type = TYPE_USHORT };
3488 static struct type int_type = { .type = TYPE_INT };
3489 static struct type uint_type = { .type = TYPE_UINT };
3490 static struct type long_type = { .type = TYPE_LONG };
3491 static struct type ulong_type = { .type = TYPE_ULONG };
3493 static struct triple *variable(struct compile_state *state, struct type *type)
3495 struct triple *result;
3496 if ((type->type & STOR_MASK) != STOR_PERM) {
3497 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3498 result = triple(state, OP_ADECL, type, 0, 0);
3501 struct triple **vector;
3503 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3504 vector = &result->param[0];
3508 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3509 vector[index] = variable(state, field->left);
3510 field = field->right;
3513 vector[index] = variable(state, field);
3517 result = triple(state, OP_SDECL, type, 0, 0);
3522 static void stor_of(FILE *fp, struct type *type)
3524 switch(type->type & STOR_MASK) {
3526 fprintf(fp, "auto ");
3529 fprintf(fp, "static ");
3532 fprintf(fp, "extern ");
3535 fprintf(fp, "register ");
3538 fprintf(fp, "typedef ");
3541 fprintf(fp, "inline ");
3545 static void qual_of(FILE *fp, struct type *type)
3547 if (type->type & QUAL_CONST) {
3548 fprintf(fp, " const");
3550 if (type->type & QUAL_VOLATILE) {
3551 fprintf(fp, " volatile");
3553 if (type->type & QUAL_RESTRICT) {
3554 fprintf(fp, " restrict");
3558 static void name_of(FILE *fp, struct type *type)
3561 switch(type->type & TYPE_MASK) {
3563 fprintf(fp, "void");
3567 fprintf(fp, "signed char");
3571 fprintf(fp, "unsigned char");
3575 fprintf(fp, "signed short");
3579 fprintf(fp, "unsigned short");
3583 fprintf(fp, "signed int");
3587 fprintf(fp, "unsigned int");
3591 fprintf(fp, "signed long");
3595 fprintf(fp, "unsigned long");
3599 name_of(fp, type->left);
3605 name_of(fp, type->left);
3607 name_of(fp, type->right);
3610 fprintf(fp, "enum %s", type->type_ident->name);
3614 fprintf(fp, "struct %s", type->type_ident->name);
3619 name_of(fp, type->left);
3620 fprintf(fp, " (*)(");
3621 name_of(fp, type->right);
3626 name_of(fp, type->left);
3627 fprintf(fp, " [%ld]", type->elements);
3630 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3635 static size_t align_of(struct compile_state *state, struct type *type)
3639 switch(type->type & TYPE_MASK) {
3649 align = ALIGNOF_SHORT;
3654 align = ALIGNOF_INT;
3659 align = ALIGNOF_LONG;
3664 size_t left_align, right_align;
3665 left_align = align_of(state, type->left);
3666 right_align = align_of(state, type->right);
3667 align = (left_align >= right_align) ? left_align : right_align;
3671 align = align_of(state, type->left);
3674 align = align_of(state, type->left);
3677 error(state, 0, "alignof not yet defined for type\n");
3683 static size_t size_of(struct compile_state *state, struct type *type)
3687 switch(type->type & TYPE_MASK) {
3697 size = SIZEOF_SHORT;
3712 size = size_of(state, type->left);
3713 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3715 align = align_of(state, type->left);
3716 pad = align - (size % align);
3717 size = size + pad + size_of(state, type->left);
3719 align = align_of(state, type->right);
3720 pad = align - (size % align);
3721 size = size + pad + sizeof(type->right);
3726 size_t size_left, size_right;
3727 size_left = size_of(state, type->left);
3728 size_right = size_of(state, type->right);
3729 size = (size_left >= size_right)? size_left : size_right;
3733 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3734 internal_error(state, 0, "Invalid array type");
3736 size = size_of(state, type->left) * type->elements;
3740 size = size_of(state, type->left);
3743 error(state, 0, "sizeof not yet defined for type\n");
3749 static size_t field_offset(struct compile_state *state,
3750 struct type *type, struct hash_entry *field)
3752 size_t size, align, pad;
3753 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3754 internal_error(state, 0, "field_offset only works on structures");
3758 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3759 if (type->left->field_ident == field) {
3762 size += size_of(state, type->left);
3764 align = align_of(state, type->left);
3765 pad = align - (size % align);
3768 if (type->field_ident != field) {
3769 internal_error(state, 0, "field_offset: member %s not present",
3775 static struct type *field_type(struct compile_state *state,
3776 struct type *type, struct hash_entry *field)
3778 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3779 internal_error(state, 0, "field_type only works on structures");
3782 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3783 if (type->left->field_ident == field) {
3789 if (type->field_ident != field) {
3790 internal_error(state, 0, "field_type: member %s not present",
3796 static struct triple *struct_field(struct compile_state *state,
3797 struct triple *decl, struct hash_entry *field)
3799 struct triple **vector;
3803 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3806 if (decl->op != OP_VAL_VEC) {
3807 internal_error(state, 0, "Invalid struct variable");
3810 internal_error(state, 0, "Missing structure field");
3813 vector = &RHS(decl, 0);
3815 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3816 if (type->left->field_ident == field) {
3823 if (type->field_ident != field) {
3824 internal_error(state, 0, "field %s not found?", field->name);
3826 return vector[index];
3829 static void arrays_complete(struct compile_state *state, struct type *type)
3831 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3832 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3833 error(state, 0, "array size not specified");
3835 arrays_complete(state, type->left);
3839 static unsigned int do_integral_promotion(unsigned int type)
3842 if (TYPE_INTEGER(type) &&
3843 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3849 static unsigned int do_arithmetic_conversion(
3850 unsigned int left, unsigned int right)
3854 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3855 return TYPE_LDOUBLE;
3857 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3860 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3863 left = do_integral_promotion(left);
3864 right = do_integral_promotion(right);
3865 /* If both operands have the same size done */
3866 if (left == right) {
3869 /* If both operands have the same signedness pick the larger */
3870 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3871 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3873 /* If the signed type can hold everything use it */
3874 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3877 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3880 /* Convert to the unsigned type with the same rank as the signed type */
3881 else if (TYPE_SIGNED(left)) {
3882 return TYPE_MKUNSIGNED(left);
3885 return TYPE_MKUNSIGNED(right);
3889 /* see if two types are the same except for qualifiers */
3890 static int equiv_types(struct type *left, struct type *right)
3893 /* Error if the basic types do not match */
3894 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3897 type = left->type & TYPE_MASK;
3898 /* if the basic types match and it is an arithmetic type we are done */
3899 if (TYPE_ARITHMETIC(type)) {
3902 /* If it is a pointer type recurse and keep testing */
3903 if (type == TYPE_POINTER) {
3904 return equiv_types(left->left, right->left);
3906 else if (type == TYPE_ARRAY) {
3907 return (left->elements == right->elements) &&
3908 equiv_types(left->left, right->left);
3910 /* test for struct/union equality */
3911 else if (type == TYPE_STRUCT) {
3912 return left->type_ident == right->type_ident;
3914 /* Test for equivalent functions */
3915 else if (type == TYPE_FUNCTION) {
3916 return equiv_types(left->left, right->left) &&
3917 equiv_types(left->right, right->right);
3919 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3920 else if (type == TYPE_PRODUCT) {
3921 return equiv_types(left->left, right->left) &&
3922 equiv_types(left->right, right->right);
3924 /* We should see TYPE_OVERLAP */
3930 static int equiv_ptrs(struct type *left, struct type *right)
3932 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3933 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3936 return equiv_types(left->left, right->left);
3939 static struct type *compatible_types(struct type *left, struct type *right)
3941 struct type *result;
3942 unsigned int type, qual_type;
3943 /* Error if the basic types do not match */
3944 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3947 type = left->type & TYPE_MASK;
3948 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3950 /* if the basic types match and it is an arithmetic type we are done */
3951 if (TYPE_ARITHMETIC(type)) {
3952 result = new_type(qual_type, 0, 0);
3954 /* If it is a pointer type recurse and keep testing */
3955 else if (type == TYPE_POINTER) {
3956 result = compatible_types(left->left, right->left);
3958 result = new_type(qual_type, result, 0);
3961 /* test for struct/union equality */
3962 else if (type == TYPE_STRUCT) {
3963 if (left->type_ident == right->type_ident) {
3967 /* Test for equivalent functions */
3968 else if (type == TYPE_FUNCTION) {
3969 struct type *lf, *rf;
3970 lf = compatible_types(left->left, right->left);
3971 rf = compatible_types(left->right, right->right);
3973 result = new_type(qual_type, lf, rf);
3976 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3977 else if (type == TYPE_PRODUCT) {
3978 struct type *lf, *rf;
3979 lf = compatible_types(left->left, right->left);
3980 rf = compatible_types(left->right, right->right);
3982 result = new_type(qual_type, lf, rf);
3986 /* Nothing else is compatible */
3991 static struct type *compatible_ptrs(struct type *left, struct type *right)
3993 struct type *result;
3994 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3995 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3998 result = compatible_types(left->left, right->left);
4000 unsigned int qual_type;
4001 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4002 result = new_type(qual_type, result, 0);
4007 static struct triple *integral_promotion(
4008 struct compile_state *state, struct triple *def)
4012 /* As all operations are carried out in registers
4013 * the values are converted on load I just convert
4014 * logical type of the operand.
4016 if (TYPE_INTEGER(type->type)) {
4017 unsigned int int_type;
4018 int_type = type->type & ~TYPE_MASK;
4019 int_type |= do_integral_promotion(type->type);
4020 if (int_type != type->type) {
4021 def->type = new_type(int_type, 0, 0);
4028 static void arithmetic(struct compile_state *state, struct triple *def)
4030 if (!TYPE_ARITHMETIC(def->type->type)) {
4031 error(state, 0, "arithmetic type expexted");
4035 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4037 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4038 error(state, def, "pointer or arithmetic type expected");
4042 static int is_integral(struct triple *ins)
4044 return TYPE_INTEGER(ins->type->type);
4047 static void integral(struct compile_state *state, struct triple *def)
4049 if (!is_integral(def)) {
4050 error(state, 0, "integral type expected");
4055 static void bool(struct compile_state *state, struct triple *def)
4057 if (!TYPE_ARITHMETIC(def->type->type) &&
4058 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4059 error(state, 0, "arithmetic or pointer type expected");
4063 static int is_signed(struct type *type)
4065 return !!TYPE_SIGNED(type->type);
4068 /* Is this value located in a register otherwise it must be in memory */
4069 static int is_in_reg(struct compile_state *state, struct triple *def)
4072 if (def->op == OP_ADECL) {
4075 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4078 else if (def->op == OP_VAL_VEC) {
4079 in_reg = is_in_reg(state, RHS(def, 0));
4081 else if (def->op == OP_DOT) {
4082 in_reg = is_in_reg(state, RHS(def, 0));
4085 internal_error(state, 0, "unknown expr storage location");
4091 /* Is this a stable variable location otherwise it must be a temporary */
4092 static int is_stable(struct compile_state *state, struct triple *def)
4099 if ((def->op == OP_ADECL) ||
4100 (def->op == OP_SDECL) ||
4101 (def->op == OP_DEREF) ||
4102 (def->op == OP_BLOBCONST)) {
4105 else if (def->op == OP_DOT) {
4106 ret = is_stable(state, RHS(def, 0));
4108 else if (def->op == OP_VAL_VEC) {
4109 struct triple **vector;
4112 vector = &RHS(def, 0);
4113 for(i = 0; i < def->type->elements; i++) {
4114 if (!is_stable(state, vector[i])) {
4123 static int is_lvalue(struct compile_state *state, struct triple *def)
4130 if (!is_stable(state, def)) {
4133 if (def->type->type & QUAL_CONST) {
4136 else if (def->op == OP_DOT) {
4137 ret = is_lvalue(state, RHS(def, 0));
4142 static void lvalue(struct compile_state *state, struct triple *def)
4145 internal_error(state, def, "nothing where lvalue expected?");
4147 if (!is_lvalue(state, def)) {
4148 error(state, def, "lvalue expected");
4152 static int is_pointer(struct triple *def)
4154 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4157 static void pointer(struct compile_state *state, struct triple *def)
4159 if (!is_pointer(def)) {
4160 error(state, def, "pointer expected");
4164 static struct triple *int_const(
4165 struct compile_state *state, struct type *type, ulong_t value)
4167 struct triple *result;
4168 switch(type->type & TYPE_MASK) {
4170 case TYPE_INT: case TYPE_UINT:
4171 case TYPE_LONG: case TYPE_ULONG:
4174 internal_error(state, 0, "constant for unkown type");
4176 result = triple(state, OP_INTCONST, type, 0, 0);
4177 result->u.cval = value;
4182 static struct triple *do_mk_addr_expr(struct compile_state *state,
4183 struct triple *expr, struct type *type, ulong_t offset)
4185 struct triple *result;
4186 lvalue(state, expr);
4189 if (expr->op == OP_ADECL) {
4190 error(state, expr, "address of auto variables not supported");
4192 else if (expr->op == OP_SDECL) {
4193 result = triple(state, OP_ADDRCONST, type, 0, 0);
4194 MISC(result, 0) = expr;
4195 result->u.cval = offset;
4197 else if (expr->op == OP_DEREF) {
4198 result = triple(state, OP_ADD, type,
4200 int_const(state, &ulong_type, offset));
4205 static struct triple *mk_addr_expr(
4206 struct compile_state *state, struct triple *expr, ulong_t offset)
4211 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4214 return do_mk_addr_expr(state, expr, type, offset);
4217 static struct triple *mk_deref_expr(
4218 struct compile_state *state, struct triple *expr)
4220 struct type *base_type;
4221 pointer(state, expr);
4222 base_type = expr->type->left;
4223 if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4225 "Only pointer and arithmetic values can be dereferenced");
4227 return triple(state, OP_DEREF, base_type, expr, 0);
4230 static struct triple *deref_field(
4231 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4233 struct triple *result;
4234 struct type *type, *member;
4236 internal_error(state, 0, "No field passed to deref_field");
4240 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4241 error(state, 0, "request for member %s in something not a struct or union",
4244 member = type->left;
4245 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4246 if (member->left->field_ident == field) {
4247 member = member->left;
4250 member = member->right;
4252 if (member->field_ident != field) {
4253 error(state, 0, "%s is not a member", field->name);
4255 if ((type->type & STOR_MASK) == STOR_PERM) {
4256 /* Do the pointer arithmetic to get a deref the field */
4258 offset = field_offset(state, type, field);
4259 result = do_mk_addr_expr(state, expr, member, offset);
4260 result = mk_deref_expr(state, result);
4263 /* Find the variable for the field I want. */
4264 result = triple(state, OP_DOT,
4265 field_type(state, type, field), expr, 0);
4266 result->u.field = field;
4271 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4277 if (!is_stable(state, def)) {
4280 /* Tranform an array to a pointer to the first element */
4281 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4282 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4284 struct triple *result;
4286 TYPE_POINTER | (def->type->type & QUAL_MASK),
4287 def->type->left, 0);
4288 result = triple(state, OP_ADDRCONST, type, 0, 0);
4289 MISC(result, 0) = def;
4292 if (is_in_reg(state, def)) {
4297 return triple(state, op, def->type, def, 0);
4300 static void write_compatible(struct compile_state *state,
4301 struct type *dest, struct type *rval)
4304 /* Both operands have arithmetic type */
4305 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4308 /* One operand is a pointer and the other is a pointer to void */
4309 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4310 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4311 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4312 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4315 /* If both types are the same without qualifiers we are good */
4316 else if (equiv_ptrs(dest, rval)) {
4319 /* test for struct/union equality */
4320 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4321 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4322 (dest->type_ident == rval->type_ident)) {
4326 error(state, 0, "Incompatible types in assignment");
4330 static struct triple *write_expr(
4331 struct compile_state *state, struct triple *dest, struct triple *rval)
4338 internal_error(state, 0, "missing rval");
4341 if (rval->op == OP_LIST) {
4342 internal_error(state, 0, "expression of type OP_LIST?");
4344 if (!is_lvalue(state, dest)) {
4345 internal_error(state, 0, "writing to a non lvalue?");
4348 write_compatible(state, dest->type, rval->type);
4350 /* Now figure out which assignment operator to use */
4352 if (is_in_reg(state, dest)) {
4357 def = triple(state, op, dest->type, dest, rval);
4361 static struct triple *init_expr(
4362 struct compile_state *state, struct triple *dest, struct triple *rval)
4368 internal_error(state, 0, "missing rval");
4370 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4371 rval = read_expr(state, rval);
4372 def = write_expr(state, dest, rval);
4375 /* Fill in the array size if necessary */
4376 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4377 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4378 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4379 dest->type->elements = rval->type->elements;
4382 if (!equiv_types(dest->type, rval->type)) {
4383 error(state, 0, "Incompatible types in inializer");
4385 MISC(dest, 0) = rval;
4386 insert_triple(state, dest, rval);
4387 rval->id |= TRIPLE_FLAG_FLATTENED;
4388 use_triple(MISC(dest, 0), dest);
4393 struct type *arithmetic_result(
4394 struct compile_state *state, struct triple *left, struct triple *right)
4397 /* Sanity checks to ensure I am working with arithmetic types */
4398 arithmetic(state, left);
4399 arithmetic(state, right);
4401 do_arithmetic_conversion(
4403 right->type->type), 0, 0);
4407 struct type *ptr_arithmetic_result(
4408 struct compile_state *state, struct triple *left, struct triple *right)
4411 /* Sanity checks to ensure I am working with the proper types */
4412 ptr_arithmetic(state, left);
4413 arithmetic(state, right);
4414 if (TYPE_ARITHMETIC(left->type->type) &&
4415 TYPE_ARITHMETIC(right->type->type)) {
4416 type = arithmetic_result(state, left, right);
4418 else if (TYPE_PTR(left->type->type)) {
4422 internal_error(state, 0, "huh?");
4429 /* boolean helper function */
4431 static struct triple *ltrue_expr(struct compile_state *state,
4432 struct triple *expr)
4435 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4436 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4437 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4438 /* If the expression is already boolean do nothing */
4441 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4447 static struct triple *lfalse_expr(struct compile_state *state,
4448 struct triple *expr)
4450 return triple(state, OP_LFALSE, &int_type, expr, 0);
4453 static struct triple *cond_expr(
4454 struct compile_state *state,
4455 struct triple *test, struct triple *left, struct triple *right)
4458 struct type *result_type;
4459 unsigned int left_type, right_type;
4461 left_type = left->type->type;
4462 right_type = right->type->type;
4464 /* Both operands have arithmetic type */
4465 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4466 result_type = arithmetic_result(state, left, right);
4468 /* Both operands have void type */
4469 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4470 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4471 result_type = &void_type;
4473 /* pointers to the same type... */
4474 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4477 /* Both operands are pointers and left is a pointer to void */
4478 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4479 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4480 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4481 result_type = right->type;
4483 /* Both operands are pointers and right is a pointer to void */
4484 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4485 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4486 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4487 result_type = left->type;
4490 error(state, 0, "Incompatible types in conditional expression");
4492 /* Cleanup and invert the test */
4493 test = lfalse_expr(state, read_expr(state, test));
4494 def = new_triple(state, OP_COND, result_type, 0, 3);
4495 def->param[0] = test;
4496 def->param[1] = left;
4497 def->param[2] = right;
4502 static int expr_depth(struct compile_state *state, struct triple *ins)
4506 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4509 else if (ins->op == OP_DEREF) {
4510 count = expr_depth(state, RHS(ins, 0)) - 1;
4512 else if (ins->op == OP_VAL) {
4513 count = expr_depth(state, RHS(ins, 0)) - 1;
4515 else if (ins->op == OP_COMMA) {
4517 ldepth = expr_depth(state, RHS(ins, 0));
4518 rdepth = expr_depth(state, RHS(ins, 1));
4519 count = (ldepth >= rdepth)? ldepth : rdepth;
4521 else if (ins->op == OP_CALL) {
4522 /* Don't figure the depth of a call just guess it is huge */
4526 struct triple **expr;
4527 expr = triple_rhs(state, ins, 0);
4528 for(;expr; expr = triple_rhs(state, ins, expr)) {
4531 depth = expr_depth(state, *expr);
4532 if (depth > count) {
4541 static struct triple *flatten(
4542 struct compile_state *state, struct triple *first, struct triple *ptr);
4544 static struct triple *flatten_generic(
4545 struct compile_state *state, struct triple *first, struct triple *ptr)
4549 struct triple **ins;
4552 /* Only operations with just a rhs should come here */
4553 rhs = TRIPLE_RHS(ptr->sizes);
4554 lhs = TRIPLE_LHS(ptr->sizes);
4555 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4556 internal_error(state, ptr, "unexpected args for: %d %s",
4557 ptr->op, tops(ptr->op));
4559 /* Find the depth of the rhs elements */
4560 for(i = 0; i < rhs; i++) {
4561 vector[i].ins = &RHS(ptr, i);
4562 vector[i].depth = expr_depth(state, *vector[i].ins);
4564 /* Selection sort the rhs */
4565 for(i = 0; i < rhs; i++) {
4567 for(j = i + 1; j < rhs; j++ ) {
4568 if (vector[j].depth > vector[max].depth) {
4573 struct rhs_vector tmp;
4575 vector[i] = vector[max];
4579 /* Now flatten the rhs elements */
4580 for(i = 0; i < rhs; i++) {
4581 *vector[i].ins = flatten(state, first, *vector[i].ins);
4582 use_triple(*vector[i].ins, ptr);
4585 /* Now flatten the lhs elements */
4586 for(i = 0; i < lhs; i++) {
4587 struct triple **ins = &LHS(ptr, i);
4588 *ins = flatten(state, first, *ins);
4589 use_triple(*ins, ptr);
4594 static struct triple *flatten_land(
4595 struct compile_state *state, struct triple *first, struct triple *ptr)
4597 struct triple *left, *right;
4598 struct triple *val, *test, *jmp, *label1, *end;
4600 /* Find the triples */
4602 right = RHS(ptr, 1);
4604 /* Generate the needed triples */
4607 /* Thread the triples together */
4608 val = flatten(state, first, variable(state, ptr->type));
4609 left = flatten(state, first, write_expr(state, val, left));
4610 test = flatten(state, first,
4611 lfalse_expr(state, read_expr(state, val)));
4612 jmp = flatten(state, first, branch(state, end, test));
4613 label1 = flatten(state, first, label(state));
4614 right = flatten(state, first, write_expr(state, val, right));
4615 TARG(jmp, 0) = flatten(state, first, end);
4617 /* Now give the caller something to chew on */
4618 return read_expr(state, val);
4621 static struct triple *flatten_lor(
4622 struct compile_state *state, struct triple *first, struct triple *ptr)
4624 struct triple *left, *right;
4625 struct triple *val, *jmp, *label1, *end;
4627 /* Find the triples */
4629 right = RHS(ptr, 1);
4631 /* Generate the needed triples */
4634 /* Thread the triples together */
4635 val = flatten(state, first, variable(state, ptr->type));
4636 left = flatten(state, first, write_expr(state, val, left));
4637 jmp = flatten(state, first, branch(state, end, left));
4638 label1 = flatten(state, first, label(state));
4639 right = flatten(state, first, write_expr(state, val, right));
4640 TARG(jmp, 0) = flatten(state, first, end);
4643 /* Now give the caller something to chew on */
4644 return read_expr(state, val);
4647 static struct triple *flatten_cond(
4648 struct compile_state *state, struct triple *first, struct triple *ptr)
4650 struct triple *test, *left, *right;
4651 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4653 /* Find the triples */
4656 right = RHS(ptr, 2);
4658 /* Generate the needed triples */
4660 middle = label(state);
4662 /* Thread the triples together */
4663 val = flatten(state, first, variable(state, ptr->type));
4664 test = flatten(state, first, test);
4665 jmp1 = flatten(state, first, branch(state, middle, test));
4666 label1 = flatten(state, first, label(state));
4667 left = flatten(state, first, left);
4668 mv1 = flatten(state, first, write_expr(state, val, left));
4669 jmp2 = flatten(state, first, branch(state, end, 0));
4670 TARG(jmp1, 0) = flatten(state, first, middle);
4671 right = flatten(state, first, right);
4672 mv2 = flatten(state, first, write_expr(state, val, right));
4673 TARG(jmp2, 0) = flatten(state, first, end);
4675 /* Now give the caller something to chew on */
4676 return read_expr(state, val);
4679 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4681 struct triple *nfunc;
4682 struct triple *nfirst, *ofirst;
4683 struct triple *new, *old;
4686 fprintf(stdout, "\n");
4687 loc(stdout, state, 0);
4688 fprintf(stdout, "\n__________ copy_func _________\n");
4689 print_triple(state, ofunc);
4690 fprintf(stdout, "__________ copy_func _________ done\n\n");
4693 /* Make a new copy of the old function */
4694 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4696 ofirst = old = RHS(ofunc, 0);
4699 int old_lhs, old_rhs;
4700 old_lhs = TRIPLE_LHS(old->sizes);
4701 old_rhs = TRIPLE_RHS(old->sizes);
4702 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4703 old->filename, old->line, old->col);
4704 if (!triple_stores_block(state, new)) {
4705 memcpy(&new->u, &old->u, sizeof(new->u));
4708 RHS(nfunc, 0) = nfirst = new;
4711 insert_triple(state, nfirst, new);
4713 new->id |= TRIPLE_FLAG_FLATTENED;
4715 /* During the copy remember new as user of old */
4716 use_triple(old, new);
4718 /* Populate the return type if present */
4719 if (old == MISC(ofunc, 0)) {
4720 MISC(nfunc, 0) = new;
4723 } while(old != ofirst);
4725 /* Make a second pass to fix up any unresolved references */
4729 struct triple **oexpr, **nexpr;
4731 /* Lookup where the copy is, to join pointers */
4732 count = TRIPLE_SIZE(old->sizes);
4733 for(i = 0; i < count; i++) {
4734 oexpr = &old->param[i];
4735 nexpr = &new->param[i];
4736 if (!*nexpr && *oexpr && (*oexpr)->use) {
4737 *nexpr = (*oexpr)->use->member;
4738 if (*nexpr == old) {
4739 internal_error(state, 0, "new == old?");
4741 use_triple(*nexpr, new);
4743 if (!*nexpr && *oexpr) {
4744 internal_error(state, 0, "Could not copy %d\n", i);
4749 } while((old != ofirst) && (new != nfirst));
4751 /* Make a third pass to cleanup the extra useses */
4755 unuse_triple(old, new);
4758 } while ((old != ofirst) && (new != nfirst));
4762 static struct triple *flatten_call(
4763 struct compile_state *state, struct triple *first, struct triple *ptr)
4765 /* Inline the function call */
4767 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4768 struct triple *end, *nend;
4771 /* Find the triples */
4772 ofunc = MISC(ptr, 0);
4773 if (ofunc->op != OP_LIST) {
4774 internal_error(state, 0, "improper function");
4776 nfunc = copy_func(state, ofunc);
4777 nfirst = RHS(nfunc, 0)->next;
4778 /* Prepend the parameter reading into the new function list */
4779 ptype = nfunc->type->right;
4780 param = RHS(nfunc, 0)->next;
4781 pvals = TRIPLE_RHS(ptr->sizes);
4782 for(i = 0; i < pvals; i++) {
4786 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4787 atype = ptype->left;
4789 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4790 param = param->next;
4793 flatten(state, nfirst, write_expr(state, param, arg));
4794 ptype = ptype->right;
4795 param = param->next;
4798 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4799 result = read_expr(state, MISC(nfunc,0));
4802 fprintf(stdout, "\n");
4803 loc(stdout, state, 0);
4804 fprintf(stdout, "\n__________ flatten_call _________\n");
4805 print_triple(state, nfunc);
4806 fprintf(stdout, "__________ flatten_call _________ done\n\n");
4809 /* Get rid of the extra triples */
4810 nfirst = RHS(nfunc, 0)->next;
4811 free_triple(state, RHS(nfunc, 0));
4813 free_triple(state, nfunc);
4815 /* Append the new function list onto the return list */
4817 nend = nfirst->prev;
4826 static struct triple *flatten(
4827 struct compile_state *state, struct triple *first, struct triple *ptr)
4829 struct triple *orig_ptr;
4834 /* Only flatten triples once */
4835 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4841 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4842 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4843 use_triple(LHS(ptr, 0), ptr);
4844 use_triple(RHS(ptr, 0), ptr);
4847 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4851 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4852 return MISC(ptr, 0);
4855 ptr = flatten_land(state, first, ptr);
4858 ptr = flatten_lor(state, first, ptr);
4861 ptr = flatten_cond(state, first, ptr);
4864 ptr = flatten_call(state, first, ptr);
4868 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4869 use_triple(RHS(ptr, 0), ptr);
4872 use_triple(TARG(ptr, 0), ptr);
4873 if (TRIPLE_RHS(ptr->sizes)) {
4874 use_triple(RHS(ptr, 0), ptr);
4875 if (ptr->next != ptr) {
4876 use_triple(ptr->next, ptr);
4881 insert_triple(state, first, ptr);
4882 ptr->id |= TRIPLE_FLAG_FLATTENED;
4883 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4884 use_triple(MISC(ptr, 0), ptr);
4887 /* Since OP_DEREF is just a marker delete it when I flatten it */
4889 RHS(orig_ptr, 0) = 0;
4890 free_triple(state, orig_ptr);
4894 struct triple *base;
4896 base = flatten(state, first, base);
4897 if (base->op == OP_VAL_VEC) {
4898 ptr = struct_field(state, base, ptr->u.field);
4905 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4906 use_triple(MISC(ptr, 0), ptr);
4911 /* Flatten the easy cases we don't override */
4912 ptr = flatten_generic(state, first, ptr);
4915 } while(ptr && (ptr != orig_ptr));
4917 insert_triple(state, first, ptr);
4918 ptr->id |= TRIPLE_FLAG_FLATTENED;
4923 static void release_expr(struct compile_state *state, struct triple *expr)
4925 struct triple *head;
4926 head = label(state);
4927 flatten(state, head, expr);
4928 while(head->next != head) {
4929 release_triple(state, head->next);
4931 free_triple(state, head);
4934 static int replace_rhs_use(struct compile_state *state,
4935 struct triple *orig, struct triple *new, struct triple *use)
4937 struct triple **expr;
4940 expr = triple_rhs(state, use, 0);
4941 for(;expr; expr = triple_rhs(state, use, expr)) {
4942 if (*expr == orig) {
4948 unuse_triple(orig, use);
4949 use_triple(new, use);
4954 static int replace_lhs_use(struct compile_state *state,
4955 struct triple *orig, struct triple *new, struct triple *use)
4957 struct triple **expr;
4960 expr = triple_lhs(state, use, 0);
4961 for(;expr; expr = triple_lhs(state, use, expr)) {
4962 if (*expr == orig) {
4968 unuse_triple(orig, use);
4969 use_triple(new, use);
4974 static void propogate_use(struct compile_state *state,
4975 struct triple *orig, struct triple *new)
4977 struct triple_set *user, *next;
4978 for(user = orig->use; user; user = next) {
4984 found |= replace_rhs_use(state, orig, new, use);
4985 found |= replace_lhs_use(state, orig, new, use);
4987 internal_error(state, use, "use without use");
4991 internal_error(state, orig, "used after propogate_use");
4997 * ===========================
5000 static struct triple *mk_add_expr(
5001 struct compile_state *state, struct triple *left, struct triple *right)
5003 struct type *result_type;
5004 /* Put pointer operands on the left */
5005 if (is_pointer(right)) {
5011 left = read_expr(state, left);
5012 right = read_expr(state, right);
5013 result_type = ptr_arithmetic_result(state, left, right);
5014 if (is_pointer(left)) {
5015 right = triple(state,
5016 is_signed(right->type)? OP_SMUL : OP_UMUL,
5019 int_const(state, &ulong_type,
5020 size_of(state, left->type->left)));
5022 return triple(state, OP_ADD, result_type, left, right);
5025 static struct triple *mk_sub_expr(
5026 struct compile_state *state, struct triple *left, struct triple *right)
5028 struct type *result_type;
5029 result_type = ptr_arithmetic_result(state, left, right);
5030 left = read_expr(state, left);
5031 right = read_expr(state, right);
5032 if (is_pointer(left)) {
5033 right = triple(state,
5034 is_signed(right->type)? OP_SMUL : OP_UMUL,
5037 int_const(state, &ulong_type,
5038 size_of(state, left->type->left)));
5040 return triple(state, OP_SUB, result_type, left, right);
5043 static struct triple *mk_pre_inc_expr(
5044 struct compile_state *state, struct triple *def)
5048 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5049 return triple(state, OP_VAL, def->type,
5050 write_expr(state, def, val),
5054 static struct triple *mk_pre_dec_expr(
5055 struct compile_state *state, struct triple *def)
5059 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5060 return triple(state, OP_VAL, def->type,
5061 write_expr(state, def, val),
5065 static struct triple *mk_post_inc_expr(
5066 struct compile_state *state, struct triple *def)
5070 val = read_expr(state, def);
5071 return triple(state, OP_VAL, def->type,
5072 write_expr(state, def,
5073 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5077 static struct triple *mk_post_dec_expr(
5078 struct compile_state *state, struct triple *def)
5082 val = read_expr(state, def);
5083 return triple(state, OP_VAL, def->type,
5084 write_expr(state, def,
5085 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5089 static struct triple *mk_subscript_expr(
5090 struct compile_state *state, struct triple *left, struct triple *right)
5092 left = read_expr(state, left);
5093 right = read_expr(state, right);
5094 if (!is_pointer(left) && !is_pointer(right)) {
5095 error(state, left, "subscripted value is not a pointer");
5097 return mk_deref_expr(state, mk_add_expr(state, left, right));
5101 * Compile time evaluation
5102 * ===========================
5104 static int is_const(struct triple *ins)
5106 return IS_CONST_OP(ins->op);
5109 static int constants_equal(struct compile_state *state,
5110 struct triple *left, struct triple *right)
5113 if (!is_const(left) || !is_const(right)) {
5116 else if (left->op != right->op) {
5119 else if (!equiv_types(left->type, right->type)) {
5126 if (left->u.cval == right->u.cval) {
5132 size_t lsize, rsize;
5133 lsize = size_of(state, left->type);
5134 rsize = size_of(state, right->type);
5135 if (lsize != rsize) {
5138 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5144 if ((MISC(left, 0) == MISC(right, 0)) &&
5145 (left->u.cval == right->u.cval)) {
5150 internal_error(state, left, "uknown constant type");
5157 static int is_zero(struct triple *ins)
5159 return is_const(ins) && (ins->u.cval == 0);
5162 static int is_one(struct triple *ins)
5164 return is_const(ins) && (ins->u.cval == 1);
5167 static long_t bsr(ulong_t value)
5170 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5181 static long_t bsf(ulong_t value)
5184 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5195 static long_t log2(ulong_t value)
5200 static long_t tlog2(struct triple *ins)
5202 return log2(ins->u.cval);
5205 static int is_pow2(struct triple *ins)
5207 ulong_t value, mask;
5209 if (!is_const(ins)) {
5212 value = ins->u.cval;
5219 return ((value & mask) == value);
5222 static ulong_t read_const(struct compile_state *state,
5223 struct triple *ins, struct triple **expr)
5227 switch(rhs->type->type &TYPE_MASK) {
5239 internal_error(state, rhs, "bad type to read_const\n");
5245 static long_t read_sconst(struct triple *ins, struct triple **expr)
5249 return (long_t)(rhs->u.cval);
5252 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5254 struct triple **expr;
5255 expr = triple_rhs(state, ins, 0);
5256 for(;expr;expr = triple_rhs(state, ins, expr)) {
5258 unuse_triple(*expr, ins);
5264 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5266 struct triple **expr;
5267 expr = triple_lhs(state, ins, 0);
5268 for(;expr;expr = triple_lhs(state, ins, expr)) {
5269 unuse_triple(*expr, ins);
5274 static void check_lhs(struct compile_state *state, struct triple *ins)
5276 struct triple **expr;
5277 expr = triple_lhs(state, ins, 0);
5278 for(;expr;expr = triple_lhs(state, ins, expr)) {
5279 internal_error(state, ins, "unexpected lhs");
5283 static void check_targ(struct compile_state *state, struct triple *ins)
5285 struct triple **expr;
5286 expr = triple_targ(state, ins, 0);
5287 for(;expr;expr = triple_targ(state, ins, expr)) {
5288 internal_error(state, ins, "unexpected targ");
5292 static void wipe_ins(struct compile_state *state, struct triple *ins)
5294 /* Becareful which instructions you replace the wiped
5295 * instruction with, as there are not enough slots
5296 * in all instructions to hold all others.
5298 check_targ(state, ins);
5299 unuse_rhs(state, ins);
5300 unuse_lhs(state, ins);
5303 static void mkcopy(struct compile_state *state,
5304 struct triple *ins, struct triple *rhs)
5306 wipe_ins(state, ins);
5308 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5310 use_triple(RHS(ins, 0), ins);
5313 static void mkconst(struct compile_state *state,
5314 struct triple *ins, ulong_t value)
5316 if (!is_integral(ins) && !is_pointer(ins)) {
5317 internal_error(state, ins, "unknown type to make constant\n");
5319 wipe_ins(state, ins);
5320 ins->op = OP_INTCONST;
5321 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5322 ins->u.cval = value;
5325 static void mkaddr_const(struct compile_state *state,
5326 struct triple *ins, struct triple *sdecl, ulong_t value)
5328 wipe_ins(state, ins);
5329 ins->op = OP_ADDRCONST;
5330 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5331 MISC(ins, 0) = sdecl;
5332 ins->u.cval = value;
5333 use_triple(sdecl, ins);
5336 /* Transform multicomponent variables into simple register variables */
5337 static void flatten_structures(struct compile_state *state)
5339 struct triple *ins, *first;
5340 first = RHS(state->main_function, 0);
5342 /* Pass one expand structure values into valvecs.
5346 struct triple *next;
5348 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5349 if (ins->op == OP_VAL_VEC) {
5352 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5353 struct triple *def, **vector;
5360 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5361 ins->filename, ins->line, ins->col);
5363 vector = &RHS(next, 0);
5364 tptr = next->type->left;
5365 for(i = 0; i < next->type->elements; i++) {
5366 struct triple *sfield;
5369 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5370 mtype = mtype->left;
5372 sfield = deref_field(state, def, mtype->field_ident);
5375 state, op, mtype, sfield, 0);
5376 vector[i]->filename = next->filename;
5377 vector[i]->line = next->line;
5378 vector[i]->col = next->col;
5381 propogate_use(state, ins, next);
5382 flatten(state, ins, next);
5383 free_triple(state, ins);
5385 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5386 struct triple *src, *dst, **vector;
5394 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5395 ins->filename, ins->line, ins->col);
5397 vector = &RHS(next, 0);
5398 tptr = next->type->left;
5399 for(i = 0; i < ins->type->elements; i++) {
5400 struct triple *dfield, *sfield;
5403 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5404 mtype = mtype->left;
5406 sfield = deref_field(state, src, mtype->field_ident);
5407 dfield = deref_field(state, dst, mtype->field_ident);
5409 state, op, mtype, dfield, sfield);
5410 vector[i]->filename = next->filename;
5411 vector[i]->line = next->line;
5412 vector[i]->col = next->col;
5415 propogate_use(state, ins, next);
5416 flatten(state, ins, next);
5417 free_triple(state, ins);
5421 } while(ins != first);
5422 /* Pass two flatten the valvecs.
5426 struct triple *next;
5428 if (ins->op == OP_VAL_VEC) {
5429 release_triple(state, ins);
5432 } while(ins != first);
5433 /* Pass three verify the state and set ->id to 0.
5437 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5438 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5439 internal_error(state, 0, "STRUCT_TYPE remains?");
5441 if (ins->op == OP_DOT) {
5442 internal_error(state, 0, "OP_DOT remains?");
5444 if (ins->op == OP_VAL_VEC) {
5445 internal_error(state, 0, "OP_VAL_VEC remains?");
5448 } while(ins != first);
5451 /* For those operations that cannot be simplified */
5452 static void simplify_noop(struct compile_state *state, struct triple *ins)
5457 static void simplify_smul(struct compile_state *state, struct triple *ins)
5459 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5462 RHS(ins, 0) = RHS(ins, 1);
5465 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5467 left = read_sconst(ins, &RHS(ins, 0));
5468 right = read_sconst(ins, &RHS(ins, 1));
5469 mkconst(state, ins, left * right);
5471 else if (is_zero(RHS(ins, 1))) {
5472 mkconst(state, ins, 0);
5474 else if (is_one(RHS(ins, 1))) {
5475 mkcopy(state, ins, RHS(ins, 0));
5477 else if (is_pow2(RHS(ins, 1))) {
5479 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5481 insert_triple(state, ins, val);
5482 unuse_triple(RHS(ins, 1), ins);
5483 use_triple(val, ins);
5488 static void simplify_umul(struct compile_state *state, struct triple *ins)
5490 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5493 RHS(ins, 0) = RHS(ins, 1);
5496 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5497 ulong_t left, right;
5498 left = read_const(state, ins, &RHS(ins, 0));
5499 right = read_const(state, ins, &RHS(ins, 1));
5500 mkconst(state, ins, left * right);
5502 else if (is_zero(RHS(ins, 1))) {
5503 mkconst(state, ins, 0);
5505 else if (is_one(RHS(ins, 1))) {
5506 mkcopy(state, ins, RHS(ins, 0));
5508 else if (is_pow2(RHS(ins, 1))) {
5510 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5512 insert_triple(state, ins, val);
5513 unuse_triple(RHS(ins, 1), ins);
5514 use_triple(val, ins);
5519 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5521 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5523 left = read_sconst(ins, &RHS(ins, 0));
5524 right = read_sconst(ins, &RHS(ins, 1));
5525 mkconst(state, ins, left / right);
5527 else if (is_zero(RHS(ins, 0))) {
5528 mkconst(state, ins, 0);
5530 else if (is_zero(RHS(ins, 1))) {
5531 error(state, ins, "division by zero");
5533 else if (is_one(RHS(ins, 1))) {
5534 mkcopy(state, ins, RHS(ins, 0));
5536 else if (is_pow2(RHS(ins, 1))) {
5538 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5540 insert_triple(state, ins, val);
5541 unuse_triple(RHS(ins, 1), ins);
5542 use_triple(val, ins);
5547 static void simplify_udiv(struct compile_state *state, struct triple *ins)
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, 0))) {
5556 mkconst(state, ins, 0);
5558 else if (is_zero(RHS(ins, 1))) {
5559 error(state, ins, "division by zero");
5561 else if (is_one(RHS(ins, 1))) {
5562 mkcopy(state, ins, RHS(ins, 0));
5564 else if (is_pow2(RHS(ins, 1))) {
5566 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5568 insert_triple(state, ins, val);
5569 unuse_triple(RHS(ins, 1), ins);
5570 use_triple(val, ins);
5575 static void simplify_smod(struct compile_state *state, struct triple *ins)
5577 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5579 left = read_const(state, ins, &RHS(ins, 0));
5580 right = read_const(state, ins, &RHS(ins, 1));
5581 mkconst(state, ins, left % right);
5583 else if (is_zero(RHS(ins, 0))) {
5584 mkconst(state, ins, 0);
5586 else if (is_zero(RHS(ins, 1))) {
5587 error(state, ins, "division by zero");
5589 else if (is_one(RHS(ins, 1))) {
5590 mkconst(state, ins, 0);
5592 else if (is_pow2(RHS(ins, 1))) {
5594 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5596 insert_triple(state, ins, val);
5597 unuse_triple(RHS(ins, 1), ins);
5598 use_triple(val, ins);
5602 static void simplify_umod(struct compile_state *state, struct triple *ins)
5604 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5605 ulong_t left, right;
5606 left = read_const(state, ins, &RHS(ins, 0));
5607 right = read_const(state, ins, &RHS(ins, 1));
5608 mkconst(state, ins, left % right);
5610 else if (is_zero(RHS(ins, 0))) {
5611 mkconst(state, ins, 0);
5613 else if (is_zero(RHS(ins, 1))) {
5614 error(state, ins, "division by zero");
5616 else if (is_one(RHS(ins, 1))) {
5617 mkconst(state, ins, 0);
5619 else if (is_pow2(RHS(ins, 1))) {
5621 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5623 insert_triple(state, ins, val);
5624 unuse_triple(RHS(ins, 1), ins);
5625 use_triple(val, ins);
5630 static void simplify_add(struct compile_state *state, struct triple *ins)
5632 /* start with the pointer on the left */
5633 if (is_pointer(RHS(ins, 1))) {
5636 RHS(ins, 0) = RHS(ins, 1);
5639 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5640 if (!is_pointer(RHS(ins, 0))) {
5641 ulong_t left, right;
5642 left = read_const(state, ins, &RHS(ins, 0));
5643 right = read_const(state, ins, &RHS(ins, 1));
5644 mkconst(state, ins, left + right);
5646 else /* op == OP_ADDRCONST */ {
5647 struct triple *sdecl;
5648 ulong_t left, right;
5649 sdecl = MISC(RHS(ins, 0), 0);
5650 left = RHS(ins, 0)->u.cval;
5651 right = RHS(ins, 1)->u.cval;
5652 mkaddr_const(state, ins, sdecl, left + right);
5655 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5658 RHS(ins, 1) = RHS(ins, 0);
5663 static void simplify_sub(struct compile_state *state, struct triple *ins)
5665 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5666 if (!is_pointer(RHS(ins, 0))) {
5667 ulong_t left, right;
5668 left = read_const(state, ins, &RHS(ins, 0));
5669 right = read_const(state, ins, &RHS(ins, 1));
5670 mkconst(state, ins, left - right);
5672 else /* op == OP_ADDRCONST */ {
5673 struct triple *sdecl;
5674 ulong_t left, right;
5675 sdecl = MISC(RHS(ins, 0), 0);
5676 left = RHS(ins, 0)->u.cval;
5677 right = RHS(ins, 1)->u.cval;
5678 mkaddr_const(state, ins, sdecl, left - right);
5683 static void simplify_sl(struct compile_state *state, struct triple *ins)
5685 if (is_const(RHS(ins, 1))) {
5687 right = read_const(state, ins, &RHS(ins, 1));
5688 if (right >= (size_of(state, ins->type)*8)) {
5689 warning(state, ins, "left shift count >= width of type");
5692 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5693 ulong_t left, right;
5694 left = read_const(state, ins, &RHS(ins, 0));
5695 right = read_const(state, ins, &RHS(ins, 1));
5696 mkconst(state, ins, left << right);
5700 static void simplify_usr(struct compile_state *state, struct triple *ins)
5702 if (is_const(RHS(ins, 1))) {
5704 right = read_const(state, ins, &RHS(ins, 1));
5705 if (right >= (size_of(state, ins->type)*8)) {
5706 warning(state, ins, "right shift count >= width of type");
5709 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5710 ulong_t left, right;
5711 left = read_const(state, ins, &RHS(ins, 0));
5712 right = read_const(state, ins, &RHS(ins, 1));
5713 mkconst(state, ins, left >> right);
5717 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5719 if (is_const(RHS(ins, 1))) {
5721 right = read_const(state, ins, &RHS(ins, 1));
5722 if (right >= (size_of(state, ins->type)*8)) {
5723 warning(state, ins, "right shift count >= width of type");
5726 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5728 left = read_sconst(ins, &RHS(ins, 0));
5729 right = read_sconst(ins, &RHS(ins, 1));
5730 mkconst(state, ins, left >> right);
5734 static void simplify_and(struct compile_state *state, struct triple *ins)
5736 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5737 ulong_t left, right;
5738 left = read_const(state, ins, &RHS(ins, 0));
5739 right = read_const(state, ins, &RHS(ins, 1));
5740 mkconst(state, ins, left & right);
5744 static void simplify_or(struct compile_state *state, struct triple *ins)
5746 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5747 ulong_t left, right;
5748 left = read_const(state, ins, &RHS(ins, 0));
5749 right = read_const(state, ins, &RHS(ins, 1));
5750 mkconst(state, ins, left | right);
5754 static void simplify_xor(struct compile_state *state, struct triple *ins)
5756 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5757 ulong_t left, right;
5758 left = read_const(state, ins, &RHS(ins, 0));
5759 right = read_const(state, ins, &RHS(ins, 1));
5760 mkconst(state, ins, left ^ right);
5764 static void simplify_pos(struct compile_state *state, struct triple *ins)
5766 if (is_const(RHS(ins, 0))) {
5767 mkconst(state, ins, RHS(ins, 0)->u.cval);
5770 mkcopy(state, ins, RHS(ins, 0));
5774 static void simplify_neg(struct compile_state *state, struct triple *ins)
5776 if (is_const(RHS(ins, 0))) {
5778 left = read_const(state, ins, &RHS(ins, 0));
5779 mkconst(state, ins, -left);
5781 else if (RHS(ins, 0)->op == OP_NEG) {
5782 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5786 static void simplify_invert(struct compile_state *state, struct triple *ins)
5788 if (is_const(RHS(ins, 0))) {
5790 left = read_const(state, ins, &RHS(ins, 0));
5791 mkconst(state, ins, ~left);
5795 static void simplify_eq(struct compile_state *state, struct triple *ins)
5797 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5798 ulong_t left, right;
5799 left = read_const(state, ins, &RHS(ins, 0));
5800 right = read_const(state, ins, &RHS(ins, 1));
5801 mkconst(state, ins, left == right);
5803 else if (RHS(ins, 0) == RHS(ins, 1)) {
5804 mkconst(state, ins, 1);
5808 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5810 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5811 ulong_t left, right;
5812 left = read_const(state, ins, &RHS(ins, 0));
5813 right = read_const(state, ins, &RHS(ins, 1));
5814 mkconst(state, ins, left != right);
5816 else if (RHS(ins, 0) == RHS(ins, 1)) {
5817 mkconst(state, ins, 0);
5821 static void simplify_sless(struct compile_state *state, struct triple *ins)
5823 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5825 left = read_sconst(ins, &RHS(ins, 0));
5826 right = read_sconst(ins, &RHS(ins, 1));
5827 mkconst(state, ins, left < right);
5829 else if (RHS(ins, 0) == RHS(ins, 1)) {
5830 mkconst(state, ins, 0);
5834 static void simplify_uless(struct compile_state *state, struct triple *ins)
5836 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5837 ulong_t left, right;
5838 left = read_const(state, ins, &RHS(ins, 0));
5839 right = read_const(state, ins, &RHS(ins, 1));
5840 mkconst(state, ins, left < right);
5842 else if (is_zero(RHS(ins, 0))) {
5843 mkconst(state, ins, 1);
5845 else if (RHS(ins, 0) == RHS(ins, 1)) {
5846 mkconst(state, ins, 0);
5850 static void simplify_smore(struct compile_state *state, struct triple *ins)
5852 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5854 left = read_sconst(ins, &RHS(ins, 0));
5855 right = read_sconst(ins, &RHS(ins, 1));
5856 mkconst(state, ins, left > right);
5858 else if (RHS(ins, 0) == RHS(ins, 1)) {
5859 mkconst(state, ins, 0);
5863 static void simplify_umore(struct compile_state *state, struct triple *ins)
5865 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5866 ulong_t left, right;
5867 left = read_const(state, ins, &RHS(ins, 0));
5868 right = read_const(state, ins, &RHS(ins, 1));
5869 mkconst(state, ins, left > right);
5871 else if (is_zero(RHS(ins, 1))) {
5872 mkconst(state, ins, 1);
5874 else if (RHS(ins, 0) == RHS(ins, 1)) {
5875 mkconst(state, ins, 0);
5880 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5882 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5884 left = read_sconst(ins, &RHS(ins, 0));
5885 right = read_sconst(ins, &RHS(ins, 1));
5886 mkconst(state, ins, left <= right);
5888 else if (RHS(ins, 0) == RHS(ins, 1)) {
5889 mkconst(state, ins, 1);
5893 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5895 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5896 ulong_t left, right;
5897 left = read_const(state, ins, &RHS(ins, 0));
5898 right = read_const(state, ins, &RHS(ins, 1));
5899 mkconst(state, ins, left <= right);
5901 else if (is_zero(RHS(ins, 0))) {
5902 mkconst(state, ins, 1);
5904 else if (RHS(ins, 0) == RHS(ins, 1)) {
5905 mkconst(state, ins, 1);
5909 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5911 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5913 left = read_sconst(ins, &RHS(ins, 0));
5914 right = read_sconst(ins, &RHS(ins, 1));
5915 mkconst(state, ins, left >= right);
5917 else if (RHS(ins, 0) == RHS(ins, 1)) {
5918 mkconst(state, ins, 1);
5922 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5924 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5925 ulong_t left, right;
5926 left = read_const(state, ins, &RHS(ins, 0));
5927 right = read_const(state, ins, &RHS(ins, 1));
5928 mkconst(state, ins, left >= right);
5930 else if (is_zero(RHS(ins, 1))) {
5931 mkconst(state, ins, 1);
5933 else if (RHS(ins, 0) == RHS(ins, 1)) {
5934 mkconst(state, ins, 1);
5938 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5940 if (is_const(RHS(ins, 0))) {
5942 left = read_const(state, ins, &RHS(ins, 0));
5943 mkconst(state, ins, left == 0);
5945 /* Otherwise if I am the only user... */
5946 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
5948 /* Invert a boolean operation */
5949 switch(RHS(ins, 0)->op) {
5950 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
5951 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
5952 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
5953 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
5954 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
5955 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
5956 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
5957 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
5958 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
5959 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
5960 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
5961 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
5967 mkcopy(state, ins, RHS(ins, 0));
5972 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
5974 if (is_const(RHS(ins, 0))) {
5976 left = read_const(state, ins, &RHS(ins, 0));
5977 mkconst(state, ins, left != 0);
5979 else switch(RHS(ins, 0)->op) {
5980 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
5981 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
5982 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
5983 mkcopy(state, ins, RHS(ins, 0));
5988 static void simplify_copy(struct compile_state *state, struct triple *ins)
5990 if (is_const(RHS(ins, 0))) {
5991 switch(RHS(ins, 0)->op) {
5995 left = read_const(state, ins, &RHS(ins, 0));
5996 mkconst(state, ins, left);
6001 struct triple *sdecl;
6003 sdecl = MISC(RHS(ins, 0), 0);
6004 offset = RHS(ins, 0)->u.cval;
6005 mkaddr_const(state, ins, sdecl, offset);
6009 internal_error(state, ins, "uknown constant");
6015 static void simplify_branch(struct compile_state *state, struct triple *ins)
6017 struct block *block;
6018 if (ins->op != OP_BRANCH) {
6019 internal_error(state, ins, "not branch");
6021 if (ins->use != 0) {
6022 internal_error(state, ins, "branch use");
6024 #warning "FIXME implement simplify branch."
6025 /* The challenge here with simplify branch is that I need to
6026 * make modifications to the control flow graph as well
6027 * as to the branch instruction itself.
6029 block = ins->u.block;
6031 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6032 struct triple *targ;
6034 value = read_const(state, ins, &RHS(ins, 0));
6035 unuse_triple(RHS(ins, 0), ins);
6036 targ = TARG(ins, 0);
6037 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6039 unuse_triple(ins->next, ins);
6040 TARG(ins, 0) = targ;
6043 unuse_triple(targ, ins);
6044 TARG(ins, 0) = ins->next;
6046 #warning "FIXME handle the case of making a branch unconditional"
6048 if (TARG(ins, 0) == ins->next) {
6049 unuse_triple(ins->next, ins);
6050 if (TRIPLE_RHS(ins->sizes)) {
6051 unuse_triple(RHS(ins, 0), ins);
6052 unuse_triple(ins->next, ins);
6054 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6057 internal_error(state, ins, "noop use != 0");
6059 #warning "FIXME handle the case of killing a branch"
6063 static void simplify_phi(struct compile_state *state, struct triple *ins)
6065 struct triple **expr;
6067 expr = triple_rhs(state, ins, 0);
6068 if (!*expr || !is_const(*expr)) {
6071 value = read_const(state, ins, expr);
6072 for(;expr;expr = triple_rhs(state, ins, expr)) {
6073 if (!*expr || !is_const(*expr)) {
6076 if (value != read_const(state, ins, expr)) {
6080 mkconst(state, ins, value);
6084 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6086 if (is_const(RHS(ins, 0))) {
6088 left = read_const(state, ins, &RHS(ins, 0));
6089 mkconst(state, ins, bsf(left));
6093 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6095 if (is_const(RHS(ins, 0))) {
6097 left = read_const(state, ins, &RHS(ins, 0));
6098 mkconst(state, ins, bsr(left));
6103 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6104 static const simplify_t table_simplify[] = {
6106 #define simplify_smul simplify_noop
6107 #define simplify_umul simplify_noop
6108 #define simplify_sdiv simplify_noop
6109 #define simplify_udiv simplify_noop
6110 #define simplify_smod simplify_noop
6111 #define simplify_umod simplify_noop
6114 #define simplify_add simplify_noop
6115 #define simplify_sub simplify_noop
6118 #define simplify_sl simplify_noop
6119 #define simplify_usr simplify_noop
6120 #define simplify_ssr simplify_noop
6123 #define simplify_and simplify_noop
6124 #define simplify_xor simplify_noop
6125 #define simplify_or simplify_noop
6128 #define simplify_pos simplify_noop
6129 #define simplify_neg simplify_noop
6130 #define simplify_invert simplify_noop
6134 #define simplify_eq simplify_noop
6135 #define simplify_noteq simplify_noop
6138 #define simplify_sless simplify_noop
6139 #define simplify_uless simplify_noop
6140 #define simplify_smore simplify_noop
6141 #define simplify_umore simplify_noop
6144 #define simplify_slesseq simplify_noop
6145 #define simplify_ulesseq simplify_noop
6146 #define simplify_smoreeq simplify_noop
6147 #define simplify_umoreeq simplify_noop
6150 #define simplify_lfalse simplify_noop
6153 #define simplify_ltrue simplify_noop
6157 #define simplify_copy simplify_noop
6161 #define simplify_branch simplify_noop
6165 #define simplify_phi simplify_noop
6169 #define simplify_bsf simplify_noop
6170 #define simplify_bsr simplify_noop
6173 [OP_SMUL ] = simplify_smul,
6174 [OP_UMUL ] = simplify_umul,
6175 [OP_SDIV ] = simplify_sdiv,
6176 [OP_UDIV ] = simplify_udiv,
6177 [OP_SMOD ] = simplify_smod,
6178 [OP_UMOD ] = simplify_umod,
6179 [OP_ADD ] = simplify_add,
6180 [OP_SUB ] = simplify_sub,
6181 [OP_SL ] = simplify_sl,
6182 [OP_USR ] = simplify_usr,
6183 [OP_SSR ] = simplify_ssr,
6184 [OP_AND ] = simplify_and,
6185 [OP_XOR ] = simplify_xor,
6186 [OP_OR ] = simplify_or,
6187 [OP_POS ] = simplify_pos,
6188 [OP_NEG ] = simplify_neg,
6189 [OP_INVERT ] = simplify_invert,
6191 [OP_EQ ] = simplify_eq,
6192 [OP_NOTEQ ] = simplify_noteq,
6193 [OP_SLESS ] = simplify_sless,
6194 [OP_ULESS ] = simplify_uless,
6195 [OP_SMORE ] = simplify_smore,
6196 [OP_UMORE ] = simplify_umore,
6197 [OP_SLESSEQ ] = simplify_slesseq,
6198 [OP_ULESSEQ ] = simplify_ulesseq,
6199 [OP_SMOREEQ ] = simplify_smoreeq,
6200 [OP_UMOREEQ ] = simplify_umoreeq,
6201 [OP_LFALSE ] = simplify_lfalse,
6202 [OP_LTRUE ] = simplify_ltrue,
6204 [OP_LOAD ] = simplify_noop,
6205 [OP_STORE ] = simplify_noop,
6207 [OP_NOOP ] = simplify_noop,
6209 [OP_INTCONST ] = simplify_noop,
6210 [OP_BLOBCONST ] = simplify_noop,
6211 [OP_ADDRCONST ] = simplify_noop,
6213 [OP_WRITE ] = simplify_noop,
6214 [OP_READ ] = simplify_noop,
6215 [OP_COPY ] = simplify_copy,
6216 [OP_PIECE ] = simplify_noop,
6217 [OP_ASM ] = simplify_noop,
6219 [OP_DOT ] = simplify_noop,
6220 [OP_VAL_VEC ] = simplify_noop,
6222 [OP_LIST ] = simplify_noop,
6223 [OP_BRANCH ] = simplify_branch,
6224 [OP_LABEL ] = simplify_noop,
6225 [OP_ADECL ] = simplify_noop,
6226 [OP_SDECL ] = simplify_noop,
6227 [OP_PHI ] = simplify_phi,
6229 [OP_INB ] = simplify_noop,
6230 [OP_INW ] = simplify_noop,
6231 [OP_INL ] = simplify_noop,
6232 [OP_OUTB ] = simplify_noop,
6233 [OP_OUTW ] = simplify_noop,
6234 [OP_OUTL ] = simplify_noop,
6235 [OP_BSF ] = simplify_bsf,
6236 [OP_BSR ] = simplify_bsr,
6237 [OP_RDMSR ] = simplify_noop,
6238 [OP_WRMSR ] = simplify_noop,
6239 [OP_HLT ] = simplify_noop,
6242 static void simplify(struct compile_state *state, struct triple *ins)
6245 simplify_t do_simplify;
6249 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6253 do_simplify = table_simplify[op];
6256 internal_error(state, ins, "cannot simplify op: %d %s\n",
6260 do_simplify(state, ins);
6261 } while(ins->op != op);
6264 static void simplify_all(struct compile_state *state)
6266 struct triple *ins, *first;
6267 first = RHS(state->main_function, 0);
6270 simplify(state, ins);
6272 } while(ins != first);
6277 * ============================
6280 static void register_builtin_function(struct compile_state *state,
6281 const char *name, int op, struct type *rtype, ...)
6283 struct type *ftype, *atype, *param, **next;
6284 struct triple *def, *arg, *result, *work, *last, *first;
6285 struct hash_entry *ident;
6286 struct file_state file;
6292 /* Dummy file state to get debug handling right */
6293 memset(&file, 0, sizeof(file));
6294 file.basename = name;
6296 file.prev = state->file;
6297 state->file = &file;
6299 /* Find the Parameter count */
6300 valid_op(state, op);
6301 parameters = table_ops[op].rhs;
6302 if (parameters < 0 ) {
6303 internal_error(state, 0, "Invalid builtin parameter count");
6306 /* Find the function type */
6307 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6308 next = &ftype->right;
6309 va_start(args, rtype);
6310 for(i = 0; i < parameters; i++) {
6311 atype = va_arg(args, struct type *);
6315 *next = new_type(TYPE_PRODUCT, *next, atype);
6316 next = &((*next)->right);
6324 /* Generate the needed triples */
6325 def = triple(state, OP_LIST, ftype, 0, 0);
6326 first = label(state);
6327 RHS(def, 0) = first;
6329 /* Now string them together */
6330 param = ftype->right;
6331 for(i = 0; i < parameters; i++) {
6332 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6333 atype = param->left;
6337 arg = flatten(state, first, variable(state, atype));
6338 param = param->right;
6341 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6342 result = flatten(state, first, variable(state, rtype));
6344 MISC(def, 0) = result;
6345 work = new_triple(state, op, rtype, -1, parameters);
6346 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6347 RHS(work, i) = read_expr(state, arg);
6349 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6351 /* Populate the LHS with the target registers */
6352 work = flatten(state, first, work);
6353 work->type = &void_type;
6354 param = rtype->left;
6355 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6356 internal_error(state, 0, "Invalid result type");
6358 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6359 for(i = 0; i < rtype->elements; i++) {
6360 struct triple *piece;
6362 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6363 atype = param->left;
6365 if (!TYPE_ARITHMETIC(atype->type) &&
6366 !TYPE_PTR(atype->type)) {
6367 internal_error(state, 0, "Invalid lhs type");
6369 piece = triple(state, OP_PIECE, atype, work, 0);
6371 LHS(work, i) = piece;
6372 RHS(val, i) = piece;
6377 work = write_expr(state, result, work);
6379 work = flatten(state, first, work);
6380 last = flatten(state, first, label(state));
6381 name_len = strlen(name);
6382 ident = lookup(state, name, name_len);
6383 symbol(state, ident, &ident->sym_ident, def, ftype);
6385 state->file = file.prev;
6387 fprintf(stdout, "\n");
6388 loc(stdout, state, 0);
6389 fprintf(stdout, "\n__________ builtin_function _________\n");
6390 print_triple(state, def);
6391 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6395 static struct type *partial_struct(struct compile_state *state,
6396 const char *field_name, struct type *type, struct type *rest)
6398 struct hash_entry *field_ident;
6399 struct type *result;
6402 field_name_len = strlen(field_name);
6403 field_ident = lookup(state, field_name, field_name_len);
6405 result = clone_type(0, type);
6406 result->field_ident = field_ident;
6409 result = new_type(TYPE_PRODUCT, result, rest);
6414 static struct type *register_builtin_type(struct compile_state *state,
6415 const char *name, struct type *type)
6417 struct hash_entry *ident;
6420 name_len = strlen(name);
6421 ident = lookup(state, name, name_len);
6423 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6424 ulong_t elements = 0;
6426 type = new_type(TYPE_STRUCT, type, 0);
6428 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6430 field = field->right;
6433 symbol(state, ident, &ident->sym_struct, 0, type);
6434 type->type_ident = ident;
6435 type->elements = elements;
6437 symbol(state, ident, &ident->sym_ident, 0, type);
6438 ident->tok = TOK_TYPE_NAME;
6443 static void register_builtins(struct compile_state *state)
6445 struct type *msr_type;
6447 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6449 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6451 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6454 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6455 &uchar_type, &ushort_type);
6456 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6457 &ushort_type, &ushort_type);
6458 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6459 &uint_type, &ushort_type);
6461 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6463 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6466 msr_type = register_builtin_type(state, "__builtin_msr_t",
6467 partial_struct(state, "lo", &ulong_type,
6468 partial_struct(state, "hi", &ulong_type, 0)));
6470 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6472 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6473 &ulong_type, &ulong_type, &ulong_type);
6475 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6479 static struct type *declarator(
6480 struct compile_state *state, struct type *type,
6481 struct hash_entry **ident, int need_ident);
6482 static void decl(struct compile_state *state, struct triple *first);
6483 static struct type *specifier_qualifier_list(struct compile_state *state);
6484 static int isdecl_specifier(int tok);
6485 static struct type *decl_specifiers(struct compile_state *state);
6486 static int istype(int tok);
6487 static struct triple *expr(struct compile_state *state);
6488 static struct triple *assignment_expr(struct compile_state *state);
6489 static struct type *type_name(struct compile_state *state);
6490 static void statement(struct compile_state *state, struct triple *fist);
6492 static struct triple *call_expr(
6493 struct compile_state *state, struct triple *func)
6496 struct type *param, *type;
6497 ulong_t pvals, index;
6499 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6500 error(state, 0, "Called object is not a function");
6502 if (func->op != OP_LIST) {
6503 internal_error(state, 0, "improper function");
6505 eat(state, TOK_LPAREN);
6506 /* Find the return type without any specifiers */
6507 type = clone_type(0, func->type->left);
6508 def = new_triple(state, OP_CALL, func->type, -1, -1);
6511 pvals = TRIPLE_RHS(def->sizes);
6512 MISC(def, 0) = func;
6514 param = func->type->right;
6515 for(index = 0; index < pvals; index++) {
6517 struct type *arg_type;
6518 val = read_expr(state, assignment_expr(state));
6520 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6521 arg_type = param->left;
6523 write_compatible(state, arg_type, val->type);
6524 RHS(def, index) = val;
6525 if (index != (pvals - 1)) {
6526 eat(state, TOK_COMMA);
6527 param = param->right;
6530 eat(state, TOK_RPAREN);
6535 static struct triple *character_constant(struct compile_state *state)
6539 const signed char *str, *end;
6542 eat(state, TOK_LIT_CHAR);
6543 tk = &state->token[0];
6544 str = tk->val.str + 1;
6545 str_len = tk->str_len - 2;
6547 error(state, 0, "empty character constant");
6549 end = str + str_len;
6550 c = char_value(state, &str, end);
6552 error(state, 0, "multibyte character constant not supported");
6554 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6558 static struct triple *string_constant(struct compile_state *state)
6563 const signed char *str, *end;
6564 signed char *buf, *ptr;
6568 type = new_type(TYPE_ARRAY, &char_type, 0);
6570 /* The while loop handles string concatenation */
6572 eat(state, TOK_LIT_STRING);
6573 tk = &state->token[0];
6574 str = tk->val.str + 1;
6575 str_len = tk->str_len - 2;
6577 error(state, 0, "negative string constant length");
6579 end = str + str_len;
6581 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6582 memcpy(buf, ptr, type->elements);
6583 ptr = buf + type->elements;
6585 *ptr++ = char_value(state, &str, end);
6587 type->elements = ptr - buf;
6588 } while(peek(state) == TOK_LIT_STRING);
6590 type->elements += 1;
6591 def = triple(state, OP_BLOBCONST, type, 0, 0);
6597 static struct triple *integer_constant(struct compile_state *state)
6606 eat(state, TOK_LIT_INT);
6607 tk = &state->token[0];
6609 decimal = (tk->val.str[0] != '0');
6610 val = strtoul(tk->val.str, &end, 0);
6611 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6612 error(state, 0, "Integer constant to large");
6615 if ((*end == 'u') || (*end == 'U')) {
6619 if ((*end == 'l') || (*end == 'L')) {
6623 if ((*end == 'u') || (*end == 'U')) {
6628 error(state, 0, "Junk at end of integer constant");
6635 if (!decimal && (val > LONG_MAX)) {
6641 if (val > UINT_MAX) {
6647 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6650 else if (!decimal && (val > LONG_MAX)) {
6653 else if (val > INT_MAX) {
6657 def = int_const(state, type, val);
6661 static struct triple *primary_expr(struct compile_state *state)
6669 struct hash_entry *ident;
6670 /* Here ident is either:
6673 * an enumeration constant.
6675 eat(state, TOK_IDENT);
6676 ident = state->token[0].ident;
6677 if (!ident->sym_ident) {
6678 error(state, 0, "%s undeclared", ident->name);
6680 def = ident->sym_ident->def;
6683 case TOK_ENUM_CONST:
6684 /* Here ident is an enumeration constant */
6685 eat(state, TOK_ENUM_CONST);
6690 eat(state, TOK_LPAREN);
6692 eat(state, TOK_RPAREN);
6695 def = integer_constant(state);
6698 eat(state, TOK_LIT_FLOAT);
6699 error(state, 0, "Floating point constants not supported");
6704 def = character_constant(state);
6706 case TOK_LIT_STRING:
6707 def = string_constant(state);
6711 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6716 static struct triple *postfix_expr(struct compile_state *state)
6720 def = primary_expr(state);
6722 struct triple *left;
6726 switch((tok = peek(state))) {
6728 eat(state, TOK_LBRACKET);
6729 def = mk_subscript_expr(state, left, expr(state));
6730 eat(state, TOK_RBRACKET);
6733 def = call_expr(state, def);
6737 struct hash_entry *field;
6738 eat(state, TOK_DOT);
6739 eat(state, TOK_IDENT);
6740 field = state->token[0].ident;
6741 def = deref_field(state, def, field);
6746 struct hash_entry *field;
6747 eat(state, TOK_ARROW);
6748 eat(state, TOK_IDENT);
6749 field = state->token[0].ident;
6750 def = mk_deref_expr(state, read_expr(state, def));
6751 def = deref_field(state, def, field);
6755 eat(state, TOK_PLUSPLUS);
6756 def = mk_post_inc_expr(state, left);
6758 case TOK_MINUSMINUS:
6759 eat(state, TOK_MINUSMINUS);
6760 def = mk_post_dec_expr(state, left);
6770 static struct triple *cast_expr(struct compile_state *state);
6772 static struct triple *unary_expr(struct compile_state *state)
6774 struct triple *def, *right;
6776 switch((tok = peek(state))) {
6778 eat(state, TOK_PLUSPLUS);
6779 def = mk_pre_inc_expr(state, unary_expr(state));
6781 case TOK_MINUSMINUS:
6782 eat(state, TOK_MINUSMINUS);
6783 def = mk_pre_dec_expr(state, unary_expr(state));
6786 eat(state, TOK_AND);
6787 def = mk_addr_expr(state, cast_expr(state), 0);
6790 eat(state, TOK_STAR);
6791 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6794 eat(state, TOK_PLUS);
6795 right = read_expr(state, cast_expr(state));
6796 arithmetic(state, right);
6797 def = integral_promotion(state, right);
6800 eat(state, TOK_MINUS);
6801 right = read_expr(state, cast_expr(state));
6802 arithmetic(state, right);
6803 def = integral_promotion(state, right);
6804 def = triple(state, OP_NEG, def->type, def, 0);
6807 eat(state, TOK_TILDE);
6808 right = read_expr(state, cast_expr(state));
6809 integral(state, right);
6810 def = integral_promotion(state, right);
6811 def = triple(state, OP_INVERT, def->type, def, 0);
6814 eat(state, TOK_BANG);
6815 right = read_expr(state, cast_expr(state));
6817 def = lfalse_expr(state, right);
6823 eat(state, TOK_SIZEOF);
6825 tok2 = peek2(state);
6826 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6827 eat(state, TOK_LPAREN);
6828 type = type_name(state);
6829 eat(state, TOK_RPAREN);
6832 struct triple *expr;
6833 expr = unary_expr(state);
6835 release_expr(state, expr);
6837 def = int_const(state, &ulong_type, size_of(state, type));
6844 eat(state, TOK_ALIGNOF);
6846 tok2 = peek2(state);
6847 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6848 eat(state, TOK_LPAREN);
6849 type = type_name(state);
6850 eat(state, TOK_RPAREN);
6853 struct triple *expr;
6854 expr = unary_expr(state);
6856 release_expr(state, expr);
6858 def = int_const(state, &ulong_type, align_of(state, type));
6862 def = postfix_expr(state);
6868 static struct triple *cast_expr(struct compile_state *state)
6873 tok2 = peek2(state);
6874 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6876 eat(state, TOK_LPAREN);
6877 type = type_name(state);
6878 eat(state, TOK_RPAREN);
6879 def = read_expr(state, cast_expr(state));
6880 def = triple(state, OP_COPY, type, def, 0);
6883 def = unary_expr(state);
6888 static struct triple *mult_expr(struct compile_state *state)
6892 def = cast_expr(state);
6894 struct triple *left, *right;
6895 struct type *result_type;
6898 switch(tok = (peek(state))) {
6902 left = read_expr(state, def);
6903 arithmetic(state, left);
6907 right = read_expr(state, cast_expr(state));
6908 arithmetic(state, right);
6910 result_type = arithmetic_result(state, left, right);
6911 sign = is_signed(result_type);
6914 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6915 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
6916 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
6918 def = triple(state, op, result_type, left, right);
6928 static struct triple *add_expr(struct compile_state *state)
6932 def = mult_expr(state);
6935 switch( peek(state)) {
6937 eat(state, TOK_PLUS);
6938 def = mk_add_expr(state, def, mult_expr(state));
6941 eat(state, TOK_MINUS);
6942 def = mk_sub_expr(state, def, mult_expr(state));
6952 static struct triple *shift_expr(struct compile_state *state)
6956 def = add_expr(state);
6958 struct triple *left, *right;
6961 switch((tok = peek(state))) {
6964 left = read_expr(state, def);
6965 integral(state, left);
6966 left = integral_promotion(state, left);
6970 right = read_expr(state, add_expr(state));
6971 integral(state, right);
6972 right = integral_promotion(state, right);
6974 op = (tok == TOK_SL)? OP_SL :
6975 is_signed(left->type)? OP_SSR: OP_USR;
6977 def = triple(state, op, left->type, left, right);
6987 static struct triple *relational_expr(struct compile_state *state)
6989 #warning "Extend relational exprs to work on more than arithmetic types"
6992 def = shift_expr(state);
6994 struct triple *left, *right;
6995 struct type *arg_type;
6998 switch((tok = peek(state))) {
7003 left = read_expr(state, def);
7004 arithmetic(state, left);
7008 right = read_expr(state, shift_expr(state));
7009 arithmetic(state, right);
7011 arg_type = arithmetic_result(state, left, right);
7012 sign = is_signed(arg_type);
7015 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7016 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7017 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7018 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7020 def = triple(state, op, &int_type, left, right);
7030 static struct triple *equality_expr(struct compile_state *state)
7032 #warning "Extend equality exprs to work on more than arithmetic types"
7035 def = relational_expr(state);
7037 struct triple *left, *right;
7040 switch((tok = peek(state))) {
7043 left = read_expr(state, def);
7044 arithmetic(state, left);
7046 right = read_expr(state, relational_expr(state));
7047 arithmetic(state, right);
7048 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7049 def = triple(state, op, &int_type, left, right);
7059 static struct triple *and_expr(struct compile_state *state)
7062 def = equality_expr(state);
7063 while(peek(state) == TOK_AND) {
7064 struct triple *left, *right;
7065 struct type *result_type;
7066 left = read_expr(state, def);
7067 integral(state, left);
7068 eat(state, TOK_AND);
7069 right = read_expr(state, equality_expr(state));
7070 integral(state, right);
7071 result_type = arithmetic_result(state, left, right);
7072 def = triple(state, OP_AND, result_type, left, right);
7077 static struct triple *xor_expr(struct compile_state *state)
7080 def = and_expr(state);
7081 while(peek(state) == TOK_XOR) {
7082 struct triple *left, *right;
7083 struct type *result_type;
7084 left = read_expr(state, def);
7085 integral(state, left);
7086 eat(state, TOK_XOR);
7087 right = read_expr(state, and_expr(state));
7088 integral(state, right);
7089 result_type = arithmetic_result(state, left, right);
7090 def = triple(state, OP_XOR, result_type, left, right);
7095 static struct triple *or_expr(struct compile_state *state)
7098 def = xor_expr(state);
7099 while(peek(state) == TOK_OR) {
7100 struct triple *left, *right;
7101 struct type *result_type;
7102 left = read_expr(state, def);
7103 integral(state, left);
7105 right = read_expr(state, xor_expr(state));
7106 integral(state, right);
7107 result_type = arithmetic_result(state, left, right);
7108 def = triple(state, OP_OR, result_type, left, right);
7113 static struct triple *land_expr(struct compile_state *state)
7116 def = or_expr(state);
7117 while(peek(state) == TOK_LOGAND) {
7118 struct triple *left, *right;
7119 left = read_expr(state, def);
7121 eat(state, TOK_LOGAND);
7122 right = read_expr(state, or_expr(state));
7125 def = triple(state, OP_LAND, &int_type,
7126 ltrue_expr(state, left),
7127 ltrue_expr(state, right));
7132 static struct triple *lor_expr(struct compile_state *state)
7135 def = land_expr(state);
7136 while(peek(state) == TOK_LOGOR) {
7137 struct triple *left, *right;
7138 left = read_expr(state, def);
7140 eat(state, TOK_LOGOR);
7141 right = read_expr(state, land_expr(state));
7144 def = triple(state, OP_LOR, &int_type,
7145 ltrue_expr(state, left),
7146 ltrue_expr(state, right));
7151 static struct triple *conditional_expr(struct compile_state *state)
7154 def = lor_expr(state);
7155 if (peek(state) == TOK_QUEST) {
7156 struct triple *test, *left, *right;
7158 test = ltrue_expr(state, read_expr(state, def));
7159 eat(state, TOK_QUEST);
7160 left = read_expr(state, expr(state));
7161 eat(state, TOK_COLON);
7162 right = read_expr(state, conditional_expr(state));
7164 def = cond_expr(state, test, left, right);
7169 static struct triple *eval_const_expr(
7170 struct compile_state *state, struct triple *expr)
7173 struct triple *head, *ptr;
7174 head = label(state); /* dummy initial triple */
7175 flatten(state, head, expr);
7176 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7177 simplify(state, ptr);
7179 /* Remove the constant value the tail of the list */
7181 def->prev->next = def->next;
7182 def->next->prev = def->prev;
7183 def->next = def->prev = def;
7184 if (!is_const(def)) {
7185 internal_error(state, 0, "Not a constant expression");
7187 /* Free the intermediate expressions */
7188 while(head->next != head) {
7189 release_triple(state, head->next);
7191 free_triple(state, head);
7195 static struct triple *constant_expr(struct compile_state *state)
7197 return eval_const_expr(state, conditional_expr(state));
7200 static struct triple *assignment_expr(struct compile_state *state)
7202 struct triple *def, *left, *right;
7204 /* The C grammer in K&R shows assignment expressions
7205 * only taking unary expressions as input on their
7206 * left hand side. But specifies the precedence of
7207 * assignemnt as the lowest operator except for comma.
7209 * Allowing conditional expressions on the left hand side
7210 * of an assignement results in a grammar that accepts
7211 * a larger set of statements than standard C. As long
7212 * as the subset of the grammar that is standard C behaves
7213 * correctly this should cause no problems.
7215 * For the extra token strings accepted by the grammar
7216 * none of them should produce a valid lvalue, so they
7217 * should not produce functioning programs.
7219 * GCC has this bug as well, so surprises should be minimal.
7221 def = conditional_expr(state);
7223 switch((tok = peek(state))) {
7225 lvalue(state, left);
7227 def = write_expr(state, left,
7228 read_expr(state, assignment_expr(state)));
7233 lvalue(state, left);
7234 arithmetic(state, left);
7236 right = read_expr(state, assignment_expr(state));
7237 arithmetic(state, right);
7239 sign = is_signed(left->type);
7242 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7243 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7244 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7246 def = write_expr(state, left,
7247 triple(state, op, left->type,
7248 read_expr(state, left), right));
7251 lvalue(state, left);
7252 eat(state, TOK_PLUSEQ);
7253 def = write_expr(state, left,
7254 mk_add_expr(state, left, assignment_expr(state)));
7257 lvalue(state, left);
7258 eat(state, TOK_MINUSEQ);
7259 def = write_expr(state, left,
7260 mk_sub_expr(state, left, assignment_expr(state)));
7267 lvalue(state, left);
7268 integral(state, left);
7270 right = read_expr(state, assignment_expr(state));
7271 integral(state, right);
7272 right = integral_promotion(state, right);
7273 sign = is_signed(left->type);
7276 case TOK_SLEQ: op = OP_SL; break;
7277 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7278 case TOK_ANDEQ: op = OP_AND; break;
7279 case TOK_XOREQ: op = OP_XOR; break;
7280 case TOK_OREQ: op = OP_OR; break;
7282 def = write_expr(state, left,
7283 triple(state, op, left->type,
7284 read_expr(state, left), right));
7290 static struct triple *expr(struct compile_state *state)
7293 def = assignment_expr(state);
7294 while(peek(state) == TOK_COMMA) {
7295 struct triple *left, *right;
7297 eat(state, TOK_COMMA);
7298 right = assignment_expr(state);
7299 def = triple(state, OP_COMMA, right->type, left, right);
7304 static void expr_statement(struct compile_state *state, struct triple *first)
7306 if (peek(state) != TOK_SEMI) {
7307 flatten(state, first, expr(state));
7309 eat(state, TOK_SEMI);
7312 static void if_statement(struct compile_state *state, struct triple *first)
7314 struct triple *test, *jmp1, *jmp2, *middle, *end;
7316 jmp1 = jmp2 = middle = 0;
7318 eat(state, TOK_LPAREN);
7321 /* Cleanup and invert the test */
7322 test = lfalse_expr(state, read_expr(state, test));
7323 eat(state, TOK_RPAREN);
7324 /* Generate the needed pieces */
7325 middle = label(state);
7326 jmp1 = branch(state, middle, test);
7327 /* Thread the pieces together */
7328 flatten(state, first, test);
7329 flatten(state, first, jmp1);
7330 flatten(state, first, label(state));
7331 statement(state, first);
7332 if (peek(state) == TOK_ELSE) {
7333 eat(state, TOK_ELSE);
7334 /* Generate the rest of the pieces */
7336 jmp2 = branch(state, end, 0);
7337 /* Thread them together */
7338 flatten(state, first, jmp2);
7339 flatten(state, first, middle);
7340 statement(state, first);
7341 flatten(state, first, end);
7344 flatten(state, first, middle);
7348 static void for_statement(struct compile_state *state, struct triple *first)
7350 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7351 struct triple *label1, *label2, *label3;
7352 struct hash_entry *ident;
7354 eat(state, TOK_FOR);
7355 eat(state, TOK_LPAREN);
7356 head = test = tail = jmp1 = jmp2 = 0;
7357 if (peek(state) != TOK_SEMI) {
7360 eat(state, TOK_SEMI);
7361 if (peek(state) != TOK_SEMI) {
7364 test = ltrue_expr(state, read_expr(state, test));
7366 eat(state, TOK_SEMI);
7367 if (peek(state) != TOK_RPAREN) {
7370 eat(state, TOK_RPAREN);
7371 /* Generate the needed pieces */
7372 label1 = label(state);
7373 label2 = label(state);
7374 label3 = label(state);
7376 jmp1 = branch(state, label3, 0);
7377 jmp2 = branch(state, label1, test);
7380 jmp2 = branch(state, label1, 0);
7383 /* Remember where break and continue go */
7385 ident = state->i_break;
7386 symbol(state, ident, &ident->sym_ident, end, end->type);
7387 ident = state->i_continue;
7388 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7389 /* Now include the body */
7390 flatten(state, first, head);
7391 flatten(state, first, jmp1);
7392 flatten(state, first, label1);
7393 statement(state, first);
7394 flatten(state, first, label2);
7395 flatten(state, first, tail);
7396 flatten(state, first, label3);
7397 flatten(state, first, test);
7398 flatten(state, first, jmp2);
7399 flatten(state, first, end);
7400 /* Cleanup the break/continue scope */
7404 static void while_statement(struct compile_state *state, struct triple *first)
7406 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7407 struct hash_entry *ident;
7408 eat(state, TOK_WHILE);
7409 eat(state, TOK_LPAREN);
7412 test = ltrue_expr(state, read_expr(state, test));
7413 eat(state, TOK_RPAREN);
7414 /* Generate the needed pieces */
7415 label1 = label(state);
7416 label2 = label(state);
7417 jmp1 = branch(state, label2, 0);
7418 jmp2 = branch(state, label1, test);
7420 /* Remember where break and continue go */
7422 ident = state->i_break;
7423 symbol(state, ident, &ident->sym_ident, end, end->type);
7424 ident = state->i_continue;
7425 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7426 /* Thread them together */
7427 flatten(state, first, jmp1);
7428 flatten(state, first, label1);
7429 statement(state, first);
7430 flatten(state, first, label2);
7431 flatten(state, first, test);
7432 flatten(state, first, jmp2);
7433 flatten(state, first, end);
7434 /* Cleanup the break/continue scope */
7438 static void do_statement(struct compile_state *state, struct triple *first)
7440 struct triple *label1, *label2, *test, *end;
7441 struct hash_entry *ident;
7443 /* Generate the needed pieces */
7444 label1 = label(state);
7445 label2 = label(state);
7447 /* Remember where break and continue go */
7449 ident = state->i_break;
7450 symbol(state, ident, &ident->sym_ident, end, end->type);
7451 ident = state->i_continue;
7452 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7453 /* Now include the body */
7454 flatten(state, first, label1);
7455 statement(state, first);
7456 /* Cleanup the break/continue scope */
7458 /* Eat the rest of the loop */
7459 eat(state, TOK_WHILE);
7460 eat(state, TOK_LPAREN);
7461 test = read_expr(state, expr(state));
7463 eat(state, TOK_RPAREN);
7464 eat(state, TOK_SEMI);
7465 /* Thread the pieces together */
7466 test = ltrue_expr(state, test);
7467 flatten(state, first, label2);
7468 flatten(state, first, test);
7469 flatten(state, first, branch(state, label1, test));
7470 flatten(state, first, end);
7474 static void return_statement(struct compile_state *state, struct triple *first)
7476 struct triple *jmp, *mv, *dest, *var, *val;
7478 eat(state, TOK_RETURN);
7480 #warning "FIXME implement a more general excess branch elimination"
7482 /* If we have a return value do some more work */
7483 if (peek(state) != TOK_SEMI) {
7484 val = read_expr(state, expr(state));
7486 eat(state, TOK_SEMI);
7488 /* See if this last statement in a function */
7489 last = ((peek(state) == TOK_RBRACE) &&
7490 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7492 /* Find the return variable */
7493 var = MISC(state->main_function, 0);
7494 /* Find the return destination */
7495 dest = RHS(state->main_function, 0)->prev;
7497 /* If needed generate a jump instruction */
7499 jmp = branch(state, dest, 0);
7501 /* If needed generate an assignment instruction */
7503 mv = write_expr(state, var, val);
7505 /* Now put the code together */
7507 flatten(state, first, mv);
7508 flatten(state, first, jmp);
7511 flatten(state, first, jmp);
7515 static void break_statement(struct compile_state *state, struct triple *first)
7517 struct triple *dest;
7518 eat(state, TOK_BREAK);
7519 eat(state, TOK_SEMI);
7520 if (!state->i_break->sym_ident) {
7521 error(state, 0, "break statement not within loop or switch");
7523 dest = state->i_break->sym_ident->def;
7524 flatten(state, first, branch(state, dest, 0));
7527 static void continue_statement(struct compile_state *state, struct triple *first)
7529 struct triple *dest;
7530 eat(state, TOK_CONTINUE);
7531 eat(state, TOK_SEMI);
7532 if (!state->i_continue->sym_ident) {
7533 error(state, 0, "continue statement outside of a loop");
7535 dest = state->i_continue->sym_ident->def;
7536 flatten(state, first, branch(state, dest, 0));
7539 static void goto_statement(struct compile_state *state, struct triple *first)
7542 eat(state, TOK_GOTO);
7543 eat(state, TOK_IDENT);
7544 eat(state, TOK_SEMI);
7545 error(state, 0, "goto is not implemeted");
7549 static void labeled_statement(struct compile_state *state, struct triple *first)
7552 eat(state, TOK_IDENT);
7553 eat(state, TOK_COLON);
7554 statement(state, first);
7555 error(state, 0, "labeled statements are not implemented");
7559 static void switch_statement(struct compile_state *state, struct triple *first)
7562 eat(state, TOK_SWITCH);
7563 eat(state, TOK_LPAREN);
7565 eat(state, TOK_RPAREN);
7566 statement(state, first);
7567 error(state, 0, "switch statements are not implemented");
7571 static void case_statement(struct compile_state *state, struct triple *first)
7574 eat(state, TOK_CASE);
7575 constant_expr(state);
7576 eat(state, TOK_COLON);
7577 statement(state, first);
7578 error(state, 0, "case statements are not implemented");
7582 static void default_statement(struct compile_state *state, struct triple *first)
7585 eat(state, TOK_DEFAULT);
7586 eat(state, TOK_COLON);
7587 statement(state, first);
7588 error(state, 0, "default statements are not implemented");
7592 static void asm_statement(struct compile_state *state, struct triple *first)
7594 struct asm_info *info;
7596 struct triple *constraint;
7597 struct triple *expr;
7598 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7599 struct triple *def, *asm_str;
7600 int out, in, clobbers, more, colons, i;
7602 eat(state, TOK_ASM);
7603 /* For now ignore the qualifiers */
7604 switch(peek(state)) {
7606 eat(state, TOK_CONST);
7609 eat(state, TOK_VOLATILE);
7612 eat(state, TOK_LPAREN);
7613 asm_str = string_constant(state);
7616 out = in = clobbers = 0;
7618 if ((colons == 0) && (peek(state) == TOK_COLON)) {
7619 eat(state, TOK_COLON);
7621 more = (peek(state) == TOK_LIT_STRING);
7624 struct triple *constraint;
7626 if (out > MAX_LHS) {
7627 error(state, 0, "Maximum output count exceeded.");
7629 constraint = string_constant(state);
7630 eat(state, TOK_LPAREN);
7631 var = conditional_expr(state);
7632 eat(state, TOK_RPAREN);
7635 out_param[out].constraint = constraint;
7636 out_param[out].expr = var;
7637 if (peek(state) == TOK_COMMA) {
7638 eat(state, TOK_COMMA);
7645 if ((colons == 1) && (peek(state) == TOK_COLON)) {
7646 eat(state, TOK_COLON);
7648 more = (peek(state) == TOK_LIT_STRING);
7651 struct triple *constraint;
7654 error(state, 0, "Maximum input count exceeded.");
7656 constraint = string_constant(state);
7657 eat(state, TOK_LPAREN);
7658 val = conditional_expr(state);
7659 eat(state, TOK_RPAREN);
7661 in_param[in].constraint = constraint;
7662 in_param[in].expr = val;
7663 if (peek(state) == TOK_COMMA) {
7664 eat(state, TOK_COMMA);
7672 if ((colons == 2) && (peek(state) == TOK_COLON)) {
7673 eat(state, TOK_COLON);
7675 more = (peek(state) == TOK_LIT_STRING);
7677 struct triple *clobber;
7679 if ((clobbers + out) > MAX_LHS) {
7680 error(state, 0, "Maximum clobber limit exceeded.");
7682 clobber = string_constant(state);
7683 eat(state, TOK_RPAREN);
7685 clob_param[clobbers].constraint = clobber;
7686 if (peek(state) == TOK_COMMA) {
7687 eat(state, TOK_COMMA);
7693 eat(state, TOK_RPAREN);
7694 eat(state, TOK_SEMI);
7697 info = xcmalloc(sizeof(*info), "asm_info");
7698 info->str = asm_str->u.blob;
7699 free_triple(state, asm_str);
7701 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
7702 def->u.ainfo = info;
7703 for(i = 0; i < in; i++) {
7704 struct triple *constraint;
7705 constraint = in_param[i].constraint;
7706 info->tmpl.rhs[i] = arch_reg_constraint(state,
7707 in_param[i].expr->type, constraint->u.blob);
7709 RHS(def, i) = read_expr(state,in_param[i].expr);
7710 free_triple(state, constraint);
7712 flatten(state, first, def);
7713 for(i = 0; i < out; i++) {
7714 struct triple *piece;
7715 struct triple *constraint;
7716 constraint = out_param[i].constraint;
7717 info->tmpl.lhs[i] = arch_reg_constraint(state,
7718 out_param[i].expr->type, constraint->u.blob);
7720 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
7722 LHS(def, i) = piece;
7723 flatten(state, first,
7724 write_expr(state, out_param[i].expr, piece));
7725 free_triple(state, constraint);
7727 for(; i - out < clobbers; i++) {
7728 struct triple *piece;
7729 struct triple *constraint;
7730 constraint = clob_param[i - out].constraint;
7731 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
7733 piece = triple(state, OP_PIECE, &void_type, def, 0);
7735 LHS(def, i) = piece;
7736 flatten(state, first, piece);
7737 free_triple(state, constraint);
7742 static int isdecl(int tok)
7765 case TOK_TYPE_NAME: /* typedef name */
7772 static void compound_statement(struct compile_state *state, struct triple *first)
7774 eat(state, TOK_LBRACE);
7777 /* statement-list opt */
7778 while (peek(state) != TOK_RBRACE) {
7779 statement(state, first);
7782 eat(state, TOK_RBRACE);
7785 static void statement(struct compile_state *state, struct triple *first)
7789 if (tok == TOK_LBRACE) {
7790 compound_statement(state, first);
7792 else if (tok == TOK_IF) {
7793 if_statement(state, first);
7795 else if (tok == TOK_FOR) {
7796 for_statement(state, first);
7798 else if (tok == TOK_WHILE) {
7799 while_statement(state, first);
7801 else if (tok == TOK_DO) {
7802 do_statement(state, first);
7804 else if (tok == TOK_RETURN) {
7805 return_statement(state, first);
7807 else if (tok == TOK_BREAK) {
7808 break_statement(state, first);
7810 else if (tok == TOK_CONTINUE) {
7811 continue_statement(state, first);
7813 else if (tok == TOK_GOTO) {
7814 goto_statement(state, first);
7816 else if (tok == TOK_SWITCH) {
7817 switch_statement(state, first);
7819 else if (tok == TOK_ASM) {
7820 asm_statement(state, first);
7822 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7823 labeled_statement(state, first);
7825 else if (tok == TOK_CASE) {
7826 case_statement(state, first);
7828 else if (tok == TOK_DEFAULT) {
7829 default_statement(state, first);
7831 else if (isdecl(tok)) {
7832 /* This handles C99 intermixing of statements and decls */
7836 expr_statement(state, first);
7840 static struct type *param_decl(struct compile_state *state)
7843 struct hash_entry *ident;
7844 /* Cheat so the declarator will know we are not global */
7847 type = decl_specifiers(state);
7848 type = declarator(state, type, &ident, 0);
7849 type->field_ident = ident;
7854 static struct type *param_type_list(struct compile_state *state, struct type *type)
7856 struct type *ftype, **next;
7857 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7858 next = &ftype->right;
7859 while(peek(state) == TOK_COMMA) {
7860 eat(state, TOK_COMMA);
7861 if (peek(state) == TOK_DOTS) {
7862 eat(state, TOK_DOTS);
7863 error(state, 0, "variadic functions not supported");
7866 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7867 next = &((*next)->right);
7874 static struct type *type_name(struct compile_state *state)
7877 type = specifier_qualifier_list(state);
7878 /* abstract-declarator (may consume no tokens) */
7879 type = declarator(state, type, 0, 0);
7883 static struct type *direct_declarator(
7884 struct compile_state *state, struct type *type,
7885 struct hash_entry **ident, int need_ident)
7890 arrays_complete(state, type);
7891 switch(peek(state)) {
7893 eat(state, TOK_IDENT);
7895 error(state, 0, "Unexpected identifier found");
7897 /* The name of what we are declaring */
7898 *ident = state->token[0].ident;
7901 eat(state, TOK_LPAREN);
7902 outer = declarator(state, type, ident, need_ident);
7903 eat(state, TOK_RPAREN);
7907 error(state, 0, "Identifier expected");
7913 arrays_complete(state, type);
7914 switch(peek(state)) {
7916 eat(state, TOK_LPAREN);
7917 type = param_type_list(state, type);
7918 eat(state, TOK_RPAREN);
7922 unsigned int qualifiers;
7923 struct triple *value;
7925 eat(state, TOK_LBRACKET);
7926 if (peek(state) != TOK_RBRACKET) {
7927 value = constant_expr(state);
7928 integral(state, value);
7930 eat(state, TOK_RBRACKET);
7932 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
7933 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
7935 type->elements = value->u.cval;
7936 free_triple(state, value);
7938 type->elements = ELEMENT_COUNT_UNSPECIFIED;
7950 arrays_complete(state, type);
7952 for(inner = outer; inner->left; inner = inner->left)
7960 static struct type *declarator(
7961 struct compile_state *state, struct type *type,
7962 struct hash_entry **ident, int need_ident)
7964 while(peek(state) == TOK_STAR) {
7965 eat(state, TOK_STAR);
7966 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
7968 type = direct_declarator(state, type, ident, need_ident);
7973 static struct type *typedef_name(
7974 struct compile_state *state, unsigned int specifiers)
7976 struct hash_entry *ident;
7978 eat(state, TOK_TYPE_NAME);
7979 ident = state->token[0].ident;
7980 type = ident->sym_ident->type;
7981 specifiers |= type->type & QUAL_MASK;
7982 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
7983 (type->type & (STOR_MASK | QUAL_MASK))) {
7984 type = clone_type(specifiers, type);
7989 static struct type *enum_specifier(
7990 struct compile_state *state, unsigned int specifiers)
7996 eat(state, TOK_ENUM);
7998 if (tok == TOK_IDENT) {
7999 eat(state, TOK_IDENT);
8001 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8002 eat(state, TOK_LBRACE);
8004 eat(state, TOK_IDENT);
8005 if (peek(state) == TOK_EQ) {
8007 constant_expr(state);
8009 if (peek(state) == TOK_COMMA) {
8010 eat(state, TOK_COMMA);
8012 } while(peek(state) != TOK_RBRACE);
8013 eat(state, TOK_RBRACE);
8020 static struct type *struct_declarator(
8021 struct compile_state *state, struct type *type, struct hash_entry **ident)
8024 #warning "struct_declarator is complicated because of bitfields, kill them?"
8026 if (tok != TOK_COLON) {
8027 type = declarator(state, type, ident, 1);
8029 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8030 eat(state, TOK_COLON);
8031 constant_expr(state);
8038 static struct type *struct_or_union_specifier(
8039 struct compile_state *state, unsigned int specifiers)
8041 struct type *struct_type;
8042 struct hash_entry *ident;
8043 unsigned int type_join;
8047 switch(peek(state)) {
8049 eat(state, TOK_STRUCT);
8050 type_join = TYPE_PRODUCT;
8053 eat(state, TOK_UNION);
8054 type_join = TYPE_OVERLAP;
8055 error(state, 0, "unions not yet supported\n");
8058 eat(state, TOK_STRUCT);
8059 type_join = TYPE_PRODUCT;
8063 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8065 ident = state->token[0].ident;
8067 if (!ident || (peek(state) == TOK_LBRACE)) {
8070 eat(state, TOK_LBRACE);
8072 struct type *base_type;
8075 base_type = specifier_qualifier_list(state);
8076 next = &struct_type;
8079 struct hash_entry *fident;
8081 type = declarator(state, base_type, &fident, 1);
8083 if (peek(state) == TOK_COMMA) {
8085 eat(state, TOK_COMMA);
8087 type = clone_type(0, type);
8088 type->field_ident = fident;
8090 *next = new_type(type_join, *next, type);
8091 next = &((*next)->right);
8096 eat(state, TOK_SEMI);
8097 } while(peek(state) != TOK_RBRACE);
8098 eat(state, TOK_RBRACE);
8099 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
8100 struct_type->type_ident = ident;
8101 struct_type->elements = elements;
8102 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8104 if (ident && ident->sym_struct) {
8105 struct_type = ident->sym_struct->type;
8107 else if (ident && !ident->sym_struct) {
8108 error(state, 0, "struct %s undeclared", ident->name);
8113 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8115 unsigned int specifiers;
8116 switch(peek(state)) {
8118 eat(state, TOK_AUTO);
8119 specifiers = STOR_AUTO;
8122 eat(state, TOK_REGISTER);
8123 specifiers = STOR_REGISTER;
8126 eat(state, TOK_STATIC);
8127 specifiers = STOR_STATIC;
8130 eat(state, TOK_EXTERN);
8131 specifiers = STOR_EXTERN;
8134 eat(state, TOK_TYPEDEF);
8135 specifiers = STOR_TYPEDEF;
8138 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8139 specifiers = STOR_STATIC;
8142 specifiers = STOR_AUTO;
8148 static unsigned int function_specifier_opt(struct compile_state *state)
8150 /* Ignore the inline keyword */
8151 unsigned int specifiers;
8153 switch(peek(state)) {
8155 eat(state, TOK_INLINE);
8156 specifiers = STOR_INLINE;
8161 static unsigned int type_qualifiers(struct compile_state *state)
8163 unsigned int specifiers;
8166 specifiers = QUAL_NONE;
8168 switch(peek(state)) {
8170 eat(state, TOK_CONST);
8171 specifiers = QUAL_CONST;
8174 eat(state, TOK_VOLATILE);
8175 specifiers = QUAL_VOLATILE;
8178 eat(state, TOK_RESTRICT);
8179 specifiers = QUAL_RESTRICT;
8189 static struct type *type_specifier(
8190 struct compile_state *state, unsigned int spec)
8194 switch(peek(state)) {
8196 eat(state, TOK_VOID);
8197 type = new_type(TYPE_VOID | spec, 0, 0);
8200 eat(state, TOK_CHAR);
8201 type = new_type(TYPE_CHAR | spec, 0, 0);
8204 eat(state, TOK_SHORT);
8205 if (peek(state) == TOK_INT) {
8206 eat(state, TOK_INT);
8208 type = new_type(TYPE_SHORT | spec, 0, 0);
8211 eat(state, TOK_INT);
8212 type = new_type(TYPE_INT | spec, 0, 0);
8215 eat(state, TOK_LONG);
8216 switch(peek(state)) {
8218 eat(state, TOK_LONG);
8219 error(state, 0, "long long not supported");
8222 eat(state, TOK_DOUBLE);
8223 error(state, 0, "long double not supported");
8226 eat(state, TOK_INT);
8227 type = new_type(TYPE_LONG | spec, 0, 0);
8230 type = new_type(TYPE_LONG | spec, 0, 0);
8235 eat(state, TOK_FLOAT);
8236 error(state, 0, "type float not supported");
8239 eat(state, TOK_DOUBLE);
8240 error(state, 0, "type double not supported");
8243 eat(state, TOK_SIGNED);
8244 switch(peek(state)) {
8246 eat(state, TOK_LONG);
8247 switch(peek(state)) {
8249 eat(state, TOK_LONG);
8250 error(state, 0, "type long long not supported");
8253 eat(state, TOK_INT);
8254 type = new_type(TYPE_LONG | spec, 0, 0);
8257 type = new_type(TYPE_LONG | spec, 0, 0);
8262 eat(state, TOK_INT);
8263 type = new_type(TYPE_INT | spec, 0, 0);
8266 eat(state, TOK_SHORT);
8267 type = new_type(TYPE_SHORT | spec, 0, 0);
8270 eat(state, TOK_CHAR);
8271 type = new_type(TYPE_CHAR | spec, 0, 0);
8274 type = new_type(TYPE_INT | spec, 0, 0);
8279 eat(state, TOK_UNSIGNED);
8280 switch(peek(state)) {
8282 eat(state, TOK_LONG);
8283 switch(peek(state)) {
8285 eat(state, TOK_LONG);
8286 error(state, 0, "unsigned long long not supported");
8289 eat(state, TOK_INT);
8290 type = new_type(TYPE_ULONG | spec, 0, 0);
8293 type = new_type(TYPE_ULONG | spec, 0, 0);
8298 eat(state, TOK_INT);
8299 type = new_type(TYPE_UINT | spec, 0, 0);
8302 eat(state, TOK_SHORT);
8303 type = new_type(TYPE_USHORT | spec, 0, 0);
8306 eat(state, TOK_CHAR);
8307 type = new_type(TYPE_UCHAR | spec, 0, 0);
8310 type = new_type(TYPE_UINT | spec, 0, 0);
8314 /* struct or union specifier */
8317 type = struct_or_union_specifier(state, spec);
8319 /* enum-spefifier */
8321 type = enum_specifier(state, spec);
8325 type = typedef_name(state, spec);
8328 error(state, 0, "bad type specifier %s",
8329 tokens[peek(state)]);
8335 static int istype(int tok)
8361 static struct type *specifier_qualifier_list(struct compile_state *state)
8364 unsigned int specifiers = 0;
8366 /* type qualifiers */
8367 specifiers |= type_qualifiers(state);
8369 /* type specifier */
8370 type = type_specifier(state, specifiers);
8375 static int isdecl_specifier(int tok)
8378 /* storage class specifier */
8384 /* type qualifier */
8388 /* type specifiers */
8398 /* struct or union specifier */
8401 /* enum-spefifier */
8405 /* function specifiers */
8413 static struct type *decl_specifiers(struct compile_state *state)
8416 unsigned int specifiers;
8417 /* I am overly restrictive in the arragement of specifiers supported.
8418 * C is overly flexible in this department it makes interpreting
8419 * the parse tree difficult.
8423 /* storage class specifier */
8424 specifiers |= storage_class_specifier_opt(state);
8426 /* function-specifier */
8427 specifiers |= function_specifier_opt(state);
8429 /* type qualifier */
8430 specifiers |= type_qualifiers(state);
8432 /* type specifier */
8433 type = type_specifier(state, specifiers);
8437 static unsigned designator(struct compile_state *state)
8443 switch(peek(state)) {
8446 struct triple *value;
8447 eat(state, TOK_LBRACKET);
8448 value = constant_expr(state);
8449 eat(state, TOK_RBRACKET);
8450 index = value->u.cval;
8454 eat(state, TOK_DOT);
8455 eat(state, TOK_IDENT);
8456 error(state, 0, "Struct Designators not currently supported");
8459 error(state, 0, "Invalid designator");
8462 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8467 static struct triple *initializer(
8468 struct compile_state *state, struct type *type)
8470 struct triple *result;
8471 if (peek(state) != TOK_LBRACE) {
8472 result = assignment_expr(state);
8476 unsigned index, max_index;
8478 max_index = index = 0;
8479 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8480 max_index = type->elements;
8481 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8485 error(state, 0, "Struct initializers not currently supported");
8487 buf = xcmalloc(size_of(state, type), "initializer");
8488 eat(state, TOK_LBRACE);
8490 struct triple *value;
8491 struct type *value_type;
8496 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8497 index = designator(state);
8499 if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8500 (index > max_index)) {
8501 error(state, 0, "element beyond bounds");
8504 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8505 value_type = type->left;
8507 value = eval_const_expr(state, initializer(state, value_type));
8508 value_size = size_of(state, value_type);
8509 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8510 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8511 (type->elements <= index)) {
8515 old_size = size_of(state, type);
8516 type->elements = index + 1;
8517 buf = xmalloc(size_of(state, type), "initializer");
8518 memcpy(buf, old_buf, old_size);
8521 if (value->op == OP_BLOBCONST) {
8522 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8524 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8525 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8527 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8528 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8530 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8531 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8534 fprintf(stderr, "%d %d\n",
8535 value->op, value_size);
8536 internal_error(state, 0, "unhandled constant initializer");
8538 if (peek(state) == TOK_COMMA) {
8539 eat(state, TOK_COMMA);
8543 } while(comma && (peek(state) != TOK_RBRACE));
8544 eat(state, TOK_RBRACE);
8545 result = triple(state, OP_BLOBCONST, type, 0, 0);
8546 result->u.blob = buf;
8551 static struct triple *function_definition(
8552 struct compile_state *state, struct type *type)
8554 struct triple *def, *tmp, *first, *end;
8555 struct hash_entry *ident;
8558 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8559 error(state, 0, "Invalid function header");
8562 /* Verify the function type */
8563 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8564 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8565 (type->right->field_ident == 0)) {
8566 error(state, 0, "Invalid function parameters");
8568 param = type->right;
8570 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8572 if (!param->left->field_ident) {
8573 error(state, 0, "No identifier for parameter %d\n", i);
8575 param = param->right;
8578 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8579 error(state, 0, "No identifier for paramter %d\n", i);
8582 /* Get a list of statements for this function. */
8583 def = triple(state, OP_LIST, type, 0, 0);
8585 /* Start a new scope for the passed parameters */
8588 /* Put a label at the very start of a function */
8589 first = label(state);
8590 RHS(def, 0) = first;
8592 /* Put a label at the very end of a function */
8594 flatten(state, first, end);
8596 /* Walk through the parameters and create symbol table entries
8599 param = type->right;
8600 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8601 ident = param->left->field_ident;
8602 tmp = variable(state, param->left);
8603 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8604 flatten(state, end, tmp);
8605 param = param->right;
8607 if ((param->type & TYPE_MASK) != TYPE_VOID) {
8608 /* And don't forget the last parameter */
8609 ident = param->field_ident;
8610 tmp = variable(state, param);
8611 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8612 flatten(state, end, tmp);
8614 /* Add a variable for the return value */
8616 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8617 /* Remove all type qualifiers from the return type */
8618 tmp = variable(state, clone_type(0, type->left));
8619 flatten(state, end, tmp);
8620 /* Remember where the return value is */
8624 /* Remember which function I am compiling.
8625 * Also assume the last defined function is the main function.
8627 state->main_function = def;
8629 /* Now get the actual function definition */
8630 compound_statement(state, end);
8632 /* Remove the parameter scope */
8635 fprintf(stdout, "\n");
8636 loc(stdout, state, 0);
8637 fprintf(stdout, "\n__________ function_definition _________\n");
8638 print_triple(state, def);
8639 fprintf(stdout, "__________ function_definition _________ done\n\n");
8645 static struct triple *do_decl(struct compile_state *state,
8646 struct type *type, struct hash_entry *ident)
8650 /* Clean up the storage types used */
8651 switch (type->type & STOR_MASK) {
8654 /* These are the good types I am aiming for */
8657 type->type &= ~STOR_MASK;
8658 type->type |= STOR_AUTO;
8661 type->type &= ~STOR_MASK;
8662 type->type |= STOR_STATIC;
8666 error(state, 0, "typedef without name");
8668 symbol(state, ident, &ident->sym_ident, 0, type);
8669 ident->tok = TOK_TYPE_NAME;
8673 internal_error(state, 0, "Undefined storage class");
8675 if (((type->type & STOR_MASK) == STOR_STATIC) &&
8676 ((type->type & QUAL_CONST) == 0)) {
8677 error(state, 0, "non const static variables not supported");
8680 def = variable(state, type);
8681 symbol(state, ident, &ident->sym_ident, def, type);
8686 static void decl(struct compile_state *state, struct triple *first)
8688 struct type *base_type, *type;
8689 struct hash_entry *ident;
8692 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8693 base_type = decl_specifiers(state);
8695 type = declarator(state, base_type, &ident, 0);
8696 if (global && ident && (peek(state) == TOK_LBRACE)) {
8698 def = function_definition(state, type);
8699 symbol(state, ident, &ident->sym_ident, def, type);
8703 flatten(state, first, do_decl(state, type, ident));
8704 /* type or variable definition */
8707 if (peek(state) == TOK_EQ) {
8709 error(state, 0, "cannot assign to a type");
8712 flatten(state, first,
8714 ident->sym_ident->def,
8715 initializer(state, type)));
8717 arrays_complete(state, type);
8718 if (peek(state) == TOK_COMMA) {
8719 eat(state, TOK_COMMA);
8721 type = declarator(state, base_type, &ident, 0);
8722 flatten(state, first, do_decl(state, type, ident));
8726 eat(state, TOK_SEMI);
8730 static void decls(struct compile_state *state)
8732 struct triple *list;
8734 list = label(state);
8737 if (tok == TOK_EOF) {
8740 if (tok == TOK_SPACE) {
8741 eat(state, TOK_SPACE);
8744 if (list->next != list) {
8745 error(state, 0, "global variables not supported");
8751 * Data structurs for optimation.
8754 static void do_use_block(
8755 struct block *used, struct block_set **head, struct block *user,
8758 struct block_set **ptr, *new;
8765 if ((*ptr)->member == user) {
8768 ptr = &(*ptr)->next;
8770 new = xcmalloc(sizeof(*new), "block_set");
8781 static void do_unuse_block(
8782 struct block *used, struct block_set **head, struct block *unuser)
8784 struct block_set *use, **ptr;
8788 if (use->member == unuser) {
8790 memset(use, -1, sizeof(*use));
8799 static void use_block(struct block *used, struct block *user)
8801 /* Append new to the head of the list, print_block
8804 do_use_block(used, &used->use, user, 1);
8807 static void unuse_block(struct block *used, struct block *unuser)
8809 do_unuse_block(used, &used->use, unuser);
8813 static void idom_block(struct block *idom, struct block *user)
8815 do_use_block(idom, &idom->idominates, user, 0);
8818 static void unidom_block(struct block *idom, struct block *unuser)
8820 do_unuse_block(idom, &idom->idominates, unuser);
8823 static void domf_block(struct block *block, struct block *domf)
8825 do_use_block(block, &block->domfrontier, domf, 0);
8828 static void undomf_block(struct block *block, struct block *undomf)
8830 do_unuse_block(block, &block->domfrontier, undomf);
8833 static void ipdom_block(struct block *ipdom, struct block *user)
8835 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8838 static void unipdom_block(struct block *ipdom, struct block *unuser)
8840 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8843 static void ipdomf_block(struct block *block, struct block *ipdomf)
8845 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8848 static void unipdomf_block(struct block *block, struct block *unipdomf)
8850 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8855 static int do_walk_triple(struct compile_state *state,
8856 struct triple *ptr, int depth,
8857 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8860 result = cb(state, ptr, depth);
8861 if ((result == 0) && (ptr->op == OP_LIST)) {
8862 struct triple *list;
8866 result = do_walk_triple(state, ptr, depth + 1, cb);
8867 if (ptr->next->prev != ptr) {
8868 internal_error(state, ptr->next, "bad prev");
8872 } while((result == 0) && (ptr != RHS(list, 0)));
8877 static int walk_triple(
8878 struct compile_state *state,
8880 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8882 return do_walk_triple(state, ptr, 0, cb);
8885 static void do_print_prefix(int depth)
8888 for(i = 0; i < depth; i++) {
8893 #define PRINT_LIST 1
8894 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8898 if (op == OP_LIST) {
8903 if ((op == OP_LABEL) && (ins->use)) {
8904 printf("\n%p:\n", ins);
8906 do_print_prefix(depth);
8907 display_triple(stdout, ins);
8909 if ((ins->op == OP_BRANCH) && ins->use) {
8910 internal_error(state, ins, "branch used?");
8914 struct triple_set *user;
8915 for(user = ins->use; user; user = user->next) {
8916 printf("use: %p\n", user->member);
8920 if (triple_is_branch(state, ins)) {
8926 static void print_triple(struct compile_state *state, struct triple *ins)
8928 walk_triple(state, ins, do_print_triple);
8931 static void print_triples(struct compile_state *state)
8933 print_triple(state, state->main_function);
8937 struct block *block;
8939 static void find_cf_blocks(struct cf_block *cf, struct block *block)
8941 if (!block || (cf[block->vertex].block == block)) {
8944 cf[block->vertex].block = block;
8945 find_cf_blocks(cf, block->left);
8946 find_cf_blocks(cf, block->right);
8949 static void print_control_flow(struct compile_state *state)
8951 struct cf_block *cf;
8953 printf("\ncontrol flow\n");
8954 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
8955 find_cf_blocks(cf, state->first_block);
8957 for(i = 1; i <= state->last_vertex; i++) {
8958 struct block *block;
8959 block = cf[i].block;
8962 printf("(%p) %d:", block, block->vertex);
8964 printf(" %d", block->left->vertex);
8966 if (block->right && (block->right != block->left)) {
8967 printf(" %d", block->right->vertex);
8976 static struct block *basic_block(struct compile_state *state,
8977 struct triple *first)
8979 struct block *block;
8982 if (first->op != OP_LABEL) {
8983 internal_error(state, 0, "block does not start with a label");
8985 /* See if this basic block has already been setup */
8986 if (first->u.block != 0) {
8987 return first->u.block;
8989 /* Allocate another basic block structure */
8990 state->last_vertex += 1;
8991 block = xcmalloc(sizeof(*block), "block");
8992 block->first = block->last = first;
8993 block->vertex = state->last_vertex;
8996 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9000 /* If ptr->u is not used remember where the baic block is */
9001 if (triple_stores_block(state, ptr)) {
9002 ptr->u.block = block;
9004 if (ptr->op == OP_BRANCH) {
9008 } while (ptr != RHS(state->main_function, 0));
9009 if (ptr == RHS(state->main_function, 0))
9012 if (op == OP_LABEL) {
9013 block->left = basic_block(state, ptr);
9015 use_block(block->left, block);
9017 else if (op == OP_BRANCH) {
9019 /* Trace the branch target */
9020 block->right = basic_block(state, TARG(ptr, 0));
9021 use_block(block->right, block);
9022 /* If there is a test trace the branch as well */
9023 if (TRIPLE_RHS(ptr->sizes)) {
9024 block->left = basic_block(state, ptr->next);
9025 use_block(block->left, block);
9029 internal_error(state, 0, "Bad basic block split");
9035 static void walk_blocks(struct compile_state *state,
9036 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9039 struct triple *ptr, *first;
9040 struct block *last_block;
9042 first = RHS(state->main_function, 0);
9045 struct block *block;
9046 if (ptr->op == OP_LABEL) {
9047 block = ptr->u.block;
9048 if (block && (block != last_block)) {
9049 cb(state, block, arg);
9054 } while(ptr != first);
9057 static void print_block(
9058 struct compile_state *state, struct block *block, void *arg)
9063 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
9067 block->left && block->left->use?block->left->use->member : 0,
9069 block->right && block->right->use?block->right->use->member : 0);
9070 if (block->first->op == OP_LABEL) {
9071 fprintf(fp, "%p:\n", block->first);
9073 for(ptr = block->first; ; ptr = ptr->next) {
9074 struct triple_set *user;
9077 if (triple_stores_block(state, ptr)) {
9078 if (ptr->u.block != block) {
9079 internal_error(state, ptr,
9080 "Wrong block pointer: %p\n",
9084 if (op == OP_ADECL) {
9085 for(user = ptr->use; user; user = user->next) {
9086 if (!user->member->u.block) {
9087 internal_error(state, user->member,
9088 "Use %p not in a block?\n",
9093 display_triple(fp, ptr);
9096 for(user = ptr->use; user; user = user->next) {
9097 fprintf(fp, "use: %p\n", user->member);
9101 /* Sanity checks... */
9102 valid_ins(state, ptr);
9103 for(user = ptr->use; user; user = user->next) {
9106 valid_ins(state, use);
9107 if (triple_stores_block(state, user->member) &&
9108 !user->member->u.block) {
9109 internal_error(state, user->member,
9110 "Use %p not in a block?",
9115 if (ptr == block->last)
9122 static void print_blocks(struct compile_state *state, FILE *fp)
9124 fprintf(fp, "--------------- blocks ---------------\n");
9125 walk_blocks(state, print_block, fp);
9128 static void prune_nonblock_triples(struct compile_state *state)
9130 struct block *block;
9131 struct triple *first, *ins, *next;
9132 /* Delete the triples not in a basic block */
9133 first = RHS(state->main_function, 0);
9138 if (ins->op == OP_LABEL) {
9139 block = ins->u.block;
9142 release_triple(state, ins);
9145 } while(ins != first);
9148 static void setup_basic_blocks(struct compile_state *state)
9150 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9151 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9152 internal_error(state, 0, "ins will not store block?");
9154 /* Find the basic blocks */
9155 state->last_vertex = 0;
9156 state->first_block = basic_block(state, RHS(state->main_function,0));
9157 /* Delete the triples not in a basic block */
9158 prune_nonblock_triples(state);
9159 /* Find the last basic block */
9160 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9161 if (!state->last_block) {
9162 internal_error(state, 0, "end not used?");
9164 /* Insert an extra unused edge from start to the end
9165 * This helps with reverse control flow calculations.
9167 use_block(state->first_block, state->last_block);
9168 /* If we are debugging print what I have just done */
9169 if (state->debug & DEBUG_BASIC_BLOCKS) {
9170 print_blocks(state, stdout);
9171 print_control_flow(state);
9175 static void free_basic_block(struct compile_state *state, struct block *block)
9177 struct block_set *entry, *next;
9178 struct block *child;
9182 if (block->vertex == -1) {
9187 unuse_block(block->left, block);
9190 unuse_block(block->right, block);
9193 unidom_block(block->idom, block);
9197 unipdom_block(block->ipdom, block);
9200 for(entry = block->use; entry; entry = next) {
9202 child = entry->member;
9203 unuse_block(block, child);
9204 if (child->left == block) {
9207 if (child->right == block) {
9211 for(entry = block->idominates; entry; entry = next) {
9213 child = entry->member;
9214 unidom_block(block, child);
9217 for(entry = block->domfrontier; entry; entry = next) {
9219 child = entry->member;
9220 undomf_block(block, child);
9222 for(entry = block->ipdominates; entry; entry = next) {
9224 child = entry->member;
9225 unipdom_block(block, child);
9228 for(entry = block->ipdomfrontier; entry; entry = next) {
9230 child = entry->member;
9231 unipdomf_block(block, child);
9233 if (block->users != 0) {
9234 internal_error(state, 0, "block still has users");
9236 free_basic_block(state, block->left);
9238 free_basic_block(state, block->right);
9240 memset(block, -1, sizeof(*block));
9244 static void free_basic_blocks(struct compile_state *state)
9246 struct triple *first, *ins;
9247 free_basic_block(state, state->first_block);
9248 state->last_vertex = 0;
9249 state->first_block = state->last_block = 0;
9250 first = RHS(state->main_function, 0);
9253 if (triple_stores_block(state, ins)) {
9257 } while(ins != first);
9262 struct block *block;
9263 struct sdom_block *sdominates;
9264 struct sdom_block *sdom_next;
9265 struct sdom_block *sdom;
9266 struct sdom_block *label;
9267 struct sdom_block *parent;
9268 struct sdom_block *ancestor;
9273 static void unsdom_block(struct sdom_block *block)
9275 struct sdom_block **ptr;
9276 if (!block->sdom_next) {
9279 ptr = &block->sdom->sdominates;
9281 if ((*ptr) == block) {
9282 *ptr = block->sdom_next;
9285 ptr = &(*ptr)->sdom_next;
9289 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9291 unsdom_block(block);
9293 block->sdom_next = sdom->sdominates;
9294 sdom->sdominates = block;
9299 static int initialize_sdblock(struct sdom_block *sd,
9300 struct block *parent, struct block *block, int vertex)
9302 if (!block || (sd[block->vertex].block == block)) {
9306 /* Renumber the blocks in a convinient fashion */
9307 block->vertex = vertex;
9308 sd[vertex].block = block;
9309 sd[vertex].sdom = &sd[vertex];
9310 sd[vertex].label = &sd[vertex];
9311 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9312 sd[vertex].ancestor = 0;
9313 sd[vertex].vertex = vertex;
9314 vertex = initialize_sdblock(sd, block, block->left, vertex);
9315 vertex = initialize_sdblock(sd, block, block->right, vertex);
9319 static int initialize_sdpblock(struct sdom_block *sd,
9320 struct block *parent, struct block *block, int vertex)
9322 struct block_set *user;
9323 if (!block || (sd[block->vertex].block == block)) {
9327 /* Renumber the blocks in a convinient fashion */
9328 block->vertex = vertex;
9329 sd[vertex].block = block;
9330 sd[vertex].sdom = &sd[vertex];
9331 sd[vertex].label = &sd[vertex];
9332 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9333 sd[vertex].ancestor = 0;
9334 sd[vertex].vertex = vertex;
9335 for(user = block->use; user; user = user->next) {
9336 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9341 static void compress_ancestors(struct sdom_block *v)
9343 /* This procedure assumes ancestor(v) != 0 */
9344 /* if (ancestor(ancestor(v)) != 0) {
9345 * compress(ancestor(ancestor(v)));
9346 * if (semi(label(ancestor(v))) < semi(label(v))) {
9347 * label(v) = label(ancestor(v));
9349 * ancestor(v) = ancestor(ancestor(v));
9355 if (v->ancestor->ancestor) {
9356 compress_ancestors(v->ancestor->ancestor);
9357 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9358 v->label = v->ancestor->label;
9360 v->ancestor = v->ancestor->ancestor;
9364 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9368 * for each v <= pred(w) {
9370 * if (semi[u] < semi[w] {
9371 * semi[w] = semi[u];
9374 * add w to bucket(vertex(semi[w]));
9375 * LINK(parent(w), w);
9378 * for each v <= bucket(parent(w)) {
9379 * delete v from bucket(parent(w));
9381 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9384 for(i = state->last_vertex; i >= 2; i--) {
9385 struct sdom_block *v, *parent, *next;
9386 struct block_set *user;
9387 struct block *block;
9388 block = sd[i].block;
9389 parent = sd[i].parent;
9391 for(user = block->use; user; user = user->next) {
9392 struct sdom_block *v, *u;
9393 v = &sd[user->member->vertex];
9394 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9395 if (u->sdom->vertex < sd[i].sdom->vertex) {
9396 sd[i].sdom = u->sdom;
9399 sdom_block(sd[i].sdom, &sd[i]);
9400 sd[i].ancestor = parent;
9402 for(v = parent->sdominates; v; v = next) {
9403 struct sdom_block *u;
9404 next = v->sdom_next;
9406 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9407 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9408 u->block : parent->block;
9413 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9417 * for each v <= pred(w) {
9419 * if (semi[u] < semi[w] {
9420 * semi[w] = semi[u];
9423 * add w to bucket(vertex(semi[w]));
9424 * LINK(parent(w), w);
9427 * for each v <= bucket(parent(w)) {
9428 * delete v from bucket(parent(w));
9430 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9433 for(i = state->last_vertex; i >= 2; i--) {
9434 struct sdom_block *u, *v, *parent, *next;
9435 struct block *block;
9436 block = sd[i].block;
9437 parent = sd[i].parent;
9440 v = &sd[block->left->vertex];
9441 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9442 if (u->sdom->vertex < sd[i].sdom->vertex) {
9443 sd[i].sdom = u->sdom;
9446 if (block->right && (block->right != block->left)) {
9447 v = &sd[block->right->vertex];
9448 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9449 if (u->sdom->vertex < sd[i].sdom->vertex) {
9450 sd[i].sdom = u->sdom;
9453 sdom_block(sd[i].sdom, &sd[i]);
9454 sd[i].ancestor = parent;
9456 for(v = parent->sdominates; v; v = next) {
9457 struct sdom_block *u;
9458 next = v->sdom_next;
9460 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9461 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9462 u->block : parent->block;
9467 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9470 for(i = 2; i <= state->last_vertex; i++) {
9471 struct block *block;
9472 block = sd[i].block;
9473 if (block->idom->vertex != sd[i].sdom->vertex) {
9474 block->idom = block->idom->idom;
9476 idom_block(block->idom, block);
9478 sd[1].block->idom = 0;
9481 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9484 for(i = 2; i <= state->last_vertex; i++) {
9485 struct block *block;
9486 block = sd[i].block;
9487 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9488 block->ipdom = block->ipdom->ipdom;
9490 ipdom_block(block->ipdom, block);
9492 sd[1].block->ipdom = 0;
9496 * Every vertex of a flowgraph G = (V, E, r) except r has
9497 * a unique immediate dominator.
9498 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9499 * rooted at r, called the dominator tree of G, such that
9500 * v dominates w if and only if v is a proper ancestor of w in
9501 * the dominator tree.
9504 * If v and w are vertices of G such that v <= w,
9505 * than any path from v to w must contain a common ancestor
9508 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9509 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9510 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9512 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9513 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9516 * Let w != r and let u be a vertex for which sdom(u) is
9517 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9518 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9520 /* Lemma 5: Let vertices v,w satisfy v -> w.
9521 * Then v -> idom(w) or idom(w) -> idom(v)
9524 static void find_immediate_dominators(struct compile_state *state)
9526 struct sdom_block *sd;
9527 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9528 * vi > w for (1 <= i <= k - 1}
9531 * For any vertex w != r.
9533 * {v|(v,w) <= E and v < w } U
9534 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9537 * Let w != r and let u be a vertex for which sdom(u) is
9538 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9540 * { sdom(w) if sdom(w) = sdom(u),
9542 * { idom(u) otherwise
9544 /* The algorithm consists of the following 4 steps.
9545 * Step 1. Carry out a depth-first search of the problem graph.
9546 * Number the vertices from 1 to N as they are reached during
9547 * the search. Initialize the variables used in succeeding steps.
9548 * Step 2. Compute the semidominators of all vertices by applying
9549 * theorem 4. Carry out the computation vertex by vertex in
9550 * decreasing order by number.
9551 * Step 3. Implicitly define the immediate dominator of each vertex
9552 * by applying Corollary 1.
9553 * Step 4. Explicitly define the immediate dominator of each vertex,
9554 * carrying out the computation vertex by vertex in increasing order
9557 /* Step 1 initialize the basic block information */
9558 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9559 initialize_sdblock(sd, 0, state->first_block, 0);
9565 /* Step 2 compute the semidominators */
9566 /* Step 3 implicitly define the immediate dominator of each vertex */
9567 compute_sdom(state, sd);
9568 /* Step 4 explicitly define the immediate dominator of each vertex */
9569 compute_idom(state, sd);
9573 static void find_post_dominators(struct compile_state *state)
9575 struct sdom_block *sd;
9576 /* Step 1 initialize the basic block information */
9577 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9579 initialize_sdpblock(sd, 0, state->last_block, 0);
9581 /* Step 2 compute the semidominators */
9582 /* Step 3 implicitly define the immediate dominator of each vertex */
9583 compute_spdom(state, sd);
9584 /* Step 4 explicitly define the immediate dominator of each vertex */
9585 compute_ipdom(state, sd);
9591 static void find_block_domf(struct compile_state *state, struct block *block)
9593 struct block *child;
9594 struct block_set *user;
9595 if (block->domfrontier != 0) {
9596 internal_error(state, block->first, "domfrontier present?");
9598 for(user = block->idominates; user; user = user->next) {
9599 child = user->member;
9600 if (child->idom != block) {
9601 internal_error(state, block->first, "bad idom");
9603 find_block_domf(state, child);
9605 if (block->left && block->left->idom != block) {
9606 domf_block(block, block->left);
9608 if (block->right && block->right->idom != block) {
9609 domf_block(block, block->right);
9611 for(user = block->idominates; user; user = user->next) {
9612 struct block_set *frontier;
9613 child = user->member;
9614 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9615 if (frontier->member->idom != block) {
9616 domf_block(block, frontier->member);
9622 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9624 struct block *child;
9625 struct block_set *user;
9626 if (block->ipdomfrontier != 0) {
9627 internal_error(state, block->first, "ipdomfrontier present?");
9629 for(user = block->ipdominates; user; user = user->next) {
9630 child = user->member;
9631 if (child->ipdom != block) {
9632 internal_error(state, block->first, "bad ipdom");
9634 find_block_ipdomf(state, child);
9636 if (block->left && block->left->ipdom != block) {
9637 ipdomf_block(block, block->left);
9639 if (block->right && block->right->ipdom != block) {
9640 ipdomf_block(block, block->right);
9642 for(user = block->idominates; user; user = user->next) {
9643 struct block_set *frontier;
9644 child = user->member;
9645 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9646 if (frontier->member->ipdom != block) {
9647 ipdomf_block(block, frontier->member);
9653 static void print_dominated(
9654 struct compile_state *state, struct block *block, void *arg)
9656 struct block_set *user;
9659 fprintf(fp, "%d:", block->vertex);
9660 for(user = block->idominates; user; user = user->next) {
9661 fprintf(fp, " %d", user->member->vertex);
9662 if (user->member->idom != block) {
9663 internal_error(state, user->member->first, "bad idom");
9669 static void print_dominators(struct compile_state *state, FILE *fp)
9671 fprintf(fp, "\ndominates\n");
9672 walk_blocks(state, print_dominated, fp);
9676 static int print_frontiers(
9677 struct compile_state *state, struct block *block, int vertex)
9679 struct block_set *user;
9681 if (!block || (block->vertex != vertex + 1)) {
9686 printf("%d:", block->vertex);
9687 for(user = block->domfrontier; user; user = user->next) {
9688 printf(" %d", user->member->vertex);
9692 vertex = print_frontiers(state, block->left, vertex);
9693 vertex = print_frontiers(state, block->right, vertex);
9696 static void print_dominance_frontiers(struct compile_state *state)
9698 printf("\ndominance frontiers\n");
9699 print_frontiers(state, state->first_block, 0);
9703 static void analyze_idominators(struct compile_state *state)
9705 /* Find the immediate dominators */
9706 find_immediate_dominators(state);
9707 /* Find the dominance frontiers */
9708 find_block_domf(state, state->first_block);
9709 /* If debuging print the print what I have just found */
9710 if (state->debug & DEBUG_FDOMINATORS) {
9711 print_dominators(state, stdout);
9712 print_dominance_frontiers(state);
9713 print_control_flow(state);
9719 static void print_ipdominated(
9720 struct compile_state *state, struct block *block, void *arg)
9722 struct block_set *user;
9725 fprintf(fp, "%d:", block->vertex);
9726 for(user = block->ipdominates; user; user = user->next) {
9727 fprintf(fp, " %d", user->member->vertex);
9728 if (user->member->ipdom != block) {
9729 internal_error(state, user->member->first, "bad ipdom");
9735 static void print_ipdominators(struct compile_state *state, FILE *fp)
9737 fprintf(fp, "\nipdominates\n");
9738 walk_blocks(state, print_ipdominated, fp);
9741 static int print_pfrontiers(
9742 struct compile_state *state, struct block *block, int vertex)
9744 struct block_set *user;
9746 if (!block || (block->vertex != vertex + 1)) {
9751 printf("%d:", block->vertex);
9752 for(user = block->ipdomfrontier; user; user = user->next) {
9753 printf(" %d", user->member->vertex);
9756 for(user = block->use; user; user = user->next) {
9757 vertex = print_pfrontiers(state, user->member, vertex);
9761 static void print_ipdominance_frontiers(struct compile_state *state)
9763 printf("\nipdominance frontiers\n");
9764 print_pfrontiers(state, state->last_block, 0);
9768 static void analyze_ipdominators(struct compile_state *state)
9770 /* Find the post dominators */
9771 find_post_dominators(state);
9772 /* Find the control dependencies (post dominance frontiers) */
9773 find_block_ipdomf(state, state->last_block);
9774 /* If debuging print the print what I have just found */
9775 if (state->debug & DEBUG_RDOMINATORS) {
9776 print_ipdominators(state, stdout);
9777 print_ipdominance_frontiers(state);
9778 print_control_flow(state);
9782 static int bdominates(struct compile_state *state,
9783 struct block *dom, struct block *sub)
9785 while(sub && (sub != dom)) {
9791 static int tdominates(struct compile_state *state,
9792 struct triple *dom, struct triple *sub)
9794 struct block *bdom, *bsub;
9796 bdom = block_of_triple(state, dom);
9797 bsub = block_of_triple(state, sub);
9799 result = bdominates(state, bdom, bsub);
9804 while((ins != bsub->first) && (ins != dom)) {
9807 result = (ins == dom);
9812 static void insert_phi_operations(struct compile_state *state)
9815 struct triple *first;
9816 int *has_already, *work;
9817 struct block *work_list, **work_list_tail;
9821 size = sizeof(int) * (state->last_vertex + 1);
9822 has_already = xcmalloc(size, "has_already");
9823 work = xcmalloc(size, "work");
9826 first = RHS(state->main_function, 0);
9827 for(var = first->next; var != first ; var = var->next) {
9828 struct block *block;
9829 struct triple_set *user;
9830 if ((var->op != OP_ADECL) || !var->use) {
9835 work_list_tail = &work_list;
9836 for(user = var->use; user; user = user->next) {
9837 if (user->member->op == OP_READ) {
9840 if (user->member->op != OP_WRITE) {
9841 internal_error(state, user->member,
9842 "bad variable access");
9844 block = user->member->u.block;
9846 warning(state, user->member, "dead code");
9848 if (work[block->vertex] >= iter) {
9851 work[block->vertex] = iter;
9852 *work_list_tail = block;
9853 block->work_next = 0;
9854 work_list_tail = &block->work_next;
9856 for(block = work_list; block; block = block->work_next) {
9857 struct block_set *df;
9858 for(df = block->domfrontier; df; df = df->next) {
9860 struct block *front;
9864 if (has_already[front->vertex] >= iter) {
9867 /* Count how many edges flow into this block */
9868 in_edges = front->users;
9869 /* Insert a phi function for this variable */
9871 state, OP_PHI, var->type, -1, in_edges,
9872 front->first->filename,
9875 phi->u.block = front;
9877 use_triple(var, phi);
9878 /* Insert the phi functions immediately after the label */
9879 insert_triple(state, front->first->next, phi);
9880 if (front->first == front->last) {
9881 front->last = front->first->next;
9883 has_already[front->vertex] = iter;
9885 /* If necessary plan to visit the basic block */
9886 if (work[front->vertex] >= iter) {
9889 work[front->vertex] = iter;
9890 *work_list_tail = front;
9891 front->work_next = 0;
9892 work_list_tail = &front->work_next;
9904 static void fixup_block_phi_variables(
9905 struct compile_state *state, struct block *parent, struct block *block)
9907 struct block_set *set;
9910 if (!parent || !block)
9912 /* Find the edge I am coming in on */
9914 for(set = block->use; set; set = set->next, edge++) {
9915 if (set->member == parent) {
9920 internal_error(state, 0, "phi input is not on a control predecessor");
9922 for(ptr = block->first; ; ptr = ptr->next) {
9923 if (ptr->op == OP_PHI) {
9924 struct triple *var, *val, **slot;
9927 internal_error(state, ptr, "no var???");
9929 /* Find the current value of the variable */
9930 val = var->use->member;
9931 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9932 internal_error(state, val, "bad value in phi");
9934 if (edge >= TRIPLE_RHS(ptr->sizes)) {
9935 internal_error(state, ptr, "edges > phi rhs");
9937 slot = &RHS(ptr, edge);
9938 if ((*slot != 0) && (*slot != val)) {
9939 internal_error(state, ptr, "phi already bound on this edge");
9942 use_triple(val, ptr);
9944 if (ptr == block->last) {
9951 static void rename_block_variables(
9952 struct compile_state *state, struct block *block)
9954 struct block_set *user;
9955 struct triple *ptr, *next, *last;
9959 last = block->first;
9961 for(ptr = block->first; !done; ptr = next) {
9963 if (ptr == block->last) {
9967 if (ptr->op == OP_READ) {
9968 struct triple *var, *val;
9970 unuse_triple(var, ptr);
9972 error(state, ptr, "variable used without being set");
9974 /* Find the current value of the variable */
9975 val = var->use->member;
9976 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9977 internal_error(state, val, "bad value in read");
9979 propogate_use(state, ptr, val);
9980 release_triple(state, ptr);
9984 if (ptr->op == OP_WRITE) {
9985 struct triple *var, *val;
9988 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9989 internal_error(state, val, "bad value in write");
9991 propogate_use(state, ptr, val);
9992 unuse_triple(var, ptr);
9993 /* Push OP_WRITE ptr->right onto a stack of variable uses */
9994 push_triple(var, val);
9996 if (ptr->op == OP_PHI) {
9999 /* Push OP_PHI onto a stack of variable uses */
10000 push_triple(var, ptr);
10004 block->last = last;
10006 /* Fixup PHI functions in the cf successors */
10007 fixup_block_phi_variables(state, block, block->left);
10008 fixup_block_phi_variables(state, block, block->right);
10009 /* rename variables in the dominated nodes */
10010 for(user = block->idominates; user; user = user->next) {
10011 rename_block_variables(state, user->member);
10013 /* pop the renamed variable stack */
10014 last = block->first;
10016 for(ptr = block->first; !done ; ptr = next) {
10018 if (ptr == block->last) {
10021 if (ptr->op == OP_WRITE) {
10022 struct triple *var;
10024 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10025 pop_triple(var, RHS(ptr, 0));
10026 release_triple(state, ptr);
10029 if (ptr->op == OP_PHI) {
10030 struct triple *var;
10031 var = MISC(ptr, 0);
10032 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10033 pop_triple(var, ptr);
10037 block->last = last;
10040 static void prune_block_variables(struct compile_state *state,
10041 struct block *block)
10043 struct block_set *user;
10044 struct triple *next, *last, *ptr;
10046 last = block->first;
10048 for(ptr = block->first; !done; ptr = next) {
10050 if (ptr == block->last) {
10053 if (ptr->op == OP_ADECL) {
10054 struct triple_set *user, *next;
10055 for(user = ptr->use; user; user = next) {
10056 struct triple *use;
10058 use = user->member;
10059 if (use->op != OP_PHI) {
10060 internal_error(state, use, "decl still used");
10062 if (MISC(use, 0) != ptr) {
10063 internal_error(state, use, "bad phi use of decl");
10065 unuse_triple(ptr, use);
10068 release_triple(state, ptr);
10073 block->last = last;
10074 for(user = block->idominates; user; user = user->next) {
10075 prune_block_variables(state, user->member);
10079 static void transform_to_ssa_form(struct compile_state *state)
10081 insert_phi_operations(state);
10083 printf("@%s:%d\n", __FILE__, __LINE__);
10084 print_blocks(state, stdout);
10086 rename_block_variables(state, state->first_block);
10087 prune_block_variables(state, state->first_block);
10091 static void clear_vertex(
10092 struct compile_state *state, struct block *block, void *arg)
10097 static void mark_live_block(
10098 struct compile_state *state, struct block *block, int *next_vertex)
10100 /* See if this is a block that has not been marked */
10101 if (block->vertex != 0) {
10104 block->vertex = *next_vertex;
10106 if (triple_is_branch(state, block->last)) {
10107 struct triple **targ;
10108 targ = triple_targ(state, block->last, 0);
10109 for(; targ; targ = triple_targ(state, block->last, targ)) {
10113 if (!triple_stores_block(state, *targ)) {
10114 internal_error(state, 0, "bad targ");
10116 mark_live_block(state, (*targ)->u.block, next_vertex);
10119 else if (block->last->next != RHS(state->main_function, 0)) {
10120 struct triple *ins;
10121 ins = block->last->next;
10122 if (!triple_stores_block(state, ins)) {
10123 internal_error(state, 0, "bad block start");
10125 mark_live_block(state, ins->u.block, next_vertex);
10129 static void transform_from_ssa_form(struct compile_state *state)
10131 /* To get out of ssa form we insert moves on the incoming
10132 * edges to blocks containting phi functions.
10134 struct triple *first;
10135 struct triple *phi, *next;
10138 /* Walk the control flow to see which blocks remain alive */
10139 walk_blocks(state, clear_vertex, 0);
10141 mark_live_block(state, state->first_block, &next_vertex);
10143 /* Walk all of the operations to find the phi functions */
10144 first = RHS(state->main_function, 0);
10145 for(phi = first->next; phi != first ; phi = next) {
10146 struct block_set *set;
10147 struct block *block;
10148 struct triple **slot;
10149 struct triple *var, *read;
10150 struct triple_set *use, *use_next;
10153 if (phi->op != OP_PHI) {
10156 block = phi->u.block;
10157 slot = &RHS(phi, 0);
10159 /* Forget uses from code in dead blocks */
10160 for(use = phi->use; use; use = use_next) {
10161 struct block *ublock;
10162 struct triple **expr;
10163 use_next = use->next;
10164 ublock = block_of_triple(state, use->member);
10165 if ((use->member == phi) || (ublock->vertex != 0)) {
10168 expr = triple_rhs(state, use->member, 0);
10169 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10170 if (*expr == phi) {
10174 unuse_triple(phi, use->member);
10177 /* A variable to replace the phi function */
10178 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10179 /* A read of the single value that is set into the variable */
10180 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10181 use_triple(var, read);
10183 /* Replaces uses of the phi with variable reads */
10184 propogate_use(state, phi, read);
10186 /* Walk all of the incoming edges/blocks and insert moves.
10188 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10189 struct block *eblock;
10190 struct triple *move;
10191 struct triple *val;
10192 eblock = set->member;
10195 unuse_triple(val, phi);
10197 if (!val || (val == &zero_triple) ||
10198 (block->vertex == 0) || (eblock->vertex == 0) ||
10199 (val == phi) || (val == read)) {
10203 move = post_triple(state,
10204 val, OP_WRITE, phi->type, var, val);
10205 use_triple(val, move);
10206 use_triple(var, move);
10208 /* See if there are any writers of var */
10210 for(use = var->use; use; use = use->next) {
10211 struct triple **expr;
10212 expr = triple_lhs(state, use->member, 0);
10213 for(; expr; expr = triple_lhs(state, use->member, expr)) {
10214 if (*expr == var) {
10219 /* If var is not used free it */
10221 unuse_triple(var, read);
10222 free_triple(state, read);
10223 free_triple(state, var);
10226 /* Release the phi function */
10227 release_triple(state, phi);
10234 * Register conflict resolution
10235 * =========================================================
10238 static struct reg_info find_def_color(
10239 struct compile_state *state, struct triple *def)
10241 struct triple_set *set;
10242 struct reg_info info;
10243 info.reg = REG_UNSET;
10245 if (!triple_is_def(state, def)) {
10248 info = arch_reg_lhs(state, def, 0);
10249 if (info.reg >= MAX_REGISTERS) {
10250 info.reg = REG_UNSET;
10252 for(set = def->use; set; set = set->next) {
10253 struct reg_info tinfo;
10255 i = find_rhs_use(state, set->member, def);
10259 tinfo = arch_reg_rhs(state, set->member, i);
10260 if (tinfo.reg >= MAX_REGISTERS) {
10261 tinfo.reg = REG_UNSET;
10263 if ((tinfo.reg != REG_UNSET) &&
10264 (info.reg != REG_UNSET) &&
10265 (tinfo.reg != info.reg)) {
10266 internal_error(state, def, "register conflict");
10268 if ((info.regcm & tinfo.regcm) == 0) {
10269 internal_error(state, def, "regcm conflict %x & %x == 0",
10270 info.regcm, tinfo.regcm);
10272 if (info.reg == REG_UNSET) {
10273 info.reg = tinfo.reg;
10275 info.regcm &= tinfo.regcm;
10277 if (info.reg >= MAX_REGISTERS) {
10278 internal_error(state, def, "register out of range");
10283 static struct reg_info find_lhs_pre_color(
10284 struct compile_state *state, struct triple *ins, int index)
10286 struct reg_info info;
10288 zrhs = TRIPLE_RHS(ins->sizes);
10289 zlhs = TRIPLE_LHS(ins->sizes);
10290 if (!zlhs && triple_is_def(state, ins)) {
10293 if (index >= zlhs) {
10294 internal_error(state, ins, "Bad lhs %d", index);
10296 info = arch_reg_lhs(state, ins, index);
10297 for(i = 0; i < zrhs; i++) {
10298 struct reg_info rinfo;
10299 rinfo = arch_reg_rhs(state, ins, i);
10300 if ((info.reg == rinfo.reg) &&
10301 (rinfo.reg >= MAX_REGISTERS)) {
10302 struct reg_info tinfo;
10303 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10304 info.reg = tinfo.reg;
10305 info.regcm &= tinfo.regcm;
10309 if (info.reg >= MAX_REGISTERS) {
10310 info.reg = REG_UNSET;
10315 static struct reg_info find_rhs_post_color(
10316 struct compile_state *state, struct triple *ins, int index);
10318 static struct reg_info find_lhs_post_color(
10319 struct compile_state *state, struct triple *ins, int index)
10321 struct triple_set *set;
10322 struct reg_info info;
10323 struct triple *lhs;
10325 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10328 if ((index == 0) && triple_is_def(state, ins)) {
10331 else if (index < TRIPLE_LHS(ins->sizes)) {
10332 lhs = LHS(ins, index);
10335 internal_error(state, ins, "Bad lhs %d", index);
10338 info = arch_reg_lhs(state, ins, index);
10339 if (info.reg >= MAX_REGISTERS) {
10340 info.reg = REG_UNSET;
10342 for(set = lhs->use; set; set = set->next) {
10343 struct reg_info rinfo;
10344 struct triple *user;
10346 user = set->member;
10347 zrhs = TRIPLE_RHS(user->sizes);
10348 for(i = 0; i < zrhs; i++) {
10349 if (RHS(user, i) != lhs) {
10352 rinfo = find_rhs_post_color(state, user, i);
10353 if ((info.reg != REG_UNSET) &&
10354 (rinfo.reg != REG_UNSET) &&
10355 (info.reg != rinfo.reg)) {
10356 internal_error(state, ins, "register conflict");
10358 if ((info.regcm & rinfo.regcm) == 0) {
10359 internal_error(state, ins, "regcm conflict %x & %x == 0",
10360 info.regcm, rinfo.regcm);
10362 if (info.reg == REG_UNSET) {
10363 info.reg = rinfo.reg;
10365 info.regcm &= rinfo.regcm;
10369 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10370 ins, index, info.reg, info.regcm);
10375 static struct reg_info find_rhs_post_color(
10376 struct compile_state *state, struct triple *ins, int index)
10378 struct reg_info info, rinfo;
10381 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10384 rinfo = arch_reg_rhs(state, ins, index);
10385 zlhs = TRIPLE_LHS(ins->sizes);
10386 if (!zlhs && triple_is_def(state, ins)) {
10390 if (info.reg >= MAX_REGISTERS) {
10391 info.reg = REG_UNSET;
10393 for(i = 0; i < zlhs; i++) {
10394 struct reg_info linfo;
10395 linfo = arch_reg_lhs(state, ins, i);
10396 if ((linfo.reg == rinfo.reg) &&
10397 (linfo.reg >= MAX_REGISTERS)) {
10398 struct reg_info tinfo;
10399 tinfo = find_lhs_post_color(state, ins, i);
10400 if (tinfo.reg >= MAX_REGISTERS) {
10401 tinfo.reg = REG_UNSET;
10403 info.regcm &= linfo.reg;
10404 info.regcm &= tinfo.regcm;
10405 if (info.reg != REG_UNSET) {
10406 internal_error(state, ins, "register conflict");
10408 if (info.regcm == 0) {
10409 internal_error(state, ins, "regcm conflict");
10411 info.reg = tinfo.reg;
10415 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10416 ins, index, info.reg, info.regcm);
10421 static struct reg_info find_lhs_color(
10422 struct compile_state *state, struct triple *ins, int index)
10424 struct reg_info pre, post, info;
10426 fprintf(stderr, "find_lhs_color(%p, %d)\n",
10429 pre = find_lhs_pre_color(state, ins, index);
10430 post = find_lhs_post_color(state, ins, index);
10431 if ((pre.reg != post.reg) &&
10432 (pre.reg != REG_UNSET) &&
10433 (post.reg != REG_UNSET)) {
10434 internal_error(state, ins, "register conflict");
10436 info.regcm = pre.regcm & post.regcm;
10437 info.reg = pre.reg;
10438 if (info.reg == REG_UNSET) {
10439 info.reg = post.reg;
10442 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10443 ins, index, info.reg, info.regcm);
10448 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10450 struct triple_set *entry, *next;
10451 struct triple *out;
10452 struct reg_info info, rinfo;
10454 info = arch_reg_lhs(state, ins, 0);
10455 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10456 use_triple(RHS(out, 0), out);
10457 /* Get the users of ins to use out instead */
10458 for(entry = ins->use; entry; entry = next) {
10460 next = entry->next;
10461 if (entry->member == out) {
10464 i = find_rhs_use(state, entry->member, ins);
10468 rinfo = arch_reg_rhs(state, entry->member, i);
10469 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10472 replace_rhs_use(state, ins, out, entry->member);
10474 transform_to_arch_instruction(state, out);
10478 static struct triple *pre_copy(
10479 struct compile_state *state, struct triple *ins, int index)
10481 /* Carefully insert enough operations so that I can
10482 * enter any operation with a GPR32.
10485 struct triple **expr;
10486 expr = &RHS(ins, index);
10487 in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10488 unuse_triple(*expr, ins);
10490 use_triple(RHS(in, 0), in);
10491 use_triple(in, ins);
10492 transform_to_arch_instruction(state, in);
10497 static void insert_copies_to_phi(struct compile_state *state)
10499 /* To get out of ssa form we insert moves on the incoming
10500 * edges to blocks containting phi functions.
10502 struct triple *first;
10503 struct triple *phi;
10505 /* Walk all of the operations to find the phi functions */
10506 first = RHS(state->main_function, 0);
10507 for(phi = first->next; phi != first ; phi = phi->next) {
10508 struct block_set *set;
10509 struct block *block;
10510 struct triple **slot;
10512 if (phi->op != OP_PHI) {
10515 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10516 block = phi->u.block;
10517 slot = &RHS(phi, 0);
10518 /* Walk all of the incoming edges/blocks and insert moves.
10520 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10521 struct block *eblock;
10522 struct triple *move;
10523 struct triple *val;
10524 struct triple *ptr;
10525 eblock = set->member;
10532 move = build_triple(state, OP_COPY, phi->type, val, 0,
10533 val->filename, val->line, val->col);
10534 move->u.block = eblock;
10535 move->id |= TRIPLE_FLAG_PRE_SPLIT;
10536 use_triple(val, move);
10539 unuse_triple(val, phi);
10540 use_triple(move, phi);
10542 /* Walk through the block backwards to find
10543 * an appropriate location for the OP_COPY.
10545 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10546 struct triple **expr;
10547 if ((ptr == phi) || (ptr == val)) {
10550 expr = triple_rhs(state, ptr, 0);
10551 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10552 if ((*expr) == phi) {
10558 if (triple_is_branch(state, ptr)) {
10559 internal_error(state, ptr,
10560 "Could not insert write to phi");
10562 insert_triple(state, ptr->next, move);
10563 if (eblock->last == ptr) {
10564 eblock->last = move;
10566 transform_to_arch_instruction(state, move);
10571 struct triple_reg_set {
10572 struct triple_reg_set *next;
10573 struct triple *member;
10574 struct triple *new;
10578 struct block *block;
10579 struct triple_reg_set *in;
10580 struct triple_reg_set *out;
10584 static int do_triple_set(struct triple_reg_set **head,
10585 struct triple *member, struct triple *new_member)
10587 struct triple_reg_set **ptr, *new;
10592 if ((*ptr)->member == member) {
10595 ptr = &(*ptr)->next;
10597 new = xcmalloc(sizeof(*new), "triple_set");
10598 new->member = member;
10599 new->new = new_member;
10605 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
10607 struct triple_reg_set *entry, **ptr;
10611 if (entry->member == member) {
10612 *ptr = entry->next;
10617 ptr = &entry->next;
10622 static int in_triple(struct reg_block *rb, struct triple *in)
10624 return do_triple_set(&rb->in, in, 0);
10626 static void unin_triple(struct reg_block *rb, struct triple *unin)
10628 do_triple_unset(&rb->in, unin);
10631 static int out_triple(struct reg_block *rb, struct triple *out)
10633 return do_triple_set(&rb->out, out, 0);
10635 static void unout_triple(struct reg_block *rb, struct triple *unout)
10637 do_triple_unset(&rb->out, unout);
10640 static int initialize_regblock(struct reg_block *blocks,
10641 struct block *block, int vertex)
10643 struct block_set *user;
10644 if (!block || (blocks[block->vertex].block == block)) {
10648 /* Renumber the blocks in a convinient fashion */
10649 block->vertex = vertex;
10650 blocks[vertex].block = block;
10651 blocks[vertex].vertex = vertex;
10652 for(user = block->use; user; user = user->next) {
10653 vertex = initialize_regblock(blocks, user->member, vertex);
10658 static int phi_in(struct compile_state *state, struct reg_block *blocks,
10659 struct reg_block *rb, struct block *suc)
10661 /* Read the conditional input set of a successor block
10662 * (i.e. the input to the phi nodes) and place it in the
10663 * current blocks output set.
10665 struct block_set *set;
10666 struct triple *ptr;
10670 /* Find the edge I am coming in on */
10671 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
10672 if (set->member == rb->block) {
10677 internal_error(state, 0, "Not coming on a control edge?");
10679 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
10680 struct triple **slot, *expr, *ptr2;
10681 int out_change, done2;
10682 done = (ptr == suc->last);
10683 if (ptr->op != OP_PHI) {
10686 slot = &RHS(ptr, 0);
10688 out_change = out_triple(rb, expr);
10692 /* If we don't define the variable also plast it
10693 * in the current blocks input set.
10695 ptr2 = rb->block->first;
10696 for(done2 = 0; !done2; ptr2 = ptr2->next) {
10697 if (ptr2 == expr) {
10700 done2 = (ptr2 == rb->block->last);
10705 change |= in_triple(rb, expr);
10710 static int reg_in(struct compile_state *state, struct reg_block *blocks,
10711 struct reg_block *rb, struct block *suc)
10713 struct triple_reg_set *in_set;
10716 /* Read the input set of a successor block
10717 * and place it in the current blocks output set.
10719 in_set = blocks[suc->vertex].in;
10720 for(; in_set; in_set = in_set->next) {
10721 int out_change, done;
10722 struct triple *first, *last, *ptr;
10723 out_change = out_triple(rb, in_set->member);
10727 /* If we don't define the variable also place it
10728 * in the current blocks input set.
10730 first = rb->block->first;
10731 last = rb->block->last;
10733 for(ptr = first; !done; ptr = ptr->next) {
10734 if (ptr == in_set->member) {
10737 done = (ptr == last);
10742 change |= in_triple(rb, in_set->member);
10744 change |= phi_in(state, blocks, rb, suc);
10749 static int use_in(struct compile_state *state, struct reg_block *rb)
10751 /* Find the variables we use but don't define and add
10752 * it to the current blocks input set.
10754 #warning "FIXME is this O(N^2) algorithm bad?"
10755 struct block *block;
10756 struct triple *ptr;
10761 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10762 struct triple **expr;
10763 done = (ptr == block->first);
10764 /* The variable a phi function uses depends on the
10765 * control flow, and is handled in phi_in, not
10768 if (ptr->op == OP_PHI) {
10771 expr = triple_rhs(state, ptr, 0);
10772 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10773 struct triple *rhs, *test;
10779 /* See if rhs is defined in this block */
10780 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10781 tdone = (test == block->first);
10787 /* If I still have a valid rhs add it to in */
10788 change |= in_triple(rb, rhs);
10794 static struct reg_block *compute_variable_lifetimes(
10795 struct compile_state *state)
10797 struct reg_block *blocks;
10800 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10801 initialize_regblock(blocks, state->last_block, 0);
10805 for(i = 1; i <= state->last_vertex; i++) {
10806 struct reg_block *rb;
10808 /* Add the left successor's input set to in */
10809 if (rb->block->left) {
10810 change |= reg_in(state, blocks, rb, rb->block->left);
10812 /* Add the right successor's input set to in */
10813 if ((rb->block->right) &&
10814 (rb->block->right != rb->block->left)) {
10815 change |= reg_in(state, blocks, rb, rb->block->right);
10817 /* Add use to in... */
10818 change |= use_in(state, rb);
10824 static void free_variable_lifetimes(
10825 struct compile_state *state, struct reg_block *blocks)
10828 /* free in_set && out_set on each block */
10829 for(i = 1; i <= state->last_vertex; i++) {
10830 struct triple_reg_set *entry, *next;
10831 struct reg_block *rb;
10833 for(entry = rb->in; entry ; entry = next) {
10834 next = entry->next;
10835 do_triple_unset(&rb->in, entry->member);
10837 for(entry = rb->out; entry; entry = next) {
10838 next = entry->next;
10839 do_triple_unset(&rb->out, entry->member);
10846 typedef struct triple *(*wvl_cb_t)(
10847 struct compile_state *state,
10848 struct reg_block *blocks, struct triple_reg_set *live,
10849 struct reg_block *rb, struct triple *ins, void *arg);
10851 static void walk_variable_lifetimes(struct compile_state *state,
10852 struct reg_block *blocks, wvl_cb_t cb, void *arg)
10856 for(i = 1; i <= state->last_vertex; i++) {
10857 struct triple_reg_set *live;
10858 struct triple_reg_set *entry, *next;
10859 struct triple *ptr, *prev;
10860 struct reg_block *rb;
10861 struct block *block;
10864 /* Get the blocks */
10868 /* Copy out into live */
10870 for(entry = rb->out; entry; entry = next) {
10871 next = entry->next;
10872 do_triple_set(&live, entry->member, entry->new);
10874 /* Walk through the basic block calculating live */
10875 for(done = 0, ptr = block->last; !done; ptr = prev) {
10876 struct triple **expr, *result;
10879 done = (ptr == block->first);
10881 /* Ensure the current definition is in live */
10882 if (triple_is_def(state, ptr)) {
10883 do_triple_set(&live, ptr, 0);
10886 /* Inform the callback function of what is
10889 result = cb(state, blocks, live, rb, ptr, arg);
10891 /* Remove the current definition from live */
10892 do_triple_unset(&live, ptr);
10894 /* If the current instruction was deleted continue */
10896 if (block->last == ptr) {
10897 block->last = prev;
10903 /* Add the current uses to live.
10905 * It is safe to skip phi functions because they do
10906 * not have any block local uses, and the block
10907 * output sets already properly account for what
10908 * control flow depedent uses phi functions do have.
10910 if (ptr->op == OP_PHI) {
10913 expr = triple_rhs(state, ptr, 0);
10914 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10915 /* If the triple is not a definition skip it. */
10916 if (!*expr || !triple_is_def(state, *expr)) {
10919 do_triple_set(&live, *expr, 0);
10923 for(entry = live; entry; entry = next) {
10924 next = entry->next;
10925 do_triple_unset(&live, entry->member);
10930 static int count_triples(struct compile_state *state)
10932 struct triple *first, *ins;
10934 first = RHS(state->main_function, 0);
10939 } while (ins != first);
10942 struct dead_triple {
10943 struct triple *triple;
10944 struct dead_triple *work_next;
10945 struct block *block;
10948 #define TRIPLE_FLAG_ALIVE 1
10952 static void awaken(
10953 struct compile_state *state,
10954 struct dead_triple *dtriple, struct triple **expr,
10955 struct dead_triple ***work_list_tail)
10957 struct triple *triple;
10958 struct dead_triple *dt;
10966 if (triple->id <= 0) {
10967 internal_error(state, triple, "bad triple id: %d",
10970 if (triple->op == OP_NOOP) {
10971 internal_warning(state, triple, "awakening noop?");
10974 dt = &dtriple[triple->id];
10975 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10976 dt->flags |= TRIPLE_FLAG_ALIVE;
10977 if (!dt->work_next) {
10978 **work_list_tail = dt;
10979 *work_list_tail = &dt->work_next;
10984 static void eliminate_inefectual_code(struct compile_state *state)
10986 struct block *block;
10987 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
10989 struct triple *first, *ins;
10991 /* Setup the work list */
10993 work_list_tail = &work_list;
10995 first = RHS(state->main_function, 0);
10997 /* Count how many triples I have */
10998 triples = count_triples(state);
11000 /* Now put then in an array and mark all of the triples dead */
11001 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11007 if (ins->op == OP_LABEL) {
11008 block = ins->u.block;
11010 dtriple[i].triple = ins;
11011 dtriple[i].block = block;
11012 dtriple[i].flags = 0;
11013 dtriple[i].color = ins->id;
11015 /* See if it is an operation we always keep */
11016 #warning "FIXME handle the case of killing a branch instruction"
11017 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11018 awaken(state, dtriple, &ins, &work_list_tail);
11022 } while(ins != first);
11024 struct dead_triple *dt;
11025 struct block_set *user;
11026 struct triple **expr;
11028 work_list = dt->work_next;
11030 work_list_tail = &work_list;
11032 /* Wake up the data depencencies of this triple */
11035 expr = triple_rhs(state, dt->triple, expr);
11036 awaken(state, dtriple, expr, &work_list_tail);
11039 expr = triple_lhs(state, dt->triple, expr);
11040 awaken(state, dtriple, expr, &work_list_tail);
11043 expr = triple_misc(state, dt->triple, expr);
11044 awaken(state, dtriple, expr, &work_list_tail);
11046 /* Wake up the forward control dependencies */
11048 expr = triple_targ(state, dt->triple, expr);
11049 awaken(state, dtriple, expr, &work_list_tail);
11051 /* Wake up the reverse control dependencies of this triple */
11052 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11053 awaken(state, dtriple, &user->member->last, &work_list_tail);
11056 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11057 if ((dt->triple->op == OP_NOOP) &&
11058 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11059 internal_error(state, dt->triple, "noop effective?");
11061 dt->triple->id = dt->color; /* Restore the color */
11062 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11063 #warning "FIXME handle the case of killing a basic block"
11064 if (dt->block->first == dt->triple) {
11067 if (dt->block->last == dt->triple) {
11068 dt->block->last = dt->triple->prev;
11070 release_triple(state, dt->triple);
11077 static void insert_mandatory_copies(struct compile_state *state)
11079 struct triple *ins, *first;
11081 /* The object is with a minimum of inserted copies,
11082 * to resolve in fundamental register conflicts between
11083 * register value producers and consumers.
11084 * Theoretically we may be greater than minimal when we
11085 * are inserting copies before instructions but that
11086 * case should be rare.
11088 first = RHS(state->main_function, 0);
11091 struct triple_set *entry, *next;
11092 struct triple *tmp;
11093 struct reg_info info;
11094 unsigned reg, regcm;
11095 int do_post_copy, do_pre_copy;
11097 if (!triple_is_def(state, ins)) {
11100 /* Find the architecture specific color information */
11101 info = arch_reg_lhs(state, ins, 0);
11102 if (info.reg >= MAX_REGISTERS) {
11103 info.reg = REG_UNSET;
11107 regcm = arch_type_to_regcm(state, ins->type);
11108 do_post_copy = do_pre_copy = 0;
11110 /* Walk through the uses of ins and check for conflicts */
11111 for(entry = ins->use; entry; entry = next) {
11112 struct reg_info rinfo;
11114 next = entry->next;
11115 i = find_rhs_use(state, entry->member, ins);
11120 /* Find the users color requirements */
11121 rinfo = arch_reg_rhs(state, entry->member, i);
11122 if (rinfo.reg >= MAX_REGISTERS) {
11123 rinfo.reg = REG_UNSET;
11126 /* See if I need a pre_copy */
11127 if (rinfo.reg != REG_UNSET) {
11128 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11133 regcm &= rinfo.regcm;
11134 regcm = arch_regcm_normalize(state, regcm);
11141 (((info.reg != REG_UNSET) &&
11142 (reg != REG_UNSET) &&
11143 (info.reg != reg)) ||
11144 ((info.regcm & regcm) == 0));
11147 regcm = info.regcm;
11148 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11149 for(entry = ins->use; entry; entry = next) {
11150 struct reg_info rinfo;
11152 next = entry->next;
11153 i = find_rhs_use(state, entry->member, ins);
11158 /* Find the users color requirements */
11159 rinfo = arch_reg_rhs(state, entry->member, i);
11160 if (rinfo.reg >= MAX_REGISTERS) {
11161 rinfo.reg = REG_UNSET;
11164 /* Now see if it is time to do the pre_copy */
11165 if (rinfo.reg != REG_UNSET) {
11166 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11167 ((regcm & rinfo.regcm) == 0) ||
11168 /* Don't let a mandatory coalesce sneak
11169 * into a operation that is marked to prevent
11172 ((reg != REG_UNNEEDED) &&
11173 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11174 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11177 struct triple *user;
11178 user = entry->member;
11179 if (RHS(user, i) != ins) {
11180 internal_error(state, user, "bad rhs");
11182 tmp = pre_copy(state, user, i);
11190 if ((regcm & rinfo.regcm) == 0) {
11192 struct triple *user;
11193 user = entry->member;
11194 if (RHS(user, i) != ins) {
11195 internal_error(state, user, "bad rhs");
11197 tmp = pre_copy(state, user, i);
11203 regcm &= rinfo.regcm;
11206 if (do_post_copy) {
11207 struct reg_info pre, post;
11208 tmp = post_copy(state, ins);
11209 pre = arch_reg_lhs(state, ins, 0);
11210 post = arch_reg_lhs(state, tmp, 0);
11211 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11212 internal_error(state, tmp, "useless copy");
11217 } while(ins != first);
11221 struct live_range_edge;
11222 struct live_range_def;
11223 struct live_range {
11224 struct live_range_edge *edges;
11225 struct live_range_def *defs;
11226 /* Note. The list pointed to by defs is kept in order.
11227 * That is baring splits in the flow control
11228 * defs dominates defs->next wich dominates defs->next->next
11235 struct live_range *group_next, **group_prev;
11238 struct live_range_edge {
11239 struct live_range_edge *next;
11240 struct live_range *node;
11243 struct live_range_def {
11244 struct live_range_def *next;
11245 struct live_range_def *prev;
11246 struct live_range *lr;
11247 struct triple *def;
11251 #define LRE_HASH_SIZE 2048
11253 struct lre_hash *next;
11254 struct live_range *left;
11255 struct live_range *right;
11260 struct lre_hash *hash[LRE_HASH_SIZE];
11261 struct reg_block *blocks;
11262 struct live_range_def *lrd;
11263 struct live_range *lr;
11264 struct live_range *low, **low_tail;
11265 struct live_range *high, **high_tail;
11268 int passes, max_passes;
11269 #define MAX_ALLOCATION_PASSES 100
11273 static unsigned regc_max_size(struct compile_state *state, int classes)
11278 for(i = 0; i < MAX_REGC; i++) {
11279 if (classes & (1 << i)) {
11281 size = arch_regc_size(state, i);
11282 if (size > max_size) {
11290 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11292 unsigned equivs[MAX_REG_EQUIVS];
11294 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11295 internal_error(state, 0, "invalid register");
11297 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11298 internal_error(state, 0, "invalid register");
11300 arch_reg_equivs(state, equivs, reg1);
11301 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11302 if (equivs[i] == reg2) {
11309 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11311 unsigned equivs[MAX_REG_EQUIVS];
11313 if (reg == REG_UNNEEDED) {
11316 arch_reg_equivs(state, equivs, reg);
11317 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11318 used[equivs[i]] = 1;
11323 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11325 unsigned equivs[MAX_REG_EQUIVS];
11327 if (reg == REG_UNNEEDED) {
11330 arch_reg_equivs(state, equivs, reg);
11331 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11332 used[equivs[i]] += 1;
11337 static unsigned int hash_live_edge(
11338 struct live_range *left, struct live_range *right)
11340 unsigned int hash, val;
11341 unsigned long lval, rval;
11342 lval = ((unsigned long)left)/sizeof(struct live_range);
11343 rval = ((unsigned long)right)/sizeof(struct live_range);
11348 hash = (hash *263) + val;
11353 hash = (hash *263) + val;
11355 hash = hash & (LRE_HASH_SIZE - 1);
11359 static struct lre_hash **lre_probe(struct reg_state *rstate,
11360 struct live_range *left, struct live_range *right)
11362 struct lre_hash **ptr;
11363 unsigned int index;
11364 /* Ensure left <= right */
11365 if (left > right) {
11366 struct live_range *tmp;
11371 index = hash_live_edge(left, right);
11373 ptr = &rstate->hash[index];
11374 while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
11375 ptr = &(*ptr)->next;
11380 static int interfere(struct reg_state *rstate,
11381 struct live_range *left, struct live_range *right)
11383 struct lre_hash **ptr;
11384 ptr = lre_probe(rstate, left, right);
11385 return ptr && *ptr;
11388 static void add_live_edge(struct reg_state *rstate,
11389 struct live_range *left, struct live_range *right)
11391 /* FIXME the memory allocation overhead is noticeable here... */
11392 struct lre_hash **ptr, *new_hash;
11393 struct live_range_edge *edge;
11395 if (left == right) {
11398 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11401 /* Ensure left <= right */
11402 if (left > right) {
11403 struct live_range *tmp;
11408 ptr = lre_probe(rstate, left, right);
11412 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11413 new_hash->next = *ptr;
11414 new_hash->left = left;
11415 new_hash->right = right;
11418 edge = xmalloc(sizeof(*edge), "live_range_edge");
11419 edge->next = left->edges;
11420 edge->node = right;
11421 left->edges = edge;
11424 edge = xmalloc(sizeof(*edge), "live_range_edge");
11425 edge->next = right->edges;
11427 right->edges = edge;
11428 right->degree += 1;
11431 static void remove_live_edge(struct reg_state *rstate,
11432 struct live_range *left, struct live_range *right)
11434 struct live_range_edge *edge, **ptr;
11435 struct lre_hash **hptr, *entry;
11436 hptr = lre_probe(rstate, left, right);
11437 if (!hptr || !*hptr) {
11441 *hptr = entry->next;
11444 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11446 if (edge->node == right) {
11448 memset(edge, 0, sizeof(*edge));
11453 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11455 if (edge->node == left) {
11457 memset(edge, 0, sizeof(*edge));
11464 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11466 struct live_range_edge *edge, *next;
11467 for(edge = range->edges; edge; edge = next) {
11469 remove_live_edge(rstate, range, edge->node);
11474 /* Interference graph...
11476 * new(n) --- Return a graph with n nodes but no edges.
11477 * add(g,x,y) --- Return a graph including g with an between x and y
11478 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11479 * x and y in the graph g
11480 * degree(g, x) --- Return the degree of the node x in the graph g
11481 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11483 * Implement with a hash table && a set of adjcency vectors.
11484 * The hash table supports constant time implementations of add and interfere.
11485 * The adjacency vectors support an efficient implementation of neighbors.
11489 * +---------------------------------------------------+
11490 * | +--------------+ |
11492 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
11494 * -- In simplify implment optimistic coloring... (No backtracking)
11495 * -- Implement Rematerialization it is the only form of spilling we can perform
11496 * Essentially this means dropping a constant from a register because
11497 * we can regenerate it later.
11499 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11500 * coalesce at phi points...
11501 * --- Bias coloring if at all possible do the coalesing a compile time.
11506 static void different_colored(
11507 struct compile_state *state, struct reg_state *rstate,
11508 struct triple *parent, struct triple *ins)
11510 struct live_range *lr;
11511 struct triple **expr;
11512 lr = rstate->lrd[ins->id].lr;
11513 expr = triple_rhs(state, ins, 0);
11514 for(;expr; expr = triple_rhs(state, ins, expr)) {
11515 struct live_range *lr2;
11516 if (!*expr || (*expr == parent) || (*expr == ins)) {
11519 lr2 = rstate->lrd[(*expr)->id].lr;
11520 if (lr->color == lr2->color) {
11521 internal_error(state, ins, "live range too big");
11527 static struct live_range *coalesce_ranges(
11528 struct compile_state *state, struct reg_state *rstate,
11529 struct live_range *lr1, struct live_range *lr2)
11531 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11537 if (!lr1->defs || !lr2->defs) {
11538 internal_error(state, 0,
11539 "cannot coalese dead live ranges");
11541 if ((lr1->color == REG_UNNEEDED) ||
11542 (lr2->color == REG_UNNEEDED)) {
11543 internal_error(state, 0,
11544 "cannot coalesce live ranges without a possible color");
11546 if ((lr1->color != lr2->color) &&
11547 (lr1->color != REG_UNSET) &&
11548 (lr2->color != REG_UNSET)) {
11549 internal_error(state, lr1->defs->def,
11550 "cannot coalesce live ranges of different colors");
11552 color = lr1->color;
11553 if (color == REG_UNSET) {
11554 color = lr2->color;
11556 classes = lr1->classes & lr2->classes;
11558 internal_error(state, lr1->defs->def,
11559 "cannot coalesce live ranges with dissimilar register classes");
11561 /* If there is a clear dominate live range put it in lr1,
11562 * For purposes of this test phi functions are
11563 * considered dominated by the definitions that feed into
11566 if ((lr1->defs->prev->def->op == OP_PHI) ||
11567 ((lr2->defs->prev->def->op != OP_PHI) &&
11568 tdominates(state, lr2->defs->def, lr1->defs->def))) {
11569 struct live_range *tmp;
11575 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11576 fprintf(stderr, "lr1 post\n");
11578 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11579 fprintf(stderr, "lr1 pre\n");
11581 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11582 fprintf(stderr, "lr2 post\n");
11584 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11585 fprintf(stderr, "lr2 pre\n");
11589 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
11596 lr1->classes = classes;
11597 /* Append lr2 onto lr1 */
11598 #warning "FIXME should this be a merge instead of a splice?"
11600 mid1 = lr1->defs->prev;
11602 end = lr2->defs->prev;
11610 /* Fixup the live range in the added live range defs */
11615 } while(lrd != head);
11617 /* Mark lr2 as free. */
11619 lr2->color = REG_UNNEEDED;
11623 internal_error(state, 0, "lr1->defs == 0 ?");
11626 lr1->color = color;
11627 lr1->classes = classes;
11632 static struct live_range_def *live_range_head(
11633 struct compile_state *state, struct live_range *lr,
11634 struct live_range_def *last)
11636 struct live_range_def *result;
11641 else if (!tdominates(state, lr->defs->def, last->next->def)) {
11642 result = last->next;
11647 static struct live_range_def *live_range_end(
11648 struct compile_state *state, struct live_range *lr,
11649 struct live_range_def *last)
11651 struct live_range_def *result;
11654 result = lr->defs->prev;
11656 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
11657 result = last->prev;
11663 static void initialize_live_ranges(
11664 struct compile_state *state, struct reg_state *rstate)
11666 struct triple *ins, *first;
11667 size_t count, size;
11670 first = RHS(state->main_function, 0);
11671 /* First count how many instructions I have.
11673 count = count_triples(state);
11674 /* Potentially I need one live range definitions for each
11675 * instruction, plus an extra for the split routines.
11677 rstate->defs = count + 1;
11678 /* Potentially I need one live range for each instruction
11679 * plus an extra for the dummy live range.
11681 rstate->ranges = count + 1;
11682 size = sizeof(rstate->lrd[0]) * rstate->defs;
11683 rstate->lrd = xcmalloc(size, "live_range_def");
11684 size = sizeof(rstate->lr[0]) * rstate->ranges;
11685 rstate->lr = xcmalloc(size, "live_range");
11687 /* Setup the dummy live range */
11688 rstate->lr[0].classes = 0;
11689 rstate->lr[0].color = REG_UNSET;
11690 rstate->lr[0].defs = 0;
11694 /* If the triple is a variable give it a live range */
11695 if (triple_is_def(state, ins)) {
11696 struct reg_info info;
11697 /* Find the architecture specific color information */
11698 info = find_def_color(state, ins);
11701 rstate->lr[i].defs = &rstate->lrd[j];
11702 rstate->lr[i].color = info.reg;
11703 rstate->lr[i].classes = info.regcm;
11704 rstate->lr[i].degree = 0;
11705 rstate->lrd[j].lr = &rstate->lr[i];
11707 /* Otherwise give the triple the dummy live range. */
11709 rstate->lrd[j].lr = &rstate->lr[0];
11712 /* Initalize the live_range_def */
11713 rstate->lrd[j].next = &rstate->lrd[j];
11714 rstate->lrd[j].prev = &rstate->lrd[j];
11715 rstate->lrd[j].def = ins;
11716 rstate->lrd[j].orig_id = ins->id;
11721 } while(ins != first);
11722 rstate->ranges = i;
11725 /* Make a second pass to handle achitecture specific register
11730 int zlhs, zrhs, i, j;
11731 if (ins->id > rstate->defs) {
11732 internal_error(state, ins, "bad id");
11735 /* Walk through the template of ins and coalesce live ranges */
11736 zlhs = TRIPLE_LHS(ins->sizes);
11737 if ((zlhs == 0) && triple_is_def(state, ins)) {
11740 zrhs = TRIPLE_RHS(ins->sizes);
11742 for(i = 0; i < zlhs; i++) {
11743 struct reg_info linfo;
11744 struct live_range_def *lhs;
11745 linfo = arch_reg_lhs(state, ins, i);
11746 if (linfo.reg < MAX_REGISTERS) {
11749 if (triple_is_def(state, ins)) {
11750 lhs = &rstate->lrd[ins->id];
11752 lhs = &rstate->lrd[LHS(ins, i)->id];
11754 for(j = 0; j < zrhs; j++) {
11755 struct reg_info rinfo;
11756 struct live_range_def *rhs;
11757 rinfo = arch_reg_rhs(state, ins, j);
11758 if (rinfo.reg < MAX_REGISTERS) {
11761 rhs = &rstate->lrd[RHS(ins, i)->id];
11762 if (rinfo.reg == linfo.reg) {
11763 coalesce_ranges(state, rstate,
11769 } while(ins != first);
11772 static struct triple *graph_ins(
11773 struct compile_state *state,
11774 struct reg_block *blocks, struct triple_reg_set *live,
11775 struct reg_block *rb, struct triple *ins, void *arg)
11777 struct reg_state *rstate = arg;
11778 struct live_range *def;
11779 struct triple_reg_set *entry;
11781 /* If the triple is not a definition
11782 * we do not have a definition to add to
11783 * the interference graph.
11785 if (!triple_is_def(state, ins)) {
11788 def = rstate->lrd[ins->id].lr;
11790 /* Create an edge between ins and everything that is
11791 * alive, unless the live_range cannot share
11792 * a physical register with ins.
11794 for(entry = live; entry; entry = entry->next) {
11795 struct live_range *lr;
11796 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
11797 internal_error(state, 0, "bad entry?");
11799 lr = rstate->lrd[entry->member->id].lr;
11803 if (!arch_regcm_intersect(def->classes, lr->classes)) {
11806 add_live_edge(rstate, def, lr);
11812 static struct triple *print_interference_ins(
11813 struct compile_state *state,
11814 struct reg_block *blocks, struct triple_reg_set *live,
11815 struct reg_block *rb, struct triple *ins, void *arg)
11817 struct reg_state *rstate = arg;
11818 struct live_range *lr;
11820 lr = rstate->lrd[ins->id].lr;
11821 display_triple(stdout, ins);
11824 struct live_range_def *lrd;
11828 printf(" %-10p", lrd->def);
11830 } while(lrd != lr->defs);
11834 struct triple_reg_set *entry;
11836 for(entry = live; entry; entry = entry->next) {
11837 printf(" %-10p", entry->member);
11842 struct live_range_edge *entry;
11844 for(entry = lr->edges; entry; entry = entry->next) {
11845 struct live_range_def *lrd;
11846 lrd = entry->node->defs;
11848 printf(" %-10p", lrd->def);
11850 } while(lrd != entry->node->defs);
11855 if (triple_is_branch(state, ins)) {
11861 static int coalesce_live_ranges(
11862 struct compile_state *state, struct reg_state *rstate)
11864 /* At the point where a value is moved from one
11865 * register to another that value requires two
11866 * registers, thus increasing register pressure.
11867 * Live range coaleescing reduces the register
11868 * pressure by keeping a value in one register
11871 * In the case of a phi function all paths leading
11872 * into it must be allocated to the same register
11873 * otherwise the phi function may not be removed.
11875 * Forcing a value to stay in a single register
11876 * for an extended period of time does have
11877 * limitations when applied to non homogenous
11880 * The two cases I have identified are:
11881 * 1) Two forced register assignments may
11883 * 2) Registers may go unused because they
11884 * are only good for storing the value
11885 * and not manipulating it.
11887 * Because of this I need to split live ranges,
11888 * even outside of the context of coalesced live
11889 * ranges. The need to split live ranges does
11890 * impose some constraints on live range coalescing.
11892 * - Live ranges may not be coalesced across phi
11893 * functions. This creates a 2 headed live
11894 * range that cannot be sanely split.
11896 * - phi functions (coalesced in initialize_live_ranges)
11897 * are handled as pre split live ranges so we will
11898 * never attempt to split them.
11904 for(i = 0; i <= rstate->ranges; i++) {
11905 struct live_range *lr1;
11906 struct live_range_def *lrd1;
11907 lr1 = &rstate->lr[i];
11911 lrd1 = live_range_end(state, lr1, 0);
11912 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
11913 struct triple_set *set;
11914 if (lrd1->def->op != OP_COPY) {
11917 /* Skip copies that are the result of a live range split. */
11918 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11921 for(set = lrd1->def->use; set; set = set->next) {
11922 struct live_range_def *lrd2;
11923 struct live_range *lr2, *res;
11925 lrd2 = &rstate->lrd[set->member->id];
11927 /* Don't coalesce with instructions
11928 * that are the result of a live range
11931 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11934 lr2 = rstate->lrd[set->member->id].lr;
11938 if ((lr1->color != lr2->color) &&
11939 (lr1->color != REG_UNSET) &&
11940 (lr2->color != REG_UNSET)) {
11943 if ((lr1->classes & lr2->classes) == 0) {
11947 if (interfere(rstate, lr1, lr2)) {
11951 res = coalesce_ranges(state, rstate, lr1, lr2);
11965 struct coalesce_conflict {
11966 struct triple *ins;
11969 static struct triple *spot_coalesce_conflict(struct compile_state *state,
11970 struct reg_block *blocks, struct triple_reg_set *live,
11971 struct reg_block *rb, struct triple *ins, void *arg)
11973 struct coalesce_conflict *conflict = arg;
11974 int zlhs, zrhs, i, j;
11977 /* See if we have a mandatory coalesce operation between
11978 * a lhs and a rhs value. If so and the rhs value is also
11979 * alive then this triple needs to be pre copied. Otherwise
11980 * we would have two definitions in the same live range simultaneously
11984 zlhs = TRIPLE_LHS(ins->sizes);
11985 if ((zlhs == 0) && triple_is_def(state, ins)) {
11988 zrhs = TRIPLE_RHS(ins->sizes);
11989 for(i = 0; (i < zlhs) && (found == -1); i++) {
11990 struct reg_info linfo;
11991 linfo = arch_reg_lhs(state, ins, i);
11992 if (linfo.reg < MAX_REGISTERS) {
11995 for(j = 0; (j < zrhs) && (found == -1); j++) {
11996 struct reg_info rinfo;
11997 struct triple *rhs;
11998 struct triple_reg_set *set;
11999 rinfo = arch_reg_rhs(state, ins, j);
12000 if (rinfo.reg != linfo.reg) {
12004 for(set = live; set && (found == -1); set = set->next) {
12005 if (set->member == rhs) {
12011 /* Only update conflict if we are the least dominated conflict */
12012 if ((found != -1) &&
12013 (!conflict->ins || tdominates(state, ins, conflict->ins))) {
12014 conflict->ins = ins;
12015 conflict->index = found;
12020 static void resolve_coalesce_conflict(
12021 struct compile_state *state, struct coalesce_conflict *conflict)
12023 struct triple *copy;
12024 copy = pre_copy(state, conflict->ins, conflict->index);
12025 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12029 static struct triple *spot_tangle(struct compile_state *state,
12030 struct reg_block *blocks, struct triple_reg_set *live,
12031 struct reg_block *rb, struct triple *ins, void *arg)
12033 struct triple **tangle = arg;
12034 char used[MAX_REGISTERS];
12035 struct triple_reg_set *set;
12037 /* Find out which registers have multiple uses at this point */
12038 memset(used, 0, sizeof(used));
12039 for(set = live; set; set = set->next) {
12040 struct reg_info info;
12041 info = find_lhs_color(state, set->member, 0);
12042 if (info.reg == REG_UNSET) {
12045 reg_inc_used(state, used, info.reg);
12048 /* Now find the least dominated definition of a register in
12049 * conflict I have seen so far.
12051 for(set = live; set; set = set->next) {
12052 struct reg_info info;
12053 info = find_lhs_color(state, set->member, 0);
12054 if (used[info.reg] < 2) {
12057 if (!*tangle || tdominates(state, set->member, *tangle)) {
12058 *tangle = set->member;
12064 static void resolve_tangle(struct compile_state *state, struct triple *tangle)
12066 struct reg_info info, uinfo;
12067 struct triple_set *set, *next;
12068 struct triple *copy;
12071 fprintf(stderr, "Resolving tangle: %p\n", tangle);
12072 print_blocks(state, stderr);
12074 info = find_lhs_color(state, tangle, 0);
12076 fprintf(stderr, "color: %d\n", info.reg);
12078 for(set = tangle->use; set; set = next) {
12079 struct triple *user;
12082 user = set->member;
12083 zrhs = TRIPLE_RHS(user->sizes);
12084 for(i = 0; i < zrhs; i++) {
12085 if (RHS(user, i) != tangle) {
12088 uinfo = find_rhs_post_color(state, user, i);
12090 fprintf(stderr, "%p rhs %d color: %d\n",
12091 user, i, uinfo.reg);
12093 if (uinfo.reg == info.reg) {
12094 copy = pre_copy(state, user, i);
12095 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12099 uinfo = find_lhs_pre_color(state, tangle, 0);
12101 fprintf(stderr, "pre color: %d\n", uinfo.reg);
12103 if (uinfo.reg == info.reg) {
12104 copy = post_copy(state, tangle);
12105 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12110 struct least_conflict {
12111 struct reg_state *rstate;
12112 struct live_range *ref_range;
12113 struct triple *ins;
12114 struct triple_reg_set *live;
12117 static struct triple *least_conflict(struct compile_state *state,
12118 struct reg_block *blocks, struct triple_reg_set *live,
12119 struct reg_block *rb, struct triple *ins, void *arg)
12121 struct least_conflict *conflict = arg;
12122 struct live_range_edge *edge;
12123 struct triple_reg_set *set;
12126 #warning "FIXME handle instructions with left hand sides..."
12127 /* Only instructions that introduce a new definition
12128 * can be the conflict instruction.
12130 if (!triple_is_def(state, ins)) {
12134 /* See if live ranges at this instruction are a
12135 * strict subset of the live ranges that are in conflict.
12138 for(set = live; set; set = set->next) {
12139 struct live_range *lr;
12140 lr = conflict->rstate->lrd[set->member->id].lr;
12141 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12142 if (edge->node == lr) {
12146 if (!edge && (lr != conflict->ref_range)) {
12155 /* See if there is an uncolored member in this subset.
12157 for(set = live; set; set = set->next) {
12158 struct live_range *lr;
12159 lr = conflict->rstate->lrd[set->member->id].lr;
12160 if (lr->color == REG_UNSET) {
12164 if (!set && (conflict->ref_range != REG_UNSET)) {
12169 /* Find the instruction with the largest possible subset of
12170 * conflict ranges and that dominates any other instruction
12171 * with an equal sized set of conflicting ranges.
12173 if ((count > conflict->count) ||
12174 ((count == conflict->count) &&
12175 tdominates(state, ins, conflict->ins))) {
12176 struct triple_reg_set *next;
12177 /* Remember the canidate instruction */
12178 conflict->ins = ins;
12179 conflict->count = count;
12180 /* Free the old collection of live registers */
12181 for(set = conflict->live; set; set = next) {
12183 do_triple_unset(&conflict->live, set->member);
12185 conflict->live = 0;
12186 /* Rember the registers that are alive but do not feed
12187 * into or out of conflict->ins.
12189 for(set = live; set; set = set->next) {
12190 struct triple **expr;
12191 if (set->member == ins) {
12194 expr = triple_rhs(state, ins, 0);
12195 for(;expr; expr = triple_rhs(state, ins, expr)) {
12196 if (*expr == set->member) {
12200 expr = triple_lhs(state, ins, 0);
12201 for(; expr; expr = triple_lhs(state, ins, expr)) {
12202 if (*expr == set->member) {
12206 do_triple_set(&conflict->live, set->member, set->new);
12214 static void find_range_conflict(struct compile_state *state,
12215 struct reg_state *rstate, char *used, struct live_range *ref_range,
12216 struct least_conflict *conflict)
12218 /* there are 3 kinds ways conflicts can occure.
12219 * 1) the life time of 2 values simply overlap.
12220 * 2) the 2 values feed into the same instruction.
12221 * 3) the 2 values feed into a phi function.
12224 /* find the instruction where the problematic conflict comes
12225 * into existance. that the instruction where all of
12226 * the values are alive, and among such instructions it is
12227 * the least dominated one.
12229 * a value is alive an an instruction if either;
12230 * 1) the value defintion dominates the instruction and there
12231 * is a use at or after that instrction
12232 * 2) the value definition feeds into a phi function in the
12233 * same block as the instruction. and the phi function
12234 * is at or after the instruction.
12236 memset(conflict, 0, sizeof(*conflict));
12237 conflict->rstate = rstate;
12238 conflict->ref_range = ref_range;
12240 conflict->count = 0;
12241 conflict->live = 0;
12242 walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12244 if (!conflict->ins) {
12245 internal_error(state, 0, "No conflict ins?");
12247 if (!conflict->live) {
12248 internal_error(state, 0, "No conflict live?");
12253 static struct triple *split_constrained_range(struct compile_state *state,
12254 struct reg_state *rstate, char *used, struct least_conflict *conflict)
12256 unsigned constrained_size;
12257 struct triple *new, *constrained;
12258 struct triple_reg_set *cset;
12259 /* Find a range that is having problems because it is
12260 * artificially constrained.
12262 constrained_size = ~0;
12265 for(cset = conflict->live; cset; cset = cset->next) {
12266 struct triple_set *set;
12267 struct reg_info info;
12269 unsigned cur_size, size;
12270 /* Skip the live range that starts with conflict->ins */
12271 if (cset->member == conflict->ins) {
12274 /* Find how many registers this value can potentially
12277 classes = arch_type_to_regcm(state, cset->member->type);
12278 size = regc_max_size(state, classes);
12280 /* Find how many registers we allow this value to
12283 info = arch_reg_lhs(state, cset->member, 0);
12284 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
12285 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12286 cur_size = regc_max_size(state, info.regcm);
12290 /* If this live_range feeds into conflict->ins
12291 * splitting it is unlikely to help.
12293 for(set = cset->member->use; set; set = set->next) {
12294 if (set->member == conflict->ins) {
12299 /* If there is no difference between potential and
12300 * actual register count there is nothing to do.
12302 if (cur_size >= size) {
12305 /* Of the constrained registers deal with the
12306 * most constrained one first.
12308 if (!constrained ||
12309 (size < constrained_size)) {
12310 constrained = cset->member;
12311 constrained_size = size;
12317 new = post_copy(state, constrained);
12318 new->id |= TRIPLE_FLAG_POST_SPLIT;
12323 static int split_ranges(
12324 struct compile_state *state, struct reg_state *rstate,
12325 char *used, struct live_range *range)
12327 struct triple *new;
12329 if ((range->color == REG_UNNEEDED) ||
12330 (rstate->passes >= rstate->max_passes)) {
12334 /* If I can't allocate a register something needs to be split */
12335 if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
12336 struct least_conflict conflict;
12338 /* Find where in the set of registers the conflict
12341 find_range_conflict(state, rstate, used, range, &conflict);
12343 /* If a range has been artifically constrained split it */
12344 new = split_constrained_range(state, rstate, used, &conflict);
12347 /* Ideally I would split the live range that will not be used
12348 * for the longest period of time in hopes that this will
12349 * (a) allow me to spill a register or
12350 * (b) allow me to place a value in another register.
12352 * So far I don't have a test case for this, the resolving
12353 * of mandatory constraints has solved all of my
12354 * know issues. So I have choosen not to write any
12355 * code until I cat get a better feel for cases where
12356 * it would be useful to have.
12359 #warning "WISHLIST implement live range splitting..."
12364 rstate->lrd[rstate->defs].orig_id = new->id;
12365 new->id = rstate->defs;
12368 fprintf(stderr, "new: %p\n", new);
12375 #if DEBUG_COLOR_GRAPH > 1
12376 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
12377 #define cgdebug_flush() fflush(stdout)
12378 #elif DEBUG_COLOR_GRAPH == 1
12379 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
12380 #define cgdebug_flush() fflush(stderr)
12382 #define cgdebug_printf(...)
12383 #define cgdebug_flush()
12387 static int select_free_color(struct compile_state *state,
12388 struct reg_state *rstate, struct live_range *range)
12390 struct triple_set *entry;
12391 struct live_range_def *lrd;
12392 struct live_range_def *phi;
12393 struct live_range_edge *edge;
12394 char used[MAX_REGISTERS];
12395 struct triple **expr;
12397 /* Instead of doing just the trivial color select here I try
12398 * a few extra things because a good color selection will help reduce
12402 /* Find the registers currently in use */
12403 memset(used, 0, sizeof(used));
12404 for(edge = range->edges; edge; edge = edge->next) {
12405 if (edge->node->color == REG_UNSET) {
12408 reg_fill_used(state, used, edge->node->color);
12410 #if DEBUG_COLOR_GRAPH > 1
12414 for(edge = range->edges; edge; edge = edge->next) {
12417 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
12418 tops(range->def->op), i,
12419 range->def->filename, range->def->line, range->def->col);
12420 for(i = 0; i < MAX_REGISTERS; i++) {
12422 cgdebug_printf("used: %s\n",
12429 #warning "FIXME detect conflicts caused by the source and destination being the same register"
12431 /* If a color is already assigned see if it will work */
12432 if (range->color != REG_UNSET) {
12433 struct live_range_def *lrd;
12434 if (!used[range->color]) {
12437 for(edge = range->edges; edge; edge = edge->next) {
12438 if (edge->node->color != range->color) {
12441 warning(state, edge->node->defs->def, "edge: ");
12442 lrd = edge->node->defs;
12444 warning(state, lrd->def, " %p %s",
12445 lrd->def, tops(lrd->def->op));
12447 } while(lrd != edge->node->defs);
12450 warning(state, range->defs->def, "def: ");
12452 warning(state, lrd->def, " %p %s",
12453 lrd->def, tops(lrd->def->op));
12455 } while(lrd != range->defs);
12456 internal_error(state, range->defs->def,
12457 "live range with already used color %s",
12458 arch_reg_str(range->color));
12461 /* If I feed into an expression reuse it's color.
12462 * This should help remove copies in the case of 2 register instructions
12463 * and phi functions.
12466 lrd = live_range_end(state, range, 0);
12467 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
12468 entry = lrd->def->use;
12469 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
12470 struct live_range_def *insd;
12471 insd = &rstate->lrd[entry->member->id];
12472 if (insd->lr->defs == 0) {
12475 if (!phi && (insd->def->op == OP_PHI) &&
12476 !interfere(rstate, range, insd->lr)) {
12479 if ((insd->lr->color == REG_UNSET) ||
12480 ((insd->lr->classes & range->classes) == 0) ||
12481 (used[insd->lr->color])) {
12484 if (interfere(rstate, range, insd->lr)) {
12487 range->color = insd->lr->color;
12490 /* If I feed into a phi function reuse it's color or the color
12491 * of something else that feeds into the phi function.
12494 if (phi->lr->color != REG_UNSET) {
12495 if (used[phi->lr->color]) {
12496 range->color = phi->lr->color;
12500 expr = triple_rhs(state, phi->def, 0);
12501 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
12502 struct live_range *lr;
12506 lr = rstate->lrd[(*expr)->id].lr;
12507 if ((lr->color == REG_UNSET) ||
12508 ((lr->classes & range->classes) == 0) ||
12509 (used[lr->color])) {
12512 if (interfere(rstate, range, lr)) {
12515 range->color = lr->color;
12519 /* If I don't interfere with a rhs node reuse it's color */
12520 lrd = live_range_head(state, range, 0);
12521 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
12522 expr = triple_rhs(state, lrd->def, 0);
12523 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
12524 struct live_range *lr;
12528 lr = rstate->lrd[(*expr)->id].lr;
12529 if ((lr->color == -1) ||
12530 ((lr->classes & range->classes) == 0) ||
12531 (used[lr->color])) {
12534 if (interfere(rstate, range, lr)) {
12537 range->color = lr->color;
12541 /* If I have not opportunitically picked a useful color
12542 * pick the first color that is free.
12544 if (range->color == REG_UNSET) {
12546 arch_select_free_register(state, used, range->classes);
12548 if (range->color == REG_UNSET) {
12550 if (split_ranges(state, rstate, used, range)) {
12553 for(edge = range->edges; edge; edge = edge->next) {
12554 if (edge->node->color == REG_UNSET) {
12557 warning(state, edge->node->defs->def, "reg %s",
12558 arch_reg_str(edge->node->color));
12560 warning(state, range->defs->def, "classes: %x",
12562 for(i = 0; i < MAX_REGISTERS; i++) {
12564 warning(state, range->defs->def, "used: %s",
12568 #if DEBUG_COLOR_GRAPH < 2
12569 error(state, range->defs->def, "too few registers");
12571 internal_error(state, range->defs->def, "too few registers");
12574 range->classes = arch_reg_regcm(state, range->color);
12575 if (range->color == -1) {
12576 internal_error(state, range->defs->def, "select_free_color did not?");
12581 static int color_graph(struct compile_state *state, struct reg_state *rstate)
12584 struct live_range_edge *edge;
12585 struct live_range *range;
12587 cgdebug_printf("Lo: ");
12588 range = rstate->low;
12589 if (*range->group_prev != range) {
12590 internal_error(state, 0, "lo: *prev != range?");
12592 *range->group_prev = range->group_next;
12593 if (range->group_next) {
12594 range->group_next->group_prev = range->group_prev;
12596 if (&range->group_next == rstate->low_tail) {
12597 rstate->low_tail = range->group_prev;
12599 if (rstate->low == range) {
12600 internal_error(state, 0, "low: next != prev?");
12603 else if (rstate->high) {
12604 cgdebug_printf("Hi: ");
12605 range = rstate->high;
12606 if (*range->group_prev != range) {
12607 internal_error(state, 0, "hi: *prev != range?");
12609 *range->group_prev = range->group_next;
12610 if (range->group_next) {
12611 range->group_next->group_prev = range->group_prev;
12613 if (&range->group_next == rstate->high_tail) {
12614 rstate->high_tail = range->group_prev;
12616 if (rstate->high == range) {
12617 internal_error(state, 0, "high: next != prev?");
12623 cgdebug_printf(" %d\n", range - rstate->lr);
12624 range->group_prev = 0;
12625 for(edge = range->edges; edge; edge = edge->next) {
12626 struct live_range *node;
12628 /* Move nodes from the high to the low list */
12629 if (node->group_prev && (node->color == REG_UNSET) &&
12630 (node->degree == regc_max_size(state, node->classes))) {
12631 if (*node->group_prev != node) {
12632 internal_error(state, 0, "move: *prev != node?");
12634 *node->group_prev = node->group_next;
12635 if (node->group_next) {
12636 node->group_next->group_prev = node->group_prev;
12638 if (&node->group_next == rstate->high_tail) {
12639 rstate->high_tail = node->group_prev;
12641 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
12642 node->group_prev = rstate->low_tail;
12643 node->group_next = 0;
12644 *rstate->low_tail = node;
12645 rstate->low_tail = &node->group_next;
12646 if (*node->group_prev != node) {
12647 internal_error(state, 0, "move2: *prev != node?");
12652 colored = color_graph(state, rstate);
12654 cgdebug_printf("Coloring %d @%s:%d.%d:",
12655 range - rstate->lr,
12656 range->def->filename, range->def->line, range->def->col);
12658 colored = select_free_color(state, rstate, range);
12659 cgdebug_printf(" %s\n", arch_reg_str(range->color));
12664 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
12666 struct live_range *lr;
12667 struct live_range_edge *edge;
12668 struct triple *ins, *first;
12669 char used[MAX_REGISTERS];
12670 first = RHS(state->main_function, 0);
12673 if (triple_is_def(state, ins)) {
12674 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12675 internal_error(state, ins,
12676 "triple without a live range def");
12678 lr = rstate->lrd[ins->id].lr;
12679 if (lr->color == REG_UNSET) {
12680 internal_error(state, ins,
12681 "triple without a color");
12683 /* Find the registers used by the edges */
12684 memset(used, 0, sizeof(used));
12685 for(edge = lr->edges; edge; edge = edge->next) {
12686 if (edge->node->color == REG_UNSET) {
12687 internal_error(state, 0,
12688 "live range without a color");
12690 reg_fill_used(state, used, edge->node->color);
12692 if (used[lr->color]) {
12693 internal_error(state, ins,
12694 "triple with already used color");
12698 } while(ins != first);
12701 static void color_triples(struct compile_state *state, struct reg_state *rstate)
12703 struct live_range *lr;
12704 struct triple *first, *ins;
12705 first = RHS(state->main_function, 0);
12708 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12709 internal_error(state, ins,
12710 "triple without a live range");
12712 lr = rstate->lrd[ins->id].lr;
12713 SET_REG(ins->id, lr->color);
12715 } while (ins != first);
12718 static void print_interference_block(
12719 struct compile_state *state, struct block *block, void *arg)
12722 struct reg_state *rstate = arg;
12723 struct reg_block *rb;
12724 struct triple *ptr;
12727 rb = &rstate->blocks[block->vertex];
12729 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
12733 block->left && block->left->use?block->left->use->member : 0,
12735 block->right && block->right->use?block->right->use->member : 0);
12737 struct triple_reg_set *in_set;
12739 for(in_set = rb->in; in_set; in_set = in_set->next) {
12740 printf(" %-10p", in_set->member);
12745 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12746 done = (ptr == block->last);
12747 if (ptr->op == OP_PHI) {
12754 for(edge = 0; edge < block->users; edge++) {
12755 printf(" in(%d):", edge);
12756 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12757 struct triple **slot;
12758 done = (ptr == block->last);
12759 if (ptr->op != OP_PHI) {
12762 slot = &RHS(ptr, 0);
12763 printf(" %-10p", slot[edge]);
12768 if (block->first->op == OP_LABEL) {
12769 printf("%p:\n", block->first);
12771 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12772 struct triple_set *user;
12773 struct live_range *lr;
12777 done = (ptr == block->last);
12778 lr = rstate->lrd[ptr->id].lr;
12780 if (triple_stores_block(state, ptr)) {
12781 if (ptr->u.block != block) {
12782 internal_error(state, ptr,
12783 "Wrong block pointer: %p",
12787 if (op == OP_ADECL) {
12788 for(user = ptr->use; user; user = user->next) {
12789 if (!user->member->u.block) {
12790 internal_error(state, user->member,
12791 "Use %p not in a block?",
12798 SET_REG(ptr->id, lr->color);
12799 display_triple(stdout, ptr);
12802 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
12803 internal_error(state, ptr, "lr has no defs!");
12807 struct live_range_def *lrd;
12811 printf(" %-10p", lrd->def);
12813 } while(lrd != lr->defs);
12816 if (lr->edges > 0) {
12817 struct live_range_edge *edge;
12819 for(edge = lr->edges; edge; edge = edge->next) {
12820 struct live_range_def *lrd;
12821 lrd = edge->node->defs;
12823 printf(" %-10p", lrd->def);
12825 } while(lrd != edge->node->defs);
12830 /* Do a bunch of sanity checks */
12831 valid_ins(state, ptr);
12832 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
12833 internal_error(state, ptr, "Invalid triple id: %d",
12836 for(user = ptr->use; user; user = user->next) {
12837 struct triple *use;
12838 struct live_range *ulr;
12839 use = user->member;
12840 valid_ins(state, use);
12841 if ((use->id < 0) || (use->id > rstate->defs)) {
12842 internal_error(state, use, "Invalid triple id: %d",
12845 ulr = rstate->lrd[user->member->id].lr;
12846 if (triple_stores_block(state, user->member) &&
12847 !user->member->u.block) {
12848 internal_error(state, user->member,
12849 "Use %p not in a block?",
12855 struct triple_reg_set *out_set;
12857 for(out_set = rb->out; out_set; out_set = out_set->next) {
12858 printf(" %-10p", out_set->member);
12865 static struct live_range *merge_sort_lr(
12866 struct live_range *first, struct live_range *last)
12868 struct live_range *mid, *join, **join_tail, *pick;
12870 size = (last - first) + 1;
12872 mid = first + size/2;
12873 first = merge_sort_lr(first, mid -1);
12874 mid = merge_sort_lr(mid, last);
12878 /* merge the two lists */
12879 while(first && mid) {
12880 if ((first->degree < mid->degree) ||
12881 ((first->degree == mid->degree) &&
12882 (first->length < mid->length))) {
12884 first = first->group_next;
12886 first->group_prev = 0;
12891 mid = mid->group_next;
12893 mid->group_prev = 0;
12896 pick->group_next = 0;
12897 pick->group_prev = join_tail;
12899 join_tail = &pick->group_next;
12901 /* Splice the remaining list */
12902 pick = (first)? first : mid;
12905 pick->group_prev = join_tail;
12909 if (!first->defs) {
12917 static void ids_from_rstate(struct compile_state *state,
12918 struct reg_state *rstate)
12920 struct triple *ins, *first;
12921 if (!rstate->defs) {
12924 /* Display the graph if desired */
12925 if (state->debug & DEBUG_INTERFERENCE) {
12926 print_blocks(state, stdout);
12927 print_control_flow(state);
12929 first = RHS(state->main_function, 0);
12933 struct live_range_def *lrd;
12934 lrd = &rstate->lrd[ins->id];
12935 ins->id = lrd->orig_id;
12938 } while(ins != first);
12941 static void cleanup_live_edges(struct reg_state *rstate)
12944 /* Free the edges on each node */
12945 for(i = 1; i <= rstate->ranges; i++) {
12946 remove_live_edges(rstate, &rstate->lr[i]);
12950 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
12952 cleanup_live_edges(rstate);
12953 xfree(rstate->lrd);
12956 /* Free the variable lifetime information */
12957 if (rstate->blocks) {
12958 free_variable_lifetimes(state, rstate->blocks);
12961 rstate->ranges = 0;
12964 rstate->blocks = 0;
12967 static void allocate_registers(struct compile_state *state)
12969 struct reg_state rstate;
12972 /* Clear out the reg_state */
12973 memset(&rstate, 0, sizeof(rstate));
12974 rstate.max_passes = MAX_ALLOCATION_PASSES;
12977 struct live_range **point, **next;
12978 struct triple *tangle;
12979 struct coalesce_conflict conflict;
12983 ids_from_rstate(state, &rstate);
12986 /* Cleanup the temporary data structures */
12987 cleanup_rstate(state, &rstate);
12989 /* Compute the variable lifetimes */
12990 rstate.blocks = compute_variable_lifetimes(state);
12992 /* Find an invalid mandatory live range coalesce */
12994 conflict.index = -1;
12995 walk_variable_lifetimes(
12996 state, rstate.blocks, spot_coalesce_conflict, &conflict);
12998 /* If a tangle was found resolve it */
12999 if (conflict.ins) {
13000 resolve_coalesce_conflict(state, &conflict);
13002 } while(conflict.ins);
13005 /* Cleanup the temporary data structures */
13006 cleanup_rstate(state, &rstate);
13008 /* Compute the variable lifetimes */
13009 rstate.blocks = compute_variable_lifetimes(state);
13011 /* Find two simultaneous uses of the same register */
13013 walk_variable_lifetimes(
13014 state, rstate.blocks, spot_tangle, &tangle);
13016 /* If a tangle was found resolve it */
13018 resolve_tangle(state, tangle);
13022 if (state->debug & DEBUG_INSERTED_COPIES) {
13023 printf("After resolve_tangles\n");
13024 print_blocks(state, stdout);
13025 print_control_flow(state);
13029 /* Allocate and initialize the live ranges */
13030 initialize_live_ranges(state, &rstate);
13033 /* Forget previous live range edge calculations */
13034 cleanup_live_edges(&rstate);
13036 /* Compute the interference graph */
13037 walk_variable_lifetimes(
13038 state, rstate.blocks, graph_ins, &rstate);
13040 /* Display the interference graph if desired */
13041 if (state->debug & DEBUG_INTERFERENCE) {
13042 printf("\nlive variables by block\n");
13043 walk_blocks(state, print_interference_block, &rstate);
13044 printf("\nlive variables by instruction\n");
13045 walk_variable_lifetimes(
13046 state, rstate.blocks,
13047 print_interference_ins, &rstate);
13050 coalesced = coalesce_live_ranges(state, &rstate);
13051 } while(coalesced);
13053 /* Build the groups low and high. But with the nodes
13054 * first sorted by degree order.
13056 rstate.low_tail = &rstate.low;
13057 rstate.high_tail = &rstate.high;
13058 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13060 rstate.high->group_prev = &rstate.high;
13062 for(point = &rstate.high; *point; point = &(*point)->group_next)
13064 rstate.high_tail = point;
13065 /* Walk through the high list and move everything that needs
13068 for(point = &rstate.high; *point; point = next) {
13069 struct live_range *range;
13070 next = &(*point)->group_next;
13073 /* If it has a low degree or it already has a color
13074 * place the node in low.
13076 if ((range->degree < regc_max_size(state, range->classes)) ||
13077 (range->color != REG_UNSET)) {
13078 cgdebug_printf("Lo: %5d degree %5d%s\n",
13079 range - rstate.lr, range->degree,
13080 (range->color != REG_UNSET) ? " (colored)": "");
13081 *range->group_prev = range->group_next;
13082 if (range->group_next) {
13083 range->group_next->group_prev = range->group_prev;
13085 if (&range->group_next == rstate.high_tail) {
13086 rstate.high_tail = range->group_prev;
13088 range->group_prev = rstate.low_tail;
13089 range->group_next = 0;
13090 *rstate.low_tail = range;
13091 rstate.low_tail = &range->group_next;
13095 cgdebug_printf("hi: %5d degree %5d%s\n",
13096 range - rstate.lr, range->degree,
13097 (range->color != REG_UNSET) ? " (colored)": "");
13100 /* Color the live_ranges */
13101 colored = color_graph(state, &rstate);
13103 } while (!colored);
13105 /* Verify the graph was properly colored */
13106 verify_colors(state, &rstate);
13108 /* Move the colors from the graph to the triples */
13109 color_triples(state, &rstate);
13111 /* Cleanup the temporary data structures */
13112 cleanup_rstate(state, &rstate);
13115 /* Sparce Conditional Constant Propogation
13116 * =========================================
13120 struct lattice_node {
13122 struct triple *def;
13123 struct ssa_edge *out;
13124 struct flow_block *fblock;
13125 struct triple *val;
13126 /* lattice high val && !is_const(val)
13127 * lattice const is_const(val)
13128 * lattice low val == 0
13132 struct lattice_node *src;
13133 struct lattice_node *dst;
13134 struct ssa_edge *work_next;
13135 struct ssa_edge *work_prev;
13136 struct ssa_edge *out_next;
13139 struct flow_block *src;
13140 struct flow_block *dst;
13141 struct flow_edge *work_next;
13142 struct flow_edge *work_prev;
13143 struct flow_edge *in_next;
13144 struct flow_edge *out_next;
13147 struct flow_block {
13148 struct block *block;
13149 struct flow_edge *in;
13150 struct flow_edge *out;
13151 struct flow_edge left, right;
13156 struct lattice_node *lattice;
13157 struct ssa_edge *ssa_edges;
13158 struct flow_block *flow_blocks;
13159 struct flow_edge *flow_work_list;
13160 struct ssa_edge *ssa_work_list;
13164 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13165 struct flow_edge *fedge)
13167 if (!scc->flow_work_list) {
13168 scc->flow_work_list = fedge;
13169 fedge->work_next = fedge->work_prev = fedge;
13172 struct flow_edge *ftail;
13173 ftail = scc->flow_work_list->work_prev;
13174 fedge->work_next = ftail->work_next;
13175 fedge->work_prev = ftail;
13176 fedge->work_next->work_prev = fedge;
13177 fedge->work_prev->work_next = fedge;
13181 static struct flow_edge *scc_next_fedge(
13182 struct compile_state *state, struct scc_state *scc)
13184 struct flow_edge *fedge;
13185 fedge = scc->flow_work_list;
13187 fedge->work_next->work_prev = fedge->work_prev;
13188 fedge->work_prev->work_next = fedge->work_next;
13189 if (fedge->work_next != fedge) {
13190 scc->flow_work_list = fedge->work_next;
13192 scc->flow_work_list = 0;
13198 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13199 struct ssa_edge *sedge)
13201 if (!scc->ssa_work_list) {
13202 scc->ssa_work_list = sedge;
13203 sedge->work_next = sedge->work_prev = sedge;
13206 struct ssa_edge *stail;
13207 stail = scc->ssa_work_list->work_prev;
13208 sedge->work_next = stail->work_next;
13209 sedge->work_prev = stail;
13210 sedge->work_next->work_prev = sedge;
13211 sedge->work_prev->work_next = sedge;
13215 static struct ssa_edge *scc_next_sedge(
13216 struct compile_state *state, struct scc_state *scc)
13218 struct ssa_edge *sedge;
13219 sedge = scc->ssa_work_list;
13221 sedge->work_next->work_prev = sedge->work_prev;
13222 sedge->work_prev->work_next = sedge->work_next;
13223 if (sedge->work_next != sedge) {
13224 scc->ssa_work_list = sedge->work_next;
13226 scc->ssa_work_list = 0;
13232 static void initialize_scc_state(
13233 struct compile_state *state, struct scc_state *scc)
13235 int ins_count, ssa_edge_count;
13236 int ins_index, ssa_edge_index, fblock_index;
13237 struct triple *first, *ins;
13238 struct block *block;
13239 struct flow_block *fblock;
13241 memset(scc, 0, sizeof(*scc));
13243 /* Inialize pass zero find out how much memory we need */
13244 first = RHS(state->main_function, 0);
13246 ins_count = ssa_edge_count = 0;
13248 struct triple_set *edge;
13250 for(edge = ins->use; edge; edge = edge->next) {
13254 } while(ins != first);
13256 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13257 ins_count, ssa_edge_count, state->last_vertex);
13259 scc->ins_count = ins_count;
13261 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13263 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13265 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
13268 /* Initialize pass one collect up the nodes */
13271 ins_index = ssa_edge_index = fblock_index = 0;
13274 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13275 block = ins->u.block;
13277 internal_error(state, ins, "label without block");
13280 block->vertex = fblock_index;
13281 fblock = &scc->flow_blocks[fblock_index];
13282 fblock->block = block;
13285 struct lattice_node *lnode;
13287 lnode = &scc->lattice[ins_index];
13290 lnode->fblock = fblock;
13291 lnode->val = ins; /* LATTICE HIGH */
13292 lnode->old_id = ins->id;
13293 ins->id = ins_index;
13296 } while(ins != first);
13297 /* Initialize pass two collect up the edges */
13302 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13303 struct flow_edge *fedge, **ftail;
13304 struct block_set *bedge;
13305 block = ins->u.block;
13306 fblock = &scc->flow_blocks[block->vertex];
13309 ftail = &fblock->out;
13311 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13312 if (fblock->left.dst->block != block->left) {
13313 internal_error(state, 0, "block mismatch");
13315 fblock->left.out_next = 0;
13316 *ftail = &fblock->left;
13317 ftail = &fblock->left.out_next;
13319 if (block->right) {
13320 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13321 if (fblock->right.dst->block != block->right) {
13322 internal_error(state, 0, "block mismatch");
13324 fblock->right.out_next = 0;
13325 *ftail = &fblock->right;
13326 ftail = &fblock->right.out_next;
13328 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13329 fedge->src = fblock;
13330 fedge->work_next = fedge->work_prev = fedge;
13331 fedge->executable = 0;
13333 ftail = &fblock->in;
13334 for(bedge = block->use; bedge; bedge = bedge->next) {
13335 struct block *src_block;
13336 struct flow_block *sfblock;
13337 struct flow_edge *sfedge;
13338 src_block = bedge->member;
13339 sfblock = &scc->flow_blocks[src_block->vertex];
13341 if (src_block->left == block) {
13342 sfedge = &sfblock->left;
13344 sfedge = &sfblock->right;
13347 ftail = &sfedge->in_next;
13348 sfedge->in_next = 0;
13352 struct triple_set *edge;
13353 struct ssa_edge **stail;
13354 struct lattice_node *lnode;
13355 lnode = &scc->lattice[ins->id];
13357 stail = &lnode->out;
13358 for(edge = ins->use; edge; edge = edge->next) {
13359 struct ssa_edge *sedge;
13360 ssa_edge_index += 1;
13361 sedge = &scc->ssa_edges[ssa_edge_index];
13363 stail = &sedge->out_next;
13364 sedge->src = lnode;
13365 sedge->dst = &scc->lattice[edge->member->id];
13366 sedge->work_next = sedge->work_prev = sedge;
13367 sedge->out_next = 0;
13371 } while(ins != first);
13372 /* Setup a dummy block 0 as a node above the start node */
13374 struct flow_block *fblock, *dst;
13375 struct flow_edge *fedge;
13376 fblock = &scc->flow_blocks[0];
13379 fblock->out = &fblock->left;
13380 dst = &scc->flow_blocks[state->first_block->vertex];
13381 fedge = &fblock->left;
13382 fedge->src = fblock;
13384 fedge->work_next = fedge;
13385 fedge->work_prev = fedge;
13386 fedge->in_next = fedge->dst->in;
13387 fedge->out_next = 0;
13388 fedge->executable = 0;
13389 fedge->dst->in = fedge;
13391 /* Initialize the work lists */
13392 scc->flow_work_list = 0;
13393 scc->ssa_work_list = 0;
13394 scc_add_fedge(state, scc, fedge);
13397 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
13398 ins_index, ssa_edge_index, fblock_index);
13403 static void free_scc_state(
13404 struct compile_state *state, struct scc_state *scc)
13406 xfree(scc->flow_blocks);
13407 xfree(scc->ssa_edges);
13408 xfree(scc->lattice);
13412 static struct lattice_node *triple_to_lattice(
13413 struct compile_state *state, struct scc_state *scc, struct triple *ins)
13415 if (ins->id <= 0) {
13416 internal_error(state, ins, "bad id");
13418 return &scc->lattice[ins->id];
13421 static struct triple *preserve_lval(
13422 struct compile_state *state, struct lattice_node *lnode)
13424 struct triple *old;
13425 /* Preserve the original value */
13427 old = dup_triple(state, lnode->val);
13428 if (lnode->val != lnode->def) {
13438 static int lval_changed(struct compile_state *state,
13439 struct triple *old, struct lattice_node *lnode)
13442 /* See if the lattice value has changed */
13444 if (!old && !lnode->val) {
13447 if (changed && lnode->val && !is_const(lnode->val)) {
13451 lnode->val && old &&
13452 (memcmp(lnode->val->param, old->param,
13453 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
13454 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
13464 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
13465 struct lattice_node *lnode)
13467 struct lattice_node *tmp;
13468 struct triple **slot, *old;
13469 struct flow_edge *fedge;
13471 if (lnode->def->op != OP_PHI) {
13472 internal_error(state, lnode->def, "not phi");
13474 /* Store the original value */
13475 old = preserve_lval(state, lnode);
13477 /* default to lattice high */
13478 lnode->val = lnode->def;
13479 slot = &RHS(lnode->def, 0);
13481 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
13482 if (!fedge->executable) {
13485 if (!slot[index]) {
13486 internal_error(state, lnode->def, "no phi value");
13488 tmp = triple_to_lattice(state, scc, slot[index]);
13489 /* meet(X, lattice low) = lattice low */
13493 /* meet(X, lattice high) = X */
13494 else if (!tmp->val) {
13495 lnode->val = lnode->val;
13497 /* meet(lattice high, X) = X */
13498 else if (!is_const(lnode->val)) {
13499 lnode->val = dup_triple(state, tmp->val);
13500 lnode->val->type = lnode->def->type;
13502 /* meet(const, const) = const or lattice low */
13503 else if (!constants_equal(state, lnode->val, tmp->val)) {
13511 fprintf(stderr, "phi: %d -> %s\n",
13513 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13515 /* If the lattice value has changed update the work lists. */
13516 if (lval_changed(state, old, lnode)) {
13517 struct ssa_edge *sedge;
13518 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13519 scc_add_sedge(state, scc, sedge);
13524 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
13525 struct lattice_node *lnode)
13528 struct triple *old, *scratch;
13529 struct triple **dexpr, **vexpr;
13532 /* Store the original value */
13533 old = preserve_lval(state, lnode);
13535 /* Reinitialize the value */
13536 lnode->val = scratch = dup_triple(state, lnode->def);
13537 scratch->id = lnode->old_id;
13538 scratch->next = scratch;
13539 scratch->prev = scratch;
13542 count = TRIPLE_SIZE(scratch->sizes);
13543 for(i = 0; i < count; i++) {
13544 dexpr = &lnode->def->param[i];
13545 vexpr = &scratch->param[i];
13547 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13548 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13550 struct lattice_node *tmp;
13551 tmp = triple_to_lattice(state, scc, *dexpr);
13552 *vexpr = (tmp->val)? tmp->val : tmp->def;
13555 if (scratch->op == OP_BRANCH) {
13556 scratch->next = lnode->def->next;
13558 /* Recompute the value */
13559 #warning "FIXME see if simplify does anything bad"
13560 /* So far it looks like only the strength reduction
13561 * optimization are things I need to worry about.
13563 simplify(state, scratch);
13564 /* Cleanup my value */
13565 if (scratch->use) {
13566 internal_error(state, lnode->def, "scratch used?");
13568 if ((scratch->prev != scratch) ||
13569 ((scratch->next != scratch) &&
13570 ((lnode->def->op != OP_BRANCH) ||
13571 (scratch->next != lnode->def->next)))) {
13572 internal_error(state, lnode->def, "scratch in list?");
13574 /* undo any uses... */
13575 count = TRIPLE_SIZE(scratch->sizes);
13576 for(i = 0; i < count; i++) {
13577 vexpr = &scratch->param[i];
13579 unuse_triple(*vexpr, scratch);
13582 if (!is_const(scratch)) {
13583 for(i = 0; i < count; i++) {
13584 dexpr = &lnode->def->param[i];
13585 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13586 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13588 struct lattice_node *tmp;
13589 tmp = triple_to_lattice(state, scc, *dexpr);
13597 (lnode->val->op == lnode->def->op) &&
13598 (memcmp(lnode->val->param, lnode->def->param,
13599 count * sizeof(lnode->val->param[0])) == 0) &&
13600 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
13601 lnode->val = lnode->def;
13603 /* Find the cases that are always lattice lo */
13605 triple_is_def(state, lnode->val) &&
13606 !triple_is_pure(state, lnode->val)) {
13610 (lnode->val->op == OP_SDECL) &&
13611 (lnode->val != lnode->def)) {
13612 internal_error(state, lnode->def, "bad sdecl");
13614 /* See if the lattice value has changed */
13615 changed = lval_changed(state, old, lnode);
13616 if (lnode->val != scratch) {
13622 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
13623 struct lattice_node *lnode)
13625 struct lattice_node *cond;
13628 struct flow_edge *fedge;
13629 fprintf(stderr, "branch: %d (",
13632 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
13633 fprintf(stderr, " %d", fedge->dst->block->vertex);
13635 fprintf(stderr, " )");
13636 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
13637 fprintf(stderr, " <- %d",
13638 RHS(lnode->def, 0)->id);
13640 fprintf(stderr, "\n");
13643 if (lnode->def->op != OP_BRANCH) {
13644 internal_error(state, lnode->def, "not branch");
13646 /* This only applies to conditional branches */
13647 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
13650 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
13651 if (cond->val && !is_const(cond->val)) {
13652 #warning "FIXME do I need to do something here?"
13653 warning(state, cond->def, "condition not constant?");
13656 if (cond->val == 0) {
13657 scc_add_fedge(state, scc, cond->fblock->out);
13658 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13660 else if (cond->val->u.cval) {
13661 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13664 scc_add_fedge(state, scc, cond->fblock->out);
13669 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
13670 struct lattice_node *lnode)
13674 changed = compute_lnode_val(state, scc, lnode);
13677 struct triple **expr;
13678 fprintf(stderr, "expr: %3d %10s (",
13679 lnode->def->id, tops(lnode->def->op));
13680 expr = triple_rhs(state, lnode->def, 0);
13681 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
13683 fprintf(stderr, " %d", (*expr)->id);
13686 fprintf(stderr, " ) -> %s\n",
13687 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13690 if (lnode->def->op == OP_BRANCH) {
13691 scc_visit_branch(state, scc, lnode);
13694 else if (changed) {
13695 struct ssa_edge *sedge;
13696 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13697 scc_add_sedge(state, scc, sedge);
13702 static void scc_writeback_values(
13703 struct compile_state *state, struct scc_state *scc)
13705 struct triple *first, *ins;
13706 first = RHS(state->main_function, 0);
13709 struct lattice_node *lnode;
13710 lnode = triple_to_lattice(state, scc, ins);
13712 ins->id = lnode->old_id;
13714 if (lnode->val && !is_const(lnode->val)) {
13715 warning(state, lnode->def,
13716 "lattice node still high?");
13719 if (lnode->val && (lnode->val != ins)) {
13720 /* See if it something I know how to write back */
13721 switch(lnode->val->op) {
13723 mkconst(state, ins, lnode->val->u.cval);
13726 mkaddr_const(state, ins,
13727 MISC(lnode->val, 0), lnode->val->u.cval);
13730 /* By default don't copy the changes,
13731 * recompute them in place instead.
13733 simplify(state, ins);
13736 if (is_const(lnode->val) &&
13737 !constants_equal(state, lnode->val, ins)) {
13738 internal_error(state, 0, "constants not equal");
13740 /* Free the lattice nodes */
13745 } while(ins != first);
13748 static void scc_transform(struct compile_state *state)
13750 struct scc_state scc;
13752 initialize_scc_state(state, &scc);
13754 while(scc.flow_work_list || scc.ssa_work_list) {
13755 struct flow_edge *fedge;
13756 struct ssa_edge *sedge;
13757 struct flow_edge *fptr;
13758 while((fedge = scc_next_fedge(state, &scc))) {
13759 struct block *block;
13760 struct triple *ptr;
13761 struct flow_block *fblock;
13764 if (fedge->executable) {
13768 internal_error(state, 0, "fedge without dst");
13771 internal_error(state, 0, "fedge without src");
13773 fedge->executable = 1;
13774 fblock = fedge->dst;
13775 block = fblock->block;
13777 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
13778 if (fptr->executable) {
13783 fprintf(stderr, "vertex: %d time: %d\n",
13784 block->vertex, time);
13788 for(ptr = block->first; !done; ptr = ptr->next) {
13789 struct lattice_node *lnode;
13790 done = (ptr == block->last);
13791 lnode = &scc.lattice[ptr->id];
13792 if (ptr->op == OP_PHI) {
13793 scc_visit_phi(state, &scc, lnode);
13795 else if (time == 1) {
13796 scc_visit_expr(state, &scc, lnode);
13799 if (fblock->out && !fblock->out->out_next) {
13800 scc_add_fedge(state, &scc, fblock->out);
13803 while((sedge = scc_next_sedge(state, &scc))) {
13804 struct lattice_node *lnode;
13805 struct flow_block *fblock;
13806 lnode = sedge->dst;
13807 fblock = lnode->fblock;
13809 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
13810 sedge - scc.ssa_edges,
13811 sedge->src->def->id,
13812 sedge->dst->def->id);
13814 if (lnode->def->op == OP_PHI) {
13815 scc_visit_phi(state, &scc, lnode);
13818 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
13819 if (fptr->executable) {
13824 scc_visit_expr(state, &scc, lnode);
13830 scc_writeback_values(state, &scc);
13831 free_scc_state(state, &scc);
13835 static void transform_to_arch_instructions(struct compile_state *state)
13837 struct triple *ins, *first;
13838 first = RHS(state->main_function, 0);
13841 ins = transform_to_arch_instruction(state, ins);
13842 } while(ins != first);
13845 #if DEBUG_CONSISTENCY
13846 static void verify_uses(struct compile_state *state)
13848 struct triple *first, *ins;
13849 struct triple_set *set;
13850 first = RHS(state->main_function, 0);
13853 struct triple **expr;
13854 expr = triple_rhs(state, ins, 0);
13855 for(; expr; expr = triple_rhs(state, ins, expr)) {
13856 for(set = *expr?(*expr)->use:0; set; set = set->next) {
13857 if (set->member == ins) {
13862 internal_error(state, ins, "rhs not used");
13865 expr = triple_lhs(state, ins, 0);
13866 for(; expr; expr = triple_lhs(state, ins, expr)) {
13867 for(set = *expr?(*expr)->use:0; set; set = set->next) {
13868 if (set->member == ins) {
13873 internal_error(state, ins, "lhs not used");
13877 } while(ins != first);
13880 static void verify_blocks(struct compile_state *state)
13882 struct triple *ins;
13883 struct block *block;
13884 block = state->first_block;
13889 for(ins = block->first; ins != block->last->next; ins = ins->next) {
13890 if (!triple_stores_block(state, ins)) {
13893 if (ins->u.block != block) {
13894 internal_error(state, ins, "inconsitent block specified");
13897 if (!triple_stores_block(state, block->last->next)) {
13898 internal_error(state, block->last->next,
13899 "cannot find next block");
13901 block = block->last->next->u.block;
13903 internal_error(state, block->last->next,
13906 } while(block != state->first_block);
13909 static void verify_domination(struct compile_state *state)
13911 struct triple *first, *ins;
13912 struct triple_set *set;
13913 if (!state->first_block) {
13917 first = RHS(state->main_function, 0);
13920 for(set = ins->use; set; set = set->next) {
13921 struct triple **expr;
13922 if (set->member->op == OP_PHI) {
13925 /* See if the use is on the righ hand side */
13926 expr = triple_rhs(state, set->member, 0);
13927 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
13928 if (*expr == ins) {
13933 !tdominates(state, ins, set->member)) {
13934 internal_error(state, set->member,
13935 "non dominated rhs use?");
13939 } while(ins != first);
13942 static void verify_piece(struct compile_state *state)
13944 struct triple *first, *ins;
13945 first = RHS(state->main_function, 0);
13948 struct triple *ptr;
13950 lhs = TRIPLE_LHS(ins->sizes);
13951 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
13954 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
13955 if (ptr != LHS(ins, i)) {
13956 internal_error(state, ins, "malformed lhs on %s",
13959 if (ptr->op != OP_PIECE) {
13960 internal_error(state, ins, "bad lhs op %s at %d on %s",
13961 tops(ptr->op), i, tops(ins->op));
13963 if (ptr->u.cval != i) {
13964 internal_error(state, ins, "bad u.cval of %d %d expected",
13969 } while(ins != first);
13971 static void verify_ins_colors(struct compile_state *state)
13973 struct triple *first, *ins;
13975 first = RHS(state->main_function, 0);
13979 } while(ins != first);
13981 static void verify_consistency(struct compile_state *state)
13983 verify_uses(state);
13984 verify_blocks(state);
13985 verify_domination(state);
13986 verify_piece(state);
13987 verify_ins_colors(state);
13990 #define verify_consistency(state) do {} while(0)
13991 #endif /* DEBUG_USES */
13993 static void optimize(struct compile_state *state)
13995 if (state->debug & DEBUG_TRIPLES) {
13996 print_triples(state);
13998 /* Replace structures with simpler data types */
13999 flatten_structures(state);
14000 if (state->debug & DEBUG_TRIPLES) {
14001 print_triples(state);
14003 verify_consistency(state);
14004 /* Analize the intermediate code */
14005 setup_basic_blocks(state);
14006 analyze_idominators(state);
14007 analyze_ipdominators(state);
14008 /* Transform the code to ssa form */
14009 transform_to_ssa_form(state);
14010 verify_consistency(state);
14011 if (state->debug & DEBUG_CODE_ELIMINATION) {
14012 fprintf(stdout, "After transform_to_ssa_form\n");
14013 print_blocks(state, stdout);
14015 /* Do strength reduction and simple constant optimizations */
14016 if (state->optimize >= 1) {
14017 simplify_all(state);
14019 verify_consistency(state);
14020 /* Propogate constants throughout the code */
14021 if (state->optimize >= 2) {
14022 #warning "FIXME fix scc_transform"
14023 scc_transform(state);
14024 transform_from_ssa_form(state);
14025 free_basic_blocks(state);
14026 setup_basic_blocks(state);
14027 analyze_idominators(state);
14028 analyze_ipdominators(state);
14029 transform_to_ssa_form(state);
14031 verify_consistency(state);
14032 #warning "WISHLIST implement single use constants (least possible register pressure)"
14033 #warning "WISHLIST implement induction variable elimination"
14034 /* Select architecture instructions and an initial partial
14035 * coloring based on architecture constraints.
14037 transform_to_arch_instructions(state);
14038 verify_consistency(state);
14039 if (state->debug & DEBUG_ARCH_CODE) {
14040 printf("After transform_to_arch_instructions\n");
14041 print_blocks(state, stdout);
14042 print_control_flow(state);
14044 eliminate_inefectual_code(state);
14045 verify_consistency(state);
14046 if (state->debug & DEBUG_CODE_ELIMINATION) {
14047 printf("After eliminate_inefectual_code\n");
14048 print_blocks(state, stdout);
14049 print_control_flow(state);
14051 verify_consistency(state);
14052 /* Color all of the variables to see if they will fit in registers */
14053 insert_copies_to_phi(state);
14054 if (state->debug & DEBUG_INSERTED_COPIES) {
14055 printf("After insert_copies_to_phi\n");
14056 print_blocks(state, stdout);
14057 print_control_flow(state);
14059 verify_consistency(state);
14060 insert_mandatory_copies(state);
14061 if (state->debug & DEBUG_INSERTED_COPIES) {
14062 printf("After insert_mandatory_copies\n");
14063 print_blocks(state, stdout);
14064 print_control_flow(state);
14066 verify_consistency(state);
14067 allocate_registers(state);
14068 verify_consistency(state);
14069 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14070 print_blocks(state, stdout);
14072 if (state->debug & DEBUG_CONTROL_FLOW) {
14073 print_control_flow(state);
14075 /* Remove the optimization information.
14076 * This is more to check for memory consistency than to free memory.
14078 free_basic_blocks(state);
14081 static void print_op_asm(struct compile_state *state,
14082 struct triple *ins, FILE *fp)
14084 struct asm_info *info;
14086 unsigned lhs, rhs, i;
14087 info = ins->u.ainfo;
14088 lhs = TRIPLE_LHS(ins->sizes);
14089 rhs = TRIPLE_RHS(ins->sizes);
14090 /* Don't count the clobbers in lhs */
14091 for(i = 0; i < lhs; i++) {
14092 if (LHS(ins, i)->type == &void_type) {
14098 for(ptr = info->str; *ptr; ptr++) {
14100 unsigned long param;
14101 struct triple *piece;
14111 param = strtoul(ptr, &next, 10);
14113 error(state, ins, "Invalid asm template");
14115 if (param >= (lhs + rhs)) {
14116 error(state, ins, "Invalid param %%%u in asm template",
14119 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14121 arch_reg_str(ID_REG(piece->id)));
14128 /* Only use the low x86 byte registers. This allows me
14129 * allocate the entire register when a byte register is used.
14131 #define X86_4_8BIT_GPRS 1
14133 /* Recognized x86 cpu variants */
14141 #define CPU_DEFAULT CPU_I386
14143 /* The x86 register classes */
14144 #define REGC_FLAGS 0
14145 #define REGC_GPR8 1
14146 #define REGC_GPR16 2
14147 #define REGC_GPR32 3
14148 #define REGC_GPR64 4
14151 #define REGC_GPR32_8 7
14152 #define REGC_GPR16_8 8
14153 #define REGC_IMM32 9
14154 #define REGC_IMM16 10
14155 #define REGC_IMM8 11
14156 #define LAST_REGC REGC_IMM8
14157 #if LAST_REGC >= MAX_REGC
14158 #error "MAX_REGC is to low"
14161 /* Register class masks */
14162 #define REGCM_FLAGS (1 << REGC_FLAGS)
14163 #define REGCM_GPR8 (1 << REGC_GPR8)
14164 #define REGCM_GPR16 (1 << REGC_GPR16)
14165 #define REGCM_GPR32 (1 << REGC_GPR32)
14166 #define REGCM_GPR64 (1 << REGC_GPR64)
14167 #define REGCM_MMX (1 << REGC_MMX)
14168 #define REGCM_XMM (1 << REGC_XMM)
14169 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14170 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14171 #define REGCM_IMM32 (1 << REGC_IMM32)
14172 #define REGCM_IMM16 (1 << REGC_IMM16)
14173 #define REGCM_IMM8 (1 << REGC_IMM8)
14174 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
14176 /* The x86 registers */
14177 #define REG_EFLAGS 2
14178 #define REGC_FLAGS_FIRST REG_EFLAGS
14179 #define REGC_FLAGS_LAST REG_EFLAGS
14188 #define REGC_GPR8_FIRST REG_AL
14189 #if X86_4_8BIT_GPRS
14190 #define REGC_GPR8_LAST REG_DL
14192 #define REGC_GPR8_LAST REG_DH
14202 #define REGC_GPR16_FIRST REG_AX
14203 #define REGC_GPR16_LAST REG_SP
14212 #define REGC_GPR32_FIRST REG_EAX
14213 #define REGC_GPR32_LAST REG_ESP
14214 #define REG_EDXEAX 27
14215 #define REGC_GPR64_FIRST REG_EDXEAX
14216 #define REGC_GPR64_LAST REG_EDXEAX
14217 #define REG_MMX0 28
14218 #define REG_MMX1 29
14219 #define REG_MMX2 30
14220 #define REG_MMX3 31
14221 #define REG_MMX4 32
14222 #define REG_MMX5 33
14223 #define REG_MMX6 34
14224 #define REG_MMX7 35
14225 #define REGC_MMX_FIRST REG_MMX0
14226 #define REGC_MMX_LAST REG_MMX7
14227 #define REG_XMM0 36
14228 #define REG_XMM1 37
14229 #define REG_XMM2 38
14230 #define REG_XMM3 39
14231 #define REG_XMM4 40
14232 #define REG_XMM5 41
14233 #define REG_XMM6 42
14234 #define REG_XMM7 43
14235 #define REGC_XMM_FIRST REG_XMM0
14236 #define REGC_XMM_LAST REG_XMM7
14237 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14238 #define LAST_REG REG_XMM7
14240 #define REGC_GPR32_8_FIRST REG_EAX
14241 #define REGC_GPR32_8_LAST REG_EDX
14242 #define REGC_GPR16_8_FIRST REG_AX
14243 #define REGC_GPR16_8_LAST REG_DX
14245 #define REGC_IMM8_FIRST -1
14246 #define REGC_IMM8_LAST -1
14247 #define REGC_IMM16_FIRST -2
14248 #define REGC_IMM16_LAST -1
14249 #define REGC_IMM32_FIRST -4
14250 #define REGC_IMM32_LAST -1
14252 #if LAST_REG >= MAX_REGISTERS
14253 #error "MAX_REGISTERS to low"
14257 static unsigned regc_size[LAST_REGC +1] = {
14258 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
14259 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
14260 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
14261 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
14262 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
14263 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
14264 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
14265 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14266 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14272 static const struct {
14274 } regcm_bound[LAST_REGC + 1] = {
14275 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
14276 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
14277 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
14278 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
14279 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
14280 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
14281 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
14282 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14283 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14284 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
14285 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
14286 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
14289 static int arch_encode_cpu(const char *cpu)
14295 { "i386", CPU_I386 },
14303 for(ptr = cpus; ptr->name; ptr++) {
14304 if (strcmp(ptr->name, cpu) == 0) {
14311 static unsigned arch_regc_size(struct compile_state *state, int class)
14313 if ((class < 0) || (class > LAST_REGC)) {
14316 return regc_size[class];
14318 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14320 /* See if two register classes may have overlapping registers */
14321 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14322 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14324 /* Special case for the immediates */
14325 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14326 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14327 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14328 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
14331 return (regcm1 & regcm2) ||
14332 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14335 static void arch_reg_equivs(
14336 struct compile_state *state, unsigned *equiv, int reg)
14338 if ((reg < 0) || (reg > LAST_REG)) {
14339 internal_error(state, 0, "invalid register");
14344 #if X86_4_8BIT_GPRS
14348 *equiv++ = REG_EAX;
14349 *equiv++ = REG_EDXEAX;
14352 #if X86_4_8BIT_GPRS
14356 *equiv++ = REG_EAX;
14357 *equiv++ = REG_EDXEAX;
14360 #if X86_4_8BIT_GPRS
14364 *equiv++ = REG_EBX;
14368 #if X86_4_8BIT_GPRS
14372 *equiv++ = REG_EBX;
14375 #if X86_4_8BIT_GPRS
14379 *equiv++ = REG_ECX;
14383 #if X86_4_8BIT_GPRS
14387 *equiv++ = REG_ECX;
14390 #if X86_4_8BIT_GPRS
14394 *equiv++ = REG_EDX;
14395 *equiv++ = REG_EDXEAX;
14398 #if X86_4_8BIT_GPRS
14402 *equiv++ = REG_EDX;
14403 *equiv++ = REG_EDXEAX;
14408 *equiv++ = REG_EAX;
14409 *equiv++ = REG_EDXEAX;
14414 *equiv++ = REG_EBX;
14419 *equiv++ = REG_ECX;
14424 *equiv++ = REG_EDX;
14425 *equiv++ = REG_EDXEAX;
14428 *equiv++ = REG_ESI;
14431 *equiv++ = REG_EDI;
14434 *equiv++ = REG_EBP;
14437 *equiv++ = REG_ESP;
14443 *equiv++ = REG_EDXEAX;
14459 *equiv++ = REG_EDXEAX;
14480 *equiv++ = REG_EAX;
14481 *equiv++ = REG_EDX;
14484 *equiv++ = REG_UNSET;
14487 static unsigned arch_avail_mask(struct compile_state *state)
14489 unsigned avail_mask;
14490 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14491 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
14492 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
14493 switch(state->cpu) {
14496 avail_mask |= REGCM_MMX;
14500 avail_mask |= REGCM_MMX | REGCM_XMM;
14504 /* Don't enable 8 bit values until I can force both operands
14505 * to be 8bits simultaneously.
14507 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
14512 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
14514 unsigned mask, result;
14517 result &= arch_avail_mask(state);
14519 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
14520 if ((result & mask) == 0) {
14523 if (class > LAST_REGC) {
14526 for(class2 = 0; class2 <= LAST_REGC; class2++) {
14527 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
14528 (regcm_bound[class2].last <= regcm_bound[class].last)) {
14529 result |= (1 << class2);
14536 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
14541 for(class = 0; class <= LAST_REGC; class++) {
14542 if ((reg >= regcm_bound[class].first) &&
14543 (reg <= regcm_bound[class].last)) {
14544 mask |= (1 << class);
14548 internal_error(state, 0, "reg %d not in any class", reg);
14553 static struct reg_info arch_reg_constraint(
14554 struct compile_state *state, struct type *type, const char *constraint)
14556 static const struct {
14560 } constraints[] = {
14561 { 'r', REGCM_GPR32, REG_UNSET },
14562 { 'g', REGCM_GPR32, REG_UNSET },
14563 { 'p', REGCM_GPR32, REG_UNSET },
14564 { 'q', REGCM_GPR8, REG_UNSET },
14565 { 'Q', REGCM_GPR32_8, REG_UNSET },
14566 { 'x', REGCM_XMM, REG_UNSET },
14567 { 'y', REGCM_MMX, REG_UNSET },
14568 { 'a', REGCM_GPR32, REG_EAX },
14569 { 'b', REGCM_GPR32, REG_EBX },
14570 { 'c', REGCM_GPR32, REG_ECX },
14571 { 'd', REGCM_GPR32, REG_EDX },
14572 { 'D', REGCM_GPR32, REG_EDI },
14573 { 'S', REGCM_GPR32, REG_ESI },
14574 { '\0', 0, REG_UNSET },
14576 unsigned int regcm;
14577 unsigned int mask, reg;
14578 struct reg_info result;
14580 regcm = arch_type_to_regcm(state, type);
14583 for(ptr = constraint; *ptr; ptr++) {
14588 for(i = 0; constraints[i].class != '\0'; i++) {
14589 if (constraints[i].class == *ptr) {
14593 if (constraints[i].class == '\0') {
14594 error(state, 0, "invalid register constraint ``%c''", *ptr);
14597 if ((constraints[i].mask & regcm) == 0) {
14598 error(state, 0, "invalid register class %c specified",
14601 mask |= constraints[i].mask;
14602 if (constraints[i].reg != REG_UNSET) {
14603 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
14604 error(state, 0, "Only one register may be specified");
14606 reg = constraints[i].reg;
14610 result.regcm = mask;
14614 static struct reg_info arch_reg_clobber(
14615 struct compile_state *state, const char *clobber)
14617 struct reg_info result;
14618 if (strcmp(clobber, "memory") == 0) {
14619 result.reg = REG_UNSET;
14622 else if (strcmp(clobber, "%eax") == 0) {
14623 result.reg = REG_EAX;
14624 result.regcm = REGCM_GPR32;
14626 else if (strcmp(clobber, "%ebx") == 0) {
14627 result.reg = REG_EBX;
14628 result.regcm = REGCM_GPR32;
14630 else if (strcmp(clobber, "%ecx") == 0) {
14631 result.reg = REG_ECX;
14632 result.regcm = REGCM_GPR32;
14634 else if (strcmp(clobber, "%edx") == 0) {
14635 result.reg = REG_EDX;
14636 result.regcm = REGCM_GPR32;
14638 else if (strcmp(clobber, "%esi") == 0) {
14639 result.reg = REG_ESI;
14640 result.regcm = REGCM_GPR32;
14642 else if (strcmp(clobber, "%edi") == 0) {
14643 result.reg = REG_EDI;
14644 result.regcm = REGCM_GPR32;
14646 else if (strcmp(clobber, "%ebp") == 0) {
14647 result.reg = REG_EBP;
14648 result.regcm = REGCM_GPR32;
14650 else if (strcmp(clobber, "%esp") == 0) {
14651 result.reg = REG_ESP;
14652 result.regcm = REGCM_GPR32;
14654 else if (strcmp(clobber, "cc") == 0) {
14655 result.reg = REG_EFLAGS;
14656 result.regcm = REGCM_FLAGS;
14658 else if ((strncmp(clobber, "xmm", 3) == 0) &&
14659 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14660 result.reg = REG_XMM0 + octdigval(clobber[3]);
14661 result.regcm = REGCM_XMM;
14663 else if ((strncmp(clobber, "mmx", 3) == 0) &&
14664 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14665 result.reg = REG_MMX0 + octdigval(clobber[3]);
14666 result.regcm = REGCM_MMX;
14669 error(state, 0, "Invalid register clobber");
14670 result.reg = REG_UNSET;
14676 static int do_select_reg(struct compile_state *state,
14677 char *used, int reg, unsigned classes)
14683 mask = arch_reg_regcm(state, reg);
14684 return (classes & mask) ? reg : REG_UNSET;
14687 static int arch_select_free_register(
14688 struct compile_state *state, char *used, int classes)
14690 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
14691 * other types of registers.
14695 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
14696 reg = do_select_reg(state, used, i, classes);
14698 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
14699 reg = do_select_reg(state, used, i, classes);
14701 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
14702 reg = do_select_reg(state, used, i, classes);
14704 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
14705 reg = do_select_reg(state, used, i, classes);
14707 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
14708 reg = do_select_reg(state, used, i, classes);
14710 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
14711 reg = do_select_reg(state, used, i, classes);
14713 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
14714 reg = do_select_reg(state, used, i, classes);
14720 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
14722 #warning "FIXME force types smaller (if legal) before I get here"
14723 unsigned avail_mask;
14726 avail_mask = arch_avail_mask(state);
14727 switch(type->type & TYPE_MASK) {
14734 mask = REGCM_GPR8 |
14735 REGCM_GPR16 | REGCM_GPR16_8 |
14736 REGCM_GPR32 | REGCM_GPR32_8 |
14738 REGCM_MMX | REGCM_XMM |
14739 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
14743 mask = REGCM_GPR16 | REGCM_GPR16_8 |
14744 REGCM_GPR32 | REGCM_GPR32_8 |
14746 REGCM_MMX | REGCM_XMM |
14747 REGCM_IMM32 | REGCM_IMM16;
14754 mask = REGCM_GPR32 | REGCM_GPR32_8 |
14755 REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
14759 internal_error(state, 0, "no register class for type");
14762 mask &= avail_mask;
14766 static int is_imm32(struct triple *imm)
14768 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
14769 (imm->op == OP_ADDRCONST);
14772 static int is_imm16(struct triple *imm)
14774 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
14776 static int is_imm8(struct triple *imm)
14778 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
14781 static int get_imm32(struct triple *ins, struct triple **expr)
14783 struct triple *imm;
14785 while(imm->op == OP_COPY) {
14788 if (!is_imm32(imm)) {
14791 unuse_triple(*expr, ins);
14792 use_triple(imm, ins);
14797 static int get_imm8(struct triple *ins, struct triple **expr)
14799 struct triple *imm;
14801 while(imm->op == OP_COPY) {
14804 if (!is_imm8(imm)) {
14807 unuse_triple(*expr, ins);
14808 use_triple(imm, ins);
14813 #define TEMPLATE_NOP 0
14814 #define TEMPLATE_INTCONST8 1
14815 #define TEMPLATE_INTCONST32 2
14816 #define TEMPLATE_COPY_REG 3
14817 #define TEMPLATE_COPY_IMM32 4
14818 #define TEMPLATE_COPY_IMM16 5
14819 #define TEMPLATE_COPY_IMM8 6
14820 #define TEMPLATE_PHI 7
14821 #define TEMPLATE_STORE8 8
14822 #define TEMPLATE_STORE16 9
14823 #define TEMPLATE_STORE32 10
14824 #define TEMPLATE_LOAD8 11
14825 #define TEMPLATE_LOAD16 12
14826 #define TEMPLATE_LOAD32 13
14827 #define TEMPLATE_BINARY_REG 14
14828 #define TEMPLATE_BINARY_IMM 15
14829 #define TEMPLATE_SL_CL 16
14830 #define TEMPLATE_SL_IMM 17
14831 #define TEMPLATE_UNARY 18
14832 #define TEMPLATE_CMP_REG 19
14833 #define TEMPLATE_CMP_IMM 20
14834 #define TEMPLATE_TEST 21
14835 #define TEMPLATE_SET 22
14836 #define TEMPLATE_JMP 23
14837 #define TEMPLATE_INB_DX 24
14838 #define TEMPLATE_INB_IMM 25
14839 #define TEMPLATE_INW_DX 26
14840 #define TEMPLATE_INW_IMM 27
14841 #define TEMPLATE_INL_DX 28
14842 #define TEMPLATE_INL_IMM 29
14843 #define TEMPLATE_OUTB_DX 30
14844 #define TEMPLATE_OUTB_IMM 31
14845 #define TEMPLATE_OUTW_DX 32
14846 #define TEMPLATE_OUTW_IMM 33
14847 #define TEMPLATE_OUTL_DX 34
14848 #define TEMPLATE_OUTL_IMM 35
14849 #define TEMPLATE_BSF 36
14850 #define TEMPLATE_RDMSR 37
14851 #define TEMPLATE_WRMSR 38
14852 #define LAST_TEMPLATE TEMPLATE_WRMSR
14853 #if LAST_TEMPLATE >= MAX_TEMPLATES
14854 #error "MAX_TEMPLATES to low"
14857 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
14858 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
14860 static struct ins_template templates[] = {
14861 [TEMPLATE_NOP] = {},
14862 [TEMPLATE_INTCONST8] = {
14863 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
14865 [TEMPLATE_INTCONST32] = {
14866 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
14868 [TEMPLATE_COPY_REG] = {
14869 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
14870 .rhs = { [0] = { REG_UNSET, COPY_REGCM } },
14872 [TEMPLATE_COPY_IMM32] = {
14873 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
14874 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
14876 [TEMPLATE_COPY_IMM16] = {
14877 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
14878 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
14880 [TEMPLATE_COPY_IMM8] = {
14881 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
14882 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
14885 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
14887 [ 0] = { REG_VIRT0, COPY_REGCM },
14888 [ 1] = { REG_VIRT0, COPY_REGCM },
14889 [ 2] = { REG_VIRT0, COPY_REGCM },
14890 [ 3] = { REG_VIRT0, COPY_REGCM },
14891 [ 4] = { REG_VIRT0, COPY_REGCM },
14892 [ 5] = { REG_VIRT0, COPY_REGCM },
14893 [ 6] = { REG_VIRT0, COPY_REGCM },
14894 [ 7] = { REG_VIRT0, COPY_REGCM },
14895 [ 8] = { REG_VIRT0, COPY_REGCM },
14896 [ 9] = { REG_VIRT0, COPY_REGCM },
14897 [10] = { REG_VIRT0, COPY_REGCM },
14898 [11] = { REG_VIRT0, COPY_REGCM },
14899 [12] = { REG_VIRT0, COPY_REGCM },
14900 [13] = { REG_VIRT0, COPY_REGCM },
14901 [14] = { REG_VIRT0, COPY_REGCM },
14902 [15] = { REG_VIRT0, COPY_REGCM },
14904 [TEMPLATE_STORE8] = {
14905 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14906 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
14908 [TEMPLATE_STORE16] = {
14909 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14910 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
14912 [TEMPLATE_STORE32] = {
14913 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14914 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14916 [TEMPLATE_LOAD8] = {
14917 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
14918 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14920 [TEMPLATE_LOAD16] = {
14921 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
14922 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14924 [TEMPLATE_LOAD32] = {
14925 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14926 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14928 [TEMPLATE_BINARY_REG] = {
14929 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14931 [0] = { REG_VIRT0, REGCM_GPR32 },
14932 [1] = { REG_UNSET, REGCM_GPR32 },
14935 [TEMPLATE_BINARY_IMM] = {
14936 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14938 [0] = { REG_VIRT0, REGCM_GPR32 },
14939 [1] = { REG_UNNEEDED, REGCM_IMM32 },
14942 [TEMPLATE_SL_CL] = {
14943 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14945 [0] = { REG_VIRT0, REGCM_GPR32 },
14946 [1] = { REG_CL, REGCM_GPR8 },
14949 [TEMPLATE_SL_IMM] = {
14950 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14952 [0] = { REG_VIRT0, REGCM_GPR32 },
14953 [1] = { REG_UNNEEDED, REGCM_IMM8 },
14956 [TEMPLATE_UNARY] = {
14957 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14958 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
14960 [TEMPLATE_CMP_REG] = {
14961 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
14963 [0] = { REG_UNSET, REGCM_GPR32 },
14964 [1] = { REG_UNSET, REGCM_GPR32 },
14967 [TEMPLATE_CMP_IMM] = {
14968 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
14970 [0] = { REG_UNSET, REGCM_GPR32 },
14971 [1] = { REG_UNNEEDED, REGCM_IMM32 },
14974 [TEMPLATE_TEST] = {
14975 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
14976 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
14979 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
14980 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
14983 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
14985 [TEMPLATE_INB_DX] = {
14986 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
14987 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
14989 [TEMPLATE_INB_IMM] = {
14990 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
14991 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
14993 [TEMPLATE_INW_DX] = {
14994 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
14995 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
14997 [TEMPLATE_INW_IMM] = {
14998 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
14999 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15001 [TEMPLATE_INL_DX] = {
15002 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15003 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15005 [TEMPLATE_INL_IMM] = {
15006 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15007 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15009 [TEMPLATE_OUTB_DX] = {
15011 [0] = { REG_AL, REGCM_GPR8 },
15012 [1] = { REG_DX, REGCM_GPR16 },
15015 [TEMPLATE_OUTB_IMM] = {
15017 [0] = { REG_AL, REGCM_GPR8 },
15018 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15021 [TEMPLATE_OUTW_DX] = {
15023 [0] = { REG_AX, REGCM_GPR16 },
15024 [1] = { REG_DX, REGCM_GPR16 },
15027 [TEMPLATE_OUTW_IMM] = {
15029 [0] = { REG_AX, REGCM_GPR16 },
15030 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15033 [TEMPLATE_OUTL_DX] = {
15035 [0] = { REG_EAX, REGCM_GPR32 },
15036 [1] = { REG_DX, REGCM_GPR16 },
15039 [TEMPLATE_OUTL_IMM] = {
15041 [0] = { REG_EAX, REGCM_GPR32 },
15042 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15046 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15047 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15049 [TEMPLATE_RDMSR] = {
15051 [0] = { REG_EAX, REGCM_GPR32 },
15052 [1] = { REG_EDX, REGCM_GPR32 },
15054 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15056 [TEMPLATE_WRMSR] = {
15058 [0] = { REG_ECX, REGCM_GPR32 },
15059 [1] = { REG_EAX, REGCM_GPR32 },
15060 [2] = { REG_EDX, REGCM_GPR32 },
15065 static void fixup_branches(struct compile_state *state,
15066 struct triple *cmp, struct triple *use, int jmp_op)
15068 struct triple_set *entry, *next;
15069 for(entry = use->use; entry; entry = next) {
15070 next = entry->next;
15071 if (entry->member->op == OP_COPY) {
15072 fixup_branches(state, cmp, entry->member, jmp_op);
15074 else if (entry->member->op == OP_BRANCH) {
15075 struct triple *branch, *test;
15076 struct triple *left, *right;
15078 left = RHS(cmp, 0);
15079 if (TRIPLE_RHS(cmp->sizes) > 1) {
15080 right = RHS(cmp, 1);
15082 branch = entry->member;
15083 test = pre_triple(state, branch,
15084 cmp->op, cmp->type, left, right);
15085 test->template_id = TEMPLATE_TEST;
15086 if (cmp->op == OP_CMP) {
15087 test->template_id = TEMPLATE_CMP_REG;
15088 if (get_imm32(test, &RHS(test, 1))) {
15089 test->template_id = TEMPLATE_CMP_IMM;
15092 use_triple(RHS(test, 0), test);
15093 use_triple(RHS(test, 1), test);
15094 unuse_triple(RHS(branch, 0), branch);
15095 RHS(branch, 0) = test;
15096 branch->op = jmp_op;
15097 branch->template_id = TEMPLATE_JMP;
15098 use_triple(RHS(branch, 0), branch);
15103 static void bool_cmp(struct compile_state *state,
15104 struct triple *ins, int cmp_op, int jmp_op, int set_op)
15106 struct triple_set *entry, *next;
15107 struct triple *set;
15109 /* Put a barrier up before the cmp which preceeds the
15110 * copy instruction. If a set actually occurs this gives
15111 * us a chance to move variables in registers out of the way.
15114 /* Modify the comparison operator */
15116 ins->template_id = TEMPLATE_TEST;
15117 if (cmp_op == OP_CMP) {
15118 ins->template_id = TEMPLATE_CMP_REG;
15119 if (get_imm32(ins, &RHS(ins, 1))) {
15120 ins->template_id = TEMPLATE_CMP_IMM;
15123 /* Generate the instruction sequence that will transform the
15124 * result of the comparison into a logical value.
15126 set = post_triple(state, ins, set_op, ins->type, ins, 0);
15127 use_triple(ins, set);
15128 set->template_id = TEMPLATE_SET;
15130 for(entry = ins->use; entry; entry = next) {
15131 next = entry->next;
15132 if (entry->member == set) {
15135 replace_rhs_use(state, ins, set, entry->member);
15137 fixup_branches(state, ins, set, jmp_op);
15140 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15142 struct triple *next;
15144 lhs = TRIPLE_LHS(ins->sizes);
15145 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15146 if (next != LHS(ins, i)) {
15147 internal_error(state, ins, "malformed lhs on %s",
15150 if (next->op != OP_PIECE) {
15151 internal_error(state, ins, "bad lhs op %s at %d on %s",
15152 tops(next->op), i, tops(ins->op));
15154 if (next->u.cval != i) {
15155 internal_error(state, ins, "bad u.cval of %d %d expected",
15162 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15164 struct ins_template *template;
15165 struct reg_info result;
15167 if (ins->op == OP_PIECE) {
15168 index = ins->u.cval;
15169 ins = MISC(ins, 0);
15171 zlhs = TRIPLE_LHS(ins->sizes);
15172 if (triple_is_def(state, ins)) {
15175 if (index >= zlhs) {
15176 internal_error(state, ins, "index %d out of range for %s\n",
15177 index, tops(ins->op));
15181 template = &ins->u.ainfo->tmpl;
15184 if (ins->template_id > LAST_TEMPLATE) {
15185 internal_error(state, ins, "bad template number %d",
15188 template = &templates[ins->template_id];
15191 result = template->lhs[index];
15192 result.regcm = arch_regcm_normalize(state, result.regcm);
15193 if (result.reg != REG_UNNEEDED) {
15194 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15196 if (result.regcm == 0) {
15197 internal_error(state, ins, "lhs %d regcm == 0", index);
15202 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15204 struct reg_info result;
15205 struct ins_template *template;
15206 if ((index > TRIPLE_RHS(ins->sizes)) ||
15207 (ins->op == OP_PIECE)) {
15208 internal_error(state, ins, "index %d out of range for %s\n",
15209 index, tops(ins->op));
15213 template = &ins->u.ainfo->tmpl;
15216 if (ins->template_id > LAST_TEMPLATE) {
15217 internal_error(state, ins, "bad template number %d",
15220 template = &templates[ins->template_id];
15223 result = template->rhs[index];
15224 result.regcm = arch_regcm_normalize(state, result.regcm);
15225 if (result.regcm == 0) {
15226 internal_error(state, ins, "rhs %d regcm == 0", index);
15231 static struct triple *transform_to_arch_instruction(
15232 struct compile_state *state, struct triple *ins)
15234 /* Transform from generic 3 address instructions
15235 * to archtecture specific instructions.
15236 * And apply architecture specific constrains to instructions.
15237 * Copies are inserted to preserve the register flexibility
15238 * of 3 address instructions.
15240 struct triple *next;
15244 ins->template_id = TEMPLATE_INTCONST32;
15245 if (ins->u.cval < 256) {
15246 ins->template_id = TEMPLATE_INTCONST8;
15250 ins->template_id = TEMPLATE_INTCONST32;
15256 ins->template_id = TEMPLATE_NOP;
15259 ins->template_id = TEMPLATE_COPY_REG;
15260 if (is_imm8(RHS(ins, 0))) {
15261 ins->template_id = TEMPLATE_COPY_IMM8;
15263 else if (is_imm16(RHS(ins, 0))) {
15264 ins->template_id = TEMPLATE_COPY_IMM16;
15266 else if (is_imm32(RHS(ins, 0))) {
15267 ins->template_id = TEMPLATE_COPY_IMM32;
15269 else if (is_const(RHS(ins, 0))) {
15270 internal_error(state, ins, "bad constant passed to copy");
15274 ins->template_id = TEMPLATE_PHI;
15277 switch(ins->type->type & TYPE_MASK) {
15278 case TYPE_CHAR: case TYPE_UCHAR:
15279 ins->template_id = TEMPLATE_STORE8;
15281 case TYPE_SHORT: case TYPE_USHORT:
15282 ins->template_id = TEMPLATE_STORE16;
15284 case TYPE_INT: case TYPE_UINT:
15285 case TYPE_LONG: case TYPE_ULONG:
15287 ins->template_id = TEMPLATE_STORE32;
15290 internal_error(state, ins, "unknown type in store");
15295 switch(ins->type->type & TYPE_MASK) {
15296 case TYPE_CHAR: case TYPE_UCHAR:
15297 ins->template_id = TEMPLATE_LOAD8;
15301 ins->template_id = TEMPLATE_LOAD16;
15308 ins->template_id = TEMPLATE_LOAD32;
15311 internal_error(state, ins, "unknown type in load");
15321 ins->template_id = TEMPLATE_BINARY_REG;
15322 if (get_imm32(ins, &RHS(ins, 1))) {
15323 ins->template_id = TEMPLATE_BINARY_IMM;
15329 ins->template_id = TEMPLATE_SL_CL;
15330 if (get_imm8(ins, &RHS(ins, 1))) {
15331 ins->template_id = TEMPLATE_SL_IMM;
15336 ins->template_id = TEMPLATE_UNARY;
15339 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
15342 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15345 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
15348 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
15351 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
15354 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
15357 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
15360 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
15363 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
15366 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
15369 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15372 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
15375 if (TRIPLE_RHS(ins->sizes) > 0) {
15376 internal_error(state, ins, "bad branch test");
15379 ins->template_id = TEMPLATE_NOP;
15385 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
15386 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
15387 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
15389 if (get_imm8(ins, &RHS(ins, 0))) {
15390 ins->template_id += 1;
15397 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
15398 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
15399 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
15401 if (get_imm8(ins, &RHS(ins, 1))) {
15402 ins->template_id += 1;
15407 ins->template_id = TEMPLATE_BSF;
15410 ins->template_id = TEMPLATE_RDMSR;
15411 next = after_lhs(state, ins);
15414 ins->template_id = TEMPLATE_WRMSR;
15417 ins->template_id = TEMPLATE_NOP;
15420 ins->template_id = TEMPLATE_NOP;
15421 next = after_lhs(state, ins);
15423 /* Already transformed instructions */
15425 ins->template_id = TEMPLATE_TEST;
15428 ins->template_id = TEMPLATE_CMP_REG;
15429 if (get_imm32(ins, &RHS(ins, 1))) {
15430 ins->template_id = TEMPLATE_CMP_IMM;
15433 case OP_JMP_EQ: case OP_JMP_NOTEQ:
15434 case OP_JMP_SLESS: case OP_JMP_ULESS:
15435 case OP_JMP_SMORE: case OP_JMP_UMORE:
15436 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
15437 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
15438 ins->template_id = TEMPLATE_JMP;
15440 case OP_SET_EQ: case OP_SET_NOTEQ:
15441 case OP_SET_SLESS: case OP_SET_ULESS:
15442 case OP_SET_SMORE: case OP_SET_UMORE:
15443 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
15444 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
15445 ins->template_id = TEMPLATE_SET;
15447 /* Unhandled instructions */
15450 internal_error(state, ins, "unhandled ins: %d %s\n",
15451 ins->op, tops(ins->op));
15457 static void generate_local_labels(struct compile_state *state)
15459 struct triple *first, *label;
15462 first = RHS(state->main_function, 0);
15465 if ((label->op == OP_LABEL) ||
15466 (label->op == OP_SDECL)) {
15468 label->u.cval = ++label_counter;
15474 label = label->next;
15475 } while(label != first);
15478 static int check_reg(struct compile_state *state,
15479 struct triple *triple, int classes)
15483 reg = ID_REG(triple->id);
15484 if (reg == REG_UNSET) {
15485 internal_error(state, triple, "register not set");
15487 mask = arch_reg_regcm(state, reg);
15488 if (!(classes & mask)) {
15489 internal_error(state, triple, "reg %d in wrong class",
15495 static const char *arch_reg_str(int reg)
15497 static const char *regs[] = {
15501 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
15502 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
15503 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
15505 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
15506 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
15507 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
15509 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
15516 static const char *reg(struct compile_state *state, struct triple *triple,
15520 reg = check_reg(state, triple, classes);
15521 return arch_reg_str(reg);
15524 const char *type_suffix(struct compile_state *state, struct type *type)
15526 const char *suffix;
15527 switch(size_of(state, type)) {
15528 case 1: suffix = "b"; break;
15529 case 2: suffix = "w"; break;
15530 case 4: suffix = "l"; break;
15532 internal_error(state, 0, "unknown suffix");
15539 static void print_const_val(
15540 struct compile_state *state, struct triple *ins, FILE *fp)
15544 fprintf(fp, " $%ld ",
15545 (long_t)(ins->u.cval));
15548 fprintf(fp, " $L%s%lu+%lu ",
15549 state->label_prefix,
15550 MISC(ins, 0)->u.cval,
15554 internal_error(state, ins, "unknown constant type");
15559 static void print_binary_op(struct compile_state *state,
15560 const char *op, struct triple *ins, FILE *fp)
15563 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15564 if (RHS(ins, 0)->id != ins->id) {
15565 internal_error(state, ins, "invalid register assignment");
15567 if (is_const(RHS(ins, 1))) {
15568 fprintf(fp, "\t%s ", op);
15569 print_const_val(state, RHS(ins, 1), fp);
15570 fprintf(fp, ", %s\n",
15571 reg(state, RHS(ins, 0), mask));
15574 unsigned lmask, rmask;
15576 lreg = check_reg(state, RHS(ins, 0), mask);
15577 rreg = check_reg(state, RHS(ins, 1), mask);
15578 lmask = arch_reg_regcm(state, lreg);
15579 rmask = arch_reg_regcm(state, rreg);
15580 mask = lmask & rmask;
15581 fprintf(fp, "\t%s %s, %s\n",
15583 reg(state, RHS(ins, 1), mask),
15584 reg(state, RHS(ins, 0), mask));
15587 static void print_unary_op(struct compile_state *state,
15588 const char *op, struct triple *ins, FILE *fp)
15591 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15592 fprintf(fp, "\t%s %s\n",
15594 reg(state, RHS(ins, 0), mask));
15597 static void print_op_shift(struct compile_state *state,
15598 const char *op, struct triple *ins, FILE *fp)
15601 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15602 if (RHS(ins, 0)->id != ins->id) {
15603 internal_error(state, ins, "invalid register assignment");
15605 if (is_const(RHS(ins, 1))) {
15606 fprintf(fp, "\t%s ", op);
15607 print_const_val(state, RHS(ins, 1), fp);
15608 fprintf(fp, ", %s\n",
15609 reg(state, RHS(ins, 0), mask));
15612 fprintf(fp, "\t%s %s, %s\n",
15614 reg(state, RHS(ins, 1), REGCM_GPR8),
15615 reg(state, RHS(ins, 0), mask));
15619 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
15626 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
15627 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
15628 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
15630 internal_error(state, ins, "not an in operation");
15634 dreg = check_reg(state, ins, mask);
15635 if (!reg_is_reg(state, dreg, REG_EAX)) {
15636 internal_error(state, ins, "dst != %%eax");
15638 if (is_const(RHS(ins, 0))) {
15639 fprintf(fp, "\t%s ", op);
15640 print_const_val(state, RHS(ins, 0), fp);
15641 fprintf(fp, ", %s\n",
15642 reg(state, ins, mask));
15646 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
15647 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15648 internal_error(state, ins, "src != %%dx");
15650 fprintf(fp, "\t%s %s, %s\n",
15652 reg(state, RHS(ins, 0), REGCM_GPR16),
15653 reg(state, ins, mask));
15657 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
15664 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
15665 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
15666 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
15668 internal_error(state, ins, "not an out operation");
15672 lreg = check_reg(state, RHS(ins, 0), mask);
15673 if (!reg_is_reg(state, lreg, REG_EAX)) {
15674 internal_error(state, ins, "src != %%eax");
15676 if (is_const(RHS(ins, 1))) {
15677 fprintf(fp, "\t%s %s,",
15678 op, reg(state, RHS(ins, 0), mask));
15679 print_const_val(state, RHS(ins, 1), fp);
15684 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
15685 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15686 internal_error(state, ins, "dst != %%dx");
15688 fprintf(fp, "\t%s %s, %s\n",
15690 reg(state, RHS(ins, 0), mask),
15691 reg(state, RHS(ins, 1), REGCM_GPR16));
15695 static void print_op_move(struct compile_state *state,
15696 struct triple *ins, FILE *fp)
15698 /* op_move is complex because there are many types
15699 * of registers we can move between.
15700 * Because OP_COPY will be introduced in arbitrary locations
15701 * OP_COPY must not affect flags.
15703 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
15704 struct triple *dst, *src;
15705 if (ins->op == OP_COPY) {
15709 else if (ins->op == OP_WRITE) {
15714 internal_error(state, ins, "unknown move operation");
15717 if (!is_const(src)) {
15718 int src_reg, dst_reg;
15719 int src_regcm, dst_regcm;
15720 src_reg = ID_REG(src->id);
15721 dst_reg = ID_REG(dst->id);
15722 src_regcm = arch_reg_regcm(state, src_reg);
15723 dst_regcm = arch_reg_regcm(state, dst_reg);
15724 /* If the class is the same just move the register */
15725 if (src_regcm & dst_regcm &
15726 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
15727 if ((src_reg != dst_reg) || !omit_copy) {
15728 fprintf(fp, "\tmov %s, %s\n",
15729 reg(state, src, src_regcm),
15730 reg(state, dst, dst_regcm));
15733 /* Move 32bit to 16bit */
15734 else if ((src_regcm & REGCM_GPR32) &&
15735 (dst_regcm & REGCM_GPR16)) {
15736 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
15737 if ((src_reg != dst_reg) || !omit_copy) {
15738 fprintf(fp, "\tmovw %s, %s\n",
15739 arch_reg_str(src_reg),
15740 arch_reg_str(dst_reg));
15743 /* Move 32bit to 8bit */
15744 else if ((src_regcm & REGCM_GPR32_8) &&
15745 (dst_regcm & REGCM_GPR8))
15747 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
15748 if ((src_reg != dst_reg) || !omit_copy) {
15749 fprintf(fp, "\tmovb %s, %s\n",
15750 arch_reg_str(src_reg),
15751 arch_reg_str(dst_reg));
15754 /* Move 16bit to 8bit */
15755 else if ((src_regcm & REGCM_GPR16_8) &&
15756 (dst_regcm & REGCM_GPR8))
15758 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
15759 if ((src_reg != dst_reg) || !omit_copy) {
15760 fprintf(fp, "\tmovb %s, %s\n",
15761 arch_reg_str(src_reg),
15762 arch_reg_str(dst_reg));
15765 /* Move 8/16bit to 16/32bit */
15766 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
15767 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
15769 op = is_signed(src->type)? "movsx": "movzx";
15770 fprintf(fp, "\t%s %s, %s\n",
15772 reg(state, src, src_regcm),
15773 reg(state, dst, dst_regcm));
15775 /* Move between sse registers */
15776 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
15777 if ((src_reg != dst_reg) || !omit_copy) {
15778 fprintf(fp, "\tmovdqa %s, %s\n",
15779 reg(state, src, src_regcm),
15780 reg(state, dst, dst_regcm));
15783 /* Move between mmx registers or mmx & sse registers */
15784 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
15785 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
15786 if ((src_reg != dst_reg) || !omit_copy) {
15787 fprintf(fp, "\tmovq %s, %s\n",
15788 reg(state, src, src_regcm),
15789 reg(state, dst, dst_regcm));
15792 /* Move between 32bit gprs & mmx/sse registers */
15793 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
15794 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
15795 fprintf(fp, "\tmovd %s, %s\n",
15796 reg(state, src, src_regcm),
15797 reg(state, dst, dst_regcm));
15799 #if X86_4_8BIT_GPRS
15800 /* Move from 8bit gprs to mmx/sse registers */
15801 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
15802 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
15805 op = is_signed(src->type)? "movsx":"movzx";
15806 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15807 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
15809 reg(state, src, src_regcm),
15810 arch_reg_str(mid_reg),
15811 arch_reg_str(mid_reg),
15812 reg(state, dst, dst_regcm));
15814 /* Move from mmx/sse registers and 8bit gprs */
15815 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
15816 (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
15818 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15819 fprintf(fp, "\tmovd %s, %s\n",
15820 reg(state, src, src_regcm),
15821 arch_reg_str(mid_reg));
15823 /* Move from 32bit gprs to 16bit gprs */
15824 else if ((src_regcm & REGCM_GPR32) &&
15825 (dst_regcm & REGCM_GPR16)) {
15826 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
15827 if ((src_reg != dst_reg) || !omit_copy) {
15828 fprintf(fp, "\tmov %s, %s\n",
15829 arch_reg_str(src_reg),
15830 arch_reg_str(dst_reg));
15833 /* Move from 32bit gprs to 8bit gprs */
15834 else if ((src_regcm & REGCM_GPR32) &&
15835 (dst_regcm & REGCM_GPR8)) {
15836 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
15837 if ((src_reg != dst_reg) || !omit_copy) {
15838 fprintf(fp, "\tmov %s, %s\n",
15839 arch_reg_str(src_reg),
15840 arch_reg_str(dst_reg));
15843 /* Move from 16bit gprs to 8bit gprs */
15844 else if ((src_regcm & REGCM_GPR16) &&
15845 (dst_regcm & REGCM_GPR8)) {
15846 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
15847 if ((src_reg != dst_reg) || !omit_copy) {
15848 fprintf(fp, "\tmov %s, %s\n",
15849 arch_reg_str(src_reg),
15850 arch_reg_str(dst_reg));
15853 #endif /* X86_4_8BIT_GPRS */
15855 internal_error(state, ins, "unknown copy type");
15859 fprintf(fp, "\tmov ");
15860 print_const_val(state, src, fp);
15861 fprintf(fp, ", %s\n",
15862 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
15866 static void print_op_load(struct compile_state *state,
15867 struct triple *ins, FILE *fp)
15869 struct triple *dst, *src;
15872 if (is_const(src) || is_const(dst)) {
15873 internal_error(state, ins, "unknown load operation");
15875 fprintf(fp, "\tmov (%s), %s\n",
15876 reg(state, src, REGCM_GPR32),
15877 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
15881 static void print_op_store(struct compile_state *state,
15882 struct triple *ins, FILE *fp)
15884 struct triple *dst, *src;
15887 if (is_const(src) && (src->op == OP_INTCONST)) {
15889 value = (long_t)(src->u.cval);
15890 fprintf(fp, "\tmov%s $%ld, (%s)\n",
15891 type_suffix(state, src->type),
15893 reg(state, dst, REGCM_GPR32));
15895 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
15896 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
15897 type_suffix(state, src->type),
15898 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
15902 if (is_const(src) || is_const(dst)) {
15903 internal_error(state, ins, "unknown store operation");
15905 fprintf(fp, "\tmov%s %s, (%s)\n",
15906 type_suffix(state, src->type),
15907 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
15908 reg(state, dst, REGCM_GPR32));
15914 static void print_op_smul(struct compile_state *state,
15915 struct triple *ins, FILE *fp)
15917 if (!is_const(RHS(ins, 1))) {
15918 fprintf(fp, "\timul %s, %s\n",
15919 reg(state, RHS(ins, 1), REGCM_GPR32),
15920 reg(state, RHS(ins, 0), REGCM_GPR32));
15923 fprintf(fp, "\timul ");
15924 print_const_val(state, RHS(ins, 1), fp);
15925 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
15929 static void print_op_cmp(struct compile_state *state,
15930 struct triple *ins, FILE *fp)
15934 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15935 dreg = check_reg(state, ins, REGCM_FLAGS);
15936 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
15937 internal_error(state, ins, "bad dest register for cmp");
15939 if (is_const(RHS(ins, 1))) {
15940 fprintf(fp, "\tcmp ");
15941 print_const_val(state, RHS(ins, 1), fp);
15942 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
15945 unsigned lmask, rmask;
15947 lreg = check_reg(state, RHS(ins, 0), mask);
15948 rreg = check_reg(state, RHS(ins, 1), mask);
15949 lmask = arch_reg_regcm(state, lreg);
15950 rmask = arch_reg_regcm(state, rreg);
15951 mask = lmask & rmask;
15952 fprintf(fp, "\tcmp %s, %s\n",
15953 reg(state, RHS(ins, 1), mask),
15954 reg(state, RHS(ins, 0), mask));
15958 static void print_op_test(struct compile_state *state,
15959 struct triple *ins, FILE *fp)
15962 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15963 fprintf(fp, "\ttest %s, %s\n",
15964 reg(state, RHS(ins, 0), mask),
15965 reg(state, RHS(ins, 0), mask));
15968 static void print_op_branch(struct compile_state *state,
15969 struct triple *branch, FILE *fp)
15971 const char *bop = "j";
15972 if (branch->op == OP_JMP) {
15973 if (TRIPLE_RHS(branch->sizes) != 0) {
15974 internal_error(state, branch, "jmp with condition?");
15979 struct triple *ptr;
15980 if (TRIPLE_RHS(branch->sizes) != 1) {
15981 internal_error(state, branch, "jmpcc without condition?");
15983 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
15984 if ((RHS(branch, 0)->op != OP_CMP) &&
15985 (RHS(branch, 0)->op != OP_TEST)) {
15986 internal_error(state, branch, "bad branch test");
15988 #warning "FIXME I have observed instructions between the test and branch instructions"
15989 ptr = RHS(branch, 0);
15990 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
15991 if (ptr->op != OP_COPY) {
15992 internal_error(state, branch, "branch does not follow test");
15995 switch(branch->op) {
15996 case OP_JMP_EQ: bop = "jz"; break;
15997 case OP_JMP_NOTEQ: bop = "jnz"; break;
15998 case OP_JMP_SLESS: bop = "jl"; break;
15999 case OP_JMP_ULESS: bop = "jb"; break;
16000 case OP_JMP_SMORE: bop = "jg"; break;
16001 case OP_JMP_UMORE: bop = "ja"; break;
16002 case OP_JMP_SLESSEQ: bop = "jle"; break;
16003 case OP_JMP_ULESSEQ: bop = "jbe"; break;
16004 case OP_JMP_SMOREEQ: bop = "jge"; break;
16005 case OP_JMP_UMOREEQ: bop = "jae"; break;
16007 internal_error(state, branch, "Invalid branch op");
16012 fprintf(fp, "\t%s L%s%lu\n",
16014 state->label_prefix,
16015 TARG(branch, 0)->u.cval);
16018 static void print_op_set(struct compile_state *state,
16019 struct triple *set, FILE *fp)
16021 const char *sop = "set";
16022 if (TRIPLE_RHS(set->sizes) != 1) {
16023 internal_error(state, set, "setcc without condition?");
16025 check_reg(state, RHS(set, 0), REGCM_FLAGS);
16026 if ((RHS(set, 0)->op != OP_CMP) &&
16027 (RHS(set, 0)->op != OP_TEST)) {
16028 internal_error(state, set, "bad set test");
16030 if (RHS(set, 0)->next != set) {
16031 internal_error(state, set, "set does not follow test");
16034 case OP_SET_EQ: sop = "setz"; break;
16035 case OP_SET_NOTEQ: sop = "setnz"; break;
16036 case OP_SET_SLESS: sop = "setl"; break;
16037 case OP_SET_ULESS: sop = "setb"; break;
16038 case OP_SET_SMORE: sop = "setg"; break;
16039 case OP_SET_UMORE: sop = "seta"; break;
16040 case OP_SET_SLESSEQ: sop = "setle"; break;
16041 case OP_SET_ULESSEQ: sop = "setbe"; break;
16042 case OP_SET_SMOREEQ: sop = "setge"; break;
16043 case OP_SET_UMOREEQ: sop = "setae"; break;
16045 internal_error(state, set, "Invalid set op");
16048 fprintf(fp, "\t%s %s\n",
16049 sop, reg(state, set, REGCM_GPR8));
16052 static void print_op_bit_scan(struct compile_state *state,
16053 struct triple *ins, FILE *fp)
16057 case OP_BSF: op = "bsf"; break;
16058 case OP_BSR: op = "bsr"; break;
16060 internal_error(state, ins, "unknown bit scan");
16070 reg(state, RHS(ins, 0), REGCM_GPR32),
16071 reg(state, ins, REGCM_GPR32),
16072 reg(state, ins, REGCM_GPR32));
16075 static void print_const(struct compile_state *state,
16076 struct triple *ins, FILE *fp)
16080 switch(ins->type->type & TYPE_MASK) {
16083 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16087 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16093 fprintf(fp, ".int %lu\n", ins->u.cval);
16096 internal_error(state, ins, "Unknown constant type");
16101 unsigned char *blob;
16103 size = size_of(state, ins->type);
16104 blob = ins->u.blob;
16105 for(i = 0; i < size; i++) {
16106 fprintf(fp, ".byte 0x%02x\n",
16112 internal_error(state, ins, "Unknown constant type");
16117 #define TEXT_SECTION ".rom.text"
16118 #define DATA_SECTION ".rom.data"
16120 static void print_sdecl(struct compile_state *state,
16121 struct triple *ins, FILE *fp)
16123 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16124 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16125 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16126 print_const(state, MISC(ins, 0), fp);
16127 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16131 static void print_instruction(struct compile_state *state,
16132 struct triple *ins, FILE *fp)
16134 /* Assumption: after I have exted the register allocator
16135 * everything is in a valid register.
16139 print_op_asm(state, ins, fp);
16141 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
16142 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
16143 case OP_AND: print_binary_op(state, "and", ins, fp); break;
16144 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
16145 case OP_OR: print_binary_op(state, "or", ins, fp); break;
16146 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
16147 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
16148 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
16149 case OP_POS: break;
16150 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
16151 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16155 /* Don't generate anything here for constants */
16157 /* Don't generate anything for variable declarations. */
16160 print_sdecl(state, ins, fp);
16164 print_op_move(state, ins, fp);
16167 print_op_load(state, ins, fp);
16170 print_op_store(state, ins, fp);
16173 print_op_smul(state, ins, fp);
16175 case OP_CMP: print_op_cmp(state, ins, fp); break;
16176 case OP_TEST: print_op_test(state, ins, fp); break;
16178 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16179 case OP_JMP_SLESS: case OP_JMP_ULESS:
16180 case OP_JMP_SMORE: case OP_JMP_UMORE:
16181 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16182 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16183 print_op_branch(state, ins, fp);
16185 case OP_SET_EQ: case OP_SET_NOTEQ:
16186 case OP_SET_SLESS: case OP_SET_ULESS:
16187 case OP_SET_SMORE: case OP_SET_UMORE:
16188 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16189 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16190 print_op_set(state, ins, fp);
16192 case OP_INB: case OP_INW: case OP_INL:
16193 print_op_in(state, ins, fp);
16195 case OP_OUTB: case OP_OUTW: case OP_OUTL:
16196 print_op_out(state, ins, fp);
16200 print_op_bit_scan(state, ins, fp);
16203 after_lhs(state, ins);
16204 fprintf(fp, "\trdmsr\n");
16207 fprintf(fp, "\twrmsr\n");
16210 fprintf(fp, "\thlt\n");
16216 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16218 /* Ignore OP_PIECE */
16221 /* Operations I am not yet certain how to handle */
16223 case OP_SDIV: case OP_UDIV:
16224 case OP_SMOD: case OP_UMOD:
16225 /* Operations that should never get here */
16226 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
16227 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
16228 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16230 internal_error(state, ins, "unknown op: %d %s",
16231 ins->op, tops(ins->op));
16236 static void print_instructions(struct compile_state *state)
16238 struct triple *first, *ins;
16239 int print_location;
16242 const char *last_filename;
16244 print_location = 1;
16248 fp = state->output;
16249 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16250 first = RHS(state->main_function, 0);
16253 if (print_location &&
16254 ((last_filename != ins->filename) ||
16255 (last_line != ins->line) ||
16256 (last_col != ins->col))) {
16257 fprintf(fp, "\t/* %s:%d */\n",
16258 ins->filename, ins->line);
16259 last_filename = ins->filename;
16260 last_line = ins->line;
16261 last_col = ins->col;
16264 print_instruction(state, ins, fp);
16266 } while(ins != first);
16269 static void generate_code(struct compile_state *state)
16271 generate_local_labels(state);
16272 print_instructions(state);
16276 static void print_tokens(struct compile_state *state)
16279 tk = &state->token[0];
16284 next_token(state, 0);
16286 loc(stdout, state, 0);
16287 printf("%s <- `%s'\n",
16289 tk->ident ? tk->ident->name :
16290 tk->str_len ? tk->val.str : "");
16292 } while(tk->tok != TOK_EOF);
16295 static void compile(const char *filename, const char *ofilename,
16296 int cpu, int debug, int opt, const char *label_prefix)
16299 struct compile_state state;
16300 memset(&state, 0, sizeof(state));
16302 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
16303 memset(&state.token[i], 0, sizeof(state.token[i]));
16304 state.token[i].tok = -1;
16306 /* Remember the debug settings */
16308 state.debug = debug;
16309 state.optimize = opt;
16310 /* Remember the output filename */
16311 state.ofilename = ofilename;
16312 state.output = fopen(state.ofilename, "w");
16313 if (!state.output) {
16314 error(&state, 0, "Cannot open output file %s\n",
16317 /* Remember the label prefix */
16318 state.label_prefix = label_prefix;
16319 /* Prep the preprocessor */
16320 state.if_depth = 0;
16321 state.if_value = 0;
16322 /* register the C keywords */
16323 register_keywords(&state);
16324 /* register the keywords the macro preprocessor knows */
16325 register_macro_keywords(&state);
16326 /* Memorize where some special keywords are. */
16327 state.i_continue = lookup(&state, "continue", 8);
16328 state.i_break = lookup(&state, "break", 5);
16329 /* Enter the globl definition scope */
16330 start_scope(&state);
16331 register_builtins(&state);
16332 compile_file(&state, filename, 1);
16334 print_tokens(&state);
16337 /* Exit the global definition scope */
16340 /* Now that basic compilation has happened
16341 * optimize the intermediate code
16345 generate_code(&state);
16347 fprintf(stderr, "done\n");
16351 static void version(void)
16353 printf("romcc " VERSION " released " RELEASE_DATE "\n");
16356 static void usage(void)
16360 "Usage: romcc <source>.c\n"
16361 "Compile a C source file without using ram\n"
16365 static void arg_error(char *fmt, ...)
16368 va_start(args, fmt);
16369 vfprintf(stderr, fmt, args);
16375 int main(int argc, char **argv)
16377 const char *filename;
16378 const char *ofilename;
16379 const char *label_prefix;
16386 ofilename = "auto.inc";
16390 while((argc > 1) && (argc != last_argc)) {
16392 if (strncmp(argv[1], "--debug=", 8) == 0) {
16393 debug = atoi(argv[1] + 8);
16397 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
16398 label_prefix= argv[1] + 15;
16402 else if ((strcmp(argv[1],"-O") == 0) ||
16403 (strcmp(argv[1], "-O1") == 0)) {
16408 else if (strcmp(argv[1],"-O2") == 0) {
16413 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
16414 ofilename = argv[2];
16418 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
16419 cpu = arch_encode_cpu(argv[1] + 6);
16420 if (cpu == BAD_CPU) {
16421 arg_error("Invalid cpu specified: %s\n",
16429 arg_error("Wrong argument count %d\n", argc);
16431 filename = argv[1];
16432 compile(filename, ofilename, cpu, debug, optimize, label_prefix);