5 #define VERSION_MAJOR "0"
6 #define VERSION_MINOR "72"
7 #define RELEASE_DATE "10 February 2010"
8 #define VERSION VERSION_MAJOR "." VERSION_MINOR
15 #include <sys/types.h>
25 #define MAX_CWD_SIZE 4096
26 #define MAX_ALLOCATION_PASSES 100
28 /* NOTE: Before you even start thinking to touch anything
29 * in this code, set DEBUG_ROMCC_WARNINGS to 1 to get an
30 * insight on the original author's thoughts. We introduced
31 * this switch as romcc was about the only thing producing
32 * massive warnings in our code..
34 #define DEBUG_ROMCC_WARNINGS 0
36 #define DEBUG_CONSISTENCY 1
37 #define DEBUG_SDP_BLOCKS 0
38 #define DEBUG_TRIPLE_COLOR 0
40 #define DEBUG_DISPLAY_USES 1
41 #define DEBUG_DISPLAY_TYPES 1
42 #define DEBUG_REPLACE_CLOSURE_TYPE_HIRES 0
43 #define DEBUG_DECOMPOSE_PRINT_TUPLES 0
44 #define DEBUG_DECOMPOSE_HIRES 0
45 #define DEBUG_INITIALIZER 0
46 #define DEBUG_UPDATE_CLOSURE_TYPE 0
47 #define DEBUG_LOCAL_TRIPLE 0
48 #define DEBUG_BASIC_BLOCKS_VERBOSE 0
49 #define DEBUG_CPS_RENAME_VARIABLES_HIRES 0
50 #define DEBUG_SIMPLIFY_HIRES 0
51 #define DEBUG_SHRINKING 0
52 #define DEBUG_COALESCE_HITCHES 0
53 #define DEBUG_CODE_ELIMINATION 0
55 #define DEBUG_EXPLICIT_CLOSURES 0
57 #if DEBUG_ROMCC_WARNINGS
58 #warning "FIXME give clear error messages about unused variables"
59 #warning "FIXME properly handle multi dimensional arrays"
60 #warning "FIXME handle multiple register sizes"
63 /* Control flow graph of a loop without goto.
74 * |\ GGG HHH | continue;
102 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
103 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
106 * [] == DFlocal(X) U DF(X)
109 * Dominator graph of the same nodes.
113 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
115 * CCC CCC: [ ] ( BBB, JJJ )
117 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
119 * FFF FFF: [ ] ( BBB )
121 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
123 * III III: [ BBB ] ()
126 * BBB and JJJ are definitely the dominance frontier.
127 * Where do I place phi functions and how do I make that decision.
132 const char *filename;
133 struct filelist *next;
136 struct filelist *include_filelist = NULL;
138 static void __attribute__((noreturn)) die(char *fmt, ...)
143 vfprintf(stderr, fmt, args);
150 static void *xmalloc(size_t size, const char *name)
155 die("Cannot malloc %ld bytes to hold %s: %s\n",
156 size + 0UL, name, strerror(errno));
161 static void *xcmalloc(size_t size, const char *name)
164 buf = xmalloc(size, name);
165 memset(buf, 0, size);
169 static void *xrealloc(void *ptr, size_t size, const char *name)
172 buf = realloc(ptr, size);
174 die("Cannot realloc %ld bytes to hold %s: %s\n",
175 size + 0UL, name, strerror(errno));
180 static void xfree(const void *ptr)
185 static char *xstrdup(const char *str)
190 new = xmalloc(len + 1, "xstrdup string");
191 memcpy(new, str, len);
196 static void xchdir(const char *path)
198 if (chdir(path) != 0) {
199 die("chdir to `%s' failed: %s\n",
200 path, strerror(errno));
204 static int exists(const char *dirname, const char *filename)
206 char cwd[MAX_CWD_SIZE];
209 if (getcwd(cwd, sizeof(cwd)) == 0) {
210 die("cwd buffer to small");
214 if (chdir(dirname) != 0) {
217 if (does_exist && (access(filename, O_RDONLY) < 0)) {
218 if ((errno != EACCES) && (errno != EROFS)) {
227 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
229 char cwd[MAX_CWD_SIZE];
231 off_t size, progress;
239 if (getcwd(cwd, sizeof(cwd)) == 0) {
240 die("cwd buffer to small");
243 file = fopen(filename, "rb");
246 die("Cannot open '%s' : %s\n",
247 filename, strerror(errno));
249 fseek(file, 0, SEEK_END);
251 fseek(file, 0, SEEK_SET);
253 buf = xmalloc(size +2, filename);
254 buf[size] = '\n'; /* Make certain the file is newline terminated */
255 buf[size+1] = '\0'; /* Null terminate the file for good measure */
257 while(progress < size) {
258 result = fread(buf + progress, 1, size - progress, file);
260 if ((errno == EINTR) || (errno == EAGAIN))
262 die("read on %s of %ld bytes failed: %s\n",
263 filename, (size - progress)+ 0UL, strerror(errno));
271 /* Types on the destination platform */
272 #if DEBUG_ROMCC_WARNINGS
273 #warning "FIXME this assumes 32bit x86 is the destination"
275 typedef int8_t schar_t;
276 typedef uint8_t uchar_t;
277 typedef int8_t char_t;
278 typedef int16_t short_t;
279 typedef uint16_t ushort_t;
280 typedef int32_t int_t;
281 typedef uint32_t uint_t;
282 typedef int32_t long_t;
283 #define ulong_t uint32_t
285 #define SCHAR_T_MIN (-128)
286 #define SCHAR_T_MAX 127
287 #define UCHAR_T_MAX 255
288 #define CHAR_T_MIN SCHAR_T_MIN
289 #define CHAR_T_MAX SCHAR_T_MAX
290 #define SHRT_T_MIN (-32768)
291 #define SHRT_T_MAX 32767
292 #define USHRT_T_MAX 65535
293 #define INT_T_MIN (-LONG_T_MAX - 1)
294 #define INT_T_MAX 2147483647
295 #define UINT_T_MAX 4294967295U
296 #define LONG_T_MIN (-LONG_T_MAX - 1)
297 #define LONG_T_MAX 2147483647
298 #define ULONG_T_MAX 4294967295U
301 #define SIZEOF_I16 16
302 #define SIZEOF_I32 32
303 #define SIZEOF_I64 64
305 #define SIZEOF_CHAR 8
306 #define SIZEOF_SHORT 16
307 #define SIZEOF_INT 32
308 #define SIZEOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
311 #define ALIGNOF_CHAR 8
312 #define ALIGNOF_SHORT 16
313 #define ALIGNOF_INT 32
314 #define ALIGNOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
316 #define REG_SIZEOF_REG 32
317 #define REG_SIZEOF_CHAR REG_SIZEOF_REG
318 #define REG_SIZEOF_SHORT REG_SIZEOF_REG
319 #define REG_SIZEOF_INT REG_SIZEOF_REG
320 #define REG_SIZEOF_LONG REG_SIZEOF_REG
322 #define REG_ALIGNOF_REG REG_SIZEOF_REG
323 #define REG_ALIGNOF_CHAR REG_SIZEOF_REG
324 #define REG_ALIGNOF_SHORT REG_SIZEOF_REG
325 #define REG_ALIGNOF_INT REG_SIZEOF_REG
326 #define REG_ALIGNOF_LONG REG_SIZEOF_REG
328 /* Additional definitions for clarity.
329 * I currently assume a long is the largest native
330 * machine word and that a pointer fits into it.
332 #define SIZEOF_WORD SIZEOF_LONG
333 #define SIZEOF_POINTER SIZEOF_LONG
334 #define ALIGNOF_WORD ALIGNOF_LONG
335 #define ALIGNOF_POINTER ALIGNOF_LONG
336 #define REG_SIZEOF_POINTER REG_SIZEOF_LONG
337 #define REG_ALIGNOF_POINTER REG_ALIGNOF_LONG
340 struct file_state *prev;
341 const char *basename;
347 const char *line_start;
349 const char *report_name;
350 const char *report_dir;
358 struct hash_entry *ident;
368 /* I have two classes of types:
370 * Logical types. (The type the C standard says the operation is of)
372 * The operational types are:
387 * No memory is useable by the compiler.
388 * There is no floating point support.
389 * All operations take place in general purpose registers.
390 * There is one type of general purpose register.
391 * Unsigned longs are stored in that general purpose register.
394 /* Operations on general purpose registers.
413 #define OP_POS 16 /* Dummy positive operator don't use it */
423 #define OP_SLESSEQ 26
424 #define OP_ULESSEQ 27
425 #define OP_SMOREEQ 28
426 #define OP_UMOREEQ 29
428 #define OP_LFALSE 30 /* Test if the expression is logically false */
429 #define OP_LTRUE 31 /* Test if the expression is logcially true */
433 /* For OP_STORE ->type holds the type
434 * RHS(0) holds the destination address
435 * RHS(1) holds the value to store.
438 #define OP_UEXTRACT 34
439 /* OP_UEXTRACT extracts an unsigned bitfield from a pseudo register
440 * RHS(0) holds the psuedo register to extract from
441 * ->type holds the size of the bitfield.
442 * ->u.bitfield.size holds the size of the bitfield.
443 * ->u.bitfield.offset holds the offset to extract from
445 #define OP_SEXTRACT 35
446 /* OP_SEXTRACT extracts a signed bitfield from a pseudo register
447 * RHS(0) holds the psuedo register to extract from
448 * ->type holds the size of the bitfield.
449 * ->u.bitfield.size holds the size of the bitfield.
450 * ->u.bitfield.offset holds the offset to extract from
452 #define OP_DEPOSIT 36
453 /* OP_DEPOSIT replaces a bitfield with a new value.
454 * RHS(0) holds the value to replace a bitifield in.
455 * RHS(1) holds the replacement value
456 * ->u.bitfield.size holds the size of the bitfield.
457 * ->u.bitfield.offset holds the deposit into
462 #define OP_MIN_CONST 50
463 #define OP_MAX_CONST 58
464 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
465 #define OP_INTCONST 50
466 /* For OP_INTCONST ->type holds the type.
467 * ->u.cval holds the constant value.
469 #define OP_BLOBCONST 51
470 /* For OP_BLOBCONST ->type holds the layout and size
471 * information. u.blob holds a pointer to the raw binary
472 * data for the constant initializer.
474 #define OP_ADDRCONST 52
475 /* For OP_ADDRCONST ->type holds the type.
476 * MISC(0) holds the reference to the static variable.
477 * ->u.cval holds an offset from that value.
479 #define OP_UNKNOWNVAL 59
480 /* For OP_UNKNOWNAL ->type holds the type.
481 * For some reason we don't know what value this type has.
482 * This allows for variables that have don't have values
483 * assigned yet, or variables whose value we simply do not know.
487 /* OP_WRITE moves one pseudo register to another.
488 * MISC(0) holds the destination pseudo register, which must be an OP_DECL.
489 * RHS(0) holds the psuedo to move.
493 /* OP_READ reads the value of a variable and makes
494 * it available for the pseudo operation.
495 * Useful for things like def-use chains.
496 * RHS(0) holds points to the triple to read from.
499 /* OP_COPY makes a copy of the pseudo register or constant in RHS(0).
501 #define OP_CONVERT 63
502 /* OP_CONVERT makes a copy of the pseudo register or constant in RHS(0).
503 * And then the type is converted appropriately.
506 /* OP_PIECE returns one piece of a instruction that returns a structure.
507 * MISC(0) is the instruction
508 * u.cval is the LHS piece of the instruction to return.
511 /* OP_ASM holds a sequence of assembly instructions, the result
512 * of a C asm directive.
513 * RHS(x) holds input value x to the assembly sequence.
514 * LHS(x) holds the output value x from the assembly sequence.
515 * u.blob holds the string of assembly instructions.
519 /* OP_DEREF generates an lvalue from a pointer.
520 * RHS(0) holds the pointer value.
521 * OP_DEREF serves as a place holder to indicate all necessary
522 * checks have been done to indicate a value is an lvalue.
525 /* OP_DOT references a submember of a structure lvalue.
526 * MISC(0) holds the lvalue.
527 * ->u.field holds the name of the field we want.
529 * Not seen after structures are flattened.
532 /* OP_INDEX references a submember of a tuple or array lvalue.
533 * MISC(0) holds the lvalue.
534 * ->u.cval holds the index into the lvalue.
536 * Not seen after structures are flattened.
539 /* OP_VAL returns the value of a subexpression of the current expression.
540 * Useful for operators that have side effects.
541 * RHS(0) holds the expression.
542 * MISC(0) holds the subexpression of RHS(0) that is the
543 * value of the expression.
545 * Not seen outside of expressions.
549 /* OP_TUPLE is an array of triples that are either variable
550 * or values for a structure or an array. It is used as
551 * a place holder when flattening compound types.
552 * The value represented by an OP_TUPLE is held in N registers.
553 * LHS(0..N-1) refer to those registers.
554 * ->use is a list of statements that use the value.
556 * Although OP_TUPLE always has register sized pieces they are not
557 * used until structures are flattened/decomposed into their register
559 * ???? registers ????
563 /* OP_BITREF describes a bitfield as an lvalue.
564 * RHS(0) holds the register value.
565 * ->type holds the type of the bitfield.
566 * ->u.bitfield.size holds the size of the bitfield.
567 * ->u.bitfield.offset holds the offset of the bitfield in the register
572 /* OP_FCALL performs a procedure call.
573 * MISC(0) holds a pointer to the OP_LIST of a function
574 * RHS(x) holds argument x of a function
576 * Currently not seen outside of expressions.
579 /* OP_PROG is an expression that holds a list of statements, or
580 * expressions. The final expression is the value of the expression.
581 * RHS(0) holds the start of the list.
586 /* OP_LIST Holds a list of statements that compose a function, and a result value.
587 * RHS(0) holds the list of statements.
588 * A list of all functions is maintained.
591 #define OP_BRANCH 81 /* an unconditional branch */
592 /* For branch instructions
593 * TARG(0) holds the branch target.
594 * ->next holds where to branch to if the branch is not taken.
595 * The branch target can only be a label
598 #define OP_CBRANCH 82 /* a conditional branch */
599 /* For conditional branch instructions
600 * RHS(0) holds the branch condition.
601 * TARG(0) holds the branch target.
602 * ->next holds where to branch to if the branch is not taken.
603 * The branch target can only be a label
606 #define OP_CALL 83 /* an uncontional branch that will return */
607 /* For call instructions
608 * MISC(0) holds the OP_RET that returns from the branch
609 * TARG(0) holds the branch target.
610 * ->next holds where to branch to if the branch is not taken.
611 * The branch target can only be a label
614 #define OP_RET 84 /* an uncontinonal branch through a variable back to an OP_CALL */
615 /* For call instructions
616 * RHS(0) holds the variable with the return address
617 * The branch target can only be a label
621 /* OP_LABEL is a triple that establishes an target for branches.
622 * ->use is the list of all branches that use this label.
626 /* OP_ADECL is a triple that establishes an lvalue for assignments.
627 * A variable takes N registers to contain.
628 * LHS(0..N-1) refer to an OP_PIECE triple that represents
629 * the Xth register that the variable is stored in.
630 * ->use is a list of statements that use the variable.
632 * Although OP_ADECL always has register sized pieces they are not
633 * used until structures are flattened/decomposed into their register
638 /* OP_SDECL is a triple that establishes a variable of static
640 * ->use is a list of statements that use the variable.
641 * MISC(0) holds the initializer expression.
646 /* OP_PHI is a triple used in SSA form code.
647 * It is used when multiple code paths merge and a variable needs
648 * a single assignment from any of those code paths.
649 * The operation is a cross between OP_DECL and OP_WRITE, which
650 * is what OP_PHI is generated from.
652 * RHS(x) points to the value from code path x
653 * The number of RHS entries is the number of control paths into the block
654 * in which OP_PHI resides. The elements of the array point to point
655 * to the variables OP_PHI is derived from.
657 * MISC(0) holds a pointer to the orginal OP_DECL node.
661 /* continuation helpers
663 #define OP_CPS_BRANCH 90 /* an unconditional branch */
664 /* OP_CPS_BRANCH calls a continuation
665 * RHS(x) holds argument x of the function
666 * TARG(0) holds OP_CPS_START target
668 #define OP_CPS_CBRANCH 91 /* a conditional branch */
669 /* OP_CPS_CBRANCH conditionally calls one of two continuations
670 * RHS(0) holds the branch condition
671 * RHS(x + 1) holds argument x of the function
672 * TARG(0) holds the OP_CPS_START to jump to when true
673 * ->next holds the OP_CPS_START to jump to when false
675 #define OP_CPS_CALL 92 /* an uncontional branch that will return */
676 /* For OP_CPS_CALL instructions
677 * RHS(x) holds argument x of the function
678 * MISC(0) holds the OP_CPS_RET that returns from the branch
679 * TARG(0) holds the branch target.
680 * ->next holds where the OP_CPS_RET will return to.
682 #define OP_CPS_RET 93
683 /* OP_CPS_RET conditionally calls one of two continuations
684 * RHS(0) holds the variable with the return function address
685 * RHS(x + 1) holds argument x of the function
686 * The branch target may be any OP_CPS_START
688 #define OP_CPS_END 94
689 /* OP_CPS_END is the triple at the end of the program.
690 * For most practical purposes it is a branch.
692 #define OP_CPS_START 95
693 /* OP_CPS_START is a triple at the start of a continuation
694 * The arguments variables takes N registers to contain.
695 * LHS(0..N-1) refer to an OP_PIECE triple that represents
696 * the Xth register that the arguments are stored in.
700 /* Architecture specific instructions */
703 #define OP_SET_EQ 102
704 #define OP_SET_NOTEQ 103
705 #define OP_SET_SLESS 104
706 #define OP_SET_ULESS 105
707 #define OP_SET_SMORE 106
708 #define OP_SET_UMORE 107
709 #define OP_SET_SLESSEQ 108
710 #define OP_SET_ULESSEQ 109
711 #define OP_SET_SMOREEQ 110
712 #define OP_SET_UMOREEQ 111
715 #define OP_JMP_EQ 113
716 #define OP_JMP_NOTEQ 114
717 #define OP_JMP_SLESS 115
718 #define OP_JMP_ULESS 116
719 #define OP_JMP_SMORE 117
720 #define OP_JMP_UMORE 118
721 #define OP_JMP_SLESSEQ 119
722 #define OP_JMP_ULESSEQ 120
723 #define OP_JMP_SMOREEQ 121
724 #define OP_JMP_UMOREEQ 122
726 /* Builtin operators that it is just simpler to use the compiler for */
742 #define PURE 0x001 /* Triple has no side effects */
743 #define IMPURE 0x002 /* Triple has side effects */
744 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
745 #define DEF 0x004 /* Triple is a variable definition */
746 #define BLOCK 0x008 /* Triple stores the current block */
747 #define STRUCTURAL 0x010 /* Triple does not generate a machine instruction */
748 #define BRANCH_BITS(FLAGS) ((FLAGS) & 0xe0 )
749 #define UBRANCH 0x020 /* Triple is an unconditional branch instruction */
750 #define CBRANCH 0x040 /* Triple is a conditional branch instruction */
751 #define RETBRANCH 0x060 /* Triple is a return instruction */
752 #define CALLBRANCH 0x080 /* Triple is a call instruction */
753 #define ENDBRANCH 0x0a0 /* Triple is an end instruction */
754 #define PART 0x100 /* Triple is really part of another triple */
755 #define BITFIELD 0x200 /* Triple manipulates a bitfield */
756 signed char lhs, rhs, misc, targ;
759 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
767 static const struct op_info table_ops[] = {
768 [OP_SDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "sdivt"),
769 [OP_UDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "udivt"),
770 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
771 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
772 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
773 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
774 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
775 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
776 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
777 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
778 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
779 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
780 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
781 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
782 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
783 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
784 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
785 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
786 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
788 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
789 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
790 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
791 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
792 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
793 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
794 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
795 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
796 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
797 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
798 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
799 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
801 [OP_LOAD ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "load"),
802 [OP_STORE ] = OP( 0, 2, 0, 0, PURE | BLOCK , "store"),
804 [OP_UEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "uextract"),
805 [OP_SEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "sextract"),
806 [OP_DEPOSIT ] = OP( 0, 2, 0, 0, PURE | DEF | BITFIELD, "deposit"),
808 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "noop"),
810 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
811 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE , "blobconst"),
812 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
813 [OP_UNKNOWNVAL ] = OP( 0, 0, 0, 0, PURE | DEF, "unknown"),
815 #if DEBUG_ROMCC_WARNINGS
816 #warning "FIXME is it correct for OP_WRITE to be a def? I currently use it as one..."
818 [OP_WRITE ] = OP( 0, 1, 1, 0, PURE | DEF | BLOCK, "write"),
819 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
820 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
821 [OP_CONVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "convert"),
822 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF | STRUCTURAL | PART, "piece"),
823 [OP_ASM ] = OP(-1, -1, 0, 0, PURE, "asm"),
824 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
825 [OP_DOT ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "dot"),
826 [OP_INDEX ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "index"),
828 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
829 [OP_TUPLE ] = OP(-1, 0, 0, 0, 0 | PURE | BLOCK | STRUCTURAL, "tuple"),
830 [OP_BITREF ] = OP( 0, 1, 0, 0, 0 | DEF | PURE | STRUCTURAL | BITFIELD, "bitref"),
831 /* Call is special most it can stand in for anything so it depends on context */
832 [OP_FCALL ] = OP( 0, -1, 1, 0, 0 | BLOCK | CALLBRANCH, "fcall"),
833 [OP_PROG ] = OP( 0, 1, 0, 0, 0 | IMPURE | BLOCK | STRUCTURAL, "prog"),
834 /* The sizes of OP_FCALL depends upon context */
836 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF | STRUCTURAL, "list"),
837 [OP_BRANCH ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "branch"),
838 [OP_CBRANCH ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "cbranch"),
839 [OP_CALL ] = OP( 0, 0, 1, 1, PURE | BLOCK | CALLBRANCH, "call"),
840 [OP_RET ] = OP( 0, 1, 0, 0, PURE | BLOCK | RETBRANCH, "ret"),
841 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "label"),
842 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "adecl"),
843 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK | STRUCTURAL, "sdecl"),
844 /* The number of RHS elements of OP_PHI depend upon context */
845 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
848 [OP_CPS_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK | UBRANCH, "cps_branch"),
849 [OP_CPS_CBRANCH] = OP( 0, -1, 0, 1, PURE | BLOCK | CBRANCH, "cps_cbranch"),
850 [OP_CPS_CALL ] = OP( 0, -1, 1, 1, PURE | BLOCK | CALLBRANCH, "cps_call"),
851 [OP_CPS_RET ] = OP( 0, -1, 0, 0, PURE | BLOCK | RETBRANCH, "cps_ret"),
852 [OP_CPS_END ] = OP( 0, -1, 0, 0, IMPURE | BLOCK | ENDBRANCH, "cps_end"),
853 [OP_CPS_START ] = OP( -1, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "cps_start"),
856 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
857 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
858 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
859 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
860 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
861 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
862 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
863 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
864 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
865 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
866 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
867 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
868 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "jmp"),
869 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_eq"),
870 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_noteq"),
871 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_sless"),
872 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_uless"),
873 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smore"),
874 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umore"),
875 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_slesseq"),
876 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_ulesseq"),
877 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smoreq"),
878 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umoreq"),
880 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
881 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
882 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
883 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
884 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
885 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
886 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
887 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
888 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
889 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
890 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
893 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
895 static const char *tops(int index)
897 static const char unknown[] = "unknown op";
901 if (index > OP_MAX) {
904 return table_ops[index].name;
911 struct triple_set *next;
912 struct triple *member;
922 const char *filename;
923 const char *function;
926 struct occurance *parent;
933 struct triple *next, *prev;
934 struct triple_set *use;
937 unsigned int template_id : 7;
938 unsigned int lhs : 6;
939 unsigned int rhs : 7;
940 unsigned int misc : 2;
941 unsigned int targ : 1;
942 #define TRIPLE_SIZE(TRIPLE) \
943 ((TRIPLE)->lhs + (TRIPLE)->rhs + (TRIPLE)->misc + (TRIPLE)->targ)
944 #define TRIPLE_LHS_OFF(PTR) (0)
945 #define TRIPLE_RHS_OFF(PTR) (TRIPLE_LHS_OFF(PTR) + (PTR)->lhs)
946 #define TRIPLE_MISC_OFF(PTR) (TRIPLE_RHS_OFF(PTR) + (PTR)->rhs)
947 #define TRIPLE_TARG_OFF(PTR) (TRIPLE_MISC_OFF(PTR) + (PTR)->misc)
948 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF(PTR) + (INDEX)])
949 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF(PTR) + (INDEX)])
950 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF(PTR) + (INDEX)])
951 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF(PTR) + (INDEX)])
952 unsigned id; /* A scratch value and finally the register */
953 #define TRIPLE_FLAG_FLATTENED (1 << 31)
954 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
955 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
956 #define TRIPLE_FLAG_VOLATILE (1 << 28)
957 #define TRIPLE_FLAG_INLINE (1 << 27) /* ???? */
958 #define TRIPLE_FLAG_LOCAL (1 << 26)
960 #define TRIPLE_FLAG_COPY TRIPLE_FLAG_VOLATILE
961 struct occurance *occurance;
964 struct bitfield bitfield;
967 struct hash_entry *field;
968 struct asm_info *ainfo;
970 struct symbol *symbol;
972 struct triple *param[2];
979 struct ins_template {
980 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
984 struct ins_template tmpl;
989 struct block_set *next;
990 struct block *member;
993 struct block *work_next;
994 struct triple *first, *last;
996 struct block_set *edges;
998 struct block_set *use;
999 struct block_set *idominates;
1000 struct block_set *domfrontier;
1002 struct block_set *ipdominates;
1003 struct block_set *ipdomfrontier;
1004 struct block *ipdom;
1010 struct symbol *next;
1011 struct hash_entry *ident;
1018 struct macro_arg *next;
1019 struct hash_entry *ident;
1022 struct hash_entry *ident;
1025 struct macro_arg *args;
1030 struct hash_entry *next;
1034 struct macro *sym_define;
1035 struct symbol *sym_label;
1036 struct symbol *sym_tag;
1037 struct symbol *sym_ident;
1040 #define HASH_TABLE_SIZE 2048
1042 struct compiler_state {
1043 const char *label_prefix;
1044 const char *ofilename;
1045 unsigned long flags;
1046 unsigned long debug;
1047 unsigned long max_allocation_passes;
1049 size_t include_path_count;
1050 const char **include_paths;
1052 size_t define_count;
1053 const char **defines;
1056 const char **undefs;
1059 unsigned long features;
1061 struct basic_blocks {
1062 struct triple *func;
1063 struct triple *first;
1064 struct block *first_block, *last_block;
1067 #define MAX_PP_IF_DEPTH 63
1068 struct compile_state {
1069 struct compiler_state *compiler;
1070 struct arch_state *arch;
1074 struct file_state *file;
1075 struct occurance *last_occurance;
1076 const char *function;
1078 struct token token[6];
1079 struct hash_entry *hash_table[HASH_TABLE_SIZE];
1080 struct hash_entry *i_switch;
1081 struct hash_entry *i_case;
1082 struct hash_entry *i_continue;
1083 struct hash_entry *i_break;
1084 struct hash_entry *i_default;
1085 struct hash_entry *i_return;
1086 struct hash_entry *i_noreturn;
1087 /* Additional hash entries for predefined macros */
1088 struct hash_entry *i_defined;
1089 struct hash_entry *i___VA_ARGS__;
1090 struct hash_entry *i___FILE__;
1091 struct hash_entry *i___LINE__;
1092 /* Additional hash entries for predefined identifiers */
1093 struct hash_entry *i___func__;
1094 /* Additional hash entries for attributes */
1095 struct hash_entry *i_noinline;
1096 struct hash_entry *i_always_inline;
1098 unsigned char if_bytes[(MAX_PP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1100 int eat_depth, eat_targ;
1101 struct file_state *macro_file;
1102 struct triple *functions;
1103 struct triple *main_function;
1104 struct triple *first;
1105 struct triple *global_pool;
1106 struct basic_blocks bb;
1107 int functions_joined;
1110 /* visibility global/local */
1111 /* static/auto duration */
1112 /* typedef, register, inline */
1113 #define STOR_SHIFT 0
1114 #define STOR_MASK 0x001f
1116 #define STOR_GLOBAL 0x0001
1118 #define STOR_PERM 0x0002
1119 /* Definition locality */
1120 #define STOR_NONLOCAL 0x0004 /* The definition is not in this translation unit */
1121 /* Storage specifiers */
1122 #define STOR_AUTO 0x0000
1123 #define STOR_STATIC 0x0002
1124 #define STOR_LOCAL 0x0003
1125 #define STOR_EXTERN 0x0007
1126 #define STOR_INLINE 0x0008
1127 #define STOR_REGISTER 0x0010
1128 #define STOR_TYPEDEF 0x0018
1130 #define QUAL_SHIFT 5
1131 #define QUAL_MASK 0x00e0
1132 #define QUAL_NONE 0x0000
1133 #define QUAL_CONST 0x0020
1134 #define QUAL_VOLATILE 0x0040
1135 #define QUAL_RESTRICT 0x0080
1137 #define TYPE_SHIFT 8
1138 #define TYPE_MASK 0x1f00
1139 #define TYPE_INTEGER(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1140 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1141 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
1142 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
1143 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1144 #define TYPE_RANK(TYPE) ((TYPE) & ~0xF1FF)
1145 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1146 #define TYPE_DEFAULT 0x0000
1147 #define TYPE_VOID 0x0100
1148 #define TYPE_CHAR 0x0200
1149 #define TYPE_UCHAR 0x0300
1150 #define TYPE_SHORT 0x0400
1151 #define TYPE_USHORT 0x0500
1152 #define TYPE_INT 0x0600
1153 #define TYPE_UINT 0x0700
1154 #define TYPE_LONG 0x0800
1155 #define TYPE_ULONG 0x0900
1156 #define TYPE_LLONG 0x0a00 /* long long */
1157 #define TYPE_ULLONG 0x0b00
1158 #define TYPE_FLOAT 0x0c00
1159 #define TYPE_DOUBLE 0x0d00
1160 #define TYPE_LDOUBLE 0x0e00 /* long double */
1162 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1163 #define TYPE_ENUM 0x1600
1164 #define TYPE_LIST 0x1700
1165 /* TYPE_LIST is a basic building block when defining enumerations
1166 * type->field_ident holds the name of this enumeration entry.
1167 * type->right holds the entry in the list.
1170 #define TYPE_STRUCT 0x1000
1172 * type->left holds the link list of TYPE_PRODUCT entries that
1173 * make up the structure.
1174 * type->elements hold the length of the linked list
1176 #define TYPE_UNION 0x1100
1178 * type->left holds the link list of TYPE_OVERLAP entries that
1179 * make up the union.
1180 * type->elements hold the length of the linked list
1182 #define TYPE_POINTER 0x1200
1183 /* For TYPE_POINTER:
1184 * type->left holds the type pointed to.
1186 #define TYPE_FUNCTION 0x1300
1187 /* For TYPE_FUNCTION:
1188 * type->left holds the return type.
1189 * type->right holds the type of the arguments
1190 * type->elements holds the count of the arguments
1192 #define TYPE_PRODUCT 0x1400
1193 /* TYPE_PRODUCT is a basic building block when defining structures
1194 * type->left holds the type that appears first in memory.
1195 * type->right holds the type that appears next in memory.
1197 #define TYPE_OVERLAP 0x1500
1198 /* TYPE_OVERLAP is a basic building block when defining unions
1199 * type->left and type->right holds to types that overlap
1200 * each other in memory.
1202 #define TYPE_ARRAY 0x1800
1203 /* TYPE_ARRAY is a basic building block when definitng arrays.
1204 * type->left holds the type we are an array of.
1205 * type->elements holds the number of elements.
1207 #define TYPE_TUPLE 0x1900
1208 /* TYPE_TUPLE is a basic building block when defining
1209 * positionally reference type conglomerations. (i.e. closures)
1210 * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1211 * except it has no field names.
1212 * type->left holds the liked list of TYPE_PRODUCT entries that
1213 * make up the closure type.
1214 * type->elements hold the number of elements in the closure.
1216 #define TYPE_JOIN 0x1a00
1217 /* TYPE_JOIN is a basic building block when defining
1218 * positionally reference type conglomerations. (i.e. closures)
1219 * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1220 * except it has no field names.
1221 * type->left holds the liked list of TYPE_OVERLAP entries that
1222 * make up the closure type.
1223 * type->elements hold the number of elements in the closure.
1225 #define TYPE_BITFIELD 0x1b00
1226 /* TYPE_BITFIED is the type of a bitfield.
1227 * type->left holds the type basic type TYPE_BITFIELD is derived from.
1228 * type->elements holds the number of bits in the bitfield.
1230 #define TYPE_UNKNOWN 0x1c00
1231 /* TYPE_UNKNOWN is the type of an unknown value.
1232 * Used on unknown consts and other places where I don't know the type.
1235 #define ATTRIB_SHIFT 16
1236 #define ATTRIB_MASK 0xffff0000
1237 #define ATTRIB_NOINLINE 0x00010000
1238 #define ATTRIB_ALWAYS_INLINE 0x00020000
1240 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1244 struct type *left, *right;
1246 struct hash_entry *field_ident;
1247 struct hash_entry *type_ident;
1250 #define TEMPLATE_BITS 7
1251 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
1252 #define MAX_REG_EQUIVS 16
1254 #define MAX_REGISTERS 75
1255 #define REGISTER_BITS 7
1256 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1259 #define REG_UNNEEDED 2
1260 #define REG_VIRT0 (MAX_REGISTERS + 0)
1261 #define REG_VIRT1 (MAX_REGISTERS + 1)
1262 #define REG_VIRT2 (MAX_REGISTERS + 2)
1263 #define REG_VIRT3 (MAX_REGISTERS + 3)
1264 #define REG_VIRT4 (MAX_REGISTERS + 4)
1265 #define REG_VIRT5 (MAX_REGISTERS + 5)
1266 #define REG_VIRT6 (MAX_REGISTERS + 6)
1267 #define REG_VIRT7 (MAX_REGISTERS + 7)
1268 #define REG_VIRT8 (MAX_REGISTERS + 8)
1269 #define REG_VIRT9 (MAX_REGISTERS + 9)
1271 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1272 #error "MAX_VIRT_REGISTERS to small"
1274 #if (MAX_REGC + REGISTER_BITS) >= 26
1275 #error "Too many id bits used"
1278 /* Provision for 8 register classes */
1280 #define REGC_SHIFT REGISTER_BITS
1281 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1282 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1283 #define ID_REG(ID) ((ID) & REG_MASK)
1284 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1285 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
1286 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1287 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1288 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1290 #define ARCH_INPUT_REGS 4
1291 #define ARCH_OUTPUT_REGS 4
1293 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1294 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1295 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1296 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1297 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1298 static void arch_reg_equivs(
1299 struct compile_state *state, unsigned *equiv, int reg);
1300 static int arch_select_free_register(
1301 struct compile_state *state, char *used, int classes);
1302 static unsigned arch_regc_size(struct compile_state *state, int class);
1303 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1304 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1305 static const char *arch_reg_str(int reg);
1306 static struct reg_info arch_reg_constraint(
1307 struct compile_state *state, struct type *type, const char *constraint);
1308 static struct reg_info arch_reg_clobber(
1309 struct compile_state *state, const char *clobber);
1310 static struct reg_info arch_reg_lhs(struct compile_state *state,
1311 struct triple *ins, int index);
1312 static struct reg_info arch_reg_rhs(struct compile_state *state,
1313 struct triple *ins, int index);
1314 static int arch_reg_size(int reg);
1315 static struct triple *transform_to_arch_instruction(
1316 struct compile_state *state, struct triple *ins);
1317 static struct triple *flatten(
1318 struct compile_state *state, struct triple *first, struct triple *ptr);
1319 static void print_dominators(struct compile_state *state,
1320 FILE *fp, struct basic_blocks *bb);
1321 static void print_dominance_frontiers(struct compile_state *state,
1322 FILE *fp, struct basic_blocks *bb);
1326 #define DEBUG_ABORT_ON_ERROR 0x00000001
1327 #define DEBUG_BASIC_BLOCKS 0x00000002
1328 #define DEBUG_FDOMINATORS 0x00000004
1329 #define DEBUG_RDOMINATORS 0x00000008
1330 #define DEBUG_TRIPLES 0x00000010
1331 #define DEBUG_INTERFERENCE 0x00000020
1332 #define DEBUG_SCC_TRANSFORM 0x00000040
1333 #define DEBUG_SCC_TRANSFORM2 0x00000080
1334 #define DEBUG_REBUILD_SSA_FORM 0x00000100
1335 #define DEBUG_INLINE 0x00000200
1336 #define DEBUG_RANGE_CONFLICTS 0x00000400
1337 #define DEBUG_RANGE_CONFLICTS2 0x00000800
1338 #define DEBUG_COLOR_GRAPH 0x00001000
1339 #define DEBUG_COLOR_GRAPH2 0x00002000
1340 #define DEBUG_COALESCING 0x00004000
1341 #define DEBUG_COALESCING2 0x00008000
1342 #define DEBUG_VERIFICATION 0x00010000
1343 #define DEBUG_CALLS 0x00020000
1344 #define DEBUG_CALLS2 0x00040000
1345 #define DEBUG_TOKENS 0x80000000
1347 #define DEBUG_DEFAULT ( \
1348 DEBUG_ABORT_ON_ERROR | \
1349 DEBUG_BASIC_BLOCKS | \
1350 DEBUG_FDOMINATORS | \
1351 DEBUG_RDOMINATORS | \
1355 #define DEBUG_ALL ( \
1356 DEBUG_ABORT_ON_ERROR | \
1357 DEBUG_BASIC_BLOCKS | \
1358 DEBUG_FDOMINATORS | \
1359 DEBUG_RDOMINATORS | \
1361 DEBUG_INTERFERENCE | \
1362 DEBUG_SCC_TRANSFORM | \
1363 DEBUG_SCC_TRANSFORM2 | \
1364 DEBUG_REBUILD_SSA_FORM | \
1366 DEBUG_RANGE_CONFLICTS | \
1367 DEBUG_RANGE_CONFLICTS2 | \
1368 DEBUG_COLOR_GRAPH | \
1369 DEBUG_COLOR_GRAPH2 | \
1370 DEBUG_COALESCING | \
1371 DEBUG_COALESCING2 | \
1372 DEBUG_VERIFICATION | \
1378 #define COMPILER_INLINE_MASK 0x00000007
1379 #define COMPILER_INLINE_ALWAYS 0x00000000
1380 #define COMPILER_INLINE_NEVER 0x00000001
1381 #define COMPILER_INLINE_DEFAULTON 0x00000002
1382 #define COMPILER_INLINE_DEFAULTOFF 0x00000003
1383 #define COMPILER_INLINE_NOPENALTY 0x00000004
1384 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1385 #define COMPILER_SIMPLIFY 0x00000010
1386 #define COMPILER_SCC_TRANSFORM 0x00000020
1387 #define COMPILER_SIMPLIFY_OP 0x00000040
1388 #define COMPILER_SIMPLIFY_PHI 0x00000080
1389 #define COMPILER_SIMPLIFY_LABEL 0x00000100
1390 #define COMPILER_SIMPLIFY_BRANCH 0x00000200
1391 #define COMPILER_SIMPLIFY_COPY 0x00000400
1392 #define COMPILER_SIMPLIFY_ARITH 0x00000800
1393 #define COMPILER_SIMPLIFY_SHIFT 0x00001000
1394 #define COMPILER_SIMPLIFY_BITWISE 0x00002000
1395 #define COMPILER_SIMPLIFY_LOGICAL 0x00004000
1396 #define COMPILER_SIMPLIFY_BITFIELD 0x00008000
1398 #define COMPILER_TRIGRAPHS 0x40000000
1399 #define COMPILER_PP_ONLY 0x80000000
1401 #define COMPILER_DEFAULT_FLAGS ( \
1402 COMPILER_TRIGRAPHS | \
1403 COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1404 COMPILER_INLINE_DEFAULTON | \
1405 COMPILER_SIMPLIFY_OP | \
1406 COMPILER_SIMPLIFY_PHI | \
1407 COMPILER_SIMPLIFY_LABEL | \
1408 COMPILER_SIMPLIFY_BRANCH | \
1409 COMPILER_SIMPLIFY_COPY | \
1410 COMPILER_SIMPLIFY_ARITH | \
1411 COMPILER_SIMPLIFY_SHIFT | \
1412 COMPILER_SIMPLIFY_BITWISE | \
1413 COMPILER_SIMPLIFY_LOGICAL | \
1414 COMPILER_SIMPLIFY_BITFIELD | \
1417 #define GLOBAL_SCOPE_DEPTH 1
1418 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1420 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1424 static void init_compiler_state(struct compiler_state *compiler)
1426 memset(compiler, 0, sizeof(*compiler));
1427 compiler->label_prefix = "";
1428 compiler->ofilename = "auto.inc";
1429 compiler->flags = COMPILER_DEFAULT_FLAGS;
1430 compiler->debug = 0;
1431 compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1432 compiler->include_path_count = 1;
1433 compiler->include_paths = xcmalloc(sizeof(char *), "include_paths");
1434 compiler->define_count = 1;
1435 compiler->defines = xcmalloc(sizeof(char *), "defines");
1436 compiler->undef_count = 1;
1437 compiler->undefs = xcmalloc(sizeof(char *), "undefs");
1440 struct compiler_flag {
1445 struct compiler_arg {
1448 struct compiler_flag flags[16];
1451 static int set_flag(
1452 const struct compiler_flag *ptr, unsigned long *flags,
1453 int act, const char *flag)
1456 for(; ptr->name; ptr++) {
1457 if (strcmp(ptr->name, flag) == 0) {
1463 *flags &= ~(ptr->flag);
1465 *flags |= ptr->flag;
1472 const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1477 val = strchr(arg, '=');
1481 for(; ptr->name; ptr++) {
1482 if (strncmp(ptr->name, arg, len) == 0) {
1487 *flags &= ~ptr->mask;
1488 result = set_flag(&ptr->flags[0], flags, 1, val);
1495 static void flag_usage(FILE *fp, const struct compiler_flag *ptr,
1496 const char *prefix, const char *invert_prefix)
1498 for(;ptr->name; ptr++) {
1499 fprintf(fp, "%s%s\n", prefix, ptr->name);
1500 if (invert_prefix) {
1501 fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1506 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1509 for(;ptr->name; ptr++) {
1510 const struct compiler_flag *flag;
1511 for(flag = &ptr->flags[0]; flag->name; flag++) {
1512 fprintf(fp, "%s%s=%s\n",
1513 prefix, ptr->name, flag->name);
1518 static int append_string(size_t *max, const char ***vec, const char *str,
1523 *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1524 (*vec)[count -1] = 0;
1525 (*vec)[count -2] = str;
1529 static void arg_error(char *fmt, ...);
1530 static const char *identifier(const char *str, const char *end);
1532 static int append_include_path(struct compiler_state *compiler, const char *str)
1535 if (!exists(str, ".")) {
1536 arg_error("Nonexistent include path: `%s'\n",
1539 result = append_string(&compiler->include_path_count,
1540 &compiler->include_paths, str, "include_paths");
1544 static int append_define(struct compiler_state *compiler, const char *str)
1546 const char *end, *rest;
1549 end = strchr(str, '=');
1551 end = str + strlen(str);
1553 rest = identifier(str, end);
1555 int len = end - str - 1;
1556 arg_error("Invalid name cannot define macro: `%*.*s'\n",
1559 result = append_string(&compiler->define_count,
1560 &compiler->defines, str, "defines");
1564 static int append_undef(struct compiler_state *compiler, const char *str)
1566 const char *end, *rest;
1569 end = str + strlen(str);
1570 rest = identifier(str, end);
1572 int len = end - str - 1;
1573 arg_error("Invalid name cannot undefine macro: `%*.*s'\n",
1576 result = append_string(&compiler->undef_count,
1577 &compiler->undefs, str, "undefs");
1581 static const struct compiler_flag romcc_flags[] = {
1582 { "trigraphs", COMPILER_TRIGRAPHS },
1583 { "pp-only", COMPILER_PP_ONLY },
1584 { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1585 { "simplify", COMPILER_SIMPLIFY },
1586 { "scc-transform", COMPILER_SCC_TRANSFORM },
1587 { "simplify-op", COMPILER_SIMPLIFY_OP },
1588 { "simplify-phi", COMPILER_SIMPLIFY_PHI },
1589 { "simplify-label", COMPILER_SIMPLIFY_LABEL },
1590 { "simplify-branch", COMPILER_SIMPLIFY_BRANCH },
1591 { "simplify-copy", COMPILER_SIMPLIFY_COPY },
1592 { "simplify-arith", COMPILER_SIMPLIFY_ARITH },
1593 { "simplify-shift", COMPILER_SIMPLIFY_SHIFT },
1594 { "simplify-bitwise", COMPILER_SIMPLIFY_BITWISE },
1595 { "simplify-logical", COMPILER_SIMPLIFY_LOGICAL },
1596 { "simplify-bitfield", COMPILER_SIMPLIFY_BITFIELD },
1599 static const struct compiler_arg romcc_args[] = {
1600 { "inline-policy", COMPILER_INLINE_MASK,
1602 { "always", COMPILER_INLINE_ALWAYS, },
1603 { "never", COMPILER_INLINE_NEVER, },
1604 { "defaulton", COMPILER_INLINE_DEFAULTON, },
1605 { "defaultoff", COMPILER_INLINE_DEFAULTOFF, },
1606 { "nopenalty", COMPILER_INLINE_NOPENALTY, },
1612 static const struct compiler_flag romcc_opt_flags[] = {
1613 { "-O", COMPILER_SIMPLIFY },
1614 { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1615 { "-E", COMPILER_PP_ONLY },
1618 static const struct compiler_flag romcc_debug_flags[] = {
1619 { "all", DEBUG_ALL },
1620 { "abort-on-error", DEBUG_ABORT_ON_ERROR },
1621 { "basic-blocks", DEBUG_BASIC_BLOCKS },
1622 { "fdominators", DEBUG_FDOMINATORS },
1623 { "rdominators", DEBUG_RDOMINATORS },
1624 { "triples", DEBUG_TRIPLES },
1625 { "interference", DEBUG_INTERFERENCE },
1626 { "scc-transform", DEBUG_SCC_TRANSFORM },
1627 { "scc-transform2", DEBUG_SCC_TRANSFORM2 },
1628 { "rebuild-ssa-form", DEBUG_REBUILD_SSA_FORM },
1629 { "inline", DEBUG_INLINE },
1630 { "live-range-conflicts", DEBUG_RANGE_CONFLICTS },
1631 { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1632 { "color-graph", DEBUG_COLOR_GRAPH },
1633 { "color-graph2", DEBUG_COLOR_GRAPH2 },
1634 { "coalescing", DEBUG_COALESCING },
1635 { "coalescing2", DEBUG_COALESCING2 },
1636 { "verification", DEBUG_VERIFICATION },
1637 { "calls", DEBUG_CALLS },
1638 { "calls2", DEBUG_CALLS2 },
1639 { "tokens", DEBUG_TOKENS },
1643 static int compiler_encode_flag(
1644 struct compiler_state *compiler, const char *flag)
1651 if (strncmp(flag, "no-", 3) == 0) {
1655 if (strncmp(flag, "-O", 2) == 0) {
1656 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1658 else if (strncmp(flag, "-E", 2) == 0) {
1659 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1661 else if (strncmp(flag, "-I", 2) == 0) {
1662 result = append_include_path(compiler, flag + 2);
1664 else if (strncmp(flag, "-D", 2) == 0) {
1665 result = append_define(compiler, flag + 2);
1667 else if (strncmp(flag, "-U", 2) == 0) {
1668 result = append_undef(compiler, flag + 2);
1670 else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1672 compiler->label_prefix = flag + 13;
1674 else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1675 unsigned long max_passes;
1677 max_passes = strtoul(flag + 22, &end, 10);
1678 if (end[0] == '\0') {
1680 compiler->max_allocation_passes = max_passes;
1683 else if (act && strcmp(flag, "debug") == 0) {
1685 compiler->debug |= DEBUG_DEFAULT;
1687 else if (strncmp(flag, "debug-", 6) == 0) {
1689 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1692 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1694 result = set_arg(romcc_args, &compiler->flags, flag);
1700 static void compiler_usage(FILE *fp)
1702 flag_usage(fp, romcc_opt_flags, "", 0);
1703 flag_usage(fp, romcc_flags, "-f", "-fno-");
1704 arg_usage(fp, romcc_args, "-f");
1705 flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1706 fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1707 fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1708 fprintf(fp, "-I<include path>\n");
1709 fprintf(fp, "-D<macro>[=defn]\n");
1710 fprintf(fp, "-U<macro>\n");
1713 static void do_cleanup(struct compile_state *state)
1715 if (state->output) {
1716 fclose(state->output);
1717 unlink(state->compiler->ofilename);
1720 if (state->dbgout) {
1721 fflush(state->dbgout);
1723 if (state->errout) {
1724 fflush(state->errout);
1728 static struct compile_state *exit_state;
1729 static void exit_cleanup(void)
1732 do_cleanup(exit_state);
1736 static int get_col(struct file_state *file)
1739 const char *ptr, *end;
1740 ptr = file->line_start;
1742 for(col = 0; ptr < end; ptr++) {
1747 col = (col & ~7) + 8;
1753 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1756 if (triple && triple->occurance) {
1757 struct occurance *spot;
1758 for(spot = triple->occurance; spot; spot = spot->parent) {
1759 fprintf(fp, "%s:%d.%d: ",
1760 spot->filename, spot->line, spot->col);
1767 col = get_col(state->file);
1768 fprintf(fp, "%s:%d.%d: ",
1769 state->file->report_name, state->file->report_line, col);
1772 static void __attribute__ ((noreturn)) internal_error(struct compile_state *state, struct triple *ptr,
1773 const char *fmt, ...)
1775 FILE *fp = state->errout;
1777 va_start(args, fmt);
1778 loc(fp, state, ptr);
1781 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1783 fprintf(fp, "Internal compiler error: ");
1784 vfprintf(fp, fmt, args);
1792 static void internal_warning(struct compile_state *state, struct triple *ptr,
1793 const char *fmt, ...)
1795 FILE *fp = state->errout;
1797 va_start(args, fmt);
1798 loc(fp, state, ptr);
1800 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1802 fprintf(fp, "Internal compiler warning: ");
1803 vfprintf(fp, fmt, args);
1810 static void __attribute__ ((noreturn)) error(struct compile_state *state, struct triple *ptr,
1811 const char *fmt, ...)
1813 FILE *fp = state->errout;
1815 va_start(args, fmt);
1816 loc(fp, state, ptr);
1818 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1819 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1821 vfprintf(fp, fmt, args);
1825 if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1831 static void warning(struct compile_state *state, struct triple *ptr,
1832 const char *fmt, ...)
1834 FILE *fp = state->errout;
1836 va_start(args, fmt);
1837 loc(fp, state, ptr);
1838 fprintf(fp, "warning: ");
1839 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1840 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1842 vfprintf(fp, fmt, args);
1847 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1849 static void valid_op(struct compile_state *state, int op)
1851 char *fmt = "invalid op: %d";
1853 internal_error(state, 0, fmt, op);
1856 internal_error(state, 0, fmt, op);
1860 static void valid_ins(struct compile_state *state, struct triple *ptr)
1862 valid_op(state, ptr->op);
1865 #if DEBUG_ROMCC_WARNING
1866 static void valid_param_count(struct compile_state *state, struct triple *ins)
1868 int lhs, rhs, misc, targ;
1869 valid_ins(state, ins);
1870 lhs = table_ops[ins->op].lhs;
1871 rhs = table_ops[ins->op].rhs;
1872 misc = table_ops[ins->op].misc;
1873 targ = table_ops[ins->op].targ;
1875 if ((lhs >= 0) && (ins->lhs != lhs)) {
1876 internal_error(state, ins, "Bad lhs count");
1878 if ((rhs >= 0) && (ins->rhs != rhs)) {
1879 internal_error(state, ins, "Bad rhs count");
1881 if ((misc >= 0) && (ins->misc != misc)) {
1882 internal_error(state, ins, "Bad misc count");
1884 if ((targ >= 0) && (ins->targ != targ)) {
1885 internal_error(state, ins, "Bad targ count");
1890 static struct type void_type;
1891 static struct type unknown_type;
1892 static void use_triple(struct triple *used, struct triple *user)
1894 struct triple_set **ptr, *new;
1901 if ((*ptr)->member == user) {
1904 ptr = &(*ptr)->next;
1906 /* Append new to the head of the list,
1907 * copy_func and rename_block_variables
1910 new = xcmalloc(sizeof(*new), "triple_set");
1912 new->next = used->use;
1916 static void unuse_triple(struct triple *used, struct triple *unuser)
1918 struct triple_set *use, **ptr;
1925 if (use->member == unuser) {
1935 static void put_occurance(struct occurance *occurance)
1938 occurance->count -= 1;
1939 if (occurance->count <= 0) {
1940 if (occurance->parent) {
1941 put_occurance(occurance->parent);
1948 static void get_occurance(struct occurance *occurance)
1951 occurance->count += 1;
1956 static struct occurance *new_occurance(struct compile_state *state)
1958 struct occurance *result, *last;
1959 const char *filename;
1960 const char *function;
1968 filename = state->file->report_name;
1969 line = state->file->report_line;
1970 col = get_col(state->file);
1972 if (state->function) {
1973 function = state->function;
1975 last = state->last_occurance;
1977 (last->col == col) &&
1978 (last->line == line) &&
1979 (last->function == function) &&
1980 ((last->filename == filename) ||
1981 (strcmp(last->filename, filename) == 0)))
1983 get_occurance(last);
1987 state->last_occurance = 0;
1988 put_occurance(last);
1990 result = xmalloc(sizeof(*result), "occurance");
1992 result->filename = filename;
1993 result->function = function;
1994 result->line = line;
1997 state->last_occurance = result;
2001 static struct occurance *inline_occurance(struct compile_state *state,
2002 struct occurance *base, struct occurance *top)
2004 struct occurance *result, *last;
2006 internal_error(state, 0, "inlining an already inlined function?");
2008 /* If I have a null base treat it that way */
2009 if ((base->parent == 0) &&
2011 (base->line == 0) &&
2012 (base->function[0] == '\0') &&
2013 (base->filename[0] == '\0')) {
2016 /* See if I can reuse the last occurance I had */
2017 last = state->last_occurance;
2019 (last->parent == base) &&
2020 (last->col == top->col) &&
2021 (last->line == top->line) &&
2022 (last->function == top->function) &&
2023 (last->filename == top->filename)) {
2024 get_occurance(last);
2027 /* I can't reuse the last occurance so free it */
2029 state->last_occurance = 0;
2030 put_occurance(last);
2032 /* Generate a new occurance structure */
2033 get_occurance(base);
2034 result = xmalloc(sizeof(*result), "occurance");
2036 result->filename = top->filename;
2037 result->function = top->function;
2038 result->line = top->line;
2039 result->col = top->col;
2040 result->parent = base;
2041 state->last_occurance = result;
2045 static struct occurance dummy_occurance = {
2047 .filename = __FILE__,
2054 /* The undef triple is used as a place holder when we are removing pointers
2055 * from a triple. Having allows certain sanity checks to pass even
2056 * when the original triple that was pointed to is gone.
2058 static struct triple unknown_triple = {
2059 .next = &unknown_triple,
2060 .prev = &unknown_triple,
2062 .op = OP_UNKNOWNVAL,
2067 .type = &unknown_type,
2068 .id = -1, /* An invalid id */
2069 .u = { .cval = 0, },
2070 .occurance = &dummy_occurance,
2071 .param = { [0] = 0, [1] = 0, },
2075 static size_t registers_of(struct compile_state *state, struct type *type);
2077 static struct triple *alloc_triple(struct compile_state *state,
2078 int op, struct type *type, int lhs_wanted, int rhs_wanted,
2079 struct occurance *occurance)
2081 size_t size, extra_count, min_count;
2082 int lhs, rhs, misc, targ;
2083 struct triple *ret, dummy;
2085 dummy.occurance = occurance;
2086 valid_op(state, op);
2087 lhs = table_ops[op].lhs;
2088 rhs = table_ops[op].rhs;
2089 misc = table_ops[op].misc;
2090 targ = table_ops[op].targ;
2100 lhs = registers_of(state, type);
2103 lhs = registers_of(state, type);
2110 if ((rhs < 0) || (rhs > MAX_RHS)) {
2111 internal_error(state, &dummy, "bad rhs count %d", rhs);
2113 if ((lhs < 0) || (lhs > MAX_LHS)) {
2114 internal_error(state, &dummy, "bad lhs count %d", lhs);
2116 if ((misc < 0) || (misc > MAX_MISC)) {
2117 internal_error(state, &dummy, "bad misc count %d", misc);
2119 if ((targ < 0) || (targ > MAX_TARG)) {
2120 internal_error(state, &dummy, "bad targs count %d", targ);
2123 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2124 extra_count = lhs + rhs + misc + targ;
2125 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2127 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2128 ret = xcmalloc(size, "tripple");
2137 ret->occurance = occurance;
2138 /* A simple sanity check */
2139 if ((ret->op != op) ||
2140 (ret->lhs != lhs) ||
2141 (ret->rhs != rhs) ||
2142 (ret->misc != misc) ||
2143 (ret->targ != targ) ||
2144 (ret->type != type) ||
2145 (ret->next != ret) ||
2146 (ret->prev != ret) ||
2147 (ret->occurance != occurance)) {
2148 internal_error(state, ret, "huh?");
2153 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2156 int src_lhs, src_rhs, src_size;
2159 src_size = TRIPLE_SIZE(src);
2160 get_occurance(src->occurance);
2161 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2163 memcpy(dup, src, sizeof(*src));
2164 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2168 static struct triple *copy_triple(struct compile_state *state, struct triple *src)
2170 struct triple *copy;
2171 copy = dup_triple(state, src);
2173 copy->next = copy->prev = copy;
2177 static struct triple *new_triple(struct compile_state *state,
2178 int op, struct type *type, int lhs, int rhs)
2181 struct occurance *occurance;
2182 occurance = new_occurance(state);
2183 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2187 static struct triple *build_triple(struct compile_state *state,
2188 int op, struct type *type, struct triple *left, struct triple *right,
2189 struct occurance *occurance)
2193 ret = alloc_triple(state, op, type, -1, -1, occurance);
2194 count = TRIPLE_SIZE(ret);
2196 ret->param[0] = left;
2199 ret->param[1] = right;
2204 static struct triple *triple(struct compile_state *state,
2205 int op, struct type *type, struct triple *left, struct triple *right)
2209 ret = new_triple(state, op, type, -1, -1);
2210 count = TRIPLE_SIZE(ret);
2212 ret->param[0] = left;
2215 ret->param[1] = right;
2220 static struct triple *branch(struct compile_state *state,
2221 struct triple *targ, struct triple *test)
2225 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2228 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2230 TARG(ret, 0) = targ;
2231 /* record the branch target was used */
2232 if (!targ || (targ->op != OP_LABEL)) {
2233 internal_error(state, 0, "branch not to label");
2238 static int triple_is_label(struct compile_state *state, struct triple *ins);
2239 static int triple_is_call(struct compile_state *state, struct triple *ins);
2240 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2241 static void insert_triple(struct compile_state *state,
2242 struct triple *first, struct triple *ptr)
2245 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2246 internal_error(state, ptr, "expression already used");
2249 ptr->prev = first->prev;
2250 ptr->prev->next = ptr;
2251 ptr->next->prev = ptr;
2253 if (triple_is_cbranch(state, ptr->prev) ||
2254 triple_is_call(state, ptr->prev)) {
2255 unuse_triple(first, ptr->prev);
2256 use_triple(ptr, ptr->prev);
2261 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2263 /* This function is used to determine if u.block
2264 * is utilized to store the current block number.
2267 valid_ins(state, ins);
2268 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2269 return stores_block;
2272 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2273 static struct block *block_of_triple(struct compile_state *state,
2276 struct triple *first;
2277 if (!ins || ins == &unknown_triple) {
2280 first = state->first;
2281 while(ins != first && !triple_is_branch(state, ins->prev) &&
2282 !triple_stores_block(state, ins))
2284 if (ins == ins->prev) {
2285 internal_error(state, ins, "ins == ins->prev?");
2289 return triple_stores_block(state, ins)? ins->u.block: 0;
2292 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2293 static struct triple *pre_triple(struct compile_state *state,
2294 struct triple *base,
2295 int op, struct type *type, struct triple *left, struct triple *right)
2297 struct block *block;
2300 /* If I am an OP_PIECE jump to the real instruction */
2301 if (base->op == OP_PIECE) {
2302 base = MISC(base, 0);
2304 block = block_of_triple(state, base);
2305 get_occurance(base->occurance);
2306 ret = build_triple(state, op, type, left, right, base->occurance);
2307 generate_lhs_pieces(state, ret);
2308 if (triple_stores_block(state, ret)) {
2309 ret->u.block = block;
2311 insert_triple(state, base, ret);
2312 for(i = 0; i < ret->lhs; i++) {
2313 struct triple *piece;
2314 piece = LHS(ret, i);
2315 insert_triple(state, base, piece);
2316 use_triple(ret, piece);
2317 use_triple(piece, ret);
2319 if (block && (block->first == base)) {
2325 static struct triple *post_triple(struct compile_state *state,
2326 struct triple *base,
2327 int op, struct type *type, struct triple *left, struct triple *right)
2329 struct block *block;
2330 struct triple *ret, *next;
2332 /* If I am an OP_PIECE jump to the real instruction */
2333 if (base->op == OP_PIECE) {
2334 base = MISC(base, 0);
2336 /* If I have a left hand side skip over it */
2339 base = LHS(base, zlhs - 1);
2342 block = block_of_triple(state, base);
2343 get_occurance(base->occurance);
2344 ret = build_triple(state, op, type, left, right, base->occurance);
2345 generate_lhs_pieces(state, ret);
2346 if (triple_stores_block(state, ret)) {
2347 ret->u.block = block;
2350 insert_triple(state, next, ret);
2352 for(i = 0; i < zlhs; i++) {
2353 struct triple *piece;
2354 piece = LHS(ret, i);
2355 insert_triple(state, next, piece);
2356 use_triple(ret, piece);
2357 use_triple(piece, ret);
2359 if (block && (block->last == base)) {
2362 block->last = LHS(ret, zlhs - 1);
2368 static struct type *reg_type(
2369 struct compile_state *state, struct type *type, int reg);
2371 static void generate_lhs_piece(
2372 struct compile_state *state, struct triple *ins, int index)
2374 struct type *piece_type;
2375 struct triple *piece;
2376 get_occurance(ins->occurance);
2377 piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2379 if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2380 piece_type = piece_type->left;
2384 static void name_of(FILE *fp, struct type *type);
2385 FILE * fp = state->errout;
2386 fprintf(fp, "piece_type(%d): ", index);
2387 name_of(fp, piece_type);
2391 piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2392 piece->u.cval = index;
2393 LHS(ins, piece->u.cval) = piece;
2394 MISC(piece, 0) = ins;
2397 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2401 for(i = 0; i < zlhs; i++) {
2402 generate_lhs_piece(state, ins, i);
2406 static struct triple *label(struct compile_state *state)
2408 /* Labels don't get a type */
2409 struct triple *result;
2410 result = triple(state, OP_LABEL, &void_type, 0, 0);
2414 static struct triple *mkprog(struct compile_state *state, ...)
2416 struct triple *prog, *head, *arg;
2420 head = label(state);
2421 prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2422 RHS(prog, 0) = head;
2423 va_start(args, state);
2425 while((arg = va_arg(args, struct triple *)) != 0) {
2427 internal_error(state, 0, "too many arguments to mkprog");
2429 flatten(state, head, arg);
2432 prog->type = head->prev->type;
2435 static void name_of(FILE *fp, struct type *type);
2436 static void display_triple(FILE *fp, struct triple *ins)
2438 struct occurance *ptr;
2440 char pre, post, vol;
2441 pre = post = vol = ' ';
2443 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2446 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2449 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2452 reg = arch_reg_str(ID_REG(ins->id));
2455 fprintf(fp, "(%p) <nothing> ", ins);
2457 else if (ins->op == OP_INTCONST) {
2458 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx> ",
2459 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2460 (unsigned long)(ins->u.cval));
2462 else if (ins->op == OP_ADDRCONST) {
2463 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2464 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2465 MISC(ins, 0), (unsigned long)(ins->u.cval));
2467 else if (ins->op == OP_INDEX) {
2468 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2469 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2470 RHS(ins, 0), (unsigned long)(ins->u.cval));
2472 else if (ins->op == OP_PIECE) {
2473 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2474 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2475 MISC(ins, 0), (unsigned long)(ins->u.cval));
2479 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s",
2480 ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2481 if (table_ops[ins->op].flags & BITFIELD) {
2482 fprintf(fp, " <%2d-%2d:%2d>",
2483 ins->u.bitfield.offset,
2484 ins->u.bitfield.offset + ins->u.bitfield.size,
2485 ins->u.bitfield.size);
2487 count = TRIPLE_SIZE(ins);
2488 for(i = 0; i < count; i++) {
2489 fprintf(fp, " %-10p", ins->param[i]);
2496 struct triple_set *user;
2497 #if DEBUG_DISPLAY_TYPES
2499 name_of(fp, ins->type);
2502 #if DEBUG_DISPLAY_USES
2504 for(user = ins->use; user; user = user->next) {
2505 fprintf(fp, " %-10p", user->member);
2510 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2511 fprintf(fp, " %s,%s:%d.%d",
2517 if (ins->op == OP_ASM) {
2518 fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2525 static int equiv_types(struct type *left, struct type *right);
2526 static void display_triple_changes(
2527 FILE *fp, const struct triple *new, const struct triple *orig)
2530 int new_count, orig_count;
2531 new_count = TRIPLE_SIZE(new);
2532 orig_count = TRIPLE_SIZE(orig);
2533 if ((new->op != orig->op) ||
2534 (new_count != orig_count) ||
2535 (memcmp(orig->param, new->param,
2536 orig_count * sizeof(orig->param[0])) != 0) ||
2537 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0))
2539 struct occurance *ptr;
2540 int i, min_count, indent;
2541 fprintf(fp, "(%p %p)", new, orig);
2542 if (orig->op == new->op) {
2543 fprintf(fp, " %-11s", tops(orig->op));
2545 fprintf(fp, " [%-10s %-10s]",
2546 tops(new->op), tops(orig->op));
2548 min_count = new_count;
2549 if (min_count > orig_count) {
2550 min_count = orig_count;
2552 for(indent = i = 0; i < min_count; i++) {
2553 if (orig->param[i] == new->param[i]) {
2554 fprintf(fp, " %-11p",
2558 fprintf(fp, " [%-10p %-10p]",
2564 for(; i < orig_count; i++) {
2565 fprintf(fp, " [%-9p]", orig->param[i]);
2568 for(; i < new_count; i++) {
2569 fprintf(fp, " [%-9p]", new->param[i]);
2572 if ((new->op == OP_INTCONST)||
2573 (new->op == OP_ADDRCONST)) {
2574 fprintf(fp, " <0x%08lx>",
2575 (unsigned long)(new->u.cval));
2578 for(;indent < 36; indent++) {
2582 #if DEBUG_DISPLAY_TYPES
2584 name_of(fp, new->type);
2585 if (!equiv_types(new->type, orig->type)) {
2586 fprintf(fp, " -- ");
2587 name_of(fp, orig->type);
2593 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2594 fprintf(fp, " %s,%s:%d.%d",
2606 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2608 /* Does the triple have no side effects.
2609 * I.e. Rexecuting the triple with the same arguments
2610 * gives the same value.
2613 valid_ins(state, ins);
2614 pure = PURE_BITS(table_ops[ins->op].flags);
2615 if ((pure != PURE) && (pure != IMPURE)) {
2616 internal_error(state, 0, "Purity of %s not known",
2619 return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2622 static int triple_is_branch_type(struct compile_state *state,
2623 struct triple *ins, unsigned type)
2625 /* Is this one of the passed branch types? */
2626 valid_ins(state, ins);
2627 return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2630 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2632 /* Is this triple a branch instruction? */
2633 valid_ins(state, ins);
2634 return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2637 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2639 /* Is this triple a conditional branch instruction? */
2640 return triple_is_branch_type(state, ins, CBRANCH);
2643 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2645 /* Is this triple a unconditional branch instruction? */
2647 valid_ins(state, ins);
2648 type = BRANCH_BITS(table_ops[ins->op].flags);
2649 return (type != 0) && (type != CBRANCH);
2652 static int triple_is_call(struct compile_state *state, struct triple *ins)
2654 /* Is this triple a call instruction? */
2655 return triple_is_branch_type(state, ins, CALLBRANCH);
2658 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2660 /* Is this triple a return instruction? */
2661 return triple_is_branch_type(state, ins, RETBRANCH);
2664 #if DEBUG_ROMCC_WARNING
2665 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2667 /* Is this triple an unconditional branch and not a call or a
2669 return triple_is_branch_type(state, ins, UBRANCH);
2673 static int triple_is_end(struct compile_state *state, struct triple *ins)
2675 return triple_is_branch_type(state, ins, ENDBRANCH);
2678 static int triple_is_label(struct compile_state *state, struct triple *ins)
2680 valid_ins(state, ins);
2681 return (ins->op == OP_LABEL);
2684 static struct triple *triple_to_block_start(
2685 struct compile_state *state, struct triple *start)
2687 while(!triple_is_branch(state, start->prev) &&
2688 (!triple_is_label(state, start) || !start->use)) {
2689 start = start->prev;
2694 static int triple_is_def(struct compile_state *state, struct triple *ins)
2696 /* This function is used to determine which triples need
2700 valid_ins(state, ins);
2701 is_def = (table_ops[ins->op].flags & DEF) == DEF;
2702 if (ins->lhs >= 1) {
2708 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2711 valid_ins(state, ins);
2712 is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2713 return is_structural;
2716 static int triple_is_part(struct compile_state *state, struct triple *ins)
2719 valid_ins(state, ins);
2720 is_part = (table_ops[ins->op].flags & PART) == PART;
2724 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2726 return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2729 static struct triple **triple_iter(struct compile_state *state,
2730 size_t count, struct triple **vector,
2731 struct triple *ins, struct triple **last)
2733 struct triple **ret;
2739 else if ((last >= vector) && (last < (vector + count - 1))) {
2747 static struct triple **triple_lhs(struct compile_state *state,
2748 struct triple *ins, struct triple **last)
2750 return triple_iter(state, ins->lhs, &LHS(ins,0),
2754 static struct triple **triple_rhs(struct compile_state *state,
2755 struct triple *ins, struct triple **last)
2757 return triple_iter(state, ins->rhs, &RHS(ins,0),
2761 static struct triple **triple_misc(struct compile_state *state,
2762 struct triple *ins, struct triple **last)
2764 return triple_iter(state, ins->misc, &MISC(ins,0),
2768 static struct triple **do_triple_targ(struct compile_state *state,
2769 struct triple *ins, struct triple **last, int call_edges, int next_edges)
2772 struct triple **ret, **vector;
2777 if (triple_is_cbranch(state, ins)) {
2780 if (!call_edges && triple_is_call(state, ins)) {
2783 if (next_edges && triple_is_call(state, ins)) {
2786 vector = &TARG(ins, 0);
2787 if (!ret && next_is_targ) {
2790 } else if (last == &ins->next) {
2794 if (!ret && count) {
2798 else if ((last >= vector) && (last < (vector + count - 1))) {
2801 else if (last == vector + count - 1) {
2805 if (!ret && triple_is_ret(state, ins) && call_edges) {
2806 struct triple_set *use;
2807 for(use = ins->use; use; use = use->next) {
2808 if (!triple_is_call(state, use->member)) {
2812 ret = &use->member->next;
2815 else if (last == &use->member->next) {
2823 static struct triple **triple_targ(struct compile_state *state,
2824 struct triple *ins, struct triple **last)
2826 return do_triple_targ(state, ins, last, 1, 1);
2829 static struct triple **triple_edge_targ(struct compile_state *state,
2830 struct triple *ins, struct triple **last)
2832 return do_triple_targ(state, ins, last,
2833 state->functions_joined, !state->functions_joined);
2836 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2838 struct triple *next;
2842 for(i = 0; i < lhs; i++) {
2843 struct triple *piece;
2844 piece = LHS(ins, i);
2845 if (next != piece) {
2846 internal_error(state, ins, "malformed lhs on %s",
2849 if (next->op != OP_PIECE) {
2850 internal_error(state, ins, "bad lhs op %s at %d on %s",
2851 tops(next->op), i, tops(ins->op));
2853 if (next->u.cval != i) {
2854 internal_error(state, ins, "bad u.cval of %d %d expected",
2862 /* Function piece accessor functions */
2863 static struct triple *do_farg(struct compile_state *state,
2864 struct triple *func, unsigned index)
2867 struct triple *first, *arg;
2871 if((index < 0) || (index >= (ftype->elements + 2))) {
2872 internal_error(state, func, "bad argument index: %d", index);
2874 first = RHS(func, 0);
2876 for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2879 if (arg->op != OP_ADECL) {
2880 internal_error(state, 0, "arg not adecl?");
2884 static struct triple *fresult(struct compile_state *state, struct triple *func)
2886 return do_farg(state, func, 0);
2888 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2890 return do_farg(state, func, 1);
2892 static struct triple *farg(struct compile_state *state,
2893 struct triple *func, unsigned index)
2895 return do_farg(state, func, index + 2);
2899 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2901 struct triple *first, *ins;
2902 fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2903 first = ins = RHS(func, 0);
2905 if (triple_is_label(state, ins) && ins->use) {
2906 fprintf(fp, "%p:\n", ins);
2908 display_triple(fp, ins);
2910 if (triple_is_branch(state, ins)) {
2913 if (ins->next->prev != ins) {
2914 internal_error(state, ins->next, "bad prev");
2917 } while(ins != first);
2920 static void verify_use(struct compile_state *state,
2921 struct triple *user, struct triple *used)
2924 size = TRIPLE_SIZE(user);
2925 for(i = 0; i < size; i++) {
2926 if (user->param[i] == used) {
2930 if (triple_is_branch(state, user)) {
2931 if (user->next == used) {
2936 internal_error(state, user, "%s(%p) does not use %s(%p)",
2937 tops(user->op), user, tops(used->op), used);
2941 static int find_rhs_use(struct compile_state *state,
2942 struct triple *user, struct triple *used)
2944 struct triple **param;
2946 verify_use(state, user, used);
2948 #if DEBUG_ROMCC_WARNINGS
2949 #warning "AUDIT ME ->rhs"
2952 param = &RHS(user, 0);
2953 for(i = 0; i < size; i++) {
2954 if (param[i] == used) {
2961 static void free_triple(struct compile_state *state, struct triple *ptr)
2964 size = sizeof(*ptr) - sizeof(ptr->param) +
2965 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2966 ptr->prev->next = ptr->next;
2967 ptr->next->prev = ptr->prev;
2969 internal_error(state, ptr, "ptr->use != 0");
2971 put_occurance(ptr->occurance);
2972 memset(ptr, -1, size);
2976 static void release_triple(struct compile_state *state, struct triple *ptr)
2978 struct triple_set *set, *next;
2979 struct triple **expr;
2980 struct block *block;
2981 if (ptr == &unknown_triple) {
2984 valid_ins(state, ptr);
2985 /* Make certain the we are not the first or last element of a block */
2986 block = block_of_triple(state, ptr);
2988 if ((block->last == ptr) && (block->first == ptr)) {
2989 block->last = block->first = 0;
2991 else if (block->last == ptr) {
2992 block->last = ptr->prev;
2994 else if (block->first == ptr) {
2995 block->first = ptr->next;
2998 /* Remove ptr from use chains where it is the user */
2999 expr = triple_rhs(state, ptr, 0);
3000 for(; expr; expr = triple_rhs(state, ptr, expr)) {
3002 unuse_triple(*expr, ptr);
3005 expr = triple_lhs(state, ptr, 0);
3006 for(; expr; expr = triple_lhs(state, ptr, expr)) {
3008 unuse_triple(*expr, ptr);
3011 expr = triple_misc(state, ptr, 0);
3012 for(; expr; expr = triple_misc(state, ptr, expr)) {
3014 unuse_triple(*expr, ptr);
3017 expr = triple_targ(state, ptr, 0);
3018 for(; expr; expr = triple_targ(state, ptr, expr)) {
3020 unuse_triple(*expr, ptr);
3023 /* Reomve ptr from use chains where it is used */
3024 for(set = ptr->use; set; set = next) {
3026 valid_ins(state, set->member);
3027 expr = triple_rhs(state, set->member, 0);
3028 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3030 *expr = &unknown_triple;
3033 expr = triple_lhs(state, set->member, 0);
3034 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3036 *expr = &unknown_triple;
3039 expr = triple_misc(state, set->member, 0);
3040 for(; expr; expr = triple_misc(state, set->member, expr)) {
3042 *expr = &unknown_triple;
3045 expr = triple_targ(state, set->member, 0);
3046 for(; expr; expr = triple_targ(state, set->member, expr)) {
3048 *expr = &unknown_triple;
3051 unuse_triple(ptr, set->member);
3053 free_triple(state, ptr);
3056 static void print_triples(struct compile_state *state);
3057 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3059 #define TOK_UNKNOWN 0
3062 #define TOK_LBRACE 3
3063 #define TOK_RBRACE 4
3067 #define TOK_LBRACKET 8
3068 #define TOK_RBRACKET 9
3069 #define TOK_LPAREN 10
3070 #define TOK_RPAREN 11
3075 #define TOK_TIMESEQ 16
3076 #define TOK_DIVEQ 17
3077 #define TOK_MODEQ 18
3078 #define TOK_PLUSEQ 19
3079 #define TOK_MINUSEQ 20
3082 #define TOK_ANDEQ 23
3083 #define TOK_XOREQ 24
3086 #define TOK_NOTEQ 27
3087 #define TOK_QUEST 28
3088 #define TOK_LOGOR 29
3089 #define TOK_LOGAND 30
3093 #define TOK_LESSEQ 34
3094 #define TOK_MOREEQ 35
3098 #define TOK_MINUS 39
3101 #define TOK_PLUSPLUS 42
3102 #define TOK_MINUSMINUS 43
3104 #define TOK_ARROW 45
3106 #define TOK_TILDE 47
3107 #define TOK_LIT_STRING 48
3108 #define TOK_LIT_CHAR 49
3109 #define TOK_LIT_INT 50
3110 #define TOK_LIT_FLOAT 51
3111 #define TOK_MACRO 52
3112 #define TOK_CONCATENATE 53
3114 #define TOK_IDENT 54
3115 #define TOK_STRUCT_NAME 55
3116 #define TOK_ENUM_CONST 56
3117 #define TOK_TYPE_NAME 57
3120 #define TOK_BREAK 59
3123 #define TOK_CONST 62
3124 #define TOK_CONTINUE 63
3125 #define TOK_DEFAULT 64
3127 #define TOK_DOUBLE 66
3130 #define TOK_EXTERN 69
3131 #define TOK_FLOAT 70
3135 #define TOK_INLINE 74
3138 #define TOK_REGISTER 77
3139 #define TOK_RESTRICT 78
3140 #define TOK_RETURN 79
3141 #define TOK_SHORT 80
3142 #define TOK_SIGNED 81
3143 #define TOK_SIZEOF 82
3144 #define TOK_STATIC 83
3145 #define TOK_STRUCT 84
3146 #define TOK_SWITCH 85
3147 #define TOK_TYPEDEF 86
3148 #define TOK_UNION 87
3149 #define TOK_UNSIGNED 88
3151 #define TOK_VOLATILE 90
3152 #define TOK_WHILE 91
3154 #define TOK_ATTRIBUTE 93
3155 #define TOK_ALIGNOF 94
3156 #define TOK_FIRST_KEYWORD TOK_AUTO
3157 #define TOK_LAST_KEYWORD TOK_ALIGNOF
3159 #define TOK_MDEFINE 100
3160 #define TOK_MDEFINED 101
3161 #define TOK_MUNDEF 102
3162 #define TOK_MINCLUDE 103
3163 #define TOK_MLINE 104
3164 #define TOK_MERROR 105
3165 #define TOK_MWARNING 106
3166 #define TOK_MPRAGMA 107
3167 #define TOK_MIFDEF 108
3168 #define TOK_MIFNDEF 109
3169 #define TOK_MELIF 110
3170 #define TOK_MENDIF 111
3172 #define TOK_FIRST_MACRO TOK_MDEFINE
3173 #define TOK_LAST_MACRO TOK_MENDIF
3176 #define TOK_MELSE 113
3177 #define TOK_MIDENT 114
3182 static const char *tokens[] = {
3183 [TOK_UNKNOWN ] = ":unknown:",
3184 [TOK_SPACE ] = ":space:",
3186 [TOK_LBRACE ] = "{",
3187 [TOK_RBRACE ] = "}",
3191 [TOK_LBRACKET ] = "[",
3192 [TOK_RBRACKET ] = "]",
3193 [TOK_LPAREN ] = "(",
3194 [TOK_RPAREN ] = ")",
3196 [TOK_DOTS ] = "...",
3199 [TOK_TIMESEQ ] = "*=",
3200 [TOK_DIVEQ ] = "/=",
3201 [TOK_MODEQ ] = "%=",
3202 [TOK_PLUSEQ ] = "+=",
3203 [TOK_MINUSEQ ] = "-=",
3204 [TOK_SLEQ ] = "<<=",
3205 [TOK_SREQ ] = ">>=",
3206 [TOK_ANDEQ ] = "&=",
3207 [TOK_XOREQ ] = "^=",
3210 [TOK_NOTEQ ] = "!=",
3212 [TOK_LOGOR ] = "||",
3213 [TOK_LOGAND ] = "&&",
3217 [TOK_LESSEQ ] = "<=",
3218 [TOK_MOREEQ ] = ">=",
3225 [TOK_PLUSPLUS ] = "++",
3226 [TOK_MINUSMINUS ] = "--",
3228 [TOK_ARROW ] = "->",
3231 [TOK_LIT_STRING ] = ":string:",
3232 [TOK_IDENT ] = ":ident:",
3233 [TOK_TYPE_NAME ] = ":typename:",
3234 [TOK_LIT_CHAR ] = ":char:",
3235 [TOK_LIT_INT ] = ":integer:",
3236 [TOK_LIT_FLOAT ] = ":float:",
3238 [TOK_CONCATENATE ] = "##",
3240 [TOK_AUTO ] = "auto",
3241 [TOK_BREAK ] = "break",
3242 [TOK_CASE ] = "case",
3243 [TOK_CHAR ] = "char",
3244 [TOK_CONST ] = "const",
3245 [TOK_CONTINUE ] = "continue",
3246 [TOK_DEFAULT ] = "default",
3248 [TOK_DOUBLE ] = "double",
3249 [TOK_ELSE ] = "else",
3250 [TOK_ENUM ] = "enum",
3251 [TOK_EXTERN ] = "extern",
3252 [TOK_FLOAT ] = "float",
3254 [TOK_GOTO ] = "goto",
3256 [TOK_INLINE ] = "inline",
3258 [TOK_LONG ] = "long",
3259 [TOK_REGISTER ] = "register",
3260 [TOK_RESTRICT ] = "restrict",
3261 [TOK_RETURN ] = "return",
3262 [TOK_SHORT ] = "short",
3263 [TOK_SIGNED ] = "signed",
3264 [TOK_SIZEOF ] = "sizeof",
3265 [TOK_STATIC ] = "static",
3266 [TOK_STRUCT ] = "struct",
3267 [TOK_SWITCH ] = "switch",
3268 [TOK_TYPEDEF ] = "typedef",
3269 [TOK_UNION ] = "union",
3270 [TOK_UNSIGNED ] = "unsigned",
3271 [TOK_VOID ] = "void",
3272 [TOK_VOLATILE ] = "volatile",
3273 [TOK_WHILE ] = "while",
3275 [TOK_ATTRIBUTE ] = "__attribute__",
3276 [TOK_ALIGNOF ] = "__alignof__",
3278 [TOK_MDEFINE ] = "#define",
3279 [TOK_MDEFINED ] = "#defined",
3280 [TOK_MUNDEF ] = "#undef",
3281 [TOK_MINCLUDE ] = "#include",
3282 [TOK_MLINE ] = "#line",
3283 [TOK_MERROR ] = "#error",
3284 [TOK_MWARNING ] = "#warning",
3285 [TOK_MPRAGMA ] = "#pragma",
3286 [TOK_MIFDEF ] = "#ifdef",
3287 [TOK_MIFNDEF ] = "#ifndef",
3288 [TOK_MELIF ] = "#elif",
3289 [TOK_MENDIF ] = "#endif",
3292 [TOK_MELSE ] = "#else",
3293 [TOK_MIDENT ] = "#:ident:",
3298 static unsigned int hash(const char *str, int str_len)
3302 end = str + str_len;
3304 for(; str < end; str++) {
3305 hash = (hash *263) + *str;
3307 hash = hash & (HASH_TABLE_SIZE -1);
3311 static struct hash_entry *lookup(
3312 struct compile_state *state, const char *name, int name_len)
3314 struct hash_entry *entry;
3316 index = hash(name, name_len);
3317 entry = state->hash_table[index];
3319 ((entry->name_len != name_len) ||
3320 (memcmp(entry->name, name, name_len) != 0))) {
3321 entry = entry->next;
3325 /* Get a private copy of the name */
3326 new_name = xmalloc(name_len + 1, "hash_name");
3327 memcpy(new_name, name, name_len);
3328 new_name[name_len] = '\0';
3330 /* Create a new hash entry */
3331 entry = xcmalloc(sizeof(*entry), "hash_entry");
3332 entry->next = state->hash_table[index];
3333 entry->name = new_name;
3334 entry->name_len = name_len;
3336 /* Place the new entry in the hash table */
3337 state->hash_table[index] = entry;
3342 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3344 struct hash_entry *entry;
3346 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3347 (entry->tok == TOK_ENUM_CONST) ||
3348 ((entry->tok >= TOK_FIRST_KEYWORD) &&
3349 (entry->tok <= TOK_LAST_KEYWORD)))) {
3350 tk->tok = entry->tok;
3354 static void ident_to_macro(struct compile_state *state, struct token *tk)
3356 struct hash_entry *entry;
3360 if ((entry->tok >= TOK_FIRST_MACRO) && (entry->tok <= TOK_LAST_MACRO)) {
3361 tk->tok = entry->tok;
3363 else if (entry->tok == TOK_IF) {
3366 else if (entry->tok == TOK_ELSE) {
3367 tk->tok = TOK_MELSE;
3370 tk->tok = TOK_MIDENT;
3374 static void hash_keyword(
3375 struct compile_state *state, const char *keyword, int tok)
3377 struct hash_entry *entry;
3378 entry = lookup(state, keyword, strlen(keyword));
3379 if (entry && entry->tok != TOK_UNKNOWN) {
3380 die("keyword %s already hashed", keyword);
3385 static void romcc_symbol(
3386 struct compile_state *state, struct hash_entry *ident,
3387 struct symbol **chain, struct triple *def, struct type *type, int depth)
3390 if (*chain && ((*chain)->scope_depth >= depth)) {
3391 error(state, 0, "%s already defined", ident->name);
3393 sym = xcmalloc(sizeof(*sym), "symbol");
3397 sym->scope_depth = depth;
3403 struct compile_state *state, struct hash_entry *ident,
3404 struct symbol **chain, struct triple *def, struct type *type)
3406 romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3409 static void var_symbol(struct compile_state *state,
3410 struct hash_entry *ident, struct triple *def)
3412 if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3413 internal_error(state, 0, "bad var type");
3415 symbol(state, ident, &ident->sym_ident, def, def->type);
3418 static void label_symbol(struct compile_state *state,
3419 struct hash_entry *ident, struct triple *label, int depth)
3421 romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3424 static void start_scope(struct compile_state *state)
3426 state->scope_depth++;
3429 static void end_scope_syms(struct compile_state *state,
3430 struct symbol **chain, int depth)
3432 struct symbol *sym, *next;
3434 while(sym && (sym->scope_depth == depth)) {
3442 static void end_scope(struct compile_state *state)
3446 /* Walk through the hash table and remove all symbols
3447 * in the current scope.
3449 depth = state->scope_depth;
3450 for(i = 0; i < HASH_TABLE_SIZE; i++) {
3451 struct hash_entry *entry;
3452 entry = state->hash_table[i];
3454 end_scope_syms(state, &entry->sym_label, depth);
3455 end_scope_syms(state, &entry->sym_tag, depth);
3456 end_scope_syms(state, &entry->sym_ident, depth);
3457 entry = entry->next;
3460 state->scope_depth = depth - 1;
3463 static void register_keywords(struct compile_state *state)
3465 hash_keyword(state, "auto", TOK_AUTO);
3466 hash_keyword(state, "break", TOK_BREAK);
3467 hash_keyword(state, "case", TOK_CASE);
3468 hash_keyword(state, "char", TOK_CHAR);
3469 hash_keyword(state, "const", TOK_CONST);
3470 hash_keyword(state, "continue", TOK_CONTINUE);
3471 hash_keyword(state, "default", TOK_DEFAULT);
3472 hash_keyword(state, "do", TOK_DO);
3473 hash_keyword(state, "double", TOK_DOUBLE);
3474 hash_keyword(state, "else", TOK_ELSE);
3475 hash_keyword(state, "enum", TOK_ENUM);
3476 hash_keyword(state, "extern", TOK_EXTERN);
3477 hash_keyword(state, "float", TOK_FLOAT);
3478 hash_keyword(state, "for", TOK_FOR);
3479 hash_keyword(state, "goto", TOK_GOTO);
3480 hash_keyword(state, "if", TOK_IF);
3481 hash_keyword(state, "inline", TOK_INLINE);
3482 hash_keyword(state, "int", TOK_INT);
3483 hash_keyword(state, "long", TOK_LONG);
3484 hash_keyword(state, "register", TOK_REGISTER);
3485 hash_keyword(state, "restrict", TOK_RESTRICT);
3486 hash_keyword(state, "return", TOK_RETURN);
3487 hash_keyword(state, "short", TOK_SHORT);
3488 hash_keyword(state, "signed", TOK_SIGNED);
3489 hash_keyword(state, "sizeof", TOK_SIZEOF);
3490 hash_keyword(state, "static", TOK_STATIC);
3491 hash_keyword(state, "struct", TOK_STRUCT);
3492 hash_keyword(state, "switch", TOK_SWITCH);
3493 hash_keyword(state, "typedef", TOK_TYPEDEF);
3494 hash_keyword(state, "union", TOK_UNION);
3495 hash_keyword(state, "unsigned", TOK_UNSIGNED);
3496 hash_keyword(state, "void", TOK_VOID);
3497 hash_keyword(state, "volatile", TOK_VOLATILE);
3498 hash_keyword(state, "__volatile__", TOK_VOLATILE);
3499 hash_keyword(state, "while", TOK_WHILE);
3500 hash_keyword(state, "asm", TOK_ASM);
3501 hash_keyword(state, "__asm__", TOK_ASM);
3502 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3503 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
3506 static void register_macro_keywords(struct compile_state *state)
3508 hash_keyword(state, "define", TOK_MDEFINE);
3509 hash_keyword(state, "defined", TOK_MDEFINED);
3510 hash_keyword(state, "undef", TOK_MUNDEF);
3511 hash_keyword(state, "include", TOK_MINCLUDE);
3512 hash_keyword(state, "line", TOK_MLINE);
3513 hash_keyword(state, "error", TOK_MERROR);
3514 hash_keyword(state, "warning", TOK_MWARNING);
3515 hash_keyword(state, "pragma", TOK_MPRAGMA);
3516 hash_keyword(state, "ifdef", TOK_MIFDEF);
3517 hash_keyword(state, "ifndef", TOK_MIFNDEF);
3518 hash_keyword(state, "elif", TOK_MELIF);
3519 hash_keyword(state, "endif", TOK_MENDIF);
3523 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3525 if (ident->sym_define != 0) {
3526 struct macro *macro;
3527 struct macro_arg *arg, *anext;
3528 macro = ident->sym_define;
3529 ident->sym_define = 0;
3531 /* Free the macro arguments... */
3532 anext = macro->args;
3539 /* Free the macro buffer */
3542 /* Now free the macro itself */
3547 static void do_define_macro(struct compile_state *state,
3548 struct hash_entry *ident, const char *body,
3549 int argc, struct macro_arg *args)
3551 struct macro *macro;
3552 struct macro_arg *arg;
3555 /* Find the length of the body */
3556 body_len = strlen(body);
3557 macro = ident->sym_define;
3559 int identical_bodies, identical_args;
3560 struct macro_arg *oarg;
3561 /* Explicitly allow identical redfinitions of the same macro */
3563 (macro->buf_len == body_len) &&
3564 (memcmp(macro->buf, body, body_len) == 0);
3565 identical_args = macro->argc == argc;
3568 while(identical_args && arg) {
3569 identical_args = oarg->ident == arg->ident;
3573 if (identical_bodies && identical_args) {
3577 error(state, 0, "macro %s already defined\n", ident->name);
3580 fprintf(state->errout, "#define %s: `%*.*s'\n",
3581 ident->name, body_len, body_len, body);
3583 macro = xmalloc(sizeof(*macro), "macro");
3584 macro->ident = ident;
3586 macro->buf_len = body_len;
3590 ident->sym_define = macro;
3593 static void define_macro(
3594 struct compile_state *state,
3595 struct hash_entry *ident,
3596 const char *body, int body_len,
3597 int argc, struct macro_arg *args)
3600 buf = xmalloc(body_len + 1, "macro buf");
3601 memcpy(buf, body, body_len);
3602 buf[body_len] = '\0';
3603 do_define_macro(state, ident, buf, argc, args);
3606 static void register_builtin_macro(struct compile_state *state,
3607 const char *name, const char *value)
3609 struct hash_entry *ident;
3611 if (value[0] == '(') {
3612 internal_error(state, 0, "Builtin macros with arguments not supported");
3614 ident = lookup(state, name, strlen(name));
3615 define_macro(state, ident, value, strlen(value), -1, 0);
3618 static void register_builtin_macros(struct compile_state *state)
3625 tm = localtime(&now);
3627 register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3628 register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3629 register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3630 register_builtin_macro(state, "__LINE__", "54321");
3632 strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3633 sprintf(buf, "\"%s\"", scratch);
3634 register_builtin_macro(state, "__DATE__", buf);
3636 strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3637 sprintf(buf, "\"%s\"", scratch);
3638 register_builtin_macro(state, "__TIME__", buf);
3640 /* I can't be a conforming implementation of C :( */
3641 register_builtin_macro(state, "__STDC__", "0");
3642 /* In particular I don't conform to C99 */
3643 register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3647 static void process_cmdline_macros(struct compile_state *state)
3649 const char **macro, *name;
3650 struct hash_entry *ident;
3651 for(macro = state->compiler->defines; (name = *macro); macro++) {
3655 name_len = strlen(name);
3656 body = strchr(name, '=');
3660 name_len = body - name;
3663 ident = lookup(state, name, name_len);
3664 define_macro(state, ident, body, strlen(body), -1, 0);
3666 for(macro = state->compiler->undefs; (name = *macro); macro++) {
3667 ident = lookup(state, name, strlen(name));
3668 undef_macro(state, ident);
3672 static int spacep(int c)
3687 static int digitp(int c)
3691 case '0': case '1': case '2': case '3': case '4':
3692 case '5': case '6': case '7': case '8': case '9':
3698 static int digval(int c)
3701 if ((c >= '0') && (c <= '9')) {
3707 static int hexdigitp(int c)
3711 case '0': case '1': case '2': case '3': case '4':
3712 case '5': case '6': case '7': case '8': case '9':
3713 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3714 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3720 static int hexdigval(int c)
3723 if ((c >= '0') && (c <= '9')) {
3726 else if ((c >= 'A') && (c <= 'F')) {
3727 val = 10 + (c - 'A');
3729 else if ((c >= 'a') && (c <= 'f')) {
3730 val = 10 + (c - 'a');
3735 static int octdigitp(int c)
3739 case '0': case '1': case '2': case '3':
3740 case '4': case '5': case '6': case '7':
3746 static int octdigval(int c)
3749 if ((c >= '0') && (c <= '7')) {
3755 static int letterp(int c)
3759 case 'a': case 'b': case 'c': case 'd': case 'e':
3760 case 'f': case 'g': case 'h': case 'i': case 'j':
3761 case 'k': case 'l': case 'm': case 'n': case 'o':
3762 case 'p': case 'q': case 'r': case 's': case 't':
3763 case 'u': case 'v': case 'w': case 'x': case 'y':
3765 case 'A': case 'B': case 'C': case 'D': case 'E':
3766 case 'F': case 'G': case 'H': case 'I': case 'J':
3767 case 'K': case 'L': case 'M': case 'N': case 'O':
3768 case 'P': case 'Q': case 'R': case 'S': case 'T':
3769 case 'U': case 'V': case 'W': case 'X': case 'Y':
3778 static const char *identifier(const char *str, const char *end)
3780 if (letterp(*str)) {
3781 for(; str < end; str++) {
3784 if (!letterp(c) && !digitp(c)) {
3792 static int char_value(struct compile_state *state,
3793 const signed char **strp, const signed char *end)
3795 const signed char *str;
3799 if ((c == '\\') && (str < end)) {
3801 case 'n': c = '\n'; str++; break;
3802 case 't': c = '\t'; str++; break;
3803 case 'v': c = '\v'; str++; break;
3804 case 'b': c = '\b'; str++; break;
3805 case 'r': c = '\r'; str++; break;
3806 case 'f': c = '\f'; str++; break;
3807 case 'a': c = '\a'; str++; break;
3808 case '\\': c = '\\'; str++; break;
3809 case '?': c = '?'; str++; break;
3810 case '\'': c = '\''; str++; break;
3811 case '"': c = '"'; str++; break;
3815 while((str < end) && hexdigitp(*str)) {
3817 c += hexdigval(*str);
3821 case '0': case '1': case '2': case '3':
3822 case '4': case '5': case '6': case '7':
3824 while((str < end) && octdigitp(*str)) {
3826 c += octdigval(*str);
3831 error(state, 0, "Invalid character constant");
3839 static const char *next_char(struct file_state *file, const char *pos, int index)
3841 const char *end = file->buf + file->size;
3843 /* Lookup the character */
3846 /* Is this a trigraph? */
3847 if (file->trigraphs &&
3848 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3851 case '=': c = '#'; break;
3852 case '/': c = '\\'; break;
3853 case '\'': c = '^'; break;
3854 case '(': c = '['; break;
3855 case ')': c = ']'; break;
3856 case '!': c = '!'; break;
3857 case '<': c = '{'; break;
3858 case '>': c = '}'; break;
3859 case '-': c = '~'; break;
3865 /* Is this an escaped newline? */
3866 if (file->join_lines &&
3867 (c == '\\') && (pos + size < end) && ((pos[1] == '\n') || ((pos[1] == '\r') && (pos[2] == '\n'))))
3869 int cr_offset = ((pos[1] == '\r') && (pos[2] == '\n'))?1:0;
3870 /* At the start of a line just eat it */
3871 if (pos == file->pos) {
3873 file->report_line++;
3874 file->line_start = pos + size + 1 + cr_offset;
3876 pos += size + 1 + cr_offset;
3878 /* Do I need to ga any farther? */
3879 else if (index == 0) {
3882 /* Process a normal character */
3891 static int get_char(struct file_state *file, const char *pos)
3893 const char *end = file->buf + file->size;
3896 pos = next_char(file, pos, 0);
3898 /* Lookup the character */
3900 /* If it is a trigraph get the trigraph value */
3901 if (file->trigraphs &&
3902 (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3905 case '=': c = '#'; break;
3906 case '/': c = '\\'; break;
3907 case '\'': c = '^'; break;
3908 case '(': c = '['; break;
3909 case ')': c = ']'; break;
3910 case '!': c = '!'; break;
3911 case '<': c = '{'; break;
3912 case '>': c = '}'; break;
3913 case '-': c = '~'; break;
3920 static void eat_chars(struct file_state *file, const char *targ)
3922 const char *pos = file->pos;
3924 /* Do we have a newline? */
3925 if (pos[0] == '\n') {
3927 file->report_line++;
3928 file->line_start = pos + 1;
3936 static size_t char_strlen(struct file_state *file, const char *src, const char *end)
3941 src = next_char(file, src, 1);
3947 static void char_strcpy(char *dest,
3948 struct file_state *file, const char *src, const char *end)
3952 c = get_char(file, src);
3953 src = next_char(file, src, 1);
3958 static char *char_strdup(struct file_state *file,
3959 const char *start, const char *end, const char *id)
3963 str_len = char_strlen(file, start, end);
3964 str = xcmalloc(str_len + 1, id);
3965 char_strcpy(str, file, start, end);
3966 str[str_len] = '\0';
3970 static const char *after_digits(struct file_state *file, const char *ptr)
3972 while(digitp(get_char(file, ptr))) {
3973 ptr = next_char(file, ptr, 1);
3978 static const char *after_octdigits(struct file_state *file, const char *ptr)
3980 while(octdigitp(get_char(file, ptr))) {
3981 ptr = next_char(file, ptr, 1);
3986 static const char *after_hexdigits(struct file_state *file, const char *ptr)
3988 while(hexdigitp(get_char(file, ptr))) {
3989 ptr = next_char(file, ptr, 1);
3994 static const char *after_alnums(struct file_state *file, const char *ptr)
3997 c = get_char(file, ptr);
3998 while(letterp(c) || digitp(c)) {
3999 ptr = next_char(file, ptr, 1);
4000 c = get_char(file, ptr);
4005 static void save_string(struct file_state *file,
4006 struct token *tk, const char *start, const char *end, const char *id)
4010 /* Create a private copy of the string */
4011 str = char_strdup(file, start, end, id);
4013 /* Store the copy in the token */
4015 tk->str_len = strlen(str);
4018 static void raw_next_token(struct compile_state *state,
4019 struct file_state *file, struct token *tk)
4029 token = tokp = next_char(file, file->pos, 0);
4031 c = get_char(file, tokp);
4032 tokp = next_char(file, tokp, 1);
4034 c1 = get_char(file, tokp);
4035 c2 = get_char(file, next_char(file, tokp, 1));
4036 c3 = get_char(file, next_char(file, tokp, 2));
4038 /* The end of the file */
4043 else if (spacep(c)) {
4045 while (spacep(get_char(file, tokp))) {
4046 tokp = next_char(file, tokp, 1);
4050 else if ((c == '/') && (c1 == '/')) {
4052 tokp = next_char(file, tokp, 1);
4053 while((c = get_char(file, tokp)) != -1) {
4054 /* Advance to the next character only after we verify
4055 * the current character is not a newline.
4056 * EOL is special to the preprocessor so we don't
4057 * want to loose any.
4062 tokp = next_char(file, tokp, 1);
4066 else if ((c == '/') && (c1 == '*')) {
4067 tokp = next_char(file, tokp, 2);
4069 while((c1 = get_char(file, tokp)) != -1) {
4070 tokp = next_char(file, tokp, 1);
4071 if ((c == '*') && (c1 == '/')) {
4077 if (tok == TOK_UNKNOWN) {
4078 error(state, 0, "unterminated comment");
4081 /* string constants */
4082 else if ((c == '"') || ((c == 'L') && (c1 == '"'))) {
4087 tokp = next_char(file, tokp, 1);
4089 while((c = get_char(file, tokp)) != -1) {
4090 tokp = next_char(file, tokp, 1);
4094 else if (c == '\\') {
4095 tokp = next_char(file, tokp, 1);
4097 else if (c == '"') {
4098 tok = TOK_LIT_STRING;
4102 if (tok == TOK_UNKNOWN) {
4103 error(state, 0, "unterminated string constant");
4106 warning(state, 0, "multiline string constant");
4109 /* Save the string value */
4110 save_string(file, tk, token, tokp, "literal string");
4112 /* character constants */
4113 else if ((c == '\'') || ((c == 'L') && (c1 == '\''))) {
4118 tokp = next_char(file, tokp, 1);
4120 while((c = get_char(file, tokp)) != -1) {
4121 tokp = next_char(file, tokp, 1);
4125 else if (c == '\\') {
4126 tokp = next_char(file, tokp, 1);
4128 else if (c == '\'') {
4133 if (tok == TOK_UNKNOWN) {
4134 error(state, 0, "unterminated character constant");
4137 warning(state, 0, "multiline character constant");
4140 /* Save the character value */
4141 save_string(file, tk, token, tokp, "literal character");
4143 /* integer and floating constants
4149 * Floating constants
4150 * {digits}.{digits}[Ee][+-]?{digits}
4152 * {digits}[Ee][+-]?{digits}
4153 * .{digits}[Ee][+-]?{digits}
4156 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4162 next = after_digits(file, tokp);
4167 cn = get_char(file, next);
4169 next = next_char(file, next, 1);
4170 next = after_digits(file, next);
4173 cn = get_char(file, next);
4174 if ((cn == 'e') || (cn == 'E')) {
4176 next = next_char(file, next, 1);
4177 cn = get_char(file, next);
4178 if ((cn == '+') || (cn == '-')) {
4179 next = next_char(file, next, 1);
4181 new = after_digits(file, next);
4182 is_float |= (new != next);
4186 tok = TOK_LIT_FLOAT;
4187 cn = get_char(file, next);
4188 if ((cn == 'f') || (cn == 'F') || (cn == 'l') || (cn == 'L')) {
4189 next = next_char(file, next, 1);
4192 if (!is_float && digitp(c)) {
4194 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4195 next = next_char(file, tokp, 1);
4196 next = after_hexdigits(file, next);
4198 else if (c == '0') {
4199 next = after_octdigits(file, tokp);
4202 next = after_digits(file, tokp);
4204 /* crazy integer suffixes */
4205 cn = get_char(file, next);
4206 if ((cn == 'u') || (cn == 'U')) {
4207 next = next_char(file, next, 1);
4208 cn = get_char(file, next);
4209 if ((cn == 'l') || (cn == 'L')) {
4210 next = next_char(file, next, 1);
4211 cn = get_char(file, next);
4213 if ((cn == 'l') || (cn == 'L')) {
4214 next = next_char(file, next, 1);
4217 else if ((cn == 'l') || (cn == 'L')) {
4218 next = next_char(file, next, 1);
4219 cn = get_char(file, next);
4220 if ((cn == 'l') || (cn == 'L')) {
4221 next = next_char(file, next, 1);
4222 cn = get_char(file, next);
4224 if ((cn == 'u') || (cn == 'U')) {
4225 next = next_char(file, next, 1);
4231 /* Save the integer/floating point value */
4232 save_string(file, tk, token, tokp, "literal number");
4235 else if (letterp(c)) {
4238 /* Find and save the identifier string */
4239 tokp = after_alnums(file, tokp);
4240 save_string(file, tk, token, tokp, "identifier");
4242 /* Look up to see which identifier it is */
4243 tk->ident = lookup(state, tk->val.str, tk->str_len);
4245 /* Free the identifier string */
4249 /* See if this identifier can be macro expanded */
4250 tk->val.notmacro = 0;
4251 c = get_char(file, tokp);
4253 tokp = next_char(file, tokp, 1);
4254 tk->val.notmacro = 1;
4257 /* C99 alternate macro characters */
4258 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
4260 tok = TOK_CONCATENATE;
4262 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { eat += 2; tok = TOK_DOTS; }
4263 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { eat += 2; tok = TOK_SLEQ; }
4264 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { eat += 2; tok = TOK_SREQ; }
4265 else if ((c == '*') && (c1 == '=')) { eat += 1; tok = TOK_TIMESEQ; }
4266 else if ((c == '/') && (c1 == '=')) { eat += 1; tok = TOK_DIVEQ; }
4267 else if ((c == '%') && (c1 == '=')) { eat += 1; tok = TOK_MODEQ; }
4268 else if ((c == '+') && (c1 == '=')) { eat += 1; tok = TOK_PLUSEQ; }
4269 else if ((c == '-') && (c1 == '=')) { eat += 1; tok = TOK_MINUSEQ; }
4270 else if ((c == '&') && (c1 == '=')) { eat += 1; tok = TOK_ANDEQ; }
4271 else if ((c == '^') && (c1 == '=')) { eat += 1; tok = TOK_XOREQ; }
4272 else if ((c == '|') && (c1 == '=')) { eat += 1; tok = TOK_OREQ; }
4273 else if ((c == '=') && (c1 == '=')) { eat += 1; tok = TOK_EQEQ; }
4274 else if ((c == '!') && (c1 == '=')) { eat += 1; tok = TOK_NOTEQ; }
4275 else if ((c == '|') && (c1 == '|')) { eat += 1; tok = TOK_LOGOR; }
4276 else if ((c == '&') && (c1 == '&')) { eat += 1; tok = TOK_LOGAND; }
4277 else if ((c == '<') && (c1 == '=')) { eat += 1; tok = TOK_LESSEQ; }
4278 else if ((c == '>') && (c1 == '=')) { eat += 1; tok = TOK_MOREEQ; }
4279 else if ((c == '<') && (c1 == '<')) { eat += 1; tok = TOK_SL; }
4280 else if ((c == '>') && (c1 == '>')) { eat += 1; tok = TOK_SR; }
4281 else if ((c == '+') && (c1 == '+')) { eat += 1; tok = TOK_PLUSPLUS; }
4282 else if ((c == '-') && (c1 == '-')) { eat += 1; tok = TOK_MINUSMINUS; }
4283 else if ((c == '-') && (c1 == '>')) { eat += 1; tok = TOK_ARROW; }
4284 else if ((c == '<') && (c1 == ':')) { eat += 1; tok = TOK_LBRACKET; }
4285 else if ((c == ':') && (c1 == '>')) { eat += 1; tok = TOK_RBRACKET; }
4286 else if ((c == '<') && (c1 == '%')) { eat += 1; tok = TOK_LBRACE; }
4287 else if ((c == '%') && (c1 == '>')) { eat += 1; tok = TOK_RBRACE; }
4288 else if ((c == '%') && (c1 == ':')) { eat += 1; tok = TOK_MACRO; }
4289 else if ((c == '#') && (c1 == '#')) { eat += 1; tok = TOK_CONCATENATE; }
4290 else if (c == ';') { tok = TOK_SEMI; }
4291 else if (c == '{') { tok = TOK_LBRACE; }
4292 else if (c == '}') { tok = TOK_RBRACE; }
4293 else if (c == ',') { tok = TOK_COMMA; }
4294 else if (c == '=') { tok = TOK_EQ; }
4295 else if (c == ':') { tok = TOK_COLON; }
4296 else if (c == '[') { tok = TOK_LBRACKET; }
4297 else if (c == ']') { tok = TOK_RBRACKET; }
4298 else if (c == '(') { tok = TOK_LPAREN; }
4299 else if (c == ')') { tok = TOK_RPAREN; }
4300 else if (c == '*') { tok = TOK_STAR; }
4301 else if (c == '>') { tok = TOK_MORE; }
4302 else if (c == '<') { tok = TOK_LESS; }
4303 else if (c == '?') { tok = TOK_QUEST; }
4304 else if (c == '|') { tok = TOK_OR; }
4305 else if (c == '&') { tok = TOK_AND; }
4306 else if (c == '^') { tok = TOK_XOR; }
4307 else if (c == '+') { tok = TOK_PLUS; }
4308 else if (c == '-') { tok = TOK_MINUS; }
4309 else if (c == '/') { tok = TOK_DIV; }
4310 else if (c == '%') { tok = TOK_MOD; }
4311 else if (c == '!') { tok = TOK_BANG; }
4312 else if (c == '.') { tok = TOK_DOT; }
4313 else if (c == '~') { tok = TOK_TILDE; }
4314 else if (c == '#') { tok = TOK_MACRO; }
4315 else if (c == '\n') { tok = TOK_EOL; }
4317 tokp = next_char(file, tokp, eat);
4318 eat_chars(file, tokp);
4323 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4325 if (tk->tok != tok) {
4326 const char *name1, *name2;
4327 name1 = tokens[tk->tok];
4329 if ((tk->tok == TOK_IDENT) || (tk->tok == TOK_MIDENT)) {
4330 name2 = tk->ident->name;
4332 error(state, 0, "\tfound %s %s expected %s",
4333 name1, name2, tokens[tok]);
4337 struct macro_arg_value {
4338 struct hash_entry *ident;
4342 static struct macro_arg_value *read_macro_args(
4343 struct compile_state *state, struct macro *macro,
4344 struct file_state *file, struct token *tk)
4346 struct macro_arg_value *argv;
4347 struct macro_arg *arg;
4351 if (macro->argc == 0) {
4353 raw_next_token(state, file, tk);
4354 } while(tk->tok == TOK_SPACE);
4357 argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4358 for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4361 argv[i].ident = arg->ident;
4370 raw_next_token(state, file, tk);
4372 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4373 (argv[i].ident != state->i___VA_ARGS__))
4376 if (i >= macro->argc) {
4377 error(state, 0, "too many args to %s\n",
4378 macro->ident->name);
4383 if (tk->tok == TOK_LPAREN) {
4387 if (tk->tok == TOK_RPAREN) {
4388 if (paren_depth == 0) {
4393 if (tk->tok == TOK_EOF) {
4394 error(state, 0, "End of file encountered while parsing macro arguments");
4397 len = char_strlen(file, start, file->pos);
4398 argv[i].value = xrealloc(
4399 argv[i].value, argv[i].len + len, "macro args");
4400 char_strcpy((char *)argv[i].value + argv[i].len, file, start, file->pos);
4403 if (i != macro->argc -1) {
4404 error(state, 0, "missing %s arg %d\n",
4405 macro->ident->name, i +2);
4411 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4414 for(i = 0; i < macro->argc; i++) {
4415 xfree(argv[i].value);
4425 static void grow_macro_buf(struct compile_state *state,
4426 const char *id, struct macro_buf *buf,
4429 if ((buf->pos + grow) >= buf->len) {
4430 buf->str = xrealloc(buf->str, buf->len + grow, id);
4435 static void append_macro_text(struct compile_state *state,
4436 const char *id, struct macro_buf *buf,
4437 const char *fstart, size_t flen)
4439 grow_macro_buf(state, id, buf, flen);
4440 memcpy(buf->str + buf->pos, fstart, flen);
4442 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4443 buf->pos, buf->pos, buf->str,
4444 flen, flen, buf->str + buf->pos);
4450 static void append_macro_chars(struct compile_state *state,
4451 const char *id, struct macro_buf *buf,
4452 struct file_state *file, const char *start, const char *end)
4455 flen = char_strlen(file, start, end);
4456 grow_macro_buf(state, id, buf, flen);
4457 char_strcpy(buf->str + buf->pos, file, start, end);
4459 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4460 buf->pos, buf->pos, buf->str,
4461 flen, flen, buf->str + buf->pos);
4466 static int compile_macro(struct compile_state *state,
4467 struct file_state **filep, struct token *tk);
4469 static void macro_expand_args(struct compile_state *state,
4470 struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4474 for(i = 0; i < macro->argc; i++) {
4475 struct file_state fmacro, *file;
4476 struct macro_buf buf;
4479 fmacro.basename = argv[i].ident->name;
4480 fmacro.dirname = "";
4481 fmacro.buf = (char *)argv[i].value;
4482 fmacro.size = argv[i].len;
4483 fmacro.pos = fmacro.buf;
4485 fmacro.line_start = fmacro.buf;
4486 fmacro.report_line = 1;
4487 fmacro.report_name = fmacro.basename;
4488 fmacro.report_dir = fmacro.dirname;
4490 fmacro.trigraphs = 0;
4491 fmacro.join_lines = 0;
4493 buf.len = argv[i].len;
4494 buf.str = xmalloc(buf.len, argv[i].ident->name);
4499 raw_next_token(state, file, tk);
4501 /* If we have recursed into another macro body
4504 if (tk->tok == TOK_EOF) {
4505 struct file_state *old;
4511 /* old->basename is used keep it */
4512 xfree(old->dirname);
4517 else if (tk->ident && tk->ident->sym_define) {
4518 if (compile_macro(state, &file, tk)) {
4523 append_macro_chars(state, macro->ident->name, &buf,
4524 file, tk->pos, file->pos);
4527 xfree(argv[i].value);
4528 argv[i].value = buf.str;
4529 argv[i].len = buf.pos;
4534 static void expand_macro(struct compile_state *state,
4535 struct macro *macro, struct macro_buf *buf,
4536 struct macro_arg_value *argv, struct token *tk)
4538 struct file_state fmacro;
4539 const char space[] = " ";
4544 /* Place the macro body in a dummy file */
4546 fmacro.basename = macro->ident->name;
4547 fmacro.dirname = "";
4548 fmacro.buf = macro->buf;
4549 fmacro.size = macro->buf_len;
4550 fmacro.pos = fmacro.buf;
4552 fmacro.line_start = fmacro.buf;
4553 fmacro.report_line = 1;
4554 fmacro.report_name = fmacro.basename;
4555 fmacro.report_dir = fmacro.dirname;
4557 fmacro.trigraphs = 0;
4558 fmacro.join_lines = 0;
4560 /* Allocate a buffer to hold the macro expansion */
4561 buf->len = macro->buf_len + 3;
4562 buf->str = xmalloc(buf->len, macro->ident->name);
4565 fstart = fmacro.pos;
4566 raw_next_token(state, &fmacro, tk);
4567 while(tk->tok != TOK_EOF) {
4568 flen = fmacro.pos - fstart;
4571 for(i = 0; i < macro->argc; i++) {
4572 if (argv[i].ident == tk->ident) {
4576 if (i >= macro->argc) {
4579 /* Substitute macro parameter */
4580 fstart = argv[i].value;
4584 if (macro->argc < 0) {
4588 raw_next_token(state, &fmacro, tk);
4589 } while(tk->tok == TOK_SPACE);
4590 check_tok(state, tk, TOK_IDENT);
4591 for(i = 0; i < macro->argc; i++) {
4592 if (argv[i].ident == tk->ident) {
4596 if (i >= macro->argc) {
4597 error(state, 0, "parameter `%s' not found",
4600 /* Stringize token */
4601 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4602 for(j = 0; j < argv[i].len; j++) {
4603 char *str = argv[i].value + j;
4609 else if (*str == '"') {
4613 append_macro_text(state, macro->ident->name, buf, str, len);
4615 append_macro_text(state, macro->ident->name, buf, "\"", 1);
4619 case TOK_CONCATENATE:
4620 /* Concatenate tokens */
4621 /* Delete the previous whitespace token */
4622 if (buf->str[buf->pos - 1] == ' ') {
4625 /* Skip the next sequence of whitspace tokens */
4627 fstart = fmacro.pos;
4628 raw_next_token(state, &fmacro, tk);
4629 } while(tk->tok == TOK_SPACE);
4630 /* Restart at the top of the loop.
4631 * I need to process the non white space token.
4636 /* Collapse multiple spaces into one */
4637 if (buf->str[buf->pos - 1] != ' ') {
4649 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4651 fstart = fmacro.pos;
4652 raw_next_token(state, &fmacro, tk);
4656 static void tag_macro_name(struct compile_state *state,
4657 struct macro *macro, struct macro_buf *buf,
4660 /* Guard all instances of the macro name in the replacement
4661 * text from further macro expansion.
4663 struct file_state fmacro;
4667 /* Put the old macro expansion buffer in a file */
4669 fmacro.basename = macro->ident->name;
4670 fmacro.dirname = "";
4671 fmacro.buf = buf->str;
4672 fmacro.size = buf->pos;
4673 fmacro.pos = fmacro.buf;
4675 fmacro.line_start = fmacro.buf;
4676 fmacro.report_line = 1;
4677 fmacro.report_name = fmacro.basename;
4678 fmacro.report_dir = fmacro.dirname;
4680 fmacro.trigraphs = 0;
4681 fmacro.join_lines = 0;
4683 /* Allocate a new macro expansion buffer */
4684 buf->len = macro->buf_len + 3;
4685 buf->str = xmalloc(buf->len, macro->ident->name);
4688 fstart = fmacro.pos;
4689 raw_next_token(state, &fmacro, tk);
4690 while(tk->tok != TOK_EOF) {
4691 flen = fmacro.pos - fstart;
4692 if ((tk->tok == TOK_IDENT) &&
4693 (tk->ident == macro->ident) &&
4694 (tk->val.notmacro == 0))
4696 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4701 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4703 fstart = fmacro.pos;
4704 raw_next_token(state, &fmacro, tk);
4709 static int compile_macro(struct compile_state *state,
4710 struct file_state **filep, struct token *tk)
4712 struct file_state *file;
4713 struct hash_entry *ident;
4714 struct macro *macro;
4715 struct macro_arg_value *argv;
4716 struct macro_buf buf;
4719 fprintf(state->errout, "macro: %s\n", tk->ident->name);
4722 macro = ident->sym_define;
4724 /* If this token comes from a macro expansion ignore it */
4725 if (tk->val.notmacro) {
4728 /* If I am a function like macro and the identifier is not followed
4729 * by a left parenthesis, do nothing.
4731 if ((macro->argc >= 0) && (get_char(*filep, (*filep)->pos) != '(')) {
4735 /* Read in the macro arguments */
4737 if (macro->argc >= 0) {
4738 raw_next_token(state, *filep, tk);
4739 check_tok(state, tk, TOK_LPAREN);
4741 argv = read_macro_args(state, macro, *filep, tk);
4743 check_tok(state, tk, TOK_RPAREN);
4745 /* Macro expand the macro arguments */
4746 macro_expand_args(state, macro, argv, tk);
4751 if (ident == state->i___FILE__) {
4752 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4753 buf.str = xmalloc(buf.len, ident->name);
4754 sprintf(buf.str, "\"%s\"", state->file->basename);
4755 buf.pos = strlen(buf.str);
4757 else if (ident == state->i___LINE__) {
4759 buf.str = xmalloc(buf.len, ident->name);
4760 sprintf(buf.str, "%d", state->file->line);
4761 buf.pos = strlen(buf.str);
4764 expand_macro(state, macro, &buf, argv, tk);
4766 /* Tag the macro name with a $ so it will no longer
4767 * be regonized as a canidate for macro expansion.
4769 tag_macro_name(state, macro, &buf, tk);
4772 fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4773 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4776 free_macro_args(macro, argv);
4778 file = xmalloc(sizeof(*file), "file_state");
4779 file->prev = *filep;
4780 file->basename = xstrdup(ident->name);
4781 file->dirname = xstrdup("");
4782 file->buf = buf.str;
4783 file->size = buf.pos;
4784 file->pos = file->buf;
4786 file->line_start = file->pos;
4787 file->report_line = 1;
4788 file->report_name = file->basename;
4789 file->report_dir = file->dirname;
4791 file->trigraphs = 0;
4792 file->join_lines = 0;
4797 static void eat_tokens(struct compile_state *state, int targ_tok)
4799 if (state->eat_depth > 0) {
4800 internal_error(state, 0, "Already eating...");
4802 state->eat_depth = state->if_depth;
4803 state->eat_targ = targ_tok;
4805 static int if_eat(struct compile_state *state)
4807 return state->eat_depth > 0;
4809 static int if_value(struct compile_state *state)
4812 index = state->if_depth / CHAR_BIT;
4813 offset = state->if_depth % CHAR_BIT;
4814 return !!(state->if_bytes[index] & (1 << (offset)));
4816 static void set_if_value(struct compile_state *state, int value)
4819 index = state->if_depth / CHAR_BIT;
4820 offset = state->if_depth % CHAR_BIT;
4822 state->if_bytes[index] &= ~(1 << offset);
4824 state->if_bytes[index] |= (1 << offset);
4827 static void in_if(struct compile_state *state, const char *name)
4829 if (state->if_depth <= 0) {
4830 error(state, 0, "%s without #if", name);
4833 static void enter_if(struct compile_state *state)
4835 state->if_depth += 1;
4836 if (state->if_depth > MAX_PP_IF_DEPTH) {
4837 error(state, 0, "#if depth too great");
4840 static void reenter_if(struct compile_state *state, const char *name)
4843 if ((state->eat_depth == state->if_depth) &&
4844 (state->eat_targ == TOK_MELSE)) {
4845 state->eat_depth = 0;
4846 state->eat_targ = 0;
4849 static void enter_else(struct compile_state *state, const char *name)
4852 if ((state->eat_depth == state->if_depth) &&
4853 (state->eat_targ == TOK_MELSE)) {
4854 state->eat_depth = 0;
4855 state->eat_targ = 0;
4858 static void exit_if(struct compile_state *state, const char *name)
4861 if (state->eat_depth == state->if_depth) {
4862 state->eat_depth = 0;
4863 state->eat_targ = 0;
4865 state->if_depth -= 1;
4868 static void raw_token(struct compile_state *state, struct token *tk)
4870 struct file_state *file;
4874 raw_next_token(state, file, tk);
4878 /* Exit out of an include directive or macro call */
4879 if ((tk->tok == TOK_EOF) &&
4880 (file != state->macro_file) && file->prev)
4882 state->file = file->prev;
4883 /* file->basename is used keep it */
4884 xfree(file->dirname);
4888 raw_next_token(state, state->file, tk);
4894 static void pp_token(struct compile_state *state, struct token *tk)
4898 raw_token(state, tk);
4901 if (tk->tok == TOK_SPACE) {
4902 raw_token(state, tk);
4905 else if (tk->tok == TOK_IDENT) {
4906 if (state->token_base == 0) {
4907 ident_to_keyword(state, tk);
4909 ident_to_macro(state, tk);
4915 static void preprocess(struct compile_state *state, struct token *tk);
4917 static void token(struct compile_state *state, struct token *tk)
4920 pp_token(state, tk);
4923 /* Process a macro directive */
4924 if (tk->tok == TOK_MACRO) {
4925 /* Only match preprocessor directives at the start of a line */
4927 ptr = state->file->line_start;
4928 while((ptr < tk->pos)
4929 && spacep(get_char(state->file, ptr)))
4931 ptr = next_char(state->file, ptr, 1);
4933 if (ptr == tk->pos) {
4934 preprocess(state, tk);
4938 /* Expand a macro call */
4939 else if (tk->ident && tk->ident->sym_define) {
4940 rescan = compile_macro(state, &state->file, tk);
4942 pp_token(state, tk);
4945 /* Eat tokens disabled by the preprocessor
4946 * (Unless we are parsing a preprocessor directive
4948 else if (if_eat(state) && (state->token_base == 0)) {
4949 pp_token(state, tk);
4952 /* Make certain EOL only shows up in preprocessor directives */
4953 else if ((tk->tok == TOK_EOL) && (state->token_base == 0)) {
4954 pp_token(state, tk);
4957 /* Error on unknown tokens */
4958 else if (tk->tok == TOK_UNKNOWN) {
4959 error(state, 0, "unknown token");
4965 static inline struct token *get_token(struct compile_state *state, int offset)
4968 index = state->token_base + offset;
4969 if (index >= sizeof(state->token)/sizeof(state->token[0])) {
4970 internal_error(state, 0, "token array to small");
4972 return &state->token[index];
4975 static struct token *do_eat_token(struct compile_state *state, int tok)
4979 check_tok(state, get_token(state, 1), tok);
4981 /* Free the old token value */
4982 tk = get_token(state, 0);
4984 memset((void *)tk->val.str, -1, tk->str_len);
4987 /* Overwrite the old token with newer tokens */
4988 for(i = state->token_base; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4989 state->token[i] = state->token[i + 1];
4991 /* Clear the last token */
4992 memset(&state->token[i], 0, sizeof(state->token[i]));
4993 state->token[i].tok = -1;
4995 /* Return the token */
4999 static int raw_peek(struct compile_state *state)
5002 tk1 = get_token(state, 1);
5003 if (tk1->tok == -1) {
5004 raw_token(state, tk1);
5009 static struct token *raw_eat(struct compile_state *state, int tok)
5012 return do_eat_token(state, tok);
5015 static int pp_peek(struct compile_state *state)
5018 tk1 = get_token(state, 1);
5019 if (tk1->tok == -1) {
5020 pp_token(state, tk1);
5025 static struct token *pp_eat(struct compile_state *state, int tok)
5028 return do_eat_token(state, tok);
5031 static int peek(struct compile_state *state)
5034 tk1 = get_token(state, 1);
5035 if (tk1->tok == -1) {
5041 static int peek2(struct compile_state *state)
5043 struct token *tk1, *tk2;
5044 tk1 = get_token(state, 1);
5045 tk2 = get_token(state, 2);
5046 if (tk1->tok == -1) {
5049 if (tk2->tok == -1) {
5055 static struct token *eat(struct compile_state *state, int tok)
5058 return do_eat_token(state, tok);
5061 static void compile_file(struct compile_state *state, const char *filename, int local)
5063 char cwd[MAX_CWD_SIZE];
5064 const char *subdir, *base;
5066 struct file_state *file;
5068 file = xmalloc(sizeof(*file), "file_state");
5070 base = strrchr(filename, '/');
5073 subdir_len = base - filename;
5080 basename = xmalloc(strlen(base) +1, "basename");
5081 strcpy(basename, base);
5082 file->basename = basename;
5084 if (getcwd(cwd, sizeof(cwd)) == 0) {
5085 die("cwd buffer to small");
5087 if ((subdir[0] == '/') || ((subdir[1] == ':') && ((subdir[2] == '/') || (subdir[2] == '\\')))) {
5088 file->dirname = xmalloc(subdir_len + 1, "dirname");
5089 memcpy(file->dirname, subdir, subdir_len);
5090 file->dirname[subdir_len] = '\0';
5096 /* Find the appropriate directory... */
5098 if (!state->file && exists(cwd, filename)) {
5101 if (local && state->file && exists(state->file->dirname, filename)) {
5102 dir = state->file->dirname;
5104 for(path = state->compiler->include_paths; !dir && *path; path++) {
5105 if (exists(*path, filename)) {
5110 error(state, 0, "Cannot open `%s'\n", filename);
5112 dirlen = strlen(dir);
5113 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5114 memcpy(file->dirname, dir, dirlen);
5115 file->dirname[dirlen] = '/';
5116 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5117 file->dirname[dirlen + 1 + subdir_len] = '\0';
5119 file->buf = slurp_file(file->dirname, file->basename, &file->size);
5121 file->pos = file->buf;
5122 file->line_start = file->pos;
5125 file->report_line = 1;
5126 file->report_name = file->basename;
5127 file->report_dir = file->dirname;
5129 file->trigraphs = (state->compiler->flags & COMPILER_TRIGRAPHS)? 1: 0;
5130 file->join_lines = 1;
5132 file->prev = state->file;
5136 static struct triple *constant_expr(struct compile_state *state);
5137 static void integral(struct compile_state *state, struct triple *def);
5139 static int mcexpr(struct compile_state *state)
5141 struct triple *cvalue;
5142 cvalue = constant_expr(state);
5143 integral(state, cvalue);
5144 if (cvalue->op != OP_INTCONST) {
5145 error(state, 0, "integer constant expected");
5147 return cvalue->u.cval != 0;
5150 static void preprocess(struct compile_state *state, struct token *current_token)
5152 /* Doing much more with the preprocessor would require
5153 * a parser and a major restructuring.
5154 * Postpone that for later.
5159 state->macro_file = state->file;
5161 old_token_base = state->token_base;
5162 state->token_base = current_token - state->token;
5164 tok = pp_peek(state);
5170 tk = pp_eat(state, TOK_LIT_INT);
5171 override_line = strtoul(tk->val.str, 0, 10);
5172 /* I have a preprocessor line marker parse it */
5173 if (pp_peek(state) == TOK_LIT_STRING) {
5174 const char *token, *base;
5176 int name_len, dir_len;
5177 tk = pp_eat(state, TOK_LIT_STRING);
5178 name = xmalloc(tk->str_len, "report_name");
5179 token = tk->val.str + 1;
5180 base = strrchr(token, '/');
5181 name_len = tk->str_len -2;
5183 dir_len = base - token;
5185 name_len -= base - token;
5190 memcpy(name, base, name_len);
5191 name[name_len] = '\0';
5192 dir = xmalloc(dir_len + 1, "report_dir");
5193 memcpy(dir, token, dir_len);
5194 dir[dir_len] = '\0';
5195 state->file->report_line = override_line - 1;
5196 state->file->report_name = name;
5197 state->file->report_dir = dir;
5198 state->file->macro = 0;
5205 pp_eat(state, TOK_MLINE);
5206 tk = eat(state, TOK_LIT_INT);
5207 state->file->report_line = strtoul(tk->val.str, 0, 10) -1;
5208 if (pp_peek(state) == TOK_LIT_STRING) {
5209 const char *token, *base;
5211 int name_len, dir_len;
5212 tk = pp_eat(state, TOK_LIT_STRING);
5213 name = xmalloc(tk->str_len, "report_name");
5214 token = tk->val.str + 1;
5215 base = strrchr(token, '/');
5216 name_len = tk->str_len - 2;
5218 dir_len = base - token;
5220 name_len -= base - token;
5225 memcpy(name, base, name_len);
5226 name[name_len] = '\0';
5227 dir = xmalloc(dir_len + 1, "report_dir");
5228 memcpy(dir, token, dir_len);
5229 dir[dir_len] = '\0';
5230 state->file->report_name = name;
5231 state->file->report_dir = dir;
5232 state->file->macro = 0;
5238 struct hash_entry *ident;
5239 pp_eat(state, TOK_MUNDEF);
5240 if (if_eat(state)) /* quit early when #if'd out */
5243 ident = pp_eat(state, TOK_MIDENT)->ident;
5245 undef_macro(state, ident);
5249 pp_eat(state, TOK_MPRAGMA);
5250 if (if_eat(state)) /* quit early when #if'd out */
5252 warning(state, 0, "Ignoring pragma");
5255 pp_eat(state, TOK_MELIF);
5256 reenter_if(state, "#elif");
5257 if (if_eat(state)) /* quit early when #if'd out */
5259 /* If the #if was taken the #elif just disables the following code */
5260 if (if_value(state)) {
5261 eat_tokens(state, TOK_MENDIF);
5263 /* If the previous #if was not taken see if the #elif enables the
5267 set_if_value(state, mcexpr(state));
5268 if (!if_value(state)) {
5269 eat_tokens(state, TOK_MELSE);
5274 pp_eat(state, TOK_MIF);
5276 if (if_eat(state)) /* quit early when #if'd out */
5278 set_if_value(state, mcexpr(state));
5279 if (!if_value(state)) {
5280 eat_tokens(state, TOK_MELSE);
5285 struct hash_entry *ident;
5287 pp_eat(state, TOK_MIFNDEF);
5289 if (if_eat(state)) /* quit early when #if'd out */
5291 ident = pp_eat(state, TOK_MIDENT)->ident;
5292 set_if_value(state, ident->sym_define == 0);
5293 if (!if_value(state)) {
5294 eat_tokens(state, TOK_MELSE);
5300 struct hash_entry *ident;
5301 pp_eat(state, TOK_MIFDEF);
5303 if (if_eat(state)) /* quit early when #if'd out */
5305 ident = pp_eat(state, TOK_MIDENT)->ident;
5306 set_if_value(state, ident->sym_define != 0);
5307 if (!if_value(state)) {
5308 eat_tokens(state, TOK_MELSE);
5313 pp_eat(state, TOK_MELSE);
5314 enter_else(state, "#else");
5315 if (!if_eat(state) && if_value(state)) {
5316 eat_tokens(state, TOK_MENDIF);
5320 pp_eat(state, TOK_MENDIF);
5321 exit_if(state, "#endif");
5325 struct hash_entry *ident;
5326 struct macro_arg *args, **larg;
5327 const char *mstart, *mend;
5330 pp_eat(state, TOK_MDEFINE);
5331 if (if_eat(state)) /* quit early when #if'd out */
5333 ident = pp_eat(state, TOK_MIDENT)->ident;
5338 /* Parse macro parameters */
5339 if (raw_peek(state) == TOK_LPAREN) {
5340 raw_eat(state, TOK_LPAREN);
5344 struct macro_arg *narg, *arg;
5345 struct hash_entry *aident;
5348 tok = pp_peek(state);
5349 if (!args && (tok == TOK_RPAREN)) {
5352 else if (tok == TOK_DOTS) {
5353 pp_eat(state, TOK_DOTS);
5354 aident = state->i___VA_ARGS__;
5357 aident = pp_eat(state, TOK_MIDENT)->ident;
5360 narg = xcmalloc(sizeof(*arg), "macro arg");
5361 narg->ident = aident;
5363 /* Verify I don't have a duplicate identifier */
5364 for(arg = args; arg; arg = arg->next) {
5365 if (arg->ident == narg->ident) {
5366 error(state, 0, "Duplicate macro arg `%s'",
5370 /* Add the new argument to the end of the list */
5375 if ((aident == state->i___VA_ARGS__) ||
5376 (pp_peek(state) != TOK_COMMA)) {
5379 pp_eat(state, TOK_COMMA);
5381 pp_eat(state, TOK_RPAREN);
5383 /* Remove leading whitespace */
5384 while(raw_peek(state) == TOK_SPACE) {
5385 raw_eat(state, TOK_SPACE);
5388 /* Remember the start of the macro body */
5389 tok = raw_peek(state);
5390 mend = mstart = get_token(state, 1)->pos;
5392 /* Find the end of the macro */
5393 for(tok = raw_peek(state); tok != TOK_EOL; tok = raw_peek(state)) {
5394 raw_eat(state, tok);
5395 /* Remember the end of the last non space token */
5397 if (tok != TOK_SPACE) {
5398 mend = get_token(state, 1)->pos;
5402 /* Now that I have found the body defined the token */
5403 do_define_macro(state, ident,
5404 char_strdup(state->file, mstart, mend, "macro buf"),
5410 const char *start, *end;
5413 pp_eat(state, TOK_MERROR);
5414 /* Find the start of the line */
5416 start = get_token(state, 1)->pos;
5418 /* Find the end of the line */
5419 while((tok = raw_peek(state)) != TOK_EOL) {
5420 raw_eat(state, tok);
5422 end = get_token(state, 1)->pos;
5424 if (!if_eat(state)) {
5425 error(state, 0, "%*.*s", len, len, start);
5431 const char *start, *end;
5434 pp_eat(state, TOK_MWARNING);
5436 /* Find the start of the line */
5438 start = get_token(state, 1)->pos;
5440 /* Find the end of the line */
5441 while((tok = raw_peek(state)) != TOK_EOL) {
5442 raw_eat(state, tok);
5444 end = get_token(state, 1)->pos;
5446 if (!if_eat(state)) {
5447 warning(state, 0, "%*.*s", len, len, start);
5458 pp_eat(state, TOK_MINCLUDE);
5459 if (if_eat(state)) {
5460 /* Find the end of the line */
5461 while((tok = raw_peek(state)) != TOK_EOL) {
5462 raw_eat(state, tok);
5467 if (tok == TOK_LIT_STRING) {
5471 tk = eat(state, TOK_LIT_STRING);
5472 name = xmalloc(tk->str_len, "include");
5473 token = tk->val.str +1;
5474 name_len = tk->str_len -2;
5475 if (*token == '"') {
5479 memcpy(name, token, name_len);
5480 name[name_len] = '\0';
5483 else if (tok == TOK_LESS) {
5484 struct macro_buf buf;
5485 eat(state, TOK_LESS);
5488 buf.str = xmalloc(buf.len, "include");
5492 while((tok != TOK_MORE) &&
5493 (tok != TOK_EOL) && (tok != TOK_EOF))
5496 tk = eat(state, tok);
5497 append_macro_chars(state, "include", &buf,
5498 state->file, tk->pos, state->file->pos);
5501 append_macro_text(state, "include", &buf, "\0", 1);
5502 if (peek(state) != TOK_MORE) {
5503 error(state, 0, "Unterminated include directive");
5505 eat(state, TOK_MORE);
5510 error(state, 0, "Invalid include directive");
5512 /* Error if there are any tokens after the include */
5513 if (pp_peek(state) != TOK_EOL) {
5514 error(state, 0, "garbage after include directive");
5516 if (!if_eat(state)) {
5517 compile_file(state, name, local);
5523 /* Ignore # without a follwing ident */
5527 const char *name1, *name2;
5528 name1 = tokens[tok];
5530 if (tok == TOK_MIDENT) {
5531 name2 = get_token(state, 1)->ident->name;
5533 error(state, 0, "Invalid preprocessor directive: %s %s",
5538 /* Consume the rest of the macro line */
5540 tok = pp_peek(state);
5542 } while((tok != TOK_EOF) && (tok != TOK_EOL));
5543 state->token_base = old_token_base;
5544 state->macro_file = NULL;
5548 /* Type helper functions */
5550 static struct type *new_type(
5551 unsigned int type, struct type *left, struct type *right)
5553 struct type *result;
5554 result = xmalloc(sizeof(*result), "type");
5555 result->type = type;
5556 result->left = left;
5557 result->right = right;
5558 result->field_ident = 0;
5559 result->type_ident = 0;
5560 result->elements = 0;
5564 static struct type *clone_type(unsigned int specifiers, struct type *old)
5566 struct type *result;
5567 result = xmalloc(sizeof(*result), "type");
5568 memcpy(result, old, sizeof(*result));
5569 result->type &= TYPE_MASK;
5570 result->type |= specifiers;
5574 static struct type *dup_type(struct compile_state *state, struct type *orig)
5577 new = xcmalloc(sizeof(*new), "type");
5578 new->type = orig->type;
5579 new->field_ident = orig->field_ident;
5580 new->type_ident = orig->type_ident;
5581 new->elements = orig->elements;
5583 new->left = dup_type(state, orig->left);
5586 new->right = dup_type(state, orig->right);
5592 static struct type *invalid_type(struct compile_state *state, struct type *type)
5594 struct type *invalid, *member;
5597 internal_error(state, 0, "type missing?");
5599 switch(type->type & TYPE_MASK) {
5601 case TYPE_CHAR: case TYPE_UCHAR:
5602 case TYPE_SHORT: case TYPE_USHORT:
5603 case TYPE_INT: case TYPE_UINT:
5604 case TYPE_LONG: case TYPE_ULONG:
5605 case TYPE_LLONG: case TYPE_ULLONG:
5610 invalid = invalid_type(state, type->left);
5613 invalid = invalid_type(state, type->left);
5617 member = type->left;
5618 while(member && (invalid == 0) &&
5619 ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5620 invalid = invalid_type(state, member->left);
5621 member = member->right;
5624 invalid = invalid_type(state, member);
5629 member = type->left;
5630 while(member && (invalid == 0) &&
5631 ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5632 invalid = invalid_type(state, member->left);
5633 member = member->right;
5636 invalid = invalid_type(state, member);
5647 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
5648 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5649 static inline ulong_t mask_uint(ulong_t x)
5651 if (SIZEOF_INT < SIZEOF_LONG) {
5652 ulong_t mask = (1ULL << ((ulong_t)(SIZEOF_INT))) -1;
5657 #define MASK_UINT(X) (mask_uint(X))
5658 #define MASK_ULONG(X) (X)
5660 static struct type void_type = { .type = TYPE_VOID };
5661 static struct type char_type = { .type = TYPE_CHAR };
5662 static struct type uchar_type = { .type = TYPE_UCHAR };
5663 #if DEBUG_ROMCC_WARNING
5664 static struct type short_type = { .type = TYPE_SHORT };
5666 static struct type ushort_type = { .type = TYPE_USHORT };
5667 static struct type int_type = { .type = TYPE_INT };
5668 static struct type uint_type = { .type = TYPE_UINT };
5669 static struct type long_type = { .type = TYPE_LONG };
5670 static struct type ulong_type = { .type = TYPE_ULONG };
5671 static struct type unknown_type = { .type = TYPE_UNKNOWN };
5673 static struct type void_ptr_type = {
5674 .type = TYPE_POINTER,
5678 #if DEBUG_ROMCC_WARNING
5679 static struct type void_func_type = {
5680 .type = TYPE_FUNCTION,
5682 .right = &void_type,
5686 static size_t bits_to_bytes(size_t size)
5688 return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5691 static struct triple *variable(struct compile_state *state, struct type *type)
5693 struct triple *result;
5694 if ((type->type & STOR_MASK) != STOR_PERM) {
5695 result = triple(state, OP_ADECL, type, 0, 0);
5696 generate_lhs_pieces(state, result);
5699 result = triple(state, OP_SDECL, type, 0, 0);
5704 static void stor_of(FILE *fp, struct type *type)
5706 switch(type->type & STOR_MASK) {
5708 fprintf(fp, "auto ");
5711 fprintf(fp, "static ");
5714 fprintf(fp, "local ");
5717 fprintf(fp, "extern ");
5720 fprintf(fp, "register ");
5723 fprintf(fp, "typedef ");
5725 case STOR_INLINE | STOR_LOCAL:
5726 fprintf(fp, "inline ");
5728 case STOR_INLINE | STOR_STATIC:
5729 fprintf(fp, "static inline");
5731 case STOR_INLINE | STOR_EXTERN:
5732 fprintf(fp, "extern inline");
5735 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5739 static void qual_of(FILE *fp, struct type *type)
5741 if (type->type & QUAL_CONST) {
5742 fprintf(fp, " const");
5744 if (type->type & QUAL_VOLATILE) {
5745 fprintf(fp, " volatile");
5747 if (type->type & QUAL_RESTRICT) {
5748 fprintf(fp, " restrict");
5752 static void name_of(FILE *fp, struct type *type)
5754 unsigned int base_type;
5755 base_type = type->type & TYPE_MASK;
5756 if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5761 fprintf(fp, "void");
5765 fprintf(fp, "signed char");
5769 fprintf(fp, "unsigned char");
5773 fprintf(fp, "signed short");
5777 fprintf(fp, "unsigned short");
5781 fprintf(fp, "signed int");
5785 fprintf(fp, "unsigned int");
5789 fprintf(fp, "signed long");
5793 fprintf(fp, "unsigned long");
5797 name_of(fp, type->left);
5802 name_of(fp, type->left);
5804 name_of(fp, type->right);
5807 name_of(fp, type->left);
5809 name_of(fp, type->right);
5812 fprintf(fp, "enum %s",
5813 (type->type_ident)? type->type_ident->name : "");
5817 fprintf(fp, "struct %s { ",
5818 (type->type_ident)? type->type_ident->name : "");
5819 name_of(fp, type->left);
5824 fprintf(fp, "union %s { ",
5825 (type->type_ident)? type->type_ident->name : "");
5826 name_of(fp, type->left);
5831 name_of(fp, type->left);
5832 fprintf(fp, " (*)(");
5833 name_of(fp, type->right);
5837 name_of(fp, type->left);
5838 fprintf(fp, " [%ld]", (long)(type->elements));
5841 fprintf(fp, "tuple { ");
5842 name_of(fp, type->left);
5847 fprintf(fp, "join { ");
5848 name_of(fp, type->left);
5853 name_of(fp, type->left);
5854 fprintf(fp, " : %d ", type->elements);
5858 fprintf(fp, "unknown_t");
5861 fprintf(fp, "????: %x", base_type);
5864 if (type->field_ident && type->field_ident->name) {
5865 fprintf(fp, " .%s", type->field_ident->name);
5869 static size_t align_of(struct compile_state *state, struct type *type)
5873 switch(type->type & TYPE_MASK) {
5882 align = ALIGNOF_CHAR;
5886 align = ALIGNOF_SHORT;
5891 align = ALIGNOF_INT;
5895 align = ALIGNOF_LONG;
5898 align = ALIGNOF_POINTER;
5903 size_t left_align, right_align;
5904 left_align = align_of(state, type->left);
5905 right_align = align_of(state, type->right);
5906 align = (left_align >= right_align) ? left_align : right_align;
5910 align = align_of(state, type->left);
5916 align = align_of(state, type->left);
5919 error(state, 0, "alignof not yet defined for type\n");
5925 static size_t reg_align_of(struct compile_state *state, struct type *type)
5929 switch(type->type & TYPE_MASK) {
5938 align = REG_ALIGNOF_CHAR;
5942 align = REG_ALIGNOF_SHORT;
5947 align = REG_ALIGNOF_INT;
5951 align = REG_ALIGNOF_LONG;
5954 align = REG_ALIGNOF_POINTER;
5959 size_t left_align, right_align;
5960 left_align = reg_align_of(state, type->left);
5961 right_align = reg_align_of(state, type->right);
5962 align = (left_align >= right_align) ? left_align : right_align;
5966 align = reg_align_of(state, type->left);
5972 align = reg_align_of(state, type->left);
5975 error(state, 0, "alignof not yet defined for type\n");
5981 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
5983 return bits_to_bytes(align_of(state, type));
5985 static size_t size_of(struct compile_state *state, struct type *type);
5986 static size_t reg_size_of(struct compile_state *state, struct type *type);
5988 static size_t needed_padding(struct compile_state *state,
5989 struct type *type, size_t offset)
5991 size_t padding, align;
5992 align = align_of(state, type);
5993 /* Align to the next machine word if the bitfield does completely
5994 * fit into the current word.
5996 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
5998 size = size_of(state, type);
5999 if ((offset + type->elements)/size != offset/size) {
6004 if (offset % align) {
6005 padding = align - (offset % align);
6010 static size_t reg_needed_padding(struct compile_state *state,
6011 struct type *type, size_t offset)
6013 size_t padding, align;
6014 align = reg_align_of(state, type);
6015 /* Align to the next register word if the bitfield does completely
6016 * fit into the current register.
6018 if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
6019 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG)))
6021 align = REG_SIZEOF_REG;
6024 if (offset % align) {
6025 padding = align - (offset % align);
6030 static size_t size_of(struct compile_state *state, struct type *type)
6034 switch(type->type & TYPE_MASK) {
6039 size = type->elements;
6047 size = SIZEOF_SHORT;
6059 size = SIZEOF_POINTER;
6065 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6066 pad = needed_padding(state, type->left, size);
6067 size = size + pad + size_of(state, type->left);
6070 pad = needed_padding(state, type, size);
6071 size = size + pad + size_of(state, type);
6076 size_t size_left, size_right;
6077 size_left = size_of(state, type->left);
6078 size_right = size_of(state, type->right);
6079 size = (size_left >= size_right)? size_left : size_right;
6083 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6084 internal_error(state, 0, "Invalid array type");
6086 size = size_of(state, type->left) * type->elements;
6093 size = size_of(state, type->left);
6094 /* Pad structures so their size is a multiples of their alignment */
6095 pad = needed_padding(state, type, size);
6103 size = size_of(state, type->left);
6104 /* Pad unions so their size is a multiple of their alignment */
6105 pad = needed_padding(state, type, size);
6110 internal_error(state, 0, "sizeof not yet defined for type");
6116 static size_t reg_size_of(struct compile_state *state, struct type *type)
6120 switch(type->type & TYPE_MASK) {
6125 size = type->elements;
6129 size = REG_SIZEOF_CHAR;
6133 size = REG_SIZEOF_SHORT;
6138 size = REG_SIZEOF_INT;
6142 size = REG_SIZEOF_LONG;
6145 size = REG_SIZEOF_POINTER;
6151 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6152 pad = reg_needed_padding(state, type->left, size);
6153 size = size + pad + reg_size_of(state, type->left);
6156 pad = reg_needed_padding(state, type, size);
6157 size = size + pad + reg_size_of(state, type);
6162 size_t size_left, size_right;
6163 size_left = reg_size_of(state, type->left);
6164 size_right = reg_size_of(state, type->right);
6165 size = (size_left >= size_right)? size_left : size_right;
6169 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6170 internal_error(state, 0, "Invalid array type");
6172 size = reg_size_of(state, type->left) * type->elements;
6179 size = reg_size_of(state, type->left);
6180 /* Pad structures so their size is a multiples of their alignment */
6181 pad = reg_needed_padding(state, type, size);
6189 size = reg_size_of(state, type->left);
6190 /* Pad unions so their size is a multiple of their alignment */
6191 pad = reg_needed_padding(state, type, size);
6196 internal_error(state, 0, "sizeof not yet defined for type");
6202 static size_t registers_of(struct compile_state *state, struct type *type)
6205 registers = reg_size_of(state, type);
6206 registers += REG_SIZEOF_REG - 1;
6207 registers /= REG_SIZEOF_REG;
6211 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6213 return bits_to_bytes(size_of(state, type));
6216 static size_t field_offset(struct compile_state *state,
6217 struct type *type, struct hash_entry *field)
6219 struct type *member;
6224 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6225 member = type->left;
6226 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6227 size += needed_padding(state, member->left, size);
6228 if (member->left->field_ident == field) {
6229 member = member->left;
6232 size += size_of(state, member->left);
6233 member = member->right;
6235 size += needed_padding(state, member, size);
6237 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6238 member = type->left;
6239 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6240 if (member->left->field_ident == field) {
6241 member = member->left;
6244 member = member->right;
6248 internal_error(state, 0, "field_offset only works on structures and unions");
6251 if (!member || (member->field_ident != field)) {
6252 error(state, 0, "member %s not present", field->name);
6257 static size_t field_reg_offset(struct compile_state *state,
6258 struct type *type, struct hash_entry *field)
6260 struct type *member;
6265 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6266 member = type->left;
6267 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6268 size += reg_needed_padding(state, member->left, size);
6269 if (member->left->field_ident == field) {
6270 member = member->left;
6273 size += reg_size_of(state, member->left);
6274 member = member->right;
6277 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6278 member = type->left;
6279 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6280 if (member->left->field_ident == field) {
6281 member = member->left;
6284 member = member->right;
6288 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6291 size += reg_needed_padding(state, member, size);
6292 if (!member || (member->field_ident != field)) {
6293 error(state, 0, "member %s not present", field->name);
6298 static struct type *field_type(struct compile_state *state,
6299 struct type *type, struct hash_entry *field)
6301 struct type *member;
6304 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6305 member = type->left;
6306 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6307 if (member->left->field_ident == field) {
6308 member = member->left;
6311 member = member->right;
6314 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6315 member = type->left;
6316 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6317 if (member->left->field_ident == field) {
6318 member = member->left;
6321 member = member->right;
6325 internal_error(state, 0, "field_type only works on structures and unions");
6328 if (!member || (member->field_ident != field)) {
6329 error(state, 0, "member %s not present", field->name);
6334 static size_t index_offset(struct compile_state *state,
6335 struct type *type, ulong_t index)
6337 struct type *member;
6340 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6341 size = size_of(state, type->left) * index;
6343 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6345 member = type->left;
6347 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6348 size += needed_padding(state, member->left, size);
6350 member = member->left;
6353 size += size_of(state, member->left);
6355 member = member->right;
6357 size += needed_padding(state, member, size);
6359 internal_error(state, 0, "Missing member index: %u", index);
6362 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6365 member = type->left;
6367 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6369 member = member->left;
6373 member = member->right;
6376 internal_error(state, 0, "Missing member index: %u", index);
6380 internal_error(state, 0,
6381 "request for index %u in something not an array, tuple or join",
6387 static size_t index_reg_offset(struct compile_state *state,
6388 struct type *type, ulong_t index)
6390 struct type *member;
6393 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6394 size = reg_size_of(state, type->left) * index;
6396 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6398 member = type->left;
6400 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6401 size += reg_needed_padding(state, member->left, size);
6403 member = member->left;
6406 size += reg_size_of(state, member->left);
6408 member = member->right;
6410 size += reg_needed_padding(state, member, size);
6412 internal_error(state, 0, "Missing member index: %u", index);
6416 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6419 member = type->left;
6421 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6423 member = member->left;
6427 member = member->right;
6430 internal_error(state, 0, "Missing member index: %u", index);
6434 internal_error(state, 0,
6435 "request for index %u in something not an array, tuple or join",
6441 static struct type *index_type(struct compile_state *state,
6442 struct type *type, ulong_t index)
6444 struct type *member;
6445 if (index >= type->elements) {
6446 internal_error(state, 0, "Invalid element %u requested", index);
6448 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6449 member = type->left;
6451 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6453 member = type->left;
6455 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6457 member = member->left;
6461 member = member->right;
6464 internal_error(state, 0, "Missing member index: %u", index);
6467 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6469 member = type->left;
6471 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6473 member = member->left;
6477 member = member->right;
6480 internal_error(state, 0, "Missing member index: %u", index);
6485 internal_error(state, 0,
6486 "request for index %u in something not an array, tuple or join",
6492 static struct type *unpack_type(struct compile_state *state, struct type *type)
6494 /* If I have a single register compound type not a bit-field
6495 * find the real type.
6497 struct type *start_type;
6499 /* Get out early if I need multiple registers for this type */
6500 size = reg_size_of(state, type);
6501 if (size > REG_SIZEOF_REG) {
6504 /* Get out early if I don't need any registers for this type */
6508 /* Loop until I have no more layers I can remove */
6511 switch(type->type & TYPE_MASK) {
6513 /* If I have a single element the unpacked type
6516 if (type->elements == 1) {
6522 /* If I have a single element the unpacked type
6525 if (type->elements == 1) {
6528 /* If I have multiple elements the unpacked
6529 * type is the non-void element.
6532 struct type *next, *member;
6533 struct type *sub_type;
6539 if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6540 next = member->right;
6541 member = member->left;
6543 if (reg_size_of(state, member) > 0) {
6545 internal_error(state, 0, "true compound type in a register");
6558 /* If I have a single element the unpacked type
6561 if (type->elements == 1) {
6564 /* I can't in general unpack union types */
6567 /* If I'm not a compound type I can't unpack it */
6570 } while(start_type != type);
6571 switch(type->type & TYPE_MASK) {
6575 internal_error(state, 0, "irredicible type?");
6581 static int equiv_types(struct type *left, struct type *right);
6582 static int is_compound_type(struct type *type);
6584 static struct type *reg_type(
6585 struct compile_state *state, struct type *type, int reg_offset)
6587 struct type *member;
6590 struct type *invalid;
6591 invalid = invalid_type(state, type);
6593 fprintf(state->errout, "type: ");
6594 name_of(state->errout, type);
6595 fprintf(state->errout, "\n");
6596 fprintf(state->errout, "invalid: ");
6597 name_of(state->errout, invalid);
6598 fprintf(state->errout, "\n");
6599 internal_error(state, 0, "bad input type?");
6603 size = reg_size_of(state, type);
6604 if (reg_offset > size) {
6606 fprintf(state->errout, "type: ");
6607 name_of(state->errout, type);
6608 fprintf(state->errout, "\n");
6609 internal_error(state, 0, "offset outside of type");
6612 switch(type->type & TYPE_MASK) {
6613 /* Don't do anything with the basic types */
6615 case TYPE_CHAR: case TYPE_UCHAR:
6616 case TYPE_SHORT: case TYPE_USHORT:
6617 case TYPE_INT: case TYPE_UINT:
6618 case TYPE_LONG: case TYPE_ULONG:
6619 case TYPE_LLONG: case TYPE_ULLONG:
6620 case TYPE_FLOAT: case TYPE_DOUBLE:
6628 member = type->left;
6629 size = reg_size_of(state, member);
6630 if (size > REG_SIZEOF_REG) {
6631 member = reg_type(state, member, reg_offset % size);
6639 member = type->left;
6640 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6641 size = reg_size_of(state, member->left);
6642 offset += reg_needed_padding(state, member->left, offset);
6643 if ((offset + size) > reg_offset) {
6644 member = member->left;
6648 member = member->right;
6650 offset += reg_needed_padding(state, member, offset);
6651 member = reg_type(state, member, reg_offset - offset);
6657 struct type *join, **jnext, *mnext;
6658 join = new_type(TYPE_JOIN, 0, 0);
6659 jnext = &join->left;
6665 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6666 mnext = member->right;
6667 member = member->left;
6669 size = reg_size_of(state, member);
6670 if (size > reg_offset) {
6671 struct type *part, *hunt;
6672 part = reg_type(state, member, reg_offset);
6673 /* See if this type is already in the union */
6676 struct type *test = hunt;
6678 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6682 if (equiv_types(part, test)) {
6690 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6691 jnext = &(*jnext)->right;
6698 if (join->elements == 0) {
6699 internal_error(state, 0, "No elements?");
6706 fprintf(state->errout, "type: ");
6707 name_of(state->errout, type);
6708 fprintf(state->errout, "\n");
6709 internal_error(state, 0, "reg_type not yet defined for type");
6713 /* If I have a single register compound type not a bit-field
6714 * find the real type.
6716 member = unpack_type(state, member);
6718 size = reg_size_of(state, member);
6719 if (size > REG_SIZEOF_REG) {
6720 internal_error(state, 0, "Cannot find type of single register");
6723 invalid = invalid_type(state, member);
6725 fprintf(state->errout, "type: ");
6726 name_of(state->errout, member);
6727 fprintf(state->errout, "\n");
6728 fprintf(state->errout, "invalid: ");
6729 name_of(state->errout, invalid);
6730 fprintf(state->errout, "\n");
6731 internal_error(state, 0, "returning bad type?");
6737 static struct type *next_field(struct compile_state *state,
6738 struct type *type, struct type *prev_member)
6740 struct type *member;
6741 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6742 internal_error(state, 0, "next_field only works on structures");
6744 member = type->left;
6745 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6747 member = member->left;
6750 if (member->left == prev_member) {
6753 member = member->right;
6755 if (member == prev_member) {
6759 internal_error(state, 0, "prev_member %s not present",
6760 prev_member->field_ident->name);
6765 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type,
6766 size_t ret_offset, size_t mem_offset, void *arg);
6768 static void walk_type_fields(struct compile_state *state,
6769 struct type *type, size_t reg_offset, size_t mem_offset,
6770 walk_type_fields_cb_t cb, void *arg);
6772 static void walk_struct_fields(struct compile_state *state,
6773 struct type *type, size_t reg_offset, size_t mem_offset,
6774 walk_type_fields_cb_t cb, void *arg)
6778 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6779 internal_error(state, 0, "walk_struct_fields only works on structures");
6782 for(i = 0; i < type->elements; i++) {
6785 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6786 mtype = mtype->left;
6788 walk_type_fields(state, mtype,
6790 field_reg_offset(state, type, mtype->field_ident),
6792 field_offset(state, type, mtype->field_ident),
6799 static void walk_type_fields(struct compile_state *state,
6800 struct type *type, size_t reg_offset, size_t mem_offset,
6801 walk_type_fields_cb_t cb, void *arg)
6803 switch(type->type & TYPE_MASK) {
6805 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6815 cb(state, type, reg_offset, mem_offset, arg);
6820 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6824 static void arrays_complete(struct compile_state *state, struct type *type)
6826 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6827 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6828 error(state, 0, "array size not specified");
6830 arrays_complete(state, type->left);
6834 static unsigned int get_basic_type(struct type *type)
6837 basic = type->type & TYPE_MASK;
6838 /* Convert enums to ints */
6839 if (basic == TYPE_ENUM) {
6842 /* Convert bitfields to standard types */
6843 else if (basic == TYPE_BITFIELD) {
6844 if (type->elements <= SIZEOF_CHAR) {
6847 else if (type->elements <= SIZEOF_SHORT) {
6850 else if (type->elements <= SIZEOF_INT) {
6853 else if (type->elements <= SIZEOF_LONG) {
6856 if (!TYPE_SIGNED(type->left->type)) {
6863 static unsigned int do_integral_promotion(unsigned int type)
6865 if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6871 static unsigned int do_arithmetic_conversion(
6872 unsigned int left, unsigned int right)
6874 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6875 return TYPE_LDOUBLE;
6877 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
6880 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
6883 left = do_integral_promotion(left);
6884 right = do_integral_promotion(right);
6885 /* If both operands have the same size done */
6886 if (left == right) {
6889 /* If both operands have the same signedness pick the larger */
6890 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
6891 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
6893 /* If the signed type can hold everything use it */
6894 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
6897 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
6900 /* Convert to the unsigned type with the same rank as the signed type */
6901 else if (TYPE_SIGNED(left)) {
6902 return TYPE_MKUNSIGNED(left);
6905 return TYPE_MKUNSIGNED(right);
6909 /* see if two types are the same except for qualifiers */
6910 static int equiv_types(struct type *left, struct type *right)
6913 /* Error if the basic types do not match */
6914 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6917 type = left->type & TYPE_MASK;
6918 /* If the basic types match and it is a void type we are done */
6919 if (type == TYPE_VOID) {
6922 /* For bitfields we need to compare the sizes */
6923 else if (type == TYPE_BITFIELD) {
6924 return (left->elements == right->elements) &&
6925 (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
6927 /* if the basic types match and it is an arithmetic type we are done */
6928 else if (TYPE_ARITHMETIC(type)) {
6931 /* If it is a pointer type recurse and keep testing */
6932 else if (type == TYPE_POINTER) {
6933 return equiv_types(left->left, right->left);
6935 else if (type == TYPE_ARRAY) {
6936 return (left->elements == right->elements) &&
6937 equiv_types(left->left, right->left);
6939 /* test for struct equality */
6940 else if (type == TYPE_STRUCT) {
6941 return left->type_ident == right->type_ident;
6943 /* test for union equality */
6944 else if (type == TYPE_UNION) {
6945 return left->type_ident == right->type_ident;
6947 /* Test for equivalent functions */
6948 else if (type == TYPE_FUNCTION) {
6949 return equiv_types(left->left, right->left) &&
6950 equiv_types(left->right, right->right);
6952 /* We only see TYPE_PRODUCT as part of function equivalence matching */
6953 /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
6954 else if (type == TYPE_PRODUCT) {
6955 return equiv_types(left->left, right->left) &&
6956 equiv_types(left->right, right->right);
6958 /* We should see TYPE_OVERLAP when comparing joins */
6959 else if (type == TYPE_OVERLAP) {
6960 return equiv_types(left->left, right->left) &&
6961 equiv_types(left->right, right->right);
6963 /* Test for equivalence of tuples */
6964 else if (type == TYPE_TUPLE) {
6965 return (left->elements == right->elements) &&
6966 equiv_types(left->left, right->left);
6968 /* Test for equivalence of joins */
6969 else if (type == TYPE_JOIN) {
6970 return (left->elements == right->elements) &&
6971 equiv_types(left->left, right->left);
6978 static int equiv_ptrs(struct type *left, struct type *right)
6980 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
6981 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
6984 return equiv_types(left->left, right->left);
6987 static struct type *compatible_types(struct type *left, struct type *right)
6989 struct type *result;
6990 unsigned int type, qual_type;
6991 /* Error if the basic types do not match */
6992 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6995 type = left->type & TYPE_MASK;
6996 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
6998 /* if the basic types match and it is an arithmetic type we are done */
6999 if (TYPE_ARITHMETIC(type)) {
7000 result = new_type(qual_type, 0, 0);
7002 /* If it is a pointer type recurse and keep testing */
7003 else if (type == TYPE_POINTER) {
7004 result = compatible_types(left->left, right->left);
7006 result = new_type(qual_type, result, 0);
7009 /* test for struct equality */
7010 else if (type == TYPE_STRUCT) {
7011 if (left->type_ident == right->type_ident) {
7015 /* test for union equality */
7016 else if (type == TYPE_UNION) {
7017 if (left->type_ident == right->type_ident) {
7021 /* Test for equivalent functions */
7022 else if (type == TYPE_FUNCTION) {
7023 struct type *lf, *rf;
7024 lf = compatible_types(left->left, right->left);
7025 rf = compatible_types(left->right, right->right);
7027 result = new_type(qual_type, lf, rf);
7030 /* We only see TYPE_PRODUCT as part of function equivalence matching */
7031 else if (type == TYPE_PRODUCT) {
7032 struct type *lf, *rf;
7033 lf = compatible_types(left->left, right->left);
7034 rf = compatible_types(left->right, right->right);
7036 result = new_type(qual_type, lf, rf);
7040 /* Nothing else is compatible */
7045 /* See if left is a equivalent to right or right is a union member of left */
7046 static int is_subset_type(struct type *left, struct type *right)
7048 if (equiv_types(left, right)) {
7051 if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7052 struct type *member, *mnext;
7057 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7058 mnext = member->right;
7059 member = member->left;
7061 if (is_subset_type( member, right)) {
7069 static struct type *compatible_ptrs(struct type *left, struct type *right)
7071 struct type *result;
7072 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7073 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7076 result = compatible_types(left->left, right->left);
7078 unsigned int qual_type;
7079 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7080 result = new_type(qual_type, result, 0);
7085 static struct triple *integral_promotion(
7086 struct compile_state *state, struct triple *def)
7090 /* As all operations are carried out in registers
7091 * the values are converted on load I just convert
7092 * logical type of the operand.
7094 if (TYPE_INTEGER(type->type)) {
7095 unsigned int int_type;
7096 int_type = type->type & ~TYPE_MASK;
7097 int_type |= do_integral_promotion(get_basic_type(type));
7098 if (int_type != type->type) {
7099 if (def->op != OP_LOAD) {
7100 def->type = new_type(int_type, 0, 0);
7103 def = triple(state, OP_CONVERT,
7104 new_type(int_type, 0, 0), def, 0);
7112 static void arithmetic(struct compile_state *state, struct triple *def)
7114 if (!TYPE_ARITHMETIC(def->type->type)) {
7115 error(state, 0, "arithmetic type expexted");
7119 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7121 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7122 error(state, def, "pointer or arithmetic type expected");
7126 static int is_integral(struct triple *ins)
7128 return TYPE_INTEGER(ins->type->type);
7131 static void integral(struct compile_state *state, struct triple *def)
7133 if (!is_integral(def)) {
7134 error(state, 0, "integral type expected");
7139 static void bool(struct compile_state *state, struct triple *def)
7141 if (!TYPE_ARITHMETIC(def->type->type) &&
7142 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7143 error(state, 0, "arithmetic or pointer type expected");
7147 static int is_signed(struct type *type)
7149 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7152 return !!TYPE_SIGNED(type->type);
7154 static int is_compound_type(struct type *type)
7157 switch((type->type & TYPE_MASK)) {
7172 /* Is this value located in a register otherwise it must be in memory */
7173 static int is_in_reg(struct compile_state *state, struct triple *def)
7176 if (def->op == OP_ADECL) {
7179 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7182 else if (triple_is_part(state, def)) {
7183 in_reg = is_in_reg(state, MISC(def, 0));
7186 internal_error(state, def, "unknown expr storage location");
7192 /* Is this an auto or static variable location? Something that can
7193 * be assigned to. Otherwise it must must be a pure value, a temporary.
7195 static int is_lvalue(struct compile_state *state, struct triple *def)
7202 if ((def->op == OP_ADECL) ||
7203 (def->op == OP_SDECL) ||
7204 (def->op == OP_DEREF) ||
7205 (def->op == OP_BLOBCONST) ||
7206 (def->op == OP_LIST)) {
7209 else if (triple_is_part(state, def)) {
7210 ret = is_lvalue(state, MISC(def, 0));
7215 static void clvalue(struct compile_state *state, struct triple *def)
7218 internal_error(state, def, "nothing where lvalue expected?");
7220 if (!is_lvalue(state, def)) {
7221 error(state, def, "lvalue expected");
7224 static void lvalue(struct compile_state *state, struct triple *def)
7226 clvalue(state, def);
7227 if (def->type->type & QUAL_CONST) {
7228 error(state, def, "modifable lvalue expected");
7232 static int is_pointer(struct triple *def)
7234 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7237 static void pointer(struct compile_state *state, struct triple *def)
7239 if (!is_pointer(def)) {
7240 error(state, def, "pointer expected");
7244 static struct triple *int_const(
7245 struct compile_state *state, struct type *type, ulong_t value)
7247 struct triple *result;
7248 switch(type->type & TYPE_MASK) {
7250 case TYPE_INT: case TYPE_UINT:
7251 case TYPE_LONG: case TYPE_ULONG:
7254 internal_error(state, 0, "constant for unknown type");
7256 result = triple(state, OP_INTCONST, type, 0, 0);
7257 result->u.cval = value;
7262 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7264 static struct triple *do_mk_addr_expr(struct compile_state *state,
7265 struct triple *expr, struct type *type, ulong_t offset)
7267 struct triple *result;
7268 struct type *ptr_type;
7269 clvalue(state, expr);
7271 ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7275 if (expr->op == OP_ADECL) {
7276 error(state, expr, "address of auto variables not supported");
7278 else if (expr->op == OP_SDECL) {
7279 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7280 MISC(result, 0) = expr;
7281 result->u.cval = offset;
7283 else if (expr->op == OP_DEREF) {
7284 result = triple(state, OP_ADD, ptr_type,
7286 int_const(state, &ulong_type, offset));
7288 else if (expr->op == OP_BLOBCONST) {
7290 internal_error(state, expr, "not yet implemented");
7292 else if (expr->op == OP_LIST) {
7293 error(state, 0, "Function addresses not supported");
7295 else if (triple_is_part(state, expr)) {
7296 struct triple *part;
7298 expr = MISC(expr, 0);
7299 if (part->op == OP_DOT) {
7300 offset += bits_to_bytes(
7301 field_offset(state, expr->type, part->u.field));
7303 else if (part->op == OP_INDEX) {
7304 offset += bits_to_bytes(
7305 index_offset(state, expr->type, part->u.cval));
7308 internal_error(state, part, "unhandled part type");
7310 result = do_mk_addr_expr(state, expr, type, offset);
7313 internal_error(state, expr, "cannot take address of expression");
7318 static struct triple *mk_addr_expr(
7319 struct compile_state *state, struct triple *expr, ulong_t offset)
7321 return do_mk_addr_expr(state, expr, expr->type, offset);
7324 static struct triple *mk_deref_expr(
7325 struct compile_state *state, struct triple *expr)
7327 struct type *base_type;
7328 pointer(state, expr);
7329 base_type = expr->type->left;
7330 return triple(state, OP_DEREF, base_type, expr, 0);
7333 /* lvalue conversions always apply except when certain operators
7334 * are applied. So I apply apply it when I know no more
7335 * operators will be applied.
7337 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7339 /* Tranform an array to a pointer to the first element */
7340 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7343 TYPE_POINTER | (def->type->type & QUAL_MASK),
7344 def->type->left, 0);
7345 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7346 struct triple *addrconst;
7347 if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7348 internal_error(state, def, "bad array constant");
7350 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7351 MISC(addrconst, 0) = def;
7355 def = triple(state, OP_CONVERT, type, def, 0);
7358 /* Transform a function to a pointer to it */
7359 else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7360 def = mk_addr_expr(state, def, 0);
7365 static struct triple *deref_field(
7366 struct compile_state *state, struct triple *expr, struct hash_entry *field)
7368 struct triple *result;
7369 struct type *type, *member;
7372 internal_error(state, 0, "No field passed to deref_field");
7376 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7377 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7378 error(state, 0, "request for member %s in something not a struct or union",
7381 member = field_type(state, type, field);
7382 if ((type->type & STOR_MASK) == STOR_PERM) {
7383 /* Do the pointer arithmetic to get a deref the field */
7384 offset = bits_to_bytes(field_offset(state, type, field));
7385 result = do_mk_addr_expr(state, expr, member, offset);
7386 result = mk_deref_expr(state, result);
7389 /* Find the variable for the field I want. */
7390 result = triple(state, OP_DOT, member, expr, 0);
7391 result->u.field = field;
7396 static struct triple *deref_index(
7397 struct compile_state *state, struct triple *expr, size_t index)
7399 struct triple *result;
7400 struct type *type, *member;
7405 member = index_type(state, type, index);
7407 if ((type->type & STOR_MASK) == STOR_PERM) {
7408 offset = bits_to_bytes(index_offset(state, type, index));
7409 result = do_mk_addr_expr(state, expr, member, offset);
7410 result = mk_deref_expr(state, result);
7413 result = triple(state, OP_INDEX, member, expr, 0);
7414 result->u.cval = index;
7419 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7425 #if DEBUG_ROMCC_WARNINGS
7426 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7428 /* Transform lvalues into something we can read */
7429 def = lvalue_conversion(state, def);
7430 if (!is_lvalue(state, def)) {
7433 if (is_in_reg(state, def)) {
7436 if (def->op == OP_SDECL) {
7437 def = mk_addr_expr(state, def, 0);
7438 def = mk_deref_expr(state, def);
7442 def = triple(state, op, def->type, def, 0);
7443 if (def->type->type & QUAL_VOLATILE) {
7444 def->id |= TRIPLE_FLAG_VOLATILE;
7449 int is_write_compatible(struct compile_state *state,
7450 struct type *dest, struct type *rval)
7453 /* Both operands have arithmetic type */
7454 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7457 /* One operand is a pointer and the other is a pointer to void */
7458 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7459 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7460 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7461 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7464 /* If both types are the same without qualifiers we are good */
7465 else if (equiv_ptrs(dest, rval)) {
7468 /* test for struct/union equality */
7469 else if (equiv_types(dest, rval)) {
7475 static void write_compatible(struct compile_state *state,
7476 struct type *dest, struct type *rval)
7478 if (!is_write_compatible(state, dest, rval)) {
7479 FILE *fp = state->errout;
7480 fprintf(fp, "dest: ");
7482 fprintf(fp,"\nrval: ");
7485 error(state, 0, "Incompatible types in assignment");
7489 static int is_init_compatible(struct compile_state *state,
7490 struct type *dest, struct type *rval)
7493 if (is_write_compatible(state, dest, rval)) {
7496 else if (equiv_types(dest, rval)) {
7502 static struct triple *write_expr(
7503 struct compile_state *state, struct triple *dest, struct triple *rval)
7509 internal_error(state, 0, "missing rval");
7512 if (rval->op == OP_LIST) {
7513 internal_error(state, 0, "expression of type OP_LIST?");
7515 if (!is_lvalue(state, dest)) {
7516 internal_error(state, 0, "writing to a non lvalue?");
7518 if (dest->type->type & QUAL_CONST) {
7519 internal_error(state, 0, "modifable lvalue expexted");
7522 write_compatible(state, dest->type, rval->type);
7523 if (!equiv_types(dest->type, rval->type)) {
7524 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7527 /* Now figure out which assignment operator to use */
7528 if (is_in_reg(state, dest)) {
7529 def = triple(state, OP_WRITE, dest->type, rval, dest);
7530 if (MISC(def, 0) != dest) {
7531 internal_error(state, def, "huh?");
7533 if (RHS(def, 0) != rval) {
7534 internal_error(state, def, "huh?");
7537 def = triple(state, OP_STORE, dest->type, dest, rval);
7539 if (def->type->type & QUAL_VOLATILE) {
7540 def->id |= TRIPLE_FLAG_VOLATILE;
7545 static struct triple *init_expr(
7546 struct compile_state *state, struct triple *dest, struct triple *rval)
7552 internal_error(state, 0, "missing rval");
7554 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
7555 rval = read_expr(state, rval);
7556 def = write_expr(state, dest, rval);
7559 /* Fill in the array size if necessary */
7560 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
7561 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
7562 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
7563 dest->type->elements = rval->type->elements;
7566 if (!equiv_types(dest->type, rval->type)) {
7567 error(state, 0, "Incompatible types in inializer");
7569 MISC(dest, 0) = rval;
7570 insert_triple(state, dest, rval);
7571 rval->id |= TRIPLE_FLAG_FLATTENED;
7572 use_triple(MISC(dest, 0), dest);
7577 struct type *arithmetic_result(
7578 struct compile_state *state, struct triple *left, struct triple *right)
7581 /* Sanity checks to ensure I am working with arithmetic types */
7582 arithmetic(state, left);
7583 arithmetic(state, right);
7585 do_arithmetic_conversion(
7586 get_basic_type(left->type),
7587 get_basic_type(right->type)),
7592 struct type *ptr_arithmetic_result(
7593 struct compile_state *state, struct triple *left, struct triple *right)
7596 /* Sanity checks to ensure I am working with the proper types */
7597 ptr_arithmetic(state, left);
7598 arithmetic(state, right);
7599 if (TYPE_ARITHMETIC(left->type->type) &&
7600 TYPE_ARITHMETIC(right->type->type)) {
7601 type = arithmetic_result(state, left, right);
7603 else if (TYPE_PTR(left->type->type)) {
7607 internal_error(state, 0, "huh?");
7613 /* boolean helper function */
7615 static struct triple *ltrue_expr(struct compile_state *state,
7616 struct triple *expr)
7619 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
7620 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
7621 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
7622 /* If the expression is already boolean do nothing */
7625 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
7631 static struct triple *lfalse_expr(struct compile_state *state,
7632 struct triple *expr)
7634 return triple(state, OP_LFALSE, &int_type, expr, 0);
7637 static struct triple *mkland_expr(
7638 struct compile_state *state,
7639 struct triple *left, struct triple *right)
7641 struct triple *def, *val, *var, *jmp, *mid, *end;
7642 struct triple *lstore, *rstore;
7644 /* Generate some intermediate triples */
7646 var = variable(state, &int_type);
7648 /* Store the left hand side value */
7649 lstore = write_expr(state, var, left);
7651 /* Jump if the value is false */
7652 jmp = branch(state, end,
7653 lfalse_expr(state, read_expr(state, var)));
7656 /* Store the right hand side value */
7657 rstore = write_expr(state, var, right);
7659 /* An expression for the computed value */
7660 val = read_expr(state, var);
7662 /* Generate the prog for a logical and */
7663 def = mkprog(state, var, lstore, jmp, mid, rstore, end, val, 0UL);
7668 static struct triple *mklor_expr(
7669 struct compile_state *state,
7670 struct triple *left, struct triple *right)
7672 struct triple *def, *val, *var, *jmp, *mid, *end;
7674 /* Generate some intermediate triples */
7676 var = variable(state, &int_type);
7678 /* Store the left hand side value */
7679 left = write_expr(state, var, left);
7681 /* Jump if the value is true */
7682 jmp = branch(state, end, read_expr(state, var));
7685 /* Store the right hand side value */
7686 right = write_expr(state, var, right);
7688 /* An expression for the computed value*/
7689 val = read_expr(state, var);
7691 /* Generate the prog for a logical or */
7692 def = mkprog(state, var, left, jmp, mid, right, end, val, 0UL);
7697 static struct triple *mkcond_expr(
7698 struct compile_state *state,
7699 struct triple *test, struct triple *left, struct triple *right)
7701 struct triple *def, *val, *var, *jmp1, *jmp2, *top, *mid, *end;
7702 struct type *result_type;
7703 unsigned int left_type, right_type;
7705 left_type = left->type->type;
7706 right_type = right->type->type;
7708 /* Both operands have arithmetic type */
7709 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
7710 result_type = arithmetic_result(state, left, right);
7712 /* Both operands have void type */
7713 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
7714 ((right_type & TYPE_MASK) == TYPE_VOID)) {
7715 result_type = &void_type;
7717 /* pointers to the same type... */
7718 else if ((result_type = compatible_ptrs(left->type, right->type))) {
7721 /* Both operands are pointers and left is a pointer to void */
7722 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7723 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7724 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7725 result_type = right->type;
7727 /* Both operands are pointers and right is a pointer to void */
7728 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7729 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7730 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7731 result_type = left->type;
7734 error(state, 0, "Incompatible types in conditional expression");
7736 /* Generate some intermediate triples */
7739 var = variable(state, result_type);
7741 /* Branch if the test is false */
7742 jmp1 = branch(state, mid, lfalse_expr(state, read_expr(state, test)));
7745 /* Store the left hand side value */
7746 left = write_expr(state, var, left);
7748 /* Branch to the end */
7749 jmp2 = branch(state, end, 0);
7751 /* Store the right hand side value */
7752 right = write_expr(state, var, right);
7754 /* An expression for the computed value */
7755 val = read_expr(state, var);
7757 /* Generate the prog for a conditional expression */
7758 def = mkprog(state, var, jmp1, top, left, jmp2, mid, right, end, val, 0UL);
7764 static int expr_depth(struct compile_state *state, struct triple *ins)
7766 #if DEBUG_ROMCC_WARNINGS
7767 #warning "FIXME move optimal ordering of subexpressions into the optimizer"
7771 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
7774 else if (ins->op == OP_DEREF) {
7775 count = expr_depth(state, RHS(ins, 0)) - 1;
7777 else if (ins->op == OP_VAL) {
7778 count = expr_depth(state, RHS(ins, 0)) - 1;
7780 else if (ins->op == OP_FCALL) {
7781 /* Don't figure the depth of a call just guess it is huge */
7785 struct triple **expr;
7786 expr = triple_rhs(state, ins, 0);
7787 for(;expr; expr = triple_rhs(state, ins, expr)) {
7790 depth = expr_depth(state, *expr);
7791 if (depth > count) {
7800 static struct triple *flatten_generic(
7801 struct compile_state *state, struct triple *first, struct triple *ptr,
7806 struct triple **ins;
7809 /* Only operations with just a rhs and a lhs should come here */
7812 if (TRIPLE_SIZE(ptr) != lhs + rhs + ignored) {
7813 internal_error(state, ptr, "unexpected args for: %d %s",
7814 ptr->op, tops(ptr->op));
7816 /* Find the depth of the rhs elements */
7817 for(i = 0; i < rhs; i++) {
7818 vector[i].ins = &RHS(ptr, i);
7819 vector[i].depth = expr_depth(state, *vector[i].ins);
7821 /* Selection sort the rhs */
7822 for(i = 0; i < rhs; i++) {
7824 for(j = i + 1; j < rhs; j++ ) {
7825 if (vector[j].depth > vector[max].depth) {
7830 struct rhs_vector tmp;
7832 vector[i] = vector[max];
7836 /* Now flatten the rhs elements */
7837 for(i = 0; i < rhs; i++) {
7838 *vector[i].ins = flatten(state, first, *vector[i].ins);
7839 use_triple(*vector[i].ins, ptr);
7842 insert_triple(state, first, ptr);
7843 ptr->id |= TRIPLE_FLAG_FLATTENED;
7844 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7846 /* Now flatten the lhs elements */
7847 for(i = 0; i < lhs; i++) {
7848 struct triple **ins = &LHS(ptr, i);
7849 *ins = flatten(state, first, *ins);
7850 use_triple(*ins, ptr);
7856 static struct triple *flatten_prog(
7857 struct compile_state *state, struct triple *first, struct triple *ptr)
7859 struct triple *head, *body, *val;
7864 release_triple(state, head);
7865 release_triple(state, ptr);
7867 body->prev = first->prev;
7868 body->prev->next = body;
7869 val->next->prev = val;
7871 if (triple_is_cbranch(state, body->prev) ||
7872 triple_is_call(state, body->prev)) {
7873 unuse_triple(first, body->prev);
7874 use_triple(body, body->prev);
7877 if (!(val->id & TRIPLE_FLAG_FLATTENED)) {
7878 internal_error(state, val, "val not flattened?");
7885 static struct triple *flatten_part(
7886 struct compile_state *state, struct triple *first, struct triple *ptr)
7888 if (!triple_is_part(state, ptr)) {
7889 internal_error(state, ptr, "not a part");
7891 if (ptr->rhs || ptr->lhs || ptr->targ || (ptr->misc != 1)) {
7892 internal_error(state, ptr, "unexpected args for: %d %s",
7893 ptr->op, tops(ptr->op));
7895 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7896 use_triple(MISC(ptr, 0), ptr);
7897 return flatten_generic(state, first, ptr, 1);
7900 static struct triple *flatten(
7901 struct compile_state *state, struct triple *first, struct triple *ptr)
7903 struct triple *orig_ptr;
7908 /* Only flatten triples once */
7909 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
7914 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7915 return MISC(ptr, 0);
7918 ptr = flatten_prog(state, first, ptr);
7921 ptr = flatten_generic(state, first, ptr, 1);
7922 insert_triple(state, first, ptr);
7923 ptr->id |= TRIPLE_FLAG_FLATTENED;
7924 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7925 if (ptr->next != ptr) {
7926 use_triple(ptr->next, ptr);
7931 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7932 use_triple(RHS(ptr, 0), ptr);
7935 ptr = flatten_generic(state, first, ptr, 1);
7936 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7937 use_triple(MISC(ptr, 0), ptr);
7940 use_triple(TARG(ptr, 0), ptr);
7943 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7944 use_triple(RHS(ptr, 0), ptr);
7945 use_triple(TARG(ptr, 0), ptr);
7946 insert_triple(state, first, ptr);
7947 ptr->id |= TRIPLE_FLAG_FLATTENED;
7948 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7949 if (ptr->next != ptr) {
7950 use_triple(ptr->next, ptr);
7954 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7955 use_triple(MISC(ptr, 0), ptr);
7956 use_triple(TARG(ptr, 0), ptr);
7957 insert_triple(state, first, ptr);
7958 ptr->id |= TRIPLE_FLAG_FLATTENED;
7959 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7960 if (ptr->next != ptr) {
7961 use_triple(ptr->next, ptr);
7965 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7966 use_triple(RHS(ptr, 0), ptr);
7969 insert_triple(state, state->global_pool, ptr);
7970 ptr->id |= TRIPLE_FLAG_FLATTENED;
7971 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7972 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
7973 use_triple(MISC(ptr, 0), ptr);
7976 /* Since OP_DEREF is just a marker delete it when I flatten it */
7978 RHS(orig_ptr, 0) = 0;
7979 free_triple(state, orig_ptr);
7982 if (RHS(ptr, 0)->op == OP_DEREF) {
7983 struct triple *base, *left;
7985 base = MISC(ptr, 0);
7986 offset = bits_to_bytes(field_offset(state, base->type, ptr->u.field));
7987 left = RHS(base, 0);
7988 ptr = triple(state, OP_ADD, left->type,
7989 read_expr(state, left),
7990 int_const(state, &ulong_type, offset));
7991 free_triple(state, base);
7994 ptr = flatten_part(state, first, ptr);
7998 if (RHS(ptr, 0)->op == OP_DEREF) {
7999 struct triple *base, *left;
8001 base = MISC(ptr, 0);
8002 offset = bits_to_bytes(index_offset(state, base->type, ptr->u.cval));
8003 left = RHS(base, 0);
8004 ptr = triple(state, OP_ADD, left->type,
8005 read_expr(state, left),
8006 int_const(state, &long_type, offset));
8007 free_triple(state, base);
8010 ptr = flatten_part(state, first, ptr);
8014 ptr = flatten_part(state, first, ptr);
8015 use_triple(ptr, MISC(ptr, 0));
8018 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8019 use_triple(MISC(ptr, 0), ptr);
8022 first = state->global_pool;
8023 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8024 use_triple(MISC(ptr, 0), ptr);
8025 insert_triple(state, first, ptr);
8026 ptr->id |= TRIPLE_FLAG_FLATTENED;
8027 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8030 ptr = flatten_generic(state, first, ptr, 0);
8033 /* Flatten the easy cases we don't override */
8034 ptr = flatten_generic(state, first, ptr, 0);
8037 } while(ptr && (ptr != orig_ptr));
8038 if (ptr && !(ptr->id & TRIPLE_FLAG_FLATTENED)) {
8039 insert_triple(state, first, ptr);
8040 ptr->id |= TRIPLE_FLAG_FLATTENED;
8041 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8046 static void release_expr(struct compile_state *state, struct triple *expr)
8048 struct triple *head;
8049 head = label(state);
8050 flatten(state, head, expr);
8051 while(head->next != head) {
8052 release_triple(state, head->next);
8054 free_triple(state, head);
8057 static int replace_rhs_use(struct compile_state *state,
8058 struct triple *orig, struct triple *new, struct triple *use)
8060 struct triple **expr;
8063 expr = triple_rhs(state, use, 0);
8064 for(;expr; expr = triple_rhs(state, use, expr)) {
8065 if (*expr == orig) {
8071 unuse_triple(orig, use);
8072 use_triple(new, use);
8077 static int replace_lhs_use(struct compile_state *state,
8078 struct triple *orig, struct triple *new, struct triple *use)
8080 struct triple **expr;
8083 expr = triple_lhs(state, use, 0);
8084 for(;expr; expr = triple_lhs(state, use, expr)) {
8085 if (*expr == orig) {
8091 unuse_triple(orig, use);
8092 use_triple(new, use);
8097 static int replace_misc_use(struct compile_state *state,
8098 struct triple *orig, struct triple *new, struct triple *use)
8100 struct triple **expr;
8103 expr = triple_misc(state, use, 0);
8104 for(;expr; expr = triple_misc(state, use, expr)) {
8105 if (*expr == orig) {
8111 unuse_triple(orig, use);
8112 use_triple(new, use);
8117 static int replace_targ_use(struct compile_state *state,
8118 struct triple *orig, struct triple *new, struct triple *use)
8120 struct triple **expr;
8123 expr = triple_targ(state, use, 0);
8124 for(;expr; expr = triple_targ(state, use, expr)) {
8125 if (*expr == orig) {
8131 unuse_triple(orig, use);
8132 use_triple(new, use);
8137 static void replace_use(struct compile_state *state,
8138 struct triple *orig, struct triple *new, struct triple *use)
8142 found |= replace_rhs_use(state, orig, new, use);
8143 found |= replace_lhs_use(state, orig, new, use);
8144 found |= replace_misc_use(state, orig, new, use);
8145 found |= replace_targ_use(state, orig, new, use);
8147 internal_error(state, use, "use without use");
8151 static void propogate_use(struct compile_state *state,
8152 struct triple *orig, struct triple *new)
8154 struct triple_set *user, *next;
8155 for(user = orig->use; user; user = next) {
8156 /* Careful replace_use modifies the use chain and
8157 * removes use. So we must get a copy of the next
8161 replace_use(state, orig, new, user->member);
8164 internal_error(state, orig, "used after propogate_use");
8170 * ===========================
8173 static struct triple *mk_cast_expr(
8174 struct compile_state *state, struct type *type, struct triple *expr)
8177 def = read_expr(state, expr);
8178 def = triple(state, OP_CONVERT, type, def, 0);
8182 static struct triple *mk_add_expr(
8183 struct compile_state *state, struct triple *left, struct triple *right)
8185 struct type *result_type;
8186 /* Put pointer operands on the left */
8187 if (is_pointer(right)) {
8193 left = read_expr(state, left);
8194 right = read_expr(state, right);
8195 result_type = ptr_arithmetic_result(state, left, right);
8196 if (is_pointer(left)) {
8197 struct type *ptr_math;
8199 if (is_signed(right->type)) {
8200 ptr_math = &long_type;
8203 ptr_math = &ulong_type;
8206 if (!equiv_types(right->type, ptr_math)) {
8207 right = mk_cast_expr(state, ptr_math, right);
8209 right = triple(state, op, ptr_math, right,
8210 int_const(state, ptr_math,
8211 size_of_in_bytes(state, left->type->left)));
8213 return triple(state, OP_ADD, result_type, left, right);
8216 static struct triple *mk_sub_expr(
8217 struct compile_state *state, struct triple *left, struct triple *right)
8219 struct type *result_type;
8220 result_type = ptr_arithmetic_result(state, left, right);
8221 left = read_expr(state, left);
8222 right = read_expr(state, right);
8223 if (is_pointer(left)) {
8224 struct type *ptr_math;
8226 if (is_signed(right->type)) {
8227 ptr_math = &long_type;
8230 ptr_math = &ulong_type;
8233 if (!equiv_types(right->type, ptr_math)) {
8234 right = mk_cast_expr(state, ptr_math, right);
8236 right = triple(state, op, ptr_math, right,
8237 int_const(state, ptr_math,
8238 size_of_in_bytes(state, left->type->left)));
8240 return triple(state, OP_SUB, result_type, left, right);
8243 static struct triple *mk_pre_inc_expr(
8244 struct compile_state *state, struct triple *def)
8248 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
8249 return triple(state, OP_VAL, def->type,
8250 write_expr(state, def, val),
8254 static struct triple *mk_pre_dec_expr(
8255 struct compile_state *state, struct triple *def)
8259 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
8260 return triple(state, OP_VAL, def->type,
8261 write_expr(state, def, val),
8265 static struct triple *mk_post_inc_expr(
8266 struct compile_state *state, struct triple *def)
8270 val = read_expr(state, def);
8271 return triple(state, OP_VAL, def->type,
8272 write_expr(state, def,
8273 mk_add_expr(state, val, int_const(state, &int_type, 1)))
8277 static struct triple *mk_post_dec_expr(
8278 struct compile_state *state, struct triple *def)
8282 val = read_expr(state, def);
8283 return triple(state, OP_VAL, def->type,
8284 write_expr(state, def,
8285 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
8289 static struct triple *mk_subscript_expr(
8290 struct compile_state *state, struct triple *left, struct triple *right)
8292 left = read_expr(state, left);
8293 right = read_expr(state, right);
8294 if (!is_pointer(left) && !is_pointer(right)) {
8295 error(state, left, "subscripted value is not a pointer");
8297 return mk_deref_expr(state, mk_add_expr(state, left, right));
8302 * Compile time evaluation
8303 * ===========================
8305 static int is_const(struct triple *ins)
8307 return IS_CONST_OP(ins->op);
8310 static int is_simple_const(struct triple *ins)
8312 /* Is this a constant that u.cval has the value.
8313 * Or equivalently is this a constant that read_const
8315 * So far only OP_INTCONST qualifies.
8317 return (ins->op == OP_INTCONST);
8320 static int constants_equal(struct compile_state *state,
8321 struct triple *left, struct triple *right)
8324 if ((left->op == OP_UNKNOWNVAL) || (right->op == OP_UNKNOWNVAL)) {
8327 else if (!is_const(left) || !is_const(right)) {
8330 else if (left->op != right->op) {
8333 else if (!equiv_types(left->type, right->type)) {
8340 if (left->u.cval == right->u.cval) {
8346 size_t lsize, rsize, bytes;
8347 lsize = size_of(state, left->type);
8348 rsize = size_of(state, right->type);
8349 if (lsize != rsize) {
8352 bytes = bits_to_bytes(lsize);
8353 if (memcmp(left->u.blob, right->u.blob, bytes) == 0) {
8359 if ((MISC(left, 0) == MISC(right, 0)) &&
8360 (left->u.cval == right->u.cval)) {
8365 internal_error(state, left, "uknown constant type");
8372 static int is_zero(struct triple *ins)
8374 return is_simple_const(ins) && (ins->u.cval == 0);
8377 static int is_one(struct triple *ins)
8379 return is_simple_const(ins) && (ins->u.cval == 1);
8382 #if DEBUG_ROMCC_WARNING
8383 static long_t bit_count(ulong_t value)
8388 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8401 static long_t bsr(ulong_t value)
8404 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8415 static long_t bsf(ulong_t value)
8418 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
8429 static long_t ilog2(ulong_t value)
8434 static long_t tlog2(struct triple *ins)
8436 return ilog2(ins->u.cval);
8439 static int is_pow2(struct triple *ins)
8441 ulong_t value, mask;
8443 if (!is_const(ins)) {
8446 value = ins->u.cval;
8453 return ((value & mask) == value);
8456 static ulong_t read_const(struct compile_state *state,
8457 struct triple *ins, struct triple *rhs)
8459 switch(rhs->type->type &TYPE_MASK) {
8472 fprintf(state->errout, "type: ");
8473 name_of(state->errout, rhs->type);
8474 fprintf(state->errout, "\n");
8475 internal_warning(state, rhs, "bad type to read_const");
8478 if (!is_simple_const(rhs)) {
8479 internal_error(state, rhs, "bad op to read_const");
8484 static long_t read_sconst(struct compile_state *state,
8485 struct triple *ins, struct triple *rhs)
8487 return (long_t)(rhs->u.cval);
8490 int const_ltrue(struct compile_state *state, struct triple *ins, struct triple *rhs)
8492 if (!is_const(rhs)) {
8493 internal_error(state, 0, "non const passed to const_true");
8495 return !is_zero(rhs);
8498 int const_eq(struct compile_state *state, struct triple *ins,
8499 struct triple *left, struct triple *right)
8502 if (!is_const(left) || !is_const(right)) {
8503 internal_warning(state, ins, "non const passed to const_eq");
8506 else if (left == right) {
8509 else if (is_simple_const(left) && is_simple_const(right)) {
8511 lval = read_const(state, ins, left);
8512 rval = read_const(state, ins, right);
8513 result = (lval == rval);
8515 else if ((left->op == OP_ADDRCONST) &&
8516 (right->op == OP_ADDRCONST)) {
8517 result = (MISC(left, 0) == MISC(right, 0)) &&
8518 (left->u.cval == right->u.cval);
8521 internal_warning(state, ins, "incomparable constants passed to const_eq");
8528 int const_ucmp(struct compile_state *state, struct triple *ins,
8529 struct triple *left, struct triple *right)
8532 if (!is_const(left) || !is_const(right)) {
8533 internal_warning(state, ins, "non const past to const_ucmp");
8536 else if (left == right) {
8539 else if (is_simple_const(left) && is_simple_const(right)) {
8541 lval = read_const(state, ins, left);
8542 rval = read_const(state, ins, right);
8546 } else if (rval > lval) {
8550 else if ((left->op == OP_ADDRCONST) &&
8551 (right->op == OP_ADDRCONST) &&
8552 (MISC(left, 0) == MISC(right, 0))) {
8554 if (left->u.cval > right->u.cval) {
8556 } else if (left->u.cval < right->u.cval) {
8561 internal_warning(state, ins, "incomparable constants passed to const_ucmp");
8567 int const_scmp(struct compile_state *state, struct triple *ins,
8568 struct triple *left, struct triple *right)
8571 if (!is_const(left) || !is_const(right)) {
8572 internal_warning(state, ins, "non const past to ucmp_const");
8575 else if (left == right) {
8578 else if (is_simple_const(left) && is_simple_const(right)) {
8580 lval = read_sconst(state, ins, left);
8581 rval = read_sconst(state, ins, right);
8585 } else if (rval > lval) {
8590 internal_warning(state, ins, "incomparable constants passed to const_scmp");
8596 static void unuse_rhs(struct compile_state *state, struct triple *ins)
8598 struct triple **expr;
8599 expr = triple_rhs(state, ins, 0);
8600 for(;expr;expr = triple_rhs(state, ins, expr)) {
8602 unuse_triple(*expr, ins);
8608 static void unuse_lhs(struct compile_state *state, struct triple *ins)
8610 struct triple **expr;
8611 expr = triple_lhs(state, ins, 0);
8612 for(;expr;expr = triple_lhs(state, ins, expr)) {
8613 unuse_triple(*expr, ins);
8618 #if DEBUG_ROMCC_WARNING
8619 static void unuse_misc(struct compile_state *state, struct triple *ins)
8621 struct triple **expr;
8622 expr = triple_misc(state, ins, 0);
8623 for(;expr;expr = triple_misc(state, ins, expr)) {
8624 unuse_triple(*expr, ins);
8629 static void unuse_targ(struct compile_state *state, struct triple *ins)
8632 struct triple **slot;
8633 slot = &TARG(ins, 0);
8634 for(i = 0; i < ins->targ; i++) {
8635 unuse_triple(slot[i], ins);
8640 static void check_lhs(struct compile_state *state, struct triple *ins)
8642 struct triple **expr;
8643 expr = triple_lhs(state, ins, 0);
8644 for(;expr;expr = triple_lhs(state, ins, expr)) {
8645 internal_error(state, ins, "unexpected lhs");
8651 static void check_misc(struct compile_state *state, struct triple *ins)
8653 struct triple **expr;
8654 expr = triple_misc(state, ins, 0);
8655 for(;expr;expr = triple_misc(state, ins, expr)) {
8657 internal_error(state, ins, "unexpected misc");
8662 static void check_targ(struct compile_state *state, struct triple *ins)
8664 struct triple **expr;
8665 expr = triple_targ(state, ins, 0);
8666 for(;expr;expr = triple_targ(state, ins, expr)) {
8667 internal_error(state, ins, "unexpected targ");
8671 static void wipe_ins(struct compile_state *state, struct triple *ins)
8673 /* Becareful which instructions you replace the wiped
8674 * instruction with, as there are not enough slots
8675 * in all instructions to hold all others.
8677 check_targ(state, ins);
8678 check_misc(state, ins);
8679 unuse_rhs(state, ins);
8680 unuse_lhs(state, ins);
8687 #if DEBUG_ROMCC_WARNING
8688 static void wipe_branch(struct compile_state *state, struct triple *ins)
8690 /* Becareful which instructions you replace the wiped
8691 * instruction with, as there are not enough slots
8692 * in all instructions to hold all others.
8694 unuse_rhs(state, ins);
8695 unuse_lhs(state, ins);
8696 unuse_misc(state, ins);
8697 unuse_targ(state, ins);
8705 static void mkcopy(struct compile_state *state,
8706 struct triple *ins, struct triple *rhs)
8708 struct block *block;
8709 if (!equiv_types(ins->type, rhs->type)) {
8710 FILE *fp = state->errout;
8711 fprintf(fp, "src type: ");
8712 name_of(fp, rhs->type);
8713 fprintf(fp, "\ndst type: ");
8714 name_of(fp, ins->type);
8716 internal_error(state, ins, "mkcopy type mismatch");
8718 block = block_of_triple(state, ins);
8719 wipe_ins(state, ins);
8722 ins->u.block = block;
8724 use_triple(RHS(ins, 0), ins);
8727 static void mkconst(struct compile_state *state,
8728 struct triple *ins, ulong_t value)
8730 if (!is_integral(ins) && !is_pointer(ins)) {
8731 fprintf(state->errout, "type: ");
8732 name_of(state->errout, ins->type);
8733 fprintf(state->errout, "\n");
8734 internal_error(state, ins, "unknown type to make constant value: %ld",
8737 wipe_ins(state, ins);
8738 ins->op = OP_INTCONST;
8739 ins->u.cval = value;
8742 static void mkaddr_const(struct compile_state *state,
8743 struct triple *ins, struct triple *sdecl, ulong_t value)
8745 if ((sdecl->op != OP_SDECL) && (sdecl->op != OP_LABEL)) {
8746 internal_error(state, ins, "bad base for addrconst");
8748 wipe_ins(state, ins);
8749 ins->op = OP_ADDRCONST;
8751 MISC(ins, 0) = sdecl;
8752 ins->u.cval = value;
8753 use_triple(sdecl, ins);
8756 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8757 static void print_tuple(struct compile_state *state,
8758 struct triple *ins, struct triple *tuple)
8760 FILE *fp = state->dbgout;
8761 fprintf(fp, "%5s %p tuple: %p ", tops(ins->op), ins, tuple);
8762 name_of(fp, tuple->type);
8763 if (tuple->lhs > 0) {
8764 fprintf(fp, " lhs: ");
8765 name_of(fp, LHS(tuple, 0)->type);
8772 static struct triple *decompose_with_tuple(struct compile_state *state,
8773 struct triple *ins, struct triple *tuple)
8775 struct triple *next;
8777 flatten(state, next, tuple);
8778 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8779 print_tuple(state, ins, tuple);
8782 if (!is_compound_type(tuple->type) && (tuple->lhs > 0)) {
8784 if (tuple->lhs != 1) {
8785 internal_error(state, tuple, "plain type in multiple registers?");
8787 tmp = LHS(tuple, 0);
8788 release_triple(state, tuple);
8792 propogate_use(state, ins, tuple);
8793 release_triple(state, ins);
8798 static struct triple *decompose_unknownval(struct compile_state *state,
8801 struct triple *tuple;
8804 #if DEBUG_DECOMPOSE_HIRES
8805 FILE *fp = state->dbgout;
8806 fprintf(fp, "unknown type: ");
8807 name_of(fp, ins->type);
8811 get_occurance(ins->occurance);
8812 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8815 for(i = 0; i < tuple->lhs; i++) {
8816 struct type *piece_type;
8817 struct triple *unknown;
8819 piece_type = reg_type(state, ins->type, i * REG_SIZEOF_REG);
8820 get_occurance(tuple->occurance);
8821 unknown = alloc_triple(state, OP_UNKNOWNVAL, piece_type, 0, 0,
8823 LHS(tuple, i) = unknown;
8825 return decompose_with_tuple(state, ins, tuple);
8829 static struct triple *decompose_read(struct compile_state *state,
8832 struct triple *tuple, *lval;
8837 if (lval->op == OP_PIECE) {
8840 get_occurance(ins->occurance);
8841 tuple = alloc_triple(state, OP_TUPLE, lval->type, -1, -1,
8844 if ((tuple->lhs != lval->lhs) &&
8845 (!triple_is_def(state, lval) || (tuple->lhs != 1)))
8847 internal_error(state, ins, "lhs size inconsistency?");
8849 for(i = 0; i < tuple->lhs; i++) {
8850 struct triple *piece, *read, *bitref;
8851 if ((i != 0) || !triple_is_def(state, lval)) {
8852 piece = LHS(lval, i);
8857 /* See if the piece is really a bitref */
8859 if (piece->op == OP_BITREF) {
8861 piece = RHS(bitref, 0);
8864 get_occurance(tuple->occurance);
8865 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8867 RHS(read, 0) = piece;
8870 struct triple *extract;
8872 if (is_signed(bitref->type->left)) {
8877 get_occurance(tuple->occurance);
8878 extract = alloc_triple(state, op, bitref->type, -1, -1,
8880 RHS(extract, 0) = read;
8881 extract->u.bitfield.size = bitref->u.bitfield.size;
8882 extract->u.bitfield.offset = bitref->u.bitfield.offset;
8887 LHS(tuple, i) = read;
8889 return decompose_with_tuple(state, ins, tuple);
8892 static struct triple *decompose_write(struct compile_state *state,
8895 struct triple *tuple, *lval, *val;
8898 lval = MISC(ins, 0);
8900 get_occurance(ins->occurance);
8901 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8904 if ((tuple->lhs != lval->lhs) &&
8905 (!triple_is_def(state, lval) || tuple->lhs != 1))
8907 internal_error(state, ins, "lhs size inconsistency?");
8909 for(i = 0; i < tuple->lhs; i++) {
8910 struct triple *piece, *write, *pval, *bitref;
8911 if ((i != 0) || !triple_is_def(state, lval)) {
8912 piece = LHS(lval, i);
8916 if ((i == 0) && (tuple->lhs == 1) && (val->lhs == 0)) {
8921 internal_error(state, ins, "lhs size inconsistency?");
8926 /* See if the piece is really a bitref */
8928 if (piece->op == OP_BITREF) {
8929 struct triple *read, *deposit;
8931 piece = RHS(bitref, 0);
8933 /* Read the destination register */
8934 get_occurance(tuple->occurance);
8935 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8937 RHS(read, 0) = piece;
8939 /* Deposit the new bitfield value */
8940 get_occurance(tuple->occurance);
8941 deposit = alloc_triple(state, OP_DEPOSIT, piece->type, -1, -1,
8943 RHS(deposit, 0) = read;
8944 RHS(deposit, 1) = pval;
8945 deposit->u.bitfield.size = bitref->u.bitfield.size;
8946 deposit->u.bitfield.offset = bitref->u.bitfield.offset;
8948 /* Now write the newly generated value */
8952 get_occurance(tuple->occurance);
8953 write = alloc_triple(state, OP_WRITE, piece->type, -1, -1,
8955 MISC(write, 0) = piece;
8956 RHS(write, 0) = pval;
8957 LHS(tuple, i) = write;
8959 return decompose_with_tuple(state, ins, tuple);
8962 struct decompose_load_info {
8963 struct occurance *occurance;
8964 struct triple *lval;
8965 struct triple *tuple;
8967 static void decompose_load_cb(struct compile_state *state,
8968 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
8970 struct decompose_load_info *info = arg;
8971 struct triple *load;
8973 if (reg_offset > info->tuple->lhs) {
8974 internal_error(state, info->tuple, "lhs to small?");
8976 get_occurance(info->occurance);
8977 load = alloc_triple(state, OP_LOAD, type, -1, -1, info->occurance);
8978 RHS(load, 0) = mk_addr_expr(state, info->lval, mem_offset);
8979 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = load;
8982 static struct triple *decompose_load(struct compile_state *state,
8985 struct triple *tuple;
8986 struct decompose_load_info info;
8988 if (!is_compound_type(ins->type)) {
8991 get_occurance(ins->occurance);
8992 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8995 info.occurance = ins->occurance;
8996 info.lval = RHS(ins, 0);
8998 walk_type_fields(state, ins->type, 0, 0, decompose_load_cb, &info);
9000 return decompose_with_tuple(state, ins, tuple);
9004 struct decompose_store_info {
9005 struct occurance *occurance;
9006 struct triple *lval;
9008 struct triple *tuple;
9010 static void decompose_store_cb(struct compile_state *state,
9011 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9013 struct decompose_store_info *info = arg;
9014 struct triple *store;
9016 if (reg_offset > info->tuple->lhs) {
9017 internal_error(state, info->tuple, "lhs to small?");
9019 get_occurance(info->occurance);
9020 store = alloc_triple(state, OP_STORE, type, -1, -1, info->occurance);
9021 RHS(store, 0) = mk_addr_expr(state, info->lval, mem_offset);
9022 RHS(store, 1) = LHS(info->val, reg_offset);
9023 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = store;
9026 static struct triple *decompose_store(struct compile_state *state,
9029 struct triple *tuple;
9030 struct decompose_store_info info;
9032 if (!is_compound_type(ins->type)) {
9035 get_occurance(ins->occurance);
9036 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9039 info.occurance = ins->occurance;
9040 info.lval = RHS(ins, 0);
9041 info.val = RHS(ins, 1);
9043 walk_type_fields(state, ins->type, 0, 0, decompose_store_cb, &info);
9045 return decompose_with_tuple(state, ins, tuple);
9048 static struct triple *decompose_dot(struct compile_state *state,
9051 struct triple *tuple, *lval;
9056 lval = MISC(ins, 0);
9057 reg_offset = field_reg_offset(state, lval->type, ins->u.field);
9058 idx = reg_offset/REG_SIZEOF_REG;
9059 type = field_type(state, lval->type, ins->u.field);
9060 #if DEBUG_DECOMPOSE_HIRES
9062 FILE *fp = state->dbgout;
9063 fprintf(fp, "field type: ");
9069 get_occurance(ins->occurance);
9070 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9073 if (((ins->type->type & TYPE_MASK) == TYPE_BITFIELD) &&
9076 internal_error(state, ins, "multi register bitfield?");
9079 for(i = 0; i < tuple->lhs; i++, idx++) {
9080 struct triple *piece;
9081 if (!triple_is_def(state, lval)) {
9082 if (idx > lval->lhs) {
9083 internal_error(state, ins, "inconsistent lhs count");
9085 piece = LHS(lval, idx);
9088 internal_error(state, ins, "bad reg_offset into def");
9091 internal_error(state, ins, "bad reg count from def");
9096 /* Remember the offset of the bitfield */
9097 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
9098 get_occurance(ins->occurance);
9099 piece = build_triple(state, OP_BITREF, type, piece, 0,
9101 piece->u.bitfield.size = size_of(state, type);
9102 piece->u.bitfield.offset = reg_offset % REG_SIZEOF_REG;
9104 else if ((reg_offset % REG_SIZEOF_REG) != 0) {
9105 internal_error(state, ins,
9106 "request for a nonbitfield sub register?");
9109 LHS(tuple, i) = piece;
9112 return decompose_with_tuple(state, ins, tuple);
9115 static struct triple *decompose_index(struct compile_state *state,
9118 struct triple *tuple, *lval;
9122 lval = MISC(ins, 0);
9123 idx = index_reg_offset(state, lval->type, ins->u.cval)/REG_SIZEOF_REG;
9124 type = index_type(state, lval->type, ins->u.cval);
9125 #if DEBUG_DECOMPOSE_HIRES
9127 FILE *fp = state->dbgout;
9128 fprintf(fp, "index type: ");
9134 get_occurance(ins->occurance);
9135 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9138 for(i = 0; i < tuple->lhs; i++, idx++) {
9139 struct triple *piece;
9140 if (!triple_is_def(state, lval)) {
9141 if (idx > lval->lhs) {
9142 internal_error(state, ins, "inconsistent lhs count");
9144 piece = LHS(lval, idx);
9147 internal_error(state, ins, "bad reg_offset into def");
9150 internal_error(state, ins, "bad reg count from def");
9154 LHS(tuple, i) = piece;
9157 return decompose_with_tuple(state, ins, tuple);
9160 static void decompose_compound_types(struct compile_state *state)
9162 struct triple *ins, *next, *first;
9163 #if DEBUG_DECOMPOSE_HIRES
9167 first = state->first;
9170 /* Pass one expand compound values into pseudo registers.
9178 next = decompose_unknownval(state, ins);
9182 next = decompose_read(state, ins);
9186 next = decompose_write(state, ins);
9190 /* Be very careful with the load/store logic. These
9191 * operations must convert from the in register layout
9192 * to the in memory layout, which is nontrivial.
9195 next = decompose_load(state, ins);
9198 next = decompose_store(state, ins);
9202 next = decompose_dot(state, ins);
9205 next = decompose_index(state, ins);
9209 #if DEBUG_DECOMPOSE_HIRES
9210 fprintf(fp, "decompose next: %p \n", next);
9212 fprintf(fp, "next->op: %d %s\n",
9213 next->op, tops(next->op));
9214 /* High resolution debugging mode */
9215 print_triples(state);
9217 } while (next != first);
9219 /* Pass two remove the tuples.
9224 if (ins->op == OP_TUPLE) {
9226 internal_error(state, ins, "tuple used");
9229 release_triple(state, ins);
9233 } while(ins != first);
9237 if (ins->op == OP_BITREF) {
9239 internal_error(state, ins, "bitref used");
9242 release_triple(state, ins);
9246 } while(ins != first);
9248 /* Pass three verify the state and set ->id to 0.
9254 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9255 if (triple_stores_block(state, ins)) {
9258 if (triple_is_def(state, ins)) {
9259 if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9260 internal_error(state, ins, "multi register value remains?");
9263 if (ins->op == OP_DOT) {
9264 internal_error(state, ins, "OP_DOT remains?");
9266 if (ins->op == OP_INDEX) {
9267 internal_error(state, ins, "OP_INDEX remains?");
9269 if (ins->op == OP_BITREF) {
9270 internal_error(state, ins, "OP_BITREF remains?");
9272 if (ins->op == OP_TUPLE) {
9273 internal_error(state, ins, "OP_TUPLE remains?");
9275 } while(next != first);
9278 /* For those operations that cannot be simplified */
9279 static void simplify_noop(struct compile_state *state, struct triple *ins)
9284 static void simplify_smul(struct compile_state *state, struct triple *ins)
9286 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9289 RHS(ins, 0) = RHS(ins, 1);
9292 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9294 left = read_sconst(state, ins, RHS(ins, 0));
9295 right = read_sconst(state, ins, RHS(ins, 1));
9296 mkconst(state, ins, left * right);
9298 else if (is_zero(RHS(ins, 1))) {
9299 mkconst(state, ins, 0);
9301 else if (is_one(RHS(ins, 1))) {
9302 mkcopy(state, ins, RHS(ins, 0));
9304 else if (is_pow2(RHS(ins, 1))) {
9306 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9308 insert_triple(state, state->global_pool, val);
9309 unuse_triple(RHS(ins, 1), ins);
9310 use_triple(val, ins);
9315 static void simplify_umul(struct compile_state *state, struct triple *ins)
9317 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9320 RHS(ins, 0) = RHS(ins, 1);
9323 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9324 ulong_t left, right;
9325 left = read_const(state, ins, RHS(ins, 0));
9326 right = read_const(state, ins, RHS(ins, 1));
9327 mkconst(state, ins, left * right);
9329 else if (is_zero(RHS(ins, 1))) {
9330 mkconst(state, ins, 0);
9332 else if (is_one(RHS(ins, 1))) {
9333 mkcopy(state, ins, RHS(ins, 0));
9335 else if (is_pow2(RHS(ins, 1))) {
9337 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9339 insert_triple(state, state->global_pool, val);
9340 unuse_triple(RHS(ins, 1), ins);
9341 use_triple(val, ins);
9346 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9348 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9350 left = read_sconst(state, ins, RHS(ins, 0));
9351 right = read_sconst(state, ins, RHS(ins, 1));
9352 mkconst(state, ins, left / right);
9354 else if (is_zero(RHS(ins, 0))) {
9355 mkconst(state, ins, 0);
9357 else if (is_zero(RHS(ins, 1))) {
9358 error(state, ins, "division by zero");
9360 else if (is_one(RHS(ins, 1))) {
9361 mkcopy(state, ins, RHS(ins, 0));
9363 else if (is_pow2(RHS(ins, 1))) {
9365 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9367 insert_triple(state, state->global_pool, val);
9368 unuse_triple(RHS(ins, 1), ins);
9369 use_triple(val, ins);
9374 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9376 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9377 ulong_t left, right;
9378 left = read_const(state, ins, RHS(ins, 0));
9379 right = read_const(state, ins, RHS(ins, 1));
9380 mkconst(state, ins, left / right);
9382 else if (is_zero(RHS(ins, 0))) {
9383 mkconst(state, ins, 0);
9385 else if (is_zero(RHS(ins, 1))) {
9386 error(state, ins, "division by zero");
9388 else if (is_one(RHS(ins, 1))) {
9389 mkcopy(state, ins, RHS(ins, 0));
9391 else if (is_pow2(RHS(ins, 1))) {
9393 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9395 insert_triple(state, state->global_pool, val);
9396 unuse_triple(RHS(ins, 1), ins);
9397 use_triple(val, ins);
9402 static void simplify_smod(struct compile_state *state, struct triple *ins)
9404 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9406 left = read_const(state, ins, RHS(ins, 0));
9407 right = read_const(state, ins, RHS(ins, 1));
9408 mkconst(state, ins, left % right);
9410 else if (is_zero(RHS(ins, 0))) {
9411 mkconst(state, ins, 0);
9413 else if (is_zero(RHS(ins, 1))) {
9414 error(state, ins, "division by zero");
9416 else if (is_one(RHS(ins, 1))) {
9417 mkconst(state, ins, 0);
9419 else if (is_pow2(RHS(ins, 1))) {
9421 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9423 insert_triple(state, state->global_pool, val);
9424 unuse_triple(RHS(ins, 1), ins);
9425 use_triple(val, ins);
9430 static void simplify_umod(struct compile_state *state, struct triple *ins)
9432 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9433 ulong_t left, right;
9434 left = read_const(state, ins, RHS(ins, 0));
9435 right = read_const(state, ins, RHS(ins, 1));
9436 mkconst(state, ins, left % right);
9438 else if (is_zero(RHS(ins, 0))) {
9439 mkconst(state, ins, 0);
9441 else if (is_zero(RHS(ins, 1))) {
9442 error(state, ins, "division by zero");
9444 else if (is_one(RHS(ins, 1))) {
9445 mkconst(state, ins, 0);
9447 else if (is_pow2(RHS(ins, 1))) {
9449 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9451 insert_triple(state, state->global_pool, val);
9452 unuse_triple(RHS(ins, 1), ins);
9453 use_triple(val, ins);
9458 static void simplify_add(struct compile_state *state, struct triple *ins)
9460 /* start with the pointer on the left */
9461 if (is_pointer(RHS(ins, 1))) {
9464 RHS(ins, 0) = RHS(ins, 1);
9467 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9468 if (RHS(ins, 0)->op == OP_INTCONST) {
9469 ulong_t left, right;
9470 left = read_const(state, ins, RHS(ins, 0));
9471 right = read_const(state, ins, RHS(ins, 1));
9472 mkconst(state, ins, left + right);
9474 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9475 struct triple *sdecl;
9476 ulong_t left, right;
9477 sdecl = MISC(RHS(ins, 0), 0);
9478 left = RHS(ins, 0)->u.cval;
9479 right = RHS(ins, 1)->u.cval;
9480 mkaddr_const(state, ins, sdecl, left + right);
9483 internal_warning(state, ins, "Optimize me!");
9486 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9489 RHS(ins, 1) = RHS(ins, 0);
9494 static void simplify_sub(struct compile_state *state, struct triple *ins)
9496 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9497 if (RHS(ins, 0)->op == OP_INTCONST) {
9498 ulong_t left, right;
9499 left = read_const(state, ins, RHS(ins, 0));
9500 right = read_const(state, ins, RHS(ins, 1));
9501 mkconst(state, ins, left - right);
9503 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9504 struct triple *sdecl;
9505 ulong_t left, right;
9506 sdecl = MISC(RHS(ins, 0), 0);
9507 left = RHS(ins, 0)->u.cval;
9508 right = RHS(ins, 1)->u.cval;
9509 mkaddr_const(state, ins, sdecl, left - right);
9512 internal_warning(state, ins, "Optimize me!");
9517 static void simplify_sl(struct compile_state *state, struct triple *ins)
9519 if (is_simple_const(RHS(ins, 1))) {
9521 right = read_const(state, ins, RHS(ins, 1));
9522 if (right >= (size_of(state, ins->type))) {
9523 warning(state, ins, "left shift count >= width of type");
9526 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9527 ulong_t left, right;
9528 left = read_const(state, ins, RHS(ins, 0));
9529 right = read_const(state, ins, RHS(ins, 1));
9530 mkconst(state, ins, left << right);
9534 static void simplify_usr(struct compile_state *state, struct triple *ins)
9536 if (is_simple_const(RHS(ins, 1))) {
9538 right = read_const(state, ins, RHS(ins, 1));
9539 if (right >= (size_of(state, ins->type))) {
9540 warning(state, ins, "right shift count >= width of type");
9543 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9544 ulong_t left, right;
9545 left = read_const(state, ins, RHS(ins, 0));
9546 right = read_const(state, ins, RHS(ins, 1));
9547 mkconst(state, ins, left >> right);
9551 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9553 if (is_simple_const(RHS(ins, 1))) {
9555 right = read_const(state, ins, RHS(ins, 1));
9556 if (right >= (size_of(state, ins->type))) {
9557 warning(state, ins, "right shift count >= width of type");
9560 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9562 left = read_sconst(state, ins, RHS(ins, 0));
9563 right = read_sconst(state, ins, RHS(ins, 1));
9564 mkconst(state, ins, left >> right);
9568 static void simplify_and(struct compile_state *state, struct triple *ins)
9570 struct triple *left, *right;
9572 right = RHS(ins, 1);
9574 if (is_simple_const(left) && is_simple_const(right)) {
9576 lval = read_const(state, ins, left);
9577 rval = read_const(state, ins, right);
9578 mkconst(state, ins, lval & rval);
9580 else if (is_zero(right) || is_zero(left)) {
9581 mkconst(state, ins, 0);
9585 static void simplify_or(struct compile_state *state, struct triple *ins)
9587 struct triple *left, *right;
9589 right = RHS(ins, 1);
9591 if (is_simple_const(left) && is_simple_const(right)) {
9593 lval = read_const(state, ins, left);
9594 rval = read_const(state, ins, right);
9595 mkconst(state, ins, lval | rval);
9597 #if 0 /* I need to handle type mismatches here... */
9598 else if (is_zero(right)) {
9599 mkcopy(state, ins, left);
9601 else if (is_zero(left)) {
9602 mkcopy(state, ins, right);
9607 static void simplify_xor(struct compile_state *state, struct triple *ins)
9609 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9610 ulong_t left, right;
9611 left = read_const(state, ins, RHS(ins, 0));
9612 right = read_const(state, ins, RHS(ins, 1));
9613 mkconst(state, ins, left ^ right);
9617 static void simplify_pos(struct compile_state *state, struct triple *ins)
9619 if (is_const(RHS(ins, 0))) {
9620 mkconst(state, ins, RHS(ins, 0)->u.cval);
9623 mkcopy(state, ins, RHS(ins, 0));
9627 static void simplify_neg(struct compile_state *state, struct triple *ins)
9629 if (is_simple_const(RHS(ins, 0))) {
9631 left = read_const(state, ins, RHS(ins, 0));
9632 mkconst(state, ins, -left);
9634 else if (RHS(ins, 0)->op == OP_NEG) {
9635 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9639 static void simplify_invert(struct compile_state *state, struct triple *ins)
9641 if (is_simple_const(RHS(ins, 0))) {
9643 left = read_const(state, ins, RHS(ins, 0));
9644 mkconst(state, ins, ~left);
9648 static void simplify_eq(struct compile_state *state, struct triple *ins)
9650 struct triple *left, *right;
9652 right = RHS(ins, 1);
9654 if (is_const(left) && is_const(right)) {
9656 val = const_eq(state, ins, left, right);
9658 mkconst(state, ins, val == 1);
9661 else if (left == right) {
9662 mkconst(state, ins, 1);
9666 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9668 struct triple *left, *right;
9670 right = RHS(ins, 1);
9672 if (is_const(left) && is_const(right)) {
9674 val = const_eq(state, ins, left, right);
9676 mkconst(state, ins, val != 1);
9679 if (left == right) {
9680 mkconst(state, ins, 0);
9684 static void simplify_sless(struct compile_state *state, struct triple *ins)
9686 struct triple *left, *right;
9688 right = RHS(ins, 1);
9690 if (is_const(left) && is_const(right)) {
9692 val = const_scmp(state, ins, left, right);
9693 if ((val >= -1) && (val <= 1)) {
9694 mkconst(state, ins, val < 0);
9697 else if (left == right) {
9698 mkconst(state, ins, 0);
9702 static void simplify_uless(struct compile_state *state, struct triple *ins)
9704 struct triple *left, *right;
9706 right = RHS(ins, 1);
9708 if (is_const(left) && is_const(right)) {
9710 val = const_ucmp(state, ins, left, right);
9711 if ((val >= -1) && (val <= 1)) {
9712 mkconst(state, ins, val < 0);
9715 else if (is_zero(right)) {
9716 mkconst(state, ins, 0);
9718 else if (left == right) {
9719 mkconst(state, ins, 0);
9723 static void simplify_smore(struct compile_state *state, struct triple *ins)
9725 struct triple *left, *right;
9727 right = RHS(ins, 1);
9729 if (is_const(left) && is_const(right)) {
9731 val = const_scmp(state, ins, left, right);
9732 if ((val >= -1) && (val <= 1)) {
9733 mkconst(state, ins, val > 0);
9736 else if (left == right) {
9737 mkconst(state, ins, 0);
9741 static void simplify_umore(struct compile_state *state, struct triple *ins)
9743 struct triple *left, *right;
9745 right = RHS(ins, 1);
9747 if (is_const(left) && is_const(right)) {
9749 val = const_ucmp(state, ins, left, right);
9750 if ((val >= -1) && (val <= 1)) {
9751 mkconst(state, ins, val > 0);
9754 else if (is_zero(left)) {
9755 mkconst(state, ins, 0);
9757 else if (left == right) {
9758 mkconst(state, ins, 0);
9763 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9765 struct triple *left, *right;
9767 right = RHS(ins, 1);
9769 if (is_const(left) && is_const(right)) {
9771 val = const_scmp(state, ins, left, right);
9772 if ((val >= -1) && (val <= 1)) {
9773 mkconst(state, ins, val <= 0);
9776 else if (left == right) {
9777 mkconst(state, ins, 1);
9781 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9783 struct triple *left, *right;
9785 right = RHS(ins, 1);
9787 if (is_const(left) && is_const(right)) {
9789 val = const_ucmp(state, ins, left, right);
9790 if ((val >= -1) && (val <= 1)) {
9791 mkconst(state, ins, val <= 0);
9794 else if (is_zero(left)) {
9795 mkconst(state, ins, 1);
9797 else if (left == right) {
9798 mkconst(state, ins, 1);
9802 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9804 struct triple *left, *right;
9806 right = RHS(ins, 1);
9808 if (is_const(left) && is_const(right)) {
9810 val = const_scmp(state, ins, left, right);
9811 if ((val >= -1) && (val <= 1)) {
9812 mkconst(state, ins, val >= 0);
9815 else if (left == right) {
9816 mkconst(state, ins, 1);
9820 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9822 struct triple *left, *right;
9824 right = RHS(ins, 1);
9826 if (is_const(left) && is_const(right)) {
9828 val = const_ucmp(state, ins, left, right);
9829 if ((val >= -1) && (val <= 1)) {
9830 mkconst(state, ins, val >= 0);
9833 else if (is_zero(right)) {
9834 mkconst(state, ins, 1);
9836 else if (left == right) {
9837 mkconst(state, ins, 1);
9841 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9846 if (is_const(rhs)) {
9847 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9849 /* Otherwise if I am the only user... */
9850 else if ((rhs->use) &&
9851 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9853 /* Invert a boolean operation */
9855 case OP_LTRUE: rhs->op = OP_LFALSE; break;
9856 case OP_LFALSE: rhs->op = OP_LTRUE; break;
9857 case OP_EQ: rhs->op = OP_NOTEQ; break;
9858 case OP_NOTEQ: rhs->op = OP_EQ; break;
9859 case OP_SLESS: rhs->op = OP_SMOREEQ; break;
9860 case OP_ULESS: rhs->op = OP_UMOREEQ; break;
9861 case OP_SMORE: rhs->op = OP_SLESSEQ; break;
9862 case OP_UMORE: rhs->op = OP_ULESSEQ; break;
9863 case OP_SLESSEQ: rhs->op = OP_SMORE; break;
9864 case OP_ULESSEQ: rhs->op = OP_UMORE; break;
9865 case OP_SMOREEQ: rhs->op = OP_SLESS; break;
9866 case OP_UMOREEQ: rhs->op = OP_ULESS; break;
9872 mkcopy(state, ins, rhs);
9877 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9882 if (is_const(rhs)) {
9883 mkconst(state, ins, const_ltrue(state, ins, rhs));
9885 else switch(rhs->op) {
9886 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
9887 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
9888 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9889 mkcopy(state, ins, rhs);
9894 static void simplify_load(struct compile_state *state, struct triple *ins)
9896 struct triple *addr, *sdecl, *blob;
9898 /* If I am doing a load with a constant pointer from a constant
9899 * table get the value.
9902 if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
9903 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
9904 (blob->op == OP_BLOBCONST)) {
9905 unsigned char buffer[SIZEOF_WORD];
9906 size_t reg_size, mem_size;
9907 const char *src, *end;
9909 reg_size = reg_size_of(state, ins->type);
9910 if (reg_size > REG_SIZEOF_REG) {
9911 internal_error(state, ins, "load size greater than register");
9913 mem_size = size_of(state, ins->type);
9915 end += bits_to_bytes(size_of(state, sdecl->type));
9917 src += addr->u.cval;
9920 error(state, ins, "Load address out of bounds");
9923 memset(buffer, 0, sizeof(buffer));
9924 memcpy(buffer, src, bits_to_bytes(mem_size));
9927 case SIZEOF_I8: val = *((uint8_t *) buffer); break;
9928 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
9929 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
9930 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
9932 internal_error(state, ins, "mem_size: %d not handled",
9937 mkconst(state, ins, val);
9941 static void simplify_uextract(struct compile_state *state, struct triple *ins)
9943 if (is_simple_const(RHS(ins, 0))) {
9946 val = read_const(state, ins, RHS(ins, 0));
9948 mask <<= ins->u.bitfield.size;
9950 val >>= ins->u.bitfield.offset;
9952 mkconst(state, ins, val);
9956 static void simplify_sextract(struct compile_state *state, struct triple *ins)
9958 if (is_simple_const(RHS(ins, 0))) {
9962 val = read_const(state, ins, RHS(ins, 0));
9964 mask <<= ins->u.bitfield.size;
9966 val >>= ins->u.bitfield.offset;
9968 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
9970 sval >>= (SIZEOF_LONG - ins->u.bitfield.size);
9971 mkconst(state, ins, sval);
9975 static void simplify_deposit(struct compile_state *state, struct triple *ins)
9977 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9980 targ = read_const(state, ins, RHS(ins, 0));
9981 val = read_const(state, ins, RHS(ins, 1));
9983 mask <<= ins->u.bitfield.size;
9985 mask <<= ins->u.bitfield.offset;
9987 val <<= ins->u.bitfield.offset;
9990 mkconst(state, ins, targ);
9994 static void simplify_copy(struct compile_state *state, struct triple *ins)
9996 struct triple *right;
9997 right = RHS(ins, 0);
9998 if (is_subset_type(ins->type, right->type)) {
9999 ins->type = right->type;
10001 if (equiv_types(ins->type, right->type)) {
10002 ins->op = OP_COPY;/* I don't need to convert if the types match */
10004 if (ins->op == OP_COPY) {
10005 internal_error(state, ins, "type mismatch on copy");
10008 if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
10009 struct triple *sdecl;
10011 sdecl = MISC(right, 0);
10012 offset = right->u.cval;
10013 mkaddr_const(state, ins, sdecl, offset);
10015 else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
10016 switch(right->op) {
10020 left = read_const(state, ins, right);
10021 /* Ensure I have not overflowed the destination. */
10022 if (size_of(state, right->type) > size_of(state, ins->type)) {
10025 mask <<= size_of(state, ins->type);
10029 /* Ensure I am properly sign extended */
10030 if (size_of(state, right->type) < size_of(state, ins->type) &&
10031 is_signed(right->type)) {
10034 shift = SIZEOF_LONG - size_of(state, right->type);
10040 mkconst(state, ins, left);
10044 internal_error(state, ins, "uknown constant");
10050 static int phi_present(struct block *block)
10052 struct triple *ptr;
10056 ptr = block->first;
10058 if (ptr->op == OP_PHI) {
10062 } while(ptr != block->last);
10066 static int phi_dependency(struct block *block)
10068 /* A block has a phi dependency if a phi function
10069 * depends on that block to exist, and makes a block
10070 * that is otherwise useless unsafe to remove.
10073 struct block_set *edge;
10074 for(edge = block->edges; edge; edge = edge->next) {
10075 if (phi_present(edge->member)) {
10083 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10085 struct triple *targ;
10086 targ = TARG(ins, 0);
10087 /* During scc_transform temporary triples are allocated that
10088 * loop back onto themselves. If I see one don't advance the
10091 while(triple_is_structural(state, targ) &&
10092 (targ->next != targ) && (targ->next != state->first)) {
10099 static void simplify_branch(struct compile_state *state, struct triple *ins)
10101 int simplified, loops;
10102 if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10103 internal_error(state, ins, "not branch");
10105 if (ins->use != 0) {
10106 internal_error(state, ins, "branch use");
10108 /* The challenge here with simplify branch is that I need to
10109 * make modifications to the control flow graph as well
10110 * as to the branch instruction itself. That is handled
10111 * by rebuilding the basic blocks after simplify all is called.
10114 /* If we have a branch to an unconditional branch update
10115 * our target. But watch out for dependencies from phi
10117 * Also only do this a limited number of times so
10118 * we don't get into an infinite loop.
10122 struct triple *targ;
10124 targ = branch_target(state, ins);
10125 if ((targ != ins) && (targ->op == OP_BRANCH) &&
10126 !phi_dependency(targ->u.block))
10128 unuse_triple(TARG(ins, 0), ins);
10129 TARG(ins, 0) = TARG(targ, 0);
10130 use_triple(TARG(ins, 0), ins);
10133 } while(simplified && (++loops < 20));
10135 /* If we have a conditional branch with a constant condition
10136 * make it an unconditional branch.
10138 if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10139 struct triple *targ;
10141 value = read_const(state, ins, RHS(ins, 0));
10142 unuse_triple(RHS(ins, 0), ins);
10143 targ = TARG(ins, 0);
10146 ins->op = OP_BRANCH;
10148 unuse_triple(ins->next, ins);
10149 TARG(ins, 0) = targ;
10152 unuse_triple(targ, ins);
10153 TARG(ins, 0) = ins->next;
10157 /* If we have a branch to the next instruction,
10160 if (TARG(ins, 0) == ins->next) {
10161 unuse_triple(TARG(ins, 0), ins);
10162 if (ins->op == OP_CBRANCH) {
10163 unuse_triple(RHS(ins, 0), ins);
10164 unuse_triple(ins->next, ins);
10172 internal_error(state, ins, "noop use != 0");
10177 static void simplify_label(struct compile_state *state, struct triple *ins)
10179 /* Ignore volatile labels */
10180 if (!triple_is_pure(state, ins, ins->id)) {
10183 if (ins->use == 0) {
10186 else if (ins->prev->op == OP_LABEL) {
10187 /* In general it is not safe to merge one label that
10188 * imediately follows another. The problem is that the empty
10189 * looking block may have phi functions that depend on it.
10191 if (!phi_dependency(ins->prev->u.block)) {
10192 struct triple_set *user, *next;
10194 for(user = ins->use; user; user = next) {
10195 struct triple *use, **expr;
10197 use = user->member;
10198 expr = triple_targ(state, use, 0);
10199 for(;expr; expr = triple_targ(state, use, expr)) {
10200 if (*expr == ins) {
10202 unuse_triple(ins, use);
10203 use_triple(ins->prev, use);
10209 internal_error(state, ins, "noop use != 0");
10215 static void simplify_phi(struct compile_state *state, struct triple *ins)
10217 struct triple **slot;
10218 struct triple *value;
10221 slot = &RHS(ins, 0);
10226 /* See if all of the rhs members of a phi have the same value */
10227 if (slot[0] && is_simple_const(slot[0])) {
10228 cvalue = read_const(state, ins, slot[0]);
10229 for(i = 1; i < zrhs; i++) {
10231 !is_simple_const(slot[i]) ||
10232 !equiv_types(slot[0]->type, slot[i]->type) ||
10233 (cvalue != read_const(state, ins, slot[i]))) {
10238 mkconst(state, ins, cvalue);
10243 /* See if all of rhs members of a phi are the same */
10245 for(i = 1; i < zrhs; i++) {
10246 if (slot[i] != value) {
10251 /* If the phi has a single value just copy it */
10252 if (!is_subset_type(ins->type, value->type)) {
10253 internal_error(state, ins, "bad input type to phi");
10255 /* Make the types match */
10256 if (!equiv_types(ins->type, value->type)) {
10257 ins->type = value->type;
10259 /* Now make the actual copy */
10260 mkcopy(state, ins, value);
10266 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10268 if (is_simple_const(RHS(ins, 0))) {
10270 left = read_const(state, ins, RHS(ins, 0));
10271 mkconst(state, ins, bsf(left));
10275 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10277 if (is_simple_const(RHS(ins, 0))) {
10279 left = read_const(state, ins, RHS(ins, 0));
10280 mkconst(state, ins, bsr(left));
10285 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10286 static const struct simplify_table {
10288 unsigned long flag;
10289 } table_simplify[] = {
10290 #define simplify_sdivt simplify_noop
10291 #define simplify_udivt simplify_noop
10292 #define simplify_piece simplify_noop
10294 [OP_SDIVT ] = { simplify_sdivt, COMPILER_SIMPLIFY_ARITH },
10295 [OP_UDIVT ] = { simplify_udivt, COMPILER_SIMPLIFY_ARITH },
10296 [OP_SMUL ] = { simplify_smul, COMPILER_SIMPLIFY_ARITH },
10297 [OP_UMUL ] = { simplify_umul, COMPILER_SIMPLIFY_ARITH },
10298 [OP_SDIV ] = { simplify_sdiv, COMPILER_SIMPLIFY_ARITH },
10299 [OP_UDIV ] = { simplify_udiv, COMPILER_SIMPLIFY_ARITH },
10300 [OP_SMOD ] = { simplify_smod, COMPILER_SIMPLIFY_ARITH },
10301 [OP_UMOD ] = { simplify_umod, COMPILER_SIMPLIFY_ARITH },
10302 [OP_ADD ] = { simplify_add, COMPILER_SIMPLIFY_ARITH },
10303 [OP_SUB ] = { simplify_sub, COMPILER_SIMPLIFY_ARITH },
10304 [OP_SL ] = { simplify_sl, COMPILER_SIMPLIFY_SHIFT },
10305 [OP_USR ] = { simplify_usr, COMPILER_SIMPLIFY_SHIFT },
10306 [OP_SSR ] = { simplify_ssr, COMPILER_SIMPLIFY_SHIFT },
10307 [OP_AND ] = { simplify_and, COMPILER_SIMPLIFY_BITWISE },
10308 [OP_XOR ] = { simplify_xor, COMPILER_SIMPLIFY_BITWISE },
10309 [OP_OR ] = { simplify_or, COMPILER_SIMPLIFY_BITWISE },
10310 [OP_POS ] = { simplify_pos, COMPILER_SIMPLIFY_ARITH },
10311 [OP_NEG ] = { simplify_neg, COMPILER_SIMPLIFY_ARITH },
10312 [OP_INVERT ] = { simplify_invert, COMPILER_SIMPLIFY_BITWISE },
10314 [OP_EQ ] = { simplify_eq, COMPILER_SIMPLIFY_LOGICAL },
10315 [OP_NOTEQ ] = { simplify_noteq, COMPILER_SIMPLIFY_LOGICAL },
10316 [OP_SLESS ] = { simplify_sless, COMPILER_SIMPLIFY_LOGICAL },
10317 [OP_ULESS ] = { simplify_uless, COMPILER_SIMPLIFY_LOGICAL },
10318 [OP_SMORE ] = { simplify_smore, COMPILER_SIMPLIFY_LOGICAL },
10319 [OP_UMORE ] = { simplify_umore, COMPILER_SIMPLIFY_LOGICAL },
10320 [OP_SLESSEQ ] = { simplify_slesseq, COMPILER_SIMPLIFY_LOGICAL },
10321 [OP_ULESSEQ ] = { simplify_ulesseq, COMPILER_SIMPLIFY_LOGICAL },
10322 [OP_SMOREEQ ] = { simplify_smoreeq, COMPILER_SIMPLIFY_LOGICAL },
10323 [OP_UMOREEQ ] = { simplify_umoreeq, COMPILER_SIMPLIFY_LOGICAL },
10324 [OP_LFALSE ] = { simplify_lfalse, COMPILER_SIMPLIFY_LOGICAL },
10325 [OP_LTRUE ] = { simplify_ltrue, COMPILER_SIMPLIFY_LOGICAL },
10327 [OP_LOAD ] = { simplify_load, COMPILER_SIMPLIFY_OP },
10328 [OP_STORE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10330 [OP_UEXTRACT ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10331 [OP_SEXTRACT ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10332 [OP_DEPOSIT ] = { simplify_deposit, COMPILER_SIMPLIFY_BITFIELD },
10334 [OP_NOOP ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10336 [OP_INTCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10337 [OP_BLOBCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10338 [OP_ADDRCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10339 [OP_UNKNOWNVAL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10341 [OP_WRITE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10342 [OP_READ ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10343 [OP_COPY ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10344 [OP_CONVERT ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10345 [OP_PIECE ] = { simplify_piece, COMPILER_SIMPLIFY_OP },
10346 [OP_ASM ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10348 [OP_DOT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10349 [OP_INDEX ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10351 [OP_LIST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10352 [OP_BRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10353 [OP_CBRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10354 [OP_CALL ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10355 [OP_RET ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10356 [OP_LABEL ] = { simplify_label, COMPILER_SIMPLIFY_LABEL },
10357 [OP_ADECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10358 [OP_SDECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10359 [OP_PHI ] = { simplify_phi, COMPILER_SIMPLIFY_PHI },
10361 [OP_INB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10362 [OP_INW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10363 [OP_INL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10364 [OP_OUTB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10365 [OP_OUTW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10366 [OP_OUTL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10367 [OP_BSF ] = { simplify_bsf, COMPILER_SIMPLIFY_OP },
10368 [OP_BSR ] = { simplify_bsr, COMPILER_SIMPLIFY_OP },
10369 [OP_RDMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10370 [OP_WRMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10371 [OP_HLT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10374 static inline void debug_simplify(struct compile_state *state,
10375 simplify_t do_simplify, struct triple *ins)
10377 #if DEBUG_SIMPLIFY_HIRES
10378 if (state->functions_joined && (do_simplify != simplify_noop)) {
10379 /* High resolution debugging mode */
10380 fprintf(state->dbgout, "simplifing: ");
10381 display_triple(state->dbgout, ins);
10384 do_simplify(state, ins);
10385 #if DEBUG_SIMPLIFY_HIRES
10386 if (state->functions_joined && (do_simplify != simplify_noop)) {
10387 /* High resolution debugging mode */
10388 fprintf(state->dbgout, "simplified: ");
10389 display_triple(state->dbgout, ins);
10393 static void simplify(struct compile_state *state, struct triple *ins)
10396 simplify_t do_simplify;
10397 if (ins == &unknown_triple) {
10398 internal_error(state, ins, "simplifying the unknown triple?");
10403 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10407 do_simplify = table_simplify[op].func;
10410 !(state->compiler->flags & table_simplify[op].flag)) {
10411 do_simplify = simplify_noop;
10413 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10414 do_simplify = simplify_noop;
10417 if (!do_simplify) {
10418 internal_error(state, ins, "cannot simplify op: %d %s",
10422 debug_simplify(state, do_simplify, ins);
10423 } while(ins->op != op);
10426 static void rebuild_ssa_form(struct compile_state *state);
10428 static void simplify_all(struct compile_state *state)
10430 struct triple *ins, *first;
10431 if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10434 first = state->first;
10437 simplify(state, ins);
10439 } while(ins != first->prev);
10442 simplify(state, ins);
10444 }while(ins != first);
10445 rebuild_ssa_form(state);
10447 print_blocks(state, __func__, state->dbgout);
10452 * ============================
10455 static void register_builtin_function(struct compile_state *state,
10456 const char *name, int op, struct type *rtype, ...)
10458 struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10459 struct triple *def, *result, *work, *first, *retvar, *ret;
10460 struct hash_entry *ident;
10461 struct file_state file;
10467 /* Dummy file state to get debug handling right */
10468 memset(&file, 0, sizeof(file));
10469 file.basename = "<built-in>";
10471 file.report_line = 1;
10472 file.report_name = file.basename;
10473 file.prev = state->file;
10474 state->file = &file;
10475 state->function = name;
10477 /* Find the Parameter count */
10478 valid_op(state, op);
10479 parameters = table_ops[op].rhs;
10480 if (parameters < 0 ) {
10481 internal_error(state, 0, "Invalid builtin parameter count");
10484 /* Find the function type */
10485 ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10486 ftype->elements = parameters;
10487 next = &ftype->right;
10488 va_start(args, rtype);
10489 for(i = 0; i < parameters; i++) {
10490 atype = va_arg(args, struct type *);
10494 *next = new_type(TYPE_PRODUCT, *next, atype);
10495 next = &((*next)->right);
10499 *next = &void_type;
10503 /* Get the initial closure type */
10504 ctype = new_type(TYPE_JOIN, &void_type, 0);
10505 ctype->elements = 1;
10507 /* Get the return type */
10508 crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10509 crtype->elements = 2;
10511 /* Generate the needed triples */
10512 def = triple(state, OP_LIST, ftype, 0, 0);
10513 first = label(state);
10514 RHS(def, 0) = first;
10515 result = flatten(state, first, variable(state, crtype));
10516 retvar = flatten(state, first, variable(state, &void_ptr_type));
10517 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10519 /* Now string them together */
10520 param = ftype->right;
10521 for(i = 0; i < parameters; i++) {
10522 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10523 atype = param->left;
10527 flatten(state, first, variable(state, atype));
10528 param = param->right;
10530 work = new_triple(state, op, rtype, -1, parameters);
10531 generate_lhs_pieces(state, work);
10532 for(i = 0; i < parameters; i++) {
10533 RHS(work, i) = read_expr(state, farg(state, def, i));
10535 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10536 work = write_expr(state, deref_index(state, result, 1), work);
10538 work = flatten(state, first, work);
10539 flatten(state, first, label(state));
10540 ret = flatten(state, first, ret);
10541 name_len = strlen(name);
10542 ident = lookup(state, name, name_len);
10543 ftype->type_ident = ident;
10544 symbol(state, ident, &ident->sym_ident, def, ftype);
10546 state->file = file.prev;
10547 state->function = 0;
10548 state->main_function = 0;
10550 if (!state->functions) {
10551 state->functions = def;
10553 insert_triple(state, state->functions, def);
10555 if (state->compiler->debug & DEBUG_INLINE) {
10556 FILE *fp = state->dbgout;
10559 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10560 display_func(state, fp, def);
10561 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10565 static struct type *partial_struct(struct compile_state *state,
10566 const char *field_name, struct type *type, struct type *rest)
10568 struct hash_entry *field_ident;
10569 struct type *result;
10570 int field_name_len;
10572 field_name_len = strlen(field_name);
10573 field_ident = lookup(state, field_name, field_name_len);
10575 result = clone_type(0, type);
10576 result->field_ident = field_ident;
10579 result = new_type(TYPE_PRODUCT, result, rest);
10584 static struct type *register_builtin_type(struct compile_state *state,
10585 const char *name, struct type *type)
10587 struct hash_entry *ident;
10590 name_len = strlen(name);
10591 ident = lookup(state, name, name_len);
10593 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10594 ulong_t elements = 0;
10595 struct type *field;
10596 type = new_type(TYPE_STRUCT, type, 0);
10597 field = type->left;
10598 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10600 field = field->right;
10603 symbol(state, ident, &ident->sym_tag, 0, type);
10604 type->type_ident = ident;
10605 type->elements = elements;
10607 symbol(state, ident, &ident->sym_ident, 0, type);
10608 ident->tok = TOK_TYPE_NAME;
10613 static void register_builtins(struct compile_state *state)
10615 struct type *div_type, *ldiv_type;
10616 struct type *udiv_type, *uldiv_type;
10617 struct type *msr_type;
10619 div_type = register_builtin_type(state, "__builtin_div_t",
10620 partial_struct(state, "quot", &int_type,
10621 partial_struct(state, "rem", &int_type, 0)));
10622 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10623 partial_struct(state, "quot", &long_type,
10624 partial_struct(state, "rem", &long_type, 0)));
10625 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10626 partial_struct(state, "quot", &uint_type,
10627 partial_struct(state, "rem", &uint_type, 0)));
10628 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10629 partial_struct(state, "quot", &ulong_type,
10630 partial_struct(state, "rem", &ulong_type, 0)));
10632 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
10633 &int_type, &int_type);
10634 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
10635 &long_type, &long_type);
10636 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
10637 &uint_type, &uint_type);
10638 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10639 &ulong_type, &ulong_type);
10641 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
10643 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10645 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
10648 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
10649 &uchar_type, &ushort_type);
10650 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
10651 &ushort_type, &ushort_type);
10652 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
10653 &uint_type, &ushort_type);
10655 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
10657 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
10660 msr_type = register_builtin_type(state, "__builtin_msr_t",
10661 partial_struct(state, "lo", &ulong_type,
10662 partial_struct(state, "hi", &ulong_type, 0)));
10664 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10666 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10667 &ulong_type, &ulong_type, &ulong_type);
10669 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
10673 static struct type *declarator(
10674 struct compile_state *state, struct type *type,
10675 struct hash_entry **ident, int need_ident);
10676 static void decl(struct compile_state *state, struct triple *first);
10677 static struct type *specifier_qualifier_list(struct compile_state *state);
10678 #if DEBUG_ROMCC_WARNING
10679 static int isdecl_specifier(int tok);
10681 static struct type *decl_specifiers(struct compile_state *state);
10682 static int istype(int tok);
10683 static struct triple *expr(struct compile_state *state);
10684 static struct triple *assignment_expr(struct compile_state *state);
10685 static struct type *type_name(struct compile_state *state);
10686 static void statement(struct compile_state *state, struct triple *first);
10688 static struct triple *call_expr(
10689 struct compile_state *state, struct triple *func)
10691 struct triple *def;
10692 struct type *param, *type;
10693 ulong_t pvals, index;
10695 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10696 error(state, 0, "Called object is not a function");
10698 if (func->op != OP_LIST) {
10699 internal_error(state, 0, "improper function");
10701 eat(state, TOK_LPAREN);
10702 /* Find the return type without any specifiers */
10703 type = clone_type(0, func->type->left);
10704 /* Count the number of rhs entries for OP_FCALL */
10705 param = func->type->right;
10707 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10709 param = param->right;
10711 if ((param->type & TYPE_MASK) != TYPE_VOID) {
10714 def = new_triple(state, OP_FCALL, type, -1, pvals);
10715 MISC(def, 0) = func;
10717 param = func->type->right;
10718 for(index = 0; index < pvals; index++) {
10719 struct triple *val;
10720 struct type *arg_type;
10721 val = read_expr(state, assignment_expr(state));
10723 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10724 arg_type = param->left;
10726 write_compatible(state, arg_type, val->type);
10727 RHS(def, index) = val;
10728 if (index != (pvals - 1)) {
10729 eat(state, TOK_COMMA);
10730 param = param->right;
10733 eat(state, TOK_RPAREN);
10738 static struct triple *character_constant(struct compile_state *state)
10740 struct triple *def;
10742 const signed char *str, *end;
10745 tk = eat(state, TOK_LIT_CHAR);
10746 str = (signed char *)tk->val.str + 1;
10747 str_len = tk->str_len - 2;
10748 if (str_len <= 0) {
10749 error(state, 0, "empty character constant");
10751 end = str + str_len;
10752 c = char_value(state, &str, end);
10754 error(state, 0, "multibyte character constant not supported");
10756 def = int_const(state, &char_type, (ulong_t)((long_t)c));
10760 static struct triple *string_constant(struct compile_state *state)
10762 struct triple *def;
10765 const signed char *str, *end;
10766 signed char *buf, *ptr;
10770 type = new_type(TYPE_ARRAY, &char_type, 0);
10771 type->elements = 0;
10772 /* The while loop handles string concatenation */
10774 tk = eat(state, TOK_LIT_STRING);
10775 str = (signed char *)tk->val.str + 1;
10776 str_len = tk->str_len - 2;
10778 error(state, 0, "negative string constant length");
10780 /* ignore empty string tokens */
10781 if ('"' == *str && 0 == str[1])
10783 end = str + str_len;
10785 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10786 memcpy(buf, ptr, type->elements);
10787 ptr = buf + type->elements;
10789 *ptr++ = char_value(state, &str, end);
10790 } while(str < end);
10791 type->elements = ptr - buf;
10792 } while(peek(state) == TOK_LIT_STRING);
10794 type->elements += 1;
10795 def = triple(state, OP_BLOBCONST, type, 0, 0);
10802 static struct triple *integer_constant(struct compile_state *state)
10804 struct triple *def;
10811 tk = eat(state, TOK_LIT_INT);
10813 decimal = (tk->val.str[0] != '0');
10814 val = strtoul(tk->val.str, &end, 0);
10815 if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10816 error(state, 0, "Integer constant to large");
10819 if ((*end == 'u') || (*end == 'U')) {
10823 if ((*end == 'l') || (*end == 'L')) {
10827 if ((*end == 'u') || (*end == 'U')) {
10832 error(state, 0, "Junk at end of integer constant");
10835 type = &ulong_type;
10839 if (!decimal && (val > LONG_T_MAX)) {
10840 type = &ulong_type;
10845 if (val > UINT_T_MAX) {
10846 type = &ulong_type;
10851 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10854 else if (!decimal && (val > LONG_T_MAX)) {
10855 type = &ulong_type;
10857 else if (val > INT_T_MAX) {
10861 def = int_const(state, type, val);
10865 static struct triple *primary_expr(struct compile_state *state)
10867 struct triple *def;
10873 struct hash_entry *ident;
10874 /* Here ident is either:
10878 ident = eat(state, TOK_IDENT)->ident;
10879 if (!ident->sym_ident) {
10880 error(state, 0, "%s undeclared", ident->name);
10882 def = ident->sym_ident->def;
10885 case TOK_ENUM_CONST:
10887 struct hash_entry *ident;
10888 /* Here ident is an enumeration constant */
10889 ident = eat(state, TOK_ENUM_CONST)->ident;
10890 if (!ident->sym_ident) {
10891 error(state, 0, "%s undeclared", ident->name);
10893 def = ident->sym_ident->def;
10898 struct hash_entry *ident;
10899 ident = eat(state, TOK_MIDENT)->ident;
10900 warning(state, 0, "Replacing undefined macro: %s with 0",
10902 def = int_const(state, &int_type, 0);
10906 eat(state, TOK_LPAREN);
10908 eat(state, TOK_RPAREN);
10911 def = integer_constant(state);
10913 case TOK_LIT_FLOAT:
10914 eat(state, TOK_LIT_FLOAT);
10915 error(state, 0, "Floating point constants not supported");
10920 def = character_constant(state);
10922 case TOK_LIT_STRING:
10923 def = string_constant(state);
10927 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
10932 static struct triple *postfix_expr(struct compile_state *state)
10934 struct triple *def;
10936 def = primary_expr(state);
10938 struct triple *left;
10942 switch((tok = peek(state))) {
10944 eat(state, TOK_LBRACKET);
10945 def = mk_subscript_expr(state, left, expr(state));
10946 eat(state, TOK_RBRACKET);
10949 def = call_expr(state, def);
10953 struct hash_entry *field;
10954 eat(state, TOK_DOT);
10955 field = eat(state, TOK_IDENT)->ident;
10956 def = deref_field(state, def, field);
10961 struct hash_entry *field;
10962 eat(state, TOK_ARROW);
10963 field = eat(state, TOK_IDENT)->ident;
10964 def = mk_deref_expr(state, read_expr(state, def));
10965 def = deref_field(state, def, field);
10969 eat(state, TOK_PLUSPLUS);
10970 def = mk_post_inc_expr(state, left);
10972 case TOK_MINUSMINUS:
10973 eat(state, TOK_MINUSMINUS);
10974 def = mk_post_dec_expr(state, left);
10984 static struct triple *cast_expr(struct compile_state *state);
10986 static struct triple *unary_expr(struct compile_state *state)
10988 struct triple *def, *right;
10990 switch((tok = peek(state))) {
10992 eat(state, TOK_PLUSPLUS);
10993 def = mk_pre_inc_expr(state, unary_expr(state));
10995 case TOK_MINUSMINUS:
10996 eat(state, TOK_MINUSMINUS);
10997 def = mk_pre_dec_expr(state, unary_expr(state));
11000 eat(state, TOK_AND);
11001 def = mk_addr_expr(state, cast_expr(state), 0);
11004 eat(state, TOK_STAR);
11005 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
11008 eat(state, TOK_PLUS);
11009 right = read_expr(state, cast_expr(state));
11010 arithmetic(state, right);
11011 def = integral_promotion(state, right);
11014 eat(state, TOK_MINUS);
11015 right = read_expr(state, cast_expr(state));
11016 arithmetic(state, right);
11017 def = integral_promotion(state, right);
11018 def = triple(state, OP_NEG, def->type, def, 0);
11021 eat(state, TOK_TILDE);
11022 right = read_expr(state, cast_expr(state));
11023 integral(state, right);
11024 def = integral_promotion(state, right);
11025 def = triple(state, OP_INVERT, def->type, def, 0);
11028 eat(state, TOK_BANG);
11029 right = read_expr(state, cast_expr(state));
11030 bool(state, right);
11031 def = lfalse_expr(state, right);
11037 eat(state, TOK_SIZEOF);
11038 tok1 = peek(state);
11039 tok2 = peek2(state);
11040 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11041 eat(state, TOK_LPAREN);
11042 type = type_name(state);
11043 eat(state, TOK_RPAREN);
11046 struct triple *expr;
11047 expr = unary_expr(state);
11049 release_expr(state, expr);
11051 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11058 eat(state, TOK_ALIGNOF);
11059 tok1 = peek(state);
11060 tok2 = peek2(state);
11061 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11062 eat(state, TOK_LPAREN);
11063 type = type_name(state);
11064 eat(state, TOK_RPAREN);
11067 struct triple *expr;
11068 expr = unary_expr(state);
11070 release_expr(state, expr);
11072 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11077 /* We only come here if we are called from the preprocessor */
11078 struct hash_entry *ident;
11080 eat(state, TOK_MDEFINED);
11082 if (pp_peek(state) == TOK_LPAREN) {
11083 pp_eat(state, TOK_LPAREN);
11086 ident = pp_eat(state, TOK_MIDENT)->ident;
11088 eat(state, TOK_RPAREN);
11090 def = int_const(state, &int_type, ident->sym_define != 0);
11094 def = postfix_expr(state);
11100 static struct triple *cast_expr(struct compile_state *state)
11102 struct triple *def;
11104 tok1 = peek(state);
11105 tok2 = peek2(state);
11106 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11108 eat(state, TOK_LPAREN);
11109 type = type_name(state);
11110 eat(state, TOK_RPAREN);
11111 def = mk_cast_expr(state, type, cast_expr(state));
11114 def = unary_expr(state);
11119 static struct triple *mult_expr(struct compile_state *state)
11121 struct triple *def;
11123 def = cast_expr(state);
11125 struct triple *left, *right;
11126 struct type *result_type;
11134 left = read_expr(state, def);
11135 arithmetic(state, left);
11139 right = read_expr(state, cast_expr(state));
11140 arithmetic(state, right);
11142 result_type = arithmetic_result(state, left, right);
11143 sign = is_signed(result_type);
11146 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11147 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
11148 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
11150 def = triple(state, op, result_type, left, right);
11160 static struct triple *add_expr(struct compile_state *state)
11162 struct triple *def;
11164 def = mult_expr(state);
11167 switch( peek(state)) {
11169 eat(state, TOK_PLUS);
11170 def = mk_add_expr(state, def, mult_expr(state));
11173 eat(state, TOK_MINUS);
11174 def = mk_sub_expr(state, def, mult_expr(state));
11184 static struct triple *shift_expr(struct compile_state *state)
11186 struct triple *def;
11188 def = add_expr(state);
11190 struct triple *left, *right;
11193 switch((tok = peek(state))) {
11196 left = read_expr(state, def);
11197 integral(state, left);
11198 left = integral_promotion(state, left);
11202 right = read_expr(state, add_expr(state));
11203 integral(state, right);
11204 right = integral_promotion(state, right);
11206 op = (tok == TOK_SL)? OP_SL :
11207 is_signed(left->type)? OP_SSR: OP_USR;
11209 def = triple(state, op, left->type, left, right);
11219 static struct triple *relational_expr(struct compile_state *state)
11221 #if DEBUG_ROMCC_WARNINGS
11222 #warning "Extend relational exprs to work on more than arithmetic types"
11224 struct triple *def;
11226 def = shift_expr(state);
11228 struct triple *left, *right;
11229 struct type *arg_type;
11232 switch((tok = peek(state))) {
11237 left = read_expr(state, def);
11238 arithmetic(state, left);
11242 right = read_expr(state, shift_expr(state));
11243 arithmetic(state, right);
11245 arg_type = arithmetic_result(state, left, right);
11246 sign = is_signed(arg_type);
11249 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
11250 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
11251 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11252 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11254 def = triple(state, op, &int_type, left, right);
11264 static struct triple *equality_expr(struct compile_state *state)
11266 #if DEBUG_ROMCC_WARNINGS
11267 #warning "Extend equality exprs to work on more than arithmetic types"
11269 struct triple *def;
11271 def = relational_expr(state);
11273 struct triple *left, *right;
11276 switch((tok = peek(state))) {
11279 left = read_expr(state, def);
11280 arithmetic(state, left);
11282 right = read_expr(state, relational_expr(state));
11283 arithmetic(state, right);
11284 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11285 def = triple(state, op, &int_type, left, right);
11295 static struct triple *and_expr(struct compile_state *state)
11297 struct triple *def;
11298 def = equality_expr(state);
11299 while(peek(state) == TOK_AND) {
11300 struct triple *left, *right;
11301 struct type *result_type;
11302 left = read_expr(state, def);
11303 integral(state, left);
11304 eat(state, TOK_AND);
11305 right = read_expr(state, equality_expr(state));
11306 integral(state, right);
11307 result_type = arithmetic_result(state, left, right);
11308 def = triple(state, OP_AND, result_type, left, right);
11313 static struct triple *xor_expr(struct compile_state *state)
11315 struct triple *def;
11316 def = and_expr(state);
11317 while(peek(state) == TOK_XOR) {
11318 struct triple *left, *right;
11319 struct type *result_type;
11320 left = read_expr(state, def);
11321 integral(state, left);
11322 eat(state, TOK_XOR);
11323 right = read_expr(state, and_expr(state));
11324 integral(state, right);
11325 result_type = arithmetic_result(state, left, right);
11326 def = triple(state, OP_XOR, result_type, left, right);
11331 static struct triple *or_expr(struct compile_state *state)
11333 struct triple *def;
11334 def = xor_expr(state);
11335 while(peek(state) == TOK_OR) {
11336 struct triple *left, *right;
11337 struct type *result_type;
11338 left = read_expr(state, def);
11339 integral(state, left);
11340 eat(state, TOK_OR);
11341 right = read_expr(state, xor_expr(state));
11342 integral(state, right);
11343 result_type = arithmetic_result(state, left, right);
11344 def = triple(state, OP_OR, result_type, left, right);
11349 static struct triple *land_expr(struct compile_state *state)
11351 struct triple *def;
11352 def = or_expr(state);
11353 while(peek(state) == TOK_LOGAND) {
11354 struct triple *left, *right;
11355 left = read_expr(state, def);
11357 eat(state, TOK_LOGAND);
11358 right = read_expr(state, or_expr(state));
11359 bool(state, right);
11361 def = mkland_expr(state,
11362 ltrue_expr(state, left),
11363 ltrue_expr(state, right));
11368 static struct triple *lor_expr(struct compile_state *state)
11370 struct triple *def;
11371 def = land_expr(state);
11372 while(peek(state) == TOK_LOGOR) {
11373 struct triple *left, *right;
11374 left = read_expr(state, def);
11376 eat(state, TOK_LOGOR);
11377 right = read_expr(state, land_expr(state));
11378 bool(state, right);
11380 def = mklor_expr(state,
11381 ltrue_expr(state, left),
11382 ltrue_expr(state, right));
11387 static struct triple *conditional_expr(struct compile_state *state)
11389 struct triple *def;
11390 def = lor_expr(state);
11391 if (peek(state) == TOK_QUEST) {
11392 struct triple *test, *left, *right;
11394 test = ltrue_expr(state, read_expr(state, def));
11395 eat(state, TOK_QUEST);
11396 left = read_expr(state, expr(state));
11397 eat(state, TOK_COLON);
11398 right = read_expr(state, conditional_expr(state));
11400 def = mkcond_expr(state, test, left, right);
11406 struct triple *val;
11410 static void set_cv(struct compile_state *state, struct cv_triple *cv,
11411 struct triple *dest, struct triple *val)
11413 if (cv[dest->id].val) {
11414 free_triple(state, cv[dest->id].val);
11416 cv[dest->id].val = val;
11418 static struct triple *get_cv(struct compile_state *state, struct cv_triple *cv,
11419 struct triple *src)
11421 return cv[src->id].val;
11424 static struct triple *eval_const_expr(
11425 struct compile_state *state, struct triple *expr)
11427 struct triple *def;
11428 if (is_const(expr)) {
11432 /* If we don't start out as a constant simplify into one */
11433 struct triple *head, *ptr;
11434 struct cv_triple *cv;
11436 head = label(state); /* dummy initial triple */
11437 flatten(state, head, expr);
11439 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11442 cv = xcmalloc(sizeof(struct cv_triple)*count, "const value vector");
11444 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11446 cv[i].id = ptr->id;
11452 valid_ins(state, ptr);
11453 if ((ptr->op == OP_PHI) || (ptr->op == OP_LIST)) {
11454 internal_error(state, ptr,
11455 "unexpected %s in constant expression",
11458 else if (ptr->op == OP_LIST) {
11460 else if (triple_is_structural(state, ptr)) {
11463 else if (triple_is_ubranch(state, ptr)) {
11464 ptr = TARG(ptr, 0);
11466 else if (triple_is_cbranch(state, ptr)) {
11467 struct triple *cond_val;
11468 cond_val = get_cv(state, cv, RHS(ptr, 0));
11469 if (!cond_val || !is_const(cond_val) ||
11470 (cond_val->op != OP_INTCONST))
11472 internal_error(state, ptr, "bad branch condition");
11474 if (cond_val->u.cval == 0) {
11477 ptr = TARG(ptr, 0);
11480 else if (triple_is_branch(state, ptr)) {
11481 error(state, ptr, "bad branch type in constant expression");
11483 else if (ptr->op == OP_WRITE) {
11484 struct triple *val;
11485 val = get_cv(state, cv, RHS(ptr, 0));
11487 set_cv(state, cv, MISC(ptr, 0),
11488 copy_triple(state, val));
11489 set_cv(state, cv, ptr,
11490 copy_triple(state, val));
11493 else if (ptr->op == OP_READ) {
11494 set_cv(state, cv, ptr,
11496 get_cv(state, cv, RHS(ptr, 0))));
11499 else if (triple_is_pure(state, ptr, cv[ptr->id].id)) {
11500 struct triple *val, **rhs;
11501 val = copy_triple(state, ptr);
11502 rhs = triple_rhs(state, val, 0);
11503 for(; rhs; rhs = triple_rhs(state, val, rhs)) {
11505 internal_error(state, ptr, "Missing rhs");
11507 *rhs = get_cv(state, cv, *rhs);
11509 simplify(state, val);
11510 set_cv(state, cv, ptr, val);
11514 error(state, ptr, "impure operation in constant expression");
11517 } while(ptr != head);
11519 /* Get the result value */
11520 def = get_cv(state, cv, head->prev);
11521 cv[head->prev->id].val = 0;
11523 /* Free the temporary values */
11524 for(i = 0; i < count; i++) {
11526 free_triple(state, cv[i].val);
11531 /* Free the intermediate expressions */
11532 while(head->next != head) {
11533 release_triple(state, head->next);
11535 free_triple(state, head);
11537 if (!is_const(def)) {
11538 error(state, expr, "Not a constant expression");
11543 static struct triple *constant_expr(struct compile_state *state)
11545 return eval_const_expr(state, conditional_expr(state));
11548 static struct triple *assignment_expr(struct compile_state *state)
11550 struct triple *def, *left, *right;
11552 /* The C grammer in K&R shows assignment expressions
11553 * only taking unary expressions as input on their
11554 * left hand side. But specifies the precedence of
11555 * assignemnt as the lowest operator except for comma.
11557 * Allowing conditional expressions on the left hand side
11558 * of an assignement results in a grammar that accepts
11559 * a larger set of statements than standard C. As long
11560 * as the subset of the grammar that is standard C behaves
11561 * correctly this should cause no problems.
11563 * For the extra token strings accepted by the grammar
11564 * none of them should produce a valid lvalue, so they
11565 * should not produce functioning programs.
11567 * GCC has this bug as well, so surprises should be minimal.
11569 def = conditional_expr(state);
11571 switch((tok = peek(state))) {
11573 lvalue(state, left);
11574 eat(state, TOK_EQ);
11575 def = write_expr(state, left,
11576 read_expr(state, assignment_expr(state)));
11581 lvalue(state, left);
11582 arithmetic(state, left);
11584 right = read_expr(state, assignment_expr(state));
11585 arithmetic(state, right);
11587 sign = is_signed(left->type);
11590 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11591 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
11592 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
11594 def = write_expr(state, left,
11595 triple(state, op, left->type,
11596 read_expr(state, left), right));
11599 lvalue(state, left);
11600 eat(state, TOK_PLUSEQ);
11601 def = write_expr(state, left,
11602 mk_add_expr(state, left, assignment_expr(state)));
11605 lvalue(state, left);
11606 eat(state, TOK_MINUSEQ);
11607 def = write_expr(state, left,
11608 mk_sub_expr(state, left, assignment_expr(state)));
11615 lvalue(state, left);
11616 integral(state, left);
11618 right = read_expr(state, assignment_expr(state));
11619 integral(state, right);
11620 right = integral_promotion(state, right);
11621 sign = is_signed(left->type);
11624 case TOK_SLEQ: op = OP_SL; break;
11625 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
11626 case TOK_ANDEQ: op = OP_AND; break;
11627 case TOK_XOREQ: op = OP_XOR; break;
11628 case TOK_OREQ: op = OP_OR; break;
11630 def = write_expr(state, left,
11631 triple(state, op, left->type,
11632 read_expr(state, left), right));
11638 static struct triple *expr(struct compile_state *state)
11640 struct triple *def;
11641 def = assignment_expr(state);
11642 while(peek(state) == TOK_COMMA) {
11643 eat(state, TOK_COMMA);
11644 def = mkprog(state, def, assignment_expr(state), 0UL);
11649 static void expr_statement(struct compile_state *state, struct triple *first)
11651 if (peek(state) != TOK_SEMI) {
11652 /* lvalue conversions always apply except when certian operators
11653 * are applied. I apply the lvalue conversions here
11654 * as I know no more operators will be applied.
11656 flatten(state, first, lvalue_conversion(state, expr(state)));
11658 eat(state, TOK_SEMI);
11661 static void if_statement(struct compile_state *state, struct triple *first)
11663 struct triple *test, *jmp1, *jmp2, *middle, *end;
11665 jmp1 = jmp2 = middle = 0;
11666 eat(state, TOK_IF);
11667 eat(state, TOK_LPAREN);
11668 test = expr(state);
11670 /* Cleanup and invert the test */
11671 test = lfalse_expr(state, read_expr(state, test));
11672 eat(state, TOK_RPAREN);
11673 /* Generate the needed pieces */
11674 middle = label(state);
11675 jmp1 = branch(state, middle, test);
11676 /* Thread the pieces together */
11677 flatten(state, first, test);
11678 flatten(state, first, jmp1);
11679 flatten(state, first, label(state));
11680 statement(state, first);
11681 if (peek(state) == TOK_ELSE) {
11682 eat(state, TOK_ELSE);
11683 /* Generate the rest of the pieces */
11684 end = label(state);
11685 jmp2 = branch(state, end, 0);
11686 /* Thread them together */
11687 flatten(state, first, jmp2);
11688 flatten(state, first, middle);
11689 statement(state, first);
11690 flatten(state, first, end);
11693 flatten(state, first, middle);
11697 static void for_statement(struct compile_state *state, struct triple *first)
11699 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11700 struct triple *label1, *label2, *label3;
11701 struct hash_entry *ident;
11703 eat(state, TOK_FOR);
11704 eat(state, TOK_LPAREN);
11705 head = test = tail = jmp1 = jmp2 = 0;
11706 if (peek(state) != TOK_SEMI) {
11707 head = expr(state);
11709 eat(state, TOK_SEMI);
11710 if (peek(state) != TOK_SEMI) {
11711 test = expr(state);
11713 test = ltrue_expr(state, read_expr(state, test));
11715 eat(state, TOK_SEMI);
11716 if (peek(state) != TOK_RPAREN) {
11717 tail = expr(state);
11719 eat(state, TOK_RPAREN);
11720 /* Generate the needed pieces */
11721 label1 = label(state);
11722 label2 = label(state);
11723 label3 = label(state);
11725 jmp1 = branch(state, label3, 0);
11726 jmp2 = branch(state, label1, test);
11729 jmp2 = branch(state, label1, 0);
11731 end = label(state);
11732 /* Remember where break and continue go */
11733 start_scope(state);
11734 ident = state->i_break;
11735 symbol(state, ident, &ident->sym_ident, end, end->type);
11736 ident = state->i_continue;
11737 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11738 /* Now include the body */
11739 flatten(state, first, head);
11740 flatten(state, first, jmp1);
11741 flatten(state, first, label1);
11742 statement(state, first);
11743 flatten(state, first, label2);
11744 flatten(state, first, tail);
11745 flatten(state, first, label3);
11746 flatten(state, first, test);
11747 flatten(state, first, jmp2);
11748 flatten(state, first, end);
11749 /* Cleanup the break/continue scope */
11753 static void while_statement(struct compile_state *state, struct triple *first)
11755 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11756 struct hash_entry *ident;
11757 eat(state, TOK_WHILE);
11758 eat(state, TOK_LPAREN);
11759 test = expr(state);
11761 test = ltrue_expr(state, read_expr(state, test));
11762 eat(state, TOK_RPAREN);
11763 /* Generate the needed pieces */
11764 label1 = label(state);
11765 label2 = label(state);
11766 jmp1 = branch(state, label2, 0);
11767 jmp2 = branch(state, label1, test);
11768 end = label(state);
11769 /* Remember where break and continue go */
11770 start_scope(state);
11771 ident = state->i_break;
11772 symbol(state, ident, &ident->sym_ident, end, end->type);
11773 ident = state->i_continue;
11774 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11775 /* Thread them together */
11776 flatten(state, first, jmp1);
11777 flatten(state, first, label1);
11778 statement(state, first);
11779 flatten(state, first, label2);
11780 flatten(state, first, test);
11781 flatten(state, first, jmp2);
11782 flatten(state, first, end);
11783 /* Cleanup the break/continue scope */
11787 static void do_statement(struct compile_state *state, struct triple *first)
11789 struct triple *label1, *label2, *test, *end;
11790 struct hash_entry *ident;
11791 eat(state, TOK_DO);
11792 /* Generate the needed pieces */
11793 label1 = label(state);
11794 label2 = label(state);
11795 end = label(state);
11796 /* Remember where break and continue go */
11797 start_scope(state);
11798 ident = state->i_break;
11799 symbol(state, ident, &ident->sym_ident, end, end->type);
11800 ident = state->i_continue;
11801 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11802 /* Now include the body */
11803 flatten(state, first, label1);
11804 statement(state, first);
11805 /* Cleanup the break/continue scope */
11807 /* Eat the rest of the loop */
11808 eat(state, TOK_WHILE);
11809 eat(state, TOK_LPAREN);
11810 test = read_expr(state, expr(state));
11812 eat(state, TOK_RPAREN);
11813 eat(state, TOK_SEMI);
11814 /* Thread the pieces together */
11815 test = ltrue_expr(state, test);
11816 flatten(state, first, label2);
11817 flatten(state, first, test);
11818 flatten(state, first, branch(state, label1, test));
11819 flatten(state, first, end);
11823 static void return_statement(struct compile_state *state, struct triple *first)
11825 struct triple *jmp, *mv, *dest, *var, *val;
11827 eat(state, TOK_RETURN);
11829 #if DEBUG_ROMCC_WARNINGS
11830 #warning "FIXME implement a more general excess branch elimination"
11833 /* If we have a return value do some more work */
11834 if (peek(state) != TOK_SEMI) {
11835 val = read_expr(state, expr(state));
11837 eat(state, TOK_SEMI);
11839 /* See if this last statement in a function */
11840 last = ((peek(state) == TOK_RBRACE) &&
11841 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11843 /* Find the return variable */
11844 var = fresult(state, state->main_function);
11846 /* Find the return destination */
11847 dest = state->i_return->sym_ident->def;
11849 /* If needed generate a jump instruction */
11851 jmp = branch(state, dest, 0);
11853 /* If needed generate an assignment instruction */
11855 mv = write_expr(state, deref_index(state, var, 1), val);
11857 /* Now put the code together */
11859 flatten(state, first, mv);
11860 flatten(state, first, jmp);
11863 flatten(state, first, jmp);
11867 static void break_statement(struct compile_state *state, struct triple *first)
11869 struct triple *dest;
11870 eat(state, TOK_BREAK);
11871 eat(state, TOK_SEMI);
11872 if (!state->i_break->sym_ident) {
11873 error(state, 0, "break statement not within loop or switch");
11875 dest = state->i_break->sym_ident->def;
11876 flatten(state, first, branch(state, dest, 0));
11879 static void continue_statement(struct compile_state *state, struct triple *first)
11881 struct triple *dest;
11882 eat(state, TOK_CONTINUE);
11883 eat(state, TOK_SEMI);
11884 if (!state->i_continue->sym_ident) {
11885 error(state, 0, "continue statement outside of a loop");
11887 dest = state->i_continue->sym_ident->def;
11888 flatten(state, first, branch(state, dest, 0));
11891 static void goto_statement(struct compile_state *state, struct triple *first)
11893 struct hash_entry *ident;
11894 eat(state, TOK_GOTO);
11895 ident = eat(state, TOK_IDENT)->ident;
11896 if (!ident->sym_label) {
11897 /* If this is a forward branch allocate the label now,
11898 * it will be flattend in the appropriate location later.
11900 struct triple *ins;
11901 ins = label(state);
11902 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11904 eat(state, TOK_SEMI);
11906 flatten(state, first, branch(state, ident->sym_label->def, 0));
11909 static void labeled_statement(struct compile_state *state, struct triple *first)
11911 struct triple *ins;
11912 struct hash_entry *ident;
11914 ident = eat(state, TOK_IDENT)->ident;
11915 if (ident->sym_label && ident->sym_label->def) {
11916 ins = ident->sym_label->def;
11917 put_occurance(ins->occurance);
11918 ins->occurance = new_occurance(state);
11921 ins = label(state);
11922 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11924 if (ins->id & TRIPLE_FLAG_FLATTENED) {
11925 error(state, 0, "label %s already defined", ident->name);
11927 flatten(state, first, ins);
11929 eat(state, TOK_COLON);
11930 statement(state, first);
11933 static void switch_statement(struct compile_state *state, struct triple *first)
11935 struct triple *value, *top, *end, *dbranch;
11936 struct hash_entry *ident;
11938 /* See if we have a valid switch statement */
11939 eat(state, TOK_SWITCH);
11940 eat(state, TOK_LPAREN);
11941 value = expr(state);
11942 integral(state, value);
11943 value = read_expr(state, value);
11944 eat(state, TOK_RPAREN);
11945 /* Generate the needed pieces */
11946 top = label(state);
11947 end = label(state);
11948 dbranch = branch(state, end, 0);
11949 /* Remember where case branches and break goes */
11950 start_scope(state);
11951 ident = state->i_switch;
11952 symbol(state, ident, &ident->sym_ident, value, value->type);
11953 ident = state->i_case;
11954 symbol(state, ident, &ident->sym_ident, top, top->type);
11955 ident = state->i_break;
11956 symbol(state, ident, &ident->sym_ident, end, end->type);
11957 ident = state->i_default;
11958 symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11959 /* Thread them together */
11960 flatten(state, first, value);
11961 flatten(state, first, top);
11962 flatten(state, first, dbranch);
11963 statement(state, first);
11964 flatten(state, first, end);
11965 /* Cleanup the switch scope */
11969 static void case_statement(struct compile_state *state, struct triple *first)
11971 struct triple *cvalue, *dest, *test, *jmp;
11972 struct triple *ptr, *value, *top, *dbranch;
11974 /* See if w have a valid case statement */
11975 eat(state, TOK_CASE);
11976 cvalue = constant_expr(state);
11977 integral(state, cvalue);
11978 if (cvalue->op != OP_INTCONST) {
11979 error(state, 0, "integer constant expected");
11981 eat(state, TOK_COLON);
11982 if (!state->i_case->sym_ident) {
11983 error(state, 0, "case statement not within a switch");
11986 /* Lookup the interesting pieces */
11987 top = state->i_case->sym_ident->def;
11988 value = state->i_switch->sym_ident->def;
11989 dbranch = state->i_default->sym_ident->def;
11991 /* See if this case label has already been used */
11992 for(ptr = top; ptr != dbranch; ptr = ptr->next) {
11993 if (ptr->op != OP_EQ) {
11996 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
11997 error(state, 0, "duplicate case %d statement",
12001 /* Generate the needed pieces */
12002 dest = label(state);
12003 test = triple(state, OP_EQ, &int_type, value, cvalue);
12004 jmp = branch(state, dest, test);
12005 /* Thread the pieces together */
12006 flatten(state, dbranch, test);
12007 flatten(state, dbranch, jmp);
12008 flatten(state, dbranch, label(state));
12009 flatten(state, first, dest);
12010 statement(state, first);
12013 static void default_statement(struct compile_state *state, struct triple *first)
12015 struct triple *dest;
12016 struct triple *dbranch, *end;
12018 /* See if we have a valid default statement */
12019 eat(state, TOK_DEFAULT);
12020 eat(state, TOK_COLON);
12022 if (!state->i_case->sym_ident) {
12023 error(state, 0, "default statement not within a switch");
12026 /* Lookup the interesting pieces */
12027 dbranch = state->i_default->sym_ident->def;
12028 end = state->i_break->sym_ident->def;
12030 /* See if a default statement has already happened */
12031 if (TARG(dbranch, 0) != end) {
12032 error(state, 0, "duplicate default statement");
12035 /* Generate the needed pieces */
12036 dest = label(state);
12038 /* Blame the branch on the default statement */
12039 put_occurance(dbranch->occurance);
12040 dbranch->occurance = new_occurance(state);
12042 /* Thread the pieces together */
12043 TARG(dbranch, 0) = dest;
12044 use_triple(dest, dbranch);
12045 flatten(state, first, dest);
12046 statement(state, first);
12049 static void asm_statement(struct compile_state *state, struct triple *first)
12051 struct asm_info *info;
12053 struct triple *constraint;
12054 struct triple *expr;
12055 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12056 struct triple *def, *asm_str;
12057 int out, in, clobbers, more, colons, i;
12061 eat(state, TOK_ASM);
12062 /* For now ignore the qualifiers */
12063 switch(peek(state)) {
12065 eat(state, TOK_CONST);
12068 eat(state, TOK_VOLATILE);
12069 flags |= TRIPLE_FLAG_VOLATILE;
12072 eat(state, TOK_LPAREN);
12073 asm_str = string_constant(state);
12076 out = in = clobbers = 0;
12078 if ((colons == 0) && (peek(state) == TOK_COLON)) {
12079 eat(state, TOK_COLON);
12081 more = (peek(state) == TOK_LIT_STRING);
12083 struct triple *var;
12084 struct triple *constraint;
12087 if (out > MAX_LHS) {
12088 error(state, 0, "Maximum output count exceeded.");
12090 constraint = string_constant(state);
12091 str = constraint->u.blob;
12092 if (str[0] != '=') {
12093 error(state, 0, "Output constraint does not start with =");
12095 constraint->u.blob = str + 1;
12096 eat(state, TOK_LPAREN);
12097 var = conditional_expr(state);
12098 eat(state, TOK_RPAREN);
12100 lvalue(state, var);
12101 out_param[out].constraint = constraint;
12102 out_param[out].expr = var;
12103 if (peek(state) == TOK_COMMA) {
12104 eat(state, TOK_COMMA);
12111 if ((colons == 1) && (peek(state) == TOK_COLON)) {
12112 eat(state, TOK_COLON);
12114 more = (peek(state) == TOK_LIT_STRING);
12116 struct triple *val;
12117 struct triple *constraint;
12120 if (in > MAX_RHS) {
12121 error(state, 0, "Maximum input count exceeded.");
12123 constraint = string_constant(state);
12124 str = constraint->u.blob;
12125 if (digitp(str[0] && str[1] == '\0')) {
12127 val = digval(str[0]);
12128 if ((val < 0) || (val >= out)) {
12129 error(state, 0, "Invalid input constraint %d", val);
12132 eat(state, TOK_LPAREN);
12133 val = conditional_expr(state);
12134 eat(state, TOK_RPAREN);
12136 in_param[in].constraint = constraint;
12137 in_param[in].expr = val;
12138 if (peek(state) == TOK_COMMA) {
12139 eat(state, TOK_COMMA);
12147 if ((colons == 2) && (peek(state) == TOK_COLON)) {
12148 eat(state, TOK_COLON);
12150 more = (peek(state) == TOK_LIT_STRING);
12152 struct triple *clobber;
12154 if ((clobbers + out) > MAX_LHS) {
12155 error(state, 0, "Maximum clobber limit exceeded.");
12157 clobber = string_constant(state);
12159 clob_param[clobbers].constraint = clobber;
12160 if (peek(state) == TOK_COMMA) {
12161 eat(state, TOK_COMMA);
12167 eat(state, TOK_RPAREN);
12168 eat(state, TOK_SEMI);
12171 info = xcmalloc(sizeof(*info), "asm_info");
12172 info->str = asm_str->u.blob;
12173 free_triple(state, asm_str);
12175 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12176 def->u.ainfo = info;
12179 /* Find the register constraints */
12180 for(i = 0; i < out; i++) {
12181 struct triple *constraint;
12182 constraint = out_param[i].constraint;
12183 info->tmpl.lhs[i] = arch_reg_constraint(state,
12184 out_param[i].expr->type, constraint->u.blob);
12185 free_triple(state, constraint);
12187 for(; i - out < clobbers; i++) {
12188 struct triple *constraint;
12189 constraint = clob_param[i - out].constraint;
12190 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12191 free_triple(state, constraint);
12193 for(i = 0; i < in; i++) {
12194 struct triple *constraint;
12196 constraint = in_param[i].constraint;
12197 str = constraint->u.blob;
12198 if (digitp(str[0]) && str[1] == '\0') {
12199 struct reg_info cinfo;
12201 val = digval(str[0]);
12202 cinfo.reg = info->tmpl.lhs[val].reg;
12203 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12204 cinfo.regcm &= info->tmpl.lhs[val].regcm;
12205 if (cinfo.reg == REG_UNSET) {
12206 cinfo.reg = REG_VIRT0 + val;
12208 if (cinfo.regcm == 0) {
12209 error(state, 0, "No registers for %d", val);
12211 info->tmpl.lhs[val] = cinfo;
12212 info->tmpl.rhs[i] = cinfo;
12215 info->tmpl.rhs[i] = arch_reg_constraint(state,
12216 in_param[i].expr->type, str);
12218 free_triple(state, constraint);
12221 /* Now build the helper expressions */
12222 for(i = 0; i < in; i++) {
12223 RHS(def, i) = read_expr(state, in_param[i].expr);
12225 flatten(state, first, def);
12226 for(i = 0; i < (out + clobbers); i++) {
12228 struct triple *piece;
12230 type = out_param[i].expr->type;
12232 size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12233 if (size >= SIZEOF_LONG) {
12234 type = &ulong_type;
12236 else if (size >= SIZEOF_INT) {
12239 else if (size >= SIZEOF_SHORT) {
12240 type = &ushort_type;
12243 type = &uchar_type;
12246 piece = triple(state, OP_PIECE, type, def, 0);
12248 LHS(def, i) = piece;
12249 flatten(state, first, piece);
12251 /* And write the helpers to their destinations */
12252 for(i = 0; i < out; i++) {
12253 struct triple *piece;
12254 piece = LHS(def, i);
12255 flatten(state, first,
12256 write_expr(state, out_param[i].expr, piece));
12261 static int isdecl(int tok)
12284 case TOK_TYPE_NAME: /* typedef name */
12291 static void compound_statement(struct compile_state *state, struct triple *first)
12293 eat(state, TOK_LBRACE);
12294 start_scope(state);
12296 /* statement-list opt */
12297 while (peek(state) != TOK_RBRACE) {
12298 statement(state, first);
12301 eat(state, TOK_RBRACE);
12304 static void statement(struct compile_state *state, struct triple *first)
12308 if (tok == TOK_LBRACE) {
12309 compound_statement(state, first);
12311 else if (tok == TOK_IF) {
12312 if_statement(state, first);
12314 else if (tok == TOK_FOR) {
12315 for_statement(state, first);
12317 else if (tok == TOK_WHILE) {
12318 while_statement(state, first);
12320 else if (tok == TOK_DO) {
12321 do_statement(state, first);
12323 else if (tok == TOK_RETURN) {
12324 return_statement(state, first);
12326 else if (tok == TOK_BREAK) {
12327 break_statement(state, first);
12329 else if (tok == TOK_CONTINUE) {
12330 continue_statement(state, first);
12332 else if (tok == TOK_GOTO) {
12333 goto_statement(state, first);
12335 else if (tok == TOK_SWITCH) {
12336 switch_statement(state, first);
12338 else if (tok == TOK_ASM) {
12339 asm_statement(state, first);
12341 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12342 labeled_statement(state, first);
12344 else if (tok == TOK_CASE) {
12345 case_statement(state, first);
12347 else if (tok == TOK_DEFAULT) {
12348 default_statement(state, first);
12350 else if (isdecl(tok)) {
12351 /* This handles C99 intermixing of statements and decls */
12352 decl(state, first);
12355 expr_statement(state, first);
12359 static struct type *param_decl(struct compile_state *state)
12362 struct hash_entry *ident;
12363 /* Cheat so the declarator will know we are not global */
12364 start_scope(state);
12366 type = decl_specifiers(state);
12367 type = declarator(state, type, &ident, 0);
12368 type->field_ident = ident;
12373 static struct type *param_type_list(struct compile_state *state, struct type *type)
12375 struct type *ftype, **next;
12376 ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12377 next = &ftype->right;
12378 ftype->elements = 1;
12379 while(peek(state) == TOK_COMMA) {
12380 eat(state, TOK_COMMA);
12381 if (peek(state) == TOK_DOTS) {
12382 eat(state, TOK_DOTS);
12383 error(state, 0, "variadic functions not supported");
12386 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12387 next = &((*next)->right);
12394 static struct type *type_name(struct compile_state *state)
12397 type = specifier_qualifier_list(state);
12398 /* abstract-declarator (may consume no tokens) */
12399 type = declarator(state, type, 0, 0);
12403 static struct type *direct_declarator(
12404 struct compile_state *state, struct type *type,
12405 struct hash_entry **pident, int need_ident)
12407 struct hash_entry *ident;
12408 struct type *outer;
12411 arrays_complete(state, type);
12412 switch(peek(state)) {
12414 ident = eat(state, TOK_IDENT)->ident;
12416 error(state, 0, "Unexpected identifier found");
12418 /* The name of what we are declaring */
12422 eat(state, TOK_LPAREN);
12423 outer = declarator(state, type, pident, need_ident);
12424 eat(state, TOK_RPAREN);
12428 error(state, 0, "Identifier expected");
12434 arrays_complete(state, type);
12435 switch(peek(state)) {
12437 eat(state, TOK_LPAREN);
12438 type = param_type_list(state, type);
12439 eat(state, TOK_RPAREN);
12443 unsigned int qualifiers;
12444 struct triple *value;
12446 eat(state, TOK_LBRACKET);
12447 if (peek(state) != TOK_RBRACKET) {
12448 value = constant_expr(state);
12449 integral(state, value);
12451 eat(state, TOK_RBRACKET);
12453 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12454 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12456 type->elements = value->u.cval;
12457 free_triple(state, value);
12459 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12470 struct type *inner;
12471 arrays_complete(state, type);
12473 for(inner = outer; inner->left; inner = inner->left)
12475 inner->left = type;
12481 static struct type *declarator(
12482 struct compile_state *state, struct type *type,
12483 struct hash_entry **pident, int need_ident)
12485 while(peek(state) == TOK_STAR) {
12486 eat(state, TOK_STAR);
12487 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12489 type = direct_declarator(state, type, pident, need_ident);
12493 static struct type *typedef_name(
12494 struct compile_state *state, unsigned int specifiers)
12496 struct hash_entry *ident;
12498 ident = eat(state, TOK_TYPE_NAME)->ident;
12499 type = ident->sym_ident->type;
12500 specifiers |= type->type & QUAL_MASK;
12501 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
12502 (type->type & (STOR_MASK | QUAL_MASK))) {
12503 type = clone_type(specifiers, type);
12508 static struct type *enum_specifier(
12509 struct compile_state *state, unsigned int spec)
12511 struct hash_entry *ident;
12514 struct type *enum_type;
12517 eat(state, TOK_ENUM);
12519 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12520 ident = eat(state, tok)->ident;
12523 if (!ident || (peek(state) == TOK_LBRACE)) {
12524 struct type **next;
12525 eat(state, TOK_LBRACE);
12526 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12527 enum_type->type_ident = ident;
12528 next = &enum_type->right;
12530 struct hash_entry *eident;
12531 struct triple *value;
12532 struct type *entry;
12533 eident = eat(state, TOK_IDENT)->ident;
12534 if (eident->sym_ident) {
12535 error(state, 0, "%s already declared",
12538 eident->tok = TOK_ENUM_CONST;
12539 if (peek(state) == TOK_EQ) {
12540 struct triple *val;
12541 eat(state, TOK_EQ);
12542 val = constant_expr(state);
12543 integral(state, val);
12544 base = val->u.cval;
12546 value = int_const(state, &int_type, base);
12547 symbol(state, eident, &eident->sym_ident, value, &int_type);
12548 entry = new_type(TYPE_LIST, 0, 0);
12549 entry->field_ident = eident;
12551 next = &entry->right;
12553 if (peek(state) == TOK_COMMA) {
12554 eat(state, TOK_COMMA);
12556 } while(peek(state) != TOK_RBRACE);
12557 eat(state, TOK_RBRACE);
12559 symbol(state, ident, &ident->sym_tag, 0, enum_type);
12562 if (ident && ident->sym_tag &&
12563 ident->sym_tag->type &&
12564 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12565 enum_type = clone_type(spec, ident->sym_tag->type);
12567 else if (ident && !enum_type) {
12568 error(state, 0, "enum %s undeclared", ident->name);
12573 static struct type *struct_declarator(
12574 struct compile_state *state, struct type *type, struct hash_entry **ident)
12576 if (peek(state) != TOK_COLON) {
12577 type = declarator(state, type, ident, 1);
12579 if (peek(state) == TOK_COLON) {
12580 struct triple *value;
12581 eat(state, TOK_COLON);
12582 value = constant_expr(state);
12583 if (value->op != OP_INTCONST) {
12584 error(state, 0, "Invalid constant expression");
12586 if (value->u.cval > size_of(state, type)) {
12587 error(state, 0, "bitfield larger than base type");
12589 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12590 error(state, 0, "bitfield base not an integer type");
12592 type = new_type(TYPE_BITFIELD, type, 0);
12593 type->elements = value->u.cval;
12598 static struct type *struct_or_union_specifier(
12599 struct compile_state *state, unsigned int spec)
12601 struct type *struct_type;
12602 struct hash_entry *ident;
12603 unsigned int type_main;
12604 unsigned int type_join;
12608 switch(peek(state)) {
12610 eat(state, TOK_STRUCT);
12611 type_main = TYPE_STRUCT;
12612 type_join = TYPE_PRODUCT;
12615 eat(state, TOK_UNION);
12616 type_main = TYPE_UNION;
12617 type_join = TYPE_OVERLAP;
12620 eat(state, TOK_STRUCT);
12621 type_main = TYPE_STRUCT;
12622 type_join = TYPE_PRODUCT;
12626 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12627 ident = eat(state, tok)->ident;
12629 if (!ident || (peek(state) == TOK_LBRACE)) {
12631 struct type **next;
12633 eat(state, TOK_LBRACE);
12634 next = &struct_type;
12636 struct type *base_type;
12638 base_type = specifier_qualifier_list(state);
12641 struct hash_entry *fident;
12643 type = struct_declarator(state, base_type, &fident);
12645 if (peek(state) == TOK_COMMA) {
12647 eat(state, TOK_COMMA);
12649 type = clone_type(0, type);
12650 type->field_ident = fident;
12652 *next = new_type(type_join, *next, type);
12653 next = &((*next)->right);
12658 eat(state, TOK_SEMI);
12659 } while(peek(state) != TOK_RBRACE);
12660 eat(state, TOK_RBRACE);
12661 struct_type = new_type(type_main | spec, struct_type, 0);
12662 struct_type->type_ident = ident;
12663 struct_type->elements = elements;
12665 symbol(state, ident, &ident->sym_tag, 0, struct_type);
12668 if (ident && ident->sym_tag &&
12669 ident->sym_tag->type &&
12670 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12671 struct_type = clone_type(spec, ident->sym_tag->type);
12673 else if (ident && !struct_type) {
12674 error(state, 0, "%s %s undeclared",
12675 (type_main == TYPE_STRUCT)?"struct" : "union",
12678 return struct_type;
12681 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12683 unsigned int specifiers;
12684 switch(peek(state)) {
12686 eat(state, TOK_AUTO);
12687 specifiers = STOR_AUTO;
12690 eat(state, TOK_REGISTER);
12691 specifiers = STOR_REGISTER;
12694 eat(state, TOK_STATIC);
12695 specifiers = STOR_STATIC;
12698 eat(state, TOK_EXTERN);
12699 specifiers = STOR_EXTERN;
12702 eat(state, TOK_TYPEDEF);
12703 specifiers = STOR_TYPEDEF;
12706 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12707 specifiers = STOR_LOCAL;
12710 specifiers = STOR_AUTO;
12716 static unsigned int function_specifier_opt(struct compile_state *state)
12718 /* Ignore the inline keyword */
12719 unsigned int specifiers;
12721 switch(peek(state)) {
12723 eat(state, TOK_INLINE);
12724 specifiers = STOR_INLINE;
12729 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12731 int tok = peek(state);
12735 /* The empty attribute ignore it */
12738 case TOK_ENUM_CONST:
12739 case TOK_TYPE_NAME:
12741 struct hash_entry *ident;
12742 ident = eat(state, TOK_IDENT)->ident;
12744 if (ident == state->i_noinline) {
12745 if (attributes & ATTRIB_ALWAYS_INLINE) {
12746 error(state, 0, "both always_inline and noinline attribtes");
12748 attributes |= ATTRIB_NOINLINE;
12750 else if (ident == state->i_always_inline) {
12751 if (attributes & ATTRIB_NOINLINE) {
12752 error(state, 0, "both noinline and always_inline attribtes");
12754 attributes |= ATTRIB_ALWAYS_INLINE;
12756 else if (ident == state->i_noreturn) {
12757 // attribute((noreturn)) does nothing (yet?)
12760 error(state, 0, "Unknown attribute:%s", ident->name);
12765 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12771 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12773 type = attrib(state, type);
12774 while(peek(state) == TOK_COMMA) {
12775 eat(state, TOK_COMMA);
12776 type = attrib(state, type);
12781 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12783 if (peek(state) == TOK_ATTRIBUTE) {
12784 eat(state, TOK_ATTRIBUTE);
12785 eat(state, TOK_LPAREN);
12786 eat(state, TOK_LPAREN);
12787 type = attribute_list(state, type);
12788 eat(state, TOK_RPAREN);
12789 eat(state, TOK_RPAREN);
12794 static unsigned int type_qualifiers(struct compile_state *state)
12796 unsigned int specifiers;
12799 specifiers = QUAL_NONE;
12801 switch(peek(state)) {
12803 eat(state, TOK_CONST);
12804 specifiers |= QUAL_CONST;
12807 eat(state, TOK_VOLATILE);
12808 specifiers |= QUAL_VOLATILE;
12811 eat(state, TOK_RESTRICT);
12812 specifiers |= QUAL_RESTRICT;
12822 static struct type *type_specifier(
12823 struct compile_state *state, unsigned int spec)
12828 switch((tok = peek(state))) {
12830 eat(state, TOK_VOID);
12831 type = new_type(TYPE_VOID | spec, 0, 0);
12834 eat(state, TOK_CHAR);
12835 type = new_type(TYPE_CHAR | spec, 0, 0);
12838 eat(state, TOK_SHORT);
12839 if (peek(state) == TOK_INT) {
12840 eat(state, TOK_INT);
12842 type = new_type(TYPE_SHORT | spec, 0, 0);
12845 eat(state, TOK_INT);
12846 type = new_type(TYPE_INT | spec, 0, 0);
12849 eat(state, TOK_LONG);
12850 switch(peek(state)) {
12852 eat(state, TOK_LONG);
12853 error(state, 0, "long long not supported");
12856 eat(state, TOK_DOUBLE);
12857 error(state, 0, "long double not supported");
12860 eat(state, TOK_INT);
12861 type = new_type(TYPE_LONG | spec, 0, 0);
12864 type = new_type(TYPE_LONG | spec, 0, 0);
12869 eat(state, TOK_FLOAT);
12870 error(state, 0, "type float not supported");
12873 eat(state, TOK_DOUBLE);
12874 error(state, 0, "type double not supported");
12877 eat(state, TOK_SIGNED);
12878 switch(peek(state)) {
12880 eat(state, TOK_LONG);
12881 switch(peek(state)) {
12883 eat(state, TOK_LONG);
12884 error(state, 0, "type long long not supported");
12887 eat(state, TOK_INT);
12888 type = new_type(TYPE_LONG | spec, 0, 0);
12891 type = new_type(TYPE_LONG | spec, 0, 0);
12896 eat(state, TOK_INT);
12897 type = new_type(TYPE_INT | spec, 0, 0);
12900 eat(state, TOK_SHORT);
12901 type = new_type(TYPE_SHORT | spec, 0, 0);
12904 eat(state, TOK_CHAR);
12905 type = new_type(TYPE_CHAR | spec, 0, 0);
12908 type = new_type(TYPE_INT | spec, 0, 0);
12913 eat(state, TOK_UNSIGNED);
12914 switch(peek(state)) {
12916 eat(state, TOK_LONG);
12917 switch(peek(state)) {
12919 eat(state, TOK_LONG);
12920 error(state, 0, "unsigned long long not supported");
12923 eat(state, TOK_INT);
12924 type = new_type(TYPE_ULONG | spec, 0, 0);
12927 type = new_type(TYPE_ULONG | spec, 0, 0);
12932 eat(state, TOK_INT);
12933 type = new_type(TYPE_UINT | spec, 0, 0);
12936 eat(state, TOK_SHORT);
12937 type = new_type(TYPE_USHORT | spec, 0, 0);
12940 eat(state, TOK_CHAR);
12941 type = new_type(TYPE_UCHAR | spec, 0, 0);
12944 type = new_type(TYPE_UINT | spec, 0, 0);
12948 /* struct or union specifier */
12951 type = struct_or_union_specifier(state, spec);
12953 /* enum-spefifier */
12955 type = enum_specifier(state, spec);
12958 case TOK_TYPE_NAME:
12959 type = typedef_name(state, spec);
12962 error(state, 0, "bad type specifier %s",
12969 static int istype(int tok)
12987 case TOK_TYPE_NAME:
12995 static struct type *specifier_qualifier_list(struct compile_state *state)
12998 unsigned int specifiers = 0;
13000 /* type qualifiers */
13001 specifiers |= type_qualifiers(state);
13003 /* type specifier */
13004 type = type_specifier(state, specifiers);
13009 #if DEBUG_ROMCC_WARNING
13010 static int isdecl_specifier(int tok)
13013 /* storage class specifier */
13019 /* type qualifier */
13023 /* type specifiers */
13033 /* struct or union specifier */
13036 /* enum-spefifier */
13039 case TOK_TYPE_NAME:
13040 /* function specifiers */
13049 static struct type *decl_specifiers(struct compile_state *state)
13052 unsigned int specifiers;
13053 /* I am overly restrictive in the arragement of specifiers supported.
13054 * C is overly flexible in this department it makes interpreting
13055 * the parse tree difficult.
13059 /* storage class specifier */
13060 specifiers |= storage_class_specifier_opt(state);
13062 /* function-specifier */
13063 specifiers |= function_specifier_opt(state);
13066 specifiers |= attributes_opt(state, 0);
13068 /* type qualifier */
13069 specifiers |= type_qualifiers(state);
13071 /* type specifier */
13072 type = type_specifier(state, specifiers);
13076 struct field_info {
13081 static struct field_info designator(struct compile_state *state, struct type *type)
13084 struct field_info info;
13088 switch(peek(state)) {
13091 struct triple *value;
13092 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13093 error(state, 0, "Array designator not in array initializer");
13095 eat(state, TOK_LBRACKET);
13096 value = constant_expr(state);
13097 eat(state, TOK_RBRACKET);
13099 info.type = type->left;
13100 info.offset = value->u.cval * size_of(state, info.type);
13105 struct hash_entry *field;
13106 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13107 ((type->type & TYPE_MASK) != TYPE_UNION))
13109 error(state, 0, "Struct designator not in struct initializer");
13111 eat(state, TOK_DOT);
13112 field = eat(state, TOK_IDENT)->ident;
13113 info.offset = field_offset(state, type, field);
13114 info.type = field_type(state, type, field);
13118 error(state, 0, "Invalid designator");
13121 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13122 eat(state, TOK_EQ);
13126 static struct triple *initializer(
13127 struct compile_state *state, struct type *type)
13129 struct triple *result;
13130 #if DEBUG_ROMCC_WARNINGS
13131 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13133 if (peek(state) != TOK_LBRACE) {
13134 result = assignment_expr(state);
13135 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13136 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13137 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13138 (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13139 (equiv_types(type->left, result->type->left))) {
13140 type->elements = result->type->elements;
13142 if (is_lvalue(state, result) &&
13143 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13144 (type->type & TYPE_MASK) != TYPE_ARRAY)
13146 result = lvalue_conversion(state, result);
13148 if (!is_init_compatible(state, type, result->type)) {
13149 error(state, 0, "Incompatible types in initializer");
13151 if (!equiv_types(type, result->type)) {
13152 result = mk_cast_expr(state, type, result);
13158 struct field_info info;
13160 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13161 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13162 internal_error(state, 0, "unknown initializer type");
13165 info.type = type->left;
13166 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13167 info.type = next_field(state, type, 0);
13169 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13172 max_offset = size_of(state, type);
13174 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13175 eat(state, TOK_LBRACE);
13177 struct triple *value;
13178 struct type *value_type;
13184 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13185 info = designator(state, type);
13187 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13188 (info.offset >= max_offset)) {
13189 error(state, 0, "element beyond bounds");
13191 value_type = info.type;
13192 value = eval_const_expr(state, initializer(state, value_type));
13193 value_size = size_of(state, value_type);
13194 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13195 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13196 (max_offset <= info.offset)) {
13200 old_size = max_offset;
13201 max_offset = info.offset + value_size;
13202 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13203 memcpy(buf, old_buf, bits_to_bytes(old_size));
13206 dest = ((char *)buf) + bits_to_bytes(info.offset);
13207 #if DEBUG_INITIALIZER
13208 fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n",
13210 bits_to_bytes(max_offset),
13211 bits_to_bytes(value_size),
13214 if (value->op == OP_BLOBCONST) {
13215 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13217 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13218 #if DEBUG_INITIALIZER
13219 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13221 *((uint8_t *)dest) = value->u.cval & 0xff;
13223 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13224 *((uint16_t *)dest) = value->u.cval & 0xffff;
13226 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13227 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13230 internal_error(state, 0, "unhandled constant initializer");
13232 free_triple(state, value);
13233 if (peek(state) == TOK_COMMA) {
13234 eat(state, TOK_COMMA);
13237 info.offset += value_size;
13238 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13239 info.type = next_field(state, type, info.type);
13240 info.offset = field_offset(state, type,
13241 info.type->field_ident);
13243 } while(comma && (peek(state) != TOK_RBRACE));
13244 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13245 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13246 type->elements = max_offset / size_of(state, type->left);
13248 eat(state, TOK_RBRACE);
13249 result = triple(state, OP_BLOBCONST, type, 0, 0);
13250 result->u.blob = buf;
13255 static void resolve_branches(struct compile_state *state, struct triple *first)
13257 /* Make a second pass and finish anything outstanding
13258 * with respect to branches. The only outstanding item
13259 * is to see if there are goto to labels that have not
13260 * been defined and to error about them.
13263 struct triple *ins;
13264 /* Also error on branches that do not use their targets */
13267 if (!triple_is_ret(state, ins)) {
13268 struct triple **expr ;
13269 struct triple_set *set;
13270 expr = triple_targ(state, ins, 0);
13271 for(; expr; expr = triple_targ(state, ins, expr)) {
13272 struct triple *targ;
13274 for(set = targ?targ->use:0; set; set = set->next) {
13275 if (set->member == ins) {
13280 internal_error(state, ins, "targ not used");
13285 } while(ins != first);
13286 /* See if there are goto to labels that have not been defined */
13287 for(i = 0; i < HASH_TABLE_SIZE; i++) {
13288 struct hash_entry *entry;
13289 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13290 struct triple *ins;
13291 if (!entry->sym_label) {
13294 ins = entry->sym_label->def;
13295 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13296 error(state, ins, "label `%s' used but not defined",
13303 static struct triple *function_definition(
13304 struct compile_state *state, struct type *type)
13306 struct triple *def, *tmp, *first, *end, *retvar, *ret;
13307 struct triple *fname;
13308 struct type *fname_type;
13309 struct hash_entry *ident;
13310 struct type *param, *crtype, *ctype;
13312 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13313 error(state, 0, "Invalid function header");
13316 /* Verify the function type */
13317 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
13318 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13319 (type->right->field_ident == 0)) {
13320 error(state, 0, "Invalid function parameters");
13322 param = type->right;
13324 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13326 if (!param->left->field_ident) {
13327 error(state, 0, "No identifier for parameter %d\n", i);
13329 param = param->right;
13332 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13333 error(state, 0, "No identifier for paramter %d\n", i);
13336 /* Get a list of statements for this function. */
13337 def = triple(state, OP_LIST, type, 0, 0);
13339 /* Start a new scope for the passed parameters */
13340 start_scope(state);
13342 /* Put a label at the very start of a function */
13343 first = label(state);
13344 RHS(def, 0) = first;
13346 /* Put a label at the very end of a function */
13347 end = label(state);
13348 flatten(state, first, end);
13349 /* Remember where return goes */
13350 ident = state->i_return;
13351 symbol(state, ident, &ident->sym_ident, end, end->type);
13353 /* Get the initial closure type */
13354 ctype = new_type(TYPE_JOIN, &void_type, 0);
13355 ctype->elements = 1;
13357 /* Add a variable for the return value */
13358 crtype = new_type(TYPE_TUPLE,
13359 /* Remove all type qualifiers from the return type */
13360 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13361 crtype->elements = 2;
13362 flatten(state, end, variable(state, crtype));
13364 /* Allocate a variable for the return address */
13365 retvar = flatten(state, end, variable(state, &void_ptr_type));
13367 /* Add in the return instruction */
13368 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13369 ret = flatten(state, first, ret);
13371 /* Walk through the parameters and create symbol table entries
13374 param = type->right;
13375 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13376 ident = param->left->field_ident;
13377 tmp = variable(state, param->left);
13378 var_symbol(state, ident, tmp);
13379 flatten(state, end, tmp);
13380 param = param->right;
13382 if ((param->type & TYPE_MASK) != TYPE_VOID) {
13383 /* And don't forget the last parameter */
13384 ident = param->field_ident;
13385 tmp = variable(state, param);
13386 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13387 flatten(state, end, tmp);
13390 /* Add the declaration static const char __func__ [] = "func-name" */
13391 fname_type = new_type(TYPE_ARRAY,
13392 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13393 fname_type->type |= QUAL_CONST | STOR_STATIC;
13394 fname_type->elements = strlen(state->function) + 1;
13396 fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13397 fname->u.blob = (void *)state->function;
13398 fname = flatten(state, end, fname);
13400 ident = state->i___func__;
13401 symbol(state, ident, &ident->sym_ident, fname, fname_type);
13403 /* Remember which function I am compiling.
13404 * Also assume the last defined function is the main function.
13406 state->main_function = def;
13408 /* Now get the actual function definition */
13409 compound_statement(state, end);
13411 /* Finish anything unfinished with branches */
13412 resolve_branches(state, first);
13414 /* Remove the parameter scope */
13418 /* Remember I have defined a function */
13419 if (!state->functions) {
13420 state->functions = def;
13422 insert_triple(state, state->functions, def);
13424 if (state->compiler->debug & DEBUG_INLINE) {
13425 FILE *fp = state->dbgout;
13428 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13429 display_func(state, fp, def);
13430 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13436 static struct triple *do_decl(struct compile_state *state,
13437 struct type *type, struct hash_entry *ident)
13439 struct triple *def;
13441 /* Clean up the storage types used */
13442 switch (type->type & STOR_MASK) {
13445 /* These are the good types I am aiming for */
13447 case STOR_REGISTER:
13448 type->type &= ~STOR_MASK;
13449 type->type |= STOR_AUTO;
13453 type->type &= ~STOR_MASK;
13454 type->type |= STOR_STATIC;
13458 error(state, 0, "typedef without name");
13460 symbol(state, ident, &ident->sym_ident, 0, type);
13461 ident->tok = TOK_TYPE_NAME;
13465 internal_error(state, 0, "Undefined storage class");
13467 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13468 error(state, 0, "Function prototypes not supported");
13471 ((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13472 ((type->type & STOR_MASK) != STOR_STATIC))
13473 error(state, 0, "non static arrays not supported");
13475 ((type->type & STOR_MASK) == STOR_STATIC) &&
13476 ((type->type & QUAL_CONST) == 0)) {
13477 error(state, 0, "non const static variables not supported");
13480 def = variable(state, type);
13481 var_symbol(state, ident, def);
13486 static void decl(struct compile_state *state, struct triple *first)
13488 struct type *base_type, *type;
13489 struct hash_entry *ident;
13490 struct triple *def;
13492 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13493 base_type = decl_specifiers(state);
13495 type = declarator(state, base_type, &ident, 0);
13496 type->type = attributes_opt(state, type->type);
13497 if (global && ident && (peek(state) == TOK_LBRACE)) {
13499 type->type_ident = ident;
13500 state->function = ident->name;
13501 def = function_definition(state, type);
13502 symbol(state, ident, &ident->sym_ident, def, type);
13503 state->function = 0;
13507 flatten(state, first, do_decl(state, type, ident));
13508 /* type or variable definition */
13511 if (peek(state) == TOK_EQ) {
13513 error(state, 0, "cannot assign to a type");
13515 eat(state, TOK_EQ);
13516 flatten(state, first,
13518 ident->sym_ident->def,
13519 initializer(state, type)));
13521 arrays_complete(state, type);
13522 if (peek(state) == TOK_COMMA) {
13523 eat(state, TOK_COMMA);
13525 type = declarator(state, base_type, &ident, 0);
13526 flatten(state, first, do_decl(state, type, ident));
13530 eat(state, TOK_SEMI);
13534 static void decls(struct compile_state *state)
13536 struct triple *list;
13538 list = label(state);
13541 if (tok == TOK_EOF) {
13544 if (tok == TOK_SPACE) {
13545 eat(state, TOK_SPACE);
13548 if (list->next != list) {
13549 error(state, 0, "global variables not supported");
13555 * Function inlining
13557 struct triple_reg_set {
13558 struct triple_reg_set *next;
13559 struct triple *member;
13560 struct triple *new;
13563 struct block *block;
13564 struct triple_reg_set *in;
13565 struct triple_reg_set *out;
13568 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13569 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13570 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13571 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13572 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13573 void (*cb)(struct compile_state *state, struct block *block, void *arg),
13575 static void print_block(
13576 struct compile_state *state, struct block *block, void *arg);
13577 static int do_triple_set(struct triple_reg_set **head,
13578 struct triple *member, struct triple *new_member);
13579 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13580 static struct reg_block *compute_variable_lifetimes(
13581 struct compile_state *state, struct basic_blocks *bb);
13582 static void free_variable_lifetimes(struct compile_state *state,
13583 struct basic_blocks *bb, struct reg_block *blocks);
13584 #if DEBUG_EXPLICIT_CLOSURES
13585 static void print_live_variables(struct compile_state *state,
13586 struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13590 static struct triple *call(struct compile_state *state,
13591 struct triple *retvar, struct triple *ret_addr,
13592 struct triple *targ, struct triple *ret)
13594 struct triple *call;
13596 if (!retvar || !is_lvalue(state, retvar)) {
13597 internal_error(state, 0, "writing to a non lvalue?");
13599 write_compatible(state, retvar->type, &void_ptr_type);
13601 call = new_triple(state, OP_CALL, &void_type, 1, 0);
13602 TARG(call, 0) = targ;
13603 MISC(call, 0) = ret;
13604 if (!targ || (targ->op != OP_LABEL)) {
13605 internal_error(state, 0, "call not to a label");
13607 if (!ret || (ret->op != OP_RET)) {
13608 internal_error(state, 0, "call not matched with return");
13613 static void walk_functions(struct compile_state *state,
13614 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13617 struct triple *func, *first;
13618 func = first = state->functions;
13620 cb(state, func, arg);
13622 } while(func != first);
13625 static void reverse_walk_functions(struct compile_state *state,
13626 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13629 struct triple *func, *first;
13630 func = first = state->functions;
13633 cb(state, func, arg);
13634 } while(func != first);
13638 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13640 struct triple *ptr, *first;
13641 if (func->u.cval == 0) {
13644 ptr = first = RHS(func, 0);
13646 if (ptr->op == OP_FCALL) {
13647 struct triple *called_func;
13648 called_func = MISC(ptr, 0);
13649 /* Mark the called function as used */
13650 if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13651 called_func->u.cval++;
13653 /* Remove the called function from the list */
13654 called_func->prev->next = called_func->next;
13655 called_func->next->prev = called_func->prev;
13657 /* Place the called function before me on the list */
13658 called_func->next = func;
13659 called_func->prev = func->prev;
13660 called_func->prev->next = called_func;
13661 called_func->next->prev = called_func;
13664 } while(ptr != first);
13665 func->id |= TRIPLE_FLAG_FLATTENED;
13668 static void mark_live_functions(struct compile_state *state)
13670 /* Ensure state->main_function is the last function in
13671 * the list of functions.
13673 if ((state->main_function->next != state->functions) ||
13674 (state->functions->prev != state->main_function)) {
13675 internal_error(state, 0,
13676 "state->main_function is not at the end of the function list ");
13678 state->main_function->u.cval = 1;
13679 reverse_walk_functions(state, mark_live, 0);
13682 static int local_triple(struct compile_state *state,
13683 struct triple *func, struct triple *ins)
13685 int local = (ins->id & TRIPLE_FLAG_LOCAL);
13688 FILE *fp = state->errout;
13689 fprintf(fp, "global: ");
13690 display_triple(fp, ins);
13696 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
13697 struct occurance *base_occurance)
13699 struct triple *nfunc;
13700 struct triple *nfirst, *ofirst;
13701 struct triple *new, *old;
13703 if (state->compiler->debug & DEBUG_INLINE) {
13704 FILE *fp = state->dbgout;
13707 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13708 display_func(state, fp, ofunc);
13709 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13712 /* Make a new copy of the old function */
13713 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13715 ofirst = old = RHS(ofunc, 0);
13717 struct triple *new;
13718 struct occurance *occurance;
13719 int old_lhs, old_rhs;
13720 old_lhs = old->lhs;
13721 old_rhs = old->rhs;
13722 occurance = inline_occurance(state, base_occurance, old->occurance);
13723 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13724 MISC(old, 0)->u.cval += 1;
13726 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13728 if (!triple_stores_block(state, new)) {
13729 memcpy(&new->u, &old->u, sizeof(new->u));
13732 RHS(nfunc, 0) = nfirst = new;
13735 insert_triple(state, nfirst, new);
13737 new->id |= TRIPLE_FLAG_FLATTENED;
13738 new->id |= old->id & TRIPLE_FLAG_COPY;
13740 /* During the copy remember new as user of old */
13741 use_triple(old, new);
13743 /* Remember which instructions are local */
13744 old->id |= TRIPLE_FLAG_LOCAL;
13746 } while(old != ofirst);
13748 /* Make a second pass to fix up any unresolved references */
13752 struct triple **oexpr, **nexpr;
13754 /* Lookup where the copy is, to join pointers */
13755 count = TRIPLE_SIZE(old);
13756 for(i = 0; i < count; i++) {
13757 oexpr = &old->param[i];
13758 nexpr = &new->param[i];
13759 if (*oexpr && !*nexpr) {
13760 if (!local_triple(state, ofunc, *oexpr)) {
13763 else if ((*oexpr)->use) {
13764 *nexpr = (*oexpr)->use->member;
13766 if (*nexpr == old) {
13767 internal_error(state, 0, "new == old?");
13769 use_triple(*nexpr, new);
13771 if (!*nexpr && *oexpr) {
13772 internal_error(state, 0, "Could not copy %d", i);
13777 } while((old != ofirst) && (new != nfirst));
13779 /* Make a third pass to cleanup the extra useses */
13783 unuse_triple(old, new);
13784 /* Forget which instructions are local */
13785 old->id &= ~TRIPLE_FLAG_LOCAL;
13788 } while ((old != ofirst) && (new != nfirst));
13792 static void expand_inline_call(
13793 struct compile_state *state, struct triple *me, struct triple *fcall)
13795 /* Inline the function call */
13796 struct type *ptype;
13797 struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13798 struct triple *end, *nend;
13801 /* Find the triples */
13802 ofunc = MISC(fcall, 0);
13803 if (ofunc->op != OP_LIST) {
13804 internal_error(state, 0, "improper function");
13806 nfunc = copy_func(state, ofunc, fcall->occurance);
13807 /* Prepend the parameter reading into the new function list */
13808 ptype = nfunc->type->right;
13809 pvals = fcall->rhs;
13810 for(i = 0; i < pvals; i++) {
13811 struct type *atype;
13812 struct triple *arg, *param;
13814 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13815 atype = ptype->left;
13817 param = farg(state, nfunc, i);
13818 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13819 internal_error(state, fcall, "param %d type mismatch", i);
13821 arg = RHS(fcall, i);
13822 flatten(state, fcall, write_expr(state, param, arg));
13823 ptype = ptype->right;
13826 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13827 result = read_expr(state,
13828 deref_index(state, fresult(state, nfunc), 1));
13830 if (state->compiler->debug & DEBUG_INLINE) {
13831 FILE *fp = state->dbgout;
13834 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13835 display_func(state, fp, nfunc);
13836 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13840 * Get rid of the extra triples
13842 /* Remove the read of the return address */
13843 ins = RHS(nfunc, 0)->prev->prev;
13844 if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13845 internal_error(state, ins, "Not return addres read?");
13847 release_triple(state, ins);
13848 /* Remove the return instruction */
13849 ins = RHS(nfunc, 0)->prev;
13850 if (ins->op != OP_RET) {
13851 internal_error(state, ins, "Not return?");
13853 release_triple(state, ins);
13854 /* Remove the retaddres variable */
13855 retvar = fretaddr(state, nfunc);
13856 if ((retvar->lhs != 1) ||
13857 (retvar->op != OP_ADECL) ||
13858 (retvar->next->op != OP_PIECE) ||
13859 (MISC(retvar->next, 0) != retvar)) {
13860 internal_error(state, retvar, "Not the return address?");
13862 release_triple(state, retvar->next);
13863 release_triple(state, retvar);
13865 /* Remove the label at the start of the function */
13866 ins = RHS(nfunc, 0);
13867 if (ins->op != OP_LABEL) {
13868 internal_error(state, ins, "Not label?");
13870 nfirst = ins->next;
13871 free_triple(state, ins);
13872 /* Release the new function header */
13874 free_triple(state, nfunc);
13876 /* Append the new function list onto the return list */
13878 nend = nfirst->prev;
13879 end->next = nfirst;
13880 nfirst->prev = end;
13881 nend->next = fcall;
13882 fcall->prev = nend;
13884 /* Now the result reading code */
13886 result = flatten(state, fcall, result);
13887 propogate_use(state, fcall, result);
13890 /* Release the original fcall instruction */
13891 release_triple(state, fcall);
13898 * Type of the result variable.
13902 * +----------+------------+
13904 * union of closures result_type
13906 * +------------------+---------------+
13908 * closure1 ... closuerN
13910 * +----+--+-+--------+-----+ +----+----+---+-----+
13911 * | | | | | | | | |
13912 * var1 var2 var3 ... varN result var1 var2 ... varN result
13914 * +--------+---------+
13916 * union of closures result_type
13918 * +-----+-------------------+
13920 * closure1 ... closureN
13922 * +-----+---+----+----+ +----+---+----+-----+
13924 * var1 var2 ... varN result var1 var2 ... varN result
13927 static int add_closure_type(struct compile_state *state,
13928 struct triple *func, struct type *closure_type)
13930 struct type *type, *ctype, **next;
13931 struct triple *var, *new_var;
13935 FILE *fp = state->errout;
13936 fprintf(fp, "original_type: ");
13937 name_of(fp, fresult(state, func)->type);
13940 /* find the original type */
13941 var = fresult(state, func);
13943 if (type->elements != 2) {
13944 internal_error(state, var, "bad return type");
13947 /* Find the complete closure type and update it */
13948 ctype = type->left->left;
13949 next = &ctype->left;
13950 while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13951 next = &(*next)->right;
13953 *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13954 ctype->elements += 1;
13957 fprintf(fp, "new_type: ");
13960 fprintf(fp, "ctype: %p %d bits: %d ",
13961 ctype, ctype->elements, reg_size_of(state, ctype));
13962 name_of(fp, ctype);
13966 /* Regenerate the variable with the new type definition */
13967 new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13968 new_var->id |= TRIPLE_FLAG_FLATTENED;
13969 for(i = 0; i < new_var->lhs; i++) {
13970 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13973 /* Point everyone at the new variable */
13974 propogate_use(state, var, new_var);
13976 /* Release the original variable */
13977 for(i = 0; i < var->lhs; i++) {
13978 release_triple(state, LHS(var, i));
13980 release_triple(state, var);
13982 /* Return the index of the added closure type */
13983 return ctype->elements - 1;
13986 static struct triple *closure_expr(struct compile_state *state,
13987 struct triple *func, int closure_idx, int var_idx)
13989 return deref_index(state,
13991 deref_index(state, fresult(state, func), 0),
13997 static void insert_triple_set(
13998 struct triple_reg_set **head, struct triple *member)
14000 struct triple_reg_set *new;
14001 new = xcmalloc(sizeof(*new), "triple_set");
14002 new->member = member;
14008 static int ordered_triple_set(
14009 struct triple_reg_set **head, struct triple *member)
14011 struct triple_reg_set **ptr;
14016 if (member == (*ptr)->member) {
14019 /* keep the list ordered */
14020 if (member->id < (*ptr)->member->id) {
14023 ptr = &(*ptr)->next;
14025 insert_triple_set(ptr, member);
14030 static void free_closure_variables(struct compile_state *state,
14031 struct triple_reg_set **enclose)
14033 struct triple_reg_set *entry, *next;
14034 for(entry = *enclose; entry; entry = next) {
14035 next = entry->next;
14036 do_triple_unset(enclose, entry->member);
14040 static int lookup_closure_index(struct compile_state *state,
14041 struct triple *me, struct triple *val)
14043 struct triple *first, *ins, *next;
14044 first = RHS(me, 0);
14045 ins = next = first;
14047 struct triple *result;
14048 struct triple *index0, *index1, *index2, *read, *write;
14051 if (ins->op != OP_CALL) {
14054 /* I am at a previous call point examine it closely */
14055 if (ins->next->op != OP_LABEL) {
14056 internal_error(state, ins, "call not followed by label");
14058 /* Does this call does not enclose any variables? */
14059 if ((ins->next->next->op != OP_INDEX) ||
14060 (ins->next->next->u.cval != 0) ||
14061 (result = MISC(ins->next->next, 0)) ||
14062 (result->id & TRIPLE_FLAG_LOCAL)) {
14065 index0 = ins->next->next;
14067 * 0 index result < 0 >
14073 for(index0 = ins->next->next;
14074 (index0->op == OP_INDEX) &&
14075 (MISC(index0, 0) == result) &&
14076 (index0->u.cval == 0) ;
14077 index0 = write->next)
14079 index1 = index0->next;
14080 index2 = index1->next;
14081 read = index2->next;
14082 write = read->next;
14083 if ((index0->op != OP_INDEX) ||
14084 (index1->op != OP_INDEX) ||
14085 (index2->op != OP_INDEX) ||
14086 (read->op != OP_READ) ||
14087 (write->op != OP_WRITE) ||
14088 (MISC(index1, 0) != index0) ||
14089 (MISC(index2, 0) != index1) ||
14090 (RHS(read, 0) != index2) ||
14091 (RHS(write, 0) != read)) {
14092 internal_error(state, index0, "bad var read");
14094 if (MISC(write, 0) == val) {
14095 return index2->u.cval;
14098 } while(next != first);
14102 static inline int enclose_triple(struct triple *ins)
14104 return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14107 static void compute_closure_variables(struct compile_state *state,
14108 struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14110 struct triple_reg_set *set, *vars, **last_var;
14111 struct basic_blocks bb;
14112 struct reg_block *rb;
14113 struct block *block;
14114 struct triple *old_result, *first, *ins;
14116 unsigned long used_indicies;
14118 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14119 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14126 /* Find the basic blocks of this function */
14128 bb.first = RHS(me, 0);
14130 if (!triple_is_ret(state, bb.first->prev)) {
14133 old_result = fresult(state, me);
14135 analyze_basic_blocks(state, &bb);
14137 /* Find which variables are currently alive in a given block */
14138 rb = compute_variable_lifetimes(state, &bb);
14140 /* Find the variables that are currently alive */
14141 block = block_of_triple(state, fcall);
14142 if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14143 internal_error(state, fcall, "No reg block? block: %p", block);
14146 #if DEBUG_EXPLICIT_CLOSURES
14147 print_live_variables(state, &bb, rb, state->dbgout);
14148 fflush(state->dbgout);
14151 /* Count the number of triples in the function */
14152 first = RHS(me, 0);
14158 } while(ins != first);
14160 /* Allocate some memory to temorary hold the id info */
14161 info = xcmalloc(sizeof(*info) * (count +1), "info");
14163 /* Mark the local function */
14164 first = RHS(me, 0);
14168 info[idx].id = ins->id;
14169 ins->id = TRIPLE_FLAG_LOCAL | idx;
14172 } while(ins != first);
14175 * Build the list of variables to enclose.
14177 * A target it to put the same variable in the
14178 * same slot for ever call of a given function.
14179 * After coloring this removes all of the variable
14180 * manipulation code.
14182 * The list of variables to enclose is built ordered
14183 * program order because except in corner cases this
14184 * gives me the stability of assignment I need.
14186 * To gurantee that stability I lookup the variables
14187 * to see where they have been used before and
14188 * I build my final list with the assigned indicies.
14191 if (enclose_triple(old_result)) {
14192 ordered_triple_set(&vars, old_result);
14194 for(set = rb[block->vertex].out; set; set = set->next) {
14195 if (!enclose_triple(set->member)) {
14198 if ((set->member == fcall) || (set->member == old_result)) {
14201 if (!local_triple(state, me, set->member)) {
14202 internal_error(state, set->member, "not local?");
14204 ordered_triple_set(&vars, set->member);
14207 /* Lookup the current indicies of the live varialbe */
14210 for(set = vars; set ; set = set->next) {
14211 struct triple *ins;
14214 index = lookup_closure_index(state, me, ins);
14215 info[ID_BITS(ins->id)].index = index;
14219 if (index >= MAX_INDICIES) {
14220 internal_error(state, ins, "index unexpectedly large");
14222 if (used_indicies & (1 << index)) {
14223 internal_error(state, ins, "index previously used?");
14225 /* Remember which indicies have been used */
14226 used_indicies |= (1 << index);
14227 if (index > max_index) {
14232 /* Walk through the live variables and make certain
14233 * everything is assigned an index.
14235 for(set = vars; set; set = set->next) {
14236 struct triple *ins;
14239 index = info[ID_BITS(ins->id)].index;
14243 /* Find the lowest unused index value */
14244 for(index = 0; index < MAX_INDICIES; index++) {
14245 if (!(used_indicies & (1 << index))) {
14249 if (index == MAX_INDICIES) {
14250 internal_error(state, ins, "no free indicies?");
14252 info[ID_BITS(ins->id)].index = index;
14253 /* Remember which indicies have been used */
14254 used_indicies |= (1 << index);
14255 if (index > max_index) {
14260 /* Build the return list of variables with positions matching
14264 last_var = enclose;
14265 for(i = 0; i <= max_index; i++) {
14266 struct triple *var;
14268 if (used_indicies & (1 << i)) {
14269 for(set = vars; set; set = set->next) {
14271 index = info[ID_BITS(set->member->id)].index;
14278 internal_error(state, me, "missing variable");
14281 insert_triple_set(last_var, var);
14282 last_var = &(*last_var)->next;
14285 #if DEBUG_EXPLICIT_CLOSURES
14286 /* Print out the variables to be enclosed */
14287 loc(state->dbgout, state, fcall);
14288 fprintf(state->dbgout, "Alive: \n");
14289 for(set = *enclose; set; set = set->next) {
14290 display_triple(state->dbgout, set->member);
14292 fflush(state->dbgout);
14295 /* Clear the marks */
14298 ins->id = info[ID_BITS(ins->id)].id;
14300 } while(ins != first);
14302 /* Release the ordered list of live variables */
14303 free_closure_variables(state, &vars);
14305 /* Release the storage of the old ids */
14308 /* Release the variable lifetime information */
14309 free_variable_lifetimes(state, &bb, rb);
14311 /* Release the basic blocks of this function */
14312 free_basic_blocks(state, &bb);
14315 static void expand_function_call(
14316 struct compile_state *state, struct triple *me, struct triple *fcall)
14318 /* Generate an ordinary function call */
14319 struct type *closure_type, **closure_next;
14320 struct triple *func, *func_first, *func_last, *retvar;
14321 struct triple *first;
14322 struct type *ptype, *rtype;
14323 struct triple *ret_addr, *ret_loc;
14324 struct triple_reg_set *enclose, *set;
14325 int closure_idx, pvals, i;
14327 #if DEBUG_EXPLICIT_CLOSURES
14328 FILE *fp = state->dbgout;
14329 fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14330 display_func(state, fp, MISC(fcall, 0));
14331 display_func(state, fp, me);
14332 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14335 /* Find the triples */
14336 func = MISC(fcall, 0);
14337 func_first = RHS(func, 0);
14338 retvar = fretaddr(state, func);
14339 func_last = func_first->prev;
14340 first = fcall->next;
14342 /* Find what I need to enclose */
14343 compute_closure_variables(state, me, fcall, &enclose);
14345 /* Compute the closure type */
14346 closure_type = new_type(TYPE_TUPLE, 0, 0);
14347 closure_type->elements = 0;
14348 closure_next = &closure_type->left;
14349 for(set = enclose; set ; set = set->next) {
14353 type = set->member->type;
14355 if (!*closure_next) {
14356 *closure_next = type;
14358 *closure_next = new_type(TYPE_PRODUCT, *closure_next,
14360 closure_next = &(*closure_next)->right;
14362 closure_type->elements += 1;
14364 if (closure_type->elements == 0) {
14365 closure_type->type = TYPE_VOID;
14369 #if DEBUG_EXPLICIT_CLOSURES
14370 fprintf(state->dbgout, "closure type: ");
14371 name_of(state->dbgout, closure_type);
14372 fprintf(state->dbgout, "\n");
14375 /* Update the called functions closure variable */
14376 closure_idx = add_closure_type(state, func, closure_type);
14378 /* Generate some needed triples */
14379 ret_loc = label(state);
14380 ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14382 /* Pass the parameters to the new function */
14383 ptype = func->type->right;
14384 pvals = fcall->rhs;
14385 for(i = 0; i < pvals; i++) {
14386 struct type *atype;
14387 struct triple *arg, *param;
14389 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14390 atype = ptype->left;
14392 param = farg(state, func, i);
14393 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14394 internal_error(state, fcall, "param type mismatch");
14396 arg = RHS(fcall, i);
14397 flatten(state, first, write_expr(state, param, arg));
14398 ptype = ptype->right;
14400 rtype = func->type->left;
14402 /* Thread the triples together */
14403 ret_loc = flatten(state, first, ret_loc);
14405 /* Save the active variables in the result variable */
14406 for(i = 0, set = enclose; set ; set = set->next, i++) {
14407 if (!set->member) {
14410 flatten(state, ret_loc,
14412 closure_expr(state, func, closure_idx, i),
14413 read_expr(state, set->member)));
14416 /* Initialize the return value */
14417 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14418 flatten(state, ret_loc,
14420 deref_index(state, fresult(state, func), 1),
14421 new_triple(state, OP_UNKNOWNVAL, rtype, 0, 0)));
14424 ret_addr = flatten(state, ret_loc, ret_addr);
14425 flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14426 flatten(state, ret_loc,
14427 call(state, retvar, ret_addr, func_first, func_last));
14429 /* Find the result */
14430 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14431 struct triple * result;
14432 result = flatten(state, first,
14434 deref_index(state, fresult(state, func), 1)));
14436 propogate_use(state, fcall, result);
14439 /* Release the original fcall instruction */
14440 release_triple(state, fcall);
14442 /* Restore the active variables from the result variable */
14443 for(i = 0, set = enclose; set ; set = set->next, i++) {
14444 struct triple_set *use, *next;
14445 struct triple *new;
14446 struct basic_blocks bb;
14447 if (!set->member || (set->member == fcall)) {
14450 /* Generate an expression for the value */
14451 new = flatten(state, first,
14453 closure_expr(state, func, closure_idx, i)));
14456 /* If the original is an lvalue restore the preserved value */
14457 if (is_lvalue(state, set->member)) {
14458 flatten(state, first,
14459 write_expr(state, set->member, new));
14463 * If the original is a value update the dominated uses.
14466 /* Analyze the basic blocks so I can see who dominates whom */
14468 bb.first = RHS(me, 0);
14469 if (!triple_is_ret(state, bb.first->prev)) {
14472 analyze_basic_blocks(state, &bb);
14475 #if DEBUG_EXPLICIT_CLOSURES
14476 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14479 /* If fcall dominates the use update the expression */
14480 for(use = set->member->use; use; use = next) {
14481 /* Replace use modifies the use chain and
14482 * removes use, so I must take a copy of the
14483 * next entry early.
14486 if (!tdominates(state, fcall, use->member)) {
14489 replace_use(state, set->member, new, use->member);
14492 /* Release the basic blocks, the instructions will be
14493 * different next time, and flatten/insert_triple does
14494 * not update the block values so I can't cache the analysis.
14496 free_basic_blocks(state, &bb);
14499 /* Release the closure variable list */
14500 free_closure_variables(state, &enclose);
14502 if (state->compiler->debug & DEBUG_INLINE) {
14503 FILE *fp = state->dbgout;
14506 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14507 display_func(state, fp, func);
14508 display_func(state, fp, me);
14509 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14515 static int do_inline(struct compile_state *state, struct triple *func)
14520 policy = state->compiler->flags & COMPILER_INLINE_MASK;
14522 case COMPILER_INLINE_ALWAYS:
14524 if (func->type->type & ATTRIB_NOINLINE) {
14525 error(state, func, "noinline with always_inline compiler option");
14528 case COMPILER_INLINE_NEVER:
14530 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14531 error(state, func, "always_inline with noinline compiler option");
14534 case COMPILER_INLINE_DEFAULTON:
14535 switch(func->type->type & STOR_MASK) {
14536 case STOR_STATIC | STOR_INLINE:
14537 case STOR_LOCAL | STOR_INLINE:
14538 case STOR_EXTERN | STOR_INLINE:
14546 case COMPILER_INLINE_DEFAULTOFF:
14547 switch(func->type->type & STOR_MASK) {
14548 case STOR_STATIC | STOR_INLINE:
14549 case STOR_LOCAL | STOR_INLINE:
14550 case STOR_EXTERN | STOR_INLINE:
14558 case COMPILER_INLINE_NOPENALTY:
14559 switch(func->type->type & STOR_MASK) {
14560 case STOR_STATIC | STOR_INLINE:
14561 case STOR_LOCAL | STOR_INLINE:
14562 case STOR_EXTERN | STOR_INLINE:
14566 do_inline = (func->u.cval == 1);
14572 internal_error(state, 0, "Unimplemented inline policy");
14575 /* Force inlining */
14576 if (func->type->type & ATTRIB_NOINLINE) {
14579 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14585 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14587 struct triple *first, *ptr, *next;
14588 /* If the function is not used don't bother */
14589 if (me->u.cval <= 0) {
14592 if (state->compiler->debug & DEBUG_CALLS2) {
14593 FILE *fp = state->dbgout;
14594 fprintf(fp, "in: %s\n",
14595 me->type->type_ident->name);
14598 first = RHS(me, 0);
14599 ptr = next = first;
14601 struct triple *func, *prev;
14605 if (ptr->op != OP_FCALL) {
14608 func = MISC(ptr, 0);
14609 /* See if the function should be inlined */
14610 if (!do_inline(state, func)) {
14611 /* Put a label after the fcall */
14612 post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14615 if (state->compiler->debug & DEBUG_CALLS) {
14616 FILE *fp = state->dbgout;
14617 if (state->compiler->debug & DEBUG_CALLS2) {
14618 loc(fp, state, ptr);
14620 fprintf(fp, "inlining %s\n",
14621 func->type->type_ident->name);
14625 /* Update the function use counts */
14628 /* Replace the fcall with the called function */
14629 expand_inline_call(state, me, ptr);
14632 } while (next != first);
14634 ptr = next = first;
14636 struct triple *prev, *func;
14640 if (ptr->op != OP_FCALL) {
14643 func = MISC(ptr, 0);
14644 if (state->compiler->debug & DEBUG_CALLS) {
14645 FILE *fp = state->dbgout;
14646 if (state->compiler->debug & DEBUG_CALLS2) {
14647 loc(fp, state, ptr);
14649 fprintf(fp, "calling %s\n",
14650 func->type->type_ident->name);
14653 /* Replace the fcall with the instruction sequence
14654 * needed to make the call.
14656 expand_function_call(state, me, ptr);
14658 } while(next != first);
14661 static void inline_functions(struct compile_state *state, struct triple *func)
14663 inline_function(state, func, 0);
14664 reverse_walk_functions(state, inline_function, 0);
14667 static void insert_function(struct compile_state *state,
14668 struct triple *func, void *arg)
14670 struct triple *first, *end, *ffirst, *fend;
14672 if (state->compiler->debug & DEBUG_INLINE) {
14673 FILE *fp = state->errout;
14674 fprintf(fp, "%s func count: %d\n",
14675 func->type->type_ident->name, func->u.cval);
14677 if (func->u.cval == 0) {
14681 /* Find the end points of the lists */
14684 ffirst = RHS(func, 0);
14685 fend = ffirst->prev;
14687 /* splice the lists together */
14688 end->next = ffirst;
14689 ffirst->prev = end;
14690 fend->next = first;
14691 first->prev = fend;
14694 struct triple *input_asm(struct compile_state *state)
14696 struct asm_info *info;
14697 struct triple *def;
14700 info = xcmalloc(sizeof(*info), "asm_info");
14703 out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14704 memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14706 def = new_triple(state, OP_ASM, &void_type, out, 0);
14707 def->u.ainfo = info;
14708 def->id |= TRIPLE_FLAG_VOLATILE;
14710 for(i = 0; i < out; i++) {
14711 struct triple *piece;
14712 piece = triple(state, OP_PIECE, &int_type, def, 0);
14714 LHS(def, i) = piece;
14720 struct triple *output_asm(struct compile_state *state)
14722 struct asm_info *info;
14723 struct triple *def;
14726 info = xcmalloc(sizeof(*info), "asm_info");
14729 in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14730 memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14732 def = new_triple(state, OP_ASM, &void_type, 0, in);
14733 def->u.ainfo = info;
14734 def->id |= TRIPLE_FLAG_VOLATILE;
14739 static void join_functions(struct compile_state *state)
14741 struct triple *start, *end, *call, *in, *out, *func;
14742 struct file_state file;
14743 struct type *pnext, *param;
14744 struct type *result_type, *args_type;
14747 /* Be clear the functions have not been joined yet */
14748 state->functions_joined = 0;
14750 /* Dummy file state to get debug handing right */
14751 memset(&file, 0, sizeof(file));
14752 file.basename = "";
14754 file.report_line = 0;
14755 file.report_name = file.basename;
14756 file.prev = state->file;
14757 state->file = &file;
14758 state->function = "";
14760 if (!state->main_function) {
14761 error(state, 0, "No functions to compile\n");
14764 /* The type of arguments */
14765 args_type = state->main_function->type->right;
14766 /* The return type without any specifiers */
14767 result_type = clone_type(0, state->main_function->type->left);
14770 /* Verify the external arguments */
14771 if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14772 error(state, state->main_function,
14773 "Too many external input arguments");
14775 if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14776 error(state, state->main_function,
14777 "Too many external output arguments");
14780 /* Lay down the basic program structure */
14781 end = label(state);
14782 start = label(state);
14783 start = flatten(state, state->first, start);
14784 end = flatten(state, state->first, end);
14785 in = input_asm(state);
14786 out = output_asm(state);
14787 call = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14788 MISC(call, 0) = state->main_function;
14789 in = flatten(state, state->first, in);
14790 call = flatten(state, state->first, call);
14791 out = flatten(state, state->first, out);
14794 /* Read the external input arguments */
14797 while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14798 struct triple *expr;
14801 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14802 pnext = param->right;
14803 param = param->left;
14805 if (registers_of(state, param) != 1) {
14806 error(state, state->main_function,
14807 "Arg: %d %s requires multiple registers",
14808 idx + 1, param->field_ident->name);
14810 expr = read_expr(state, LHS(in, idx));
14811 RHS(call, idx) = expr;
14812 expr = flatten(state, call, expr);
14813 use_triple(expr, call);
14819 /* Write the external output arguments */
14820 pnext = result_type;
14821 if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14822 pnext = result_type->left;
14824 for(idx = 0; idx < out->rhs; idx++) {
14825 struct triple *expr;
14828 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14829 pnext = param->right;
14830 param = param->left;
14832 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14836 if (registers_of(state, param) != 1) {
14837 error(state, state->main_function,
14838 "Result: %d %s requires multiple registers",
14839 idx, param->field_ident->name);
14841 expr = read_expr(state, call);
14842 if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14843 expr = deref_field(state, expr, param->field_ident);
14846 expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14848 flatten(state, out, expr);
14849 RHS(out, idx) = expr;
14850 use_triple(expr, out);
14853 /* Allocate a dummy containing function */
14854 func = triple(state, OP_LIST,
14855 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14856 func->type->type_ident = lookup(state, "", 0);
14857 RHS(func, 0) = state->first;
14860 /* See which functions are called, and how often */
14861 mark_live_functions(state);
14862 inline_functions(state, func);
14863 walk_functions(state, insert_function, end);
14865 if (start->next != end) {
14866 flatten(state, start, branch(state, end, 0));
14869 /* OK now the functions have been joined. */
14870 state->functions_joined = 1;
14872 /* Done now cleanup */
14873 state->file = file.prev;
14874 state->function = 0;
14878 * Data structurs for optimation.
14882 static int do_use_block(
14883 struct block *used, struct block_set **head, struct block *user,
14886 struct block_set **ptr, *new;
14893 if ((*ptr)->member == user) {
14896 ptr = &(*ptr)->next;
14898 new = xcmalloc(sizeof(*new), "block_set");
14899 new->member = user;
14910 static int do_unuse_block(
14911 struct block *used, struct block_set **head, struct block *unuser)
14913 struct block_set *use, **ptr;
14919 if (use->member == unuser) {
14921 memset(use, -1, sizeof(*use));
14932 static void use_block(struct block *used, struct block *user)
14935 /* Append new to the head of the list, print_block
14938 count = do_use_block(used, &used->use, user, 1);
14939 used->users += count;
14941 static void unuse_block(struct block *used, struct block *unuser)
14944 count = do_unuse_block(used, &used->use, unuser);
14945 used->users -= count;
14948 static void add_block_edge(struct block *block, struct block *edge, int front)
14951 count = do_use_block(block, &block->edges, edge, front);
14952 block->edge_count += count;
14955 static void remove_block_edge(struct block *block, struct block *edge)
14958 count = do_unuse_block(block, &block->edges, edge);
14959 block->edge_count -= count;
14962 static void idom_block(struct block *idom, struct block *user)
14964 do_use_block(idom, &idom->idominates, user, 0);
14967 static void unidom_block(struct block *idom, struct block *unuser)
14969 do_unuse_block(idom, &idom->idominates, unuser);
14972 static void domf_block(struct block *block, struct block *domf)
14974 do_use_block(block, &block->domfrontier, domf, 0);
14977 static void undomf_block(struct block *block, struct block *undomf)
14979 do_unuse_block(block, &block->domfrontier, undomf);
14982 static void ipdom_block(struct block *ipdom, struct block *user)
14984 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14987 static void unipdom_block(struct block *ipdom, struct block *unuser)
14989 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14992 static void ipdomf_block(struct block *block, struct block *ipdomf)
14994 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
14997 static void unipdomf_block(struct block *block, struct block *unipdomf)
14999 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
15002 static int walk_triples(
15003 struct compile_state *state,
15004 int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
15007 struct triple *ptr;
15009 ptr = state->first;
15011 result = cb(state, ptr, arg);
15012 if (ptr->next->prev != ptr) {
15013 internal_error(state, ptr->next, "bad prev");
15016 } while((result == 0) && (ptr != state->first));
15020 #define PRINT_LIST 1
15021 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
15026 if (op == OP_LIST) {
15031 if ((op == OP_LABEL) && (ins->use)) {
15032 fprintf(fp, "\n%p:\n", ins);
15034 display_triple(fp, ins);
15036 if (triple_is_branch(state, ins) && ins->use &&
15037 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
15038 internal_error(state, ins, "branch used?");
15040 if (triple_is_branch(state, ins)) {
15046 static void print_triples(struct compile_state *state)
15048 if (state->compiler->debug & DEBUG_TRIPLES) {
15049 FILE *fp = state->dbgout;
15050 fprintf(fp, "--------------- triples ---------------\n");
15051 walk_triples(state, do_print_triple, fp);
15057 struct block *block;
15059 static void find_cf_blocks(struct cf_block *cf, struct block *block)
15061 struct block_set *edge;
15062 if (!block || (cf[block->vertex].block == block)) {
15065 cf[block->vertex].block = block;
15066 for(edge = block->edges; edge; edge = edge->next) {
15067 find_cf_blocks(cf, edge->member);
15071 static void print_control_flow(struct compile_state *state,
15072 FILE *fp, struct basic_blocks *bb)
15074 struct cf_block *cf;
15076 fprintf(fp, "\ncontrol flow\n");
15077 cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15078 find_cf_blocks(cf, bb->first_block);
15080 for(i = 1; i <= bb->last_vertex; i++) {
15081 struct block *block;
15082 struct block_set *edge;
15083 block = cf[i].block;
15086 fprintf(fp, "(%p) %d:", block, block->vertex);
15087 for(edge = block->edges; edge; edge = edge->next) {
15088 fprintf(fp, " %d", edge->member->vertex);
15096 static void free_basic_block(struct compile_state *state, struct block *block)
15098 struct block_set *edge, *entry;
15099 struct block *child;
15103 if (block->vertex == -1) {
15106 block->vertex = -1;
15107 for(edge = block->edges; edge; edge = edge->next) {
15108 if (edge->member) {
15109 unuse_block(edge->member, block);
15113 unidom_block(block->idom, block);
15116 if (block->ipdom) {
15117 unipdom_block(block->ipdom, block);
15120 while((entry = block->use)) {
15121 child = entry->member;
15122 unuse_block(block, child);
15123 if (child && (child->vertex != -1)) {
15124 for(edge = child->edges; edge; edge = edge->next) {
15129 while((entry = block->idominates)) {
15130 child = entry->member;
15131 unidom_block(block, child);
15132 if (child && (child->vertex != -1)) {
15136 while((entry = block->domfrontier)) {
15137 child = entry->member;
15138 undomf_block(block, child);
15140 while((entry = block->ipdominates)) {
15141 child = entry->member;
15142 unipdom_block(block, child);
15143 if (child && (child->vertex != -1)) {
15147 while((entry = block->ipdomfrontier)) {
15148 child = entry->member;
15149 unipdomf_block(block, child);
15151 if (block->users != 0) {
15152 internal_error(state, 0, "block still has users");
15154 while((edge = block->edges)) {
15155 child = edge->member;
15156 remove_block_edge(block, child);
15158 if (child && (child->vertex != -1)) {
15159 free_basic_block(state, child);
15162 memset(block, -1, sizeof(*block));
15168 static void free_basic_blocks(struct compile_state *state,
15169 struct basic_blocks *bb)
15171 struct triple *first, *ins;
15172 free_basic_block(state, bb->first_block);
15173 bb->last_vertex = 0;
15174 bb->first_block = bb->last_block = 0;
15178 if (triple_stores_block(state, ins)) {
15182 } while(ins != first);
15186 static struct block *basic_block(struct compile_state *state,
15187 struct basic_blocks *bb, struct triple *first)
15189 struct block *block;
15190 struct triple *ptr;
15191 if (!triple_is_label(state, first)) {
15192 internal_error(state, first, "block does not start with a label");
15194 /* See if this basic block has already been setup */
15195 if (first->u.block != 0) {
15196 return first->u.block;
15198 /* Allocate another basic block structure */
15199 bb->last_vertex += 1;
15200 block = xcmalloc(sizeof(*block), "block");
15201 block->first = block->last = first;
15202 block->vertex = bb->last_vertex;
15205 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) {
15209 /* If ptr->u is not used remember where the baic block is */
15210 if (triple_stores_block(state, ptr)) {
15211 ptr->u.block = block;
15213 if (triple_is_branch(state, ptr)) {
15217 } while (ptr != bb->first);
15218 if ((ptr == bb->first) ||
15219 ((ptr->next == bb->first) && (
15220 triple_is_end(state, ptr) ||
15221 triple_is_ret(state, ptr))))
15223 /* The block has no outflowing edges */
15225 else if (triple_is_label(state, ptr)) {
15226 struct block *next;
15227 next = basic_block(state, bb, ptr);
15228 add_block_edge(block, next, 0);
15229 use_block(next, block);
15231 else if (triple_is_branch(state, ptr)) {
15232 struct triple **expr, *first;
15233 struct block *child;
15234 /* Find the branch targets.
15235 * I special case the first branch as that magically
15236 * avoids some difficult cases for the register allocator.
15238 expr = triple_edge_targ(state, ptr, 0);
15240 internal_error(state, ptr, "branch without targets");
15243 expr = triple_edge_targ(state, ptr, expr);
15244 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15245 if (!*expr) continue;
15246 child = basic_block(state, bb, *expr);
15247 use_block(child, block);
15248 add_block_edge(block, child, 0);
15251 child = basic_block(state, bb, first);
15252 use_block(child, block);
15253 add_block_edge(block, child, 1);
15255 /* Be certain the return block of a call is
15256 * in a basic block. When it is not find
15257 * start of the block, insert a label if
15258 * necessary and build the basic block.
15259 * Then add a fake edge from the start block
15260 * to the return block of the function.
15262 if (state->functions_joined && triple_is_call(state, ptr)
15263 && !block_of_triple(state, MISC(ptr, 0))) {
15264 struct block *tail;
15265 struct triple *start;
15266 start = triple_to_block_start(state, MISC(ptr, 0));
15267 if (!triple_is_label(state, start)) {
15268 start = pre_triple(state,
15269 start, OP_LABEL, &void_type, 0, 0);
15271 tail = basic_block(state, bb, start);
15272 add_block_edge(child, tail, 0);
15273 use_block(tail, child);
15278 internal_error(state, 0, "Bad basic block split");
15282 struct block_set *edge;
15283 FILE *fp = state->errout;
15284 fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15285 block, block->vertex,
15286 block->first, block->last);
15287 for(edge = block->edges; edge; edge = edge->next) {
15288 fprintf(fp, " %10p [%2d]",
15289 edge->member ? edge->member->first : 0,
15290 edge->member ? edge->member->vertex : -1);
15299 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15300 void (*cb)(struct compile_state *state, struct block *block, void *arg),
15303 struct triple *ptr, *first;
15304 struct block *last_block;
15309 if (triple_stores_block(state, ptr)) {
15310 struct block *block;
15311 block = ptr->u.block;
15312 if (block && (block != last_block)) {
15313 cb(state, block, arg);
15315 last_block = block;
15318 } while(ptr != first);
15321 static void print_block(
15322 struct compile_state *state, struct block *block, void *arg)
15324 struct block_set *user, *edge;
15325 struct triple *ptr;
15328 fprintf(fp, "\nblock: %p (%d) ",
15332 for(edge = block->edges; edge; edge = edge->next) {
15333 fprintf(fp, " %p<-%p",
15335 (edge->member && edge->member->use)?
15336 edge->member->use->member : 0);
15339 if (block->first->op == OP_LABEL) {
15340 fprintf(fp, "%p:\n", block->first);
15342 for(ptr = block->first; ; ) {
15343 display_triple(fp, ptr);
15344 if (ptr == block->last)
15347 if (ptr == block->first) {
15348 internal_error(state, 0, "missing block last?");
15351 fprintf(fp, "users %d: ", block->users);
15352 for(user = block->use; user; user = user->next) {
15353 fprintf(fp, "%p (%d) ",
15355 user->member->vertex);
15357 fprintf(fp,"\n\n");
15361 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15363 fprintf(fp, "--------------- blocks ---------------\n");
15364 walk_blocks(state, &state->bb, print_block, fp);
15366 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15368 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15369 fprintf(fp, "After %s\n", func);
15370 romcc_print_blocks(state, fp);
15371 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15372 print_dominators(state, fp, &state->bb);
15373 print_dominance_frontiers(state, fp, &state->bb);
15375 print_control_flow(state, fp, &state->bb);
15379 static void prune_nonblock_triples(struct compile_state *state,
15380 struct basic_blocks *bb)
15382 struct block *block;
15383 struct triple *first, *ins, *next;
15384 /* Delete the triples not in a basic block */
15390 if (ins->op == OP_LABEL) {
15391 block = ins->u.block;
15394 struct triple_set *use;
15395 for(use = ins->use; use; use = use->next) {
15396 struct block *block;
15397 block = block_of_triple(state, use->member);
15399 internal_error(state, ins, "pruning used ins?");
15402 release_triple(state, ins);
15404 if (block && block->last == ins) {
15408 } while(ins != first);
15411 static void setup_basic_blocks(struct compile_state *state,
15412 struct basic_blocks *bb)
15414 if (!triple_stores_block(state, bb->first)) {
15415 internal_error(state, 0, "ins will not store block?");
15417 /* Initialize the state */
15418 bb->first_block = bb->last_block = 0;
15419 bb->last_vertex = 0;
15420 free_basic_blocks(state, bb);
15422 /* Find the basic blocks */
15423 bb->first_block = basic_block(state, bb, bb->first);
15425 /* Be certain the last instruction of a function, or the
15426 * entire program is in a basic block. When it is not find
15427 * the start of the block, insert a label if necessary and build
15428 * basic block. Then add a fake edge from the start block
15429 * to the final block.
15431 if (!block_of_triple(state, bb->first->prev)) {
15432 struct triple *start;
15433 struct block *tail;
15434 start = triple_to_block_start(state, bb->first->prev);
15435 if (!triple_is_label(state, start)) {
15436 start = pre_triple(state,
15437 start, OP_LABEL, &void_type, 0, 0);
15439 tail = basic_block(state, bb, start);
15440 add_block_edge(bb->first_block, tail, 0);
15441 use_block(tail, bb->first_block);
15444 /* Find the last basic block.
15446 bb->last_block = block_of_triple(state, bb->first->prev);
15448 /* Delete the triples not in a basic block */
15449 prune_nonblock_triples(state, bb);
15452 /* If we are debugging print what I have just done */
15453 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15454 print_blocks(state, state->dbgout);
15455 print_control_flow(state, bb);
15461 struct sdom_block {
15462 struct block *block;
15463 struct sdom_block *sdominates;
15464 struct sdom_block *sdom_next;
15465 struct sdom_block *sdom;
15466 struct sdom_block *label;
15467 struct sdom_block *parent;
15468 struct sdom_block *ancestor;
15473 static void unsdom_block(struct sdom_block *block)
15475 struct sdom_block **ptr;
15476 if (!block->sdom_next) {
15479 ptr = &block->sdom->sdominates;
15481 if ((*ptr) == block) {
15482 *ptr = block->sdom_next;
15485 ptr = &(*ptr)->sdom_next;
15489 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15491 unsdom_block(block);
15492 block->sdom = sdom;
15493 block->sdom_next = sdom->sdominates;
15494 sdom->sdominates = block;
15499 static int initialize_sdblock(struct sdom_block *sd,
15500 struct block *parent, struct block *block, int vertex)
15502 struct block_set *edge;
15503 if (!block || (sd[block->vertex].block == block)) {
15507 /* Renumber the blocks in a convinient fashion */
15508 block->vertex = vertex;
15509 sd[vertex].block = block;
15510 sd[vertex].sdom = &sd[vertex];
15511 sd[vertex].label = &sd[vertex];
15512 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15513 sd[vertex].ancestor = 0;
15514 sd[vertex].vertex = vertex;
15515 for(edge = block->edges; edge; edge = edge->next) {
15516 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15521 static int initialize_spdblock(
15522 struct compile_state *state, struct sdom_block *sd,
15523 struct block *parent, struct block *block, int vertex)
15525 struct block_set *user;
15526 if (!block || (sd[block->vertex].block == block)) {
15530 /* Renumber the blocks in a convinient fashion */
15531 block->vertex = vertex;
15532 sd[vertex].block = block;
15533 sd[vertex].sdom = &sd[vertex];
15534 sd[vertex].label = &sd[vertex];
15535 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15536 sd[vertex].ancestor = 0;
15537 sd[vertex].vertex = vertex;
15538 for(user = block->use; user; user = user->next) {
15539 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15544 static int setup_spdblocks(struct compile_state *state,
15545 struct basic_blocks *bb, struct sdom_block *sd)
15547 struct block *block;
15549 /* Setup as many sdpblocks as possible without using fake edges */
15550 vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15552 /* Walk through the graph and find unconnected blocks. Add a
15553 * fake edge from the unconnected blocks to the end of the
15556 block = bb->first_block->last->next->u.block;
15557 for(; block && block != bb->first_block; block = block->last->next->u.block) {
15558 if (sd[block->vertex].block == block) {
15561 #if DEBUG_SDP_BLOCKS
15563 FILE *fp = state->errout;
15564 fprintf(fp, "Adding %d\n", vertex +1);
15567 add_block_edge(block, bb->last_block, 0);
15568 use_block(bb->last_block, block);
15570 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15575 static void compress_ancestors(struct sdom_block *v)
15577 /* This procedure assumes ancestor(v) != 0 */
15578 /* if (ancestor(ancestor(v)) != 0) {
15579 * compress(ancestor(ancestor(v)));
15580 * if (semi(label(ancestor(v))) < semi(label(v))) {
15581 * label(v) = label(ancestor(v));
15583 * ancestor(v) = ancestor(ancestor(v));
15586 if (!v->ancestor) {
15589 if (v->ancestor->ancestor) {
15590 compress_ancestors(v->ancestor->ancestor);
15591 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15592 v->label = v->ancestor->label;
15594 v->ancestor = v->ancestor->ancestor;
15598 static void compute_sdom(struct compile_state *state,
15599 struct basic_blocks *bb, struct sdom_block *sd)
15603 * for each v <= pred(w) {
15605 * if (semi[u] < semi[w] {
15606 * semi[w] = semi[u];
15609 * add w to bucket(vertex(semi[w]));
15610 * LINK(parent(w), w);
15613 * for each v <= bucket(parent(w)) {
15614 * delete v from bucket(parent(w));
15616 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15619 for(i = bb->last_vertex; i >= 2; i--) {
15620 struct sdom_block *v, *parent, *next;
15621 struct block_set *user;
15622 struct block *block;
15623 block = sd[i].block;
15624 parent = sd[i].parent;
15626 for(user = block->use; user; user = user->next) {
15627 struct sdom_block *v, *u;
15628 v = &sd[user->member->vertex];
15629 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15630 if (u->sdom->vertex < sd[i].sdom->vertex) {
15631 sd[i].sdom = u->sdom;
15634 sdom_block(sd[i].sdom, &sd[i]);
15635 sd[i].ancestor = parent;
15637 for(v = parent->sdominates; v; v = next) {
15638 struct sdom_block *u;
15639 next = v->sdom_next;
15641 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15642 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
15643 u->block : parent->block;
15648 static void compute_spdom(struct compile_state *state,
15649 struct basic_blocks *bb, struct sdom_block *sd)
15653 * for each v <= pred(w) {
15655 * if (semi[u] < semi[w] {
15656 * semi[w] = semi[u];
15659 * add w to bucket(vertex(semi[w]));
15660 * LINK(parent(w), w);
15663 * for each v <= bucket(parent(w)) {
15664 * delete v from bucket(parent(w));
15666 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15669 for(i = bb->last_vertex; i >= 2; i--) {
15670 struct sdom_block *u, *v, *parent, *next;
15671 struct block_set *edge;
15672 struct block *block;
15673 block = sd[i].block;
15674 parent = sd[i].parent;
15676 for(edge = block->edges; edge; edge = edge->next) {
15677 v = &sd[edge->member->vertex];
15678 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15679 if (u->sdom->vertex < sd[i].sdom->vertex) {
15680 sd[i].sdom = u->sdom;
15683 sdom_block(sd[i].sdom, &sd[i]);
15684 sd[i].ancestor = parent;
15686 for(v = parent->sdominates; v; v = next) {
15687 struct sdom_block *u;
15688 next = v->sdom_next;
15690 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15691 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
15692 u->block : parent->block;
15697 static void compute_idom(struct compile_state *state,
15698 struct basic_blocks *bb, struct sdom_block *sd)
15701 for(i = 2; i <= bb->last_vertex; i++) {
15702 struct block *block;
15703 block = sd[i].block;
15704 if (block->idom->vertex != sd[i].sdom->vertex) {
15705 block->idom = block->idom->idom;
15707 idom_block(block->idom, block);
15709 sd[1].block->idom = 0;
15712 static void compute_ipdom(struct compile_state *state,
15713 struct basic_blocks *bb, struct sdom_block *sd)
15716 for(i = 2; i <= bb->last_vertex; i++) {
15717 struct block *block;
15718 block = sd[i].block;
15719 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15720 block->ipdom = block->ipdom->ipdom;
15722 ipdom_block(block->ipdom, block);
15724 sd[1].block->ipdom = 0;
15728 * Every vertex of a flowgraph G = (V, E, r) except r has
15729 * a unique immediate dominator.
15730 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15731 * rooted at r, called the dominator tree of G, such that
15732 * v dominates w if and only if v is a proper ancestor of w in
15733 * the dominator tree.
15736 * If v and w are vertices of G such that v <= w,
15737 * than any path from v to w must contain a common ancestor
15740 /* Lemma 2: For any vertex w != r, idom(w) -> w */
15741 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
15742 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
15744 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
15745 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
15748 * Let w != r and let u be a vertex for which sdom(u) is
15749 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15750 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15752 /* Lemma 5: Let vertices v,w satisfy v -> w.
15753 * Then v -> idom(w) or idom(w) -> idom(v)
15756 static void find_immediate_dominators(struct compile_state *state,
15757 struct basic_blocks *bb)
15759 struct sdom_block *sd;
15760 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15761 * vi > w for (1 <= i <= k - 1}
15764 * For any vertex w != r.
15766 * {v|(v,w) <= E and v < w } U
15767 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15770 * Let w != r and let u be a vertex for which sdom(u) is
15771 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15773 * { sdom(w) if sdom(w) = sdom(u),
15775 * { idom(u) otherwise
15777 /* The algorithm consists of the following 4 steps.
15778 * Step 1. Carry out a depth-first search of the problem graph.
15779 * Number the vertices from 1 to N as they are reached during
15780 * the search. Initialize the variables used in succeeding steps.
15781 * Step 2. Compute the semidominators of all vertices by applying
15782 * theorem 4. Carry out the computation vertex by vertex in
15783 * decreasing order by number.
15784 * Step 3. Implicitly define the immediate dominator of each vertex
15785 * by applying Corollary 1.
15786 * Step 4. Explicitly define the immediate dominator of each vertex,
15787 * carrying out the computation vertex by vertex in increasing order
15790 /* Step 1 initialize the basic block information */
15791 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15792 initialize_sdblock(sd, 0, bb->first_block, 0);
15798 /* Step 2 compute the semidominators */
15799 /* Step 3 implicitly define the immediate dominator of each vertex */
15800 compute_sdom(state, bb, sd);
15801 /* Step 4 explicitly define the immediate dominator of each vertex */
15802 compute_idom(state, bb, sd);
15806 static void find_post_dominators(struct compile_state *state,
15807 struct basic_blocks *bb)
15809 struct sdom_block *sd;
15811 /* Step 1 initialize the basic block information */
15812 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15814 vertex = setup_spdblocks(state, bb, sd);
15815 if (vertex != bb->last_vertex) {
15816 internal_error(state, 0, "missing %d blocks",
15817 bb->last_vertex - vertex);
15820 /* Step 2 compute the semidominators */
15821 /* Step 3 implicitly define the immediate dominator of each vertex */
15822 compute_spdom(state, bb, sd);
15823 /* Step 4 explicitly define the immediate dominator of each vertex */
15824 compute_ipdom(state, bb, sd);
15830 static void find_block_domf(struct compile_state *state, struct block *block)
15832 struct block *child;
15833 struct block_set *user, *edge;
15834 if (block->domfrontier != 0) {
15835 internal_error(state, block->first, "domfrontier present?");
15837 for(user = block->idominates; user; user = user->next) {
15838 child = user->member;
15839 if (child->idom != block) {
15840 internal_error(state, block->first, "bad idom");
15842 find_block_domf(state, child);
15844 for(edge = block->edges; edge; edge = edge->next) {
15845 if (edge->member->idom != block) {
15846 domf_block(block, edge->member);
15849 for(user = block->idominates; user; user = user->next) {
15850 struct block_set *frontier;
15851 child = user->member;
15852 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15853 if (frontier->member->idom != block) {
15854 domf_block(block, frontier->member);
15860 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15862 struct block *child;
15863 struct block_set *user;
15864 if (block->ipdomfrontier != 0) {
15865 internal_error(state, block->first, "ipdomfrontier present?");
15867 for(user = block->ipdominates; user; user = user->next) {
15868 child = user->member;
15869 if (child->ipdom != block) {
15870 internal_error(state, block->first, "bad ipdom");
15872 find_block_ipdomf(state, child);
15874 for(user = block->use; user; user = user->next) {
15875 if (user->member->ipdom != block) {
15876 ipdomf_block(block, user->member);
15879 for(user = block->ipdominates; user; user = user->next) {
15880 struct block_set *frontier;
15881 child = user->member;
15882 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15883 if (frontier->member->ipdom != block) {
15884 ipdomf_block(block, frontier->member);
15890 static void print_dominated(
15891 struct compile_state *state, struct block *block, void *arg)
15893 struct block_set *user;
15896 fprintf(fp, "%d:", block->vertex);
15897 for(user = block->idominates; user; user = user->next) {
15898 fprintf(fp, " %d", user->member->vertex);
15899 if (user->member->idom != block) {
15900 internal_error(state, user->member->first, "bad idom");
15906 static void print_dominated2(
15907 struct compile_state *state, FILE *fp, int depth, struct block *block)
15909 struct block_set *user;
15910 struct triple *ins;
15911 struct occurance *ptr, *ptr2;
15912 const char *filename1, *filename2;
15913 int equal_filenames;
15915 for(i = 0; i < depth; i++) {
15918 fprintf(fp, "%3d: %p (%p - %p) @",
15919 block->vertex, block, block->first, block->last);
15920 ins = block->first;
15921 while(ins != block->last && (ins->occurance->line == 0)) {
15924 ptr = ins->occurance;
15925 ptr2 = block->last->occurance;
15926 filename1 = ptr->filename? ptr->filename : "";
15927 filename2 = ptr2->filename? ptr2->filename : "";
15928 equal_filenames = (strcmp(filename1, filename2) == 0);
15929 if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15930 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15931 } else if (equal_filenames) {
15932 fprintf(fp, " %s:(%d - %d)",
15933 ptr->filename, ptr->line, ptr2->line);
15935 fprintf(fp, " (%s:%d - %s:%d)",
15936 ptr->filename, ptr->line,
15937 ptr2->filename, ptr2->line);
15940 for(user = block->idominates; user; user = user->next) {
15941 print_dominated2(state, fp, depth + 1, user->member);
15945 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15947 fprintf(fp, "\ndominates\n");
15948 walk_blocks(state, bb, print_dominated, fp);
15949 fprintf(fp, "dominates\n");
15950 print_dominated2(state, fp, 0, bb->first_block);
15954 static int print_frontiers(
15955 struct compile_state *state, FILE *fp, struct block *block, int vertex)
15957 struct block_set *user, *edge;
15959 if (!block || (block->vertex != vertex + 1)) {
15964 fprintf(fp, "%d:", block->vertex);
15965 for(user = block->domfrontier; user; user = user->next) {
15966 fprintf(fp, " %d", user->member->vertex);
15970 for(edge = block->edges; edge; edge = edge->next) {
15971 vertex = print_frontiers(state, fp, edge->member, vertex);
15975 static void print_dominance_frontiers(struct compile_state *state,
15976 FILE *fp, struct basic_blocks *bb)
15978 fprintf(fp, "\ndominance frontiers\n");
15979 print_frontiers(state, fp, bb->first_block, 0);
15983 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15985 /* Find the immediate dominators */
15986 find_immediate_dominators(state, bb);
15987 /* Find the dominance frontiers */
15988 find_block_domf(state, bb->first_block);
15989 /* If debuging print the print what I have just found */
15990 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15991 print_dominators(state, state->dbgout, bb);
15992 print_dominance_frontiers(state, state->dbgout, bb);
15993 print_control_flow(state, state->dbgout, bb);
15998 static void print_ipdominated(
15999 struct compile_state *state, struct block *block, void *arg)
16001 struct block_set *user;
16004 fprintf(fp, "%d:", block->vertex);
16005 for(user = block->ipdominates; user; user = user->next) {
16006 fprintf(fp, " %d", user->member->vertex);
16007 if (user->member->ipdom != block) {
16008 internal_error(state, user->member->first, "bad ipdom");
16014 static void print_ipdominators(struct compile_state *state, FILE *fp,
16015 struct basic_blocks *bb)
16017 fprintf(fp, "\nipdominates\n");
16018 walk_blocks(state, bb, print_ipdominated, fp);
16021 static int print_pfrontiers(
16022 struct compile_state *state, FILE *fp, struct block *block, int vertex)
16024 struct block_set *user;
16026 if (!block || (block->vertex != vertex + 1)) {
16031 fprintf(fp, "%d:", block->vertex);
16032 for(user = block->ipdomfrontier; user; user = user->next) {
16033 fprintf(fp, " %d", user->member->vertex);
16036 for(user = block->use; user; user = user->next) {
16037 vertex = print_pfrontiers(state, fp, user->member, vertex);
16041 static void print_ipdominance_frontiers(struct compile_state *state,
16042 FILE *fp, struct basic_blocks *bb)
16044 fprintf(fp, "\nipdominance frontiers\n");
16045 print_pfrontiers(state, fp, bb->last_block, 0);
16049 static void analyze_ipdominators(struct compile_state *state,
16050 struct basic_blocks *bb)
16052 /* Find the post dominators */
16053 find_post_dominators(state, bb);
16054 /* Find the control dependencies (post dominance frontiers) */
16055 find_block_ipdomf(state, bb->last_block);
16056 /* If debuging print the print what I have just found */
16057 if (state->compiler->debug & DEBUG_RDOMINATORS) {
16058 print_ipdominators(state, state->dbgout, bb);
16059 print_ipdominance_frontiers(state, state->dbgout, bb);
16060 print_control_flow(state, state->dbgout, bb);
16064 static int bdominates(struct compile_state *state,
16065 struct block *dom, struct block *sub)
16067 while(sub && (sub != dom)) {
16073 static int tdominates(struct compile_state *state,
16074 struct triple *dom, struct triple *sub)
16076 struct block *bdom, *bsub;
16078 bdom = block_of_triple(state, dom);
16079 bsub = block_of_triple(state, sub);
16080 if (bdom != bsub) {
16081 result = bdominates(state, bdom, bsub);
16084 struct triple *ins;
16085 if (!bdom || !bsub) {
16086 internal_error(state, dom, "huh?");
16089 while((ins != bsub->first) && (ins != dom)) {
16092 result = (ins == dom);
16097 static void analyze_basic_blocks(
16098 struct compile_state *state, struct basic_blocks *bb)
16100 setup_basic_blocks(state, bb);
16101 analyze_idominators(state, bb);
16102 analyze_ipdominators(state, bb);
16105 static void insert_phi_operations(struct compile_state *state)
16108 struct triple *first;
16109 int *has_already, *work;
16110 struct block *work_list, **work_list_tail;
16112 struct triple *var, *vnext;
16114 size = sizeof(int) * (state->bb.last_vertex + 1);
16115 has_already = xcmalloc(size, "has_already");
16116 work = xcmalloc(size, "work");
16119 first = state->first;
16120 for(var = first->next; var != first ; var = vnext) {
16121 struct block *block;
16122 struct triple_set *user, *unext;
16125 if (!triple_is_auto_var(state, var) || !var->use) {
16131 work_list_tail = &work_list;
16132 for(user = var->use; user; user = unext) {
16133 unext = user->next;
16134 if (MISC(var, 0) == user->member) {
16137 if (user->member->op == OP_READ) {
16140 if (user->member->op != OP_WRITE) {
16141 internal_error(state, user->member,
16142 "bad variable access");
16144 block = user->member->u.block;
16146 warning(state, user->member, "dead code");
16147 release_triple(state, user->member);
16150 if (work[block->vertex] >= iter) {
16153 work[block->vertex] = iter;
16154 *work_list_tail = block;
16155 block->work_next = 0;
16156 work_list_tail = &block->work_next;
16158 for(block = work_list; block; block = block->work_next) {
16159 struct block_set *df;
16160 for(df = block->domfrontier; df; df = df->next) {
16161 struct triple *phi;
16162 struct block *front;
16164 front = df->member;
16166 if (has_already[front->vertex] >= iter) {
16169 /* Count how many edges flow into this block */
16170 in_edges = front->users;
16171 /* Insert a phi function for this variable */
16172 get_occurance(var->occurance);
16173 phi = alloc_triple(
16174 state, OP_PHI, var->type, -1, in_edges,
16176 phi->u.block = front;
16177 MISC(phi, 0) = var;
16178 use_triple(var, phi);
16180 if (phi->rhs != in_edges) {
16181 internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16182 phi->rhs, in_edges);
16185 /* Insert the phi functions immediately after the label */
16186 insert_triple(state, front->first->next, phi);
16187 if (front->first == front->last) {
16188 front->last = front->first->next;
16190 has_already[front->vertex] = iter;
16191 transform_to_arch_instruction(state, phi);
16193 /* If necessary plan to visit the basic block */
16194 if (work[front->vertex] >= iter) {
16197 work[front->vertex] = iter;
16198 *work_list_tail = front;
16199 front->work_next = 0;
16200 work_list_tail = &front->work_next;
16204 xfree(has_already);
16210 struct triple_set *top;
16214 static int count_auto_vars(struct compile_state *state)
16216 struct triple *first, *ins;
16218 first = state->first;
16221 if (triple_is_auto_var(state, ins)) {
16225 } while(ins != first);
16229 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16231 struct triple *first, *ins;
16233 first = state->first;
16236 if (triple_is_auto_var(state, ins)) {
16238 stacks[auto_vars].orig_id = ins->id;
16239 ins->id = auto_vars;
16242 } while(ins != first);
16245 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16247 struct triple *first, *ins;
16248 first = state->first;
16251 if (triple_is_auto_var(state, ins)) {
16252 ins->id = stacks[ins->id].orig_id;
16255 } while(ins != first);
16258 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16260 struct triple_set *head;
16261 struct triple *top_val;
16263 head = stacks[var->id].top;
16265 top_val = head->member;
16270 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16272 struct triple_set *new;
16273 /* Append new to the head of the list,
16274 * it's the only sensible behavoir for a stack.
16276 new = xcmalloc(sizeof(*new), "triple_set");
16278 new->next = stacks[var->id].top;
16279 stacks[var->id].top = new;
16282 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16284 struct triple_set *set, **ptr;
16285 ptr = &stacks[var->id].top;
16288 if (set->member == oldval) {
16291 /* Only free one occurance from the stack */
16304 static void fixup_block_phi_variables(
16305 struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16307 struct block_set *set;
16308 struct triple *ptr;
16310 if (!parent || !block)
16312 /* Find the edge I am coming in on */
16314 for(set = block->use; set; set = set->next, edge++) {
16315 if (set->member == parent) {
16320 internal_error(state, 0, "phi input is not on a control predecessor");
16322 for(ptr = block->first; ; ptr = ptr->next) {
16323 if (ptr->op == OP_PHI) {
16324 struct triple *var, *val, **slot;
16325 var = MISC(ptr, 0);
16327 internal_error(state, ptr, "no var???");
16329 /* Find the current value of the variable */
16330 val = peek_triple(stacks, var);
16331 if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16332 internal_error(state, val, "bad value in phi");
16334 if (edge >= ptr->rhs) {
16335 internal_error(state, ptr, "edges > phi rhs");
16337 slot = &RHS(ptr, edge);
16338 if ((*slot != 0) && (*slot != val)) {
16339 internal_error(state, ptr, "phi already bound on this edge");
16342 use_triple(val, ptr);
16344 if (ptr == block->last) {
16351 static void rename_block_variables(
16352 struct compile_state *state, struct stack *stacks, struct block *block)
16354 struct block_set *user, *edge;
16355 struct triple *ptr, *next, *last;
16359 last = block->first;
16361 for(ptr = block->first; !done; ptr = next) {
16363 if (ptr == block->last) {
16367 if (ptr->op == OP_READ) {
16368 struct triple *var, *val;
16370 if (!triple_is_auto_var(state, var)) {
16371 internal_error(state, ptr, "read of non auto var!");
16373 unuse_triple(var, ptr);
16374 /* Find the current value of the variable */
16375 val = peek_triple(stacks, var);
16377 /* Let the optimizer at variables that are not initially
16378 * set. But give it a bogus value so things seem to
16379 * work by accident. This is useful for bitfields because
16380 * setting them always involves a read-modify-write.
16382 if (TYPE_ARITHMETIC(ptr->type->type)) {
16383 val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16384 val->u.cval = 0xdeadbeaf;
16386 val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16390 error(state, ptr, "variable used without being set");
16392 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16393 internal_error(state, val, "bad value in read");
16395 propogate_use(state, ptr, val);
16396 release_triple(state, ptr);
16400 if (ptr->op == OP_WRITE) {
16401 struct triple *var, *val, *tval;
16402 var = MISC(ptr, 0);
16403 if (!triple_is_auto_var(state, var)) {
16404 internal_error(state, ptr, "write to non auto var!");
16406 tval = val = RHS(ptr, 0);
16407 if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16408 triple_is_auto_var(state, val)) {
16409 internal_error(state, ptr, "bad value in write");
16411 /* Insert a cast if the types differ */
16412 if (!is_subset_type(ptr->type, val->type)) {
16413 if (val->op == OP_INTCONST) {
16414 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16415 tval->u.cval = val->u.cval;
16418 tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16419 use_triple(val, tval);
16421 transform_to_arch_instruction(state, tval);
16422 unuse_triple(val, ptr);
16423 RHS(ptr, 0) = tval;
16424 use_triple(tval, ptr);
16426 propogate_use(state, ptr, tval);
16427 unuse_triple(var, ptr);
16428 /* Push OP_WRITE ptr->right onto a stack of variable uses */
16429 push_triple(stacks, var, tval);
16431 if (ptr->op == OP_PHI) {
16432 struct triple *var;
16433 var = MISC(ptr, 0);
16434 if (!triple_is_auto_var(state, var)) {
16435 internal_error(state, ptr, "phi references non auto var!");
16437 /* Push OP_PHI onto a stack of variable uses */
16438 push_triple(stacks, var, ptr);
16442 block->last = last;
16444 /* Fixup PHI functions in the cf successors */
16445 for(edge = block->edges; edge; edge = edge->next) {
16446 fixup_block_phi_variables(state, stacks, block, edge->member);
16448 /* rename variables in the dominated nodes */
16449 for(user = block->idominates; user; user = user->next) {
16450 rename_block_variables(state, stacks, user->member);
16452 /* pop the renamed variable stack */
16453 last = block->first;
16455 for(ptr = block->first; !done ; ptr = next) {
16457 if (ptr == block->last) {
16460 if (ptr->op == OP_WRITE) {
16461 struct triple *var;
16462 var = MISC(ptr, 0);
16463 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16464 pop_triple(stacks, var, RHS(ptr, 0));
16465 release_triple(state, ptr);
16468 if (ptr->op == OP_PHI) {
16469 struct triple *var;
16470 var = MISC(ptr, 0);
16471 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16472 pop_triple(stacks, var, ptr);
16476 block->last = last;
16479 static void rename_variables(struct compile_state *state)
16481 struct stack *stacks;
16484 /* Allocate stacks for the Variables */
16485 auto_vars = count_auto_vars(state);
16486 stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16488 /* Give each auto_var a stack */
16489 number_auto_vars(state, stacks);
16491 /* Rename the variables */
16492 rename_block_variables(state, stacks, state->bb.first_block);
16494 /* Remove the stacks from the auto_vars */
16495 restore_auto_vars(state, stacks);
16499 static void prune_block_variables(struct compile_state *state,
16500 struct block *block)
16502 struct block_set *user;
16503 struct triple *next, *ptr;
16507 for(ptr = block->first; !done; ptr = next) {
16508 /* Be extremely careful I am deleting the list
16509 * as I walk trhough it.
16512 if (ptr == block->last) {
16515 if (triple_is_auto_var(state, ptr)) {
16516 struct triple_set *user, *next;
16517 for(user = ptr->use; user; user = next) {
16518 struct triple *use;
16520 use = user->member;
16521 if (MISC(ptr, 0) == user->member) {
16524 if (use->op != OP_PHI) {
16525 internal_error(state, use, "decl still used");
16527 if (MISC(use, 0) != ptr) {
16528 internal_error(state, use, "bad phi use of decl");
16530 unuse_triple(ptr, use);
16533 if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16534 /* Delete the adecl */
16535 release_triple(state, MISC(ptr, 0));
16536 /* And the piece */
16537 release_triple(state, ptr);
16542 for(user = block->idominates; user; user = user->next) {
16543 prune_block_variables(state, user->member);
16547 struct phi_triple {
16548 struct triple *phi;
16553 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16555 struct triple **slot;
16557 if (live[phi->id].alive) {
16560 live[phi->id].alive = 1;
16562 slot = &RHS(phi, 0);
16563 for(i = 0; i < zrhs; i++) {
16564 struct triple *used;
16566 if (used && (used->op == OP_PHI)) {
16567 keep_phi(state, live, used);
16572 static void prune_unused_phis(struct compile_state *state)
16574 struct triple *first, *phi;
16575 struct phi_triple *live;
16578 /* Find the first instruction */
16579 first = state->first;
16581 /* Count how many phi functions I need to process */
16583 for(phi = first->next; phi != first; phi = phi->next) {
16584 if (phi->op == OP_PHI) {
16589 /* Mark them all dead */
16590 live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16592 for(phi = first->next; phi != first; phi = phi->next) {
16593 if (phi->op != OP_PHI) {
16596 live[phis].alive = 0;
16597 live[phis].orig_id = phi->id;
16598 live[phis].phi = phi;
16603 /* Mark phis alive that are used by non phis */
16604 for(i = 0; i < phis; i++) {
16605 struct triple_set *set;
16606 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16607 if (set->member->op != OP_PHI) {
16608 keep_phi(state, live, live[i].phi);
16614 /* Delete the extraneous phis */
16615 for(i = 0; i < phis; i++) {
16616 struct triple **slot;
16618 if (!live[i].alive) {
16619 release_triple(state, live[i].phi);
16623 slot = &RHS(phi, 0);
16625 for(j = 0; j < zrhs; j++) {
16627 struct triple *unknown;
16628 get_occurance(phi->occurance);
16629 unknown = flatten(state, state->global_pool,
16630 alloc_triple(state, OP_UNKNOWNVAL,
16631 phi->type, 0, 0, phi->occurance));
16633 use_triple(unknown, phi);
16634 transform_to_arch_instruction(state, unknown);
16636 warning(state, phi, "variable not set at index %d on all paths to use", j);
16644 static void transform_to_ssa_form(struct compile_state *state)
16646 insert_phi_operations(state);
16647 rename_variables(state);
16649 prune_block_variables(state, state->bb.first_block);
16650 prune_unused_phis(state);
16652 print_blocks(state, __func__, state->dbgout);
16656 static void clear_vertex(
16657 struct compile_state *state, struct block *block, void *arg)
16659 /* Clear the current blocks vertex and the vertex of all
16660 * of the current blocks neighbors in case there are malformed
16661 * blocks with now instructions at this point.
16663 struct block_set *user, *edge;
16665 for(edge = block->edges; edge; edge = edge->next) {
16666 edge->member->vertex = 0;
16668 for(user = block->use; user; user = user->next) {
16669 user->member->vertex = 0;
16673 static void mark_live_block(
16674 struct compile_state *state, struct block *block, int *next_vertex)
16676 /* See if this is a block that has not been marked */
16677 if (block->vertex != 0) {
16680 block->vertex = *next_vertex;
16682 if (triple_is_branch(state, block->last)) {
16683 struct triple **targ;
16684 targ = triple_edge_targ(state, block->last, 0);
16685 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16689 if (!triple_stores_block(state, *targ)) {
16690 internal_error(state, 0, "bad targ");
16692 mark_live_block(state, (*targ)->u.block, next_vertex);
16694 /* Ensure the last block of a function remains alive */
16695 if (triple_is_call(state, block->last)) {
16696 mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16699 else if (block->last->next != state->first) {
16700 struct triple *ins;
16701 ins = block->last->next;
16702 if (!triple_stores_block(state, ins)) {
16703 internal_error(state, 0, "bad block start");
16705 mark_live_block(state, ins->u.block, next_vertex);
16709 static void transform_from_ssa_form(struct compile_state *state)
16711 /* To get out of ssa form we insert moves on the incoming
16712 * edges to blocks containting phi functions.
16714 struct triple *first;
16715 struct triple *phi, *var, *next;
16718 /* Walk the control flow to see which blocks remain alive */
16719 walk_blocks(state, &state->bb, clear_vertex, 0);
16721 mark_live_block(state, state->bb.first_block, &next_vertex);
16723 /* Walk all of the operations to find the phi functions */
16724 first = state->first;
16725 for(phi = first->next; phi != first ; phi = next) {
16726 struct block_set *set;
16727 struct block *block;
16728 struct triple **slot;
16729 struct triple *var;
16730 struct triple_set *use, *use_next;
16731 int edge, writers, readers;
16733 if (phi->op != OP_PHI) {
16737 block = phi->u.block;
16738 slot = &RHS(phi, 0);
16740 /* If this phi is in a dead block just forget it */
16741 if (block->vertex == 0) {
16742 release_triple(state, phi);
16746 /* Forget uses from code in dead blocks */
16747 for(use = phi->use; use; use = use_next) {
16748 struct block *ublock;
16749 struct triple **expr;
16750 use_next = use->next;
16751 ublock = block_of_triple(state, use->member);
16752 if ((use->member == phi) || (ublock->vertex != 0)) {
16755 expr = triple_rhs(state, use->member, 0);
16756 for(; expr; expr = triple_rhs(state, use->member, expr)) {
16757 if (*expr == phi) {
16761 unuse_triple(phi, use->member);
16763 /* A variable to replace the phi function */
16764 if (registers_of(state, phi->type) != 1) {
16765 internal_error(state, phi, "phi->type does not fit in a single register!");
16767 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16768 var = var->next; /* point at the var */
16770 /* Replaces use of phi with var */
16771 propogate_use(state, phi, var);
16773 /* Count the readers */
16775 for(use = var->use; use; use = use->next) {
16776 if (use->member != MISC(var, 0)) {
16781 /* Walk all of the incoming edges/blocks and insert moves.
16784 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16785 struct block *eblock, *vblock;
16786 struct triple *move;
16787 struct triple *val, *base;
16788 eblock = set->member;
16791 unuse_triple(val, phi);
16792 vblock = block_of_triple(state, val);
16794 /* If we don't have a value that belongs in an OP_WRITE
16797 if (!val || (val == &unknown_triple) || (val == phi)
16798 || (vblock && (vblock->vertex == 0))) {
16801 /* If the value should never occur error */
16803 internal_error(state, val, "no vblock?");
16807 /* If the value occurs in a dead block see if a replacement
16808 * block can be found.
16810 while(eblock && (eblock->vertex == 0)) {
16811 eblock = eblock->idom;
16813 /* If not continue on with the next value. */
16814 if (!eblock || (eblock->vertex == 0)) {
16818 /* If we have an empty incoming block ignore it. */
16819 if (!eblock->first) {
16820 internal_error(state, 0, "empty block?");
16823 /* Make certain the write is placed in the edge block... */
16824 /* Walk through the edge block backwards to find an
16825 * appropriate location for the OP_WRITE.
16827 for(base = eblock->last; base != eblock->first; base = base->prev) {
16828 struct triple **expr;
16829 if (base->op == OP_PIECE) {
16830 base = MISC(base, 0);
16832 if ((base == var) || (base == val)) {
16835 expr = triple_lhs(state, base, 0);
16836 for(; expr; expr = triple_lhs(state, base, expr)) {
16837 if ((*expr) == val) {
16841 expr = triple_rhs(state, base, 0);
16842 for(; expr; expr = triple_rhs(state, base, expr)) {
16843 if ((*expr) == var) {
16849 if (triple_is_branch(state, base)) {
16850 internal_error(state, base,
16851 "Could not insert write to phi");
16853 move = post_triple(state, base, OP_WRITE, var->type, val, var);
16854 use_triple(val, move);
16855 use_triple(var, move);
16858 if (!writers && readers) {
16859 internal_error(state, var, "no value written to in use phi?");
16861 /* If var is not used free it */
16863 release_triple(state, MISC(var, 0));
16864 release_triple(state, var);
16866 /* Release the phi function */
16867 release_triple(state, phi);
16870 /* Walk all of the operations to find the adecls */
16871 for(var = first->next; var != first ; var = var->next) {
16872 struct triple_set *use, *use_next;
16873 if (!triple_is_auto_var(state, var)) {
16877 /* Walk through all of the rhs uses of var and
16878 * replace them with read of var.
16880 for(use = var->use; use; use = use_next) {
16881 struct triple *read, *user;
16882 struct triple **slot;
16884 use_next = use->next;
16885 user = use->member;
16887 /* Generate a read of var */
16888 read = pre_triple(state, user, OP_READ, var->type, var, 0);
16889 use_triple(var, read);
16891 /* Find the rhs uses and see if they need to be replaced */
16894 slot = &RHS(user, 0);
16895 for(i = 0; i < zrhs; i++) {
16896 if (slot[i] == var) {
16901 /* If we did use it cleanup the uses */
16903 unuse_triple(var, user);
16904 use_triple(read, user);
16906 /* If we didn't use it release the extra triple */
16908 release_triple(state, read);
16914 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16915 FILE *fp = state->dbgout; \
16916 fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16919 static void rebuild_ssa_form(struct compile_state *state)
16922 transform_from_ssa_form(state);
16924 state->bb.first = state->first;
16925 free_basic_blocks(state, &state->bb);
16926 analyze_basic_blocks(state, &state->bb);
16928 insert_phi_operations(state);
16930 rename_variables(state);
16933 prune_block_variables(state, state->bb.first_block);
16935 prune_unused_phis(state);
16941 * Register conflict resolution
16942 * =========================================================
16945 static struct reg_info find_def_color(
16946 struct compile_state *state, struct triple *def)
16948 struct triple_set *set;
16949 struct reg_info info;
16950 info.reg = REG_UNSET;
16952 if (!triple_is_def(state, def)) {
16955 info = arch_reg_lhs(state, def, 0);
16956 if (info.reg >= MAX_REGISTERS) {
16957 info.reg = REG_UNSET;
16959 for(set = def->use; set; set = set->next) {
16960 struct reg_info tinfo;
16962 i = find_rhs_use(state, set->member, def);
16966 tinfo = arch_reg_rhs(state, set->member, i);
16967 if (tinfo.reg >= MAX_REGISTERS) {
16968 tinfo.reg = REG_UNSET;
16970 if ((tinfo.reg != REG_UNSET) &&
16971 (info.reg != REG_UNSET) &&
16972 (tinfo.reg != info.reg)) {
16973 internal_error(state, def, "register conflict");
16975 if ((info.regcm & tinfo.regcm) == 0) {
16976 internal_error(state, def, "regcm conflict %x & %x == 0",
16977 info.regcm, tinfo.regcm);
16979 if (info.reg == REG_UNSET) {
16980 info.reg = tinfo.reg;
16982 info.regcm &= tinfo.regcm;
16984 if (info.reg >= MAX_REGISTERS) {
16985 internal_error(state, def, "register out of range");
16990 static struct reg_info find_lhs_pre_color(
16991 struct compile_state *state, struct triple *ins, int index)
16993 struct reg_info info;
16997 if (!zlhs && triple_is_def(state, ins)) {
17000 if (index >= zlhs) {
17001 internal_error(state, ins, "Bad lhs %d", index);
17003 info = arch_reg_lhs(state, ins, index);
17004 for(i = 0; i < zrhs; i++) {
17005 struct reg_info rinfo;
17006 rinfo = arch_reg_rhs(state, ins, i);
17007 if ((info.reg == rinfo.reg) &&
17008 (rinfo.reg >= MAX_REGISTERS)) {
17009 struct reg_info tinfo;
17010 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
17011 info.reg = tinfo.reg;
17012 info.regcm &= tinfo.regcm;
17016 if (info.reg >= MAX_REGISTERS) {
17017 info.reg = REG_UNSET;
17022 static struct reg_info find_rhs_post_color(
17023 struct compile_state *state, struct triple *ins, int index);
17025 static struct reg_info find_lhs_post_color(
17026 struct compile_state *state, struct triple *ins, int index)
17028 struct triple_set *set;
17029 struct reg_info info;
17030 struct triple *lhs;
17031 #if DEBUG_TRIPLE_COLOR
17032 fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
17035 if ((index == 0) && triple_is_def(state, ins)) {
17038 else if (index < ins->lhs) {
17039 lhs = LHS(ins, index);
17042 internal_error(state, ins, "Bad lhs %d", index);
17045 info = arch_reg_lhs(state, ins, index);
17046 if (info.reg >= MAX_REGISTERS) {
17047 info.reg = REG_UNSET;
17049 for(set = lhs->use; set; set = set->next) {
17050 struct reg_info rinfo;
17051 struct triple *user;
17053 user = set->member;
17055 for(i = 0; i < zrhs; i++) {
17056 if (RHS(user, i) != lhs) {
17059 rinfo = find_rhs_post_color(state, user, i);
17060 if ((info.reg != REG_UNSET) &&
17061 (rinfo.reg != REG_UNSET) &&
17062 (info.reg != rinfo.reg)) {
17063 internal_error(state, ins, "register conflict");
17065 if ((info.regcm & rinfo.regcm) == 0) {
17066 internal_error(state, ins, "regcm conflict %x & %x == 0",
17067 info.regcm, rinfo.regcm);
17069 if (info.reg == REG_UNSET) {
17070 info.reg = rinfo.reg;
17072 info.regcm &= rinfo.regcm;
17075 #if DEBUG_TRIPLE_COLOR
17076 fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17077 ins, index, info.reg, info.regcm);
17082 static struct reg_info find_rhs_post_color(
17083 struct compile_state *state, struct triple *ins, int index)
17085 struct reg_info info, rinfo;
17087 #if DEBUG_TRIPLE_COLOR
17088 fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17091 rinfo = arch_reg_rhs(state, ins, index);
17093 if (!zlhs && triple_is_def(state, ins)) {
17097 if (info.reg >= MAX_REGISTERS) {
17098 info.reg = REG_UNSET;
17100 for(i = 0; i < zlhs; i++) {
17101 struct reg_info linfo;
17102 linfo = arch_reg_lhs(state, ins, i);
17103 if ((linfo.reg == rinfo.reg) &&
17104 (linfo.reg >= MAX_REGISTERS)) {
17105 struct reg_info tinfo;
17106 tinfo = find_lhs_post_color(state, ins, i);
17107 if (tinfo.reg >= MAX_REGISTERS) {
17108 tinfo.reg = REG_UNSET;
17110 info.regcm &= linfo.regcm;
17111 info.regcm &= tinfo.regcm;
17112 if (info.reg != REG_UNSET) {
17113 internal_error(state, ins, "register conflict");
17115 if (info.regcm == 0) {
17116 internal_error(state, ins, "regcm conflict");
17118 info.reg = tinfo.reg;
17121 #if DEBUG_TRIPLE_COLOR
17122 fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17123 ins, index, info.reg, info.regcm);
17128 static struct reg_info find_lhs_color(
17129 struct compile_state *state, struct triple *ins, int index)
17131 struct reg_info pre, post, info;
17132 #if DEBUG_TRIPLE_COLOR
17133 fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17136 pre = find_lhs_pre_color(state, ins, index);
17137 post = find_lhs_post_color(state, ins, index);
17138 if ((pre.reg != post.reg) &&
17139 (pre.reg != REG_UNSET) &&
17140 (post.reg != REG_UNSET)) {
17141 internal_error(state, ins, "register conflict");
17143 info.regcm = pre.regcm & post.regcm;
17144 info.reg = pre.reg;
17145 if (info.reg == REG_UNSET) {
17146 info.reg = post.reg;
17148 #if DEBUG_TRIPLE_COLOR
17149 fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17150 ins, index, info.reg, info.regcm,
17151 pre.reg, pre.regcm, post.reg, post.regcm);
17156 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17158 struct triple_set *entry, *next;
17159 struct triple *out;
17160 struct reg_info info, rinfo;
17162 info = arch_reg_lhs(state, ins, 0);
17163 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17164 use_triple(RHS(out, 0), out);
17165 /* Get the users of ins to use out instead */
17166 for(entry = ins->use; entry; entry = next) {
17168 next = entry->next;
17169 if (entry->member == out) {
17172 i = find_rhs_use(state, entry->member, ins);
17176 rinfo = arch_reg_rhs(state, entry->member, i);
17177 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17180 replace_rhs_use(state, ins, out, entry->member);
17182 transform_to_arch_instruction(state, out);
17186 static struct triple *typed_pre_copy(
17187 struct compile_state *state, struct type *type, struct triple *ins, int index)
17189 /* Carefully insert enough operations so that I can
17190 * enter any operation with a GPR32.
17193 struct triple **expr;
17195 struct reg_info info;
17197 if (ins->op == OP_PHI) {
17198 internal_error(state, ins, "pre_copy on a phi?");
17200 classes = arch_type_to_regcm(state, type);
17201 info = arch_reg_rhs(state, ins, index);
17202 expr = &RHS(ins, index);
17203 if ((info.regcm & classes) == 0) {
17204 FILE *fp = state->errout;
17205 fprintf(fp, "src_type: ");
17206 name_of(fp, ins->type);
17207 fprintf(fp, "\ndst_type: ");
17210 internal_error(state, ins, "pre_copy with no register classes");
17213 if (!equiv_types(type, (*expr)->type)) {
17216 in = pre_triple(state, ins, op, type, *expr, 0);
17217 unuse_triple(*expr, ins);
17219 use_triple(RHS(in, 0), in);
17220 use_triple(in, ins);
17221 transform_to_arch_instruction(state, in);
17225 static struct triple *pre_copy(
17226 struct compile_state *state, struct triple *ins, int index)
17228 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17232 static void insert_copies_to_phi(struct compile_state *state)
17234 /* To get out of ssa form we insert moves on the incoming
17235 * edges to blocks containting phi functions.
17237 struct triple *first;
17238 struct triple *phi;
17240 /* Walk all of the operations to find the phi functions */
17241 first = state->first;
17242 for(phi = first->next; phi != first ; phi = phi->next) {
17243 struct block_set *set;
17244 struct block *block;
17245 struct triple **slot, *copy;
17247 if (phi->op != OP_PHI) {
17250 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17251 block = phi->u.block;
17252 slot = &RHS(phi, 0);
17253 /* Phi's that feed into mandatory live range joins
17254 * cause nasty complications. Insert a copy of
17255 * the phi value so I never have to deal with
17256 * that in the rest of the code.
17258 copy = post_copy(state, phi);
17259 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17260 /* Walk all of the incoming edges/blocks and insert moves.
17262 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17263 struct block *eblock;
17264 struct triple *move;
17265 struct triple *val;
17266 struct triple *ptr;
17267 eblock = set->member;
17274 get_occurance(val->occurance);
17275 move = build_triple(state, OP_COPY, val->type, val, 0,
17277 move->u.block = eblock;
17278 move->id |= TRIPLE_FLAG_PRE_SPLIT;
17279 use_triple(val, move);
17282 unuse_triple(val, phi);
17283 use_triple(move, phi);
17285 /* Walk up the dominator tree until I have found the appropriate block */
17286 while(eblock && !tdominates(state, val, eblock->last)) {
17287 eblock = eblock->idom;
17290 internal_error(state, phi, "Cannot find block dominated by %p",
17294 /* Walk through the block backwards to find
17295 * an appropriate location for the OP_COPY.
17297 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17298 struct triple **expr;
17299 if (ptr->op == OP_PIECE) {
17300 ptr = MISC(ptr, 0);
17302 if ((ptr == phi) || (ptr == val)) {
17305 expr = triple_lhs(state, ptr, 0);
17306 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17307 if ((*expr) == val) {
17311 expr = triple_rhs(state, ptr, 0);
17312 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17313 if ((*expr) == phi) {
17319 if (triple_is_branch(state, ptr)) {
17320 internal_error(state, ptr,
17321 "Could not insert write to phi");
17323 insert_triple(state, after_lhs(state, ptr), move);
17324 if (eblock->last == after_lhs(state, ptr)->prev) {
17325 eblock->last = move;
17327 transform_to_arch_instruction(state, move);
17330 print_blocks(state, __func__, state->dbgout);
17333 struct triple_reg_set;
17337 static int do_triple_set(struct triple_reg_set **head,
17338 struct triple *member, struct triple *new_member)
17340 struct triple_reg_set **ptr, *new;
17345 if ((*ptr)->member == member) {
17348 ptr = &(*ptr)->next;
17350 new = xcmalloc(sizeof(*new), "triple_set");
17351 new->member = member;
17352 new->new = new_member;
17358 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17360 struct triple_reg_set *entry, **ptr;
17364 if (entry->member == member) {
17365 *ptr = entry->next;
17370 ptr = &entry->next;
17375 static int in_triple(struct reg_block *rb, struct triple *in)
17377 return do_triple_set(&rb->in, in, 0);
17380 #if DEBUG_ROMCC_WARNING
17381 static void unin_triple(struct reg_block *rb, struct triple *unin)
17383 do_triple_unset(&rb->in, unin);
17387 static int out_triple(struct reg_block *rb, struct triple *out)
17389 return do_triple_set(&rb->out, out, 0);
17391 #if DEBUG_ROMCC_WARNING
17392 static void unout_triple(struct reg_block *rb, struct triple *unout)
17394 do_triple_unset(&rb->out, unout);
17398 static int initialize_regblock(struct reg_block *blocks,
17399 struct block *block, int vertex)
17401 struct block_set *user;
17402 if (!block || (blocks[block->vertex].block == block)) {
17406 /* Renumber the blocks in a convinient fashion */
17407 block->vertex = vertex;
17408 blocks[vertex].block = block;
17409 blocks[vertex].vertex = vertex;
17410 for(user = block->use; user; user = user->next) {
17411 vertex = initialize_regblock(blocks, user->member, vertex);
17416 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17418 /* Part to piece is a best attempt and it cannot be correct all by
17419 * itself. If various values are read as different sizes in different
17420 * parts of the code this function cannot work. Or rather it cannot
17421 * work in conjunction with compute_variable_liftimes. As the
17422 * analysis will get confused.
17424 struct triple *base;
17426 if (!is_lvalue(state, ins)) {
17431 while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17432 base = MISC(ins, 0);
17435 reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17438 reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17441 internal_error(state, ins, "unhandled part");
17447 if (reg > base->lhs) {
17448 internal_error(state, base, "part out of range?");
17450 ins = LHS(base, reg);
17455 static int this_def(struct compile_state *state,
17456 struct triple *ins, struct triple *other)
17458 if (ins == other) {
17461 if (ins->op == OP_WRITE) {
17462 ins = part_to_piece(state, MISC(ins, 0));
17464 return ins == other;
17467 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17468 struct reg_block *rb, struct block *suc)
17470 /* Read the conditional input set of a successor block
17471 * (i.e. the input to the phi nodes) and place it in the
17472 * current blocks output set.
17474 struct block_set *set;
17475 struct triple *ptr;
17479 /* Find the edge I am coming in on */
17480 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17481 if (set->member == rb->block) {
17486 internal_error(state, 0, "Not coming on a control edge?");
17488 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17489 struct triple **slot, *expr, *ptr2;
17490 int out_change, done2;
17491 done = (ptr == suc->last);
17492 if (ptr->op != OP_PHI) {
17495 slot = &RHS(ptr, 0);
17497 out_change = out_triple(rb, expr);
17501 /* If we don't define the variable also plast it
17502 * in the current blocks input set.
17504 ptr2 = rb->block->first;
17505 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17506 if (this_def(state, ptr2, expr)) {
17509 done2 = (ptr2 == rb->block->last);
17514 change |= in_triple(rb, expr);
17519 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17520 struct reg_block *rb, struct block *suc)
17522 struct triple_reg_set *in_set;
17525 /* Read the input set of a successor block
17526 * and place it in the current blocks output set.
17528 in_set = blocks[suc->vertex].in;
17529 for(; in_set; in_set = in_set->next) {
17530 int out_change, done;
17531 struct triple *first, *last, *ptr;
17532 out_change = out_triple(rb, in_set->member);
17536 /* If we don't define the variable also place it
17537 * in the current blocks input set.
17539 first = rb->block->first;
17540 last = rb->block->last;
17542 for(ptr = first; !done; ptr = ptr->next) {
17543 if (this_def(state, ptr, in_set->member)) {
17546 done = (ptr == last);
17551 change |= in_triple(rb, in_set->member);
17553 change |= phi_in(state, blocks, rb, suc);
17557 static int use_in(struct compile_state *state, struct reg_block *rb)
17559 /* Find the variables we use but don't define and add
17560 * it to the current blocks input set.
17562 #if DEBUG_ROMCC_WARNINGS
17563 #warning "FIXME is this O(N^2) algorithm bad?"
17565 struct block *block;
17566 struct triple *ptr;
17571 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17572 struct triple **expr;
17573 done = (ptr == block->first);
17574 /* The variable a phi function uses depends on the
17575 * control flow, and is handled in phi_in, not
17578 if (ptr->op == OP_PHI) {
17581 expr = triple_rhs(state, ptr, 0);
17582 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17583 struct triple *rhs, *test;
17585 rhs = part_to_piece(state, *expr);
17590 /* See if rhs is defined in this block.
17591 * A write counts as a definition.
17593 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17594 tdone = (test == block->first);
17595 if (this_def(state, test, rhs)) {
17600 /* If I still have a valid rhs add it to in */
17601 change |= in_triple(rb, rhs);
17607 static struct reg_block *compute_variable_lifetimes(
17608 struct compile_state *state, struct basic_blocks *bb)
17610 struct reg_block *blocks;
17613 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17614 initialize_regblock(blocks, bb->last_block, 0);
17618 for(i = 1; i <= bb->last_vertex; i++) {
17619 struct block_set *edge;
17620 struct reg_block *rb;
17622 /* Add the all successor's input set to in */
17623 for(edge = rb->block->edges; edge; edge = edge->next) {
17624 change |= reg_in(state, blocks, rb, edge->member);
17626 /* Add use to in... */
17627 change |= use_in(state, rb);
17633 static void free_variable_lifetimes(struct compile_state *state,
17634 struct basic_blocks *bb, struct reg_block *blocks)
17637 /* free in_set && out_set on each block */
17638 for(i = 1; i <= bb->last_vertex; i++) {
17639 struct triple_reg_set *entry, *next;
17640 struct reg_block *rb;
17642 for(entry = rb->in; entry ; entry = next) {
17643 next = entry->next;
17644 do_triple_unset(&rb->in, entry->member);
17646 for(entry = rb->out; entry; entry = next) {
17647 next = entry->next;
17648 do_triple_unset(&rb->out, entry->member);
17655 typedef void (*wvl_cb_t)(
17656 struct compile_state *state,
17657 struct reg_block *blocks, struct triple_reg_set *live,
17658 struct reg_block *rb, struct triple *ins, void *arg);
17660 static void walk_variable_lifetimes(struct compile_state *state,
17661 struct basic_blocks *bb, struct reg_block *blocks,
17662 wvl_cb_t cb, void *arg)
17666 for(i = 1; i <= state->bb.last_vertex; i++) {
17667 struct triple_reg_set *live;
17668 struct triple_reg_set *entry, *next;
17669 struct triple *ptr, *prev;
17670 struct reg_block *rb;
17671 struct block *block;
17674 /* Get the blocks */
17678 /* Copy out into live */
17680 for(entry = rb->out; entry; entry = next) {
17681 next = entry->next;
17682 do_triple_set(&live, entry->member, entry->new);
17684 /* Walk through the basic block calculating live */
17685 for(done = 0, ptr = block->last; !done; ptr = prev) {
17686 struct triple **expr;
17689 done = (ptr == block->first);
17691 /* Ensure the current definition is in live */
17692 if (triple_is_def(state, ptr)) {
17693 do_triple_set(&live, ptr, 0);
17696 /* Inform the callback function of what is
17699 cb(state, blocks, live, rb, ptr, arg);
17701 /* Remove the current definition from live */
17702 do_triple_unset(&live, ptr);
17704 /* Add the current uses to live.
17706 * It is safe to skip phi functions because they do
17707 * not have any block local uses, and the block
17708 * output sets already properly account for what
17709 * control flow depedent uses phi functions do have.
17711 if (ptr->op == OP_PHI) {
17714 expr = triple_rhs(state, ptr, 0);
17715 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17716 /* If the triple is not a definition skip it. */
17717 if (!*expr || !triple_is_def(state, *expr)) {
17720 do_triple_set(&live, *expr, 0);
17724 for(entry = live; entry; entry = next) {
17725 next = entry->next;
17726 do_triple_unset(&live, entry->member);
17731 struct print_live_variable_info {
17732 struct reg_block *rb;
17735 #if DEBUG_EXPLICIT_CLOSURES
17736 static void print_live_variables_block(
17737 struct compile_state *state, struct block *block, void *arg)
17740 struct print_live_variable_info *info = arg;
17741 struct block_set *edge;
17742 FILE *fp = info->fp;
17743 struct reg_block *rb;
17744 struct triple *ptr;
17747 rb = &info->rb[block->vertex];
17749 fprintf(fp, "\nblock: %p (%d),",
17750 block, block->vertex);
17751 for(edge = block->edges; edge; edge = edge->next) {
17752 fprintf(fp, " %p<-%p",
17754 edge->member && edge->member->use?edge->member->use->member : 0);
17758 struct triple_reg_set *in_set;
17759 fprintf(fp, " in:");
17760 for(in_set = rb->in; in_set; in_set = in_set->next) {
17761 fprintf(fp, " %-10p", in_set->member);
17766 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17767 done = (ptr == block->last);
17768 if (ptr->op == OP_PHI) {
17775 for(edge = 0; edge < block->users; edge++) {
17776 fprintf(fp, " in(%d):", edge);
17777 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17778 struct triple **slot;
17779 done = (ptr == block->last);
17780 if (ptr->op != OP_PHI) {
17783 slot = &RHS(ptr, 0);
17784 fprintf(fp, " %-10p", slot[edge]);
17789 if (block->first->op == OP_LABEL) {
17790 fprintf(fp, "%p:\n", block->first);
17792 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17793 done = (ptr == block->last);
17794 display_triple(fp, ptr);
17797 struct triple_reg_set *out_set;
17798 fprintf(fp, " out:");
17799 for(out_set = rb->out; out_set; out_set = out_set->next) {
17800 fprintf(fp, " %-10p", out_set->member);
17807 static void print_live_variables(struct compile_state *state,
17808 struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17810 struct print_live_variable_info info;
17813 fprintf(fp, "\nlive variables by block\n");
17814 walk_blocks(state, bb, print_live_variables_block, &info);
17819 static int count_triples(struct compile_state *state)
17821 struct triple *first, *ins;
17823 first = state->first;
17828 } while (ins != first);
17833 struct dead_triple {
17834 struct triple *triple;
17835 struct dead_triple *work_next;
17836 struct block *block;
17839 #define TRIPLE_FLAG_ALIVE 1
17840 #define TRIPLE_FLAG_FREE 1
17843 static void print_dead_triples(struct compile_state *state,
17844 struct dead_triple *dtriple)
17846 struct triple *first, *ins;
17847 struct dead_triple *dt;
17849 if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17852 fp = state->dbgout;
17853 fprintf(fp, "--------------- dtriples ---------------\n");
17854 first = state->first;
17857 dt = &dtriple[ins->id];
17858 if ((ins->op == OP_LABEL) && (ins->use)) {
17859 fprintf(fp, "\n%p:\n", ins);
17862 (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17863 display_triple(fp, ins);
17864 if (triple_is_branch(state, ins)) {
17868 } while(ins != first);
17873 static void awaken(
17874 struct compile_state *state,
17875 struct dead_triple *dtriple, struct triple **expr,
17876 struct dead_triple ***work_list_tail)
17878 struct triple *triple;
17879 struct dead_triple *dt;
17887 if (triple->id <= 0) {
17888 internal_error(state, triple, "bad triple id: %d",
17891 if (triple->op == OP_NOOP) {
17892 internal_error(state, triple, "awakening noop?");
17895 dt = &dtriple[triple->id];
17896 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17897 dt->flags |= TRIPLE_FLAG_ALIVE;
17898 if (!dt->work_next) {
17899 **work_list_tail = dt;
17900 *work_list_tail = &dt->work_next;
17905 static void eliminate_inefectual_code(struct compile_state *state)
17907 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17909 struct triple *first, *ins;
17911 if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17915 /* Setup the work list */
17917 work_list_tail = &work_list;
17919 first = state->first;
17921 /* Count how many triples I have */
17922 triples = count_triples(state);
17924 /* Now put then in an array and mark all of the triples dead */
17925 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17930 dtriple[i].triple = ins;
17931 dtriple[i].block = block_of_triple(state, ins);
17932 dtriple[i].flags = 0;
17933 dtriple[i].old_id = ins->id;
17935 /* See if it is an operation we always keep */
17936 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17937 awaken(state, dtriple, &ins, &work_list_tail);
17941 } while(ins != first);
17943 struct block *block;
17944 struct dead_triple *dt;
17945 struct block_set *user;
17946 struct triple **expr;
17948 work_list = dt->work_next;
17950 work_list_tail = &work_list;
17952 /* Make certain the block the current instruction is in lives */
17953 block = block_of_triple(state, dt->triple);
17954 awaken(state, dtriple, &block->first, &work_list_tail);
17955 if (triple_is_branch(state, block->last)) {
17956 awaken(state, dtriple, &block->last, &work_list_tail);
17958 awaken(state, dtriple, &block->last->next, &work_list_tail);
17961 /* Wake up the data depencencies of this triple */
17964 expr = triple_rhs(state, dt->triple, expr);
17965 awaken(state, dtriple, expr, &work_list_tail);
17968 expr = triple_lhs(state, dt->triple, expr);
17969 awaken(state, dtriple, expr, &work_list_tail);
17972 expr = triple_misc(state, dt->triple, expr);
17973 awaken(state, dtriple, expr, &work_list_tail);
17975 /* Wake up the forward control dependencies */
17977 expr = triple_targ(state, dt->triple, expr);
17978 awaken(state, dtriple, expr, &work_list_tail);
17980 /* Wake up the reverse control dependencies of this triple */
17981 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17982 struct triple *last;
17983 last = user->member->last;
17984 while((last->op == OP_NOOP) && (last != user->member->first)) {
17985 #if DEBUG_ROMCC_WARNINGS
17986 #warning "Should we bring the awakening noops back?"
17988 // internal_warning(state, last, "awakening noop?");
17991 awaken(state, dtriple, &last, &work_list_tail);
17994 print_dead_triples(state, dtriple);
17995 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
17996 if ((dt->triple->op == OP_NOOP) &&
17997 (dt->flags & TRIPLE_FLAG_ALIVE)) {
17998 internal_error(state, dt->triple, "noop effective?");
18000 dt->triple->id = dt->old_id; /* Restore the color */
18001 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
18002 release_triple(state, dt->triple);
18007 rebuild_ssa_form(state);
18009 print_blocks(state, __func__, state->dbgout);
18013 static void insert_mandatory_copies(struct compile_state *state)
18015 struct triple *ins, *first;
18017 /* The object is with a minimum of inserted copies,
18018 * to resolve in fundamental register conflicts between
18019 * register value producers and consumers.
18020 * Theoretically we may be greater than minimal when we
18021 * are inserting copies before instructions but that
18022 * case should be rare.
18024 first = state->first;
18027 struct triple_set *entry, *next;
18028 struct triple *tmp;
18029 struct reg_info info;
18030 unsigned reg, regcm;
18031 int do_post_copy, do_pre_copy;
18033 if (!triple_is_def(state, ins)) {
18036 /* Find the architecture specific color information */
18037 info = find_lhs_pre_color(state, ins, 0);
18038 if (info.reg >= MAX_REGISTERS) {
18039 info.reg = REG_UNSET;
18043 regcm = arch_type_to_regcm(state, ins->type);
18044 do_post_copy = do_pre_copy = 0;
18046 /* Walk through the uses of ins and check for conflicts */
18047 for(entry = ins->use; entry; entry = next) {
18048 struct reg_info rinfo;
18050 next = entry->next;
18051 i = find_rhs_use(state, entry->member, ins);
18056 /* Find the users color requirements */
18057 rinfo = arch_reg_rhs(state, entry->member, i);
18058 if (rinfo.reg >= MAX_REGISTERS) {
18059 rinfo.reg = REG_UNSET;
18062 /* See if I need a pre_copy */
18063 if (rinfo.reg != REG_UNSET) {
18064 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
18069 regcm &= rinfo.regcm;
18070 regcm = arch_regcm_normalize(state, regcm);
18074 /* Always use pre_copies for constants.
18075 * They do not take up any registers until a
18076 * copy places them in one.
18078 if ((info.reg == REG_UNNEEDED) &&
18079 (rinfo.reg != REG_UNNEEDED)) {
18085 (((info.reg != REG_UNSET) &&
18086 (reg != REG_UNSET) &&
18087 (info.reg != reg)) ||
18088 ((info.regcm & regcm) == 0));
18091 regcm = info.regcm;
18092 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18093 for(entry = ins->use; entry; entry = next) {
18094 struct reg_info rinfo;
18096 next = entry->next;
18097 i = find_rhs_use(state, entry->member, ins);
18102 /* Find the users color requirements */
18103 rinfo = arch_reg_rhs(state, entry->member, i);
18104 if (rinfo.reg >= MAX_REGISTERS) {
18105 rinfo.reg = REG_UNSET;
18108 /* Now see if it is time to do the pre_copy */
18109 if (rinfo.reg != REG_UNSET) {
18110 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18111 ((regcm & rinfo.regcm) == 0) ||
18112 /* Don't let a mandatory coalesce sneak
18113 * into a operation that is marked to prevent
18116 ((reg != REG_UNNEEDED) &&
18117 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18118 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18121 struct triple *user;
18122 user = entry->member;
18123 if (RHS(user, i) != ins) {
18124 internal_error(state, user, "bad rhs");
18126 tmp = pre_copy(state, user, i);
18127 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18135 if ((regcm & rinfo.regcm) == 0) {
18137 struct triple *user;
18138 user = entry->member;
18139 if (RHS(user, i) != ins) {
18140 internal_error(state, user, "bad rhs");
18142 tmp = pre_copy(state, user, i);
18143 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18149 regcm &= rinfo.regcm;
18152 if (do_post_copy) {
18153 struct reg_info pre, post;
18154 tmp = post_copy(state, ins);
18155 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18156 pre = arch_reg_lhs(state, ins, 0);
18157 post = arch_reg_lhs(state, tmp, 0);
18158 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18159 internal_error(state, tmp, "useless copy");
18164 } while(ins != first);
18166 print_blocks(state, __func__, state->dbgout);
18170 struct live_range_edge;
18171 struct live_range_def;
18172 struct live_range {
18173 struct live_range_edge *edges;
18174 struct live_range_def *defs;
18175 /* Note. The list pointed to by defs is kept in order.
18176 * That is baring splits in the flow control
18177 * defs dominates defs->next wich dominates defs->next->next
18184 struct live_range *group_next, **group_prev;
18187 struct live_range_edge {
18188 struct live_range_edge *next;
18189 struct live_range *node;
18192 struct live_range_def {
18193 struct live_range_def *next;
18194 struct live_range_def *prev;
18195 struct live_range *lr;
18196 struct triple *def;
18200 #define LRE_HASH_SIZE 2048
18202 struct lre_hash *next;
18203 struct live_range *left;
18204 struct live_range *right;
18209 struct lre_hash *hash[LRE_HASH_SIZE];
18210 struct reg_block *blocks;
18211 struct live_range_def *lrd;
18212 struct live_range *lr;
18213 struct live_range *low, **low_tail;
18214 struct live_range *high, **high_tail;
18217 int passes, max_passes;
18221 struct print_interference_block_info {
18222 struct reg_state *rstate;
18226 static void print_interference_block(
18227 struct compile_state *state, struct block *block, void *arg)
18230 struct print_interference_block_info *info = arg;
18231 struct reg_state *rstate = info->rstate;
18232 struct block_set *edge;
18233 FILE *fp = info->fp;
18234 struct reg_block *rb;
18235 struct triple *ptr;
18238 rb = &rstate->blocks[block->vertex];
18240 fprintf(fp, "\nblock: %p (%d),",
18241 block, block->vertex);
18242 for(edge = block->edges; edge; edge = edge->next) {
18243 fprintf(fp, " %p<-%p",
18245 edge->member && edge->member->use?edge->member->use->member : 0);
18249 struct triple_reg_set *in_set;
18250 fprintf(fp, " in:");
18251 for(in_set = rb->in; in_set; in_set = in_set->next) {
18252 fprintf(fp, " %-10p", in_set->member);
18257 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18258 done = (ptr == block->last);
18259 if (ptr->op == OP_PHI) {
18266 for(edge = 0; edge < block->users; edge++) {
18267 fprintf(fp, " in(%d):", edge);
18268 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18269 struct triple **slot;
18270 done = (ptr == block->last);
18271 if (ptr->op != OP_PHI) {
18274 slot = &RHS(ptr, 0);
18275 fprintf(fp, " %-10p", slot[edge]);
18280 if (block->first->op == OP_LABEL) {
18281 fprintf(fp, "%p:\n", block->first);
18283 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18284 struct live_range *lr;
18286 done = (ptr == block->last);
18287 lr = rstate->lrd[ptr->id].lr;
18290 ptr->id = rstate->lrd[id].orig_id;
18291 SET_REG(ptr->id, lr->color);
18292 display_triple(fp, ptr);
18295 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18296 internal_error(state, ptr, "lr has no defs!");
18298 if (info->need_edges) {
18300 struct live_range_def *lrd;
18301 fprintf(fp, " range:");
18304 fprintf(fp, " %-10p", lrd->def);
18306 } while(lrd != lr->defs);
18309 if (lr->edges > 0) {
18310 struct live_range_edge *edge;
18311 fprintf(fp, " edges:");
18312 for(edge = lr->edges; edge; edge = edge->next) {
18313 struct live_range_def *lrd;
18314 lrd = edge->node->defs;
18316 fprintf(fp, " %-10p", lrd->def);
18318 } while(lrd != edge->node->defs);
18324 /* Do a bunch of sanity checks */
18325 valid_ins(state, ptr);
18326 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18327 internal_error(state, ptr, "Invalid triple id: %d",
18332 struct triple_reg_set *out_set;
18333 fprintf(fp, " out:");
18334 for(out_set = rb->out; out_set; out_set = out_set->next) {
18335 fprintf(fp, " %-10p", out_set->member);
18342 static void print_interference_blocks(
18343 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18345 struct print_interference_block_info info;
18346 info.rstate = rstate;
18348 info.need_edges = need_edges;
18349 fprintf(fp, "\nlive variables by block\n");
18350 walk_blocks(state, &state->bb, print_interference_block, &info);
18354 static unsigned regc_max_size(struct compile_state *state, int classes)
18359 for(i = 0; i < MAX_REGC; i++) {
18360 if (classes & (1 << i)) {
18362 size = arch_regc_size(state, i);
18363 if (size > max_size) {
18371 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18373 unsigned equivs[MAX_REG_EQUIVS];
18375 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18376 internal_error(state, 0, "invalid register");
18378 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18379 internal_error(state, 0, "invalid register");
18381 arch_reg_equivs(state, equivs, reg1);
18382 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18383 if (equivs[i] == reg2) {
18390 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18392 unsigned equivs[MAX_REG_EQUIVS];
18394 if (reg == REG_UNNEEDED) {
18397 arch_reg_equivs(state, equivs, reg);
18398 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18399 used[equivs[i]] = 1;
18404 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18406 unsigned equivs[MAX_REG_EQUIVS];
18408 if (reg == REG_UNNEEDED) {
18411 arch_reg_equivs(state, equivs, reg);
18412 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18413 used[equivs[i]] += 1;
18418 static unsigned int hash_live_edge(
18419 struct live_range *left, struct live_range *right)
18421 unsigned int hash, val;
18422 unsigned long lval, rval;
18423 lval = ((unsigned long)left)/sizeof(struct live_range);
18424 rval = ((unsigned long)right)/sizeof(struct live_range);
18429 hash = (hash *263) + val;
18434 hash = (hash *263) + val;
18436 hash = hash & (LRE_HASH_SIZE - 1);
18440 static struct lre_hash **lre_probe(struct reg_state *rstate,
18441 struct live_range *left, struct live_range *right)
18443 struct lre_hash **ptr;
18444 unsigned int index;
18445 /* Ensure left <= right */
18446 if (left > right) {
18447 struct live_range *tmp;
18452 index = hash_live_edge(left, right);
18454 ptr = &rstate->hash[index];
18456 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18459 ptr = &(*ptr)->next;
18464 static int interfere(struct reg_state *rstate,
18465 struct live_range *left, struct live_range *right)
18467 struct lre_hash **ptr;
18468 ptr = lre_probe(rstate, left, right);
18469 return ptr && *ptr;
18472 static void add_live_edge(struct reg_state *rstate,
18473 struct live_range *left, struct live_range *right)
18475 /* FIXME the memory allocation overhead is noticeable here... */
18476 struct lre_hash **ptr, *new_hash;
18477 struct live_range_edge *edge;
18479 if (left == right) {
18482 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18485 /* Ensure left <= right */
18486 if (left > right) {
18487 struct live_range *tmp;
18492 ptr = lre_probe(rstate, left, right);
18497 fprintf(state->errout, "new_live_edge(%p, %p)\n",
18500 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18501 new_hash->next = *ptr;
18502 new_hash->left = left;
18503 new_hash->right = right;
18506 edge = xmalloc(sizeof(*edge), "live_range_edge");
18507 edge->next = left->edges;
18508 edge->node = right;
18509 left->edges = edge;
18512 edge = xmalloc(sizeof(*edge), "live_range_edge");
18513 edge->next = right->edges;
18515 right->edges = edge;
18516 right->degree += 1;
18519 static void remove_live_edge(struct reg_state *rstate,
18520 struct live_range *left, struct live_range *right)
18522 struct live_range_edge *edge, **ptr;
18523 struct lre_hash **hptr, *entry;
18524 hptr = lre_probe(rstate, left, right);
18525 if (!hptr || !*hptr) {
18529 *hptr = entry->next;
18532 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18534 if (edge->node == right) {
18536 memset(edge, 0, sizeof(*edge));
18542 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18544 if (edge->node == left) {
18546 memset(edge, 0, sizeof(*edge));
18554 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18556 struct live_range_edge *edge, *next;
18557 for(edge = range->edges; edge; edge = next) {
18559 remove_live_edge(rstate, range, edge->node);
18563 static void transfer_live_edges(struct reg_state *rstate,
18564 struct live_range *dest, struct live_range *src)
18566 struct live_range_edge *edge, *next;
18567 for(edge = src->edges; edge; edge = next) {
18568 struct live_range *other;
18570 other = edge->node;
18571 remove_live_edge(rstate, src, other);
18572 add_live_edge(rstate, dest, other);
18577 /* Interference graph...
18579 * new(n) --- Return a graph with n nodes but no edges.
18580 * add(g,x,y) --- Return a graph including g with an between x and y
18581 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18582 * x and y in the graph g
18583 * degree(g, x) --- Return the degree of the node x in the graph g
18584 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18586 * Implement with a hash table && a set of adjcency vectors.
18587 * The hash table supports constant time implementations of add and interfere.
18588 * The adjacency vectors support an efficient implementation of neighbors.
18592 * +---------------------------------------------------+
18593 * | +--------------+ |
18595 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
18597 * -- In simplify implment optimistic coloring... (No backtracking)
18598 * -- Implement Rematerialization it is the only form of spilling we can perform
18599 * Essentially this means dropping a constant from a register because
18600 * we can regenerate it later.
18602 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18603 * coalesce at phi points...
18604 * --- Bias coloring if at all possible do the coalesing a compile time.
18609 #if DEBUG_ROMCC_WARNING
18610 static void different_colored(
18611 struct compile_state *state, struct reg_state *rstate,
18612 struct triple *parent, struct triple *ins)
18614 struct live_range *lr;
18615 struct triple **expr;
18616 lr = rstate->lrd[ins->id].lr;
18617 expr = triple_rhs(state, ins, 0);
18618 for(;expr; expr = triple_rhs(state, ins, expr)) {
18619 struct live_range *lr2;
18620 if (!*expr || (*expr == parent) || (*expr == ins)) {
18623 lr2 = rstate->lrd[(*expr)->id].lr;
18624 if (lr->color == lr2->color) {
18625 internal_error(state, ins, "live range too big");
18631 static struct live_range *coalesce_ranges(
18632 struct compile_state *state, struct reg_state *rstate,
18633 struct live_range *lr1, struct live_range *lr2)
18635 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18641 if (!lr1->defs || !lr2->defs) {
18642 internal_error(state, 0,
18643 "cannot coalese dead live ranges");
18645 if ((lr1->color == REG_UNNEEDED) ||
18646 (lr2->color == REG_UNNEEDED)) {
18647 internal_error(state, 0,
18648 "cannot coalesce live ranges without a possible color");
18650 if ((lr1->color != lr2->color) &&
18651 (lr1->color != REG_UNSET) &&
18652 (lr2->color != REG_UNSET)) {
18653 internal_error(state, lr1->defs->def,
18654 "cannot coalesce live ranges of different colors");
18656 color = lr1->color;
18657 if (color == REG_UNSET) {
18658 color = lr2->color;
18660 classes = lr1->classes & lr2->classes;
18662 internal_error(state, lr1->defs->def,
18663 "cannot coalesce live ranges with dissimilar register classes");
18665 if (state->compiler->debug & DEBUG_COALESCING) {
18666 FILE *fp = state->errout;
18667 fprintf(fp, "coalescing:");
18670 fprintf(fp, " %p", lrd->def);
18672 } while(lrd != lr1->defs);
18676 fprintf(fp, " %p", lrd->def);
18678 } while(lrd != lr2->defs);
18681 /* If there is a clear dominate live range put it in lr1,
18682 * For purposes of this test phi functions are
18683 * considered dominated by the definitions that feed into
18686 if ((lr1->defs->prev->def->op == OP_PHI) ||
18687 ((lr2->defs->prev->def->op != OP_PHI) &&
18688 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18689 struct live_range *tmp;
18695 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18696 fprintf(state->errout, "lr1 post\n");
18698 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18699 fprintf(state->errout, "lr1 pre\n");
18701 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18702 fprintf(state->errout, "lr2 post\n");
18704 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18705 fprintf(state->errout, "lr2 pre\n");
18709 fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18716 /* Append lr2 onto lr1 */
18717 #if DEBUG_ROMCC_WARNINGS
18718 #warning "FIXME should this be a merge instead of a splice?"
18720 /* This FIXME item applies to the correctness of live_range_end
18721 * and to the necessity of making multiple passes of coalesce_live_ranges.
18722 * A failure to find some coalesce opportunities in coaleace_live_ranges
18723 * does not impact the correct of the compiler just the efficiency with
18724 * which registers are allocated.
18727 mid1 = lr1->defs->prev;
18729 end = lr2->defs->prev;
18737 /* Fixup the live range in the added live range defs */
18742 } while(lrd != head);
18744 /* Mark lr2 as free. */
18746 lr2->color = REG_UNNEEDED;
18750 internal_error(state, 0, "lr1->defs == 0 ?");
18753 lr1->color = color;
18754 lr1->classes = classes;
18756 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18757 transfer_live_edges(rstate, lr1, lr2);
18762 static struct live_range_def *live_range_head(
18763 struct compile_state *state, struct live_range *lr,
18764 struct live_range_def *last)
18766 struct live_range_def *result;
18771 else if (!tdominates(state, lr->defs->def, last->next->def)) {
18772 result = last->next;
18777 static struct live_range_def *live_range_end(
18778 struct compile_state *state, struct live_range *lr,
18779 struct live_range_def *last)
18781 struct live_range_def *result;
18784 result = lr->defs->prev;
18786 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18787 result = last->prev;
18793 static void initialize_live_ranges(
18794 struct compile_state *state, struct reg_state *rstate)
18796 struct triple *ins, *first;
18797 size_t count, size;
18800 first = state->first;
18801 /* First count how many instructions I have.
18803 count = count_triples(state);
18804 /* Potentially I need one live range definitions for each
18807 rstate->defs = count;
18808 /* Potentially I need one live range for each instruction
18809 * plus an extra for the dummy live range.
18811 rstate->ranges = count + 1;
18812 size = sizeof(rstate->lrd[0]) * rstate->defs;
18813 rstate->lrd = xcmalloc(size, "live_range_def");
18814 size = sizeof(rstate->lr[0]) * rstate->ranges;
18815 rstate->lr = xcmalloc(size, "live_range");
18817 /* Setup the dummy live range */
18818 rstate->lr[0].classes = 0;
18819 rstate->lr[0].color = REG_UNSET;
18820 rstate->lr[0].defs = 0;
18824 /* If the triple is a variable give it a live range */
18825 if (triple_is_def(state, ins)) {
18826 struct reg_info info;
18827 /* Find the architecture specific color information */
18828 info = find_def_color(state, ins);
18830 rstate->lr[i].defs = &rstate->lrd[j];
18831 rstate->lr[i].color = info.reg;
18832 rstate->lr[i].classes = info.regcm;
18833 rstate->lr[i].degree = 0;
18834 rstate->lrd[j].lr = &rstate->lr[i];
18836 /* Otherwise give the triple the dummy live range. */
18838 rstate->lrd[j].lr = &rstate->lr[0];
18841 /* Initalize the live_range_def */
18842 rstate->lrd[j].next = &rstate->lrd[j];
18843 rstate->lrd[j].prev = &rstate->lrd[j];
18844 rstate->lrd[j].def = ins;
18845 rstate->lrd[j].orig_id = ins->id;
18850 } while(ins != first);
18851 rstate->ranges = i;
18853 /* Make a second pass to handle achitecture specific register
18858 int zlhs, zrhs, i, j;
18859 if (ins->id > rstate->defs) {
18860 internal_error(state, ins, "bad id");
18863 /* Walk through the template of ins and coalesce live ranges */
18865 if ((zlhs == 0) && triple_is_def(state, ins)) {
18870 if (state->compiler->debug & DEBUG_COALESCING2) {
18871 fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18875 for(i = 0; i < zlhs; i++) {
18876 struct reg_info linfo;
18877 struct live_range_def *lhs;
18878 linfo = arch_reg_lhs(state, ins, i);
18879 if (linfo.reg < MAX_REGISTERS) {
18882 if (triple_is_def(state, ins)) {
18883 lhs = &rstate->lrd[ins->id];
18885 lhs = &rstate->lrd[LHS(ins, i)->id];
18888 if (state->compiler->debug & DEBUG_COALESCING2) {
18889 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18890 i, lhs, linfo.reg);
18893 for(j = 0; j < zrhs; j++) {
18894 struct reg_info rinfo;
18895 struct live_range_def *rhs;
18896 rinfo = arch_reg_rhs(state, ins, j);
18897 if (rinfo.reg < MAX_REGISTERS) {
18900 rhs = &rstate->lrd[RHS(ins, j)->id];
18902 if (state->compiler->debug & DEBUG_COALESCING2) {
18903 fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18904 j, rhs, rinfo.reg);
18907 if (rinfo.reg == linfo.reg) {
18908 coalesce_ranges(state, rstate,
18914 } while(ins != first);
18917 static void graph_ins(
18918 struct compile_state *state,
18919 struct reg_block *blocks, struct triple_reg_set *live,
18920 struct reg_block *rb, struct triple *ins, void *arg)
18922 struct reg_state *rstate = arg;
18923 struct live_range *def;
18924 struct triple_reg_set *entry;
18926 /* If the triple is not a definition
18927 * we do not have a definition to add to
18928 * the interference graph.
18930 if (!triple_is_def(state, ins)) {
18933 def = rstate->lrd[ins->id].lr;
18935 /* Create an edge between ins and everything that is
18936 * alive, unless the live_range cannot share
18937 * a physical register with ins.
18939 for(entry = live; entry; entry = entry->next) {
18940 struct live_range *lr;
18941 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18942 internal_error(state, 0, "bad entry?");
18944 lr = rstate->lrd[entry->member->id].lr;
18948 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18951 add_live_edge(rstate, def, lr);
18956 #if DEBUG_CONSISTENCY > 1
18957 static struct live_range *get_verify_live_range(
18958 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18960 struct live_range *lr;
18961 struct live_range_def *lrd;
18963 if ((ins->id < 0) || (ins->id > rstate->defs)) {
18964 internal_error(state, ins, "bad ins?");
18966 lr = rstate->lrd[ins->id].lr;
18970 if (lrd->def == ins) {
18974 } while(lrd != lr->defs);
18976 internal_error(state, ins, "ins not in live range");
18981 static void verify_graph_ins(
18982 struct compile_state *state,
18983 struct reg_block *blocks, struct triple_reg_set *live,
18984 struct reg_block *rb, struct triple *ins, void *arg)
18986 struct reg_state *rstate = arg;
18987 struct triple_reg_set *entry1, *entry2;
18990 /* Compare live against edges and make certain the code is working */
18991 for(entry1 = live; entry1; entry1 = entry1->next) {
18992 struct live_range *lr1;
18993 lr1 = get_verify_live_range(state, rstate, entry1->member);
18994 for(entry2 = live; entry2; entry2 = entry2->next) {
18995 struct live_range *lr2;
18996 struct live_range_edge *edge2;
18999 if (entry2 == entry1) {
19002 lr2 = get_verify_live_range(state, rstate, entry2->member);
19004 internal_error(state, entry2->member,
19005 "live range with 2 values simultaneously alive");
19007 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
19010 if (!interfere(rstate, lr1, lr2)) {
19011 internal_error(state, entry2->member,
19012 "edges don't interfere?");
19017 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
19019 if (edge2->node == lr1) {
19023 if (lr2_degree != lr2->degree) {
19024 internal_error(state, entry2->member,
19025 "computed degree: %d does not match reported degree: %d\n",
19026 lr2_degree, lr2->degree);
19029 internal_error(state, entry2->member, "missing edge");
19037 static void print_interference_ins(
19038 struct compile_state *state,
19039 struct reg_block *blocks, struct triple_reg_set *live,
19040 struct reg_block *rb, struct triple *ins, void *arg)
19042 struct reg_state *rstate = arg;
19043 struct live_range *lr;
19045 FILE *fp = state->dbgout;
19047 lr = rstate->lrd[ins->id].lr;
19049 ins->id = rstate->lrd[id].orig_id;
19050 SET_REG(ins->id, lr->color);
19051 display_triple(state->dbgout, ins);
19055 struct live_range_def *lrd;
19056 fprintf(fp, " range:");
19059 fprintf(fp, " %-10p", lrd->def);
19061 } while(lrd != lr->defs);
19065 struct triple_reg_set *entry;
19066 fprintf(fp, " live:");
19067 for(entry = live; entry; entry = entry->next) {
19068 fprintf(fp, " %-10p", entry->member);
19073 struct live_range_edge *entry;
19074 fprintf(fp, " edges:");
19075 for(entry = lr->edges; entry; entry = entry->next) {
19076 struct live_range_def *lrd;
19077 lrd = entry->node->defs;
19079 fprintf(fp, " %-10p", lrd->def);
19081 } while(lrd != entry->node->defs);
19086 if (triple_is_branch(state, ins)) {
19092 static int coalesce_live_ranges(
19093 struct compile_state *state, struct reg_state *rstate)
19095 /* At the point where a value is moved from one
19096 * register to another that value requires two
19097 * registers, thus increasing register pressure.
19098 * Live range coaleescing reduces the register
19099 * pressure by keeping a value in one register
19102 * In the case of a phi function all paths leading
19103 * into it must be allocated to the same register
19104 * otherwise the phi function may not be removed.
19106 * Forcing a value to stay in a single register
19107 * for an extended period of time does have
19108 * limitations when applied to non homogenous
19111 * The two cases I have identified are:
19112 * 1) Two forced register assignments may
19114 * 2) Registers may go unused because they
19115 * are only good for storing the value
19116 * and not manipulating it.
19118 * Because of this I need to split live ranges,
19119 * even outside of the context of coalesced live
19120 * ranges. The need to split live ranges does
19121 * impose some constraints on live range coalescing.
19123 * - Live ranges may not be coalesced across phi
19124 * functions. This creates a 2 headed live
19125 * range that cannot be sanely split.
19127 * - phi functions (coalesced in initialize_live_ranges)
19128 * are handled as pre split live ranges so we will
19129 * never attempt to split them.
19135 for(i = 0; i <= rstate->ranges; i++) {
19136 struct live_range *lr1;
19137 struct live_range_def *lrd1;
19138 lr1 = &rstate->lr[i];
19142 lrd1 = live_range_end(state, lr1, 0);
19143 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19144 struct triple_set *set;
19145 if (lrd1->def->op != OP_COPY) {
19148 /* Skip copies that are the result of a live range split. */
19149 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19152 for(set = lrd1->def->use; set; set = set->next) {
19153 struct live_range_def *lrd2;
19154 struct live_range *lr2, *res;
19156 lrd2 = &rstate->lrd[set->member->id];
19158 /* Don't coalesce with instructions
19159 * that are the result of a live range
19162 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19165 lr2 = rstate->lrd[set->member->id].lr;
19169 if ((lr1->color != lr2->color) &&
19170 (lr1->color != REG_UNSET) &&
19171 (lr2->color != REG_UNSET)) {
19174 if ((lr1->classes & lr2->classes) == 0) {
19178 if (interfere(rstate, lr1, lr2)) {
19182 res = coalesce_ranges(state, rstate, lr1, lr2);
19196 static void fix_coalesce_conflicts(struct compile_state *state,
19197 struct reg_block *blocks, struct triple_reg_set *live,
19198 struct reg_block *rb, struct triple *ins, void *arg)
19200 int *conflicts = arg;
19201 int zlhs, zrhs, i, j;
19203 /* See if we have a mandatory coalesce operation between
19204 * a lhs and a rhs value. If so and the rhs value is also
19205 * alive then this triple needs to be pre copied. Otherwise
19206 * we would have two definitions in the same live range simultaneously
19210 if ((zlhs == 0) && triple_is_def(state, ins)) {
19214 for(i = 0; i < zlhs; i++) {
19215 struct reg_info linfo;
19216 linfo = arch_reg_lhs(state, ins, i);
19217 if (linfo.reg < MAX_REGISTERS) {
19220 for(j = 0; j < zrhs; j++) {
19221 struct reg_info rinfo;
19222 struct triple *rhs;
19223 struct triple_reg_set *set;
19226 rinfo = arch_reg_rhs(state, ins, j);
19227 if (rinfo.reg != linfo.reg) {
19231 for(set = live; set && !found; set = set->next) {
19232 if (set->member == rhs) {
19237 struct triple *copy;
19238 copy = pre_copy(state, ins, j);
19239 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19247 static int correct_coalesce_conflicts(
19248 struct compile_state *state, struct reg_block *blocks)
19252 walk_variable_lifetimes(state, &state->bb, blocks,
19253 fix_coalesce_conflicts, &conflicts);
19257 static void replace_set_use(struct compile_state *state,
19258 struct triple_reg_set *head, struct triple *orig, struct triple *new)
19260 struct triple_reg_set *set;
19261 for(set = head; set; set = set->next) {
19262 if (set->member == orig) {
19268 static void replace_block_use(struct compile_state *state,
19269 struct reg_block *blocks, struct triple *orig, struct triple *new)
19272 #if DEBUG_ROMCC_WARNINGS
19273 #warning "WISHLIST visit just those blocks that need it *"
19275 for(i = 1; i <= state->bb.last_vertex; i++) {
19276 struct reg_block *rb;
19278 replace_set_use(state, rb->in, orig, new);
19279 replace_set_use(state, rb->out, orig, new);
19283 static void color_instructions(struct compile_state *state)
19285 struct triple *ins, *first;
19286 first = state->first;
19289 if (triple_is_def(state, ins)) {
19290 struct reg_info info;
19291 info = find_lhs_color(state, ins, 0);
19292 if (info.reg >= MAX_REGISTERS) {
19293 info.reg = REG_UNSET;
19295 SET_INFO(ins->id, info);
19298 } while(ins != first);
19301 static struct reg_info read_lhs_color(
19302 struct compile_state *state, struct triple *ins, int index)
19304 struct reg_info info;
19305 if ((index == 0) && triple_is_def(state, ins)) {
19306 info.reg = ID_REG(ins->id);
19307 info.regcm = ID_REGCM(ins->id);
19309 else if (index < ins->lhs) {
19310 info = read_lhs_color(state, LHS(ins, index), 0);
19313 internal_error(state, ins, "Bad lhs %d", index);
19314 info.reg = REG_UNSET;
19320 static struct triple *resolve_tangle(
19321 struct compile_state *state, struct triple *tangle)
19323 struct reg_info info, uinfo;
19324 struct triple_set *set, *next;
19325 struct triple *copy;
19327 #if DEBUG_ROMCC_WARNINGS
19328 #warning "WISHLIST recalculate all affected instructions colors"
19330 info = find_lhs_color(state, tangle, 0);
19331 for(set = tangle->use; set; set = next) {
19332 struct triple *user;
19335 user = set->member;
19337 for(i = 0; i < zrhs; i++) {
19338 if (RHS(user, i) != tangle) {
19341 uinfo = find_rhs_post_color(state, user, i);
19342 if (uinfo.reg == info.reg) {
19343 copy = pre_copy(state, user, i);
19344 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19345 SET_INFO(copy->id, uinfo);
19350 uinfo = find_lhs_pre_color(state, tangle, 0);
19351 if (uinfo.reg == info.reg) {
19352 struct reg_info linfo;
19353 copy = post_copy(state, tangle);
19354 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19355 linfo = find_lhs_color(state, copy, 0);
19356 SET_INFO(copy->id, linfo);
19358 info = find_lhs_color(state, tangle, 0);
19359 SET_INFO(tangle->id, info);
19365 static void fix_tangles(struct compile_state *state,
19366 struct reg_block *blocks, struct triple_reg_set *live,
19367 struct reg_block *rb, struct triple *ins, void *arg)
19369 int *tangles = arg;
19370 struct triple *tangle;
19372 char used[MAX_REGISTERS];
19373 struct triple_reg_set *set;
19376 /* Find out which registers have multiple uses at this point */
19377 memset(used, 0, sizeof(used));
19378 for(set = live; set; set = set->next) {
19379 struct reg_info info;
19380 info = read_lhs_color(state, set->member, 0);
19381 if (info.reg == REG_UNSET) {
19384 reg_inc_used(state, used, info.reg);
19387 /* Now find the least dominated definition of a register in
19388 * conflict I have seen so far.
19390 for(set = live; set; set = set->next) {
19391 struct reg_info info;
19392 info = read_lhs_color(state, set->member, 0);
19393 if (used[info.reg] < 2) {
19396 /* Changing copies that feed into phi functions
19399 if (set->member->use &&
19400 (set->member->use->member->op == OP_PHI)) {
19403 if (!tangle || tdominates(state, set->member, tangle)) {
19404 tangle = set->member;
19407 /* If I have found a tangle resolve it */
19409 struct triple *post_copy;
19411 post_copy = resolve_tangle(state, tangle);
19413 replace_block_use(state, blocks, tangle, post_copy);
19415 if (post_copy && (tangle != ins)) {
19416 replace_set_use(state, live, tangle, post_copy);
19423 static int correct_tangles(
19424 struct compile_state *state, struct reg_block *blocks)
19428 color_instructions(state);
19429 walk_variable_lifetimes(state, &state->bb, blocks,
19430 fix_tangles, &tangles);
19435 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19436 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19438 struct triple *find_constrained_def(
19439 struct compile_state *state, struct live_range *range, struct triple *constrained)
19441 struct live_range_def *lrd, *lrd_next;
19442 lrd_next = range->defs;
19444 struct reg_info info;
19448 lrd_next = lrd->next;
19450 regcm = arch_type_to_regcm(state, lrd->def->type);
19451 info = find_lhs_color(state, lrd->def, 0);
19452 regcm = arch_regcm_reg_normalize(state, regcm);
19453 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19454 /* If the 2 register class masks are equal then
19455 * the current register class is not constrained.
19457 if (regcm == info.regcm) {
19461 /* If there is just one use.
19462 * That use cannot accept a larger register class.
19463 * There are no intervening definitions except
19464 * definitions that feed into that use.
19465 * Then a triple is not constrained.
19466 * FIXME handle this case!
19468 #if DEBUG_ROMCC_WARNINGS
19469 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19473 /* Of the constrained live ranges deal with the
19474 * least dominated one first.
19476 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19477 fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19478 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19480 if (!constrained ||
19481 tdominates(state, lrd->def, constrained))
19483 constrained = lrd->def;
19485 } while(lrd_next != range->defs);
19486 return constrained;
19489 static int split_constrained_ranges(
19490 struct compile_state *state, struct reg_state *rstate,
19491 struct live_range *range)
19493 /* Walk through the edges in conflict and our current live
19494 * range, and find definitions that are more severly constrained
19495 * than they type of data they contain require.
19497 * Then pick one of those ranges and relax the constraints.
19499 struct live_range_edge *edge;
19500 struct triple *constrained;
19503 for(edge = range->edges; edge; edge = edge->next) {
19504 constrained = find_constrained_def(state, edge->node, constrained);
19506 #if DEBUG_ROMCC_WARNINGS
19507 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19509 if (!constrained) {
19510 constrained = find_constrained_def(state, range, constrained);
19513 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19514 fprintf(state->errout, "constrained: ");
19515 display_triple(state->errout, constrained);
19518 ids_from_rstate(state, rstate);
19519 cleanup_rstate(state, rstate);
19520 resolve_tangle(state, constrained);
19522 return !!constrained;
19525 static int split_ranges(
19526 struct compile_state *state, struct reg_state *rstate,
19527 char *used, struct live_range *range)
19530 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19531 fprintf(state->errout, "split_ranges %d %s %p\n",
19532 rstate->passes, tops(range->defs->def->op), range->defs->def);
19534 if ((range->color == REG_UNNEEDED) ||
19535 (rstate->passes >= rstate->max_passes)) {
19538 split = split_constrained_ranges(state, rstate, range);
19540 /* Ideally I would split the live range that will not be used
19541 * for the longest period of time in hopes that this will
19542 * (a) allow me to spill a register or
19543 * (b) allow me to place a value in another register.
19545 * So far I don't have a test case for this, the resolving
19546 * of mandatory constraints has solved all of my
19547 * know issues. So I have choosen not to write any
19548 * code until I cat get a better feel for cases where
19549 * it would be useful to have.
19552 #if DEBUG_ROMCC_WARNINGS
19553 #warning "WISHLIST implement live range splitting..."
19556 if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19557 FILE *fp = state->errout;
19558 print_interference_blocks(state, rstate, fp, 0);
19559 print_dominators(state, fp, &state->bb);
19564 static FILE *cgdebug_fp(struct compile_state *state)
19568 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19569 fp = state->errout;
19571 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19572 fp = state->dbgout;
19577 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19580 fp = cgdebug_fp(state);
19583 va_start(args, fmt);
19584 vfprintf(fp, fmt, args);
19589 static void cgdebug_flush(struct compile_state *state)
19592 fp = cgdebug_fp(state);
19598 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19601 fp = cgdebug_fp(state);
19603 loc(fp, state, ins);
19607 static int select_free_color(struct compile_state *state,
19608 struct reg_state *rstate, struct live_range *range)
19610 struct triple_set *entry;
19611 struct live_range_def *lrd;
19612 struct live_range_def *phi;
19613 struct live_range_edge *edge;
19614 char used[MAX_REGISTERS];
19615 struct triple **expr;
19617 /* Instead of doing just the trivial color select here I try
19618 * a few extra things because a good color selection will help reduce
19622 /* Find the registers currently in use */
19623 memset(used, 0, sizeof(used));
19624 for(edge = range->edges; edge; edge = edge->next) {
19625 if (edge->node->color == REG_UNSET) {
19628 reg_fill_used(state, used, edge->node->color);
19631 if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19634 for(edge = range->edges; edge; edge = edge->next) {
19637 cgdebug_printf(state, "\n%s edges: %d",
19638 tops(range->defs->def->op), i);
19639 cgdebug_loc(state, range->defs->def);
19640 cgdebug_printf(state, "\n");
19641 for(i = 0; i < MAX_REGISTERS; i++) {
19643 cgdebug_printf(state, "used: %s\n",
19649 /* If a color is already assigned see if it will work */
19650 if (range->color != REG_UNSET) {
19651 struct live_range_def *lrd;
19652 if (!used[range->color]) {
19655 for(edge = range->edges; edge; edge = edge->next) {
19656 if (edge->node->color != range->color) {
19659 warning(state, edge->node->defs->def, "edge: ");
19660 lrd = edge->node->defs;
19662 warning(state, lrd->def, " %p %s",
19663 lrd->def, tops(lrd->def->op));
19665 } while(lrd != edge->node->defs);
19668 warning(state, range->defs->def, "def: ");
19670 warning(state, lrd->def, " %p %s",
19671 lrd->def, tops(lrd->def->op));
19673 } while(lrd != range->defs);
19674 internal_error(state, range->defs->def,
19675 "live range with already used color %s",
19676 arch_reg_str(range->color));
19679 /* If I feed into an expression reuse it's color.
19680 * This should help remove copies in the case of 2 register instructions
19681 * and phi functions.
19684 lrd = live_range_end(state, range, 0);
19685 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19686 entry = lrd->def->use;
19687 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19688 struct live_range_def *insd;
19690 insd = &rstate->lrd[entry->member->id];
19691 if (insd->lr->defs == 0) {
19694 if (!phi && (insd->def->op == OP_PHI) &&
19695 !interfere(rstate, range, insd->lr)) {
19698 if (insd->lr->color == REG_UNSET) {
19701 regcm = insd->lr->classes;
19702 if (((regcm & range->classes) == 0) ||
19703 (used[insd->lr->color])) {
19706 if (interfere(rstate, range, insd->lr)) {
19709 range->color = insd->lr->color;
19712 /* If I feed into a phi function reuse it's color or the color
19713 * of something else that feeds into the phi function.
19716 if (phi->lr->color != REG_UNSET) {
19717 if (used[phi->lr->color]) {
19718 range->color = phi->lr->color;
19722 expr = triple_rhs(state, phi->def, 0);
19723 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19724 struct live_range *lr;
19729 lr = rstate->lrd[(*expr)->id].lr;
19730 if (lr->color == REG_UNSET) {
19733 regcm = lr->classes;
19734 if (((regcm & range->classes) == 0) ||
19735 (used[lr->color])) {
19738 if (interfere(rstate, range, lr)) {
19741 range->color = lr->color;
19745 /* If I don't interfere with a rhs node reuse it's color */
19746 lrd = live_range_head(state, range, 0);
19747 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19748 expr = triple_rhs(state, lrd->def, 0);
19749 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19750 struct live_range *lr;
19755 lr = rstate->lrd[(*expr)->id].lr;
19756 if (lr->color == REG_UNSET) {
19759 regcm = lr->classes;
19760 if (((regcm & range->classes) == 0) ||
19761 (used[lr->color])) {
19764 if (interfere(rstate, range, lr)) {
19767 range->color = lr->color;
19771 /* If I have not opportunitically picked a useful color
19772 * pick the first color that is free.
19774 if (range->color == REG_UNSET) {
19776 arch_select_free_register(state, used, range->classes);
19778 if (range->color == REG_UNSET) {
19779 struct live_range_def *lrd;
19781 if (split_ranges(state, rstate, used, range)) {
19784 for(edge = range->edges; edge; edge = edge->next) {
19785 warning(state, edge->node->defs->def, "edge reg %s",
19786 arch_reg_str(edge->node->color));
19787 lrd = edge->node->defs;
19789 warning(state, lrd->def, " %s %p",
19790 tops(lrd->def->op), lrd->def);
19792 } while(lrd != edge->node->defs);
19794 warning(state, range->defs->def, "range: ");
19797 warning(state, lrd->def, " %s %p",
19798 tops(lrd->def->op), lrd->def);
19800 } while(lrd != range->defs);
19802 warning(state, range->defs->def, "classes: %x",
19804 for(i = 0; i < MAX_REGISTERS; i++) {
19806 warning(state, range->defs->def, "used: %s",
19810 error(state, range->defs->def, "too few registers");
19812 range->classes &= arch_reg_regcm(state, range->color);
19813 if ((range->color == REG_UNSET) || (range->classes == 0)) {
19814 internal_error(state, range->defs->def, "select_free_color did not?");
19819 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19822 struct live_range_edge *edge;
19823 struct live_range *range;
19825 cgdebug_printf(state, "Lo: ");
19826 range = rstate->low;
19827 if (*range->group_prev != range) {
19828 internal_error(state, 0, "lo: *prev != range?");
19830 *range->group_prev = range->group_next;
19831 if (range->group_next) {
19832 range->group_next->group_prev = range->group_prev;
19834 if (&range->group_next == rstate->low_tail) {
19835 rstate->low_tail = range->group_prev;
19837 if (rstate->low == range) {
19838 internal_error(state, 0, "low: next != prev?");
19841 else if (rstate->high) {
19842 cgdebug_printf(state, "Hi: ");
19843 range = rstate->high;
19844 if (*range->group_prev != range) {
19845 internal_error(state, 0, "hi: *prev != range?");
19847 *range->group_prev = range->group_next;
19848 if (range->group_next) {
19849 range->group_next->group_prev = range->group_prev;
19851 if (&range->group_next == rstate->high_tail) {
19852 rstate->high_tail = range->group_prev;
19854 if (rstate->high == range) {
19855 internal_error(state, 0, "high: next != prev?");
19861 cgdebug_printf(state, " %d\n", range - rstate->lr);
19862 range->group_prev = 0;
19863 for(edge = range->edges; edge; edge = edge->next) {
19864 struct live_range *node;
19866 /* Move nodes from the high to the low list */
19867 if (node->group_prev && (node->color == REG_UNSET) &&
19868 (node->degree == regc_max_size(state, node->classes))) {
19869 if (*node->group_prev != node) {
19870 internal_error(state, 0, "move: *prev != node?");
19872 *node->group_prev = node->group_next;
19873 if (node->group_next) {
19874 node->group_next->group_prev = node->group_prev;
19876 if (&node->group_next == rstate->high_tail) {
19877 rstate->high_tail = node->group_prev;
19879 cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19880 node->group_prev = rstate->low_tail;
19881 node->group_next = 0;
19882 *rstate->low_tail = node;
19883 rstate->low_tail = &node->group_next;
19884 if (*node->group_prev != node) {
19885 internal_error(state, 0, "move2: *prev != node?");
19890 colored = color_graph(state, rstate);
19892 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19893 cgdebug_loc(state, range->defs->def);
19894 cgdebug_flush(state);
19895 colored = select_free_color(state, rstate, range);
19897 cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19903 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19905 struct live_range *lr;
19906 struct live_range_edge *edge;
19907 struct triple *ins, *first;
19908 char used[MAX_REGISTERS];
19909 first = state->first;
19912 if (triple_is_def(state, ins)) {
19913 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19914 internal_error(state, ins,
19915 "triple without a live range def");
19917 lr = rstate->lrd[ins->id].lr;
19918 if (lr->color == REG_UNSET) {
19919 internal_error(state, ins,
19920 "triple without a color");
19922 /* Find the registers used by the edges */
19923 memset(used, 0, sizeof(used));
19924 for(edge = lr->edges; edge; edge = edge->next) {
19925 if (edge->node->color == REG_UNSET) {
19926 internal_error(state, 0,
19927 "live range without a color");
19929 reg_fill_used(state, used, edge->node->color);
19931 if (used[lr->color]) {
19932 internal_error(state, ins,
19933 "triple with already used color");
19937 } while(ins != first);
19940 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19942 struct live_range_def *lrd;
19943 struct live_range *lr;
19944 struct triple *first, *ins;
19945 first = state->first;
19948 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19949 internal_error(state, ins,
19950 "triple without a live range");
19952 lrd = &rstate->lrd[ins->id];
19954 ins->id = lrd->orig_id;
19955 SET_REG(ins->id, lr->color);
19957 } while (ins != first);
19960 static struct live_range *merge_sort_lr(
19961 struct live_range *first, struct live_range *last)
19963 struct live_range *mid, *join, **join_tail, *pick;
19965 size = (last - first) + 1;
19967 mid = first + size/2;
19968 first = merge_sort_lr(first, mid -1);
19969 mid = merge_sort_lr(mid, last);
19973 /* merge the two lists */
19974 while(first && mid) {
19975 if ((first->degree < mid->degree) ||
19976 ((first->degree == mid->degree) &&
19977 (first->length < mid->length))) {
19979 first = first->group_next;
19981 first->group_prev = 0;
19986 mid = mid->group_next;
19988 mid->group_prev = 0;
19991 pick->group_next = 0;
19992 pick->group_prev = join_tail;
19994 join_tail = &pick->group_next;
19996 /* Splice the remaining list */
19997 pick = (first)? first : mid;
20000 pick->group_prev = join_tail;
20004 if (!first->defs) {
20012 static void ids_from_rstate(struct compile_state *state,
20013 struct reg_state *rstate)
20015 struct triple *ins, *first;
20016 if (!rstate->defs) {
20019 /* Display the graph if desired */
20020 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20021 FILE *fp = state->dbgout;
20022 print_interference_blocks(state, rstate, fp, 0);
20023 print_control_flow(state, fp, &state->bb);
20026 first = state->first;
20030 struct live_range_def *lrd;
20031 lrd = &rstate->lrd[ins->id];
20032 ins->id = lrd->orig_id;
20035 } while(ins != first);
20038 static void cleanup_live_edges(struct reg_state *rstate)
20041 /* Free the edges on each node */
20042 for(i = 1; i <= rstate->ranges; i++) {
20043 remove_live_edges(rstate, &rstate->lr[i]);
20047 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
20049 cleanup_live_edges(rstate);
20050 xfree(rstate->lrd);
20053 /* Free the variable lifetime information */
20054 if (rstate->blocks) {
20055 free_variable_lifetimes(state, &state->bb, rstate->blocks);
20058 rstate->ranges = 0;
20061 rstate->blocks = 0;
20064 static void verify_consistency(struct compile_state *state);
20065 static void allocate_registers(struct compile_state *state)
20067 struct reg_state rstate;
20070 /* Clear out the reg_state */
20071 memset(&rstate, 0, sizeof(rstate));
20072 rstate.max_passes = state->compiler->max_allocation_passes;
20075 struct live_range **point, **next;
20079 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
20080 FILE *fp = state->errout;
20081 fprintf(fp, "pass: %d\n", rstate.passes);
20086 ids_from_rstate(state, &rstate);
20088 /* Cleanup the temporary data structures */
20089 cleanup_rstate(state, &rstate);
20091 /* Compute the variable lifetimes */
20092 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20094 /* Fix invalid mandatory live range coalesce conflicts */
20095 correct_coalesce_conflicts(state, rstate.blocks);
20097 /* Fix two simultaneous uses of the same register.
20098 * In a few pathlogical cases a partial untangle moves
20099 * the tangle to a part of the graph we won't revisit.
20100 * So we keep looping until we have no more tangle fixes
20104 tangles = correct_tangles(state, rstate.blocks);
20108 print_blocks(state, "resolve_tangles", state->dbgout);
20109 verify_consistency(state);
20111 /* Allocate and initialize the live ranges */
20112 initialize_live_ranges(state, &rstate);
20114 /* Note currently doing coalescing in a loop appears to
20115 * buys me nothing. The code is left this way in case
20116 * there is some value in it. Or if a future bugfix
20117 * yields some benefit.
20120 if (state->compiler->debug & DEBUG_COALESCING) {
20121 fprintf(state->errout, "coalescing\n");
20124 /* Remove any previous live edge calculations */
20125 cleanup_live_edges(&rstate);
20127 /* Compute the interference graph */
20128 walk_variable_lifetimes(
20129 state, &state->bb, rstate.blocks,
20130 graph_ins, &rstate);
20132 /* Display the interference graph if desired */
20133 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20134 print_interference_blocks(state, &rstate, state->dbgout, 1);
20135 fprintf(state->dbgout, "\nlive variables by instruction\n");
20136 walk_variable_lifetimes(
20137 state, &state->bb, rstate.blocks,
20138 print_interference_ins, &rstate);
20141 coalesced = coalesce_live_ranges(state, &rstate);
20143 if (state->compiler->debug & DEBUG_COALESCING) {
20144 fprintf(state->errout, "coalesced: %d\n", coalesced);
20146 } while(coalesced);
20148 #if DEBUG_CONSISTENCY > 1
20150 fprintf(state->errout, "verify_graph_ins...\n");
20152 /* Verify the interference graph */
20153 walk_variable_lifetimes(
20154 state, &state->bb, rstate.blocks,
20155 verify_graph_ins, &rstate);
20157 fprintf(state->errout, "verify_graph_ins done\n");
20161 /* Build the groups low and high. But with the nodes
20162 * first sorted by degree order.
20164 rstate.low_tail = &rstate.low;
20165 rstate.high_tail = &rstate.high;
20166 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20168 rstate.high->group_prev = &rstate.high;
20170 for(point = &rstate.high; *point; point = &(*point)->group_next)
20172 rstate.high_tail = point;
20173 /* Walk through the high list and move everything that needs
20176 for(point = &rstate.high; *point; point = next) {
20177 struct live_range *range;
20178 next = &(*point)->group_next;
20181 /* If it has a low degree or it already has a color
20182 * place the node in low.
20184 if ((range->degree < regc_max_size(state, range->classes)) ||
20185 (range->color != REG_UNSET)) {
20186 cgdebug_printf(state, "Lo: %5d degree %5d%s\n",
20187 range - rstate.lr, range->degree,
20188 (range->color != REG_UNSET) ? " (colored)": "");
20189 *range->group_prev = range->group_next;
20190 if (range->group_next) {
20191 range->group_next->group_prev = range->group_prev;
20193 if (&range->group_next == rstate.high_tail) {
20194 rstate.high_tail = range->group_prev;
20196 range->group_prev = rstate.low_tail;
20197 range->group_next = 0;
20198 *rstate.low_tail = range;
20199 rstate.low_tail = &range->group_next;
20203 cgdebug_printf(state, "hi: %5d degree %5d%s\n",
20204 range - rstate.lr, range->degree,
20205 (range->color != REG_UNSET) ? " (colored)": "");
20208 /* Color the live_ranges */
20209 colored = color_graph(state, &rstate);
20211 } while (!colored);
20213 /* Verify the graph was properly colored */
20214 verify_colors(state, &rstate);
20216 /* Move the colors from the graph to the triples */
20217 color_triples(state, &rstate);
20219 /* Cleanup the temporary data structures */
20220 cleanup_rstate(state, &rstate);
20222 /* Display the new graph */
20223 print_blocks(state, __func__, state->dbgout);
20226 /* Sparce Conditional Constant Propogation
20227 * =========================================
20231 struct lattice_node {
20233 struct triple *def;
20234 struct ssa_edge *out;
20235 struct flow_block *fblock;
20236 struct triple *val;
20237 /* lattice high val == def
20238 * lattice const is_const(val)
20239 * lattice low other
20243 struct lattice_node *src;
20244 struct lattice_node *dst;
20245 struct ssa_edge *work_next;
20246 struct ssa_edge *work_prev;
20247 struct ssa_edge *out_next;
20250 struct flow_block *src;
20251 struct flow_block *dst;
20252 struct flow_edge *work_next;
20253 struct flow_edge *work_prev;
20254 struct flow_edge *in_next;
20255 struct flow_edge *out_next;
20258 #define MAX_FLOW_BLOCK_EDGES 3
20259 struct flow_block {
20260 struct block *block;
20261 struct flow_edge *in;
20262 struct flow_edge *out;
20263 struct flow_edge *edges;
20268 struct lattice_node *lattice;
20269 struct ssa_edge *ssa_edges;
20270 struct flow_block *flow_blocks;
20271 struct flow_edge *flow_work_list;
20272 struct ssa_edge *ssa_work_list;
20276 static int is_scc_const(struct compile_state *state, struct triple *ins)
20278 return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20281 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20283 return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20286 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20288 return is_scc_const(state, lnode->val);
20291 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20293 return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20296 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
20297 struct flow_edge *fedge)
20299 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20300 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20302 fedge->src->block?fedge->src->block->last->id: 0,
20303 fedge->dst->block?fedge->dst->block->first->id: 0);
20305 if ((fedge == scc->flow_work_list) ||
20306 (fedge->work_next != fedge) ||
20307 (fedge->work_prev != fedge)) {
20309 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20310 fprintf(state->errout, "dupped fedge: %p\n",
20315 if (!scc->flow_work_list) {
20316 scc->flow_work_list = fedge;
20317 fedge->work_next = fedge->work_prev = fedge;
20320 struct flow_edge *ftail;
20321 ftail = scc->flow_work_list->work_prev;
20322 fedge->work_next = ftail->work_next;
20323 fedge->work_prev = ftail;
20324 fedge->work_next->work_prev = fedge;
20325 fedge->work_prev->work_next = fedge;
20329 static struct flow_edge *scc_next_fedge(
20330 struct compile_state *state, struct scc_state *scc)
20332 struct flow_edge *fedge;
20333 fedge = scc->flow_work_list;
20335 fedge->work_next->work_prev = fedge->work_prev;
20336 fedge->work_prev->work_next = fedge->work_next;
20337 if (fedge->work_next != fedge) {
20338 scc->flow_work_list = fedge->work_next;
20340 scc->flow_work_list = 0;
20342 fedge->work_next = fedge->work_prev = fedge;
20347 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20348 struct ssa_edge *sedge)
20350 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20351 fprintf(state->errout, "adding sedge: %5ld (%4d -> %5d)\n",
20352 (long)(sedge - scc->ssa_edges),
20353 sedge->src->def->id,
20354 sedge->dst->def->id);
20356 if ((sedge == scc->ssa_work_list) ||
20357 (sedge->work_next != sedge) ||
20358 (sedge->work_prev != sedge)) {
20360 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20361 fprintf(state->errout, "dupped sedge: %5ld\n",
20362 (long)(sedge - scc->ssa_edges));
20366 if (!scc->ssa_work_list) {
20367 scc->ssa_work_list = sedge;
20368 sedge->work_next = sedge->work_prev = sedge;
20371 struct ssa_edge *stail;
20372 stail = scc->ssa_work_list->work_prev;
20373 sedge->work_next = stail->work_next;
20374 sedge->work_prev = stail;
20375 sedge->work_next->work_prev = sedge;
20376 sedge->work_prev->work_next = sedge;
20380 static struct ssa_edge *scc_next_sedge(
20381 struct compile_state *state, struct scc_state *scc)
20383 struct ssa_edge *sedge;
20384 sedge = scc->ssa_work_list;
20386 sedge->work_next->work_prev = sedge->work_prev;
20387 sedge->work_prev->work_next = sedge->work_next;
20388 if (sedge->work_next != sedge) {
20389 scc->ssa_work_list = sedge->work_next;
20391 scc->ssa_work_list = 0;
20393 sedge->work_next = sedge->work_prev = sedge;
20398 static void initialize_scc_state(
20399 struct compile_state *state, struct scc_state *scc)
20401 int ins_count, ssa_edge_count;
20402 int ins_index, ssa_edge_index, fblock_index;
20403 struct triple *first, *ins;
20404 struct block *block;
20405 struct flow_block *fblock;
20407 memset(scc, 0, sizeof(*scc));
20409 /* Inialize pass zero find out how much memory we need */
20410 first = state->first;
20412 ins_count = ssa_edge_count = 0;
20414 struct triple_set *edge;
20416 for(edge = ins->use; edge; edge = edge->next) {
20420 } while(ins != first);
20421 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20422 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20423 ins_count, ssa_edge_count, state->bb.last_vertex);
20425 scc->ins_count = ins_count;
20427 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20429 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20431 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1),
20434 /* Initialize pass one collect up the nodes */
20437 ins_index = ssa_edge_index = fblock_index = 0;
20440 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20441 block = ins->u.block;
20443 internal_error(state, ins, "label without block");
20446 block->vertex = fblock_index;
20447 fblock = &scc->flow_blocks[fblock_index];
20448 fblock->block = block;
20449 fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20453 struct lattice_node *lnode;
20455 lnode = &scc->lattice[ins_index];
20458 lnode->fblock = fblock;
20459 lnode->val = ins; /* LATTICE HIGH */
20460 if (lnode->val->op == OP_UNKNOWNVAL) {
20461 lnode->val = 0; /* LATTICE LOW by definition */
20463 lnode->old_id = ins->id;
20464 ins->id = ins_index;
20467 } while(ins != first);
20468 /* Initialize pass two collect up the edges */
20474 struct triple_set *edge;
20475 struct ssa_edge **stail;
20476 struct lattice_node *lnode;
20477 lnode = &scc->lattice[ins->id];
20479 stail = &lnode->out;
20480 for(edge = ins->use; edge; edge = edge->next) {
20481 struct ssa_edge *sedge;
20482 ssa_edge_index += 1;
20483 sedge = &scc->ssa_edges[ssa_edge_index];
20485 stail = &sedge->out_next;
20486 sedge->src = lnode;
20487 sedge->dst = &scc->lattice[edge->member->id];
20488 sedge->work_next = sedge->work_prev = sedge;
20489 sedge->out_next = 0;
20492 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20493 struct flow_edge *fedge, **ftail;
20494 struct block_set *bedge;
20495 block = ins->u.block;
20496 fblock = &scc->flow_blocks[block->vertex];
20499 ftail = &fblock->out;
20501 fedge = fblock->edges;
20502 bedge = block->edges;
20503 for(; bedge; bedge = bedge->next, fedge++) {
20504 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20505 if (fedge->dst->block != bedge->member) {
20506 internal_error(state, 0, "block mismatch");
20509 ftail = &fedge->out_next;
20510 fedge->out_next = 0;
20512 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20513 fedge->src = fblock;
20514 fedge->work_next = fedge->work_prev = fedge;
20515 fedge->executable = 0;
20519 } while (ins != first);
20524 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20525 struct flow_edge **ftail;
20526 struct block_set *bedge;
20527 block = ins->u.block;
20528 fblock = &scc->flow_blocks[block->vertex];
20529 ftail = &fblock->in;
20530 for(bedge = block->use; bedge; bedge = bedge->next) {
20531 struct block *src_block;
20532 struct flow_block *sfblock;
20533 struct flow_edge *sfedge;
20534 src_block = bedge->member;
20535 sfblock = &scc->flow_blocks[src_block->vertex];
20536 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20537 if (sfedge->dst == fblock) {
20542 internal_error(state, 0, "edge mismatch");
20545 ftail = &sfedge->in_next;
20546 sfedge->in_next = 0;
20550 } while(ins != first);
20551 /* Setup a dummy block 0 as a node above the start node */
20553 struct flow_block *fblock, *dst;
20554 struct flow_edge *fedge;
20555 fblock = &scc->flow_blocks[0];
20557 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20559 fblock->out = fblock->edges;
20560 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20561 fedge = fblock->edges;
20562 fedge->src = fblock;
20564 fedge->work_next = fedge;
20565 fedge->work_prev = fedge;
20566 fedge->in_next = fedge->dst->in;
20567 fedge->out_next = 0;
20568 fedge->executable = 0;
20569 fedge->dst->in = fedge;
20571 /* Initialize the work lists */
20572 scc->flow_work_list = 0;
20573 scc->ssa_work_list = 0;
20574 scc_add_fedge(state, scc, fedge);
20576 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20577 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20578 ins_index, ssa_edge_index, fblock_index);
20583 static void free_scc_state(
20584 struct compile_state *state, struct scc_state *scc)
20587 for(i = 0; i < state->bb.last_vertex + 1; i++) {
20588 struct flow_block *fblock;
20589 fblock = &scc->flow_blocks[i];
20590 if (fblock->edges) {
20591 xfree(fblock->edges);
20595 xfree(scc->flow_blocks);
20596 xfree(scc->ssa_edges);
20597 xfree(scc->lattice);
20601 static struct lattice_node *triple_to_lattice(
20602 struct compile_state *state, struct scc_state *scc, struct triple *ins)
20604 if (ins->id <= 0) {
20605 internal_error(state, ins, "bad id");
20607 return &scc->lattice[ins->id];
20610 static struct triple *preserve_lval(
20611 struct compile_state *state, struct lattice_node *lnode)
20613 struct triple *old;
20614 /* Preserve the original value */
20616 old = dup_triple(state, lnode->val);
20617 if (lnode->val != lnode->def) {
20627 static int lval_changed(struct compile_state *state,
20628 struct triple *old, struct lattice_node *lnode)
20631 /* See if the lattice value has changed */
20633 if (!old && !lnode->val) {
20637 lnode->val && old &&
20638 (memcmp(lnode->val->param, old->param,
20639 TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20640 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20650 static void scc_debug_lnode(
20651 struct compile_state *state, struct scc_state *scc,
20652 struct lattice_node *lnode, int changed)
20654 if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20655 display_triple_changes(state->errout, lnode->val, lnode->def);
20657 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20658 FILE *fp = state->errout;
20659 struct triple *val, **expr;
20660 val = lnode->val? lnode->val : lnode->def;
20661 fprintf(fp, "%p %s %3d %10s (",
20663 ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20665 tops(lnode->def->op));
20666 expr = triple_rhs(state, lnode->def, 0);
20667 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20669 fprintf(fp, " %d", (*expr)->id);
20672 if (val->op == OP_INTCONST) {
20673 fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20675 fprintf(fp, " ) -> %s %s\n",
20676 (is_lattice_hi(state, lnode)? "hi":
20677 is_lattice_const(state, lnode)? "const" : "lo"),
20678 changed? "changed" : ""
20683 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20684 struct lattice_node *lnode)
20687 struct triple *old, *scratch;
20688 struct triple **dexpr, **vexpr;
20691 /* Store the original value */
20692 old = preserve_lval(state, lnode);
20694 /* Reinitialize the value */
20695 lnode->val = scratch = dup_triple(state, lnode->def);
20696 scratch->id = lnode->old_id;
20697 scratch->next = scratch;
20698 scratch->prev = scratch;
20701 count = TRIPLE_SIZE(scratch);
20702 for(i = 0; i < count; i++) {
20703 dexpr = &lnode->def->param[i];
20704 vexpr = &scratch->param[i];
20706 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20707 (i >= TRIPLE_TARG_OFF(scratch))) &&
20709 struct lattice_node *tmp;
20710 tmp = triple_to_lattice(state, scc, *dexpr);
20711 *vexpr = (tmp->val)? tmp->val : tmp->def;
20714 if (triple_is_branch(state, scratch)) {
20715 scratch->next = lnode->def->next;
20717 /* Recompute the value */
20718 #if DEBUG_ROMCC_WARNINGS
20719 #warning "FIXME see if simplify does anything bad"
20721 /* So far it looks like only the strength reduction
20722 * optimization are things I need to worry about.
20724 simplify(state, scratch);
20725 /* Cleanup my value */
20726 if (scratch->use) {
20727 internal_error(state, lnode->def, "scratch used?");
20729 if ((scratch->prev != scratch) ||
20730 ((scratch->next != scratch) &&
20731 (!triple_is_branch(state, lnode->def) ||
20732 (scratch->next != lnode->def->next)))) {
20733 internal_error(state, lnode->def, "scratch in list?");
20735 /* undo any uses... */
20736 count = TRIPLE_SIZE(scratch);
20737 for(i = 0; i < count; i++) {
20738 vexpr = &scratch->param[i];
20740 unuse_triple(*vexpr, scratch);
20743 if (lnode->val->op == OP_UNKNOWNVAL) {
20744 lnode->val = 0; /* Lattice low by definition */
20746 /* Find the case when I am lattice high */
20748 (lnode->val->op == lnode->def->op) &&
20749 (memcmp(lnode->val->param, lnode->def->param,
20750 count * sizeof(lnode->val->param[0])) == 0) &&
20751 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20752 lnode->val = lnode->def;
20754 /* Only allow lattice high when all of my inputs
20755 * are also lattice high. Occassionally I can
20756 * have constants with a lattice low input, so
20757 * I do not need to check that case.
20759 if (is_lattice_hi(state, lnode)) {
20760 struct lattice_node *tmp;
20762 rhs = lnode->val->rhs;
20763 for(i = 0; i < rhs; i++) {
20764 tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20765 if (!is_lattice_hi(state, tmp)) {
20771 /* Find the cases that are always lattice lo */
20773 triple_is_def(state, lnode->val) &&
20774 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20777 /* See if the lattice value has changed */
20778 changed = lval_changed(state, old, lnode);
20779 /* See if this value should not change */
20780 if ((lnode->val != lnode->def) &&
20781 (( !triple_is_def(state, lnode->def) &&
20782 !triple_is_cbranch(state, lnode->def)) ||
20783 (lnode->def->op == OP_PIECE))) {
20784 #if DEBUG_ROMCC_WARNINGS
20785 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20788 internal_warning(state, lnode->def, "non def changes value?");
20793 /* See if we need to free the scratch value */
20794 if (lnode->val != scratch) {
20802 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20803 struct lattice_node *lnode)
20805 struct lattice_node *cond;
20806 struct flow_edge *left, *right;
20809 /* Update the branch value */
20810 changed = compute_lnode_val(state, scc, lnode);
20811 scc_debug_lnode(state, scc, lnode, changed);
20813 /* This only applies to conditional branches */
20814 if (!triple_is_cbranch(state, lnode->def)) {
20815 internal_error(state, lnode->def, "not a conditional branch");
20818 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20819 struct flow_edge *fedge;
20820 FILE *fp = state->errout;
20821 fprintf(fp, "%s: %d (",
20822 tops(lnode->def->op),
20825 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20826 fprintf(fp, " %d", fedge->dst->block->vertex);
20829 if (lnode->def->rhs > 0) {
20830 fprintf(fp, " <- %d",
20831 RHS(lnode->def, 0)->id);
20835 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20836 for(left = cond->fblock->out; left; left = left->out_next) {
20837 if (left->dst->block->first == lnode->def->next) {
20842 internal_error(state, lnode->def, "Cannot find left branch edge");
20844 for(right = cond->fblock->out; right; right = right->out_next) {
20845 if (right->dst->block->first == TARG(lnode->def, 0)) {
20850 internal_error(state, lnode->def, "Cannot find right branch edge");
20852 /* I should only come here if the controlling expressions value
20853 * has changed, which means it must be either a constant or lo.
20855 if (is_lattice_hi(state, cond)) {
20856 internal_error(state, cond->def, "condition high?");
20859 if (is_lattice_lo(state, cond)) {
20860 scc_add_fedge(state, scc, left);
20861 scc_add_fedge(state, scc, right);
20863 else if (cond->val->u.cval) {
20864 scc_add_fedge(state, scc, right);
20866 scc_add_fedge(state, scc, left);
20872 static void scc_add_sedge_dst(struct compile_state *state,
20873 struct scc_state *scc, struct ssa_edge *sedge)
20875 if (triple_is_cbranch(state, sedge->dst->def)) {
20876 scc_visit_cbranch(state, scc, sedge->dst);
20878 else if (triple_is_def(state, sedge->dst->def)) {
20879 scc_add_sedge(state, scc, sedge);
20883 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
20884 struct lattice_node *lnode)
20886 struct lattice_node *tmp;
20887 struct triple **slot, *old;
20888 struct flow_edge *fedge;
20891 if (lnode->def->op != OP_PHI) {
20892 internal_error(state, lnode->def, "not phi");
20894 /* Store the original value */
20895 old = preserve_lval(state, lnode);
20897 /* default to lattice high */
20898 lnode->val = lnode->def;
20899 slot = &RHS(lnode->def, 0);
20901 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20902 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20903 fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n",
20905 fedge->dst->block->vertex,
20909 if (!fedge->executable) {
20912 if (!slot[index]) {
20913 internal_error(state, lnode->def, "no phi value");
20915 tmp = triple_to_lattice(state, scc, slot[index]);
20916 /* meet(X, lattice low) = lattice low */
20917 if (is_lattice_lo(state, tmp)) {
20920 /* meet(X, lattice high) = X */
20921 else if (is_lattice_hi(state, tmp)) {
20922 lnode->val = lnode->val;
20924 /* meet(lattice high, X) = X */
20925 else if (is_lattice_hi(state, lnode)) {
20926 lnode->val = dup_triple(state, tmp->val);
20927 /* Only change the type if necessary */
20928 if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20929 lnode->val->type = lnode->def->type;
20932 /* meet(const, const) = const or lattice low */
20933 else if (!constants_equal(state, lnode->val, tmp->val)) {
20937 /* meet(lattice low, X) = lattice low */
20938 if (is_lattice_lo(state, lnode)) {
20943 changed = lval_changed(state, old, lnode);
20944 scc_debug_lnode(state, scc, lnode, changed);
20946 /* If the lattice value has changed update the work lists. */
20948 struct ssa_edge *sedge;
20949 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20950 scc_add_sedge_dst(state, scc, sedge);
20956 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20957 struct lattice_node *lnode)
20961 if (!triple_is_def(state, lnode->def)) {
20962 internal_warning(state, lnode->def, "not visiting an expression?");
20964 changed = compute_lnode_val(state, scc, lnode);
20965 scc_debug_lnode(state, scc, lnode, changed);
20968 struct ssa_edge *sedge;
20969 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20970 scc_add_sedge_dst(state, scc, sedge);
20975 static void scc_writeback_values(
20976 struct compile_state *state, struct scc_state *scc)
20978 struct triple *first, *ins;
20979 first = state->first;
20982 struct lattice_node *lnode;
20983 lnode = triple_to_lattice(state, scc, ins);
20984 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20985 if (is_lattice_hi(state, lnode) &&
20986 (lnode->val->op != OP_NOOP))
20988 struct flow_edge *fedge;
20991 for(fedge = lnode->fblock->in;
20992 !executable && fedge; fedge = fedge->in_next) {
20993 executable |= fedge->executable;
20996 internal_warning(state, lnode->def,
20997 "lattice node %d %s->%s still high?",
20999 tops(lnode->def->op),
21000 tops(lnode->val->op));
21006 ins->id = lnode->old_id;
21007 if (lnode->val && (lnode->val != ins)) {
21008 /* See if it something I know how to write back */
21009 switch(lnode->val->op) {
21011 mkconst(state, ins, lnode->val->u.cval);
21014 mkaddr_const(state, ins,
21015 MISC(lnode->val, 0), lnode->val->u.cval);
21018 /* By default don't copy the changes,
21019 * recompute them in place instead.
21021 simplify(state, ins);
21024 if (is_const(lnode->val) &&
21025 !constants_equal(state, lnode->val, ins)) {
21026 internal_error(state, 0, "constants not equal");
21028 /* Free the lattice nodes */
21033 } while(ins != first);
21036 static void scc_transform(struct compile_state *state)
21038 struct scc_state scc;
21039 if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
21043 initialize_scc_state(state, &scc);
21045 while(scc.flow_work_list || scc.ssa_work_list) {
21046 struct flow_edge *fedge;
21047 struct ssa_edge *sedge;
21048 struct flow_edge *fptr;
21049 while((fedge = scc_next_fedge(state, &scc))) {
21050 struct block *block;
21051 struct triple *ptr;
21052 struct flow_block *fblock;
21055 if (fedge->executable) {
21059 internal_error(state, 0, "fedge without dst");
21062 internal_error(state, 0, "fedge without src");
21064 fedge->executable = 1;
21065 fblock = fedge->dst;
21066 block = fblock->block;
21068 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21069 if (fptr->executable) {
21074 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21075 fprintf(state->errout, "vertex: %d reps: %d\n",
21076 block->vertex, reps);
21080 for(ptr = block->first; !done; ptr = ptr->next) {
21081 struct lattice_node *lnode;
21082 done = (ptr == block->last);
21083 lnode = &scc.lattice[ptr->id];
21084 if (ptr->op == OP_PHI) {
21085 scc_visit_phi(state, &scc, lnode);
21087 else if ((reps == 1) && triple_is_def(state, ptr))
21089 scc_visit_expr(state, &scc, lnode);
21092 /* Add unconditional branch edges */
21093 if (!triple_is_cbranch(state, fblock->block->last)) {
21094 struct flow_edge *out;
21095 for(out = fblock->out; out; out = out->out_next) {
21096 scc_add_fedge(state, &scc, out);
21100 while((sedge = scc_next_sedge(state, &scc))) {
21101 struct lattice_node *lnode;
21102 struct flow_block *fblock;
21103 lnode = sedge->dst;
21104 fblock = lnode->fblock;
21106 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21107 fprintf(state->errout, "sedge: %5ld (%5d -> %5d)\n",
21108 (unsigned long)sedge - (unsigned long)scc.ssa_edges,
21109 sedge->src->def->id,
21110 sedge->dst->def->id);
21113 if (lnode->def->op == OP_PHI) {
21114 scc_visit_phi(state, &scc, lnode);
21117 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21118 if (fptr->executable) {
21123 scc_visit_expr(state, &scc, lnode);
21129 scc_writeback_values(state, &scc);
21130 free_scc_state(state, &scc);
21131 rebuild_ssa_form(state);
21133 print_blocks(state, __func__, state->dbgout);
21137 static void transform_to_arch_instructions(struct compile_state *state)
21139 struct triple *ins, *first;
21140 first = state->first;
21143 ins = transform_to_arch_instruction(state, ins);
21144 } while(ins != first);
21146 print_blocks(state, __func__, state->dbgout);
21149 #if DEBUG_CONSISTENCY
21150 static void verify_uses(struct compile_state *state)
21152 struct triple *first, *ins;
21153 struct triple_set *set;
21154 first = state->first;
21157 struct triple **expr;
21158 expr = triple_rhs(state, ins, 0);
21159 for(; expr; expr = triple_rhs(state, ins, expr)) {
21160 struct triple *rhs;
21162 for(set = rhs?rhs->use:0; set; set = set->next) {
21163 if (set->member == ins) {
21168 internal_error(state, ins, "rhs not used");
21171 expr = triple_lhs(state, ins, 0);
21172 for(; expr; expr = triple_lhs(state, ins, expr)) {
21173 struct triple *lhs;
21175 for(set = lhs?lhs->use:0; set; set = set->next) {
21176 if (set->member == ins) {
21181 internal_error(state, ins, "lhs not used");
21184 expr = triple_misc(state, ins, 0);
21185 if (ins->op != OP_PHI) {
21186 for(; expr; expr = triple_targ(state, ins, expr)) {
21187 struct triple *misc;
21189 for(set = misc?misc->use:0; set; set = set->next) {
21190 if (set->member == ins) {
21195 internal_error(state, ins, "misc not used");
21199 if (!triple_is_ret(state, ins)) {
21200 expr = triple_targ(state, ins, 0);
21201 for(; expr; expr = triple_targ(state, ins, expr)) {
21202 struct triple *targ;
21204 for(set = targ?targ->use:0; set; set = set->next) {
21205 if (set->member == ins) {
21210 internal_error(state, ins, "targ not used");
21215 } while(ins != first);
21218 static void verify_blocks_present(struct compile_state *state)
21220 struct triple *first, *ins;
21221 if (!state->bb.first_block) {
21224 first = state->first;
21227 valid_ins(state, ins);
21228 if (triple_stores_block(state, ins)) {
21229 if (!ins->u.block) {
21230 internal_error(state, ins,
21231 "%p not in a block?", ins);
21235 } while(ins != first);
21240 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21242 struct block_set *bedge;
21243 struct block *targ;
21244 targ = block_of_triple(state, edge);
21245 for(bedge = block->edges; bedge; bedge = bedge->next) {
21246 if (bedge->member == targ) {
21253 static void verify_blocks(struct compile_state *state)
21255 struct triple *ins;
21256 struct block *block;
21258 block = state->bb.first_block;
21265 struct block_set *user, *edge;
21267 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21268 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21269 internal_error(state, ins, "inconsitent block specified");
21271 valid_ins(state, ins);
21274 for(user = block->use; user; user = user->next) {
21276 if (!user->member->first) {
21277 internal_error(state, block->first, "user is empty");
21279 if ((block == state->bb.last_block) &&
21280 (user->member == state->bb.first_block)) {
21283 for(edge = user->member->edges; edge; edge = edge->next) {
21284 if (edge->member == block) {
21289 internal_error(state, user->member->first,
21290 "user does not use block");
21293 if (triple_is_branch(state, block->last)) {
21294 struct triple **expr;
21295 expr = triple_edge_targ(state, block->last, 0);
21296 for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21297 if (*expr && !edge_present(state, block, *expr)) {
21298 internal_error(state, block->last, "no edge to targ");
21302 if (!triple_is_ubranch(state, block->last) &&
21303 (block != state->bb.last_block) &&
21304 !edge_present(state, block, block->last->next)) {
21305 internal_error(state, block->last, "no edge to block->last->next");
21307 for(edge = block->edges; edge; edge = edge->next) {
21308 for(user = edge->member->use; user; user = user->next) {
21309 if (user->member == block) {
21313 if (!user || user->member != block) {
21314 internal_error(state, block->first,
21315 "block does not use edge");
21317 if (!edge->member->first) {
21318 internal_error(state, block->first, "edge block is empty");
21321 if (block->users != users) {
21322 internal_error(state, block->first,
21323 "computed users %d != stored users %d",
21324 users, block->users);
21326 if (!triple_stores_block(state, block->last->next)) {
21327 internal_error(state, block->last->next,
21328 "cannot find next block");
21330 block = block->last->next->u.block;
21332 internal_error(state, block->last->next,
21335 } while(block != state->bb.first_block);
21336 if (blocks != state->bb.last_vertex) {
21337 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21338 blocks, state->bb.last_vertex);
21342 static void verify_domination(struct compile_state *state)
21344 struct triple *first, *ins;
21345 struct triple_set *set;
21346 if (!state->bb.first_block) {
21350 first = state->first;
21353 for(set = ins->use; set; set = set->next) {
21354 struct triple **slot;
21355 struct triple *use_point;
21358 zrhs = set->member->rhs;
21359 slot = &RHS(set->member, 0);
21360 /* See if the use is on the right hand side */
21361 for(i = 0; i < zrhs; i++) {
21362 if (slot[i] == ins) {
21367 use_point = set->member;
21368 if (set->member->op == OP_PHI) {
21369 struct block_set *bset;
21371 bset = set->member->u.block->use;
21372 for(edge = 0; bset && (edge < i); edge++) {
21376 internal_error(state, set->member,
21377 "no edge for phi rhs %d", i);
21379 use_point = bset->member->last;
21383 !tdominates(state, ins, use_point)) {
21384 if (is_const(ins)) {
21385 internal_warning(state, ins,
21386 "non dominated rhs use point %p?", use_point);
21389 internal_error(state, ins,
21390 "non dominated rhs use point %p?", use_point);
21395 } while(ins != first);
21398 static void verify_rhs(struct compile_state *state)
21400 struct triple *first, *ins;
21401 first = state->first;
21404 struct triple **slot;
21407 slot = &RHS(ins, 0);
21408 for(i = 0; i < zrhs; i++) {
21409 if (slot[i] == 0) {
21410 internal_error(state, ins,
21411 "missing rhs %d on %s",
21414 if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21415 internal_error(state, ins,
21416 "ins == rhs[%d] on %s",
21421 } while(ins != first);
21424 static void verify_piece(struct compile_state *state)
21426 struct triple *first, *ins;
21427 first = state->first;
21430 struct triple *ptr;
21433 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21434 if (ptr != LHS(ins, i)) {
21435 internal_error(state, ins, "malformed lhs on %s",
21438 if (ptr->op != OP_PIECE) {
21439 internal_error(state, ins, "bad lhs op %s at %d on %s",
21440 tops(ptr->op), i, tops(ins->op));
21442 if (ptr->u.cval != i) {
21443 internal_error(state, ins, "bad u.cval of %d %d expected",
21448 } while(ins != first);
21451 static void verify_ins_colors(struct compile_state *state)
21453 struct triple *first, *ins;
21455 first = state->first;
21459 } while(ins != first);
21462 static void verify_unknown(struct compile_state *state)
21464 struct triple *first, *ins;
21465 if ( (unknown_triple.next != &unknown_triple) ||
21466 (unknown_triple.prev != &unknown_triple) ||
21468 (unknown_triple.use != 0) ||
21470 (unknown_triple.op != OP_UNKNOWNVAL) ||
21471 (unknown_triple.lhs != 0) ||
21472 (unknown_triple.rhs != 0) ||
21473 (unknown_triple.misc != 0) ||
21474 (unknown_triple.targ != 0) ||
21475 (unknown_triple.template_id != 0) ||
21476 (unknown_triple.id != -1) ||
21477 (unknown_triple.type != &unknown_type) ||
21478 (unknown_triple.occurance != &dummy_occurance) ||
21479 (unknown_triple.param[0] != 0) ||
21480 (unknown_triple.param[1] != 0)) {
21481 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21483 if ( (dummy_occurance.count != 2) ||
21484 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21485 (strcmp(dummy_occurance.function, "") != 0) ||
21486 (dummy_occurance.col != 0) ||
21487 (dummy_occurance.parent != 0)) {
21488 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21490 if ( (unknown_type.type != TYPE_UNKNOWN)) {
21491 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21493 first = state->first;
21497 if (ins == &unknown_triple) {
21498 internal_error(state, ins, "unknown triple in list");
21500 params = TRIPLE_SIZE(ins);
21501 for(i = 0; i < params; i++) {
21502 if (ins->param[i] == &unknown_triple) {
21503 internal_error(state, ins, "unknown triple used!");
21507 } while(ins != first);
21510 static void verify_types(struct compile_state *state)
21512 struct triple *first, *ins;
21513 first = state->first;
21516 struct type *invalid;
21517 invalid = invalid_type(state, ins->type);
21519 FILE *fp = state->errout;
21520 fprintf(fp, "type: ");
21521 name_of(fp, ins->type);
21523 fprintf(fp, "invalid type: ");
21524 name_of(fp, invalid);
21526 internal_error(state, ins, "invalid ins type");
21528 } while(ins != first);
21531 static void verify_copy(struct compile_state *state)
21533 struct triple *first, *ins, *next;
21534 first = state->first;
21535 next = ins = first;
21539 if (ins->op != OP_COPY) {
21542 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21543 FILE *fp = state->errout;
21544 fprintf(fp, "src type: ");
21545 name_of(fp, RHS(ins, 0)->type);
21547 fprintf(fp, "dst type: ");
21548 name_of(fp, ins->type);
21550 internal_error(state, ins, "type mismatch in copy");
21552 } while(next != first);
21555 static void verify_consistency(struct compile_state *state)
21557 verify_unknown(state);
21558 verify_uses(state);
21559 verify_blocks_present(state);
21560 verify_blocks(state);
21561 verify_domination(state);
21563 verify_piece(state);
21564 verify_ins_colors(state);
21565 verify_types(state);
21566 verify_copy(state);
21567 if (state->compiler->debug & DEBUG_VERIFICATION) {
21568 fprintf(state->dbgout, "consistency verified\n");
21572 static void verify_consistency(struct compile_state *state) {}
21573 #endif /* DEBUG_CONSISTENCY */
21575 static void optimize(struct compile_state *state)
21577 /* Join all of the functions into one giant function */
21578 join_functions(state);
21580 /* Dump what the instruction graph intially looks like */
21581 print_triples(state);
21583 /* Replace structures with simpler data types */
21584 decompose_compound_types(state);
21585 print_triples(state);
21587 verify_consistency(state);
21588 /* Analyze the intermediate code */
21589 state->bb.first = state->first;
21590 analyze_basic_blocks(state, &state->bb);
21592 /* Transform the code to ssa form. */
21594 * The transformation to ssa form puts a phi function
21595 * on each of edge of a dominance frontier where that
21596 * phi function might be needed. At -O2 if we don't
21597 * eleminate the excess phi functions we can get an
21598 * exponential code size growth. So I kill the extra
21599 * phi functions early and I kill them often.
21601 transform_to_ssa_form(state);
21602 verify_consistency(state);
21604 /* Remove dead code */
21605 eliminate_inefectual_code(state);
21606 verify_consistency(state);
21608 /* Do strength reduction and simple constant optimizations */
21609 simplify_all(state);
21610 verify_consistency(state);
21611 /* Propogate constants throughout the code */
21612 scc_transform(state);
21613 verify_consistency(state);
21614 #if DEBUG_ROMCC_WARNINGS
21615 #warning "WISHLIST implement single use constants (least possible register pressure)"
21616 #warning "WISHLIST implement induction variable elimination"
21618 /* Select architecture instructions and an initial partial
21619 * coloring based on architecture constraints.
21621 transform_to_arch_instructions(state);
21622 verify_consistency(state);
21624 /* Remove dead code */
21625 eliminate_inefectual_code(state);
21626 verify_consistency(state);
21628 /* Color all of the variables to see if they will fit in registers */
21629 insert_copies_to_phi(state);
21630 verify_consistency(state);
21632 insert_mandatory_copies(state);
21633 verify_consistency(state);
21635 allocate_registers(state);
21636 verify_consistency(state);
21638 /* Remove the optimization information.
21639 * This is more to check for memory consistency than to free memory.
21641 free_basic_blocks(state, &state->bb);
21644 static void print_op_asm(struct compile_state *state,
21645 struct triple *ins, FILE *fp)
21647 struct asm_info *info;
21649 unsigned lhs, rhs, i;
21650 info = ins->u.ainfo;
21653 /* Don't count the clobbers in lhs */
21654 for(i = 0; i < lhs; i++) {
21655 if (LHS(ins, i)->type == &void_type) {
21660 fprintf(fp, "#ASM\n");
21662 for(ptr = info->str; *ptr; ptr++) {
21664 unsigned long param;
21665 struct triple *piece;
21675 param = strtoul(ptr, &next, 10);
21677 error(state, ins, "Invalid asm template");
21679 if (param >= (lhs + rhs)) {
21680 error(state, ins, "Invalid param %%%u in asm template",
21683 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21685 arch_reg_str(ID_REG(piece->id)));
21688 fprintf(fp, "\n#NOT ASM\n");
21692 /* Only use the low x86 byte registers. This allows me
21693 * allocate the entire register when a byte register is used.
21695 #define X86_4_8BIT_GPRS 1
21698 #define X86_MMX_REGS (1<<0)
21699 #define X86_XMM_REGS (1<<1)
21700 #define X86_NOOP_COPY (1<<2)
21702 /* The x86 register classes */
21703 #define REGC_FLAGS 0
21704 #define REGC_GPR8 1
21705 #define REGC_GPR16 2
21706 #define REGC_GPR32 3
21707 #define REGC_DIVIDEND64 4
21708 #define REGC_DIVIDEND32 5
21711 #define REGC_GPR32_8 8
21712 #define REGC_GPR16_8 9
21713 #define REGC_GPR8_LO 10
21714 #define REGC_IMM32 11
21715 #define REGC_IMM16 12
21716 #define REGC_IMM8 13
21717 #define LAST_REGC REGC_IMM8
21718 #if LAST_REGC >= MAX_REGC
21719 #error "MAX_REGC is to low"
21722 /* Register class masks */
21723 #define REGCM_FLAGS (1 << REGC_FLAGS)
21724 #define REGCM_GPR8 (1 << REGC_GPR8)
21725 #define REGCM_GPR16 (1 << REGC_GPR16)
21726 #define REGCM_GPR32 (1 << REGC_GPR32)
21727 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21728 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21729 #define REGCM_MMX (1 << REGC_MMX)
21730 #define REGCM_XMM (1 << REGC_XMM)
21731 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
21732 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
21733 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
21734 #define REGCM_IMM32 (1 << REGC_IMM32)
21735 #define REGCM_IMM16 (1 << REGC_IMM16)
21736 #define REGCM_IMM8 (1 << REGC_IMM8)
21737 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
21738 #define REGCM_IMMALL (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21740 /* The x86 registers */
21741 #define REG_EFLAGS 2
21742 #define REGC_FLAGS_FIRST REG_EFLAGS
21743 #define REGC_FLAGS_LAST REG_EFLAGS
21752 #define REGC_GPR8_LO_FIRST REG_AL
21753 #define REGC_GPR8_LO_LAST REG_DL
21754 #define REGC_GPR8_FIRST REG_AL
21755 #define REGC_GPR8_LAST REG_DH
21764 #define REGC_GPR16_FIRST REG_AX
21765 #define REGC_GPR16_LAST REG_SP
21774 #define REGC_GPR32_FIRST REG_EAX
21775 #define REGC_GPR32_LAST REG_ESP
21776 #define REG_EDXEAX 27
21777 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21778 #define REGC_DIVIDEND64_LAST REG_EDXEAX
21779 #define REG_DXAX 28
21780 #define REGC_DIVIDEND32_FIRST REG_DXAX
21781 #define REGC_DIVIDEND32_LAST REG_DXAX
21782 #define REG_MMX0 29
21783 #define REG_MMX1 30
21784 #define REG_MMX2 31
21785 #define REG_MMX3 32
21786 #define REG_MMX4 33
21787 #define REG_MMX5 34
21788 #define REG_MMX6 35
21789 #define REG_MMX7 36
21790 #define REGC_MMX_FIRST REG_MMX0
21791 #define REGC_MMX_LAST REG_MMX7
21792 #define REG_XMM0 37
21793 #define REG_XMM1 38
21794 #define REG_XMM2 39
21795 #define REG_XMM3 40
21796 #define REG_XMM4 41
21797 #define REG_XMM5 42
21798 #define REG_XMM6 43
21799 #define REG_XMM7 44
21800 #define REGC_XMM_FIRST REG_XMM0
21801 #define REGC_XMM_LAST REG_XMM7
21803 #if DEBUG_ROMCC_WARNINGS
21804 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21807 #define LAST_REG REG_XMM7
21809 #define REGC_GPR32_8_FIRST REG_EAX
21810 #define REGC_GPR32_8_LAST REG_EDX
21811 #define REGC_GPR16_8_FIRST REG_AX
21812 #define REGC_GPR16_8_LAST REG_DX
21814 #define REGC_IMM8_FIRST -1
21815 #define REGC_IMM8_LAST -1
21816 #define REGC_IMM16_FIRST -2
21817 #define REGC_IMM16_LAST -1
21818 #define REGC_IMM32_FIRST -4
21819 #define REGC_IMM32_LAST -1
21821 #if LAST_REG >= MAX_REGISTERS
21822 #error "MAX_REGISTERS to low"
21826 static unsigned regc_size[LAST_REGC +1] = {
21827 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
21828 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
21829 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
21830 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
21831 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21832 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21833 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
21834 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
21835 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
21836 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
21837 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
21843 static const struct {
21845 } regcm_bound[LAST_REGC + 1] = {
21846 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
21847 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
21848 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
21849 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
21850 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21851 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21852 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
21853 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
21854 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
21855 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
21856 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
21857 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
21858 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
21859 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
21862 #if ARCH_INPUT_REGS != 4
21863 #error ARCH_INPUT_REGS size mismatch
21865 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21866 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21867 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21868 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21869 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21872 #if ARCH_OUTPUT_REGS != 4
21873 #error ARCH_INPUT_REGS size mismatch
21875 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21876 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21877 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21878 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21879 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21882 static void init_arch_state(struct arch_state *arch)
21884 memset(arch, 0, sizeof(*arch));
21885 arch->features = 0;
21888 static const struct compiler_flag arch_flags[] = {
21889 { "mmx", X86_MMX_REGS },
21890 { "sse", X86_XMM_REGS },
21891 { "noop-copy", X86_NOOP_COPY },
21894 static const struct compiler_flag arch_cpus[] = {
21896 { "p2", X86_MMX_REGS },
21897 { "p3", X86_MMX_REGS | X86_XMM_REGS },
21898 { "p4", X86_MMX_REGS | X86_XMM_REGS },
21899 { "k7", X86_MMX_REGS },
21900 { "k8", X86_MMX_REGS | X86_XMM_REGS },
21901 { "c3", X86_MMX_REGS },
21902 { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21905 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21912 if (strncmp(flag, "no-", 3) == 0) {
21916 if (act && strncmp(flag, "cpu=", 4) == 0) {
21918 result = set_flag(arch_cpus, &arch->features, 1, flag);
21921 result = set_flag(arch_flags, &arch->features, act, flag);
21926 static void arch_usage(FILE *fp)
21928 flag_usage(fp, arch_flags, "-m", "-mno-");
21929 flag_usage(fp, arch_cpus, "-mcpu=", 0);
21932 static unsigned arch_regc_size(struct compile_state *state, int class)
21934 if ((class < 0) || (class > LAST_REGC)) {
21937 return regc_size[class];
21940 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21942 /* See if two register classes may have overlapping registers */
21943 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21944 REGCM_GPR32_8 | REGCM_GPR32 |
21945 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21947 /* Special case for the immediates */
21948 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21949 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21950 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21951 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
21954 return (regcm1 & regcm2) ||
21955 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21958 static void arch_reg_equivs(
21959 struct compile_state *state, unsigned *equiv, int reg)
21961 if ((reg < 0) || (reg > LAST_REG)) {
21962 internal_error(state, 0, "invalid register");
21967 #if X86_4_8BIT_GPRS
21971 *equiv++ = REG_EAX;
21972 *equiv++ = REG_DXAX;
21973 *equiv++ = REG_EDXEAX;
21976 #if X86_4_8BIT_GPRS
21980 *equiv++ = REG_EAX;
21981 *equiv++ = REG_DXAX;
21982 *equiv++ = REG_EDXEAX;
21985 #if X86_4_8BIT_GPRS
21989 *equiv++ = REG_EBX;
21993 #if X86_4_8BIT_GPRS
21997 *equiv++ = REG_EBX;
22000 #if X86_4_8BIT_GPRS
22004 *equiv++ = REG_ECX;
22008 #if X86_4_8BIT_GPRS
22012 *equiv++ = REG_ECX;
22015 #if X86_4_8BIT_GPRS
22019 *equiv++ = REG_EDX;
22020 *equiv++ = REG_DXAX;
22021 *equiv++ = REG_EDXEAX;
22024 #if X86_4_8BIT_GPRS
22028 *equiv++ = REG_EDX;
22029 *equiv++ = REG_DXAX;
22030 *equiv++ = REG_EDXEAX;
22035 *equiv++ = REG_EAX;
22036 *equiv++ = REG_DXAX;
22037 *equiv++ = REG_EDXEAX;
22042 *equiv++ = REG_EBX;
22047 *equiv++ = REG_ECX;
22052 *equiv++ = REG_EDX;
22053 *equiv++ = REG_DXAX;
22054 *equiv++ = REG_EDXEAX;
22057 *equiv++ = REG_ESI;
22060 *equiv++ = REG_EDI;
22063 *equiv++ = REG_EBP;
22066 *equiv++ = REG_ESP;
22072 *equiv++ = REG_DXAX;
22073 *equiv++ = REG_EDXEAX;
22089 *equiv++ = REG_DXAX;
22090 *equiv++ = REG_EDXEAX;
22111 *equiv++ = REG_EAX;
22112 *equiv++ = REG_EDX;
22113 *equiv++ = REG_EDXEAX;
22122 *equiv++ = REG_EAX;
22123 *equiv++ = REG_EDX;
22124 *equiv++ = REG_DXAX;
22127 *equiv++ = REG_UNSET;
22130 static unsigned arch_avail_mask(struct compile_state *state)
22132 unsigned avail_mask;
22133 /* REGCM_GPR8 is not available */
22134 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
22135 REGCM_GPR32 | REGCM_GPR32_8 |
22136 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22137 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22138 if (state->arch->features & X86_MMX_REGS) {
22139 avail_mask |= REGCM_MMX;
22141 if (state->arch->features & X86_XMM_REGS) {
22142 avail_mask |= REGCM_XMM;
22147 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22149 unsigned mask, result;
22153 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22154 if ((result & mask) == 0) {
22157 if (class > LAST_REGC) {
22160 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22161 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22162 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22163 result |= (1 << class2);
22167 result &= arch_avail_mask(state);
22171 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22173 /* Like arch_regcm_normalize except immediate register classes are excluded */
22174 regcm = arch_regcm_normalize(state, regcm);
22175 /* Remove the immediate register classes */
22176 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22181 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22186 for(class = 0; class <= LAST_REGC; class++) {
22187 if ((reg >= regcm_bound[class].first) &&
22188 (reg <= regcm_bound[class].last)) {
22189 mask |= (1 << class);
22193 internal_error(state, 0, "reg %d not in any class", reg);
22198 static struct reg_info arch_reg_constraint(
22199 struct compile_state *state, struct type *type, const char *constraint)
22201 static const struct {
22205 } constraints[] = {
22206 { 'r', REGCM_GPR32, REG_UNSET },
22207 { 'g', REGCM_GPR32, REG_UNSET },
22208 { 'p', REGCM_GPR32, REG_UNSET },
22209 { 'q', REGCM_GPR8_LO, REG_UNSET },
22210 { 'Q', REGCM_GPR32_8, REG_UNSET },
22211 { 'x', REGCM_XMM, REG_UNSET },
22212 { 'y', REGCM_MMX, REG_UNSET },
22213 { 'a', REGCM_GPR32, REG_EAX },
22214 { 'b', REGCM_GPR32, REG_EBX },
22215 { 'c', REGCM_GPR32, REG_ECX },
22216 { 'd', REGCM_GPR32, REG_EDX },
22217 { 'D', REGCM_GPR32, REG_EDI },
22218 { 'S', REGCM_GPR32, REG_ESI },
22219 { '\0', 0, REG_UNSET },
22221 unsigned int regcm;
22222 unsigned int mask, reg;
22223 struct reg_info result;
22225 regcm = arch_type_to_regcm(state, type);
22228 for(ptr = constraint; *ptr; ptr++) {
22233 for(i = 0; constraints[i].class != '\0'; i++) {
22234 if (constraints[i].class == *ptr) {
22238 if (constraints[i].class == '\0') {
22239 error(state, 0, "invalid register constraint ``%c''", *ptr);
22242 if ((constraints[i].mask & regcm) == 0) {
22243 error(state, 0, "invalid register class %c specified",
22246 mask |= constraints[i].mask;
22247 if (constraints[i].reg != REG_UNSET) {
22248 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22249 error(state, 0, "Only one register may be specified");
22251 reg = constraints[i].reg;
22255 result.regcm = mask;
22259 static struct reg_info arch_reg_clobber(
22260 struct compile_state *state, const char *clobber)
22262 struct reg_info result;
22263 if (strcmp(clobber, "memory") == 0) {
22264 result.reg = REG_UNSET;
22267 else if (strcmp(clobber, "eax") == 0) {
22268 result.reg = REG_EAX;
22269 result.regcm = REGCM_GPR32;
22271 else if (strcmp(clobber, "ebx") == 0) {
22272 result.reg = REG_EBX;
22273 result.regcm = REGCM_GPR32;
22275 else if (strcmp(clobber, "ecx") == 0) {
22276 result.reg = REG_ECX;
22277 result.regcm = REGCM_GPR32;
22279 else if (strcmp(clobber, "edx") == 0) {
22280 result.reg = REG_EDX;
22281 result.regcm = REGCM_GPR32;
22283 else if (strcmp(clobber, "esi") == 0) {
22284 result.reg = REG_ESI;
22285 result.regcm = REGCM_GPR32;
22287 else if (strcmp(clobber, "edi") == 0) {
22288 result.reg = REG_EDI;
22289 result.regcm = REGCM_GPR32;
22291 else if (strcmp(clobber, "ebp") == 0) {
22292 result.reg = REG_EBP;
22293 result.regcm = REGCM_GPR32;
22295 else if (strcmp(clobber, "esp") == 0) {
22296 result.reg = REG_ESP;
22297 result.regcm = REGCM_GPR32;
22299 else if (strcmp(clobber, "cc") == 0) {
22300 result.reg = REG_EFLAGS;
22301 result.regcm = REGCM_FLAGS;
22303 else if ((strncmp(clobber, "xmm", 3) == 0) &&
22304 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22305 result.reg = REG_XMM0 + octdigval(clobber[3]);
22306 result.regcm = REGCM_XMM;
22308 else if ((strncmp(clobber, "mm", 2) == 0) &&
22309 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22310 result.reg = REG_MMX0 + octdigval(clobber[3]);
22311 result.regcm = REGCM_MMX;
22314 error(state, 0, "unknown register name `%s' in asm",
22316 result.reg = REG_UNSET;
22322 static int do_select_reg(struct compile_state *state,
22323 char *used, int reg, unsigned classes)
22329 mask = arch_reg_regcm(state, reg);
22330 return (classes & mask) ? reg : REG_UNSET;
22333 static int arch_select_free_register(
22334 struct compile_state *state, char *used, int classes)
22336 /* Live ranges with the most neighbors are colored first.
22338 * Generally it does not matter which colors are given
22339 * as the register allocator attempts to color live ranges
22340 * in an order where you are guaranteed not to run out of colors.
22342 * Occasionally the register allocator cannot find an order
22343 * of register selection that will find a free color. To
22344 * increase the odds the register allocator will work when
22345 * it guesses first give out registers from register classes
22346 * least likely to run out of registers.
22351 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22352 reg = do_select_reg(state, used, i, classes);
22354 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22355 reg = do_select_reg(state, used, i, classes);
22357 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22358 reg = do_select_reg(state, used, i, classes);
22360 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22361 reg = do_select_reg(state, used, i, classes);
22363 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22364 reg = do_select_reg(state, used, i, classes);
22366 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22367 reg = do_select_reg(state, used, i, classes);
22369 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22370 reg = do_select_reg(state, used, i, classes);
22372 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22373 reg = do_select_reg(state, used, i, classes);
22375 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22376 reg = do_select_reg(state, used, i, classes);
22382 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
22385 #if DEBUG_ROMCC_WARNINGS
22386 #warning "FIXME force types smaller (if legal) before I get here"
22390 switch(type->type & TYPE_MASK) {
22397 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22398 REGCM_GPR16 | REGCM_GPR16_8 |
22399 REGCM_GPR32 | REGCM_GPR32_8 |
22400 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22401 REGCM_MMX | REGCM_XMM |
22402 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22406 mask = REGCM_GPR16 | REGCM_GPR16_8 |
22407 REGCM_GPR32 | REGCM_GPR32_8 |
22408 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22409 REGCM_MMX | REGCM_XMM |
22410 REGCM_IMM32 | REGCM_IMM16;
22418 mask = REGCM_GPR32 | REGCM_GPR32_8 |
22419 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22420 REGCM_MMX | REGCM_XMM |
22425 mask = arch_type_to_regcm(state, type->left);
22428 mask = arch_type_to_regcm(state, type->left) &
22429 arch_type_to_regcm(state, type->right);
22431 case TYPE_BITFIELD:
22432 mask = arch_type_to_regcm(state, type->left);
22435 fprintf(state->errout, "type: ");
22436 name_of(state->errout, type);
22437 fprintf(state->errout, "\n");
22438 internal_error(state, 0, "no register class for type");
22441 mask = arch_regcm_normalize(state, mask);
22445 static int is_imm32(struct triple *imm)
22447 // second condition commented out to prevent compiler warning:
22448 // imm->u.cval is always 32bit unsigned, so the comparison is
22450 return ((imm->op == OP_INTCONST) /* && (imm->u.cval <= 0xffffffffUL) */ ) ||
22451 (imm->op == OP_ADDRCONST);
22454 static int is_imm16(struct triple *imm)
22456 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22458 static int is_imm8(struct triple *imm)
22460 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22463 static int get_imm32(struct triple *ins, struct triple **expr)
22465 struct triple *imm;
22467 while(imm->op == OP_COPY) {
22470 if (!is_imm32(imm)) {
22473 unuse_triple(*expr, ins);
22474 use_triple(imm, ins);
22479 static int get_imm8(struct triple *ins, struct triple **expr)
22481 struct triple *imm;
22483 while(imm->op == OP_COPY) {
22486 if (!is_imm8(imm)) {
22489 unuse_triple(*expr, ins);
22490 use_triple(imm, ins);
22495 #define TEMPLATE_NOP 0
22496 #define TEMPLATE_INTCONST8 1
22497 #define TEMPLATE_INTCONST32 2
22498 #define TEMPLATE_UNKNOWNVAL 3
22499 #define TEMPLATE_COPY8_REG 5
22500 #define TEMPLATE_COPY16_REG 6
22501 #define TEMPLATE_COPY32_REG 7
22502 #define TEMPLATE_COPY_IMM8 8
22503 #define TEMPLATE_COPY_IMM16 9
22504 #define TEMPLATE_COPY_IMM32 10
22505 #define TEMPLATE_PHI8 11
22506 #define TEMPLATE_PHI16 12
22507 #define TEMPLATE_PHI32 13
22508 #define TEMPLATE_STORE8 14
22509 #define TEMPLATE_STORE16 15
22510 #define TEMPLATE_STORE32 16
22511 #define TEMPLATE_LOAD8 17
22512 #define TEMPLATE_LOAD16 18
22513 #define TEMPLATE_LOAD32 19
22514 #define TEMPLATE_BINARY8_REG 20
22515 #define TEMPLATE_BINARY16_REG 21
22516 #define TEMPLATE_BINARY32_REG 22
22517 #define TEMPLATE_BINARY8_IMM 23
22518 #define TEMPLATE_BINARY16_IMM 24
22519 #define TEMPLATE_BINARY32_IMM 25
22520 #define TEMPLATE_SL8_CL 26
22521 #define TEMPLATE_SL16_CL 27
22522 #define TEMPLATE_SL32_CL 28
22523 #define TEMPLATE_SL8_IMM 29
22524 #define TEMPLATE_SL16_IMM 30
22525 #define TEMPLATE_SL32_IMM 31
22526 #define TEMPLATE_UNARY8 32
22527 #define TEMPLATE_UNARY16 33
22528 #define TEMPLATE_UNARY32 34
22529 #define TEMPLATE_CMP8_REG 35
22530 #define TEMPLATE_CMP16_REG 36
22531 #define TEMPLATE_CMP32_REG 37
22532 #define TEMPLATE_CMP8_IMM 38
22533 #define TEMPLATE_CMP16_IMM 39
22534 #define TEMPLATE_CMP32_IMM 40
22535 #define TEMPLATE_TEST8 41
22536 #define TEMPLATE_TEST16 42
22537 #define TEMPLATE_TEST32 43
22538 #define TEMPLATE_SET 44
22539 #define TEMPLATE_JMP 45
22540 #define TEMPLATE_RET 46
22541 #define TEMPLATE_INB_DX 47
22542 #define TEMPLATE_INB_IMM 48
22543 #define TEMPLATE_INW_DX 49
22544 #define TEMPLATE_INW_IMM 50
22545 #define TEMPLATE_INL_DX 51
22546 #define TEMPLATE_INL_IMM 52
22547 #define TEMPLATE_OUTB_DX 53
22548 #define TEMPLATE_OUTB_IMM 54
22549 #define TEMPLATE_OUTW_DX 55
22550 #define TEMPLATE_OUTW_IMM 56
22551 #define TEMPLATE_OUTL_DX 57
22552 #define TEMPLATE_OUTL_IMM 58
22553 #define TEMPLATE_BSF 59
22554 #define TEMPLATE_RDMSR 60
22555 #define TEMPLATE_WRMSR 61
22556 #define TEMPLATE_UMUL8 62
22557 #define TEMPLATE_UMUL16 63
22558 #define TEMPLATE_UMUL32 64
22559 #define TEMPLATE_DIV8 65
22560 #define TEMPLATE_DIV16 66
22561 #define TEMPLATE_DIV32 67
22562 #define LAST_TEMPLATE TEMPLATE_DIV32
22563 #if LAST_TEMPLATE >= MAX_TEMPLATES
22564 #error "MAX_TEMPLATES to low"
22567 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22568 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
22569 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22572 static struct ins_template templates[] = {
22575 [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22576 [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22577 [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22578 [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22579 [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22580 [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22581 [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22582 [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22583 [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22584 [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22585 [10] = { REG_UNNEEDED, REGCM_IMMALL },
22586 [11] = { REG_UNNEEDED, REGCM_IMMALL },
22587 [12] = { REG_UNNEEDED, REGCM_IMMALL },
22588 [13] = { REG_UNNEEDED, REGCM_IMMALL },
22589 [14] = { REG_UNNEEDED, REGCM_IMMALL },
22590 [15] = { REG_UNNEEDED, REGCM_IMMALL },
22591 [16] = { REG_UNNEEDED, REGCM_IMMALL },
22592 [17] = { REG_UNNEEDED, REGCM_IMMALL },
22593 [18] = { REG_UNNEEDED, REGCM_IMMALL },
22594 [19] = { REG_UNNEEDED, REGCM_IMMALL },
22595 [20] = { REG_UNNEEDED, REGCM_IMMALL },
22596 [21] = { REG_UNNEEDED, REGCM_IMMALL },
22597 [22] = { REG_UNNEEDED, REGCM_IMMALL },
22598 [23] = { REG_UNNEEDED, REGCM_IMMALL },
22599 [24] = { REG_UNNEEDED, REGCM_IMMALL },
22600 [25] = { REG_UNNEEDED, REGCM_IMMALL },
22601 [26] = { REG_UNNEEDED, REGCM_IMMALL },
22602 [27] = { REG_UNNEEDED, REGCM_IMMALL },
22603 [28] = { REG_UNNEEDED, REGCM_IMMALL },
22604 [29] = { REG_UNNEEDED, REGCM_IMMALL },
22605 [30] = { REG_UNNEEDED, REGCM_IMMALL },
22606 [31] = { REG_UNNEEDED, REGCM_IMMALL },
22607 [32] = { REG_UNNEEDED, REGCM_IMMALL },
22608 [33] = { REG_UNNEEDED, REGCM_IMMALL },
22609 [34] = { REG_UNNEEDED, REGCM_IMMALL },
22610 [35] = { REG_UNNEEDED, REGCM_IMMALL },
22611 [36] = { REG_UNNEEDED, REGCM_IMMALL },
22612 [37] = { REG_UNNEEDED, REGCM_IMMALL },
22613 [38] = { REG_UNNEEDED, REGCM_IMMALL },
22614 [39] = { REG_UNNEEDED, REGCM_IMMALL },
22615 [40] = { REG_UNNEEDED, REGCM_IMMALL },
22616 [41] = { REG_UNNEEDED, REGCM_IMMALL },
22617 [42] = { REG_UNNEEDED, REGCM_IMMALL },
22618 [43] = { REG_UNNEEDED, REGCM_IMMALL },
22619 [44] = { REG_UNNEEDED, REGCM_IMMALL },
22620 [45] = { REG_UNNEEDED, REGCM_IMMALL },
22621 [46] = { REG_UNNEEDED, REGCM_IMMALL },
22622 [47] = { REG_UNNEEDED, REGCM_IMMALL },
22623 [48] = { REG_UNNEEDED, REGCM_IMMALL },
22624 [49] = { REG_UNNEEDED, REGCM_IMMALL },
22625 [50] = { REG_UNNEEDED, REGCM_IMMALL },
22626 [51] = { REG_UNNEEDED, REGCM_IMMALL },
22627 [52] = { REG_UNNEEDED, REGCM_IMMALL },
22628 [53] = { REG_UNNEEDED, REGCM_IMMALL },
22629 [54] = { REG_UNNEEDED, REGCM_IMMALL },
22630 [55] = { REG_UNNEEDED, REGCM_IMMALL },
22631 [56] = { REG_UNNEEDED, REGCM_IMMALL },
22632 [57] = { REG_UNNEEDED, REGCM_IMMALL },
22633 [58] = { REG_UNNEEDED, REGCM_IMMALL },
22634 [59] = { REG_UNNEEDED, REGCM_IMMALL },
22635 [60] = { REG_UNNEEDED, REGCM_IMMALL },
22636 [61] = { REG_UNNEEDED, REGCM_IMMALL },
22637 [62] = { REG_UNNEEDED, REGCM_IMMALL },
22638 [63] = { REG_UNNEEDED, REGCM_IMMALL },
22641 [TEMPLATE_INTCONST8] = {
22642 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22644 [TEMPLATE_INTCONST32] = {
22645 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22647 [TEMPLATE_UNKNOWNVAL] = {
22648 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22650 [TEMPLATE_COPY8_REG] = {
22651 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22652 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22654 [TEMPLATE_COPY16_REG] = {
22655 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22656 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22658 [TEMPLATE_COPY32_REG] = {
22659 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22660 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22662 [TEMPLATE_COPY_IMM8] = {
22663 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22664 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22666 [TEMPLATE_COPY_IMM16] = {
22667 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22668 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22670 [TEMPLATE_COPY_IMM32] = {
22671 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22672 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22674 [TEMPLATE_PHI8] = {
22675 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22676 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22678 [TEMPLATE_PHI16] = {
22679 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22680 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22682 [TEMPLATE_PHI32] = {
22683 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22684 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22686 [TEMPLATE_STORE8] = {
22688 [0] = { REG_UNSET, REGCM_GPR32 },
22689 [1] = { REG_UNSET, REGCM_GPR8_LO },
22692 [TEMPLATE_STORE16] = {
22694 [0] = { REG_UNSET, REGCM_GPR32 },
22695 [1] = { REG_UNSET, REGCM_GPR16 },
22698 [TEMPLATE_STORE32] = {
22700 [0] = { REG_UNSET, REGCM_GPR32 },
22701 [1] = { REG_UNSET, REGCM_GPR32 },
22704 [TEMPLATE_LOAD8] = {
22705 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22706 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22708 [TEMPLATE_LOAD16] = {
22709 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22710 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22712 [TEMPLATE_LOAD32] = {
22713 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22714 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22716 [TEMPLATE_BINARY8_REG] = {
22717 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22719 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22720 [1] = { REG_UNSET, REGCM_GPR8_LO },
22723 [TEMPLATE_BINARY16_REG] = {
22724 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22726 [0] = { REG_VIRT0, REGCM_GPR16 },
22727 [1] = { REG_UNSET, REGCM_GPR16 },
22730 [TEMPLATE_BINARY32_REG] = {
22731 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22733 [0] = { REG_VIRT0, REGCM_GPR32 },
22734 [1] = { REG_UNSET, REGCM_GPR32 },
22737 [TEMPLATE_BINARY8_IMM] = {
22738 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22740 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22741 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22744 [TEMPLATE_BINARY16_IMM] = {
22745 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22747 [0] = { REG_VIRT0, REGCM_GPR16 },
22748 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22751 [TEMPLATE_BINARY32_IMM] = {
22752 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22754 [0] = { REG_VIRT0, REGCM_GPR32 },
22755 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22758 [TEMPLATE_SL8_CL] = {
22759 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22761 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22762 [1] = { REG_CL, REGCM_GPR8_LO },
22765 [TEMPLATE_SL16_CL] = {
22766 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22768 [0] = { REG_VIRT0, REGCM_GPR16 },
22769 [1] = { REG_CL, REGCM_GPR8_LO },
22772 [TEMPLATE_SL32_CL] = {
22773 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22775 [0] = { REG_VIRT0, REGCM_GPR32 },
22776 [1] = { REG_CL, REGCM_GPR8_LO },
22779 [TEMPLATE_SL8_IMM] = {
22780 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22782 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22783 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22786 [TEMPLATE_SL16_IMM] = {
22787 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22789 [0] = { REG_VIRT0, REGCM_GPR16 },
22790 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22793 [TEMPLATE_SL32_IMM] = {
22794 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22796 [0] = { REG_VIRT0, REGCM_GPR32 },
22797 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22800 [TEMPLATE_UNARY8] = {
22801 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22802 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22804 [TEMPLATE_UNARY16] = {
22805 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22806 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22808 [TEMPLATE_UNARY32] = {
22809 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22810 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22812 [TEMPLATE_CMP8_REG] = {
22813 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22815 [0] = { REG_UNSET, REGCM_GPR8_LO },
22816 [1] = { REG_UNSET, REGCM_GPR8_LO },
22819 [TEMPLATE_CMP16_REG] = {
22820 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22822 [0] = { REG_UNSET, REGCM_GPR16 },
22823 [1] = { REG_UNSET, REGCM_GPR16 },
22826 [TEMPLATE_CMP32_REG] = {
22827 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22829 [0] = { REG_UNSET, REGCM_GPR32 },
22830 [1] = { REG_UNSET, REGCM_GPR32 },
22833 [TEMPLATE_CMP8_IMM] = {
22834 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22836 [0] = { REG_UNSET, REGCM_GPR8_LO },
22837 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22840 [TEMPLATE_CMP16_IMM] = {
22841 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22843 [0] = { REG_UNSET, REGCM_GPR16 },
22844 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22847 [TEMPLATE_CMP32_IMM] = {
22848 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22850 [0] = { REG_UNSET, REGCM_GPR32 },
22851 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22854 [TEMPLATE_TEST8] = {
22855 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22856 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22858 [TEMPLATE_TEST16] = {
22859 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22860 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22862 [TEMPLATE_TEST32] = {
22863 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22864 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22867 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22868 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22871 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22874 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22876 [TEMPLATE_INB_DX] = {
22877 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22878 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22880 [TEMPLATE_INB_IMM] = {
22881 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22882 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22884 [TEMPLATE_INW_DX] = {
22885 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22886 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22888 [TEMPLATE_INW_IMM] = {
22889 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22890 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22892 [TEMPLATE_INL_DX] = {
22893 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22894 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22896 [TEMPLATE_INL_IMM] = {
22897 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22898 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22900 [TEMPLATE_OUTB_DX] = {
22902 [0] = { REG_AL, REGCM_GPR8_LO },
22903 [1] = { REG_DX, REGCM_GPR16 },
22906 [TEMPLATE_OUTB_IMM] = {
22908 [0] = { REG_AL, REGCM_GPR8_LO },
22909 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22912 [TEMPLATE_OUTW_DX] = {
22914 [0] = { REG_AX, REGCM_GPR16 },
22915 [1] = { REG_DX, REGCM_GPR16 },
22918 [TEMPLATE_OUTW_IMM] = {
22920 [0] = { REG_AX, REGCM_GPR16 },
22921 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22924 [TEMPLATE_OUTL_DX] = {
22926 [0] = { REG_EAX, REGCM_GPR32 },
22927 [1] = { REG_DX, REGCM_GPR16 },
22930 [TEMPLATE_OUTL_IMM] = {
22932 [0] = { REG_EAX, REGCM_GPR32 },
22933 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22937 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22938 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22940 [TEMPLATE_RDMSR] = {
22942 [0] = { REG_EAX, REGCM_GPR32 },
22943 [1] = { REG_EDX, REGCM_GPR32 },
22945 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22947 [TEMPLATE_WRMSR] = {
22949 [0] = { REG_ECX, REGCM_GPR32 },
22950 [1] = { REG_EAX, REGCM_GPR32 },
22951 [2] = { REG_EDX, REGCM_GPR32 },
22954 [TEMPLATE_UMUL8] = {
22955 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22957 [0] = { REG_AL, REGCM_GPR8_LO },
22958 [1] = { REG_UNSET, REGCM_GPR8_LO },
22961 [TEMPLATE_UMUL16] = {
22962 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22964 [0] = { REG_AX, REGCM_GPR16 },
22965 [1] = { REG_UNSET, REGCM_GPR16 },
22968 [TEMPLATE_UMUL32] = {
22969 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22971 [0] = { REG_EAX, REGCM_GPR32 },
22972 [1] = { REG_UNSET, REGCM_GPR32 },
22975 [TEMPLATE_DIV8] = {
22977 [0] = { REG_AL, REGCM_GPR8_LO },
22978 [1] = { REG_AH, REGCM_GPR8 },
22981 [0] = { REG_AX, REGCM_GPR16 },
22982 [1] = { REG_UNSET, REGCM_GPR8_LO },
22985 [TEMPLATE_DIV16] = {
22987 [0] = { REG_AX, REGCM_GPR16 },
22988 [1] = { REG_DX, REGCM_GPR16 },
22991 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
22992 [1] = { REG_UNSET, REGCM_GPR16 },
22995 [TEMPLATE_DIV32] = {
22997 [0] = { REG_EAX, REGCM_GPR32 },
22998 [1] = { REG_EDX, REGCM_GPR32 },
23001 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
23002 [1] = { REG_UNSET, REGCM_GPR32 },
23007 static void fixup_branch(struct compile_state *state,
23008 struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
23009 struct triple *left, struct triple *right)
23011 struct triple *test;
23013 internal_error(state, branch, "no branch test?");
23015 test = pre_triple(state, branch,
23016 cmp_op, cmp_type, left, right);
23017 test->template_id = TEMPLATE_TEST32;
23018 if (cmp_op == OP_CMP) {
23019 test->template_id = TEMPLATE_CMP32_REG;
23020 if (get_imm32(test, &RHS(test, 1))) {
23021 test->template_id = TEMPLATE_CMP32_IMM;
23024 use_triple(RHS(test, 0), test);
23025 use_triple(RHS(test, 1), test);
23026 unuse_triple(RHS(branch, 0), branch);
23027 RHS(branch, 0) = test;
23028 branch->op = jmp_op;
23029 branch->template_id = TEMPLATE_JMP;
23030 use_triple(RHS(branch, 0), branch);
23033 static void fixup_branches(struct compile_state *state,
23034 struct triple *cmp, struct triple *use, int jmp_op)
23036 struct triple_set *entry, *next;
23037 for(entry = use->use; entry; entry = next) {
23038 next = entry->next;
23039 if (entry->member->op == OP_COPY) {
23040 fixup_branches(state, cmp, entry->member, jmp_op);
23042 else if (entry->member->op == OP_CBRANCH) {
23043 struct triple *branch;
23044 struct triple *left, *right;
23046 left = RHS(cmp, 0);
23047 if (cmp->rhs > 1) {
23048 right = RHS(cmp, 1);
23050 branch = entry->member;
23051 fixup_branch(state, branch, jmp_op,
23052 cmp->op, cmp->type, left, right);
23057 static void bool_cmp(struct compile_state *state,
23058 struct triple *ins, int cmp_op, int jmp_op, int set_op)
23060 struct triple_set *entry, *next;
23061 struct triple *set, *convert;
23063 /* Put a barrier up before the cmp which preceeds the
23064 * copy instruction. If a set actually occurs this gives
23065 * us a chance to move variables in registers out of the way.
23068 /* Modify the comparison operator */
23070 ins->template_id = TEMPLATE_TEST32;
23071 if (cmp_op == OP_CMP) {
23072 ins->template_id = TEMPLATE_CMP32_REG;
23073 if (get_imm32(ins, &RHS(ins, 1))) {
23074 ins->template_id = TEMPLATE_CMP32_IMM;
23077 /* Generate the instruction sequence that will transform the
23078 * result of the comparison into a logical value.
23080 set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
23081 use_triple(ins, set);
23082 set->template_id = TEMPLATE_SET;
23085 if (!equiv_types(ins->type, set->type)) {
23086 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
23087 use_triple(set, convert);
23088 convert->template_id = TEMPLATE_COPY32_REG;
23091 for(entry = ins->use; entry; entry = next) {
23092 next = entry->next;
23093 if (entry->member == set) {
23096 replace_rhs_use(state, ins, convert, entry->member);
23098 fixup_branches(state, ins, convert, jmp_op);
23101 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
23103 struct ins_template *template;
23104 struct reg_info result;
23106 if (ins->op == OP_PIECE) {
23107 index = ins->u.cval;
23108 ins = MISC(ins, 0);
23111 if (triple_is_def(state, ins)) {
23114 if (index >= zlhs) {
23115 internal_error(state, ins, "index %d out of range for %s",
23116 index, tops(ins->op));
23120 template = &ins->u.ainfo->tmpl;
23123 if (ins->template_id > LAST_TEMPLATE) {
23124 internal_error(state, ins, "bad template number %d",
23127 template = &templates[ins->template_id];
23130 result = template->lhs[index];
23131 result.regcm = arch_regcm_normalize(state, result.regcm);
23132 if (result.reg != REG_UNNEEDED) {
23133 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23135 if (result.regcm == 0) {
23136 internal_error(state, ins, "lhs %d regcm == 0", index);
23141 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23143 struct reg_info result;
23144 struct ins_template *template;
23145 if ((index > ins->rhs) ||
23146 (ins->op == OP_PIECE)) {
23147 internal_error(state, ins, "index %d out of range for %s\n",
23148 index, tops(ins->op));
23152 template = &ins->u.ainfo->tmpl;
23158 if (ins->template_id > LAST_TEMPLATE) {
23159 internal_error(state, ins, "bad template number %d",
23162 template = &templates[ins->template_id];
23165 result = template->rhs[index];
23166 result.regcm = arch_regcm_normalize(state, result.regcm);
23167 if (result.regcm == 0) {
23168 internal_error(state, ins, "rhs %d regcm == 0", index);
23173 static struct triple *mod_div(struct compile_state *state,
23174 struct triple *ins, int div_op, int index)
23176 struct triple *div, *piece1;
23178 /* Generate the appropriate division instruction */
23179 div = post_triple(state, ins, div_op, ins->type, 0, 0);
23180 RHS(div, 0) = RHS(ins, 0);
23181 RHS(div, 1) = RHS(ins, 1);
23182 piece1 = LHS(div, 1);
23183 div->template_id = TEMPLATE_DIV32;
23184 use_triple(RHS(div, 0), div);
23185 use_triple(RHS(div, 1), div);
23186 use_triple(LHS(div, 0), div);
23187 use_triple(LHS(div, 1), div);
23189 /* Replate uses of ins with the appropriate piece of the div */
23190 propogate_use(state, ins, LHS(div, index));
23191 release_triple(state, ins);
23193 /* Return the address of the next instruction */
23194 return piece1->next;
23197 static int noop_adecl(struct triple *adecl)
23199 struct triple_set *use;
23200 /* It's a noop if it doesn't specify stoorage */
23201 if (adecl->lhs == 0) {
23204 /* Is the adecl used? If not it's a noop */
23205 for(use = adecl->use; use ; use = use->next) {
23206 if ((use->member->op != OP_PIECE) ||
23207 (MISC(use->member, 0) != adecl)) {
23214 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23216 struct triple *mask, *nmask, *shift;
23217 struct triple *val, *val_mask, *val_shift;
23218 struct triple *targ, *targ_mask;
23219 struct triple *new;
23220 ulong_t the_mask, the_nmask;
23222 targ = RHS(ins, 0);
23225 /* Get constant for the mask value */
23227 the_mask <<= ins->u.bitfield.size;
23229 the_mask <<= ins->u.bitfield.offset;
23230 mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23231 mask->u.cval = the_mask;
23233 /* Get the inverted mask value */
23234 the_nmask = ~the_mask;
23235 nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23236 nmask->u.cval = the_nmask;
23238 /* Get constant for the shift value */
23239 shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23240 shift->u.cval = ins->u.bitfield.offset;
23242 /* Shift and mask the source value */
23244 if (shift->u.cval != 0) {
23245 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23246 use_triple(val, val_shift);
23247 use_triple(shift, val_shift);
23249 val_mask = val_shift;
23250 if (is_signed(val->type)) {
23251 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23252 use_triple(val_shift, val_mask);
23253 use_triple(mask, val_mask);
23256 /* Mask the target value */
23257 targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23258 use_triple(targ, targ_mask);
23259 use_triple(nmask, targ_mask);
23261 /* Now combined them together */
23262 new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23263 use_triple(targ_mask, new);
23264 use_triple(val_mask, new);
23266 /* Move all of the users over to the new expression */
23267 propogate_use(state, ins, new);
23269 /* Delete the original triple */
23270 release_triple(state, ins);
23272 /* Restart the transformation at mask */
23276 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23278 struct triple *mask, *shift;
23279 struct triple *val, *val_mask, *val_shift;
23284 /* Get constant for the mask value */
23286 the_mask <<= ins->u.bitfield.size;
23288 mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23289 mask->u.cval = the_mask;
23291 /* Get constant for the right shift value */
23292 shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23293 shift->u.cval = ins->u.bitfield.offset;
23295 /* Shift arithmetic right, to correct the sign */
23297 if (shift->u.cval != 0) {
23299 if (ins->op == OP_SEXTRACT) {
23304 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23305 use_triple(val, val_shift);
23306 use_triple(shift, val_shift);
23309 /* Finally mask the value */
23310 val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23311 use_triple(val_shift, val_mask);
23312 use_triple(mask, val_mask);
23314 /* Move all of the users over to the new expression */
23315 propogate_use(state, ins, val_mask);
23317 /* Release the original instruction */
23318 release_triple(state, ins);
23324 static struct triple *transform_to_arch_instruction(
23325 struct compile_state *state, struct triple *ins)
23327 /* Transform from generic 3 address instructions
23328 * to archtecture specific instructions.
23329 * And apply architecture specific constraints to instructions.
23330 * Copies are inserted to preserve the register flexibility
23331 * of 3 address instructions.
23333 struct triple *next, *value;
23338 ins->template_id = TEMPLATE_INTCONST32;
23339 if (ins->u.cval < 256) {
23340 ins->template_id = TEMPLATE_INTCONST8;
23344 ins->template_id = TEMPLATE_INTCONST32;
23346 case OP_UNKNOWNVAL:
23347 ins->template_id = TEMPLATE_UNKNOWNVAL;
23353 ins->template_id = TEMPLATE_NOP;
23357 size = size_of(state, ins->type);
23358 value = RHS(ins, 0);
23359 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23360 ins->template_id = TEMPLATE_COPY_IMM8;
23362 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23363 ins->template_id = TEMPLATE_COPY_IMM16;
23365 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23366 ins->template_id = TEMPLATE_COPY_IMM32;
23368 else if (is_const(value)) {
23369 internal_error(state, ins, "bad constant passed to copy");
23371 else if (size <= SIZEOF_I8) {
23372 ins->template_id = TEMPLATE_COPY8_REG;
23374 else if (size <= SIZEOF_I16) {
23375 ins->template_id = TEMPLATE_COPY16_REG;
23377 else if (size <= SIZEOF_I32) {
23378 ins->template_id = TEMPLATE_COPY32_REG;
23381 internal_error(state, ins, "bad type passed to copy");
23385 size = size_of(state, ins->type);
23386 if (size <= SIZEOF_I8) {
23387 ins->template_id = TEMPLATE_PHI8;
23389 else if (size <= SIZEOF_I16) {
23390 ins->template_id = TEMPLATE_PHI16;
23392 else if (size <= SIZEOF_I32) {
23393 ins->template_id = TEMPLATE_PHI32;
23396 internal_error(state, ins, "bad type passed to phi");
23400 /* Adecls should always be treated as dead code and
23401 * removed. If we are not optimizing they may linger.
23403 if (!noop_adecl(ins)) {
23404 internal_error(state, ins, "adecl remains?");
23406 ins->template_id = TEMPLATE_NOP;
23407 next = after_lhs(state, ins);
23410 switch(ins->type->type & TYPE_MASK) {
23411 case TYPE_CHAR: case TYPE_UCHAR:
23412 ins->template_id = TEMPLATE_STORE8;
23414 case TYPE_SHORT: case TYPE_USHORT:
23415 ins->template_id = TEMPLATE_STORE16;
23417 case TYPE_INT: case TYPE_UINT:
23418 case TYPE_LONG: case TYPE_ULONG:
23420 ins->template_id = TEMPLATE_STORE32;
23423 internal_error(state, ins, "unknown type in store");
23428 switch(ins->type->type & TYPE_MASK) {
23429 case TYPE_CHAR: case TYPE_UCHAR:
23430 case TYPE_SHORT: case TYPE_USHORT:
23431 case TYPE_INT: case TYPE_UINT:
23432 case TYPE_LONG: case TYPE_ULONG:
23436 internal_error(state, ins, "unknown type in load");
23439 ins->template_id = TEMPLATE_LOAD32;
23447 ins->template_id = TEMPLATE_BINARY32_REG;
23448 if (get_imm32(ins, &RHS(ins, 1))) {
23449 ins->template_id = TEMPLATE_BINARY32_IMM;
23454 ins->template_id = TEMPLATE_DIV32;
23455 next = after_lhs(state, ins);
23458 ins->template_id = TEMPLATE_UMUL32;
23461 next = mod_div(state, ins, OP_UDIVT, 0);
23464 next = mod_div(state, ins, OP_SDIVT, 0);
23467 next = mod_div(state, ins, OP_UDIVT, 1);
23470 next = mod_div(state, ins, OP_SDIVT, 1);
23475 ins->template_id = TEMPLATE_SL32_CL;
23476 if (get_imm8(ins, &RHS(ins, 1))) {
23477 ins->template_id = TEMPLATE_SL32_IMM;
23478 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23479 typed_pre_copy(state, &uchar_type, ins, 1);
23484 ins->template_id = TEMPLATE_UNARY32;
23487 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
23490 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23493 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23496 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23499 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23502 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23505 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23508 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23511 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23514 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23517 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23520 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23524 ins->template_id = TEMPLATE_NOP;
23527 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST,
23528 RHS(ins, 0)->type, RHS(ins, 0), 0);
23531 ins->template_id = TEMPLATE_NOP;
23534 ins->template_id = TEMPLATE_RET;
23540 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23541 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23542 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23544 if (get_imm8(ins, &RHS(ins, 0))) {
23545 ins->template_id += 1;
23552 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23553 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23554 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23556 if (get_imm8(ins, &RHS(ins, 1))) {
23557 ins->template_id += 1;
23562 ins->template_id = TEMPLATE_BSF;
23565 ins->template_id = TEMPLATE_RDMSR;
23566 next = after_lhs(state, ins);
23569 ins->template_id = TEMPLATE_WRMSR;
23572 ins->template_id = TEMPLATE_NOP;
23575 ins->template_id = TEMPLATE_NOP;
23576 next = after_lhs(state, ins);
23578 /* Already transformed instructions */
23580 ins->template_id = TEMPLATE_TEST32;
23583 ins->template_id = TEMPLATE_CMP32_REG;
23584 if (get_imm32(ins, &RHS(ins, 1))) {
23585 ins->template_id = TEMPLATE_CMP32_IMM;
23589 ins->template_id = TEMPLATE_NOP;
23591 case OP_JMP_EQ: case OP_JMP_NOTEQ:
23592 case OP_JMP_SLESS: case OP_JMP_ULESS:
23593 case OP_JMP_SMORE: case OP_JMP_UMORE:
23594 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23595 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23596 ins->template_id = TEMPLATE_JMP;
23598 case OP_SET_EQ: case OP_SET_NOTEQ:
23599 case OP_SET_SLESS: case OP_SET_ULESS:
23600 case OP_SET_SMORE: case OP_SET_UMORE:
23601 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23602 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23603 ins->template_id = TEMPLATE_SET;
23606 next = x86_deposit(state, ins);
23610 next = x86_extract(state, ins);
23612 /* Unhandled instructions */
23615 internal_error(state, ins, "unhandled ins: %d %s",
23616 ins->op, tops(ins->op));
23622 static long next_label(struct compile_state *state)
23624 static long label_counter = 1000;
23625 return ++label_counter;
23627 static void generate_local_labels(struct compile_state *state)
23629 struct triple *first, *label;
23630 first = state->first;
23633 if ((label->op == OP_LABEL) ||
23634 (label->op == OP_SDECL)) {
23636 label->u.cval = next_label(state);
23642 label = label->next;
23643 } while(label != first);
23646 static int check_reg(struct compile_state *state,
23647 struct triple *triple, int classes)
23651 reg = ID_REG(triple->id);
23652 if (reg == REG_UNSET) {
23653 internal_error(state, triple, "register not set");
23655 mask = arch_reg_regcm(state, reg);
23656 if (!(classes & mask)) {
23657 internal_error(state, triple, "reg %d in wrong class",
23665 #error "Registers have renumberd fix arch_reg_str"
23667 static const char *arch_regs[] = {
23671 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23672 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23673 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23676 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23677 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
23678 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23680 static const char *arch_reg_str(int reg)
23682 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23685 return arch_regs[reg];
23688 static const char *reg(struct compile_state *state, struct triple *triple,
23692 reg = check_reg(state, triple, classes);
23693 return arch_reg_str(reg);
23696 static int arch_reg_size(int reg)
23700 if (reg == REG_EFLAGS) {
23703 else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23706 else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23709 else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23712 else if (reg == REG_EDXEAX) {
23715 else if (reg == REG_DXAX) {
23718 else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23721 else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23727 static int reg_size(struct compile_state *state, struct triple *ins)
23730 reg = ID_REG(ins->id);
23731 if (reg == REG_UNSET) {
23732 internal_error(state, ins, "register not set");
23734 return arch_reg_size(reg);
23739 const char *type_suffix(struct compile_state *state, struct type *type)
23741 const char *suffix;
23742 switch(size_of(state, type)) {
23743 case SIZEOF_I8: suffix = "b"; break;
23744 case SIZEOF_I16: suffix = "w"; break;
23745 case SIZEOF_I32: suffix = "l"; break;
23747 internal_error(state, 0, "unknown suffix");
23754 static void print_const_val(
23755 struct compile_state *state, struct triple *ins, FILE *fp)
23759 fprintf(fp, " $%ld ",
23760 (long)(ins->u.cval));
23763 if ((MISC(ins, 0)->op != OP_SDECL) &&
23764 (MISC(ins, 0)->op != OP_LABEL))
23766 internal_error(state, ins, "bad base for addrconst");
23768 if (MISC(ins, 0)->u.cval <= 0) {
23769 internal_error(state, ins, "unlabeled constant");
23771 fprintf(fp, " $L%s%lu+%lu ",
23772 state->compiler->label_prefix,
23773 (unsigned long)(MISC(ins, 0)->u.cval),
23774 (unsigned long)(ins->u.cval));
23777 internal_error(state, ins, "unknown constant type");
23782 static void print_const(struct compile_state *state,
23783 struct triple *ins, FILE *fp)
23787 switch(ins->type->type & TYPE_MASK) {
23790 fprintf(fp, ".byte 0x%02lx\n",
23791 (unsigned long)(ins->u.cval));
23795 fprintf(fp, ".short 0x%04lx\n",
23796 (unsigned long)(ins->u.cval));
23803 fprintf(fp, ".int %lu\n",
23804 (unsigned long)(ins->u.cval));
23807 fprintf(state->errout, "type: ");
23808 name_of(state->errout, ins->type);
23809 fprintf(state->errout, "\n");
23810 internal_error(state, ins, "Unknown constant type. Val: %lu",
23811 (unsigned long)(ins->u.cval));
23816 if ((MISC(ins, 0)->op != OP_SDECL) &&
23817 (MISC(ins, 0)->op != OP_LABEL)) {
23818 internal_error(state, ins, "bad base for addrconst");
23820 if (MISC(ins, 0)->u.cval <= 0) {
23821 internal_error(state, ins, "unlabeled constant");
23823 fprintf(fp, ".int L%s%lu+%lu\n",
23824 state->compiler->label_prefix,
23825 (unsigned long)(MISC(ins, 0)->u.cval),
23826 (unsigned long)(ins->u.cval));
23830 unsigned char *blob;
23832 size = size_of_in_bytes(state, ins->type);
23833 blob = ins->u.blob;
23834 for(i = 0; i < size; i++) {
23835 fprintf(fp, ".byte 0x%02x\n",
23841 internal_error(state, ins, "Unknown constant type");
23846 #define TEXT_SECTION ".rom.text"
23847 #define DATA_SECTION ".rom.data"
23849 static long get_const_pool_ref(
23850 struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23854 ref = next_label(state);
23855 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23856 fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
23857 fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23858 print_const(state, ins, fp);
23859 fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23861 fprintf(fp, ".fill %ld, 1, 0\n", (long int)fill_bytes);
23863 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23867 static long get_mask_pool_ref(
23868 struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23871 if (mask == 0xff) {
23874 else if (mask == 0xffff) {
23879 internal_error(state, ins, "unhandled mask value");
23884 static void print_binary_op(struct compile_state *state,
23885 const char *op, struct triple *ins, FILE *fp)
23888 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23889 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23890 internal_error(state, ins, "invalid register assignment");
23892 if (is_const(RHS(ins, 1))) {
23893 fprintf(fp, "\t%s ", op);
23894 print_const_val(state, RHS(ins, 1), fp);
23895 fprintf(fp, ", %s\n",
23896 reg(state, RHS(ins, 0), mask));
23899 unsigned lmask, rmask;
23901 lreg = check_reg(state, RHS(ins, 0), mask);
23902 rreg = check_reg(state, RHS(ins, 1), mask);
23903 lmask = arch_reg_regcm(state, lreg);
23904 rmask = arch_reg_regcm(state, rreg);
23905 mask = lmask & rmask;
23906 fprintf(fp, "\t%s %s, %s\n",
23908 reg(state, RHS(ins, 1), mask),
23909 reg(state, RHS(ins, 0), mask));
23912 static void print_unary_op(struct compile_state *state,
23913 const char *op, struct triple *ins, FILE *fp)
23916 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23917 fprintf(fp, "\t%s %s\n",
23919 reg(state, RHS(ins, 0), mask));
23922 static void print_op_shift(struct compile_state *state,
23923 const char *op, struct triple *ins, FILE *fp)
23926 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23927 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23928 internal_error(state, ins, "invalid register assignment");
23930 if (is_const(RHS(ins, 1))) {
23931 fprintf(fp, "\t%s ", op);
23932 print_const_val(state, RHS(ins, 1), fp);
23933 fprintf(fp, ", %s\n",
23934 reg(state, RHS(ins, 0), mask));
23937 fprintf(fp, "\t%s %s, %s\n",
23939 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23940 reg(state, RHS(ins, 0), mask));
23944 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23951 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23952 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23953 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23955 internal_error(state, ins, "not an in operation");
23959 dreg = check_reg(state, ins, mask);
23960 if (!reg_is_reg(state, dreg, REG_EAX)) {
23961 internal_error(state, ins, "dst != %%eax");
23963 if (is_const(RHS(ins, 0))) {
23964 fprintf(fp, "\t%s ", op);
23965 print_const_val(state, RHS(ins, 0), fp);
23966 fprintf(fp, ", %s\n",
23967 reg(state, ins, mask));
23971 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23972 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23973 internal_error(state, ins, "src != %%dx");
23975 fprintf(fp, "\t%s %s, %s\n",
23977 reg(state, RHS(ins, 0), REGCM_GPR16),
23978 reg(state, ins, mask));
23982 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
23989 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
23990 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
23991 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
23993 internal_error(state, ins, "not an out operation");
23997 lreg = check_reg(state, RHS(ins, 0), mask);
23998 if (!reg_is_reg(state, lreg, REG_EAX)) {
23999 internal_error(state, ins, "src != %%eax");
24001 if (is_const(RHS(ins, 1))) {
24002 fprintf(fp, "\t%s %s,",
24003 op, reg(state, RHS(ins, 0), mask));
24004 print_const_val(state, RHS(ins, 1), fp);
24009 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
24010 if (!reg_is_reg(state, addr_reg, REG_DX)) {
24011 internal_error(state, ins, "dst != %%dx");
24013 fprintf(fp, "\t%s %s, %s\n",
24015 reg(state, RHS(ins, 0), mask),
24016 reg(state, RHS(ins, 1), REGCM_GPR16));
24020 static void print_op_move(struct compile_state *state,
24021 struct triple *ins, FILE *fp)
24023 /* op_move is complex because there are many types
24024 * of registers we can move between.
24025 * Because OP_COPY will be introduced in arbitrary locations
24026 * OP_COPY must not affect flags.
24027 * OP_CONVERT can change the flags and it is the only operation
24028 * where it is expected the types in the registers can change.
24030 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
24031 struct triple *dst, *src;
24032 if (state->arch->features & X86_NOOP_COPY) {
24035 if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
24040 internal_error(state, ins, "unknown move operation");
24043 if (reg_size(state, dst) < size_of(state, dst->type)) {
24044 internal_error(state, ins, "Invalid destination register");
24046 if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
24047 fprintf(state->errout, "src type: ");
24048 name_of(state->errout, src->type);
24049 fprintf(state->errout, "\n");
24050 fprintf(state->errout, "dst type: ");
24051 name_of(state->errout, dst->type);
24052 fprintf(state->errout, "\n");
24053 internal_error(state, ins, "Type mismatch for OP_COPY");
24056 if (!is_const(src)) {
24057 int src_reg, dst_reg;
24058 int src_regcm, dst_regcm;
24059 src_reg = ID_REG(src->id);
24060 dst_reg = ID_REG(dst->id);
24061 src_regcm = arch_reg_regcm(state, src_reg);
24062 dst_regcm = arch_reg_regcm(state, dst_reg);
24063 /* If the class is the same just move the register */
24064 if (src_regcm & dst_regcm &
24065 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
24066 if ((src_reg != dst_reg) || !omit_copy) {
24067 fprintf(fp, "\tmov %s, %s\n",
24068 reg(state, src, src_regcm),
24069 reg(state, dst, dst_regcm));
24072 /* Move 32bit to 16bit */
24073 else if ((src_regcm & REGCM_GPR32) &&
24074 (dst_regcm & REGCM_GPR16)) {
24075 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
24076 if ((src_reg != dst_reg) || !omit_copy) {
24077 fprintf(fp, "\tmovw %s, %s\n",
24078 arch_reg_str(src_reg),
24079 arch_reg_str(dst_reg));
24082 /* Move from 32bit gprs to 16bit gprs */
24083 else if ((src_regcm & REGCM_GPR32) &&
24084 (dst_regcm & REGCM_GPR16)) {
24085 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24086 if ((src_reg != dst_reg) || !omit_copy) {
24087 fprintf(fp, "\tmov %s, %s\n",
24088 arch_reg_str(src_reg),
24089 arch_reg_str(dst_reg));
24092 /* Move 32bit to 8bit */
24093 else if ((src_regcm & REGCM_GPR32_8) &&
24094 (dst_regcm & REGCM_GPR8_LO))
24096 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
24097 if ((src_reg != dst_reg) || !omit_copy) {
24098 fprintf(fp, "\tmovb %s, %s\n",
24099 arch_reg_str(src_reg),
24100 arch_reg_str(dst_reg));
24103 /* Move 16bit to 8bit */
24104 else if ((src_regcm & REGCM_GPR16_8) &&
24105 (dst_regcm & REGCM_GPR8_LO))
24107 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24108 if ((src_reg != dst_reg) || !omit_copy) {
24109 fprintf(fp, "\tmovb %s, %s\n",
24110 arch_reg_str(src_reg),
24111 arch_reg_str(dst_reg));
24114 /* Move 8/16bit to 16/32bit */
24115 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
24116 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24118 op = is_signed(src->type)? "movsx": "movzx";
24119 fprintf(fp, "\t%s %s, %s\n",
24121 reg(state, src, src_regcm),
24122 reg(state, dst, dst_regcm));
24124 /* Move between sse registers */
24125 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24126 if ((src_reg != dst_reg) || !omit_copy) {
24127 fprintf(fp, "\tmovdqa %s, %s\n",
24128 reg(state, src, src_regcm),
24129 reg(state, dst, dst_regcm));
24132 /* Move between mmx registers */
24133 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24134 if ((src_reg != dst_reg) || !omit_copy) {
24135 fprintf(fp, "\tmovq %s, %s\n",
24136 reg(state, src, src_regcm),
24137 reg(state, dst, dst_regcm));
24140 /* Move from sse to mmx registers */
24141 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24142 fprintf(fp, "\tmovdq2q %s, %s\n",
24143 reg(state, src, src_regcm),
24144 reg(state, dst, dst_regcm));
24146 /* Move from mmx to sse registers */
24147 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24148 fprintf(fp, "\tmovq2dq %s, %s\n",
24149 reg(state, src, src_regcm),
24150 reg(state, dst, dst_regcm));
24152 /* Move between 32bit gprs & mmx/sse registers */
24153 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24154 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24155 fprintf(fp, "\tmovd %s, %s\n",
24156 reg(state, src, src_regcm),
24157 reg(state, dst, dst_regcm));
24159 /* Move from 16bit gprs & mmx/sse registers */
24160 else if ((src_regcm & REGCM_GPR16) &&
24161 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24164 op = is_signed(src->type)? "movsx":"movzx";
24165 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24166 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24168 arch_reg_str(src_reg),
24169 arch_reg_str(mid_reg),
24170 arch_reg_str(mid_reg),
24171 arch_reg_str(dst_reg));
24173 /* Move from mmx/sse registers to 16bit gprs */
24174 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24175 (dst_regcm & REGCM_GPR16)) {
24176 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24177 fprintf(fp, "\tmovd %s, %s\n",
24178 arch_reg_str(src_reg),
24179 arch_reg_str(dst_reg));
24181 /* Move from gpr to 64bit dividend */
24182 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
24183 (dst_regcm & REGCM_DIVIDEND64)) {
24184 const char *extend;
24185 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24186 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24187 arch_reg_str(src_reg),
24190 /* Move from 64bit gpr to gpr */
24191 else if ((src_regcm & REGCM_DIVIDEND64) &&
24192 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24193 if (dst_regcm & REGCM_GPR32) {
24196 else if (dst_regcm & REGCM_GPR16) {
24199 else if (dst_regcm & REGCM_GPR8_LO) {
24202 fprintf(fp, "\tmov %s, %s\n",
24203 arch_reg_str(src_reg),
24204 arch_reg_str(dst_reg));
24206 /* Move from mmx/sse registers to 64bit gpr */
24207 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24208 (dst_regcm & REGCM_DIVIDEND64)) {
24209 const char *extend;
24210 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24211 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24212 arch_reg_str(src_reg),
24215 /* Move from 64bit gpr to mmx/sse register */
24216 else if ((src_regcm & REGCM_DIVIDEND64) &&
24217 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24218 fprintf(fp, "\tmovd %%eax, %s\n",
24219 arch_reg_str(dst_reg));
24221 #if X86_4_8BIT_GPRS
24222 /* Move from 8bit gprs to mmx/sse registers */
24223 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24224 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24227 op = is_signed(src->type)? "movsx":"movzx";
24228 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24229 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24231 reg(state, src, src_regcm),
24232 arch_reg_str(mid_reg),
24233 arch_reg_str(mid_reg),
24234 reg(state, dst, dst_regcm));
24236 /* Move from mmx/sse registers and 8bit gprs */
24237 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24238 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24240 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24241 fprintf(fp, "\tmovd %s, %s\n",
24242 reg(state, src, src_regcm),
24243 arch_reg_str(mid_reg));
24245 /* Move from 32bit gprs to 8bit gprs */
24246 else if ((src_regcm & REGCM_GPR32) &&
24247 (dst_regcm & REGCM_GPR8_LO)) {
24248 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24249 if ((src_reg != dst_reg) || !omit_copy) {
24250 fprintf(fp, "\tmov %s, %s\n",
24251 arch_reg_str(src_reg),
24252 arch_reg_str(dst_reg));
24255 /* Move from 16bit gprs to 8bit gprs */
24256 else if ((src_regcm & REGCM_GPR16) &&
24257 (dst_regcm & REGCM_GPR8_LO)) {
24258 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24259 if ((src_reg != dst_reg) || !omit_copy) {
24260 fprintf(fp, "\tmov %s, %s\n",
24261 arch_reg_str(src_reg),
24262 arch_reg_str(dst_reg));
24265 #endif /* X86_4_8BIT_GPRS */
24266 /* Move from %eax:%edx to %eax:%edx */
24267 else if ((src_regcm & REGCM_DIVIDEND64) &&
24268 (dst_regcm & REGCM_DIVIDEND64) &&
24269 (src_reg == dst_reg)) {
24271 fprintf(fp, "\t/*mov %s, %s*/\n",
24272 arch_reg_str(src_reg),
24273 arch_reg_str(dst_reg));
24277 if ((src_regcm & ~REGCM_FLAGS) == 0) {
24278 internal_error(state, ins, "attempt to copy from %%eflags!");
24280 internal_error(state, ins, "unknown copy type");
24287 dst_size = size_of(state, dst->type);
24288 dst_reg = ID_REG(dst->id);
24289 dst_regcm = arch_reg_regcm(state, dst_reg);
24290 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24291 fprintf(fp, "\tmov ");
24292 print_const_val(state, src, fp);
24293 fprintf(fp, ", %s\n",
24294 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24296 else if (dst_regcm & REGCM_DIVIDEND64) {
24297 if (dst_size > SIZEOF_I32) {
24298 internal_error(state, ins, "%dbit constant...", dst_size);
24300 fprintf(fp, "\tmov $0, %%edx\n");
24301 fprintf(fp, "\tmov ");
24302 print_const_val(state, src, fp);
24303 fprintf(fp, ", %%eax\n");
24305 else if (dst_regcm & REGCM_DIVIDEND32) {
24306 if (dst_size > SIZEOF_I16) {
24307 internal_error(state, ins, "%dbit constant...", dst_size);
24309 fprintf(fp, "\tmov $0, %%dx\n");
24310 fprintf(fp, "\tmov ");
24311 print_const_val(state, src, fp);
24312 fprintf(fp, ", %%ax");
24314 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24316 if (dst_size > SIZEOF_I32) {
24317 internal_error(state, ins, "%d bit constant...", dst_size);
24319 ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24320 fprintf(fp, "\tmovd L%s%lu, %s\n",
24321 state->compiler->label_prefix, ref,
24322 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24325 internal_error(state, ins, "unknown copy immediate type");
24328 /* Leave now if this is not a type conversion */
24329 if (ins->op != OP_CONVERT) {
24332 /* Now make certain I have not logically overflowed the destination */
24333 if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24334 (size_of(state, dst->type) < reg_size(state, dst)))
24336 unsigned long mask;
24339 if (size_of(state, dst->type) >= 32) {
24340 fprintf(state->errout, "dst type: ");
24341 name_of(state->errout, dst->type);
24342 fprintf(state->errout, "\n");
24343 internal_error(state, dst, "unhandled dst type size");
24346 mask <<= size_of(state, dst->type);
24349 dst_reg = ID_REG(dst->id);
24350 dst_regcm = arch_reg_regcm(state, dst_reg);
24352 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24353 fprintf(fp, "\tand $0x%lx, %s\n",
24354 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24356 else if (dst_regcm & REGCM_MMX) {
24358 ref = get_mask_pool_ref(state, dst, mask, fp);
24359 fprintf(fp, "\tpand L%s%lu, %s\n",
24360 state->compiler->label_prefix, ref,
24361 reg(state, dst, REGCM_MMX));
24363 else if (dst_regcm & REGCM_XMM) {
24365 ref = get_mask_pool_ref(state, dst, mask, fp);
24366 fprintf(fp, "\tpand L%s%lu, %s\n",
24367 state->compiler->label_prefix, ref,
24368 reg(state, dst, REGCM_XMM));
24371 fprintf(state->errout, "dst type: ");
24372 name_of(state->errout, dst->type);
24373 fprintf(state->errout, "\n");
24374 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24375 internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24378 /* Make certain I am properly sign extended */
24379 if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24380 (is_signed(src->type)))
24382 int reg_bits, shift_bits;
24386 reg_bits = reg_size(state, dst);
24387 if (reg_bits > 32) {
24390 shift_bits = reg_bits - size_of(state, src->type);
24391 dst_reg = ID_REG(dst->id);
24392 dst_regcm = arch_reg_regcm(state, dst_reg);
24394 if (shift_bits < 0) {
24395 internal_error(state, dst, "negative shift?");
24398 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24399 fprintf(fp, "\tshl $%d, %s\n",
24401 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24402 fprintf(fp, "\tsar $%d, %s\n",
24404 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24406 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24407 fprintf(fp, "\tpslld $%d, %s\n",
24409 reg(state, dst, REGCM_MMX | REGCM_XMM));
24410 fprintf(fp, "\tpsrad $%d, %s\n",
24412 reg(state, dst, REGCM_MMX | REGCM_XMM));
24415 fprintf(state->errout, "dst type: ");
24416 name_of(state->errout, dst->type);
24417 fprintf(state->errout, "\n");
24418 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24419 internal_error(state, dst, "failed to signed extend value");
24424 static void print_op_load(struct compile_state *state,
24425 struct triple *ins, FILE *fp)
24427 struct triple *dst, *src;
24431 if (is_const(src) || is_const(dst)) {
24432 internal_error(state, ins, "unknown load operation");
24434 switch(ins->type->type & TYPE_MASK) {
24435 case TYPE_CHAR: op = "movsbl"; break;
24436 case TYPE_UCHAR: op = "movzbl"; break;
24437 case TYPE_SHORT: op = "movswl"; break;
24438 case TYPE_USHORT: op = "movzwl"; break;
24439 case TYPE_INT: case TYPE_UINT:
24440 case TYPE_LONG: case TYPE_ULONG:
24445 internal_error(state, ins, "unknown type in load");
24446 op = "<invalid opcode>";
24449 fprintf(fp, "\t%s (%s), %s\n",
24451 reg(state, src, REGCM_GPR32),
24452 reg(state, dst, REGCM_GPR32));
24456 static void print_op_store(struct compile_state *state,
24457 struct triple *ins, FILE *fp)
24459 struct triple *dst, *src;
24462 if (is_const(src) && (src->op == OP_INTCONST)) {
24464 value = (long_t)(src->u.cval);
24465 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24466 type_suffix(state, src->type),
24468 reg(state, dst, REGCM_GPR32));
24470 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24471 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24472 type_suffix(state, src->type),
24473 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24474 (unsigned long)(dst->u.cval));
24477 if (is_const(src) || is_const(dst)) {
24478 internal_error(state, ins, "unknown store operation");
24480 fprintf(fp, "\tmov%s %s, (%s)\n",
24481 type_suffix(state, src->type),
24482 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24483 reg(state, dst, REGCM_GPR32));
24489 static void print_op_smul(struct compile_state *state,
24490 struct triple *ins, FILE *fp)
24492 if (!is_const(RHS(ins, 1))) {
24493 fprintf(fp, "\timul %s, %s\n",
24494 reg(state, RHS(ins, 1), REGCM_GPR32),
24495 reg(state, RHS(ins, 0), REGCM_GPR32));
24498 fprintf(fp, "\timul ");
24499 print_const_val(state, RHS(ins, 1), fp);
24500 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24504 static void print_op_cmp(struct compile_state *state,
24505 struct triple *ins, FILE *fp)
24509 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24510 dreg = check_reg(state, ins, REGCM_FLAGS);
24511 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24512 internal_error(state, ins, "bad dest register for cmp");
24514 if (is_const(RHS(ins, 1))) {
24515 fprintf(fp, "\tcmp ");
24516 print_const_val(state, RHS(ins, 1), fp);
24517 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24520 unsigned lmask, rmask;
24522 lreg = check_reg(state, RHS(ins, 0), mask);
24523 rreg = check_reg(state, RHS(ins, 1), mask);
24524 lmask = arch_reg_regcm(state, lreg);
24525 rmask = arch_reg_regcm(state, rreg);
24526 mask = lmask & rmask;
24527 fprintf(fp, "\tcmp %s, %s\n",
24528 reg(state, RHS(ins, 1), mask),
24529 reg(state, RHS(ins, 0), mask));
24533 static void print_op_test(struct compile_state *state,
24534 struct triple *ins, FILE *fp)
24537 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24538 fprintf(fp, "\ttest %s, %s\n",
24539 reg(state, RHS(ins, 0), mask),
24540 reg(state, RHS(ins, 0), mask));
24543 static void print_op_branch(struct compile_state *state,
24544 struct triple *branch, FILE *fp)
24546 const char *bop = "j";
24547 if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24548 if (branch->rhs != 0) {
24549 internal_error(state, branch, "jmp with condition?");
24554 struct triple *ptr;
24555 if (branch->rhs != 1) {
24556 internal_error(state, branch, "jmpcc without condition?");
24558 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24559 if ((RHS(branch, 0)->op != OP_CMP) &&
24560 (RHS(branch, 0)->op != OP_TEST)) {
24561 internal_error(state, branch, "bad branch test");
24563 #if DEBUG_ROMCC_WARNINGS
24564 #warning "FIXME I have observed instructions between the test and branch instructions"
24566 ptr = RHS(branch, 0);
24567 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24568 if (ptr->op != OP_COPY) {
24569 internal_error(state, branch, "branch does not follow test");
24572 switch(branch->op) {
24573 case OP_JMP_EQ: bop = "jz"; break;
24574 case OP_JMP_NOTEQ: bop = "jnz"; break;
24575 case OP_JMP_SLESS: bop = "jl"; break;
24576 case OP_JMP_ULESS: bop = "jb"; break;
24577 case OP_JMP_SMORE: bop = "jg"; break;
24578 case OP_JMP_UMORE: bop = "ja"; break;
24579 case OP_JMP_SLESSEQ: bop = "jle"; break;
24580 case OP_JMP_ULESSEQ: bop = "jbe"; break;
24581 case OP_JMP_SMOREEQ: bop = "jge"; break;
24582 case OP_JMP_UMOREEQ: bop = "jae"; break;
24584 internal_error(state, branch, "Invalid branch op");
24590 if (branch->op == OP_CALL) {
24591 fprintf(fp, "\t/* call */\n");
24594 fprintf(fp, "\t%s L%s%lu\n",
24596 state->compiler->label_prefix,
24597 (unsigned long)(TARG(branch, 0)->u.cval));
24600 static void print_op_ret(struct compile_state *state,
24601 struct triple *branch, FILE *fp)
24603 fprintf(fp, "\tjmp *%s\n",
24604 reg(state, RHS(branch, 0), REGCM_GPR32));
24607 static void print_op_set(struct compile_state *state,
24608 struct triple *set, FILE *fp)
24610 const char *sop = "set";
24611 if (set->rhs != 1) {
24612 internal_error(state, set, "setcc without condition?");
24614 check_reg(state, RHS(set, 0), REGCM_FLAGS);
24615 if ((RHS(set, 0)->op != OP_CMP) &&
24616 (RHS(set, 0)->op != OP_TEST)) {
24617 internal_error(state, set, "bad set test");
24619 if (RHS(set, 0)->next != set) {
24620 internal_error(state, set, "set does not follow test");
24623 case OP_SET_EQ: sop = "setz"; break;
24624 case OP_SET_NOTEQ: sop = "setnz"; break;
24625 case OP_SET_SLESS: sop = "setl"; break;
24626 case OP_SET_ULESS: sop = "setb"; break;
24627 case OP_SET_SMORE: sop = "setg"; break;
24628 case OP_SET_UMORE: sop = "seta"; break;
24629 case OP_SET_SLESSEQ: sop = "setle"; break;
24630 case OP_SET_ULESSEQ: sop = "setbe"; break;
24631 case OP_SET_SMOREEQ: sop = "setge"; break;
24632 case OP_SET_UMOREEQ: sop = "setae"; break;
24634 internal_error(state, set, "Invalid set op");
24637 fprintf(fp, "\t%s %s\n",
24638 sop, reg(state, set, REGCM_GPR8_LO));
24641 static void print_op_bit_scan(struct compile_state *state,
24642 struct triple *ins, FILE *fp)
24646 case OP_BSF: op = "bsf"; break;
24647 case OP_BSR: op = "bsr"; break;
24649 internal_error(state, ins, "unknown bit scan");
24659 reg(state, RHS(ins, 0), REGCM_GPR32),
24660 reg(state, ins, REGCM_GPR32),
24661 reg(state, ins, REGCM_GPR32));
24665 static void print_sdecl(struct compile_state *state,
24666 struct triple *ins, FILE *fp)
24668 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24669 fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
24670 fprintf(fp, "L%s%lu:\n",
24671 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24672 print_const(state, MISC(ins, 0), fp);
24673 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24677 static void print_instruction(struct compile_state *state,
24678 struct triple *ins, FILE *fp)
24680 /* Assumption: after I have exted the register allocator
24681 * everything is in a valid register.
24685 print_op_asm(state, ins, fp);
24687 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
24688 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
24689 case OP_AND: print_binary_op(state, "and", ins, fp); break;
24690 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
24691 case OP_OR: print_binary_op(state, "or", ins, fp); break;
24692 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
24693 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
24694 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
24695 case OP_POS: break;
24696 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
24697 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24702 /* Don't generate anything here for constants */
24704 /* Don't generate anything for variable declarations. */
24706 case OP_UNKNOWNVAL:
24707 fprintf(fp, " /* unknown %s */\n",
24708 reg(state, ins, REGCM_ALL));
24711 print_sdecl(state, ins, fp);
24715 print_op_move(state, ins, fp);
24718 print_op_load(state, ins, fp);
24721 print_op_store(state, ins, fp);
24724 print_op_smul(state, ins, fp);
24726 case OP_CMP: print_op_cmp(state, ins, fp); break;
24727 case OP_TEST: print_op_test(state, ins, fp); break;
24729 case OP_JMP_EQ: case OP_JMP_NOTEQ:
24730 case OP_JMP_SLESS: case OP_JMP_ULESS:
24731 case OP_JMP_SMORE: case OP_JMP_UMORE:
24732 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24733 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24735 print_op_branch(state, ins, fp);
24738 print_op_ret(state, ins, fp);
24740 case OP_SET_EQ: case OP_SET_NOTEQ:
24741 case OP_SET_SLESS: case OP_SET_ULESS:
24742 case OP_SET_SMORE: case OP_SET_UMORE:
24743 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24744 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24745 print_op_set(state, ins, fp);
24747 case OP_INB: case OP_INW: case OP_INL:
24748 print_op_in(state, ins, fp);
24750 case OP_OUTB: case OP_OUTW: case OP_OUTL:
24751 print_op_out(state, ins, fp);
24755 print_op_bit_scan(state, ins, fp);
24758 after_lhs(state, ins);
24759 fprintf(fp, "\trdmsr\n");
24762 fprintf(fp, "\twrmsr\n");
24765 fprintf(fp, "\thlt\n");
24768 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24771 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24774 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24780 fprintf(fp, "L%s%lu:\n",
24781 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24784 /* Ignore adecls with no registers error otherwise */
24785 if (!noop_adecl(ins)) {
24786 internal_error(state, ins, "adecl remains?");
24789 /* Ignore OP_PIECE */
24792 /* Operations that should never get here */
24793 case OP_SDIV: case OP_UDIV:
24794 case OP_SMOD: case OP_UMOD:
24795 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
24796 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
24797 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24799 internal_error(state, ins, "unknown op: %d %s",
24800 ins->op, tops(ins->op));
24805 static void print_instructions(struct compile_state *state)
24807 struct triple *first, *ins;
24808 int print_location;
24809 struct occurance *last_occurance;
24811 int max_inline_depth;
24812 max_inline_depth = 0;
24813 print_location = 1;
24814 last_occurance = 0;
24815 fp = state->output;
24816 /* Masks for common sizes */
24817 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24818 fprintf(fp, ".balign 16\n");
24819 fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24820 fprintf(fp, ".int 0xff, 0, 0, 0\n");
24821 fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24822 fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24823 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24824 first = state->first;
24827 if (print_location &&
24828 last_occurance != ins->occurance) {
24829 if (!ins->occurance->parent) {
24830 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24831 ins->occurance->function?ins->occurance->function:"(null)",
24832 ins->occurance->filename?ins->occurance->filename:"(null)",
24833 ins->occurance->line,
24834 ins->occurance->col);
24837 struct occurance *ptr;
24839 fprintf(fp, "\t/*\n");
24841 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24843 fprintf(fp, "\t * %s,%s:%d.%d\n",
24849 fprintf(fp, "\t */\n");
24850 if (inline_depth > max_inline_depth) {
24851 max_inline_depth = inline_depth;
24854 if (last_occurance) {
24855 put_occurance(last_occurance);
24857 get_occurance(ins->occurance);
24858 last_occurance = ins->occurance;
24861 print_instruction(state, ins, fp);
24863 } while(ins != first);
24864 if (print_location) {
24865 fprintf(fp, "/* max inline depth %d */\n",
24870 static void generate_code(struct compile_state *state)
24872 generate_local_labels(state);
24873 print_instructions(state);
24877 static void print_preprocessed_tokens(struct compile_state *state)
24882 const char *filename;
24883 fp = state->output;
24887 struct file_state *file;
24889 const char *token_str;
24891 if (tok == TOK_EOF) {
24894 tk = eat(state, tok);
24896 tk->ident ? tk->ident->name :
24897 tk->str_len ? tk->val.str :
24900 file = state->file;
24901 while(file->macro && file->prev) {
24904 if (!file->macro &&
24905 ((file->line != line) || (file->basename != filename)))
24908 if ((file->basename == filename) &&
24909 (line < file->line)) {
24910 while(line < file->line) {
24916 fprintf(fp, "\n#line %d \"%s\"\n",
24917 file->line, file->basename);
24920 filename = file->basename;
24921 col = get_col(file) - strlen(token_str);
24922 for(i = 0; i < col; i++) {
24927 fprintf(fp, "%s ", token_str);
24929 if (state->compiler->debug & DEBUG_TOKENS) {
24930 loc(state->dbgout, state, 0);
24931 fprintf(state->dbgout, "%s <- `%s'\n",
24932 tokens[tok], token_str);
24937 static void compile(const char *filename,
24938 struct compiler_state *compiler, struct arch_state *arch)
24941 struct compile_state state;
24942 struct triple *ptr;
24943 struct filelist *includes = include_filelist;
24944 memset(&state, 0, sizeof(state));
24945 state.compiler = compiler;
24948 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24949 memset(&state.token[i], 0, sizeof(state.token[i]));
24950 state.token[i].tok = -1;
24952 /* Remember the output descriptors */
24953 state.errout = stderr;
24954 state.dbgout = stdout;
24955 /* Remember the output filename */
24956 if ((state.compiler->flags & COMPILER_PP_ONLY) && (strcmp("auto.inc",state.compiler->ofilename) == 0)) {
24957 state.output = stdout;
24959 state.output = fopen(state.compiler->ofilename, "w");
24960 if (!state.output) {
24961 error(&state, 0, "Cannot open output file %s\n",
24962 state.compiler->ofilename);
24965 /* Make certain a good cleanup happens */
24966 exit_state = &state;
24967 atexit(exit_cleanup);
24969 /* Prep the preprocessor */
24970 state.if_depth = 0;
24971 memset(state.if_bytes, 0, sizeof(state.if_bytes));
24972 /* register the C keywords */
24973 register_keywords(&state);
24974 /* register the keywords the macro preprocessor knows */
24975 register_macro_keywords(&state);
24976 /* generate some builtin macros */
24977 register_builtin_macros(&state);
24978 /* Memorize where some special keywords are. */
24979 state.i_switch = lookup(&state, "switch", 6);
24980 state.i_case = lookup(&state, "case", 4);
24981 state.i_continue = lookup(&state, "continue", 8);
24982 state.i_break = lookup(&state, "break", 5);
24983 state.i_default = lookup(&state, "default", 7);
24984 state.i_return = lookup(&state, "return", 6);
24985 /* Memorize where predefined macros are. */
24986 state.i___VA_ARGS__ = lookup(&state, "__VA_ARGS__", 11);
24987 state.i___FILE__ = lookup(&state, "__FILE__", 8);
24988 state.i___LINE__ = lookup(&state, "__LINE__", 8);
24989 /* Memorize where predefined identifiers are. */
24990 state.i___func__ = lookup(&state, "__func__", 8);
24991 /* Memorize where some attribute keywords are. */
24992 state.i_noinline = lookup(&state, "noinline", 8);
24993 state.i_always_inline = lookup(&state, "always_inline", 13);
24994 state.i_noreturn = lookup(&state, "noreturn", 8);
24996 /* Process the command line macros */
24997 process_cmdline_macros(&state);
24999 /* Allocate beginning bounding labels for the function list */
25000 state.first = label(&state);
25001 state.first->id |= TRIPLE_FLAG_VOLATILE;
25002 use_triple(state.first, state.first);
25003 ptr = label(&state);
25004 ptr->id |= TRIPLE_FLAG_VOLATILE;
25005 use_triple(ptr, ptr);
25006 flatten(&state, state.first, ptr);
25008 /* Allocate a label for the pool of global variables */
25009 state.global_pool = label(&state);
25010 state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
25011 flatten(&state, state.first, state.global_pool);
25013 /* Enter the globl definition scope */
25014 start_scope(&state);
25015 register_builtins(&state);
25017 compile_file(&state, filename, 1);
25020 compile_file(&state, includes->filename, 1);
25021 includes=includes->next;
25024 /* Stop if all we want is preprocessor output */
25025 if (state.compiler->flags & COMPILER_PP_ONLY) {
25026 print_preprocessed_tokens(&state);
25032 /* Exit the global definition scope */
25035 /* Now that basic compilation has happened
25036 * optimize the intermediate code
25040 generate_code(&state);
25041 if (state.compiler->debug) {
25042 fprintf(state.errout, "done\n");
25047 static void version(FILE *fp)
25049 fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
25052 static void usage(void)
25057 "\nUsage: romcc [options] <source>.c\n"
25058 "Compile a C source file generating a binary that does not implicilty use RAM\n"
25060 "-o <output file name>\n"
25061 "-f<option> Specify a generic compiler option\n"
25062 "-m<option> Specify a arch dependent option\n"
25063 "-- Specify this is the last option\n"
25064 "\nGeneric compiler options:\n"
25066 compiler_usage(fp);
25068 "\nArchitecture compiler options:\n"
25076 static void arg_error(char *fmt, ...)
25079 va_start(args, fmt);
25080 vfprintf(stderr, fmt, args);
25086 int main(int argc, char **argv)
25088 const char *filename;
25089 struct compiler_state compiler;
25090 struct arch_state arch;
25094 /* I don't want any surprises */
25095 setlocale(LC_ALL, "C");
25097 init_compiler_state(&compiler);
25098 init_arch_state(&arch);
25102 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
25103 compiler.ofilename = argv[2];
25107 else if (!all_opts && argv[1][0] == '-') {
25110 if (strcmp(argv[1], "--") == 0) {
25114 else if (strncmp(argv[1], "-E", 2) == 0) {
25115 result = compiler_encode_flag(&compiler, argv[1]);
25117 else if (strncmp(argv[1], "-O", 2) == 0) {
25118 result = compiler_encode_flag(&compiler, argv[1]);
25120 else if (strncmp(argv[1], "-I", 2) == 0) {
25121 result = compiler_encode_flag(&compiler, argv[1]);
25123 else if (strncmp(argv[1], "-D", 2) == 0) {
25124 result = compiler_encode_flag(&compiler, argv[1]);
25126 else if (strncmp(argv[1], "-U", 2) == 0) {
25127 result = compiler_encode_flag(&compiler, argv[1]);
25129 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25130 result = compiler_encode_flag(&compiler, argv[1]+2);
25132 else if (strncmp(argv[1], "-f", 2) == 0) {
25133 result = compiler_encode_flag(&compiler, argv[1]+2);
25135 else if (strncmp(argv[1], "-m", 2) == 0) {
25136 result = arch_encode_flag(&arch, argv[1]+2);
25138 else if (strncmp(argv[1], "-c", 2) == 0) {
25141 else if (strncmp(argv[1], "-S", 2) == 0) {
25144 else if (strncmp(argv[1], "-include", 10) == 0) {
25145 struct filelist *old_head = include_filelist;
25146 include_filelist = malloc(sizeof(struct filelist));
25147 if (!include_filelist) {
25148 die("Out of memory.\n");
25152 include_filelist->filename = strdup(argv[1]);
25153 include_filelist->next = old_head;
25157 arg_error("Invalid option specified: %s\n",
25165 arg_error("Only one filename may be specified\n");
25167 filename = argv[1];
25173 arg_error("No filename specified\n");
25175 compile(filename, &compiler, &arch);