5 #define VERSION_MAJOR "0"
6 #define VERSION_MINOR "63"
7 #define RELEASE_DATE "28 May 2004"
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 #define DEBUG_CONSISTENCY 1
29 #define DEBUG_SDP_BLOCKS 0
30 #define DEBUG_TRIPLE_COLOR 0
32 #define DEBUG_DISPLAY_USES 1
33 #define DEBUG_DISPLAY_TYPES 1
34 #define DEBUG_REPLACE_CLOSURE_TYPE_HIRES 0
35 #define DEBUG_DECOMPOSE_PRINT_TUPLES 0
36 #define DEBUG_DECOMPOSE_HIRES 0
37 #define DEBUG_INITIALIZER 0
38 #define DEBUG_UPDATE_CLOSURE_TYPE 0
39 #define DEBUG_LOCAL_TRIPLE 0
40 #define DEBUG_BASIC_BLOCKS_VERBOSE 0
41 #define DEBUG_CPS_RENAME_VARIABLES_HIRES 0
42 #define DEBUG_SIMPLIFY_HIRES 0
43 #define DEBUG_SHRINKING 0
44 #define DEBUG_COALESCE_HITCHES 0
45 #define DEBUG_CODE_ELIMINATION 0
47 #define DEBUG_EXPLICIT_CLOSURES 0
49 #warning "FIXME give clear error messages about unused variables"
50 #warning "FIXME properly handle multi dimensional arrays"
51 #warning "FIXME handle multiple register sizes"
53 /* Control flow graph of a loop without goto.
64 * |\ GGG HHH | continue;
92 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
93 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
96 * [] == DFlocal(X) U DF(X)
99 * Dominator graph of the same nodes.
103 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
105 * CCC CCC: [ ] ( BBB, JJJ )
107 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
109 * FFF FFF: [ ] ( BBB )
111 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
113 * III III: [ BBB ] ()
116 * BBB and JJJ are definitely the dominance frontier.
117 * Where do I place phi functions and how do I make that decision.
120 static void die(char *fmt, ...)
125 vfprintf(stderr, fmt, args);
132 static void *xmalloc(size_t size, const char *name)
137 die("Cannot malloc %ld bytes to hold %s: %s\n",
138 size + 0UL, name, strerror(errno));
143 static void *xcmalloc(size_t size, const char *name)
146 buf = xmalloc(size, name);
147 memset(buf, 0, size);
151 static void *xrealloc(void *ptr, size_t size, const char *name)
154 buf = realloc(ptr, size);
156 die("Cannot realloc %ld bytes to hold %s: %s\n",
157 size + 0UL, name, strerror(errno));
162 static void xfree(const void *ptr)
167 static char *xstrdup(const char *str)
172 new = xmalloc(len + 1, "xstrdup string");
173 memcpy(new, str, len);
178 static void xchdir(const char *path)
180 if (chdir(path) != 0) {
181 die("chdir to `%s' failed: %s\n",
182 path, strerror(errno));
186 static int exists(const char *dirname, const char *filename)
188 char cwd[MAX_CWD_SIZE];
191 if (getcwd(cwd, sizeof(cwd)) == 0) {
192 die("cwd buffer to small");
196 if (chdir(dirname) != 0) {
199 if (does_exist && (access(filename, O_RDONLY) < 0)) {
200 if ((errno != EACCES) && (errno != EROFS)) {
209 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
211 char cwd[MAX_CWD_SIZE];
214 off_t size, progress;
222 if (getcwd(cwd, sizeof(cwd)) == 0) {
223 die("cwd buffer to small");
226 fd = open(filename, O_RDONLY);
229 die("Cannot open '%s' : %s\n",
230 filename, strerror(errno));
232 result = fstat(fd, &stats);
234 die("Cannot stat: %s: %s\n",
235 filename, strerror(errno));
237 size = stats.st_size;
239 buf = xmalloc(size +2, filename);
240 buf[size] = '\n'; /* Make certain the file is newline terminated */
241 buf[size+1] = '\0'; /* Null terminate the file for good measure */
243 while(progress < size) {
244 result = read(fd, buf + progress, size - progress);
246 if ((errno == EINTR) || (errno == EAGAIN))
248 die("read on %s of %ld bytes failed: %s\n",
249 filename, (size - progress)+ 0UL, strerror(errno));
255 die("Close of %s failed: %s\n",
256 filename, strerror(errno));
261 /* Types on the destination platform */
262 #warning "FIXME this assumes 32bit x86 is the destination"
263 typedef int8_t schar_t;
264 typedef uint8_t uchar_t;
265 typedef int8_t char_t;
266 typedef int16_t short_t;
267 typedef uint16_t ushort_t;
268 typedef int32_t int_t;
269 typedef uint32_t uint_t;
270 typedef int32_t long_t;
271 typedef uint32_t ulong_t;
273 #define SCHAR_T_MIN (-128)
274 #define SCHAR_T_MAX 127
275 #define UCHAR_T_MAX 255
276 #define CHAR_T_MIN SCHAR_T_MIN
277 #define CHAR_T_MAX SCHAR_T_MAX
278 #define SHRT_T_MIN (-32768)
279 #define SHRT_T_MAX 32767
280 #define USHRT_T_MAX 65535
281 #define INT_T_MIN (-LONG_T_MAX - 1)
282 #define INT_T_MAX 2147483647
283 #define UINT_T_MAX 4294967295U
284 #define LONG_T_MIN (-LONG_T_MAX - 1)
285 #define LONG_T_MAX 2147483647
286 #define ULONG_T_MAX 4294967295U
289 #define SIZEOF_I16 16
290 #define SIZEOF_I32 32
291 #define SIZEOF_I64 64
293 #define SIZEOF_CHAR 8
294 #define SIZEOF_SHORT 16
295 #define SIZEOF_INT 32
296 #define SIZEOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
299 #define ALIGNOF_CHAR 8
300 #define ALIGNOF_SHORT 16
301 #define ALIGNOF_INT 32
302 #define ALIGNOF_LONG (sizeof(long_t)*SIZEOF_CHAR)
304 #define REG_SIZEOF_REG 32
305 #define REG_SIZEOF_CHAR REG_SIZEOF_REG
306 #define REG_SIZEOF_SHORT REG_SIZEOF_REG
307 #define REG_SIZEOF_INT REG_SIZEOF_REG
308 #define REG_SIZEOF_LONG REG_SIZEOF_REG
310 #define REG_ALIGNOF_REG REG_SIZEOF_REG
311 #define REG_ALIGNOF_CHAR REG_SIZEOF_REG
312 #define REG_ALIGNOF_SHORT REG_SIZEOF_REG
313 #define REG_ALIGNOF_INT REG_SIZEOF_REG
314 #define REG_ALIGNOF_LONG REG_SIZEOF_REG
316 /* Additional definitions for clarity.
317 * I currently assume a long is the largest native
318 * machine word and that a pointer fits into it.
320 #define SIZEOF_WORD SIZEOF_LONG
321 #define SIZEOF_POINTER SIZEOF_LONG
322 #define ALIGNOF_WORD ALIGNOF_LONG
323 #define ALIGNOF_POINTER ALIGNOF_LONG
324 #define REG_SIZEOF_POINTER REG_SIZEOF_LONG
325 #define REG_ALIGNOF_POINTER REG_ALIGNOF_LONG
328 struct file_state *prev;
329 const char *basename;
335 const char *line_start;
337 const char *report_name;
338 const char *report_dir;
343 struct hash_entry *ident;
352 /* I have two classes of types:
354 * Logical types. (The type the C standard says the operation is of)
356 * The operational types are:
371 * No memory is useable by the compiler.
372 * There is no floating point support.
373 * All operations take place in general purpose registers.
374 * There is one type of general purpose register.
375 * Unsigned longs are stored in that general purpose register.
378 /* Operations on general purpose registers.
397 #define OP_POS 16 /* Dummy positive operator don't use it */
407 #define OP_SLESSEQ 26
408 #define OP_ULESSEQ 27
409 #define OP_SMOREEQ 28
410 #define OP_UMOREEQ 29
412 #define OP_LFALSE 30 /* Test if the expression is logically false */
413 #define OP_LTRUE 31 /* Test if the expression is logcially true */
417 /* For OP_STORE ->type holds the type
418 * RHS(0) holds the destination address
419 * RHS(1) holds the value to store.
422 #define OP_UEXTRACT 34
423 /* OP_UEXTRACT extracts an unsigned bitfield from a pseudo register
424 * RHS(0) holds the psuedo register to extract from
425 * ->type holds the size of the bitfield.
426 * ->u.bitfield.size holds the size of the bitfield.
427 * ->u.bitfield.offset holds the offset to extract from
429 #define OP_SEXTRACT 35
430 /* OP_SEXTRACT extracts a signed bitfield from a pseudo register
431 * RHS(0) holds the psuedo register to extract from
432 * ->type holds the size of the bitfield.
433 * ->u.bitfield.size holds the size of the bitfield.
434 * ->u.bitfield.offset holds the offset to extract from
436 #define OP_DEPOSIT 36
437 /* OP_DEPOSIT replaces a bitfield with a new value.
438 * RHS(0) holds the value to replace a bitifield in.
439 * RHS(1) holds the replacement value
440 * ->u.bitfield.size holds the size of the bitfield.
441 * ->u.bitfield.offset holds the deposit into
446 #define OP_MIN_CONST 50
447 #define OP_MAX_CONST 58
448 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
449 #define OP_INTCONST 50
450 /* For OP_INTCONST ->type holds the type.
451 * ->u.cval holds the constant value.
453 #define OP_BLOBCONST 51
454 /* For OP_BLOBCONST ->type holds the layout and size
455 * information. u.blob holds a pointer to the raw binary
456 * data for the constant initializer.
458 #define OP_ADDRCONST 52
459 /* For OP_ADDRCONST ->type holds the type.
460 * MISC(0) holds the reference to the static variable.
461 * ->u.cval holds an offset from that value.
463 #define OP_UNKNOWNVAL 59
464 /* For OP_UNKNOWNAL ->type holds the type.
465 * For some reason we don't know what value this type has.
466 * This allows for variables that have don't have values
467 * assigned yet, or variables whose value we simply do not know.
471 /* OP_WRITE moves one pseudo register to another.
472 * MISC(0) holds the destination pseudo register, which must be an OP_DECL.
473 * RHS(0) holds the psuedo to move.
477 /* OP_READ reads the value of a variable and makes
478 * it available for the pseudo operation.
479 * Useful for things like def-use chains.
480 * RHS(0) holds points to the triple to read from.
483 /* OP_COPY makes a copy of the pseudo register or constant in RHS(0).
485 #define OP_CONVERT 63
486 /* OP_CONVERT makes a copy of the pseudo register or constant in RHS(0).
487 * And then the type is converted appropriately.
490 /* OP_PIECE returns one piece of a instruction that returns a structure.
491 * MISC(0) is the instruction
492 * u.cval is the LHS piece of the instruction to return.
495 /* OP_ASM holds a sequence of assembly instructions, the result
496 * of a C asm directive.
497 * RHS(x) holds input value x to the assembly sequence.
498 * LHS(x) holds the output value x from the assembly sequence.
499 * u.blob holds the string of assembly instructions.
503 /* OP_DEREF generates an lvalue from a pointer.
504 * RHS(0) holds the pointer value.
505 * OP_DEREF serves as a place holder to indicate all necessary
506 * checks have been done to indicate a value is an lvalue.
509 /* OP_DOT references a submember of a structure lvalue.
510 * MISC(0) holds the lvalue.
511 * ->u.field holds the name of the field we want.
513 * Not seen after structures are flattened.
516 /* OP_INDEX references a submember of a tuple or array lvalue.
517 * MISC(0) holds the lvalue.
518 * ->u.cval holds the index into the lvalue.
520 * Not seen after structures are flattened.
523 /* OP_VAL returns the value of a subexpression of the current expression.
524 * Useful for operators that have side effects.
525 * RHS(0) holds the expression.
526 * MISC(0) holds the subexpression of RHS(0) that is the
527 * value of the expression.
529 * Not seen outside of expressions.
533 /* OP_TUPLE is an array of triples that are either variable
534 * or values for a structure or an array. It is used as
535 * a place holder when flattening compound types.
536 * The value represented by an OP_TUPLE is held in N registers.
537 * LHS(0..N-1) refer to those registers.
538 * ->use is a list of statements that use the value.
540 * Although OP_TUPLE always has register sized pieces they are not
541 * used until structures are flattened/decomposed into their register
543 * ???? registers ????
547 /* OP_BITREF describes a bitfield as an lvalue.
548 * RHS(0) holds the register value.
549 * ->type holds the type of the bitfield.
550 * ->u.bitfield.size holds the size of the bitfield.
551 * ->u.bitfield.offset holds the offset of the bitfield in the register
556 /* OP_FCALL performs a procedure call.
557 * MISC(0) holds a pointer to the OP_LIST of a function
558 * RHS(x) holds argument x of a function
560 * Currently not seen outside of expressions.
563 /* OP_PROG is an expression that holds a list of statements, or
564 * expressions. The final expression is the value of the expression.
565 * RHS(0) holds the start of the list.
570 /* OP_LIST Holds a list of statements that compose a function, and a result value.
571 * RHS(0) holds the list of statements.
572 * A list of all functions is maintained.
575 #define OP_BRANCH 81 /* an unconditional branch */
576 /* For branch instructions
577 * TARG(0) holds the branch target.
578 * ->next holds where to branch to if the branch is not taken.
579 * The branch target can only be a label
582 #define OP_CBRANCH 82 /* a conditional branch */
583 /* For conditional branch instructions
584 * RHS(0) holds the branch condition.
585 * TARG(1) holds the branch target.
586 * ->next holds where to branch to if the branch is not taken.
587 * The branch target can only be a label
590 #define OP_CALL 83 /* an uncontional branch that will return */
591 /* For call instructions
592 * MISC(0) holds the OP_RET that returns from the branch
593 * TARG(0) holds the branch target.
594 * ->next holds where to branch to if the branch is not taken.
595 * The branch target can only be a label
598 #define OP_RET 84 /* an uncontinonal branch through a variable back to an OP_CALL */
599 /* For call instructions
600 * RHS(0) holds the variable with the return address
601 * The branch target can only be a label
605 /* OP_LABEL is a triple that establishes an target for branches.
606 * ->use is the list of all branches that use this label.
610 /* OP_ADECL is a triple that establishes an lvalue for assignments.
611 * A variable takes N registers to contain.
612 * LHS(0..N-1) refer to an OP_PIECE triple that represents
613 * the Xth register that the variable is stored in.
614 * ->use is a list of statements that use the variable.
616 * Although OP_ADECL always has register sized pieces they are not
617 * used until structures are flattened/decomposed into their register
622 /* OP_SDECL is a triple that establishes a variable of static
624 * ->use is a list of statements that use the variable.
625 * MISC(0) holds the initializer expression.
630 /* OP_PHI is a triple used in SSA form code.
631 * It is used when multiple code paths merge and a variable needs
632 * a single assignment from any of those code paths.
633 * The operation is a cross between OP_DECL and OP_WRITE, which
634 * is what OP_PHI is generated from.
636 * RHS(x) points to the value from code path x
637 * The number of RHS entries is the number of control paths into the block
638 * in which OP_PHI resides. The elements of the array point to point
639 * to the variables OP_PHI is derived from.
641 * MISC(0) holds a pointer to the orginal OP_DECL node.
645 /* continuation helpers
647 #define OP_CPS_BRANCH 90 /* an unconditional branch */
648 /* OP_CPS_BRANCH calls a continuation
649 * RHS(x) holds argument x of the function
650 * TARG(0) holds OP_CPS_START target
652 #define OP_CPS_CBRANCH 91 /* a conditional branch */
653 /* OP_CPS_CBRANCH conditionally calls one of two continuations
654 * RHS(0) holds the branch condition
655 * RHS(x + 1) holds argument x of the function
656 * TARG(0) holds the OP_CPS_START to jump to when true
657 * ->next holds the OP_CPS_START to jump to when false
659 #define OP_CPS_CALL 92 /* an uncontional branch that will return */
660 /* For OP_CPS_CALL instructions
661 * RHS(x) holds argument x of the function
662 * MISC(0) holds the OP_CPS_RET that returns from the branch
663 * TARG(0) holds the branch target.
664 * ->next holds where the OP_CPS_RET will return to.
666 #define OP_CPS_RET 93
667 /* OP_CPS_RET conditionally calls one of two continuations
668 * RHS(0) holds the variable with the return function address
669 * RHS(x + 1) holds argument x of the function
670 * The branch target may be any OP_CPS_START
672 #define OP_CPS_END 94
673 /* OP_CPS_END is the triple at the end of the program.
674 * For most practical purposes it is a branch.
676 #define OP_CPS_START 95
677 /* OP_CPS_START is a triple at the start of a continuation
678 * The arguments variables takes N registers to contain.
679 * LHS(0..N-1) refer to an OP_PIECE triple that represents
680 * the Xth register that the arguments are stored in.
684 /* Architecture specific instructions */
687 #define OP_SET_EQ 102
688 #define OP_SET_NOTEQ 103
689 #define OP_SET_SLESS 104
690 #define OP_SET_ULESS 105
691 #define OP_SET_SMORE 106
692 #define OP_SET_UMORE 107
693 #define OP_SET_SLESSEQ 108
694 #define OP_SET_ULESSEQ 109
695 #define OP_SET_SMOREEQ 110
696 #define OP_SET_UMOREEQ 111
699 #define OP_JMP_EQ 113
700 #define OP_JMP_NOTEQ 114
701 #define OP_JMP_SLESS 115
702 #define OP_JMP_ULESS 116
703 #define OP_JMP_SMORE 117
704 #define OP_JMP_UMORE 118
705 #define OP_JMP_SLESSEQ 119
706 #define OP_JMP_ULESSEQ 120
707 #define OP_JMP_SMOREEQ 121
708 #define OP_JMP_UMOREEQ 122
710 /* Builtin operators that it is just simpler to use the compiler for */
726 #define PURE 0x001 /* Triple has no side effects */
727 #define IMPURE 0x002 /* Triple has side effects */
728 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
729 #define DEF 0x004 /* Triple is a variable definition */
730 #define BLOCK 0x008 /* Triple stores the current block */
731 #define STRUCTURAL 0x010 /* Triple does not generate a machine instruction */
732 #define BRANCH_BITS(FLAGS) ((FLAGS) & 0xe0 )
733 #define UBRANCH 0x020 /* Triple is an unconditional branch instruction */
734 #define CBRANCH 0x040 /* Triple is a conditional branch instruction */
735 #define RETBRANCH 0x060 /* Triple is a return instruction */
736 #define CALLBRANCH 0x080 /* Triple is a call instruction */
737 #define ENDBRANCH 0x0a0 /* Triple is an end instruction */
738 #define PART 0x100 /* Triple is really part of another triple */
739 #define BITFIELD 0x200 /* Triple manipulates a bitfield */
740 signed char lhs, rhs, misc, targ;
743 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
751 static const struct op_info table_ops[] = {
752 [OP_SDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "sdivt"),
753 [OP_UDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "udivt"),
754 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
755 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
756 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
757 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
758 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
759 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
760 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
761 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
762 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
763 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
764 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
765 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
766 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
767 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
768 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
769 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
770 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
772 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
773 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
774 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
775 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
776 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
777 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
778 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
779 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
780 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
781 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
782 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
783 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
785 [OP_LOAD ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "load"),
786 [OP_STORE ] = OP( 0, 2, 0, 0, PURE | BLOCK , "store"),
788 [OP_UEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "uextract"),
789 [OP_SEXTRACT ] = OP( 0, 1, 0, 0, PURE | DEF | BITFIELD, "sextract"),
790 [OP_DEPOSIT ] = OP( 0, 2, 0, 0, PURE | DEF | BITFIELD, "deposit"),
792 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "noop"),
794 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
795 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE , "blobconst"),
796 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
797 [OP_UNKNOWNVAL ] = OP( 0, 0, 0, 0, PURE | DEF, "unknown"),
799 #warning "FIXME is it correct for OP_WRITE to be a def? I currently use it as one..."
800 [OP_WRITE ] = OP( 0, 1, 1, 0, PURE | DEF | BLOCK, "write"),
801 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
802 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
803 [OP_CONVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "convert"),
804 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF | STRUCTURAL | PART, "piece"),
805 [OP_ASM ] = OP(-1, -1, 0, 0, PURE, "asm"),
806 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
807 [OP_DOT ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "dot"),
808 [OP_INDEX ] = OP( 0, 0, 1, 0, PURE | DEF | PART, "index"),
810 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
811 [OP_TUPLE ] = OP(-1, 0, 0, 0, 0 | PURE | BLOCK | STRUCTURAL, "tuple"),
812 [OP_BITREF ] = OP( 0, 1, 0, 0, 0 | DEF | PURE | STRUCTURAL | BITFIELD, "bitref"),
813 /* Call is special most it can stand in for anything so it depends on context */
814 [OP_FCALL ] = OP( 0, -1, 1, 0, 0 | BLOCK | CALLBRANCH, "fcall"),
815 [OP_PROG ] = OP( 0, 1, 0, 0, 0 | IMPURE | BLOCK | STRUCTURAL, "prog"),
816 /* The sizes of OP_FCALL depends upon context */
818 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF | STRUCTURAL, "list"),
819 [OP_BRANCH ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "branch"),
820 [OP_CBRANCH ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "cbranch"),
821 [OP_CALL ] = OP( 0, 0, 1, 1, PURE | BLOCK | CALLBRANCH, "call"),
822 [OP_RET ] = OP( 0, 1, 0, 0, PURE | BLOCK | RETBRANCH, "ret"),
823 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "label"),
824 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "adecl"),
825 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK | STRUCTURAL, "sdecl"),
826 /* The number of RHS elements of OP_PHI depend upon context */
827 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
830 [OP_CPS_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK | UBRANCH, "cps_branch"),
831 [OP_CPS_CBRANCH] = OP( 0, -1, 0, 1, PURE | BLOCK | CBRANCH, "cps_cbranch"),
832 [OP_CPS_CALL ] = OP( 0, -1, 1, 1, PURE | BLOCK | CALLBRANCH, "cps_call"),
833 [OP_CPS_RET ] = OP( 0, -1, 0, 0, PURE | BLOCK | RETBRANCH, "cps_ret"),
834 [OP_CPS_END ] = OP( 0, -1, 0, 0, IMPURE | BLOCK | ENDBRANCH, "cps_end"),
835 [OP_CPS_START ] = OP( -1, 0, 0, 0, PURE | BLOCK | STRUCTURAL, "cps_start"),
838 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
839 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
840 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
841 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
842 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
843 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
844 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
845 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
846 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
847 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
848 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
849 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
850 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK | UBRANCH, "jmp"),
851 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_eq"),
852 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_noteq"),
853 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_sless"),
854 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_uless"),
855 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smore"),
856 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umore"),
857 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_slesseq"),
858 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_ulesseq"),
859 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smoreq"),
860 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umoreq"),
862 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
863 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
864 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
865 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
866 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
867 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
868 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
869 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
870 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
871 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
872 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
875 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
877 static const char *tops(int index)
879 static const char unknown[] = "unknown op";
883 if (index > OP_MAX) {
886 return table_ops[index].name;
893 struct triple_set *next;
894 struct triple *member;
904 const char *filename;
905 const char *function;
908 struct occurance *parent;
915 struct triple *next, *prev;
916 struct triple_set *use;
919 unsigned int template_id : 7;
920 unsigned int lhs : 6;
921 unsigned int rhs : 7;
922 unsigned int misc : 2;
923 unsigned int targ : 1;
924 #define TRIPLE_SIZE(TRIPLE) \
925 ((TRIPLE)->lhs + (TRIPLE)->rhs + (TRIPLE)->misc + (TRIPLE)->targ)
926 #define TRIPLE_LHS_OFF(PTR) (0)
927 #define TRIPLE_RHS_OFF(PTR) (TRIPLE_LHS_OFF(PTR) + (PTR)->lhs)
928 #define TRIPLE_MISC_OFF(PTR) (TRIPLE_RHS_OFF(PTR) + (PTR)->rhs)
929 #define TRIPLE_TARG_OFF(PTR) (TRIPLE_MISC_OFF(PTR) + (PTR)->misc)
930 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF(PTR) + (INDEX)])
931 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF(PTR) + (INDEX)])
932 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF(PTR) + (INDEX)])
933 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF(PTR) + (INDEX)])
934 unsigned id; /* A scratch value and finally the register */
935 #define TRIPLE_FLAG_FLATTENED (1 << 31)
936 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
937 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
938 #define TRIPLE_FLAG_VOLATILE (1 << 28)
939 #define TRIPLE_FLAG_INLINE (1 << 27) /* ???? */
940 #define TRIPLE_FLAG_LOCAL (1 << 26)
942 #define TRIPLE_FLAG_COPY TRIPLE_FLAG_VOLATILE
943 struct occurance *occurance;
946 struct bitfield bitfield;
949 struct hash_entry *field;
950 struct asm_info *ainfo;
952 struct symbol *symbol;
954 struct triple *param[2];
961 struct ins_template {
962 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
966 struct ins_template tmpl;
971 struct block_set *next;
972 struct block *member;
975 struct block *work_next;
976 struct triple *first, *last;
978 struct block_set *edges;
980 struct block_set *use;
981 struct block_set *idominates;
982 struct block_set *domfrontier;
984 struct block_set *ipdominates;
985 struct block_set *ipdomfrontier;
993 struct hash_entry *ident;
1000 struct macro_arg *next;
1001 struct hash_entry *ident;
1004 struct hash_entry *ident;
1008 struct macro_arg *args;
1013 struct hash_entry *next;
1017 struct macro *sym_define;
1018 struct symbol *sym_label;
1019 struct symbol *sym_tag;
1020 struct symbol *sym_ident;
1023 #define HASH_TABLE_SIZE 2048
1025 struct compiler_state {
1026 const char *label_prefix;
1027 const char *ofilename;
1028 unsigned long flags;
1029 unsigned long debug;
1030 unsigned long max_allocation_passes;
1032 size_t include_path_count;
1033 const char **include_paths;
1035 size_t define_count;
1036 const char **defines;
1039 const char **undefs;
1042 unsigned long features;
1044 struct basic_blocks {
1045 struct triple *func;
1046 struct triple *first;
1047 struct block *first_block, *last_block;
1050 #define MAX_CPP_IF_DEPTH 63
1051 struct compile_state {
1052 struct compiler_state *compiler;
1053 struct arch_state *arch;
1057 struct file_state *file;
1058 struct occurance *last_occurance;
1059 const char *function;
1060 struct token token[4];
1061 struct hash_entry *hash_table[HASH_TABLE_SIZE];
1062 struct hash_entry *i_switch;
1063 struct hash_entry *i_case;
1064 struct hash_entry *i_continue;
1065 struct hash_entry *i_break;
1066 struct hash_entry *i_default;
1067 struct hash_entry *i_return;
1068 /* Additional hash entries for predefined macros */
1069 struct hash_entry *i_defined;
1070 struct hash_entry *i___VA_ARGS__;
1071 struct hash_entry *i___FILE__;
1072 struct hash_entry *i___LINE__;
1073 /* Additional hash entries for predefined identifiers */
1074 struct hash_entry *i___func__;
1075 /* Additional hash entries for attributes */
1076 struct hash_entry *i_noinline;
1077 struct hash_entry *i_always_inline;
1079 unsigned char if_bytes[(MAX_CPP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1081 int eat_depth, eat_targ;
1083 struct file_state *macro_file;
1084 struct triple *functions;
1085 struct triple *main_function;
1086 struct triple *first;
1087 struct triple *global_pool;
1088 struct basic_blocks bb;
1089 int functions_joined;
1092 /* visibility global/local */
1093 /* static/auto duration */
1094 /* typedef, register, inline */
1095 #define STOR_SHIFT 0
1096 #define STOR_MASK 0x001f
1098 #define STOR_GLOBAL 0x0001
1100 #define STOR_PERM 0x0002
1101 /* Definition locality */
1102 #define STOR_NONLOCAL 0x0004 /* The definition is not in this translation unit */
1103 /* Storage specifiers */
1104 #define STOR_AUTO 0x0000
1105 #define STOR_STATIC 0x0002
1106 #define STOR_LOCAL 0x0003
1107 #define STOR_EXTERN 0x0007
1108 #define STOR_INLINE 0x0008
1109 #define STOR_REGISTER 0x0010
1110 #define STOR_TYPEDEF 0x0018
1112 #define QUAL_SHIFT 5
1113 #define QUAL_MASK 0x00e0
1114 #define QUAL_NONE 0x0000
1115 #define QUAL_CONST 0x0020
1116 #define QUAL_VOLATILE 0x0040
1117 #define QUAL_RESTRICT 0x0080
1119 #define TYPE_SHIFT 8
1120 #define TYPE_MASK 0x1f00
1121 #define TYPE_INTEGER(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1122 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1123 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
1124 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
1125 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1126 #define TYPE_RANK(TYPE) ((TYPE) & ~0xF1FF)
1127 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1128 #define TYPE_DEFAULT 0x0000
1129 #define TYPE_VOID 0x0100
1130 #define TYPE_CHAR 0x0200
1131 #define TYPE_UCHAR 0x0300
1132 #define TYPE_SHORT 0x0400
1133 #define TYPE_USHORT 0x0500
1134 #define TYPE_INT 0x0600
1135 #define TYPE_UINT 0x0700
1136 #define TYPE_LONG 0x0800
1137 #define TYPE_ULONG 0x0900
1138 #define TYPE_LLONG 0x0a00 /* long long */
1139 #define TYPE_ULLONG 0x0b00
1140 #define TYPE_FLOAT 0x0c00
1141 #define TYPE_DOUBLE 0x0d00
1142 #define TYPE_LDOUBLE 0x0e00 /* long double */
1144 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1145 #define TYPE_ENUM 0x1600
1146 #define TYPE_LIST 0x1700
1147 /* TYPE_LIST is a basic building block when defining enumerations
1148 * type->field_ident holds the name of this enumeration entry.
1149 * type->right holds the entry in the list.
1152 #define TYPE_STRUCT 0x1000
1154 * type->left holds the link list of TYPE_PRODUCT entries that
1155 * make up the structure.
1156 * type->elements hold the length of the linked list
1158 #define TYPE_UNION 0x1100
1160 * type->left holds the link list of TYPE_OVERLAP entries that
1161 * make up the union.
1162 * type->elements hold the length of the linked list
1164 #define TYPE_POINTER 0x1200
1165 /* For TYPE_POINTER:
1166 * type->left holds the type pointed to.
1168 #define TYPE_FUNCTION 0x1300
1169 /* For TYPE_FUNCTION:
1170 * type->left holds the return type.
1171 * type->right holds the type of the arguments
1172 * type->elements holds the count of the arguments
1174 #define TYPE_PRODUCT 0x1400
1175 /* TYPE_PRODUCT is a basic building block when defining structures
1176 * type->left holds the type that appears first in memory.
1177 * type->right holds the type that appears next in memory.
1179 #define TYPE_OVERLAP 0x1500
1180 /* TYPE_OVERLAP is a basic building block when defining unions
1181 * type->left and type->right holds to types that overlap
1182 * each other in memory.
1184 #define TYPE_ARRAY 0x1800
1185 /* TYPE_ARRAY is a basic building block when definitng arrays.
1186 * type->left holds the type we are an array of.
1187 * type->elements holds the number of elements.
1189 #define TYPE_TUPLE 0x1900
1190 /* TYPE_TUPLE is a basic building block when defining
1191 * positionally reference type conglomerations. (i.e. closures)
1192 * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1193 * except it has no field names.
1194 * type->left holds the liked list of TYPE_PRODUCT entries that
1195 * make up the closure type.
1196 * type->elements hold the number of elements in the closure.
1198 #define TYPE_JOIN 0x1a00
1199 /* TYPE_JOIN is a basic building block when defining
1200 * positionally reference type conglomerations. (i.e. closures)
1201 * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1202 * except it has no field names.
1203 * type->left holds the liked list of TYPE_OVERLAP entries that
1204 * make up the closure type.
1205 * type->elements hold the number of elements in the closure.
1207 #define TYPE_BITFIELD 0x1b00
1208 /* TYPE_BITFIED is the type of a bitfield.
1209 * type->left holds the type basic type TYPE_BITFIELD is derived from.
1210 * type->elements holds the number of bits in the bitfield.
1212 #define TYPE_UNKNOWN 0x1c00
1213 /* TYPE_UNKNOWN is the type of an unknown value.
1214 * Used on unknown consts and other places where I don't know the type.
1217 #define ATTRIB_SHIFT 16
1218 #define ATTRIB_MASK 0xffff0000
1219 #define ATTRIB_NOINLINE 0x00010000
1220 #define ATTRIB_ALWAYS_INLINE 0x00020000
1222 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1226 struct type *left, *right;
1228 struct hash_entry *field_ident;
1229 struct hash_entry *type_ident;
1232 #define TEMPLATE_BITS 7
1233 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
1234 #define MAX_REG_EQUIVS 16
1236 #define MAX_REGISTERS 75
1237 #define REGISTER_BITS 7
1238 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1241 #define REG_UNNEEDED 2
1242 #define REG_VIRT0 (MAX_REGISTERS + 0)
1243 #define REG_VIRT1 (MAX_REGISTERS + 1)
1244 #define REG_VIRT2 (MAX_REGISTERS + 2)
1245 #define REG_VIRT3 (MAX_REGISTERS + 3)
1246 #define REG_VIRT4 (MAX_REGISTERS + 4)
1247 #define REG_VIRT5 (MAX_REGISTERS + 5)
1248 #define REG_VIRT6 (MAX_REGISTERS + 6)
1249 #define REG_VIRT7 (MAX_REGISTERS + 7)
1250 #define REG_VIRT8 (MAX_REGISTERS + 8)
1251 #define REG_VIRT9 (MAX_REGISTERS + 9)
1253 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1254 #error "MAX_VIRT_REGISTERS to small"
1256 #if (MAX_REGC + REGISTER_BITS) >= 26
1257 #error "Too many id bits used"
1260 /* Provision for 8 register classes */
1262 #define REGC_SHIFT REGISTER_BITS
1263 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1264 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1265 #define ID_REG(ID) ((ID) & REG_MASK)
1266 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1267 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
1268 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1269 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1270 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1272 #define ARCH_INPUT_REGS 4
1273 #define ARCH_OUTPUT_REGS 4
1275 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1276 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1277 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1278 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1279 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1280 static void arch_reg_equivs(
1281 struct compile_state *state, unsigned *equiv, int reg);
1282 static int arch_select_free_register(
1283 struct compile_state *state, char *used, int classes);
1284 static unsigned arch_regc_size(struct compile_state *state, int class);
1285 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1286 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1287 static const char *arch_reg_str(int reg);
1288 static struct reg_info arch_reg_constraint(
1289 struct compile_state *state, struct type *type, const char *constraint);
1290 static struct reg_info arch_reg_clobber(
1291 struct compile_state *state, const char *clobber);
1292 static struct reg_info arch_reg_lhs(struct compile_state *state,
1293 struct triple *ins, int index);
1294 static struct reg_info arch_reg_rhs(struct compile_state *state,
1295 struct triple *ins, int index);
1296 static int arch_reg_size(int reg);
1297 static struct triple *transform_to_arch_instruction(
1298 struct compile_state *state, struct triple *ins);
1299 static struct triple *flatten(
1300 struct compile_state *state, struct triple *first, struct triple *ptr);
1305 #define DEBUG_ABORT_ON_ERROR 0x00000001
1306 #define DEBUG_BASIC_BLOCKS 0x00000002
1307 #define DEBUG_FDOMINATORS 0x00000004
1308 #define DEBUG_RDOMINATORS 0x00000008
1309 #define DEBUG_TRIPLES 0x00000010
1310 #define DEBUG_INTERFERENCE 0x00000020
1311 #define DEBUG_SCC_TRANSFORM 0x00000040
1312 #define DEBUG_SCC_TRANSFORM2 0x00000080
1313 #define DEBUG_REBUILD_SSA_FORM 0x00000100
1314 #define DEBUG_INLINE 0x00000200
1315 #define DEBUG_RANGE_CONFLICTS 0x00000400
1316 #define DEBUG_RANGE_CONFLICTS2 0x00000800
1317 #define DEBUG_COLOR_GRAPH 0x00001000
1318 #define DEBUG_COLOR_GRAPH2 0x00002000
1319 #define DEBUG_COALESCING 0x00004000
1320 #define DEBUG_COALESCING2 0x00008000
1321 #define DEBUG_VERIFICATION 0x00010000
1322 #define DEBUG_CALLS 0x00020000
1323 #define DEBUG_CALLS2 0x00040000
1324 #define DEBUG_TOKENS 0x80000000
1326 #define DEBUG_DEFAULT ( \
1327 DEBUG_ABORT_ON_ERROR | \
1328 DEBUG_BASIC_BLOCKS | \
1329 DEBUG_FDOMINATORS | \
1330 DEBUG_RDOMINATORS | \
1334 #define DEBUG_ALL ( \
1335 DEBUG_ABORT_ON_ERROR | \
1336 DEBUG_BASIC_BLOCKS | \
1337 DEBUG_FDOMINATORS | \
1338 DEBUG_RDOMINATORS | \
1340 DEBUG_INTERFERENCE | \
1341 DEBUG_SCC_TRANSFORM | \
1342 DEBUG_SCC_TRANSFORM2 | \
1343 DEBUG_REBUILD_SSA_FORM | \
1345 DEBUG_RANGE_CONFLICTS | \
1346 DEBUG_RANGE_CONFLICTS2 | \
1347 DEBUG_COLOR_GRAPH | \
1348 DEBUG_COLOR_GRAPH2 | \
1349 DEBUG_COALESCING | \
1350 DEBUG_COALESCING2 | \
1351 DEBUG_VERIFICATION | \
1357 #define COMPILER_INLINE_MASK 0x00000007
1358 #define COMPILER_INLINE_ALWAYS 0x00000000
1359 #define COMPILER_INLINE_NEVER 0x00000001
1360 #define COMPILER_INLINE_DEFAULTON 0x00000002
1361 #define COMPILER_INLINE_DEFAULTOFF 0x00000003
1362 #define COMPILER_INLINE_NOPENALTY 0x00000004
1363 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1364 #define COMPILER_SIMPLIFY 0x00000010
1365 #define COMPILER_SCC_TRANSFORM 0x00000020
1366 #define COMPILER_SIMPLIFY_OP 0x00000040
1367 #define COMPILER_SIMPLIFY_PHI 0x00000080
1368 #define COMPILER_SIMPLIFY_LABEL 0x00000100
1369 #define COMPILER_SIMPLIFY_BRANCH 0x00000200
1370 #define COMPILER_SIMPLIFY_COPY 0x00000400
1371 #define COMPILER_SIMPLIFY_ARITH 0x00000800
1372 #define COMPILER_SIMPLIFY_SHIFT 0x00001000
1373 #define COMPILER_SIMPLIFY_BITWISE 0x00002000
1374 #define COMPILER_SIMPLIFY_LOGICAL 0x00004000
1375 #define COMPILER_SIMPLIFY_BITFIELD 0x00008000
1377 #define COMPILER_CPP_ONLY 0x80000000
1379 #define COMPILER_DEFAULT_FLAGS ( \
1380 COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1381 COMPILER_INLINE_DEFAULTON | \
1382 COMPILER_SIMPLIFY_OP | \
1383 COMPILER_SIMPLIFY_PHI | \
1384 COMPILER_SIMPLIFY_LABEL | \
1385 COMPILER_SIMPLIFY_BRANCH | \
1386 COMPILER_SIMPLIFY_COPY | \
1387 COMPILER_SIMPLIFY_ARITH | \
1388 COMPILER_SIMPLIFY_SHIFT | \
1389 COMPILER_SIMPLIFY_BITWISE | \
1390 COMPILER_SIMPLIFY_LOGICAL | \
1391 COMPILER_SIMPLIFY_BITFIELD | \
1394 #define GLOBAL_SCOPE_DEPTH 1
1395 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1397 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1401 static void init_compiler_state(struct compiler_state *compiler)
1403 memset(compiler, 0, sizeof(*compiler));
1404 compiler->label_prefix = "";
1405 compiler->ofilename = "auto.inc";
1406 compiler->flags = COMPILER_DEFAULT_FLAGS;
1407 compiler->debug = 0;
1408 compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1409 compiler->include_path_count = 1;
1410 compiler->include_paths = xcmalloc(sizeof(char *), "include_paths");
1411 compiler->define_count = 1;
1412 compiler->defines = xcmalloc(sizeof(char *), "defines");
1413 compiler->undef_count = 1;
1414 compiler->undefs = xcmalloc(sizeof(char *), "undefs");
1417 struct compiler_flag {
1422 struct compiler_arg {
1425 struct compiler_flag flags[16];
1428 static int set_flag(
1429 const struct compiler_flag *ptr, unsigned long *flags,
1430 int act, const char *flag)
1433 for(; ptr->name; ptr++) {
1434 if (strcmp(ptr->name, flag) == 0) {
1440 *flags &= ~(ptr->flag);
1442 *flags |= ptr->flag;
1449 const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1454 val = strchr(arg, '=');
1458 for(; ptr->name; ptr++) {
1459 if (strncmp(ptr->name, arg, len) == 0) {
1464 *flags &= ~ptr->mask;
1465 result = set_flag(&ptr->flags[0], flags, 1, val);
1472 static void flag_usage(FILE *fp, const struct compiler_flag *ptr,
1473 const char *prefix, const char *invert_prefix)
1475 for(;ptr->name; ptr++) {
1476 fprintf(fp, "%s%s\n", prefix, ptr->name);
1477 if (invert_prefix) {
1478 fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1483 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1486 for(;ptr->name; ptr++) {
1487 const struct compiler_flag *flag;
1488 for(flag = &ptr->flags[0]; flag->name; flag++) {
1489 fprintf(fp, "%s%s=%s\n",
1490 prefix, ptr->name, flag->name);
1495 static int append_string(size_t *max, const char ***vec, const char *str,
1500 *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1501 (*vec)[count -1] = 0;
1502 (*vec)[count -2] = str;
1506 static void arg_error(char *fmt, ...);
1507 static const char *identifier(const char *str, const char *end);
1509 static int append_include_path(struct compiler_state *compiler, const char *str)
1512 if (!exists(str, ".")) {
1513 arg_error("Nonexistent include path: `%s'\n",
1516 result = append_string(&compiler->include_path_count,
1517 &compiler->include_paths, str, "include_paths");
1521 static int append_define(struct compiler_state *compiler, const char *str)
1523 const char *end, *rest;
1526 end = strchr(str, '=');
1528 end = str + strlen(str);
1530 rest = identifier(str, end);
1532 int len = end - str - 1;
1533 arg_error("Invalid name cannot define macro: `%*.*s'\n",
1536 result = append_string(&compiler->define_count,
1537 &compiler->defines, str, "defines");
1541 static int append_undef(struct compiler_state *compiler, const char *str)
1543 const char *end, *rest;
1546 end = str + strlen(str);
1547 rest = identifier(str, end);
1549 int len = end - str - 1;
1550 arg_error("Invalid name cannot undefine macro: `%*.*s'\n",
1553 result = append_string(&compiler->undef_count,
1554 &compiler->undefs, str, "undefs");
1558 static const struct compiler_flag romcc_flags[] = {
1559 { "cpp-only", COMPILER_CPP_ONLY },
1560 { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1561 { "simplify", COMPILER_SIMPLIFY },
1562 { "scc-transform", COMPILER_SCC_TRANSFORM },
1563 { "simplify-op", COMPILER_SIMPLIFY_OP },
1564 { "simplify-phi", COMPILER_SIMPLIFY_PHI },
1565 { "simplify-label", COMPILER_SIMPLIFY_LABEL },
1566 { "simplify-branch", COMPILER_SIMPLIFY_BRANCH },
1567 { "simplify-copy", COMPILER_SIMPLIFY_COPY },
1568 { "simplify-arith", COMPILER_SIMPLIFY_ARITH },
1569 { "simplify-shift", COMPILER_SIMPLIFY_SHIFT },
1570 { "simplify-bitwise", COMPILER_SIMPLIFY_BITWISE },
1571 { "simplify-logical", COMPILER_SIMPLIFY_LOGICAL },
1572 { "simplify-bitfield", COMPILER_SIMPLIFY_BITFIELD },
1575 static const struct compiler_arg romcc_args[] = {
1576 { "inline-policy", COMPILER_INLINE_MASK,
1578 { "always", COMPILER_INLINE_ALWAYS, },
1579 { "never", COMPILER_INLINE_NEVER, },
1580 { "defaulton", COMPILER_INLINE_DEFAULTON, },
1581 { "defaultoff", COMPILER_INLINE_DEFAULTOFF, },
1582 { "nopenalty", COMPILER_INLINE_NOPENALTY, },
1588 static const struct compiler_flag romcc_opt_flags[] = {
1589 { "-O", COMPILER_SIMPLIFY },
1590 { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1591 { "-E", COMPILER_CPP_ONLY },
1594 static const struct compiler_flag romcc_debug_flags[] = {
1595 { "all", DEBUG_ALL },
1596 { "abort-on-error", DEBUG_ABORT_ON_ERROR },
1597 { "basic-blocks", DEBUG_BASIC_BLOCKS },
1598 { "fdominators", DEBUG_FDOMINATORS },
1599 { "rdominators", DEBUG_RDOMINATORS },
1600 { "triples", DEBUG_TRIPLES },
1601 { "interference", DEBUG_INTERFERENCE },
1602 { "scc-transform", DEBUG_SCC_TRANSFORM },
1603 { "scc-transform2", DEBUG_SCC_TRANSFORM2 },
1604 { "rebuild-ssa-form", DEBUG_REBUILD_SSA_FORM },
1605 { "inline", DEBUG_INLINE },
1606 { "live-range-conflicts", DEBUG_RANGE_CONFLICTS },
1607 { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1608 { "color-graph", DEBUG_COLOR_GRAPH },
1609 { "color-graph2", DEBUG_COLOR_GRAPH2 },
1610 { "coalescing", DEBUG_COALESCING },
1611 { "coalescing2", DEBUG_COALESCING2 },
1612 { "verification", DEBUG_VERIFICATION },
1613 { "calls", DEBUG_CALLS },
1614 { "calls2", DEBUG_CALLS2 },
1615 { "tokens", DEBUG_TOKENS },
1619 static int compiler_encode_flag(
1620 struct compiler_state *compiler, const char *flag)
1627 if (strncmp(flag, "no-", 3) == 0) {
1631 if (strncmp(flag, "-O", 2) == 0) {
1632 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1634 else if (strncmp(flag, "-E", 2) == 0) {
1635 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1637 else if (strncmp(flag, "-I", 2) == 0) {
1638 result = append_include_path(compiler, flag + 2);
1640 else if (strncmp(flag, "-D", 2) == 0) {
1641 result = append_define(compiler, flag + 2);
1643 else if (strncmp(flag, "-U", 2) == 0) {
1644 result = append_undef(compiler, flag + 2);
1646 else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1648 compiler->label_prefix = flag + 13;
1650 else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1651 unsigned long max_passes;
1653 max_passes = strtoul(flag + 22, &end, 10);
1654 if (end[0] == '\0') {
1656 compiler->max_allocation_passes = max_passes;
1659 else if (act && strcmp(flag, "debug") == 0) {
1661 compiler->debug |= DEBUG_DEFAULT;
1663 else if (strncmp(flag, "debug-", 6) == 0) {
1665 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1668 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1670 result = set_arg(romcc_args, &compiler->flags, flag);
1676 static void compiler_usage(FILE *fp)
1678 flag_usage(fp, romcc_opt_flags, "", 0);
1679 flag_usage(fp, romcc_flags, "-f", "-fno-");
1680 arg_usage(fp, romcc_args, "-f");
1681 flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1682 fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1683 fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1684 fprintf(fp, "-I<include path>\n");
1685 fprintf(fp, "-D<macro>[=defn]\n");
1686 fprintf(fp, "-U<macro>\n");
1689 static void do_cleanup(struct compile_state *state)
1691 if (state->output) {
1692 fclose(state->output);
1693 unlink(state->compiler->ofilename);
1696 if (state->dbgout) {
1697 fflush(state->dbgout);
1699 if (state->errout) {
1700 fflush(state->errout);
1704 static struct compile_state *exit_state;
1705 static void exit_cleanup(void)
1708 do_cleanup(exit_state);
1712 static int get_col(struct file_state *file)
1715 const char *ptr, *end;
1716 ptr = file->line_start;
1718 for(col = 0; ptr < end; ptr++) {
1723 col = (col & ~7) + 8;
1729 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1732 if (triple && triple->occurance) {
1733 struct occurance *spot;
1734 for(spot = triple->occurance; spot; spot = spot->parent) {
1735 fprintf(fp, "%s:%d.%d: ",
1736 spot->filename, spot->line, spot->col);
1743 col = get_col(state->file);
1744 fprintf(fp, "%s:%d.%d: ",
1745 state->file->report_name, state->file->report_line, col);
1748 static void internal_error(struct compile_state *state, struct triple *ptr,
1749 const char *fmt, ...)
1751 FILE *fp = state->errout;
1753 va_start(args, fmt);
1754 loc(fp, state, ptr);
1757 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1759 fprintf(fp, "Internal compiler error: ");
1760 vfprintf(fp, fmt, args);
1768 static void internal_warning(struct compile_state *state, struct triple *ptr,
1769 const char *fmt, ...)
1771 FILE *fp = state->errout;
1773 va_start(args, fmt);
1774 loc(fp, state, ptr);
1776 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1778 fprintf(fp, "Internal compiler warning: ");
1779 vfprintf(fp, fmt, args);
1786 static void error(struct compile_state *state, struct triple *ptr,
1787 const char *fmt, ...)
1789 FILE *fp = state->errout;
1791 va_start(args, fmt);
1792 loc(fp, state, ptr);
1794 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1795 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1797 vfprintf(fp, fmt, args);
1801 if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1807 static void warning(struct compile_state *state, struct triple *ptr,
1808 const char *fmt, ...)
1810 FILE *fp = state->errout;
1812 va_start(args, fmt);
1813 loc(fp, state, ptr);
1814 fprintf(fp, "warning: ");
1815 if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1816 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1818 vfprintf(fp, fmt, args);
1823 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1825 static void valid_op(struct compile_state *state, int op)
1827 char *fmt = "invalid op: %d";
1829 internal_error(state, 0, fmt, op);
1832 internal_error(state, 0, fmt, op);
1836 static void valid_ins(struct compile_state *state, struct triple *ptr)
1838 valid_op(state, ptr->op);
1841 static void valid_param_count(struct compile_state *state, struct triple *ins)
1843 int lhs, rhs, misc, targ;
1844 valid_ins(state, ins);
1845 lhs = table_ops[ins->op].lhs;
1846 rhs = table_ops[ins->op].rhs;
1847 misc = table_ops[ins->op].misc;
1848 targ = table_ops[ins->op].targ;
1850 if ((lhs >= 0) && (ins->lhs != lhs)) {
1851 internal_error(state, ins, "Bad lhs count");
1853 if ((rhs >= 0) && (ins->rhs != rhs)) {
1854 internal_error(state, ins, "Bad rhs count");
1856 if ((misc >= 0) && (ins->misc != misc)) {
1857 internal_error(state, ins, "Bad misc count");
1859 if ((targ >= 0) && (ins->targ != targ)) {
1860 internal_error(state, ins, "Bad targ count");
1864 static void process_trigraphs(struct compile_state *state)
1866 char *src, *dest, *end;
1867 struct file_state *file;
1869 src = dest = file->buf;
1870 end = file->buf + file->size;
1871 while((end - src) >= 3) {
1872 if ((src[0] == '?') && (src[1] == '?')) {
1875 case '=': c = '#'; break;
1876 case '/': c = '\\'; break;
1877 case '\'': c = '^'; break;
1878 case '(': c = '['; break;
1879 case ')': c = ']'; break;
1880 case '!': c = '!'; break;
1881 case '<': c = '{'; break;
1882 case '>': c = '}'; break;
1883 case '-': c = '~'; break;
1900 file->size = dest - file->buf;
1903 static void splice_lines(struct compile_state *state)
1905 char *src, *dest, *end;
1906 struct file_state *file;
1908 src = dest = file->buf;
1909 end = file->buf + file->size;
1910 while((end - src) >= 2) {
1911 if ((src[0] == '\\') && (src[1] == '\n')) {
1921 file->size = dest - file->buf;
1924 static struct type void_type;
1925 static struct type unknown_type;
1926 static void use_triple(struct triple *used, struct triple *user)
1928 struct triple_set **ptr, *new;
1935 if ((*ptr)->member == user) {
1938 ptr = &(*ptr)->next;
1940 /* Append new to the head of the list,
1941 * copy_func and rename_block_variables
1944 new = xcmalloc(sizeof(*new), "triple_set");
1946 new->next = used->use;
1950 static void unuse_triple(struct triple *used, struct triple *unuser)
1952 struct triple_set *use, **ptr;
1959 if (use->member == unuser) {
1969 static void put_occurance(struct occurance *occurance)
1972 occurance->count -= 1;
1973 if (occurance->count <= 0) {
1974 if (occurance->parent) {
1975 put_occurance(occurance->parent);
1982 static void get_occurance(struct occurance *occurance)
1985 occurance->count += 1;
1990 static struct occurance *new_occurance(struct compile_state *state)
1992 struct occurance *result, *last;
1993 const char *filename;
1994 const char *function;
2002 filename = state->file->report_name;
2003 line = state->file->report_line;
2004 col = get_col(state->file);
2006 if (state->function) {
2007 function = state->function;
2009 last = state->last_occurance;
2011 (last->col == col) &&
2012 (last->line == line) &&
2013 (last->function == function) &&
2014 ((last->filename == filename) ||
2015 (strcmp(last->filename, filename) == 0)))
2017 get_occurance(last);
2021 state->last_occurance = 0;
2022 put_occurance(last);
2024 result = xmalloc(sizeof(*result), "occurance");
2026 result->filename = filename;
2027 result->function = function;
2028 result->line = line;
2031 state->last_occurance = result;
2035 static struct occurance *inline_occurance(struct compile_state *state,
2036 struct occurance *base, struct occurance *top)
2038 struct occurance *result, *last;
2040 internal_error(state, 0, "inlining an already inlined function?");
2042 /* If I have a null base treat it that way */
2043 if ((base->parent == 0) &&
2045 (base->line == 0) &&
2046 (base->function[0] == '\0') &&
2047 (base->filename[0] == '\0')) {
2050 /* See if I can reuse the last occurance I had */
2051 last = state->last_occurance;
2053 (last->parent == base) &&
2054 (last->col == top->col) &&
2055 (last->line == top->line) &&
2056 (last->function == top->function) &&
2057 (last->filename == top->filename)) {
2058 get_occurance(last);
2061 /* I can't reuse the last occurance so free it */
2063 state->last_occurance = 0;
2064 put_occurance(last);
2066 /* Generate a new occurance structure */
2067 get_occurance(base);
2068 result = xmalloc(sizeof(*result), "occurance");
2070 result->filename = top->filename;
2071 result->function = top->function;
2072 result->line = top->line;
2073 result->col = top->col;
2074 result->parent = base;
2075 state->last_occurance = result;
2079 static struct occurance dummy_occurance = {
2081 .filename = __FILE__,
2088 /* The undef triple is used as a place holder when we are removing pointers
2089 * from a triple. Having allows certain sanity checks to pass even
2090 * when the original triple that was pointed to is gone.
2092 static struct triple unknown_triple = {
2093 .next = &unknown_triple,
2094 .prev = &unknown_triple,
2096 .op = OP_UNKNOWNVAL,
2101 .type = &unknown_type,
2102 .id = -1, /* An invalid id */
2103 .u = { .cval = 0, },
2104 .occurance = &dummy_occurance,
2105 .param = { [0] = 0, [1] = 0, },
2109 static size_t registers_of(struct compile_state *state, struct type *type);
2111 static struct triple *alloc_triple(struct compile_state *state,
2112 int op, struct type *type, int lhs_wanted, int rhs_wanted,
2113 struct occurance *occurance)
2115 size_t size, extra_count, min_count;
2116 int lhs, rhs, misc, targ;
2117 struct triple *ret, dummy;
2119 dummy.occurance = occurance;
2120 valid_op(state, op);
2121 lhs = table_ops[op].lhs;
2122 rhs = table_ops[op].rhs;
2123 misc = table_ops[op].misc;
2124 targ = table_ops[op].targ;
2134 lhs = registers_of(state, type);
2137 lhs = registers_of(state, type);
2144 if ((rhs < 0) || (rhs > MAX_RHS)) {
2145 internal_error(state, &dummy, "bad rhs count %d", rhs);
2147 if ((lhs < 0) || (lhs > MAX_LHS)) {
2148 internal_error(state, &dummy, "bad lhs count %d", lhs);
2150 if ((misc < 0) || (misc > MAX_MISC)) {
2151 internal_error(state, &dummy, "bad misc count %d", misc);
2153 if ((targ < 0) || (targ > MAX_TARG)) {
2154 internal_error(state, &dummy, "bad targs count %d", targ);
2157 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2158 extra_count = lhs + rhs + misc + targ;
2159 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2161 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2162 ret = xcmalloc(size, "tripple");
2171 ret->occurance = occurance;
2172 /* A simple sanity check */
2173 if ((ret->op != op) ||
2174 (ret->lhs != lhs) ||
2175 (ret->rhs != rhs) ||
2176 (ret->misc != misc) ||
2177 (ret->targ != targ) ||
2178 (ret->type != type) ||
2179 (ret->next != ret) ||
2180 (ret->prev != ret) ||
2181 (ret->occurance != occurance)) {
2182 internal_error(state, ret, "huh?");
2187 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2190 int src_lhs, src_rhs, src_size;
2193 src_size = TRIPLE_SIZE(src);
2194 get_occurance(src->occurance);
2195 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2197 memcpy(dup, src, sizeof(*src));
2198 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2202 static struct triple *new_triple(struct compile_state *state,
2203 int op, struct type *type, int lhs, int rhs)
2206 struct occurance *occurance;
2207 occurance = new_occurance(state);
2208 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2212 static struct triple *build_triple(struct compile_state *state,
2213 int op, struct type *type, struct triple *left, struct triple *right,
2214 struct occurance *occurance)
2218 ret = alloc_triple(state, op, type, -1, -1, occurance);
2219 count = TRIPLE_SIZE(ret);
2221 ret->param[0] = left;
2224 ret->param[1] = right;
2229 static struct triple *triple(struct compile_state *state,
2230 int op, struct type *type, struct triple *left, struct triple *right)
2234 ret = new_triple(state, op, type, -1, -1);
2235 count = TRIPLE_SIZE(ret);
2237 ret->param[0] = left;
2240 ret->param[1] = right;
2245 static struct triple *branch(struct compile_state *state,
2246 struct triple *targ, struct triple *test)
2250 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2253 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2255 TARG(ret, 0) = targ;
2256 /* record the branch target was used */
2257 if (!targ || (targ->op != OP_LABEL)) {
2258 internal_error(state, 0, "branch not to label");
2263 static int triple_is_label(struct compile_state *state, struct triple *ins);
2264 static int triple_is_call(struct compile_state *state, struct triple *ins);
2265 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2266 static void insert_triple(struct compile_state *state,
2267 struct triple *first, struct triple *ptr)
2270 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2271 internal_error(state, ptr, "expression already used");
2274 ptr->prev = first->prev;
2275 ptr->prev->next = ptr;
2276 ptr->next->prev = ptr;
2278 if (triple_is_cbranch(state, ptr->prev) ||
2279 triple_is_call(state, ptr->prev)) {
2280 unuse_triple(first, ptr->prev);
2281 use_triple(ptr, ptr->prev);
2286 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2288 /* This function is used to determine if u.block
2289 * is utilized to store the current block number.
2292 valid_ins(state, ins);
2293 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2294 return stores_block;
2297 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2298 static struct block *block_of_triple(struct compile_state *state,
2301 struct triple *first;
2302 if (!ins || ins == &unknown_triple) {
2305 first = state->first;
2306 while(ins != first && !triple_is_branch(state, ins->prev) &&
2307 !triple_stores_block(state, ins))
2309 if (ins == ins->prev) {
2310 internal_error(state, ins, "ins == ins->prev?");
2314 return triple_stores_block(state, ins)? ins->u.block: 0;
2317 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2318 static struct triple *pre_triple(struct compile_state *state,
2319 struct triple *base,
2320 int op, struct type *type, struct triple *left, struct triple *right)
2322 struct block *block;
2325 /* If I am an OP_PIECE jump to the real instruction */
2326 if (base->op == OP_PIECE) {
2327 base = MISC(base, 0);
2329 block = block_of_triple(state, base);
2330 get_occurance(base->occurance);
2331 ret = build_triple(state, op, type, left, right, base->occurance);
2332 generate_lhs_pieces(state, ret);
2333 if (triple_stores_block(state, ret)) {
2334 ret->u.block = block;
2336 insert_triple(state, base, ret);
2337 for(i = 0; i < ret->lhs; i++) {
2338 struct triple *piece;
2339 piece = LHS(ret, i);
2340 insert_triple(state, base, piece);
2341 use_triple(ret, piece);
2342 use_triple(piece, ret);
2344 if (block && (block->first == base)) {
2350 static struct triple *post_triple(struct compile_state *state,
2351 struct triple *base,
2352 int op, struct type *type, struct triple *left, struct triple *right)
2354 struct block *block;
2355 struct triple *ret, *next;
2357 /* If I am an OP_PIECE jump to the real instruction */
2358 if (base->op == OP_PIECE) {
2359 base = MISC(base, 0);
2361 /* If I have a left hand side skip over it */
2364 base = LHS(base, zlhs - 1);
2367 block = block_of_triple(state, base);
2368 get_occurance(base->occurance);
2369 ret = build_triple(state, op, type, left, right, base->occurance);
2370 generate_lhs_pieces(state, ret);
2371 if (triple_stores_block(state, ret)) {
2372 ret->u.block = block;
2375 insert_triple(state, next, ret);
2377 for(i = 0; i < zlhs; i++) {
2378 struct triple *piece;
2379 piece = LHS(ret, i);
2380 insert_triple(state, next, piece);
2381 use_triple(ret, piece);
2382 use_triple(piece, ret);
2384 if (block && (block->last == base)) {
2387 block->last = LHS(ret, zlhs - 1);
2393 static struct type *reg_type(
2394 struct compile_state *state, struct type *type, int reg);
2396 static void generate_lhs_piece(
2397 struct compile_state *state, struct triple *ins, int index)
2399 struct type *piece_type;
2400 struct triple *piece;
2401 get_occurance(ins->occurance);
2402 piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2404 if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2405 piece_type = piece_type->left;
2409 static void name_of(FILE *fp, struct type *type);
2410 FILE * fp = state->errout;
2411 fprintf(fp, "piece_type(%d): ", index);
2412 name_of(fp, piece_type);
2416 piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2417 piece->u.cval = index;
2418 LHS(ins, piece->u.cval) = piece;
2419 MISC(piece, 0) = ins;
2422 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2426 for(i = 0; i < zlhs; i++) {
2427 generate_lhs_piece(state, ins, i);
2431 static struct triple *label(struct compile_state *state)
2433 /* Labels don't get a type */
2434 struct triple *result;
2435 result = triple(state, OP_LABEL, &void_type, 0, 0);
2439 static struct triple *mkprog(struct compile_state *state, ...)
2441 struct triple *prog, *head, *arg;
2445 head = label(state);
2446 prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2447 RHS(prog, 0) = head;
2448 va_start(args, state);
2450 while((arg = va_arg(args, struct triple *)) != 0) {
2452 internal_error(state, 0, "too many arguments to mkprog");
2454 flatten(state, head, arg);
2457 prog->type = head->prev->type;
2460 static void name_of(FILE *fp, struct type *type);
2461 static void display_triple(FILE *fp, struct triple *ins)
2463 struct occurance *ptr;
2465 char pre, post, vol;
2466 pre = post = vol = ' ';
2468 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2471 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2474 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2477 reg = arch_reg_str(ID_REG(ins->id));
2480 fprintf(fp, "(%p) <nothing> ", ins);
2482 else if (ins->op == OP_INTCONST) {
2483 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx> ",
2484 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2485 (unsigned long)(ins->u.cval));
2487 else if (ins->op == OP_ADDRCONST) {
2488 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2489 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2490 MISC(ins, 0), (unsigned long)(ins->u.cval));
2492 else if (ins->op == OP_INDEX) {
2493 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2494 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2495 RHS(ins, 0), (unsigned long)(ins->u.cval));
2497 else if (ins->op == OP_PIECE) {
2498 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2499 ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2500 MISC(ins, 0), (unsigned long)(ins->u.cval));
2504 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s",
2505 ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2506 if (table_ops[ins->op].flags & BITFIELD) {
2507 fprintf(fp, " <%2d-%2d:%2d>",
2508 ins->u.bitfield.offset,
2509 ins->u.bitfield.offset + ins->u.bitfield.size,
2510 ins->u.bitfield.size);
2512 count = TRIPLE_SIZE(ins);
2513 for(i = 0; i < count; i++) {
2514 fprintf(fp, " %-10p", ins->param[i]);
2521 struct triple_set *user;
2522 #if DEBUG_DISPLAY_TYPES
2524 name_of(fp, ins->type);
2527 #if DEBUG_DISPLAY_USES
2529 for(user = ins->use; user; user = user->next) {
2530 fprintf(fp, " %-10p", user->member);
2535 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2536 fprintf(fp, " %s,%s:%d.%d",
2542 if (ins->op == OP_ASM) {
2543 fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2550 static int equiv_types(struct type *left, struct type *right);
2551 static void display_triple_changes(
2552 FILE *fp, const struct triple *new, const struct triple *orig)
2555 int new_count, orig_count;
2556 new_count = TRIPLE_SIZE(new);
2557 orig_count = TRIPLE_SIZE(orig);
2558 if ((new->op != orig->op) ||
2559 (new_count != orig_count) ||
2560 (memcmp(orig->param, new->param,
2561 orig_count * sizeof(orig->param[0])) != 0) ||
2562 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0))
2564 struct occurance *ptr;
2565 int i, min_count, indent;
2566 fprintf(fp, "(%p %p)", new, orig);
2567 if (orig->op == new->op) {
2568 fprintf(fp, " %-11s", tops(orig->op));
2570 fprintf(fp, " [%-10s %-10s]",
2571 tops(new->op), tops(orig->op));
2573 min_count = new_count;
2574 if (min_count > orig_count) {
2575 min_count = orig_count;
2577 for(indent = i = 0; i < min_count; i++) {
2578 if (orig->param[i] == new->param[i]) {
2579 fprintf(fp, " %-11p",
2583 fprintf(fp, " [%-10p %-10p]",
2589 for(; i < orig_count; i++) {
2590 fprintf(fp, " [%-9p]", orig->param[i]);
2593 for(; i < new_count; i++) {
2594 fprintf(fp, " [%-9p]", new->param[i]);
2597 if ((new->op == OP_INTCONST)||
2598 (new->op == OP_ADDRCONST)) {
2599 fprintf(fp, " <0x%08lx>",
2600 (unsigned long)(new->u.cval));
2603 for(;indent < 36; indent++) {
2607 #if DEBUG_DISPLAY_TYPES
2609 name_of(fp, new->type);
2610 if (!equiv_types(new->type, orig->type)) {
2611 fprintf(fp, " -- ");
2612 name_of(fp, orig->type);
2618 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2619 fprintf(fp, " %s,%s:%d.%d",
2631 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2633 /* Does the triple have no side effects.
2634 * I.e. Rexecuting the triple with the same arguments
2635 * gives the same value.
2638 valid_ins(state, ins);
2639 pure = PURE_BITS(table_ops[ins->op].flags);
2640 if ((pure != PURE) && (pure != IMPURE)) {
2641 internal_error(state, 0, "Purity of %s not known",
2644 return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2647 static int triple_is_branch_type(struct compile_state *state,
2648 struct triple *ins, unsigned type)
2650 /* Is this one of the passed branch types? */
2651 valid_ins(state, ins);
2652 return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2655 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2657 /* Is this triple a branch instruction? */
2658 valid_ins(state, ins);
2659 return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2662 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2664 /* Is this triple a conditional branch instruction? */
2665 return triple_is_branch_type(state, ins, CBRANCH);
2668 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2670 /* Is this triple a unconditional branch instruction? */
2672 valid_ins(state, ins);
2673 type = BRANCH_BITS(table_ops[ins->op].flags);
2674 return (type != 0) && (type != CBRANCH);
2677 static int triple_is_call(struct compile_state *state, struct triple *ins)
2679 /* Is this triple a call instruction? */
2680 return triple_is_branch_type(state, ins, CALLBRANCH);
2683 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2685 /* Is this triple a return instruction? */
2686 return triple_is_branch_type(state, ins, RETBRANCH);
2689 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2691 /* Is this triple an unconditional branch and not a call or a
2693 return triple_is_branch_type(state, ins, UBRANCH);
2696 static int triple_is_end(struct compile_state *state, struct triple *ins)
2698 return triple_is_branch_type(state, ins, ENDBRANCH);
2701 static int triple_is_label(struct compile_state *state, struct triple *ins)
2703 valid_ins(state, ins);
2704 return (ins->op == OP_LABEL);
2707 static struct triple *triple_to_block_start(
2708 struct compile_state *state, struct triple *start)
2710 while(!triple_is_branch(state, start->prev) &&
2711 (!triple_is_label(state, start) || !start->use)) {
2712 start = start->prev;
2717 static int triple_is_def(struct compile_state *state, struct triple *ins)
2719 /* This function is used to determine which triples need
2723 valid_ins(state, ins);
2724 is_def = (table_ops[ins->op].flags & DEF) == DEF;
2725 if (ins->lhs >= 1) {
2731 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2734 valid_ins(state, ins);
2735 is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2736 return is_structural;
2739 static int triple_is_part(struct compile_state *state, struct triple *ins)
2742 valid_ins(state, ins);
2743 is_part = (table_ops[ins->op].flags & PART) == PART;
2747 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2749 return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2752 static struct triple **triple_iter(struct compile_state *state,
2753 size_t count, struct triple **vector,
2754 struct triple *ins, struct triple **last)
2756 struct triple **ret;
2762 else if ((last >= vector) && (last < (vector + count - 1))) {
2770 static struct triple **triple_lhs(struct compile_state *state,
2771 struct triple *ins, struct triple **last)
2773 return triple_iter(state, ins->lhs, &LHS(ins,0),
2777 static struct triple **triple_rhs(struct compile_state *state,
2778 struct triple *ins, struct triple **last)
2780 return triple_iter(state, ins->rhs, &RHS(ins,0),
2784 static struct triple **triple_misc(struct compile_state *state,
2785 struct triple *ins, struct triple **last)
2787 return triple_iter(state, ins->misc, &MISC(ins,0),
2791 static struct triple **do_triple_targ(struct compile_state *state,
2792 struct triple *ins, struct triple **last, int call_edges, int next_edges)
2795 struct triple **ret, **vector;
2800 if (triple_is_cbranch(state, ins)) {
2803 if (!call_edges && triple_is_call(state, ins)) {
2806 if (next_edges && triple_is_call(state, ins)) {
2809 vector = &TARG(ins, 0);
2810 if (!ret && next_is_targ) {
2813 } else if (last == &ins->next) {
2817 if (!ret && count) {
2821 else if ((last >= vector) && (last < (vector + count - 1))) {
2824 else if (last == vector + count - 1) {
2828 if (!ret && triple_is_ret(state, ins) && call_edges) {
2829 struct triple_set *use;
2830 for(use = ins->use; use; use = use->next) {
2831 if (!triple_is_call(state, use->member)) {
2835 ret = &use->member->next;
2838 else if (last == &use->member->next) {
2846 static struct triple **triple_targ(struct compile_state *state,
2847 struct triple *ins, struct triple **last)
2849 return do_triple_targ(state, ins, last, 1, 1);
2852 static struct triple **triple_edge_targ(struct compile_state *state,
2853 struct triple *ins, struct triple **last)
2855 return do_triple_targ(state, ins, last,
2856 state->functions_joined, !state->functions_joined);
2859 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2861 struct triple *next;
2865 for(i = 0; i < lhs; i++) {
2866 struct triple *piece;
2867 piece = LHS(ins, i);
2868 if (next != piece) {
2869 internal_error(state, ins, "malformed lhs on %s",
2872 if (next->op != OP_PIECE) {
2873 internal_error(state, ins, "bad lhs op %s at %d on %s",
2874 tops(next->op), i, tops(ins->op));
2876 if (next->u.cval != i) {
2877 internal_error(state, ins, "bad u.cval of %d %d expected",
2885 /* Function piece accessor functions */
2886 static struct triple *do_farg(struct compile_state *state,
2887 struct triple *func, unsigned index)
2890 struct triple *first, *arg;
2894 if((index < 0) || (index >= (ftype->elements + 2))) {
2895 internal_error(state, func, "bad argument index: %d", index);
2897 first = RHS(func, 0);
2899 for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2902 if (arg->op != OP_ADECL) {
2903 internal_error(state, 0, "arg not adecl?");
2907 static struct triple *fresult(struct compile_state *state, struct triple *func)
2909 return do_farg(state, func, 0);
2911 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2913 return do_farg(state, func, 1);
2915 static struct triple *farg(struct compile_state *state,
2916 struct triple *func, unsigned index)
2918 return do_farg(state, func, index + 2);
2922 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2924 struct triple *first, *ins;
2925 fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2926 first = ins = RHS(func, 0);
2928 if (triple_is_label(state, ins) && ins->use) {
2929 fprintf(fp, "%p:\n", ins);
2931 display_triple(fp, ins);
2933 if (triple_is_branch(state, ins)) {
2936 if (ins->next->prev != ins) {
2937 internal_error(state, ins->next, "bad prev");
2940 } while(ins != first);
2943 static void verify_use(struct compile_state *state,
2944 struct triple *user, struct triple *used)
2947 size = TRIPLE_SIZE(user);
2948 for(i = 0; i < size; i++) {
2949 if (user->param[i] == used) {
2953 if (triple_is_branch(state, user)) {
2954 if (user->next == used) {
2959 internal_error(state, user, "%s(%p) does not use %s(%p)",
2960 tops(user->op), user, tops(used->op), used);
2964 static int find_rhs_use(struct compile_state *state,
2965 struct triple *user, struct triple *used)
2967 struct triple **param;
2969 verify_use(state, user, used);
2970 #warning "AUDIT ME ->rhs"
2972 param = &RHS(user, 0);
2973 for(i = 0; i < size; i++) {
2974 if (param[i] == used) {
2981 static void free_triple(struct compile_state *state, struct triple *ptr)
2984 size = sizeof(*ptr) - sizeof(ptr->param) +
2985 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2986 ptr->prev->next = ptr->next;
2987 ptr->next->prev = ptr->prev;
2989 internal_error(state, ptr, "ptr->use != 0");
2991 put_occurance(ptr->occurance);
2992 memset(ptr, -1, size);
2996 static void release_triple(struct compile_state *state, struct triple *ptr)
2998 struct triple_set *set, *next;
2999 struct triple **expr;
3000 struct block *block;
3001 if (ptr == &unknown_triple) {
3004 valid_ins(state, ptr);
3005 /* Make certain the we are not the first or last element of a block */
3006 block = block_of_triple(state, ptr);
3008 if ((block->last == ptr) && (block->first == ptr)) {
3009 block->last = block->first = 0;
3011 else if (block->last == ptr) {
3012 block->last = ptr->prev;
3014 else if (block->first == ptr) {
3015 block->first = ptr->next;
3018 /* Remove ptr from use chains where it is the user */
3019 expr = triple_rhs(state, ptr, 0);
3020 for(; expr; expr = triple_rhs(state, ptr, expr)) {
3022 unuse_triple(*expr, ptr);
3025 expr = triple_lhs(state, ptr, 0);
3026 for(; expr; expr = triple_lhs(state, ptr, expr)) {
3028 unuse_triple(*expr, ptr);
3031 expr = triple_misc(state, ptr, 0);
3032 for(; expr; expr = triple_misc(state, ptr, expr)) {
3034 unuse_triple(*expr, ptr);
3037 expr = triple_targ(state, ptr, 0);
3038 for(; expr; expr = triple_targ(state, ptr, expr)) {
3040 unuse_triple(*expr, ptr);
3043 /* Reomve ptr from use chains where it is used */
3044 for(set = ptr->use; set; set = next) {
3046 valid_ins(state, set->member);
3047 expr = triple_rhs(state, set->member, 0);
3048 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3050 *expr = &unknown_triple;
3053 expr = triple_lhs(state, set->member, 0);
3054 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3056 *expr = &unknown_triple;
3059 expr = triple_misc(state, set->member, 0);
3060 for(; expr; expr = triple_misc(state, set->member, expr)) {
3062 *expr = &unknown_triple;
3065 expr = triple_targ(state, set->member, 0);
3066 for(; expr; expr = triple_targ(state, set->member, expr)) {
3068 *expr = &unknown_triple;
3071 unuse_triple(ptr, set->member);
3073 free_triple(state, ptr);
3076 static void print_triples(struct compile_state *state);
3077 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3079 #define TOK_UNKNOWN 0
3082 #define TOK_LBRACE 3
3083 #define TOK_RBRACE 4
3087 #define TOK_LBRACKET 8
3088 #define TOK_RBRACKET 9
3089 #define TOK_LPAREN 10
3090 #define TOK_RPAREN 11
3095 #define TOK_TIMESEQ 16
3096 #define TOK_DIVEQ 17
3097 #define TOK_MODEQ 18
3098 #define TOK_PLUSEQ 19
3099 #define TOK_MINUSEQ 20
3102 #define TOK_ANDEQ 23
3103 #define TOK_XOREQ 24
3106 #define TOK_NOTEQ 27
3107 #define TOK_QUEST 28
3108 #define TOK_LOGOR 29
3109 #define TOK_LOGAND 30
3113 #define TOK_LESSEQ 34
3114 #define TOK_MOREEQ 35
3118 #define TOK_MINUS 39
3121 #define TOK_PLUSPLUS 42
3122 #define TOK_MINUSMINUS 43
3124 #define TOK_ARROW 45
3126 #define TOK_TILDE 47
3127 #define TOK_LIT_STRING 48
3128 #define TOK_LIT_CHAR 49
3129 #define TOK_LIT_INT 50
3130 #define TOK_LIT_FLOAT 51
3131 #define TOK_MACRO 52
3132 #define TOK_CONCATENATE 53
3134 #define TOK_IDENT 54
3135 #define TOK_STRUCT_NAME 55
3136 #define TOK_ENUM_CONST 56
3137 #define TOK_TYPE_NAME 57
3140 #define TOK_BREAK 59
3143 #define TOK_CONST 62
3144 #define TOK_CONTINUE 63
3145 #define TOK_DEFAULT 64
3147 #define TOK_DOUBLE 66
3150 #define TOK_EXTERN 69
3151 #define TOK_FLOAT 70
3155 #define TOK_INLINE 74
3158 #define TOK_REGISTER 77
3159 #define TOK_RESTRICT 78
3160 #define TOK_RETURN 79
3161 #define TOK_SHORT 80
3162 #define TOK_SIGNED 81
3163 #define TOK_SIZEOF 82
3164 #define TOK_STATIC 83
3165 #define TOK_STRUCT 84
3166 #define TOK_SWITCH 85
3167 #define TOK_TYPEDEF 86
3168 #define TOK_UNION 87
3169 #define TOK_UNSIGNED 88
3171 #define TOK_VOLATILE 90
3172 #define TOK_WHILE 91
3174 #define TOK_ATTRIBUTE 93
3175 #define TOK_ALIGNOF 94
3176 #define TOK_FIRST_KEYWORD TOK_AUTO
3177 #define TOK_LAST_KEYWORD TOK_ALIGNOF
3179 #define TOK_DEFINE 100
3180 #define TOK_UNDEF 101
3181 #define TOK_INCLUDE 102
3182 #define TOK_LINE 103
3183 #define TOK_ERROR 104
3184 #define TOK_WARNING 105
3185 #define TOK_PRAGMA 106
3186 #define TOK_IFDEF 107
3187 #define TOK_IFNDEF 108
3188 #define TOK_ELIF 109
3189 #define TOK_ENDIF 110
3191 #define TOK_FIRST_MACRO TOK_DEFINE
3192 #define TOK_LAST_MACRO TOK_ENDIF
3194 #define TOK_DEFINED 111
3197 static const char *tokens[] = {
3198 [TOK_UNKNOWN ] = "unknown",
3199 [TOK_SPACE ] = ":space:",
3201 [TOK_LBRACE ] = "{",
3202 [TOK_RBRACE ] = "}",
3206 [TOK_LBRACKET ] = "[",
3207 [TOK_RBRACKET ] = "]",
3208 [TOK_LPAREN ] = "(",
3209 [TOK_RPAREN ] = ")",
3211 [TOK_DOTS ] = "...",
3214 [TOK_TIMESEQ ] = "*=",
3215 [TOK_DIVEQ ] = "/=",
3216 [TOK_MODEQ ] = "%=",
3217 [TOK_PLUSEQ ] = "+=",
3218 [TOK_MINUSEQ ] = "-=",
3219 [TOK_SLEQ ] = "<<=",
3220 [TOK_SREQ ] = ">>=",
3221 [TOK_ANDEQ ] = "&=",
3222 [TOK_XOREQ ] = "^=",
3225 [TOK_NOTEQ ] = "!=",
3227 [TOK_LOGOR ] = "||",
3228 [TOK_LOGAND ] = "&&",
3232 [TOK_LESSEQ ] = "<=",
3233 [TOK_MOREEQ ] = ">=",
3240 [TOK_PLUSPLUS ] = "++",
3241 [TOK_MINUSMINUS ] = "--",
3243 [TOK_ARROW ] = "->",
3246 [TOK_LIT_STRING ] = ":string:",
3247 [TOK_IDENT ] = ":ident:",
3248 [TOK_TYPE_NAME ] = ":typename:",
3249 [TOK_LIT_CHAR ] = ":char:",
3250 [TOK_LIT_INT ] = ":integer:",
3251 [TOK_LIT_FLOAT ] = ":float:",
3253 [TOK_CONCATENATE ] = "##",
3255 [TOK_AUTO ] = "auto",
3256 [TOK_BREAK ] = "break",
3257 [TOK_CASE ] = "case",
3258 [TOK_CHAR ] = "char",
3259 [TOK_CONST ] = "const",
3260 [TOK_CONTINUE ] = "continue",
3261 [TOK_DEFAULT ] = "default",
3263 [TOK_DOUBLE ] = "double",
3264 [TOK_ELSE ] = "else",
3265 [TOK_ENUM ] = "enum",
3266 [TOK_EXTERN ] = "extern",
3267 [TOK_FLOAT ] = "float",
3269 [TOK_GOTO ] = "goto",
3271 [TOK_INLINE ] = "inline",
3273 [TOK_LONG ] = "long",
3274 [TOK_REGISTER ] = "register",
3275 [TOK_RESTRICT ] = "restrict",
3276 [TOK_RETURN ] = "return",
3277 [TOK_SHORT ] = "short",
3278 [TOK_SIGNED ] = "signed",
3279 [TOK_SIZEOF ] = "sizeof",
3280 [TOK_STATIC ] = "static",
3281 [TOK_STRUCT ] = "struct",
3282 [TOK_SWITCH ] = "switch",
3283 [TOK_TYPEDEF ] = "typedef",
3284 [TOK_UNION ] = "union",
3285 [TOK_UNSIGNED ] = "unsigned",
3286 [TOK_VOID ] = "void",
3287 [TOK_VOLATILE ] = "volatile",
3288 [TOK_WHILE ] = "while",
3290 [TOK_ATTRIBUTE ] = "__attribute__",
3291 [TOK_ALIGNOF ] = "__alignof__",
3293 [TOK_DEFINE ] = "define",
3294 [TOK_UNDEF ] = "undef",
3295 [TOK_INCLUDE ] = "include",
3296 [TOK_LINE ] = "line",
3297 [TOK_ERROR ] = "error",
3298 [TOK_WARNING ] = "warning",
3299 [TOK_PRAGMA ] = "pragma",
3300 [TOK_IFDEF ] = "ifdef",
3301 [TOK_IFNDEF ] = "ifndef",
3302 [TOK_ELIF ] = "elif",
3303 [TOK_ENDIF ] = "endif",
3305 [TOK_DEFINED ] = "defined",
3309 static unsigned int hash(const char *str, int str_len)
3313 end = str + str_len;
3315 for(; str < end; str++) {
3316 hash = (hash *263) + *str;
3318 hash = hash & (HASH_TABLE_SIZE -1);
3322 static struct hash_entry *lookup(
3323 struct compile_state *state, const char *name, int name_len)
3325 struct hash_entry *entry;
3327 index = hash(name, name_len);
3328 entry = state->hash_table[index];
3330 ((entry->name_len != name_len) ||
3331 (memcmp(entry->name, name, name_len) != 0))) {
3332 entry = entry->next;
3336 /* Get a private copy of the name */
3337 new_name = xmalloc(name_len + 1, "hash_name");
3338 memcpy(new_name, name, name_len);
3339 new_name[name_len] = '\0';
3341 /* Create a new hash entry */
3342 entry = xcmalloc(sizeof(*entry), "hash_entry");
3343 entry->next = state->hash_table[index];
3344 entry->name = new_name;
3345 entry->name_len = name_len;
3347 /* Place the new entry in the hash table */
3348 state->hash_table[index] = entry;
3353 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3355 struct hash_entry *entry;
3357 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3358 (entry->tok == TOK_ENUM_CONST) ||
3359 ((entry->tok >= TOK_FIRST_KEYWORD) &&
3360 (entry->tok <= TOK_LAST_KEYWORD)))) {
3361 tk->tok = entry->tok;
3365 static void ident_to_macro(struct compile_state *state, struct token *tk)
3367 struct hash_entry *entry;
3370 (entry->tok >= TOK_FIRST_MACRO) &&
3371 (entry->tok <= TOK_LAST_MACRO)) {
3372 tk->tok = entry->tok;
3376 static void hash_keyword(
3377 struct compile_state *state, const char *keyword, int tok)
3379 struct hash_entry *entry;
3380 entry = lookup(state, keyword, strlen(keyword));
3381 if (entry && entry->tok != TOK_UNKNOWN) {
3382 die("keyword %s already hashed", keyword);
3387 static void romcc_symbol(
3388 struct compile_state *state, struct hash_entry *ident,
3389 struct symbol **chain, struct triple *def, struct type *type, int depth)
3392 if (*chain && ((*chain)->scope_depth >= depth)) {
3393 error(state, 0, "%s already defined", ident->name);
3395 sym = xcmalloc(sizeof(*sym), "symbol");
3399 sym->scope_depth = depth;
3405 struct compile_state *state, struct hash_entry *ident,
3406 struct symbol **chain, struct triple *def, struct type *type)
3408 romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3411 static void var_symbol(struct compile_state *state,
3412 struct hash_entry *ident, struct triple *def)
3414 if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3415 internal_error(state, 0, "bad var type");
3417 symbol(state, ident, &ident->sym_ident, def, def->type);
3420 static void label_symbol(struct compile_state *state,
3421 struct hash_entry *ident, struct triple *label, int depth)
3423 romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3426 static void start_scope(struct compile_state *state)
3428 state->scope_depth++;
3431 static void end_scope_syms(struct compile_state *state,
3432 struct symbol **chain, int depth)
3434 struct symbol *sym, *next;
3436 while(sym && (sym->scope_depth == depth)) {
3444 static void end_scope(struct compile_state *state)
3448 /* Walk through the hash table and remove all symbols
3449 * in the current scope.
3451 depth = state->scope_depth;
3452 for(i = 0; i < HASH_TABLE_SIZE; i++) {
3453 struct hash_entry *entry;
3454 entry = state->hash_table[i];
3456 end_scope_syms(state, &entry->sym_label, depth);
3457 end_scope_syms(state, &entry->sym_tag, depth);
3458 end_scope_syms(state, &entry->sym_ident, depth);
3459 entry = entry->next;
3462 state->scope_depth = depth - 1;
3465 static void register_keywords(struct compile_state *state)
3467 hash_keyword(state, "auto", TOK_AUTO);
3468 hash_keyword(state, "break", TOK_BREAK);
3469 hash_keyword(state, "case", TOK_CASE);
3470 hash_keyword(state, "char", TOK_CHAR);
3471 hash_keyword(state, "const", TOK_CONST);
3472 hash_keyword(state, "continue", TOK_CONTINUE);
3473 hash_keyword(state, "default", TOK_DEFAULT);
3474 hash_keyword(state, "do", TOK_DO);
3475 hash_keyword(state, "double", TOK_DOUBLE);
3476 hash_keyword(state, "else", TOK_ELSE);
3477 hash_keyword(state, "enum", TOK_ENUM);
3478 hash_keyword(state, "extern", TOK_EXTERN);
3479 hash_keyword(state, "float", TOK_FLOAT);
3480 hash_keyword(state, "for", TOK_FOR);
3481 hash_keyword(state, "goto", TOK_GOTO);
3482 hash_keyword(state, "if", TOK_IF);
3483 hash_keyword(state, "inline", TOK_INLINE);
3484 hash_keyword(state, "int", TOK_INT);
3485 hash_keyword(state, "long", TOK_LONG);
3486 hash_keyword(state, "register", TOK_REGISTER);
3487 hash_keyword(state, "restrict", TOK_RESTRICT);
3488 hash_keyword(state, "return", TOK_RETURN);
3489 hash_keyword(state, "short", TOK_SHORT);
3490 hash_keyword(state, "signed", TOK_SIGNED);
3491 hash_keyword(state, "sizeof", TOK_SIZEOF);
3492 hash_keyword(state, "static", TOK_STATIC);
3493 hash_keyword(state, "struct", TOK_STRUCT);
3494 hash_keyword(state, "switch", TOK_SWITCH);
3495 hash_keyword(state, "typedef", TOK_TYPEDEF);
3496 hash_keyword(state, "union", TOK_UNION);
3497 hash_keyword(state, "unsigned", TOK_UNSIGNED);
3498 hash_keyword(state, "void", TOK_VOID);
3499 hash_keyword(state, "volatile", TOK_VOLATILE);
3500 hash_keyword(state, "__volatile__", TOK_VOLATILE);
3501 hash_keyword(state, "while", TOK_WHILE);
3502 hash_keyword(state, "asm", TOK_ASM);
3503 hash_keyword(state, "__asm__", TOK_ASM);
3504 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3505 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
3508 static void register_macro_keywords(struct compile_state *state)
3510 hash_keyword(state, "define", TOK_DEFINE);
3511 hash_keyword(state, "undef", TOK_UNDEF);
3512 hash_keyword(state, "include", TOK_INCLUDE);
3513 hash_keyword(state, "line", TOK_LINE);
3514 hash_keyword(state, "error", TOK_ERROR);
3515 hash_keyword(state, "warning", TOK_WARNING);
3516 hash_keyword(state, "pragma", TOK_PRAGMA);
3517 hash_keyword(state, "ifdef", TOK_IFDEF);
3518 hash_keyword(state, "ifndef", TOK_IFNDEF);
3519 hash_keyword(state, "elif", TOK_ELIF);
3520 hash_keyword(state, "endif", TOK_ENDIF);
3524 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3526 if (ident->sym_define != 0) {
3527 struct macro *macro;
3528 struct macro_arg *arg, *anext;
3529 macro = ident->sym_define;
3530 ident->sym_define = 0;
3532 /* Free the macro arguments... */
3533 anext = macro->args;
3540 /* Free the macro buffer */
3543 /* Now free the macro itself */
3548 static void define_macro(
3549 struct compile_state *state,
3550 struct hash_entry *ident,
3551 const char *value, int value_len, int value_off,
3552 struct macro_arg *args)
3554 struct macro *macro;
3555 struct macro_arg *arg;
3556 macro = ident->sym_define;
3558 /* Explicitly allow identical redefinitions of the same macro */
3559 if ((macro->buf_len == value_len) &&
3560 (memcmp(macro->buf, value, value_len))) {
3563 error(state, 0, "macro %s already defined\n", ident->name);
3566 fprintf(state->errout, "%s: `%*.*s'\n",
3568 value_len - value_off,
3569 value_len - value_off,
3572 macro = xmalloc(sizeof(*macro), "macro");
3573 macro->ident = ident;
3574 macro->buf_len = value_len;
3575 macro->buf_off = value_off;
3577 macro->buf = xmalloc(macro->buf_len + 2, "macro buf");
3580 for(arg = args; arg; arg = arg->next) {
3584 memcpy(macro->buf, value, macro->buf_len);
3585 macro->buf[macro->buf_len] = '\n';
3586 macro->buf[macro->buf_len+1] = '\0';
3588 ident->sym_define = macro;
3591 static void register_builtin_macro(struct compile_state *state,
3592 const char *name, const char *value)
3594 struct hash_entry *ident;
3596 if (value[0] == '(') {
3597 internal_error(state, 0, "Builtin macros with arguments not supported");
3599 ident = lookup(state, name, strlen(name));
3600 define_macro(state, ident, value, strlen(value), 0, 0);
3603 static void register_builtin_macros(struct compile_state *state)
3610 tm = localtime(&now);
3612 register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3613 register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3614 register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3615 register_builtin_macro(state, "__LINE__", "54321");
3617 strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3618 sprintf(buf, "\"%s\"", scratch);
3619 register_builtin_macro(state, "__DATE__", buf);
3621 strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3622 sprintf(buf, "\"%s\"", scratch);
3623 register_builtin_macro(state, "__TIME__", buf);
3625 /* I can't be a conforming implementation of C :( */
3626 register_builtin_macro(state, "__STDC__", "0");
3627 /* In particular I don't conform to C99 */
3628 register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3632 static void process_cmdline_macros(struct compile_state *state)
3634 const char **macro, *name;
3635 struct hash_entry *ident;
3636 for(macro = state->compiler->defines; (name = *macro); macro++) {
3640 name_len = strlen(name);
3641 body = strchr(name, '=');
3645 name_len = body - name;
3648 ident = lookup(state, name, name_len);
3649 define_macro(state, ident, body, strlen(body), 0, 0);
3651 for(macro = state->compiler->undefs; (name = *macro); macro++) {
3652 ident = lookup(state, name, strlen(name));
3653 undef_macro(state, ident);
3657 static int spacep(int c)
3673 static int digitp(int c)
3677 case '0': case '1': case '2': case '3': case '4':
3678 case '5': case '6': case '7': case '8': case '9':
3684 static int digval(int c)
3687 if ((c >= '0') && (c <= '9')) {
3693 static int hexdigitp(int c)
3697 case '0': case '1': case '2': case '3': case '4':
3698 case '5': case '6': case '7': case '8': case '9':
3699 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3700 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3706 static int hexdigval(int c)
3709 if ((c >= '0') && (c <= '9')) {
3712 else if ((c >= 'A') && (c <= 'F')) {
3713 val = 10 + (c - 'A');
3715 else if ((c >= 'a') && (c <= 'f')) {
3716 val = 10 + (c - 'a');
3721 static int octdigitp(int c)
3725 case '0': case '1': case '2': case '3':
3726 case '4': case '5': case '6': case '7':
3732 static int octdigval(int c)
3735 if ((c >= '0') && (c <= '7')) {
3741 static int letterp(int c)
3745 case 'a': case 'b': case 'c': case 'd': case 'e':
3746 case 'f': case 'g': case 'h': case 'i': case 'j':
3747 case 'k': case 'l': case 'm': case 'n': case 'o':
3748 case 'p': case 'q': case 'r': case 's': case 't':
3749 case 'u': case 'v': case 'w': case 'x': case 'y':
3751 case 'A': case 'B': case 'C': case 'D': case 'E':
3752 case 'F': case 'G': case 'H': case 'I': case 'J':
3753 case 'K': case 'L': case 'M': case 'N': case 'O':
3754 case 'P': case 'Q': case 'R': case 'S': case 'T':
3755 case 'U': case 'V': case 'W': case 'X': case 'Y':
3764 static const char *identifier(const char *str, const char *end)
3766 if (letterp(*str)) {
3767 for(; str < end; str++) {
3770 if (!letterp(c) && !digitp(c)) {
3778 static int char_value(struct compile_state *state,
3779 const signed char **strp, const signed char *end)
3781 const signed char *str;
3785 if ((c == '\\') && (str < end)) {
3787 case 'n': c = '\n'; str++; break;
3788 case 't': c = '\t'; str++; break;
3789 case 'v': c = '\v'; str++; break;
3790 case 'b': c = '\b'; str++; break;
3791 case 'r': c = '\r'; str++; break;
3792 case 'f': c = '\f'; str++; break;
3793 case 'a': c = '\a'; str++; break;
3794 case '\\': c = '\\'; str++; break;
3795 case '?': c = '?'; str++; break;
3796 case '\'': c = '\''; str++; break;
3797 case '"': c = '"'; str++; break;
3801 while((str < end) && hexdigitp(*str)) {
3803 c += hexdigval(*str);
3807 case '0': case '1': case '2': case '3':
3808 case '4': case '5': case '6': case '7':
3810 while((str < end) && octdigitp(*str)) {
3812 c += octdigval(*str);
3817 error(state, 0, "Invalid character constant");
3825 static const char *after_digits(const char *ptr, const char *end)
3827 while((ptr < end) && digitp(*ptr)) {
3833 static const char *after_octdigits(const char *ptr, const char *end)
3835 while((ptr < end) && octdigitp(*ptr)) {
3841 static const char *after_hexdigits(const char *ptr, const char *end)
3843 while((ptr < end) && hexdigitp(*ptr)) {
3849 static void save_string(struct compile_state *state,
3850 struct token *tk, const char *start, const char *end, const char *id)
3854 /* Create a private copy of the string */
3855 str_len = end - start + 1;
3856 str = xmalloc(str_len + 1, id);
3857 memcpy(str, start, str_len);
3858 str[str_len] = '\0';
3860 /* Store the copy in the token */
3862 tk->str_len = str_len;
3865 static int lparen_peek(struct compile_state *state, struct file_state *file)
3867 const char *tokp, *end;
3868 /* Is the next token going to be an lparen?
3869 * Whitespace tokens are significant for seeing if a macro
3870 * should be expanded.
3873 end = file->buf + file->size;
3874 return (tokp < end) && (*tokp == '(');
3877 static void raw_next_token(struct compile_state *state,
3878 struct file_state *file, struct token *tk)
3882 const char *tokp, *end;
3887 token = tokp = file->pos;
3888 end = file->buf + file->size;
3895 if ((tokp + 1) < end) {
3899 if ((tokp + 2) < end) {
3903 if ((tokp + 3) < end) {
3911 else if (spacep(c)) {
3913 while ((tokp < end) && spacep(c)) {
3916 file->report_line++;
3917 file->line_start = tokp + 1;
3926 else if ((c == '/') && (c1 == '/')) {
3928 for(tokp += 2; tokp < end; tokp++) {
3932 file->report_line++;
3933 file->line_start = tokp +1;
3939 else if ((c == '/') && (c1 == '*')) {
3941 const char *line_start;
3943 line_start = file->line_start;
3944 for(tokp += 2; (end - tokp) >= 2; tokp++) {
3948 line_start = tokp +1;
3950 else if ((c == '*') && (tokp[1] == '/')) {
3956 if (tok == TOK_UNKNOWN) {
3957 error(state, 0, "unterminated comment");
3959 file->report_line += line - file->line;
3961 file->line_start = line_start;
3963 /* string constants */
3964 else if ((c == '"') ||
3965 ((c == 'L') && (c1 == '"'))) {
3967 const char *line_start;
3970 line_start = file->line_start;
3976 for(tokp += 1; tokp < end; tokp++) {
3980 line_start = tokp + 1;
3982 else if ((c == '\\') && (tokp +1 < end)) {
3985 else if (c == '"') {
3986 tok = TOK_LIT_STRING;
3990 if (tok == TOK_UNKNOWN) {
3991 error(state, 0, "unterminated string constant");
3993 if (line != file->line) {
3994 warning(state, 0, "multiline string constant");
3996 file->report_line += line - file->line;
3998 file->line_start = line_start;
4000 /* Save the string value */
4001 save_string(state, tk, token, tokp, "literal string");
4003 /* character constants */
4004 else if ((c == '\'') ||
4005 ((c == 'L') && (c1 == '\''))) {
4007 const char *line_start;
4010 line_start = file->line_start;
4016 for(tokp += 1; tokp < end; tokp++) {
4020 line_start = tokp + 1;
4022 else if ((c == '\\') && (tokp +1 < end)) {
4025 else if (c == '\'') {
4030 if (tok == TOK_UNKNOWN) {
4031 error(state, 0, "unterminated character constant");
4033 if (line != file->line) {
4034 warning(state, 0, "multiline character constant");
4036 file->report_line += line - file->line;
4038 file->line_start = line_start;
4040 /* Save the character value */
4041 save_string(state, tk, token, tokp, "literal character");
4043 /* integer and floating constants
4049 * Floating constants
4050 * {digits}.{digits}[Ee][+-]?{digits}
4052 * {digits}[Ee][+-]?{digits}
4053 * .{digits}[Ee][+-]?{digits}
4057 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4058 const char *next, *new;
4062 next = after_digits(tokp, end);
4067 if (next[0] == '.') {
4068 new = after_digits(next, end);
4069 is_float = (new != next);
4072 if ((next[0] == 'e') || (next[0] == 'E')) {
4073 if (((next + 1) < end) &&
4074 ((next[1] == '+') || (next[1] == '-'))) {
4077 new = after_digits(next, end);
4078 is_float = (new != next);
4082 tok = TOK_LIT_FLOAT;
4083 if ((next < end) && (
4092 if (!is_float && digitp(c)) {
4094 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4095 next = after_hexdigits(tokp + 2, end);
4097 else if (c == '0') {
4098 next = after_octdigits(tokp, end);
4101 next = after_digits(tokp, end);
4103 /* crazy integer suffixes */
4105 ((next[0] == 'u') || (next[0] == 'U'))) {
4108 ((next[0] == 'l') || (next[0] == 'L'))) {
4112 else if ((next < end) &&
4113 ((next[0] == 'l') || (next[0] == 'L'))) {
4116 ((next[0] == 'u') || (next[0] == 'U'))) {
4123 /* Save the integer/floating point value */
4124 save_string(state, tk, token, tokp, "literal number");
4127 else if (letterp(c)) {
4129 tokp = identifier(tokp, end);
4131 tk->ident = lookup(state, token, tokp +1 - token);
4132 /* See if this identifier can be macro expanded */
4133 tk->val.notmacro = 0;
4134 if ((tokp < end) && (tokp[1] == '$')) {
4136 tk->val.notmacro = 1;
4139 /* C99 alternate macro characters */
4140 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
4142 tok = TOK_CONCATENATE;
4144 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
4145 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
4146 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
4147 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
4148 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
4149 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
4150 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
4151 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
4152 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
4153 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
4154 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
4155 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
4156 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
4157 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
4158 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
4159 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
4160 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
4161 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
4162 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
4163 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
4164 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
4165 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
4166 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
4167 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
4168 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
4169 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
4170 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
4171 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
4172 else if (c == ';') { tok = TOK_SEMI; }
4173 else if (c == '{') { tok = TOK_LBRACE; }
4174 else if (c == '}') { tok = TOK_RBRACE; }
4175 else if (c == ',') { tok = TOK_COMMA; }
4176 else if (c == '=') { tok = TOK_EQ; }
4177 else if (c == ':') { tok = TOK_COLON; }
4178 else if (c == '[') { tok = TOK_LBRACKET; }
4179 else if (c == ']') { tok = TOK_RBRACKET; }
4180 else if (c == '(') { tok = TOK_LPAREN; }
4181 else if (c == ')') { tok = TOK_RPAREN; }
4182 else if (c == '*') { tok = TOK_STAR; }
4183 else if (c == '>') { tok = TOK_MORE; }
4184 else if (c == '<') { tok = TOK_LESS; }
4185 else if (c == '?') { tok = TOK_QUEST; }
4186 else if (c == '|') { tok = TOK_OR; }
4187 else if (c == '&') { tok = TOK_AND; }
4188 else if (c == '^') { tok = TOK_XOR; }
4189 else if (c == '+') { tok = TOK_PLUS; }
4190 else if (c == '-') { tok = TOK_MINUS; }
4191 else if (c == '/') { tok = TOK_DIV; }
4192 else if (c == '%') { tok = TOK_MOD; }
4193 else if (c == '!') { tok = TOK_BANG; }
4194 else if (c == '.') { tok = TOK_DOT; }
4195 else if (c == '~') { tok = TOK_TILDE; }
4196 else if (c == '#') { tok = TOK_MACRO; }
4198 file->pos = tokp + 1;
4200 if (tok == TOK_IDENT) {
4201 ident_to_keyword(state, tk);
4205 static void next_token(struct compile_state *state, struct token *tk)
4207 struct file_state *file;
4209 /* Don't return space tokens. */
4211 raw_next_token(state, file, tk);
4212 if (tk->tok == TOK_MACRO) {
4213 /* Only match preprocessor directives at the start of a line */
4215 for(ptr = file->line_start; spacep(*ptr); ptr++)
4217 if (ptr != file->pos - 1) {
4218 tk->tok = TOK_UNKNOWN;
4221 if (tk->tok == TOK_UNKNOWN) {
4222 error(state, 0, "unknown token");
4224 } while(tk->tok == TOK_SPACE);
4227 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4229 if (tk->tok != tok) {
4230 const char *name1, *name2;
4231 name1 = tokens[tk->tok];
4233 if (tk->tok == TOK_IDENT) {
4234 name2 = tk->ident->name;
4236 error(state, 0, "\tfound %s %s expected %s",
4237 name1, name2, tokens[tok]);
4241 struct macro_arg_value {
4242 struct hash_entry *ident;
4243 unsigned char *value;
4246 static struct macro_arg_value *read_macro_args(
4247 struct compile_state *state, struct macro *macro,
4248 struct file_state *file, struct token *tk)
4250 struct macro_arg_value *argv;
4251 struct macro_arg *arg;
4255 if (macro->argc == 0) {
4257 raw_next_token(state, file, tk);
4258 } while(tk->tok == TOK_SPACE);
4261 argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4262 for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4265 argv[i].ident = arg->ident;
4274 raw_next_token(state, file, tk);
4276 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4277 (argv[i].ident != state->i___VA_ARGS__))
4280 if (i >= macro->argc) {
4281 error(state, 0, "too many args to %s\n",
4282 macro->ident->name);
4287 if (tk->tok == TOK_LPAREN) {
4291 if (tk->tok == TOK_RPAREN) {
4292 if (paren_depth == 0) {
4297 if (tk->tok == TOK_EOF) {
4298 error(state, 0, "End of file encountered while parsing macro arguments");
4301 len = file->pos - start;
4302 argv[i].value = xrealloc(
4303 argv[i].value, argv[i].len + len, "macro args");
4304 memcpy(argv[i].value + argv[i].len, start, len);
4307 if (i != macro->argc -1) {
4308 error(state, 0, "missing %s arg %d\n",
4309 macro->ident->name, i +2);
4315 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4318 for(i = 0; i < macro->argc; i++) {
4319 xfree(argv[i].value);
4329 static void append_macro_text(struct compile_state *state,
4330 struct macro *macro, struct macro_buf *buf,
4331 const char *fstart, size_t flen)
4334 fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4335 buf->pos, buf->pos, buf->str,
4336 flen, flen, fstart);
4338 if ((buf->pos + flen) < buf->len) {
4339 memcpy(buf->str + buf->pos, fstart, flen);
4341 buf->str = xrealloc(buf->str, buf->len + flen, macro->ident->name);
4342 memcpy(buf->str + buf->pos, fstart, flen);
4348 static int compile_macro(struct compile_state *state,
4349 struct file_state **filep, struct token *tk);
4351 static void macro_expand_args(struct compile_state *state,
4352 struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4356 for(i = 0; i < macro->argc; i++) {
4357 struct file_state fmacro, *file;
4358 struct macro_buf buf;
4362 fmacro.basename = argv[i].ident->name;
4363 fmacro.dirname = "";
4364 fmacro.size = argv[i].len;
4365 fmacro.buf = argv[i].value;
4366 fmacro.pos = fmacro.buf;
4367 fmacro.line_start = fmacro.buf;
4369 fmacro.report_line = 1;
4370 fmacro.report_name = fmacro.basename;
4371 fmacro.report_dir = fmacro.dirname;
4374 buf.len = argv[i].len;
4375 buf.str = xmalloc(buf.len, argv[i].ident->name);
4381 raw_next_token(state, file, tk);
4382 flen = file->pos - fstart;
4384 if (tk->tok == TOK_EOF) {
4385 struct file_state *old;
4391 /* old->basename is used keep it */
4392 xfree(old->dirname);
4397 else if (tk->ident && tk->ident->sym_define) {
4398 if (compile_macro(state, &file, tk)) {
4403 append_macro_text(state, macro, &buf,
4407 xfree(argv[i].value);
4408 argv[i].value = buf.str;
4409 argv[i].len = buf.pos;
4414 static void expand_macro(struct compile_state *state,
4415 struct macro *macro, struct macro_buf *buf,
4416 struct macro_arg_value *argv, struct token *tk)
4418 struct file_state fmacro;
4419 const char space[] = " ";
4423 fmacro.basename = macro->ident->name;
4424 fmacro.dirname = "";
4425 fmacro.size = macro->buf_len - macro->buf_off;;
4426 fmacro.buf = macro->buf + macro->buf_off;
4427 fmacro.pos = fmacro.buf;
4428 fmacro.line_start = fmacro.buf;
4430 fmacro.report_line = 1;
4431 fmacro.report_name = fmacro.basename;
4432 fmacro.report_dir = fmacro.dirname;
4435 buf->len = macro->buf_len + 3;
4436 buf->str = xmalloc(buf->len, macro->ident->name);
4439 fstart = fmacro.pos;
4440 raw_next_token(state, &fmacro, tk);
4441 while(tk->tok != TOK_EOF) {
4442 flen = fmacro.pos - fstart;
4445 for(i = 0; i < macro->argc; i++) {
4446 if (argv[i].ident == tk->ident) {
4450 if (i >= macro->argc) {
4453 /* Substitute macro parameter */
4454 fstart = argv[i].value;
4458 if (!macro->buf_off) {
4462 raw_next_token(state, &fmacro, tk);
4463 } while(tk->tok == TOK_SPACE);
4464 check_tok(state, tk, TOK_IDENT);
4465 for(i = 0; i < macro->argc; i++) {
4466 if (argv[i].ident == tk->ident) {
4470 if (i >= macro->argc) {
4471 error(state, 0, "parameter `%s' not found",
4474 /* Stringize token */
4475 append_macro_text(state, macro, buf, "\"", 1);
4476 for(j = 0; j < argv[i].len; j++) {
4477 char *str = argv[i].value + j;
4483 else if (*str == '"') {
4487 append_macro_text(state, macro, buf, str, len);
4489 append_macro_text(state, macro, buf, "\"", 1);
4493 case TOK_CONCATENATE:
4494 /* Concatenate tokens */
4495 /* Delete the previous whitespace token */
4496 if (buf->str[buf->pos - 1] == ' ') {
4499 /* Skip the next sequence of whitspace tokens */
4501 fstart = fmacro.pos;
4502 raw_next_token(state, &fmacro, tk);
4503 } while(tk->tok == TOK_SPACE);
4504 /* Restart at the top of the loop.
4505 * I need to process the non white space token.
4510 /* Collapse multiple spaces into one */
4511 if (buf->str[buf->pos - 1] != ' ') {
4523 append_macro_text(state, macro, buf, fstart, flen);
4525 fstart = fmacro.pos;
4526 raw_next_token(state, &fmacro, tk);
4530 static void tag_macro_name(struct compile_state *state,
4531 struct macro *macro, struct macro_buf *buf,
4534 /* Guard all instances of the macro name in the replacement
4535 * text from further macro expansion.
4537 struct file_state fmacro;
4540 fmacro.basename = macro->ident->name;
4541 fmacro.dirname = "";
4542 fmacro.size = buf->pos;
4543 fmacro.buf = buf->str;
4544 fmacro.pos = fmacro.buf;
4545 fmacro.line_start = fmacro.buf;
4547 fmacro.report_line = 1;
4548 fmacro.report_name = fmacro.basename;
4549 fmacro.report_dir = fmacro.dirname;
4552 buf->len = macro->buf_len + 3;
4553 buf->str = xmalloc(buf->len, macro->ident->name);
4556 fstart = fmacro.pos;
4557 raw_next_token(state, &fmacro, tk);
4558 while(tk->tok != TOK_EOF) {
4559 flen = fmacro.pos - fstart;
4560 if ((tk->tok == TOK_IDENT) &&
4561 (tk->ident == macro->ident) &&
4562 (tk->val.notmacro == 0)) {
4563 append_macro_text(state, macro, buf, fstart, flen);
4568 append_macro_text(state, macro, buf, fstart, flen);
4570 fstart = fmacro.pos;
4571 raw_next_token(state, &fmacro, tk);
4576 static int compile_macro(struct compile_state *state,
4577 struct file_state **filep, struct token *tk)
4579 struct file_state *file;
4580 struct hash_entry *ident;
4581 struct macro *macro;
4582 struct macro_arg_value *argv;
4583 struct macro_buf buf;
4586 fprintf(state->errout, "macro: %s\n", tk->ident->name);
4589 macro = ident->sym_define;
4591 /* If this token comes from a macro expansion ignore it */
4592 if (tk->val.notmacro) {
4595 /* If I am a function like macro and the identifier is not followed
4596 * by a left parenthesis, do nothing.
4598 if ((macro->buf_off != 0) && !lparen_peek(state, *filep)) {
4602 /* Read in the macro arguments */
4604 if (macro->buf_off) {
4605 raw_next_token(state, *filep, tk);
4606 check_tok(state, tk, TOK_LPAREN);
4608 argv = read_macro_args(state, macro, *filep, tk);
4610 check_tok(state, tk, TOK_RPAREN);
4612 /* Macro expand the macro arguments */
4613 macro_expand_args(state, macro, argv, tk);
4618 if (ident == state->i___FILE__) {
4619 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4620 buf.str = xmalloc(buf.len, ident->name);
4621 sprintf(buf.str, "\"%s\"", state->file->basename);
4622 buf.pos = strlen(buf.str);
4624 else if (ident == state->i___LINE__) {
4626 buf.str = xmalloc(buf.len, ident->name);
4627 sprintf(buf.str, "%d", state->file->line);
4628 buf.pos = strlen(buf.str);
4631 expand_macro(state, macro, &buf, argv, tk);
4633 /* Tag the macro name with a $ so it will no longer
4634 * be regonized as a canidate for macro expansion.
4636 tag_macro_name(state, macro, &buf, tk);
4637 append_macro_text(state, macro, &buf, "\n\0", 2);
4640 fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4641 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4644 free_macro_args(macro, argv);
4646 file = xmalloc(sizeof(*file), "file_state");
4647 file->basename = xstrdup(ident->name);
4648 file->dirname = xstrdup("");
4649 file->buf = buf.str;
4650 file->size = buf.pos - 2;
4651 file->pos = file->buf;
4652 file->line_start = file->pos;
4654 file->report_line = 1;
4655 file->report_name = file->basename;
4656 file->report_dir = file->dirname;
4657 file->prev = *filep;
4663 static int mpeek(struct compile_state *state, int index)
4667 tk = &state->token[index + 1];
4668 if (tk->tok == -1) {
4670 raw_next_token(state, state->file, tk);
4671 } while(tk->tok == TOK_SPACE);
4675 if ((tk->tok == TOK_EOF) &&
4676 (state->file != state->macro_file) &&
4677 (state->file->prev)) {
4678 struct file_state *file = state->file;
4679 state->file = file->prev;
4680 /* file->basename is used keep it */
4681 if (file->report_dir != file->dirname) {
4682 xfree(file->report_dir);
4684 xfree(file->dirname);
4687 next_token(state, tk);
4690 else if (tk->ident && tk->ident->sym_define) {
4691 rescan = compile_macro(state, &state->file, tk);
4693 next_token(state, tk);
4698 /* Don't show the token on the next line */
4699 if (state->macro_line < state->macro_file->line) {
4705 static void meat(struct compile_state *state, int index, int tok)
4709 next_tok = mpeek(state, index);
4710 if (next_tok != tok) {
4711 check_tok(state, &state->token[index + 1], tok);
4714 /* Free the old token value */
4715 if (state->token[index].str_len) {
4716 memset((void *)(state->token[index].val.str), -1,
4717 state->token[index].str_len);
4718 xfree(state->token[index].val.str);
4720 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4721 state->token[i] = state->token[i + 1];
4723 memset(&state->token[i], 0, sizeof(state->token[i]));
4724 state->token[i].tok = -1;
4727 static int mpeek_raw(struct compile_state *state, int index)
4731 tk = &state->token[index + 1];
4732 if (tk->tok == -1) {
4734 raw_next_token(state, state->file, tk);
4735 } while(tk->tok == TOK_SPACE);
4739 if ((tk->tok == TOK_EOF) &&
4740 (state->file != state->macro_file) &&
4741 (state->file->prev)) {
4742 struct file_state *file = state->file;
4743 state->file = file->prev;
4744 /* file->basename is used keep it */
4745 if (file->report_dir != file->dirname) {
4746 xfree(file->report_dir);
4748 xfree(file->dirname);
4751 next_token(state, tk);
4755 /* Don't show the token on the next line */
4756 if (state->macro_line < state->macro_file->line) {
4762 static void meat_raw(struct compile_state *state, int index, int tok)
4766 next_tok = mpeek_raw(state, index);
4767 if (next_tok != tok) {
4768 check_tok(state, &state->token[index + 1], tok);
4771 /* Free the old token value */
4772 if (state->token[index].str_len) {
4773 memset((void *)(state->token[index].val.str), -1,
4774 state->token[index].str_len);
4775 xfree(state->token[index].val.str);
4777 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4778 state->token[i] = state->token[i + 1];
4780 memset(&state->token[i], 0, sizeof(state->token[i]));
4781 state->token[i].tok = -1;
4784 static long_t mcexpr(struct compile_state *state, int index);
4786 static long_t mprimary_expr(struct compile_state *state, int index)
4790 tok = mpeek(state, index);
4793 meat(state, index, TOK_LPAREN);
4794 val = mcexpr(state, index);
4795 meat(state, index, TOK_RPAREN);
4801 meat(state, index, TOK_LIT_INT);
4803 lval = strtol(state->token[index].val.str, &end, 0);
4804 if ((lval > LONG_T_MAX) || (lval < LONG_T_MIN) ||
4805 (((lval == LONG_MIN) || (lval == LONG_MAX)) &&
4806 (errno == ERANGE))) {
4807 error(state, 0, "Integer constant to large");
4813 meat(state, index, TOK_LIT_INT);
4818 static long_t munary_expr(struct compile_state *state, int index)
4822 tok = mpeek(state, index);
4823 if ((tok == TOK_IDENT) &&
4824 (state->token[index + 1].ident == state->i_defined)) {
4829 meat(state, index, TOK_PLUS);
4830 val = munary_expr(state, index);
4834 meat(state, index, TOK_MINUS);
4835 val = munary_expr(state, index);
4839 meat(state, index, TOK_BANG);
4840 val = munary_expr(state, index);
4844 meat(state, index, TOK_BANG);
4845 val = munary_expr(state, index);
4850 struct hash_entry *ident;
4852 meat(state, index, TOK_IDENT);
4854 if (mpeek_raw(state, index) == TOK_LPAREN) {
4855 meat(state, index, TOK_LPAREN);
4858 meat_raw(state, index, TOK_IDENT);
4859 ident = state->token[index].ident;
4860 val = ident->sym_define != 0;
4862 meat(state, index, TOK_RPAREN);
4867 val = mprimary_expr(state, index);
4873 static long_t mmul_expr(struct compile_state *state, int index)
4877 val = munary_expr(state, index);
4881 switch(mpeek(state, index)) {
4883 meat(state, index, TOK_STAR);
4884 right = munary_expr(state, index);
4888 meat(state, index, TOK_DIV);
4889 right = munary_expr(state, index);
4893 meat(state, index, TOK_MOD);
4894 right = munary_expr(state, index);
4906 static long_t madd_expr(struct compile_state *state, int index)
4910 val = mmul_expr(state, index);
4914 switch(mpeek(state, index)) {
4916 meat(state, index, TOK_PLUS);
4917 right = mmul_expr(state, index);
4921 meat(state, index, TOK_MINUS);
4922 right = mmul_expr(state, index);
4934 static long_t mshift_expr(struct compile_state *state, int index)
4938 val = madd_expr(state, index);
4942 switch(mpeek(state, index)) {
4944 meat(state, index, TOK_SL);
4945 right = madd_expr(state, index);
4949 meat(state, index, TOK_SR);
4950 right = madd_expr(state, index);
4962 static long_t mrel_expr(struct compile_state *state, int index)
4966 val = mshift_expr(state, index);
4970 switch(mpeek(state, index)) {
4972 meat(state, index, TOK_LESS);
4973 right = mshift_expr(state, index);
4977 meat(state, index, TOK_MORE);
4978 right = mshift_expr(state, index);
4982 meat(state, index, TOK_LESSEQ);
4983 right = mshift_expr(state, index);
4987 meat(state, index, TOK_MOREEQ);
4988 right = mshift_expr(state, index);
4999 static long_t meq_expr(struct compile_state *state, int index)
5003 val = mrel_expr(state, index);
5007 switch(mpeek(state, index)) {
5009 meat(state, index, TOK_EQEQ);
5010 right = mrel_expr(state, index);
5014 meat(state, index, TOK_NOTEQ);
5015 right = mrel_expr(state, index);
5026 static long_t mand_expr(struct compile_state *state, int index)
5029 val = meq_expr(state, index);
5030 while (mpeek(state, index) == TOK_AND) {
5032 meat(state, index, TOK_AND);
5033 right = meq_expr(state, index);
5039 static long_t mxor_expr(struct compile_state *state, int index)
5042 val = mand_expr(state, index);
5043 while (mpeek(state, index) == TOK_XOR) {
5045 meat(state, index, TOK_XOR);
5046 right = mand_expr(state, index);
5052 static long_t mor_expr(struct compile_state *state, int index)
5055 val = mxor_expr(state, index);
5056 while (mpeek(state, index) == TOK_OR) {
5058 meat(state, index, TOK_OR);
5059 right = mxor_expr(state, index);
5065 static long_t mland_expr(struct compile_state *state, int index)
5068 val = mor_expr(state, index);
5069 while (mpeek(state, index) == TOK_LOGAND) {
5071 meat(state, index, TOK_LOGAND);
5072 right = mor_expr(state, index);
5077 static long_t mlor_expr(struct compile_state *state, int index)
5080 val = mland_expr(state, index);
5081 while (mpeek(state, index) == TOK_LOGOR) {
5083 meat(state, index, TOK_LOGOR);
5084 right = mland_expr(state, index);
5090 static long_t mcexpr(struct compile_state *state, int index)
5092 return mlor_expr(state, index);
5095 static void eat_tokens(struct compile_state *state, int targ_tok)
5097 if (state->eat_depth > 0) {
5098 internal_error(state, 0, "Already eating...");
5100 state->eat_depth = state->if_depth;
5101 state->eat_targ = targ_tok;
5103 static int if_eat(struct compile_state *state)
5105 return state->eat_depth > 0;
5107 static int if_value(struct compile_state *state)
5110 index = state->if_depth / CHAR_BIT;
5111 offset = state->if_depth % CHAR_BIT;
5112 return !!(state->if_bytes[index] & (1 << (offset)));
5114 static void set_if_value(struct compile_state *state, int value)
5117 index = state->if_depth / CHAR_BIT;
5118 offset = state->if_depth % CHAR_BIT;
5120 state->if_bytes[index] &= ~(1 << offset);
5122 state->if_bytes[index] |= (1 << offset);
5125 static void in_if(struct compile_state *state, const char *name)
5127 if (state->if_depth <= 0) {
5128 error(state, 0, "%s without #if", name);
5131 static void enter_if(struct compile_state *state)
5133 state->if_depth += 1;
5134 if (state->if_depth > MAX_CPP_IF_DEPTH) {
5135 error(state, 0, "#if depth too great");
5138 static void reenter_if(struct compile_state *state, const char *name)
5141 if ((state->eat_depth == state->if_depth) &&
5142 (state->eat_targ == TOK_ELSE)) {
5143 state->eat_depth = 0;
5144 state->eat_targ = 0;
5147 static void enter_else(struct compile_state *state, const char *name)
5150 if ((state->eat_depth == state->if_depth) &&
5151 (state->eat_targ == TOK_ELSE)) {
5152 state->eat_depth = 0;
5153 state->eat_targ = 0;
5156 static void exit_if(struct compile_state *state, const char *name)
5159 if (state->eat_depth == state->if_depth) {
5160 state->eat_depth = 0;
5161 state->eat_targ = 0;
5163 state->if_depth -= 1;
5166 static void preprocess(struct compile_state *state, int index)
5168 /* Doing much more with the preprocessor would require
5169 * a parser and a major restructuring.
5170 * Postpone that for later.
5172 struct file_state *file;
5178 tk = &state->token[index];
5179 state->macro_line = line = file->line;
5180 state->macro_file = file;
5182 next_token(state, tk);
5183 ident_to_macro(state, tk);
5184 if (tk->tok == TOK_IDENT) {
5185 error(state, 0, "undefined preprocessing directive `%s'",
5192 override_line = strtoul(tk->val.str, 0, 10);
5193 next_token(state, tk);
5194 /* I have a cpp line marker parse it */
5195 if (tk->tok == TOK_LIT_STRING) {
5196 const char *token, *base;
5198 int name_len, dir_len;
5199 name = xmalloc(tk->str_len, "report_name");
5200 token = tk->val.str + 1;
5201 base = strrchr(token, '/');
5202 name_len = tk->str_len -2;
5204 dir_len = base - token;
5206 name_len -= base - token;
5211 memcpy(name, base, name_len);
5212 name[name_len] = '\0';
5213 dir = xmalloc(dir_len + 1, "report_dir");
5214 memcpy(dir, token, dir_len);
5215 dir[dir_len] = '\0';
5216 file->report_line = override_line - 1;
5217 file->report_name = name;
5218 file->report_dir = dir;
5223 meat(state, index, TOK_LIT_INT);
5224 file->report_line = strtoul(tk->val.str, 0, 10) -1;
5225 if (mpeek(state, index) == TOK_LIT_STRING) {
5226 const char *token, *base;
5228 int name_len, dir_len;
5229 meat(state, index, TOK_LIT_STRING);
5230 name = xmalloc(tk->str_len, "report_name");
5231 token = tk->val.str + 1;
5232 base = strrchr(token, '/');
5233 name_len = tk->str_len - 2;
5235 dir_len = base - token;
5237 name_len -= base - token;
5242 memcpy(name, base, name_len);
5243 name[name_len] = '\0';
5244 dir = xmalloc(dir_len + 1, "report_dir");
5245 memcpy(dir, token, dir_len);
5246 dir[dir_len] = '\0';
5247 file->report_name = name;
5248 file->report_dir = dir;
5253 struct hash_entry *ident;
5254 if (if_eat(state)) /* quit early when #if'd out */
5257 meat_raw(state, index, TOK_IDENT);
5260 undef_macro(state, ident);
5264 if (if_eat(state)) /* quit early when #if'd out */
5266 warning(state, 0, "Ignoring preprocessor directive: %s",
5270 reenter_if(state, "#elif");
5271 if (if_eat(state)) /* quit early when #if'd out */
5273 /* If the #if was taken the #elif just disables the following code */
5274 if (if_value(state)) {
5275 eat_tokens(state, TOK_ENDIF);
5277 /* If the previous #if was not taken see if the #elif enables the
5281 set_if_value(state, mcexpr(state, index) != 0);
5282 if (!if_value(state)) {
5283 eat_tokens(state, TOK_ELSE);
5289 if (if_eat(state)) /* quit early when #if'd out */
5291 set_if_value(state, mcexpr(state, index) != 0);
5292 if (!if_value(state)) {
5293 eat_tokens(state, TOK_ELSE);
5298 if (if_eat(state)) /* quit early when #if'd out */
5300 next_token(state, tk);
5301 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
5302 error(state, 0, "Invalid macro name");
5304 set_if_value(state, tk->ident->sym_define == 0);
5305 if (!if_value(state)) {
5306 eat_tokens(state, TOK_ELSE);
5311 if (if_eat(state)) /* quit early when #if'd out */
5313 next_token(state, tk);
5314 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
5315 error(state, 0, "Invalid macro name");
5317 set_if_value(state, tk->ident->sym_define != 0);
5318 if (!if_value(state)) {
5319 eat_tokens(state, TOK_ELSE);
5323 enter_else(state, "#else");
5324 if (!if_eat(state) && if_value(state)) {
5325 eat_tokens(state, TOK_ENDIF);
5329 exit_if(state, "#endif");
5333 struct hash_entry *ident;
5334 struct macro_arg *args, **larg;
5335 const char *start, *mstart, *ptr;
5337 if (if_eat(state)) /* quit early when #if'd out */
5340 meat_raw(state, index, TOK_IDENT);
5345 /* Remember the start of the macro */
5348 /* Find the end of the line. */
5349 for(ptr = start; *ptr != '\n'; ptr++)
5352 /* remove the trailing whitespace */
5353 while(spacep(*ptr)) {
5357 /* Remove leading whitespace */
5358 while(spacep(*start) && (start < ptr)) {
5361 /* Remember where the macro starts */
5364 /* Parse macro parameters */
5365 if (lparen_peek(state, state->file)) {
5366 meat_raw(state, index, TOK_LPAREN);
5369 struct macro_arg *narg, *arg;
5370 struct hash_entry *aident;
5373 tok = mpeek_raw(state, index);
5374 if (!args && (tok == TOK_RPAREN)) {
5377 else if (tok == TOK_DOTS) {
5378 meat_raw(state, index, TOK_DOTS);
5379 aident = state->i___VA_ARGS__;
5382 meat_raw(state, index, TOK_IDENT);
5386 narg = xcmalloc(sizeof(*arg), "macro arg");
5387 narg->ident = aident;
5389 /* Verify I don't have a duplicate identifier */
5390 for(arg = args; arg; arg = arg->next) {
5391 if (arg->ident == narg->ident) {
5392 error(state, 0, "Duplicate macro arg `%s'",
5396 /* Add the new argument to the end of the list */
5400 if ((aident == state->i___VA_ARGS__) ||
5401 (mpeek(state, index) != TOK_COMMA)) {
5404 meat_raw(state, index, TOK_COMMA);
5406 meat_raw(state, index, TOK_RPAREN);
5408 /* Get the start of the macro body */
5411 /* Remove leading whitespace */
5412 while(spacep(*mstart) && (mstart < ptr)) {
5416 define_macro(state, ident, start, ptr - start + 1,
5417 mstart - start, args);
5425 /* Find the end of the line */
5426 for(end = file->pos; *end != '\n'; end++)
5428 len = (end - file->pos);
5429 if (!if_eat(state)) {
5430 error(state, 0, "%*.*s", len, len, file->pos);
5440 /* Find the end of the line */
5441 for(end = file->pos; *end != '\n'; end++)
5443 len = (end - file->pos);
5444 if (!if_eat(state)) {
5445 warning(state, 0, "%*.*s", len, len, file->pos);
5457 next_token(state, tk);
5458 if (tk->tok == TOK_LIT_STRING) {
5461 name = xmalloc(tk->str_len, "include");
5462 token = tk->val.str +1;
5463 name_len = tk->str_len -2;
5464 if (*token == '"') {
5468 memcpy(name, token, name_len);
5469 name[name_len] = '\0';
5472 else if (tk->tok == TOK_LESS) {
5473 const char *start, *end;
5475 for(end = start; *end != '\n'; end++) {
5481 error(state, 0, "Unterminated included directive");
5483 name = xmalloc(end - start + 1, "include");
5484 memcpy(name, start, end - start);
5485 name[end - start] = '\0';
5490 error(state, 0, "Invalid include directive");
5492 /* Error if there are any characters after the include */
5493 for(ptr = file->pos; *ptr != '\n'; ptr++) {
5500 error(state, 0, "garbage after include directive");
5503 if (!if_eat(state)) {
5504 compile_file(state, name, local);
5507 next_token(state, tk);
5511 /* Ignore # without a following ident */
5512 if (tk->tok == TOK_IDENT) {
5513 error(state, 0, "Invalid preprocessor directive: %s",
5518 /* Consume the rest of the macro line */
5520 tok = mpeek_raw(state, index);
5521 meat_raw(state, index, tok);
5522 } while(tok != TOK_EOF);
5526 static void token(struct compile_state *state, int index)
5528 struct file_state *file;
5532 tk = &state->token[index];
5533 next_token(state, tk);
5537 if (tk->tok == TOK_EOF && file->prev) {
5538 state->file = file->prev;
5539 /* file->basename is used keep it */
5540 xfree(file->dirname);
5543 next_token(state, tk);
5546 else if (tk->tok == TOK_MACRO) {
5547 preprocess(state, index);
5550 else if (tk->ident && tk->ident->sym_define) {
5551 rescan = compile_macro(state, &state->file, tk);
5553 next_token(state, tk);
5556 else if (if_eat(state)) {
5557 next_token(state, tk);
5563 static int peek(struct compile_state *state)
5565 if (state->token[1].tok == -1) {
5568 return state->token[1].tok;
5571 static int peek2(struct compile_state *state)
5573 if (state->token[1].tok == -1) {
5576 if (state->token[2].tok == -1) {
5579 return state->token[2].tok;
5582 static void eat(struct compile_state *state, int tok)
5586 check_tok(state, &state->token[1], tok);
5588 /* Free the old token value */
5589 if (state->token[0].str_len) {
5590 xfree((void *)(state->token[0].val.str));
5592 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
5593 state->token[i] = state->token[i + 1];
5595 memset(&state->token[i], 0, sizeof(state->token[i]));
5596 state->token[i].tok = -1;
5599 static void compile_file(struct compile_state *state, const char *filename, int local)
5601 char cwd[MAX_CWD_SIZE];
5602 const char *subdir, *base;
5604 struct file_state *file;
5606 file = xmalloc(sizeof(*file), "file_state");
5608 base = strrchr(filename, '/');
5611 subdir_len = base - filename;
5618 basename = xmalloc(strlen(base) +1, "basename");
5619 strcpy(basename, base);
5620 file->basename = basename;
5622 if (getcwd(cwd, sizeof(cwd)) == 0) {
5623 die("cwd buffer to small");
5625 if (subdir[0] == '/') {
5626 file->dirname = xmalloc(subdir_len + 1, "dirname");
5627 memcpy(file->dirname, subdir, subdir_len);
5628 file->dirname[subdir_len] = '\0';
5634 /* Find the appropriate directory... */
5636 if (!state->file && exists(cwd, filename)) {
5639 if (local && state->file && exists(state->file->dirname, filename)) {
5640 dir = state->file->dirname;
5642 for(path = state->compiler->include_paths; !dir && *path; path++) {
5643 if (exists(*path, filename)) {
5648 error(state, 0, "Cannot find `%s'\n", filename);
5650 dirlen = strlen(dir);
5651 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5652 memcpy(file->dirname, dir, dirlen);
5653 file->dirname[dirlen] = '/';
5654 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5655 file->dirname[dirlen + 1 + subdir_len] = '\0';
5657 file->buf = slurp_file(file->dirname, file->basename, &file->size);
5659 file->pos = file->buf;
5660 file->line_start = file->pos;
5663 file->report_line = 1;
5664 file->report_name = file->basename;
5665 file->report_dir = file->dirname;
5667 file->prev = state->file;
5670 process_trigraphs(state);
5671 splice_lines(state);
5674 /* Type helper functions */
5676 static struct type *new_type(
5677 unsigned int type, struct type *left, struct type *right)
5679 struct type *result;
5680 result = xmalloc(sizeof(*result), "type");
5681 result->type = type;
5682 result->left = left;
5683 result->right = right;
5684 result->field_ident = 0;
5685 result->type_ident = 0;
5686 result->elements = 0;
5690 static struct type *clone_type(unsigned int specifiers, struct type *old)
5692 struct type *result;
5693 result = xmalloc(sizeof(*result), "type");
5694 memcpy(result, old, sizeof(*result));
5695 result->type &= TYPE_MASK;
5696 result->type |= specifiers;
5700 static struct type *dup_type(struct compile_state *state, struct type *orig)
5703 new = xcmalloc(sizeof(*new), "type");
5704 new->type = orig->type;
5705 new->field_ident = orig->field_ident;
5706 new->type_ident = orig->type_ident;
5707 new->elements = orig->elements;
5709 new->left = dup_type(state, orig->left);
5712 new->right = dup_type(state, orig->right);
5718 static struct type *invalid_type(struct compile_state *state, struct type *type)
5720 struct type *invalid, *member;
5723 internal_error(state, 0, "type missing?");
5725 switch(type->type & TYPE_MASK) {
5727 case TYPE_CHAR: case TYPE_UCHAR:
5728 case TYPE_SHORT: case TYPE_USHORT:
5729 case TYPE_INT: case TYPE_UINT:
5730 case TYPE_LONG: case TYPE_ULONG:
5731 case TYPE_LLONG: case TYPE_ULLONG:
5736 invalid = invalid_type(state, type->left);
5739 invalid = invalid_type(state, type->left);
5743 member = type->left;
5744 while(member && (invalid == 0) &&
5745 ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5746 invalid = invalid_type(state, member->left);
5747 member = member->right;
5750 invalid = invalid_type(state, member);
5755 member = type->left;
5756 while(member && (invalid == 0) &&
5757 ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5758 invalid = invalid_type(state, member->left);
5759 member = member->right;
5762 invalid = invalid_type(state, member);
5773 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
5774 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5775 static inline ulong_t mask_uint(ulong_t x)
5777 if (SIZEOF_INT < SIZEOF_LONG) {
5778 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT))) -1;
5783 #define MASK_UINT(X) (mask_uint(X))
5784 #define MASK_ULONG(X) (X)
5786 static struct type void_type = { .type = TYPE_VOID };
5787 static struct type char_type = { .type = TYPE_CHAR };
5788 static struct type uchar_type = { .type = TYPE_UCHAR };
5789 static struct type short_type = { .type = TYPE_SHORT };
5790 static struct type ushort_type = { .type = TYPE_USHORT };
5791 static struct type int_type = { .type = TYPE_INT };
5792 static struct type uint_type = { .type = TYPE_UINT };
5793 static struct type long_type = { .type = TYPE_LONG };
5794 static struct type ulong_type = { .type = TYPE_ULONG };
5795 static struct type unknown_type = { .type = TYPE_UNKNOWN };
5797 static struct type void_ptr_type = {
5798 .type = TYPE_POINTER,
5802 static struct type void_func_type = {
5803 .type = TYPE_FUNCTION,
5805 .right = &void_type,
5808 static size_t bits_to_bytes(size_t size)
5810 return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5813 static struct triple *variable(struct compile_state *state, struct type *type)
5815 struct triple *result;
5816 if ((type->type & STOR_MASK) != STOR_PERM) {
5817 result = triple(state, OP_ADECL, type, 0, 0);
5818 generate_lhs_pieces(state, result);
5821 result = triple(state, OP_SDECL, type, 0, 0);
5826 static void stor_of(FILE *fp, struct type *type)
5828 switch(type->type & STOR_MASK) {
5830 fprintf(fp, "auto ");
5833 fprintf(fp, "static ");
5836 fprintf(fp, "local ");
5839 fprintf(fp, "extern ");
5842 fprintf(fp, "register ");
5845 fprintf(fp, "typedef ");
5847 case STOR_INLINE | STOR_LOCAL:
5848 fprintf(fp, "inline ");
5850 case STOR_INLINE | STOR_STATIC:
5851 fprintf(fp, "static inline");
5853 case STOR_INLINE | STOR_EXTERN:
5854 fprintf(fp, "extern inline");
5857 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5861 static void qual_of(FILE *fp, struct type *type)
5863 if (type->type & QUAL_CONST) {
5864 fprintf(fp, " const");
5866 if (type->type & QUAL_VOLATILE) {
5867 fprintf(fp, " volatile");
5869 if (type->type & QUAL_RESTRICT) {
5870 fprintf(fp, " restrict");
5874 static void name_of(FILE *fp, struct type *type)
5876 unsigned int base_type;
5877 base_type = type->type & TYPE_MASK;
5878 if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5883 fprintf(fp, "void");
5887 fprintf(fp, "signed char");
5891 fprintf(fp, "unsigned char");
5895 fprintf(fp, "signed short");
5899 fprintf(fp, "unsigned short");
5903 fprintf(fp, "signed int");
5907 fprintf(fp, "unsigned int");
5911 fprintf(fp, "signed long");
5915 fprintf(fp, "unsigned long");
5919 name_of(fp, type->left);
5924 name_of(fp, type->left);
5926 name_of(fp, type->right);
5929 name_of(fp, type->left);
5931 name_of(fp, type->right);
5934 fprintf(fp, "enum %s",
5935 (type->type_ident)? type->type_ident->name : "");
5939 fprintf(fp, "struct %s { ",
5940 (type->type_ident)? type->type_ident->name : "");
5941 name_of(fp, type->left);
5946 fprintf(fp, "union %s { ",
5947 (type->type_ident)? type->type_ident->name : "");
5948 name_of(fp, type->left);
5953 name_of(fp, type->left);
5954 fprintf(fp, " (*)(");
5955 name_of(fp, type->right);
5959 name_of(fp, type->left);
5960 fprintf(fp, " [%ld]", (long)(type->elements));
5963 fprintf(fp, "tuple { ");
5964 name_of(fp, type->left);
5969 fprintf(fp, "join { ");
5970 name_of(fp, type->left);
5975 name_of(fp, type->left);
5976 fprintf(fp, " : %d ", type->elements);
5980 fprintf(fp, "unknown_t");
5983 fprintf(fp, "????: %x", base_type);
5986 if (type->field_ident && type->field_ident->name) {
5987 fprintf(fp, " .%s", type->field_ident->name);
5991 static size_t align_of(struct compile_state *state, struct type *type)
5995 switch(type->type & TYPE_MASK) {
6004 align = ALIGNOF_CHAR;
6008 align = ALIGNOF_SHORT;
6013 align = ALIGNOF_INT;
6017 align = ALIGNOF_LONG;
6020 align = ALIGNOF_POINTER;
6025 size_t left_align, right_align;
6026 left_align = align_of(state, type->left);
6027 right_align = align_of(state, type->right);
6028 align = (left_align >= right_align) ? left_align : right_align;
6032 align = align_of(state, type->left);
6038 align = align_of(state, type->left);
6041 error(state, 0, "alignof not yet defined for type\n");
6047 static size_t reg_align_of(struct compile_state *state, struct type *type)
6051 switch(type->type & TYPE_MASK) {
6060 align = REG_ALIGNOF_CHAR;
6064 align = REG_ALIGNOF_SHORT;
6069 align = REG_ALIGNOF_INT;
6073 align = REG_ALIGNOF_LONG;
6076 align = REG_ALIGNOF_POINTER;
6081 size_t left_align, right_align;
6082 left_align = reg_align_of(state, type->left);
6083 right_align = reg_align_of(state, type->right);
6084 align = (left_align >= right_align) ? left_align : right_align;
6088 align = reg_align_of(state, type->left);
6094 align = reg_align_of(state, type->left);
6097 error(state, 0, "alignof not yet defined for type\n");
6103 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
6105 return bits_to_bytes(align_of(state, type));
6107 static size_t size_of(struct compile_state *state, struct type *type);
6108 static size_t reg_size_of(struct compile_state *state, struct type *type);
6110 static size_t needed_padding(struct compile_state *state,
6111 struct type *type, size_t offset)
6113 size_t padding, align;
6114 align = align_of(state, type);
6115 /* Align to the next machine word if the bitfield does completely
6116 * fit into the current word.
6118 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
6120 size = size_of(state, type);
6121 if ((offset + type->elements)/size != offset/size) {
6126 if (offset % align) {
6127 padding = align - (offset % align);
6132 static size_t reg_needed_padding(struct compile_state *state,
6133 struct type *type, size_t offset)
6135 size_t padding, align;
6136 align = reg_align_of(state, type);
6137 /* Align to the next register word if the bitfield does completely
6138 * fit into the current register.
6140 if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
6141 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG)))
6143 align = REG_SIZEOF_REG;
6146 if (offset % align) {
6147 padding = align - (offset % align);
6152 static size_t size_of(struct compile_state *state, struct type *type)
6156 switch(type->type & TYPE_MASK) {
6161 size = type->elements;
6169 size = SIZEOF_SHORT;
6181 size = SIZEOF_POINTER;
6187 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6188 pad = needed_padding(state, type->left, size);
6189 size = size + pad + size_of(state, type->left);
6192 pad = needed_padding(state, type, size);
6193 size = size + pad + size_of(state, type);
6198 size_t size_left, size_right;
6199 size_left = size_of(state, type->left);
6200 size_right = size_of(state, type->right);
6201 size = (size_left >= size_right)? size_left : size_right;
6205 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6206 internal_error(state, 0, "Invalid array type");
6208 size = size_of(state, type->left) * type->elements;
6215 size = size_of(state, type->left);
6216 /* Pad structures so their size is a multiples of their alignment */
6217 pad = needed_padding(state, type, size);
6225 size = size_of(state, type->left);
6226 /* Pad unions so their size is a multiple of their alignment */
6227 pad = needed_padding(state, type, size);
6232 internal_error(state, 0, "sizeof not yet defined for type");
6238 static size_t reg_size_of(struct compile_state *state, struct type *type)
6242 switch(type->type & TYPE_MASK) {
6247 size = type->elements;
6251 size = REG_SIZEOF_CHAR;
6255 size = REG_SIZEOF_SHORT;
6260 size = REG_SIZEOF_INT;
6264 size = REG_SIZEOF_LONG;
6267 size = REG_SIZEOF_POINTER;
6273 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6274 pad = reg_needed_padding(state, type->left, size);
6275 size = size + pad + reg_size_of(state, type->left);
6278 pad = reg_needed_padding(state, type, size);
6279 size = size + pad + reg_size_of(state, type);
6284 size_t size_left, size_right;
6285 size_left = reg_size_of(state, type->left);
6286 size_right = reg_size_of(state, type->right);
6287 size = (size_left >= size_right)? size_left : size_right;
6291 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6292 internal_error(state, 0, "Invalid array type");
6294 size = reg_size_of(state, type->left) * type->elements;
6301 size = reg_size_of(state, type->left);
6302 /* Pad structures so their size is a multiples of their alignment */
6303 pad = reg_needed_padding(state, type, size);
6311 size = reg_size_of(state, type->left);
6312 /* Pad unions so their size is a multiple of their alignment */
6313 pad = reg_needed_padding(state, type, size);
6318 internal_error(state, 0, "sizeof not yet defined for type");
6324 static size_t registers_of(struct compile_state *state, struct type *type)
6327 registers = reg_size_of(state, type);
6328 registers += REG_SIZEOF_REG - 1;
6329 registers /= REG_SIZEOF_REG;
6333 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6335 return bits_to_bytes(size_of(state, type));
6338 static size_t field_offset(struct compile_state *state,
6339 struct type *type, struct hash_entry *field)
6341 struct type *member;
6346 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6347 member = type->left;
6348 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6349 size += needed_padding(state, member->left, size);
6350 if (member->left->field_ident == field) {
6351 member = member->left;
6354 size += size_of(state, member->left);
6355 member = member->right;
6357 size += needed_padding(state, member, size);
6359 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6360 member = type->left;
6361 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6362 if (member->left->field_ident == field) {
6363 member = member->left;
6366 member = member->right;
6370 internal_error(state, 0, "field_offset only works on structures and unions");
6373 if (!member || (member->field_ident != field)) {
6374 error(state, 0, "member %s not present", field->name);
6379 static size_t field_reg_offset(struct compile_state *state,
6380 struct type *type, struct hash_entry *field)
6382 struct type *member;
6387 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6388 member = type->left;
6389 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6390 size += reg_needed_padding(state, member->left, size);
6391 if (member->left->field_ident == field) {
6392 member = member->left;
6395 size += reg_size_of(state, member->left);
6396 member = member->right;
6399 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6400 member = type->left;
6401 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6402 if (member->left->field_ident == field) {
6403 member = member->left;
6406 member = member->right;
6410 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6413 size += reg_needed_padding(state, member, size);
6414 if (!member || (member->field_ident != field)) {
6415 error(state, 0, "member %s not present", field->name);
6420 static struct type *field_type(struct compile_state *state,
6421 struct type *type, struct hash_entry *field)
6423 struct type *member;
6426 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6427 member = type->left;
6428 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6429 if (member->left->field_ident == field) {
6430 member = member->left;
6433 member = member->right;
6436 else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6437 member = type->left;
6438 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6439 if (member->left->field_ident == field) {
6440 member = member->left;
6443 member = member->right;
6447 internal_error(state, 0, "field_type only works on structures and unions");
6450 if (!member || (member->field_ident != field)) {
6451 error(state, 0, "member %s not present", field->name);
6456 static size_t index_offset(struct compile_state *state,
6457 struct type *type, ulong_t index)
6459 struct type *member;
6462 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6463 size = size_of(state, type->left) * index;
6465 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6467 member = type->left;
6469 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6470 size += needed_padding(state, member->left, size);
6472 member = member->left;
6475 size += size_of(state, member->left);
6477 member = member->right;
6479 size += needed_padding(state, member, size);
6481 internal_error(state, 0, "Missing member index: %u", index);
6484 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6487 member = type->left;
6489 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6491 member = member->left;
6495 member = member->right;
6498 internal_error(state, 0, "Missing member index: %u", index);
6502 internal_error(state, 0,
6503 "request for index %u in something not an array, tuple or join",
6509 static size_t index_reg_offset(struct compile_state *state,
6510 struct type *type, ulong_t index)
6512 struct type *member;
6515 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6516 size = reg_size_of(state, type->left) * index;
6518 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6520 member = type->left;
6522 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6523 size += reg_needed_padding(state, member->left, size);
6525 member = member->left;
6528 size += reg_size_of(state, member->left);
6530 member = member->right;
6532 size += reg_needed_padding(state, member, size);
6534 internal_error(state, 0, "Missing member index: %u", index);
6538 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6541 member = type->left;
6543 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6545 member = member->left;
6549 member = member->right;
6552 internal_error(state, 0, "Missing member index: %u", index);
6556 internal_error(state, 0,
6557 "request for index %u in something not an array, tuple or join",
6563 static struct type *index_type(struct compile_state *state,
6564 struct type *type, ulong_t index)
6566 struct type *member;
6567 if (index >= type->elements) {
6568 internal_error(state, 0, "Invalid element %u requested", index);
6570 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6571 member = type->left;
6573 else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6575 member = type->left;
6577 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6579 member = member->left;
6583 member = member->right;
6586 internal_error(state, 0, "Missing member index: %u", index);
6589 else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6591 member = type->left;
6593 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6595 member = member->left;
6599 member = member->right;
6602 internal_error(state, 0, "Missing member index: %u", index);
6607 internal_error(state, 0,
6608 "request for index %u in something not an array, tuple or join",
6614 static struct type *unpack_type(struct compile_state *state, struct type *type)
6616 /* If I have a single register compound type not a bit-field
6617 * find the real type.
6619 struct type *start_type;
6621 /* Get out early if I need multiple registers for this type */
6622 size = reg_size_of(state, type);
6623 if (size > REG_SIZEOF_REG) {
6626 /* Get out early if I don't need any registers for this type */
6630 /* Loop until I have no more layers I can remove */
6633 switch(type->type & TYPE_MASK) {
6635 /* If I have a single element the unpacked type
6638 if (type->elements == 1) {
6644 /* If I have a single element the unpacked type
6647 if (type->elements == 1) {
6650 /* If I have multiple elements the unpacked
6651 * type is the non-void element.
6654 struct type *next, *member;
6655 struct type *sub_type;
6661 if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6662 next = member->right;
6663 member = member->left;
6665 if (reg_size_of(state, member) > 0) {
6667 internal_error(state, 0, "true compound type in a register");
6680 /* If I have a single element the unpacked type
6683 if (type->elements == 1) {
6686 /* I can't in general unpack union types */
6689 /* If I'm not a compound type I can't unpack it */
6692 } while(start_type != type);
6693 switch(type->type & TYPE_MASK) {
6697 internal_error(state, 0, "irredicible type?");
6703 static int equiv_types(struct type *left, struct type *right);
6704 static int is_compound_type(struct type *type);
6706 static struct type *reg_type(
6707 struct compile_state *state, struct type *type, int reg_offset)
6709 struct type *member;
6712 struct type *invalid;
6713 invalid = invalid_type(state, type);
6715 fprintf(state->errout, "type: ");
6716 name_of(state->errout, type);
6717 fprintf(state->errout, "\n");
6718 fprintf(state->errout, "invalid: ");
6719 name_of(state->errout, invalid);
6720 fprintf(state->errout, "\n");
6721 internal_error(state, 0, "bad input type?");
6725 size = reg_size_of(state, type);
6726 if (reg_offset > size) {
6728 fprintf(state->errout, "type: ");
6729 name_of(state->errout, type);
6730 fprintf(state->errout, "\n");
6731 internal_error(state, 0, "offset outside of type");
6734 switch(type->type & TYPE_MASK) {
6735 /* Don't do anything with the basic types */
6737 case TYPE_CHAR: case TYPE_UCHAR:
6738 case TYPE_SHORT: case TYPE_USHORT:
6739 case TYPE_INT: case TYPE_UINT:
6740 case TYPE_LONG: case TYPE_ULONG:
6741 case TYPE_LLONG: case TYPE_ULLONG:
6742 case TYPE_FLOAT: case TYPE_DOUBLE:
6750 member = type->left;
6751 size = reg_size_of(state, member);
6752 if (size > REG_SIZEOF_REG) {
6753 member = reg_type(state, member, reg_offset % size);
6761 member = type->left;
6762 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6763 size = reg_size_of(state, member->left);
6764 offset += reg_needed_padding(state, member->left, offset);
6765 if ((offset + size) > reg_offset) {
6766 member = member->left;
6770 member = member->right;
6772 offset += reg_needed_padding(state, member, offset);
6773 member = reg_type(state, member, reg_offset - offset);
6779 struct type *join, **jnext, *mnext;
6780 join = new_type(TYPE_JOIN, 0, 0);
6781 jnext = &join->left;
6787 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6788 mnext = member->right;
6789 member = member->left;
6791 size = reg_size_of(state, member);
6792 if (size > reg_offset) {
6793 struct type *part, *hunt;
6794 part = reg_type(state, member, reg_offset);
6795 /* See if this type is already in the union */
6798 struct type *test = hunt;
6800 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6804 if (equiv_types(part, test)) {
6812 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6813 jnext = &(*jnext)->right;
6820 if (join->elements == 0) {
6821 internal_error(state, 0, "No elements?");
6828 fprintf(state->errout, "type: ");
6829 name_of(state->errout, type);
6830 fprintf(state->errout, "\n");
6831 internal_error(state, 0, "reg_type not yet defined for type");
6835 /* If I have a single register compound type not a bit-field
6836 * find the real type.
6838 member = unpack_type(state, member);
6840 size = reg_size_of(state, member);
6841 if (size > REG_SIZEOF_REG) {
6842 internal_error(state, 0, "Cannot find type of single register");
6845 invalid = invalid_type(state, member);
6847 fprintf(state->errout, "type: ");
6848 name_of(state->errout, member);
6849 fprintf(state->errout, "\n");
6850 fprintf(state->errout, "invalid: ");
6851 name_of(state->errout, invalid);
6852 fprintf(state->errout, "\n");
6853 internal_error(state, 0, "returning bad type?");
6859 static struct type *next_field(struct compile_state *state,
6860 struct type *type, struct type *prev_member)
6862 struct type *member;
6863 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6864 internal_error(state, 0, "next_field only works on structures");
6866 member = type->left;
6867 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6869 member = member->left;
6872 if (member->left == prev_member) {
6875 member = member->right;
6877 if (member == prev_member) {
6881 internal_error(state, 0, "prev_member %s not present",
6882 prev_member->field_ident->name);
6887 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type,
6888 size_t ret_offset, size_t mem_offset, void *arg);
6890 static void walk_type_fields(struct compile_state *state,
6891 struct type *type, size_t reg_offset, size_t mem_offset,
6892 walk_type_fields_cb_t cb, void *arg);
6894 static void walk_struct_fields(struct compile_state *state,
6895 struct type *type, size_t reg_offset, size_t mem_offset,
6896 walk_type_fields_cb_t cb, void *arg)
6900 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6901 internal_error(state, 0, "walk_struct_fields only works on structures");
6904 for(i = 0; i < type->elements; i++) {
6907 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6908 mtype = mtype->left;
6910 walk_type_fields(state, mtype,
6912 field_reg_offset(state, type, mtype->field_ident),
6914 field_offset(state, type, mtype->field_ident),
6921 static void walk_type_fields(struct compile_state *state,
6922 struct type *type, size_t reg_offset, size_t mem_offset,
6923 walk_type_fields_cb_t cb, void *arg)
6925 switch(type->type & TYPE_MASK) {
6927 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6937 cb(state, type, reg_offset, mem_offset, arg);
6942 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6946 static void arrays_complete(struct compile_state *state, struct type *type)
6948 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6949 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6950 error(state, 0, "array size not specified");
6952 arrays_complete(state, type->left);
6956 static unsigned int get_basic_type(struct type *type)
6959 basic = type->type & TYPE_MASK;
6960 /* Convert enums to ints */
6961 if (basic == TYPE_ENUM) {
6964 /* Convert bitfields to standard types */
6965 else if (basic == TYPE_BITFIELD) {
6966 if (type->elements <= SIZEOF_CHAR) {
6969 else if (type->elements <= SIZEOF_SHORT) {
6972 else if (type->elements <= SIZEOF_INT) {
6975 else if (type->elements <= SIZEOF_LONG) {
6978 if (!TYPE_SIGNED(type->left->type)) {
6985 static unsigned int do_integral_promotion(unsigned int type)
6987 if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6993 static unsigned int do_arithmetic_conversion(
6994 unsigned int left, unsigned int right)
6996 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6997 return TYPE_LDOUBLE;
6999 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
7002 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
7005 left = do_integral_promotion(left);
7006 right = do_integral_promotion(right);
7007 /* If both operands have the same size done */
7008 if (left == right) {
7011 /* If both operands have the same signedness pick the larger */
7012 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
7013 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
7015 /* If the signed type can hold everything use it */
7016 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
7019 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
7022 /* Convert to the unsigned type with the same rank as the signed type */
7023 else if (TYPE_SIGNED(left)) {
7024 return TYPE_MKUNSIGNED(left);
7027 return TYPE_MKUNSIGNED(right);
7031 /* see if two types are the same except for qualifiers */
7032 static int equiv_types(struct type *left, struct type *right)
7035 /* Error if the basic types do not match */
7036 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
7039 type = left->type & TYPE_MASK;
7040 /* If the basic types match and it is a void type we are done */
7041 if (type == TYPE_VOID) {
7044 /* For bitfields we need to compare the sizes */
7045 else if (type == TYPE_BITFIELD) {
7046 return (left->elements == right->elements) &&
7047 (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
7049 /* if the basic types match and it is an arithmetic type we are done */
7050 else if (TYPE_ARITHMETIC(type)) {
7053 /* If it is a pointer type recurse and keep testing */
7054 else if (type == TYPE_POINTER) {
7055 return equiv_types(left->left, right->left);
7057 else if (type == TYPE_ARRAY) {
7058 return (left->elements == right->elements) &&
7059 equiv_types(left->left, right->left);
7061 /* test for struct equality */
7062 else if (type == TYPE_STRUCT) {
7063 return left->type_ident == right->type_ident;
7065 /* test for union equality */
7066 else if (type == TYPE_UNION) {
7067 return left->type_ident == right->type_ident;
7069 /* Test for equivalent functions */
7070 else if (type == TYPE_FUNCTION) {
7071 return equiv_types(left->left, right->left) &&
7072 equiv_types(left->right, right->right);
7074 /* We only see TYPE_PRODUCT as part of function equivalence matching */
7075 /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
7076 else if (type == TYPE_PRODUCT) {
7077 return equiv_types(left->left, right->left) &&
7078 equiv_types(left->right, right->right);
7080 /* We should see TYPE_OVERLAP when comparing joins */
7081 else if (type == TYPE_OVERLAP) {
7082 return equiv_types(left->left, right->left) &&
7083 equiv_types(left->right, right->right);
7085 /* Test for equivalence of tuples */
7086 else if (type == TYPE_TUPLE) {
7087 return (left->elements == right->elements) &&
7088 equiv_types(left->left, right->left);
7090 /* Test for equivalence of joins */
7091 else if (type == TYPE_JOIN) {
7092 return (left->elements == right->elements) &&
7093 equiv_types(left->left, right->left);
7100 static int equiv_ptrs(struct type *left, struct type *right)
7102 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7103 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7106 return equiv_types(left->left, right->left);
7109 static struct type *compatible_types(struct type *left, struct type *right)
7111 struct type *result;
7112 unsigned int type, qual_type;
7113 /* Error if the basic types do not match */
7114 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
7117 type = left->type & TYPE_MASK;
7118 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7120 /* if the basic types match and it is an arithmetic type we are done */
7121 if (TYPE_ARITHMETIC(type)) {
7122 result = new_type(qual_type, 0, 0);
7124 /* If it is a pointer type recurse and keep testing */
7125 else if (type == TYPE_POINTER) {
7126 result = compatible_types(left->left, right->left);
7128 result = new_type(qual_type, result, 0);
7131 /* test for struct equality */
7132 else if (type == TYPE_STRUCT) {
7133 if (left->type_ident == right->type_ident) {
7137 /* test for union equality */
7138 else if (type == TYPE_UNION) {
7139 if (left->type_ident == right->type_ident) {
7143 /* Test for equivalent functions */
7144 else if (type == TYPE_FUNCTION) {
7145 struct type *lf, *rf;
7146 lf = compatible_types(left->left, right->left);
7147 rf = compatible_types(left->right, right->right);
7149 result = new_type(qual_type, lf, rf);
7152 /* We only see TYPE_PRODUCT as part of function equivalence matching */
7153 else if (type == TYPE_PRODUCT) {
7154 struct type *lf, *rf;
7155 lf = compatible_types(left->left, right->left);
7156 rf = compatible_types(left->right, right->right);
7158 result = new_type(qual_type, lf, rf);
7162 /* Nothing else is compatible */
7167 /* See if left is a equivalent to right or right is a union member of left */
7168 static int is_subset_type(struct type *left, struct type *right)
7170 if (equiv_types(left, right)) {
7173 if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7174 struct type *member, *mnext;
7179 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7180 mnext = member->right;
7181 member = member->left;
7183 if (is_subset_type( member, right)) {
7191 static struct type *compatible_ptrs(struct type *left, struct type *right)
7193 struct type *result;
7194 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7195 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7198 result = compatible_types(left->left, right->left);
7200 unsigned int qual_type;
7201 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7202 result = new_type(qual_type, result, 0);
7207 static struct triple *integral_promotion(
7208 struct compile_state *state, struct triple *def)
7212 /* As all operations are carried out in registers
7213 * the values are converted on load I just convert
7214 * logical type of the operand.
7216 if (TYPE_INTEGER(type->type)) {
7217 unsigned int int_type;
7218 int_type = type->type & ~TYPE_MASK;
7219 int_type |= do_integral_promotion(get_basic_type(type));
7220 if (int_type != type->type) {
7221 if (def->op != OP_LOAD) {
7222 def->type = new_type(int_type, 0, 0);
7225 def = triple(state, OP_CONVERT,
7226 new_type(int_type, 0, 0), def, 0);
7234 static void arithmetic(struct compile_state *state, struct triple *def)
7236 if (!TYPE_ARITHMETIC(def->type->type)) {
7237 error(state, 0, "arithmetic type expexted");
7241 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7243 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7244 error(state, def, "pointer or arithmetic type expected");
7248 static int is_integral(struct triple *ins)
7250 return TYPE_INTEGER(ins->type->type);
7253 static void integral(struct compile_state *state, struct triple *def)
7255 if (!is_integral(def)) {
7256 error(state, 0, "integral type expected");
7261 static void bool(struct compile_state *state, struct triple *def)
7263 if (!TYPE_ARITHMETIC(def->type->type) &&
7264 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7265 error(state, 0, "arithmetic or pointer type expected");
7269 static int is_signed(struct type *type)
7271 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7274 return !!TYPE_SIGNED(type->type);
7276 static int is_compound_type(struct type *type)
7279 switch((type->type & TYPE_MASK)) {
7294 /* Is this value located in a register otherwise it must be in memory */
7295 static int is_in_reg(struct compile_state *state, struct triple *def)
7298 if (def->op == OP_ADECL) {
7301 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7304 else if (triple_is_part(state, def)) {
7305 in_reg = is_in_reg(state, MISC(def, 0));
7308 internal_error(state, def, "unknown expr storage location");
7314 /* Is this an auto or static variable location? Something that can
7315 * be assigned to. Otherwise it must must be a pure value, a temporary.
7317 static int is_lvalue(struct compile_state *state, struct triple *def)
7324 if ((def->op == OP_ADECL) ||
7325 (def->op == OP_SDECL) ||
7326 (def->op == OP_DEREF) ||
7327 (def->op == OP_BLOBCONST) ||
7328 (def->op == OP_LIST)) {
7331 else if (triple_is_part(state, def)) {
7332 ret = is_lvalue(state, MISC(def, 0));
7337 static void clvalue(struct compile_state *state, struct triple *def)
7340 internal_error(state, def, "nothing where lvalue expected?");
7342 if (!is_lvalue(state, def)) {
7343 error(state, def, "lvalue expected");
7346 static void lvalue(struct compile_state *state, struct triple *def)
7348 clvalue(state, def);
7349 if (def->type->type & QUAL_CONST) {
7350 error(state, def, "modifable lvalue expected");
7354 static int is_pointer(struct triple *def)
7356 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7359 static void pointer(struct compile_state *state, struct triple *def)
7361 if (!is_pointer(def)) {
7362 error(state, def, "pointer expected");
7366 static struct triple *int_const(
7367 struct compile_state *state, struct type *type, ulong_t value)
7369 struct triple *result;
7370 switch(type->type & TYPE_MASK) {
7372 case TYPE_INT: case TYPE_UINT:
7373 case TYPE_LONG: case TYPE_ULONG:
7376 internal_error(state, 0, "constant for unknown type");
7378 result = triple(state, OP_INTCONST, type, 0, 0);
7379 result->u.cval = value;
7384 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7386 static struct triple *do_mk_addr_expr(struct compile_state *state,
7387 struct triple *expr, struct type *type, ulong_t offset)
7389 struct triple *result;
7390 struct type *ptr_type;
7391 clvalue(state, expr);
7393 ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7397 if (expr->op == OP_ADECL) {
7398 error(state, expr, "address of auto variables not supported");
7400 else if (expr->op == OP_SDECL) {
7401 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7402 MISC(result, 0) = expr;
7403 result->u.cval = offset;
7405 else if (expr->op == OP_DEREF) {
7406 result = triple(state, OP_ADD, ptr_type,
7408 int_const(state, &ulong_type, offset));
7410 else if (expr->op == OP_BLOBCONST) {
7412 internal_error(state, expr, "not yet implemented");
7414 else if (expr->op == OP_LIST) {
7415 error(state, 0, "Function addresses not supported");
7417 else if (triple_is_part(state, expr)) {
7418 struct triple *part;
7420 expr = MISC(expr, 0);
7421 if (part->op == OP_DOT) {
7422 offset += bits_to_bytes(
7423 field_offset(state, expr->type, part->u.field));
7425 else if (part->op == OP_INDEX) {
7426 offset += bits_to_bytes(
7427 index_offset(state, expr->type, part->u.cval));
7430 internal_error(state, part, "unhandled part type");
7432 result = do_mk_addr_expr(state, expr, type, offset);
7435 internal_error(state, expr, "cannot take address of expression");
7440 static struct triple *mk_addr_expr(
7441 struct compile_state *state, struct triple *expr, ulong_t offset)
7443 return do_mk_addr_expr(state, expr, expr->type, offset);
7446 static struct triple *mk_deref_expr(
7447 struct compile_state *state, struct triple *expr)
7449 struct type *base_type;
7450 pointer(state, expr);
7451 base_type = expr->type->left;
7452 return triple(state, OP_DEREF, base_type, expr, 0);
7455 /* lvalue conversions always apply except when certain operators
7456 * are applied. So I apply apply it when I know no more
7457 * operators will be applied.
7459 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7461 /* Tranform an array to a pointer to the first element */
7462 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7465 TYPE_POINTER | (def->type->type & QUAL_MASK),
7466 def->type->left, 0);
7467 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7468 struct triple *addrconst;
7469 if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7470 internal_error(state, def, "bad array constant");
7472 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7473 MISC(addrconst, 0) = def;
7477 def = triple(state, OP_CONVERT, type, def, 0);
7480 /* Transform a function to a pointer to it */
7481 else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7482 def = mk_addr_expr(state, def, 0);
7487 static struct triple *deref_field(
7488 struct compile_state *state, struct triple *expr, struct hash_entry *field)
7490 struct triple *result;
7491 struct type *type, *member;
7494 internal_error(state, 0, "No field passed to deref_field");
7498 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7499 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7500 error(state, 0, "request for member %s in something not a struct or union",
7503 member = field_type(state, type, field);
7504 if ((type->type & STOR_MASK) == STOR_PERM) {
7505 /* Do the pointer arithmetic to get a deref the field */
7506 offset = bits_to_bytes(field_offset(state, type, field));
7507 result = do_mk_addr_expr(state, expr, member, offset);
7508 result = mk_deref_expr(state, result);
7511 /* Find the variable for the field I want. */
7512 result = triple(state, OP_DOT, member, expr, 0);
7513 result->u.field = field;
7518 static struct triple *deref_index(
7519 struct compile_state *state, struct triple *expr, size_t index)
7521 struct triple *result;
7522 struct type *type, *member;
7527 member = index_type(state, type, index);
7529 if ((type->type & STOR_MASK) == STOR_PERM) {
7530 offset = bits_to_bytes(index_offset(state, type, index));
7531 result = do_mk_addr_expr(state, expr, member, offset);
7532 result = mk_deref_expr(state, result);
7535 result = triple(state, OP_INDEX, member, expr, 0);
7536 result->u.cval = index;
7541 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7547 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7548 /* Transform lvalues into something we can read */
7549 def = lvalue_conversion(state, def);
7550 if (!is_lvalue(state, def)) {
7553 if (is_in_reg(state, def)) {
7556 if (def->op == OP_SDECL) {
7557 def = mk_addr_expr(state, def, 0);
7558 def = mk_deref_expr(state, def);
7562 def = triple(state, op, def->type, def, 0);
7563 if (def->type->type & QUAL_VOLATILE) {
7564 def->id |= TRIPLE_FLAG_VOLATILE;
7569 int is_write_compatible(struct compile_state *state,
7570 struct type *dest, struct type *rval)
7573 /* Both operands have arithmetic type */
7574 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7577 /* One operand is a pointer and the other is a pointer to void */
7578 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7579 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7580 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7581 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7584 /* If both types are the same without qualifiers we are good */
7585 else if (equiv_ptrs(dest, rval)) {
7588 /* test for struct/union equality */
7589 else if (equiv_types(dest, rval)) {
7595 static void write_compatible(struct compile_state *state,
7596 struct type *dest, struct type *rval)
7598 if (!is_write_compatible(state, dest, rval)) {
7599 FILE *fp = state->errout;
7600 fprintf(fp, "dest: ");
7602 fprintf(fp,"\nrval: ");
7605 error(state, 0, "Incompatible types in assignment");
7609 static int is_init_compatible(struct compile_state *state,
7610 struct type *dest, struct type *rval)
7613 if (is_write_compatible(state, dest, rval)) {
7616 else if (equiv_types(dest, rval)) {
7622 static struct triple *write_expr(
7623 struct compile_state *state, struct triple *dest, struct triple *rval)
7630 internal_error(state, 0, "missing rval");
7633 if (rval->op == OP_LIST) {
7634 internal_error(state, 0, "expression of type OP_LIST?");
7636 if (!is_lvalue(state, dest)) {
7637 internal_error(state, 0, "writing to a non lvalue?");
7639 if (dest->type->type & QUAL_CONST) {
7640 internal_error(state, 0, "modifable lvalue expexted");
7643 write_compatible(state, dest->type, rval->type);
7644 if (!equiv_types(dest->type, rval->type)) {
7645 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7648 /* Now figure out which assignment operator to use */
7650 if (is_in_reg(state, dest)) {
7651 def = triple(state, OP_WRITE, dest->type, rval, dest);
7652 if (MISC(def, 0) != dest) {
7653 internal_error(state, def, "huh?");
7655 if (RHS(def, 0) != rval) {
7656 internal_error(state, def, "huh?");
7659 def = triple(state, OP_STORE, dest->type, dest, rval);
7661 if (def->type->type & QUAL_VOLATILE) {
7662 def->id |= TRIPLE_FLAG_VOLATILE;
7667 static struct triple *init_expr(
7668 struct compile_state *state, struct triple *dest, struct triple *rval)
7674 internal_error(state, 0, "missing rval");
7676 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
7677 rval = read_expr(state, rval);
7678 def = write_expr(state, dest, rval);
7681 /* Fill in the array size if necessary */
7682 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
7683 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
7684 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
7685 dest->type->elements = rval->type->elements;
7688 if (!equiv_types(dest->type, rval->type)) {
7689 error(state, 0, "Incompatible types in inializer");
7691 MISC(dest, 0) = rval;
7692 insert_triple(state, dest, rval);
7693 rval->id |= TRIPLE_FLAG_FLATTENED;
7694 use_triple(MISC(dest, 0), dest);
7699 struct type *arithmetic_result(
7700 struct compile_state *state, struct triple *left, struct triple *right)
7703 /* Sanity checks to ensure I am working with arithmetic types */
7704 arithmetic(state, left);
7705 arithmetic(state, right);
7707 do_arithmetic_conversion(
7708 get_basic_type(left->type),
7709 get_basic_type(right->type)),
7714 struct type *ptr_arithmetic_result(
7715 struct compile_state *state, struct triple *left, struct triple *right)
7718 /* Sanity checks to ensure I am working with the proper types */
7719 ptr_arithmetic(state, left);
7720 arithmetic(state, right);
7721 if (TYPE_ARITHMETIC(left->type->type) &&
7722 TYPE_ARITHMETIC(right->type->type)) {
7723 type = arithmetic_result(state, left, right);
7725 else if (TYPE_PTR(left->type->type)) {
7729 internal_error(state, 0, "huh?");
7735 /* boolean helper function */
7737 static struct triple *ltrue_expr(struct compile_state *state,
7738 struct triple *expr)
7741 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
7742 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
7743 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
7744 /* If the expression is already boolean do nothing */
7747 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
7753 static struct triple *lfalse_expr(struct compile_state *state,
7754 struct triple *expr)
7756 return triple(state, OP_LFALSE, &int_type, expr, 0);
7759 static struct triple *mkland_expr(
7760 struct compile_state *state,
7761 struct triple *left, struct triple *right)
7763 struct triple *def, *val, *var, *jmp, *mid, *end;
7765 /* Generate some intermediate triples */
7767 var = variable(state, &int_type);
7769 /* Store the left hand side value */
7770 left = write_expr(state, var, left);
7772 /* Jump if the value is false */
7773 jmp = branch(state, end,
7774 lfalse_expr(state, read_expr(state, var)));
7777 /* Store the right hand side value */
7778 right = write_expr(state, var, right);
7780 /* An expression for the computed value */
7781 val = read_expr(state, var);
7783 /* Generate the prog for a logical and */
7784 def = mkprog(state, var, left, jmp, mid, right, end, val, 0);
7789 static struct triple *mklor_expr(
7790 struct compile_state *state,
7791 struct triple *left, struct triple *right)
7793 struct triple *def, *val, *var, *jmp, *mid, *end;
7795 /* Generate some intermediate triples */
7797 var = variable(state, &int_type);
7799 /* Store the left hand side value */
7800 left = write_expr(state, var, left);
7802 /* Jump if the value is true */
7803 jmp = branch(state, end, read_expr(state, var));
7806 /* Store the right hand side value */
7807 right = write_expr(state, var, right);
7809 /* An expression for the computed value*/
7810 val = read_expr(state, var);
7812 /* Generate the prog for a logical or */
7813 def = mkprog(state, var, left, jmp, mid, right, end, val, 0);
7818 static struct triple *mkcond_expr(
7819 struct compile_state *state,
7820 struct triple *test, struct triple *left, struct triple *right)
7822 struct triple *def, *val, *var, *jmp1, *jmp2, *top, *mid, *end;
7823 struct type *result_type;
7824 unsigned int left_type, right_type;
7826 left_type = left->type->type;
7827 right_type = right->type->type;
7829 /* Both operands have arithmetic type */
7830 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
7831 result_type = arithmetic_result(state, left, right);
7833 /* Both operands have void type */
7834 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
7835 ((right_type & TYPE_MASK) == TYPE_VOID)) {
7836 result_type = &void_type;
7838 /* pointers to the same type... */
7839 else if ((result_type = compatible_ptrs(left->type, right->type))) {
7842 /* Both operands are pointers and left is a pointer to void */
7843 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7844 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7845 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7846 result_type = right->type;
7848 /* Both operands are pointers and right is a pointer to void */
7849 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7850 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7851 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7852 result_type = left->type;
7855 error(state, 0, "Incompatible types in conditional expression");
7857 /* Generate some intermediate triples */
7860 var = variable(state, result_type);
7862 /* Branch if the test is false */
7863 jmp1 = branch(state, mid, lfalse_expr(state, read_expr(state, test)));
7866 /* Store the left hand side value */
7867 left = write_expr(state, var, left);
7869 /* Branch to the end */
7870 jmp2 = branch(state, end, 0);
7872 /* Store the right hand side value */
7873 right = write_expr(state, var, right);
7875 /* An expression for the computed value */
7876 val = read_expr(state, var);
7878 /* Generate the prog for a conditional expression */
7879 def = mkprog(state, var, jmp1, top, left, jmp2, mid, right, end, val, 0);
7885 static int expr_depth(struct compile_state *state, struct triple *ins)
7887 #warning "FIXME move optimal ordering of subexpressions into the optimizer"
7890 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
7893 else if (ins->op == OP_DEREF) {
7894 count = expr_depth(state, RHS(ins, 0)) - 1;
7896 else if (ins->op == OP_VAL) {
7897 count = expr_depth(state, RHS(ins, 0)) - 1;
7899 else if (ins->op == OP_FCALL) {
7900 /* Don't figure the depth of a call just guess it is huge */
7904 struct triple **expr;
7905 expr = triple_rhs(state, ins, 0);
7906 for(;expr; expr = triple_rhs(state, ins, expr)) {
7909 depth = expr_depth(state, *expr);
7910 if (depth > count) {
7919 static struct triple *flatten_generic(
7920 struct compile_state *state, struct triple *first, struct triple *ptr,
7925 struct triple **ins;
7928 /* Only operations with just a rhs and a lhs should come here */
7931 if (TRIPLE_SIZE(ptr) != lhs + rhs + ignored) {
7932 internal_error(state, ptr, "unexpected args for: %d %s",
7933 ptr->op, tops(ptr->op));
7935 /* Find the depth of the rhs elements */
7936 for(i = 0; i < rhs; i++) {
7937 vector[i].ins = &RHS(ptr, i);
7938 vector[i].depth = expr_depth(state, *vector[i].ins);
7940 /* Selection sort the rhs */
7941 for(i = 0; i < rhs; i++) {
7943 for(j = i + 1; j < rhs; j++ ) {
7944 if (vector[j].depth > vector[max].depth) {
7949 struct rhs_vector tmp;
7951 vector[i] = vector[max];
7955 /* Now flatten the rhs elements */
7956 for(i = 0; i < rhs; i++) {
7957 *vector[i].ins = flatten(state, first, *vector[i].ins);
7958 use_triple(*vector[i].ins, ptr);
7961 insert_triple(state, first, ptr);
7962 ptr->id |= TRIPLE_FLAG_FLATTENED;
7963 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7965 /* Now flatten the lhs elements */
7966 for(i = 0; i < lhs; i++) {
7967 struct triple **ins = &LHS(ptr, i);
7968 *ins = flatten(state, first, *ins);
7969 use_triple(*ins, ptr);
7975 static struct triple *flatten_prog(
7976 struct compile_state *state, struct triple *first, struct triple *ptr)
7978 struct triple *head, *body, *val;
7983 release_triple(state, head);
7984 release_triple(state, ptr);
7986 body->prev = first->prev;
7987 body->prev->next = body;
7988 val->next->prev = val;
7990 if (triple_is_cbranch(state, body->prev) ||
7991 triple_is_call(state, body->prev)) {
7992 unuse_triple(first, body->prev);
7993 use_triple(body, body->prev);
7996 if (!(val->id & TRIPLE_FLAG_FLATTENED)) {
7997 internal_error(state, val, "val not flattened?");
8004 static struct triple *flatten_part(
8005 struct compile_state *state, struct triple *first, struct triple *ptr)
8007 if (!triple_is_part(state, ptr)) {
8008 internal_error(state, ptr, "not a part");
8010 if (ptr->rhs || ptr->lhs || ptr->targ || (ptr->misc != 1)) {
8011 internal_error(state, ptr, "unexpected args for: %d %s",
8012 ptr->op, tops(ptr->op));
8014 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8015 use_triple(MISC(ptr, 0), ptr);
8016 return flatten_generic(state, first, ptr, 1);
8019 static struct triple *flatten(
8020 struct compile_state *state, struct triple *first, struct triple *ptr)
8022 struct triple *orig_ptr;
8027 /* Only flatten triples once */
8028 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
8033 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
8034 return MISC(ptr, 0);
8037 ptr = flatten_prog(state, first, ptr);
8040 ptr = flatten_generic(state, first, ptr, 1);
8041 insert_triple(state, first, ptr);
8042 ptr->id |= TRIPLE_FLAG_FLATTENED;
8043 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8044 if (ptr->next != ptr) {
8045 use_triple(ptr->next, ptr);
8050 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
8051 use_triple(RHS(ptr, 0), ptr);
8054 ptr = flatten_generic(state, first, ptr, 1);
8055 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8056 use_triple(MISC(ptr, 0), ptr);
8059 use_triple(TARG(ptr, 0), ptr);
8062 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
8063 use_triple(RHS(ptr, 0), ptr);
8064 use_triple(TARG(ptr, 0), ptr);
8065 insert_triple(state, first, ptr);
8066 ptr->id |= TRIPLE_FLAG_FLATTENED;
8067 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8068 if (ptr->next != ptr) {
8069 use_triple(ptr->next, ptr);
8073 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8074 use_triple(MISC(ptr, 0), ptr);
8075 use_triple(TARG(ptr, 0), ptr);
8076 insert_triple(state, first, ptr);
8077 ptr->id |= TRIPLE_FLAG_FLATTENED;
8078 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8079 if (ptr->next != ptr) {
8080 use_triple(ptr->next, ptr);
8084 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
8085 use_triple(RHS(ptr, 0), ptr);
8088 insert_triple(state, state->global_pool, ptr);
8089 ptr->id |= TRIPLE_FLAG_FLATTENED;
8090 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8091 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
8092 use_triple(MISC(ptr, 0), ptr);
8095 /* Since OP_DEREF is just a marker delete it when I flatten it */
8097 RHS(orig_ptr, 0) = 0;
8098 free_triple(state, orig_ptr);
8101 if (RHS(ptr, 0)->op == OP_DEREF) {
8102 struct triple *base, *left;
8104 base = MISC(ptr, 0);
8105 offset = bits_to_bytes(field_offset(state, base->type, ptr->u.field));
8106 left = RHS(base, 0);
8107 ptr = triple(state, OP_ADD, left->type,
8108 read_expr(state, left),
8109 int_const(state, &ulong_type, offset));
8110 free_triple(state, base);
8113 ptr = flatten_part(state, first, ptr);
8117 if (RHS(ptr, 0)->op == OP_DEREF) {
8118 struct triple *base, *left;
8120 base = MISC(ptr, 0);
8121 offset = bits_to_bytes(index_offset(state, base->type, ptr->u.cval));
8122 left = RHS(base, 0);
8123 ptr = triple(state, OP_ADD, left->type,
8124 read_expr(state, left),
8125 int_const(state, &long_type, offset));
8126 free_triple(state, base);
8129 ptr = flatten_part(state, first, ptr);
8133 ptr = flatten_part(state, first, ptr);
8134 use_triple(ptr, MISC(ptr, 0));
8137 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8138 use_triple(MISC(ptr, 0), ptr);
8141 first = state->global_pool;
8142 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8143 use_triple(MISC(ptr, 0), ptr);
8144 insert_triple(state, first, ptr);
8145 ptr->id |= TRIPLE_FLAG_FLATTENED;
8146 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8149 ptr = flatten_generic(state, first, ptr, 0);
8152 /* Flatten the easy cases we don't override */
8153 ptr = flatten_generic(state, first, ptr, 0);
8156 } while(ptr && (ptr != orig_ptr));
8157 if (ptr && !(ptr->id & TRIPLE_FLAG_FLATTENED)) {
8158 insert_triple(state, first, ptr);
8159 ptr->id |= TRIPLE_FLAG_FLATTENED;
8160 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8165 static void release_expr(struct compile_state *state, struct triple *expr)
8167 struct triple *head;
8168 head = label(state);
8169 flatten(state, head, expr);
8170 while(head->next != head) {
8171 release_triple(state, head->next);
8173 free_triple(state, head);
8176 static int replace_rhs_use(struct compile_state *state,
8177 struct triple *orig, struct triple *new, struct triple *use)
8179 struct triple **expr;
8182 expr = triple_rhs(state, use, 0);
8183 for(;expr; expr = triple_rhs(state, use, expr)) {
8184 if (*expr == orig) {
8190 unuse_triple(orig, use);
8191 use_triple(new, use);
8196 static int replace_lhs_use(struct compile_state *state,
8197 struct triple *orig, struct triple *new, struct triple *use)
8199 struct triple **expr;
8202 expr = triple_lhs(state, use, 0);
8203 for(;expr; expr = triple_lhs(state, use, expr)) {
8204 if (*expr == orig) {
8210 unuse_triple(orig, use);
8211 use_triple(new, use);
8216 static int replace_misc_use(struct compile_state *state,
8217 struct triple *orig, struct triple *new, struct triple *use)
8219 struct triple **expr;
8222 expr = triple_misc(state, use, 0);
8223 for(;expr; expr = triple_misc(state, use, expr)) {
8224 if (*expr == orig) {
8230 unuse_triple(orig, use);
8231 use_triple(new, use);
8236 static int replace_targ_use(struct compile_state *state,
8237 struct triple *orig, struct triple *new, struct triple *use)
8239 struct triple **expr;
8242 expr = triple_targ(state, use, 0);
8243 for(;expr; expr = triple_targ(state, use, expr)) {
8244 if (*expr == orig) {
8250 unuse_triple(orig, use);
8251 use_triple(new, use);
8256 static void replace_use(struct compile_state *state,
8257 struct triple *orig, struct triple *new, struct triple *use)
8261 found |= replace_rhs_use(state, orig, new, use);
8262 found |= replace_lhs_use(state, orig, new, use);
8263 found |= replace_misc_use(state, orig, new, use);
8264 found |= replace_targ_use(state, orig, new, use);
8266 internal_error(state, use, "use without use");
8270 static void propogate_use(struct compile_state *state,
8271 struct triple *orig, struct triple *new)
8273 struct triple_set *user, *next;
8274 for(user = orig->use; user; user = next) {
8275 /* Careful replace_use modifies the use chain and
8276 * removes use. So we must get a copy of the next
8280 replace_use(state, orig, new, user->member);
8283 internal_error(state, orig, "used after propogate_use");
8289 * ===========================
8292 static struct triple *mk_cast_expr(
8293 struct compile_state *state, struct type *type, struct triple *expr)
8296 def = read_expr(state, expr);
8297 def = triple(state, OP_CONVERT, type, def, 0);
8301 static struct triple *mk_add_expr(
8302 struct compile_state *state, struct triple *left, struct triple *right)
8304 struct type *result_type;
8305 /* Put pointer operands on the left */
8306 if (is_pointer(right)) {
8312 left = read_expr(state, left);
8313 right = read_expr(state, right);
8314 result_type = ptr_arithmetic_result(state, left, right);
8315 if (is_pointer(left)) {
8316 struct type *ptr_math;
8318 if (is_signed(right->type)) {
8319 ptr_math = &long_type;
8322 ptr_math = &ulong_type;
8325 if (!equiv_types(right->type, ptr_math)) {
8326 right = mk_cast_expr(state, ptr_math, right);
8328 right = triple(state, op, ptr_math, right,
8329 int_const(state, ptr_math,
8330 size_of_in_bytes(state, left->type->left)));
8332 return triple(state, OP_ADD, result_type, left, right);
8335 static struct triple *mk_sub_expr(
8336 struct compile_state *state, struct triple *left, struct triple *right)
8338 struct type *result_type;
8339 result_type = ptr_arithmetic_result(state, left, right);
8340 left = read_expr(state, left);
8341 right = read_expr(state, right);
8342 if (is_pointer(left)) {
8343 struct type *ptr_math;
8345 if (is_signed(right->type)) {
8346 ptr_math = &long_type;
8349 ptr_math = &ulong_type;
8352 if (!equiv_types(right->type, ptr_math)) {
8353 right = mk_cast_expr(state, ptr_math, right);
8355 right = triple(state, op, ptr_math, right,
8356 int_const(state, ptr_math,
8357 size_of_in_bytes(state, left->type->left)));
8359 return triple(state, OP_SUB, result_type, left, right);
8362 static struct triple *mk_pre_inc_expr(
8363 struct compile_state *state, struct triple *def)
8367 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
8368 return triple(state, OP_VAL, def->type,
8369 write_expr(state, def, val),
8373 static struct triple *mk_pre_dec_expr(
8374 struct compile_state *state, struct triple *def)
8378 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
8379 return triple(state, OP_VAL, def->type,
8380 write_expr(state, def, val),
8384 static struct triple *mk_post_inc_expr(
8385 struct compile_state *state, struct triple *def)
8389 val = read_expr(state, def);
8390 return triple(state, OP_VAL, def->type,
8391 write_expr(state, def,
8392 mk_add_expr(state, val, int_const(state, &int_type, 1)))
8396 static struct triple *mk_post_dec_expr(
8397 struct compile_state *state, struct triple *def)
8401 val = read_expr(state, def);
8402 return triple(state, OP_VAL, def->type,
8403 write_expr(state, def,
8404 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
8408 static struct triple *mk_subscript_expr(
8409 struct compile_state *state, struct triple *left, struct triple *right)
8411 left = read_expr(state, left);
8412 right = read_expr(state, right);
8413 if (!is_pointer(left) && !is_pointer(right)) {
8414 error(state, left, "subscripted value is not a pointer");
8416 return mk_deref_expr(state, mk_add_expr(state, left, right));
8421 * Compile time evaluation
8422 * ===========================
8424 static int is_const(struct triple *ins)
8426 return IS_CONST_OP(ins->op);
8429 static int is_simple_const(struct triple *ins)
8431 /* Is this a constant that u.cval has the value.
8432 * Or equivalently is this a constant that read_const
8434 * So far only OP_INTCONST qualifies.
8436 return (ins->op == OP_INTCONST);
8439 static int constants_equal(struct compile_state *state,
8440 struct triple *left, struct triple *right)
8443 if ((left->op == OP_UNKNOWNVAL) || (right->op == OP_UNKNOWNVAL)) {
8446 else if (!is_const(left) || !is_const(right)) {
8449 else if (left->op != right->op) {
8452 else if (!equiv_types(left->type, right->type)) {
8459 if (left->u.cval == right->u.cval) {
8465 size_t lsize, rsize, bytes;
8466 lsize = size_of(state, left->type);
8467 rsize = size_of(state, right->type);
8468 if (lsize != rsize) {
8471 bytes = bits_to_bytes(lsize);
8472 if (memcmp(left->u.blob, right->u.blob, bytes) == 0) {
8478 if ((MISC(left, 0) == MISC(right, 0)) &&
8479 (left->u.cval == right->u.cval)) {
8484 internal_error(state, left, "uknown constant type");
8491 static int is_zero(struct triple *ins)
8493 return is_simple_const(ins) && (ins->u.cval == 0);
8496 static int is_one(struct triple *ins)
8498 return is_simple_const(ins) && (ins->u.cval == 1);
8501 static long_t bit_count(ulong_t value)
8506 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8517 static long_t bsr(ulong_t value)
8520 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8531 static long_t bsf(ulong_t value)
8534 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
8545 static long_t log2(ulong_t value)
8550 static long_t tlog2(struct triple *ins)
8552 return log2(ins->u.cval);
8555 static int is_pow2(struct triple *ins)
8557 ulong_t value, mask;
8559 if (!is_const(ins)) {
8562 value = ins->u.cval;
8569 return ((value & mask) == value);
8572 static ulong_t read_const(struct compile_state *state,
8573 struct triple *ins, struct triple *rhs)
8575 switch(rhs->type->type &TYPE_MASK) {
8588 fprintf(state->errout, "type: ");
8589 name_of(state->errout, rhs->type);
8590 fprintf(state->errout, "\n");
8591 internal_warning(state, rhs, "bad type to read_const");
8594 if (!is_simple_const(rhs)) {
8595 internal_error(state, rhs, "bad op to read_const");
8600 static long_t read_sconst(struct compile_state *state,
8601 struct triple *ins, struct triple *rhs)
8603 return (long_t)(rhs->u.cval);
8606 int const_ltrue(struct compile_state *state, struct triple *ins, struct triple *rhs)
8608 if (!is_const(rhs)) {
8609 internal_error(state, 0, "non const passed to const_true");
8611 return !is_zero(rhs);
8614 int const_eq(struct compile_state *state, struct triple *ins,
8615 struct triple *left, struct triple *right)
8618 if (!is_const(left) || !is_const(right)) {
8619 internal_warning(state, ins, "non const passed to const_eq");
8622 else if (left == right) {
8625 else if (is_simple_const(left) && is_simple_const(right)) {
8627 lval = read_const(state, ins, left);
8628 rval = read_const(state, ins, right);
8629 result = (lval == rval);
8631 else if ((left->op == OP_ADDRCONST) &&
8632 (right->op == OP_ADDRCONST)) {
8633 result = (MISC(left, 0) == MISC(right, 0)) &&
8634 (left->u.cval == right->u.cval);
8637 internal_warning(state, ins, "incomparable constants passed to const_eq");
8644 int const_ucmp(struct compile_state *state, struct triple *ins,
8645 struct triple *left, struct triple *right)
8648 if (!is_const(left) || !is_const(right)) {
8649 internal_warning(state, ins, "non const past to const_ucmp");
8652 else if (left == right) {
8655 else if (is_simple_const(left) && is_simple_const(right)) {
8657 lval = read_const(state, ins, left);
8658 rval = read_const(state, ins, right);
8662 } else if (rval > lval) {
8666 else if ((left->op == OP_ADDRCONST) &&
8667 (right->op == OP_ADDRCONST) &&
8668 (MISC(left, 0) == MISC(right, 0))) {
8670 if (left->u.cval > right->u.cval) {
8672 } else if (left->u.cval < right->u.cval) {
8677 internal_warning(state, ins, "incomparable constants passed to const_ucmp");
8683 int const_scmp(struct compile_state *state, struct triple *ins,
8684 struct triple *left, struct triple *right)
8687 if (!is_const(left) || !is_const(right)) {
8688 internal_warning(state, ins, "non const past to ucmp_const");
8691 else if (left == right) {
8694 else if (is_simple_const(left) && is_simple_const(right)) {
8696 lval = read_sconst(state, ins, left);
8697 rval = read_sconst(state, ins, right);
8701 } else if (rval > lval) {
8706 internal_warning(state, ins, "incomparable constants passed to const_scmp");
8712 static void unuse_rhs(struct compile_state *state, struct triple *ins)
8714 struct triple **expr;
8715 expr = triple_rhs(state, ins, 0);
8716 for(;expr;expr = triple_rhs(state, ins, expr)) {
8718 unuse_triple(*expr, ins);
8724 static void unuse_lhs(struct compile_state *state, struct triple *ins)
8726 struct triple **expr;
8727 expr = triple_lhs(state, ins, 0);
8728 for(;expr;expr = triple_lhs(state, ins, expr)) {
8729 unuse_triple(*expr, ins);
8734 static void unuse_misc(struct compile_state *state, struct triple *ins)
8736 struct triple **expr;
8737 expr = triple_misc(state, ins, 0);
8738 for(;expr;expr = triple_misc(state, ins, expr)) {
8739 unuse_triple(*expr, ins);
8744 static void unuse_targ(struct compile_state *state, struct triple *ins)
8747 struct triple **slot;
8748 slot = &TARG(ins, 0);
8749 for(i = 0; i < ins->targ; i++) {
8750 unuse_triple(slot[i], ins);
8755 static void check_lhs(struct compile_state *state, struct triple *ins)
8757 struct triple **expr;
8758 expr = triple_lhs(state, ins, 0);
8759 for(;expr;expr = triple_lhs(state, ins, expr)) {
8760 internal_error(state, ins, "unexpected lhs");
8765 static void check_misc(struct compile_state *state, struct triple *ins)
8767 struct triple **expr;
8768 expr = triple_misc(state, ins, 0);
8769 for(;expr;expr = triple_misc(state, ins, expr)) {
8771 internal_error(state, ins, "unexpected misc");
8776 static void check_targ(struct compile_state *state, struct triple *ins)
8778 struct triple **expr;
8779 expr = triple_targ(state, ins, 0);
8780 for(;expr;expr = triple_targ(state, ins, expr)) {
8781 internal_error(state, ins, "unexpected targ");
8785 static void wipe_ins(struct compile_state *state, struct triple *ins)
8787 /* Becareful which instructions you replace the wiped
8788 * instruction with, as there are not enough slots
8789 * in all instructions to hold all others.
8791 check_targ(state, ins);
8792 check_misc(state, ins);
8793 unuse_rhs(state, ins);
8794 unuse_lhs(state, ins);
8801 static void wipe_branch(struct compile_state *state, struct triple *ins)
8803 /* Becareful which instructions you replace the wiped
8804 * instruction with, as there are not enough slots
8805 * in all instructions to hold all others.
8807 unuse_rhs(state, ins);
8808 unuse_lhs(state, ins);
8809 unuse_misc(state, ins);
8810 unuse_targ(state, ins);
8817 static void mkcopy(struct compile_state *state,
8818 struct triple *ins, struct triple *rhs)
8820 struct block *block;
8821 if (!equiv_types(ins->type, rhs->type)) {
8822 FILE *fp = state->errout;
8823 fprintf(fp, "src type: ");
8824 name_of(fp, rhs->type);
8825 fprintf(fp, "\ndst type: ");
8826 name_of(fp, ins->type);
8828 internal_error(state, ins, "mkcopy type mismatch");
8830 block = block_of_triple(state, ins);
8831 wipe_ins(state, ins);
8834 ins->u.block = block;
8836 use_triple(RHS(ins, 0), ins);
8839 static void mkconst(struct compile_state *state,
8840 struct triple *ins, ulong_t value)
8842 if (!is_integral(ins) && !is_pointer(ins)) {
8843 fprintf(state->errout, "type: ");
8844 name_of(state->errout, ins->type);
8845 fprintf(state->errout, "\n");
8846 internal_error(state, ins, "unknown type to make constant value: %ld",
8849 wipe_ins(state, ins);
8850 ins->op = OP_INTCONST;
8851 ins->u.cval = value;
8854 static void mkaddr_const(struct compile_state *state,
8855 struct triple *ins, struct triple *sdecl, ulong_t value)
8857 if ((sdecl->op != OP_SDECL) && (sdecl->op != OP_LABEL)) {
8858 internal_error(state, ins, "bad base for addrconst");
8860 wipe_ins(state, ins);
8861 ins->op = OP_ADDRCONST;
8863 MISC(ins, 0) = sdecl;
8864 ins->u.cval = value;
8865 use_triple(sdecl, ins);
8868 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8869 static void print_tuple(struct compile_state *state,
8870 struct triple *ins, struct triple *tuple)
8872 FILE *fp = state->dbgout;
8873 fprintf(fp, "%5s %p tuple: %p ", tops(ins->op), ins, tuple);
8874 name_of(fp, tuple->type);
8875 if (tuple->lhs > 0) {
8876 fprintf(fp, " lhs: ");
8877 name_of(fp, LHS(tuple, 0)->type);
8884 static struct triple *decompose_with_tuple(struct compile_state *state,
8885 struct triple *ins, struct triple *tuple)
8887 struct triple *next;
8889 flatten(state, next, tuple);
8890 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8891 print_tuple(state, ins, tuple);
8894 if (!is_compound_type(tuple->type) && (tuple->lhs > 0)) {
8896 if (tuple->lhs != 1) {
8897 internal_error(state, tuple, "plain type in multiple registers?");
8899 tmp = LHS(tuple, 0);
8900 release_triple(state, tuple);
8904 propogate_use(state, ins, tuple);
8905 release_triple(state, ins);
8910 static struct triple *decompose_unknownval(struct compile_state *state,
8913 struct triple *tuple;
8916 #if DEBUG_DECOMPOSE_HIRES
8917 FILE *fp = state->dbgout;
8918 fprintf(fp, "unknown type: ");
8919 name_of(fp, ins->type);
8923 get_occurance(ins->occurance);
8924 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8927 for(i = 0; i < tuple->lhs; i++) {
8928 struct type *piece_type;
8929 struct triple *unknown;
8931 piece_type = reg_type(state, ins->type, i * REG_SIZEOF_REG);
8932 get_occurance(tuple->occurance);
8933 unknown = alloc_triple(state, OP_UNKNOWNVAL, piece_type, 0, 0,
8935 LHS(tuple, i) = unknown;
8937 return decompose_with_tuple(state, ins, tuple);
8941 static struct triple *decompose_read(struct compile_state *state,
8944 struct triple *tuple, *lval;
8949 if (lval->op == OP_PIECE) {
8952 get_occurance(ins->occurance);
8953 tuple = alloc_triple(state, OP_TUPLE, lval->type, -1, -1,
8956 if ((tuple->lhs != lval->lhs) &&
8957 (!triple_is_def(state, lval) || (tuple->lhs != 1)))
8959 internal_error(state, ins, "lhs size inconsistency?");
8961 for(i = 0; i < tuple->lhs; i++) {
8962 struct triple *piece, *read, *bitref;
8963 if ((i != 0) || !triple_is_def(state, lval)) {
8964 piece = LHS(lval, i);
8969 /* See if the piece is really a bitref */
8971 if (piece->op == OP_BITREF) {
8973 piece = RHS(bitref, 0);
8976 get_occurance(tuple->occurance);
8977 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8979 RHS(read, 0) = piece;
8982 struct triple *extract;
8984 if (is_signed(bitref->type->left)) {
8989 get_occurance(tuple->occurance);
8990 extract = alloc_triple(state, op, bitref->type, -1, -1,
8992 RHS(extract, 0) = read;
8993 extract->u.bitfield.size = bitref->u.bitfield.size;
8994 extract->u.bitfield.offset = bitref->u.bitfield.offset;
8999 LHS(tuple, i) = read;
9001 return decompose_with_tuple(state, ins, tuple);
9004 static struct triple *decompose_write(struct compile_state *state,
9007 struct triple *tuple, *lval, *val;
9010 lval = MISC(ins, 0);
9012 get_occurance(ins->occurance);
9013 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9016 if ((tuple->lhs != lval->lhs) &&
9017 (!triple_is_def(state, lval) || tuple->lhs != 1))
9019 internal_error(state, ins, "lhs size inconsistency?");
9021 for(i = 0; i < tuple->lhs; i++) {
9022 struct triple *piece, *write, *pval, *bitref;
9023 if ((i != 0) || !triple_is_def(state, lval)) {
9024 piece = LHS(lval, i);
9028 if ((i == 0) && (tuple->lhs == 1) && (val->lhs == 0)) {
9033 internal_error(state, ins, "lhs size inconsistency?");
9038 /* See if the piece is really a bitref */
9040 if (piece->op == OP_BITREF) {
9041 struct triple *read, *deposit;
9043 piece = RHS(bitref, 0);
9045 /* Read the destination register */
9046 get_occurance(tuple->occurance);
9047 read = alloc_triple(state, OP_READ, piece->type, -1, -1,
9049 RHS(read, 0) = piece;
9051 /* Deposit the new bitfield value */
9052 get_occurance(tuple->occurance);
9053 deposit = alloc_triple(state, OP_DEPOSIT, piece->type, -1, -1,
9055 RHS(deposit, 0) = read;
9056 RHS(deposit, 1) = pval;
9057 deposit->u.bitfield.size = bitref->u.bitfield.size;
9058 deposit->u.bitfield.offset = bitref->u.bitfield.offset;
9060 /* Now write the newly generated value */
9064 get_occurance(tuple->occurance);
9065 write = alloc_triple(state, OP_WRITE, piece->type, -1, -1,
9067 MISC(write, 0) = piece;
9068 RHS(write, 0) = pval;
9069 LHS(tuple, i) = write;
9071 return decompose_with_tuple(state, ins, tuple);
9074 struct decompose_load_info {
9075 struct occurance *occurance;
9076 struct triple *lval;
9077 struct triple *tuple;
9079 static void decompose_load_cb(struct compile_state *state,
9080 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9082 struct decompose_load_info *info = arg;
9083 struct triple *load;
9085 if (reg_offset > info->tuple->lhs) {
9086 internal_error(state, info->tuple, "lhs to small?");
9088 get_occurance(info->occurance);
9089 load = alloc_triple(state, OP_LOAD, type, -1, -1, info->occurance);
9090 RHS(load, 0) = mk_addr_expr(state, info->lval, mem_offset);
9091 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = load;
9094 static struct triple *decompose_load(struct compile_state *state,
9097 struct triple *tuple;
9098 struct decompose_load_info info;
9100 if (!is_compound_type(ins->type)) {
9103 get_occurance(ins->occurance);
9104 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9107 info.occurance = ins->occurance;
9108 info.lval = RHS(ins, 0);
9110 walk_type_fields(state, ins->type, 0, 0, decompose_load_cb, &info);
9112 return decompose_with_tuple(state, ins, tuple);
9116 struct decompose_store_info {
9117 struct occurance *occurance;
9118 struct triple *lval;
9120 struct triple *tuple;
9122 static void decompose_store_cb(struct compile_state *state,
9123 struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9125 struct decompose_store_info *info = arg;
9126 struct triple *store;
9128 if (reg_offset > info->tuple->lhs) {
9129 internal_error(state, info->tuple, "lhs to small?");
9131 get_occurance(info->occurance);
9132 store = alloc_triple(state, OP_STORE, type, -1, -1, info->occurance);
9133 RHS(store, 0) = mk_addr_expr(state, info->lval, mem_offset);
9134 RHS(store, 1) = LHS(info->val, reg_offset);
9135 LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = store;
9138 static struct triple *decompose_store(struct compile_state *state,
9141 struct triple *tuple;
9142 struct decompose_store_info info;
9144 if (!is_compound_type(ins->type)) {
9147 get_occurance(ins->occurance);
9148 tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9151 info.occurance = ins->occurance;
9152 info.lval = RHS(ins, 0);
9153 info.val = RHS(ins, 1);
9155 walk_type_fields(state, ins->type, 0, 0, decompose_store_cb, &info);
9157 return decompose_with_tuple(state, ins, tuple);
9160 static struct triple *decompose_dot(struct compile_state *state,
9163 struct triple *tuple, *lval;
9168 lval = MISC(ins, 0);
9169 reg_offset = field_reg_offset(state, lval->type, ins->u.field);
9170 idx = reg_offset/REG_SIZEOF_REG;
9171 type = field_type(state, lval->type, ins->u.field);
9172 #if DEBUG_DECOMPOSE_HIRES
9174 FILE *fp = state->dbgout;
9175 fprintf(fp, "field type: ");
9181 get_occurance(ins->occurance);
9182 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9185 if (((ins->type->type & TYPE_MASK) == TYPE_BITFIELD) &&
9188 internal_error(state, ins, "multi register bitfield?");
9191 for(i = 0; i < tuple->lhs; i++, idx++) {
9192 struct triple *piece;
9193 if (!triple_is_def(state, lval)) {
9194 if (idx > lval->lhs) {
9195 internal_error(state, ins, "inconsistent lhs count");
9197 piece = LHS(lval, idx);
9200 internal_error(state, ins, "bad reg_offset into def");
9203 internal_error(state, ins, "bad reg count from def");
9208 /* Remember the offset of the bitfield */
9209 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
9210 get_occurance(ins->occurance);
9211 piece = build_triple(state, OP_BITREF, type, piece, 0,
9213 piece->u.bitfield.size = size_of(state, type);
9214 piece->u.bitfield.offset = reg_offset % REG_SIZEOF_REG;
9216 else if ((reg_offset % REG_SIZEOF_REG) != 0) {
9217 internal_error(state, ins,
9218 "request for a nonbitfield sub register?");
9221 LHS(tuple, i) = piece;
9224 return decompose_with_tuple(state, ins, tuple);
9227 static struct triple *decompose_index(struct compile_state *state,
9230 struct triple *tuple, *lval;
9234 lval = MISC(ins, 0);
9235 idx = index_reg_offset(state, lval->type, ins->u.cval)/REG_SIZEOF_REG;
9236 type = index_type(state, lval->type, ins->u.cval);
9237 #if DEBUG_DECOMPOSE_HIRES
9239 FILE *fp = state->dbgout;
9240 fprintf(fp, "index type: ");
9246 get_occurance(ins->occurance);
9247 tuple = alloc_triple(state, OP_TUPLE, type, -1, -1,
9250 for(i = 0; i < tuple->lhs; i++, idx++) {
9251 struct triple *piece;
9252 if (!triple_is_def(state, lval)) {
9253 if (idx > lval->lhs) {
9254 internal_error(state, ins, "inconsistent lhs count");
9256 piece = LHS(lval, idx);
9259 internal_error(state, ins, "bad reg_offset into def");
9262 internal_error(state, ins, "bad reg count from def");
9266 LHS(tuple, i) = piece;
9269 return decompose_with_tuple(state, ins, tuple);
9272 static void decompose_compound_types(struct compile_state *state)
9274 struct triple *ins, *next, *first;
9277 first = state->first;
9280 /* Pass one expand compound values into pseudo registers.
9288 next = decompose_unknownval(state, ins);
9292 next = decompose_read(state, ins);
9296 next = decompose_write(state, ins);
9300 /* Be very careful with the load/store logic. These
9301 * operations must convert from the in register layout
9302 * to the in memory layout, which is nontrivial.
9305 next = decompose_load(state, ins);
9308 next = decompose_store(state, ins);
9312 next = decompose_dot(state, ins);
9315 next = decompose_index(state, ins);
9319 #if DEBUG_DECOMPOSE_HIRES
9320 fprintf(fp, "decompose next: %p \n", next);
9322 fprintf(fp, "next->op: %d %s\n",
9323 next->op, tops(next->op));
9324 /* High resolution debugging mode */
9325 print_triples(state);
9327 } while (next != first);
9329 /* Pass two remove the tuples.
9334 if (ins->op == OP_TUPLE) {
9336 internal_error(state, ins, "tuple used");
9339 release_triple(state, ins);
9343 } while(ins != first);
9347 if (ins->op == OP_BITREF) {
9349 internal_error(state, ins, "bitref used");
9352 release_triple(state, ins);
9356 } while(ins != first);
9358 /* Pass three verify the state and set ->id to 0.
9364 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9365 if (triple_stores_block(state, ins)) {
9368 if (triple_is_def(state, ins)) {
9369 if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9370 internal_error(state, ins, "multi register value remains?");
9373 if (ins->op == OP_DOT) {
9374 internal_error(state, ins, "OP_DOT remains?");
9376 if (ins->op == OP_INDEX) {
9377 internal_error(state, ins, "OP_INDEX remains?");
9379 if (ins->op == OP_BITREF) {
9380 internal_error(state, ins, "OP_BITREF remains?");
9382 if (ins->op == OP_TUPLE) {
9383 internal_error(state, ins, "OP_TUPLE remains?");
9385 } while(next != first);
9388 /* For those operations that cannot be simplified */
9389 static void simplify_noop(struct compile_state *state, struct triple *ins)
9394 static void simplify_smul(struct compile_state *state, struct triple *ins)
9396 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9399 RHS(ins, 0) = RHS(ins, 1);
9402 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9404 left = read_sconst(state, ins, RHS(ins, 0));
9405 right = read_sconst(state, ins, RHS(ins, 1));
9406 mkconst(state, ins, left * right);
9408 else if (is_zero(RHS(ins, 1))) {
9409 mkconst(state, ins, 0);
9411 else if (is_one(RHS(ins, 1))) {
9412 mkcopy(state, ins, RHS(ins, 0));
9414 else if (is_pow2(RHS(ins, 1))) {
9416 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9418 insert_triple(state, state->global_pool, val);
9419 unuse_triple(RHS(ins, 1), ins);
9420 use_triple(val, ins);
9425 static void simplify_umul(struct compile_state *state, struct triple *ins)
9427 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9430 RHS(ins, 0) = RHS(ins, 1);
9433 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9434 ulong_t left, right;
9435 left = read_const(state, ins, RHS(ins, 0));
9436 right = read_const(state, ins, RHS(ins, 1));
9437 mkconst(state, ins, left * right);
9439 else if (is_zero(RHS(ins, 1))) {
9440 mkconst(state, ins, 0);
9442 else if (is_one(RHS(ins, 1))) {
9443 mkcopy(state, ins, RHS(ins, 0));
9445 else if (is_pow2(RHS(ins, 1))) {
9447 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9449 insert_triple(state, state->global_pool, val);
9450 unuse_triple(RHS(ins, 1), ins);
9451 use_triple(val, ins);
9456 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9458 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9460 left = read_sconst(state, ins, RHS(ins, 0));
9461 right = read_sconst(state, ins, RHS(ins, 1));
9462 mkconst(state, ins, left / right);
9464 else if (is_zero(RHS(ins, 0))) {
9465 mkconst(state, ins, 0);
9467 else if (is_zero(RHS(ins, 1))) {
9468 error(state, ins, "division by zero");
9470 else if (is_one(RHS(ins, 1))) {
9471 mkcopy(state, ins, RHS(ins, 0));
9473 else if (is_pow2(RHS(ins, 1))) {
9475 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9477 insert_triple(state, state->global_pool, val);
9478 unuse_triple(RHS(ins, 1), ins);
9479 use_triple(val, ins);
9484 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9486 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9487 ulong_t left, right;
9488 left = read_const(state, ins, RHS(ins, 0));
9489 right = read_const(state, ins, RHS(ins, 1));
9490 mkconst(state, ins, left / right);
9492 else if (is_zero(RHS(ins, 0))) {
9493 mkconst(state, ins, 0);
9495 else if (is_zero(RHS(ins, 1))) {
9496 error(state, ins, "division by zero");
9498 else if (is_one(RHS(ins, 1))) {
9499 mkcopy(state, ins, RHS(ins, 0));
9501 else if (is_pow2(RHS(ins, 1))) {
9503 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9505 insert_triple(state, state->global_pool, val);
9506 unuse_triple(RHS(ins, 1), ins);
9507 use_triple(val, ins);
9512 static void simplify_smod(struct compile_state *state, struct triple *ins)
9514 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9516 left = read_const(state, ins, RHS(ins, 0));
9517 right = read_const(state, ins, RHS(ins, 1));
9518 mkconst(state, ins, left % right);
9520 else if (is_zero(RHS(ins, 0))) {
9521 mkconst(state, ins, 0);
9523 else if (is_zero(RHS(ins, 1))) {
9524 error(state, ins, "division by zero");
9526 else if (is_one(RHS(ins, 1))) {
9527 mkconst(state, ins, 0);
9529 else if (is_pow2(RHS(ins, 1))) {
9531 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9533 insert_triple(state, state->global_pool, val);
9534 unuse_triple(RHS(ins, 1), ins);
9535 use_triple(val, ins);
9540 static void simplify_umod(struct compile_state *state, struct triple *ins)
9542 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9543 ulong_t left, right;
9544 left = read_const(state, ins, RHS(ins, 0));
9545 right = read_const(state, ins, RHS(ins, 1));
9546 mkconst(state, ins, left % right);
9548 else if (is_zero(RHS(ins, 0))) {
9549 mkconst(state, ins, 0);
9551 else if (is_zero(RHS(ins, 1))) {
9552 error(state, ins, "division by zero");
9554 else if (is_one(RHS(ins, 1))) {
9555 mkconst(state, ins, 0);
9557 else if (is_pow2(RHS(ins, 1))) {
9559 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9561 insert_triple(state, state->global_pool, val);
9562 unuse_triple(RHS(ins, 1), ins);
9563 use_triple(val, ins);
9568 static void simplify_add(struct compile_state *state, struct triple *ins)
9570 /* start with the pointer on the left */
9571 if (is_pointer(RHS(ins, 1))) {
9574 RHS(ins, 0) = RHS(ins, 1);
9577 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9578 if (RHS(ins, 0)->op == OP_INTCONST) {
9579 ulong_t left, right;
9580 left = read_const(state, ins, RHS(ins, 0));
9581 right = read_const(state, ins, RHS(ins, 1));
9582 mkconst(state, ins, left + right);
9584 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9585 struct triple *sdecl;
9586 ulong_t left, right;
9587 sdecl = MISC(RHS(ins, 0), 0);
9588 left = RHS(ins, 0)->u.cval;
9589 right = RHS(ins, 1)->u.cval;
9590 mkaddr_const(state, ins, sdecl, left + right);
9593 internal_warning(state, ins, "Optimize me!");
9596 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9599 RHS(ins, 1) = RHS(ins, 0);
9604 static void simplify_sub(struct compile_state *state, struct triple *ins)
9606 if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9607 if (RHS(ins, 0)->op == OP_INTCONST) {
9608 ulong_t left, right;
9609 left = read_const(state, ins, RHS(ins, 0));
9610 right = read_const(state, ins, RHS(ins, 1));
9611 mkconst(state, ins, left - right);
9613 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9614 struct triple *sdecl;
9615 ulong_t left, right;
9616 sdecl = MISC(RHS(ins, 0), 0);
9617 left = RHS(ins, 0)->u.cval;
9618 right = RHS(ins, 1)->u.cval;
9619 mkaddr_const(state, ins, sdecl, left - right);
9622 internal_warning(state, ins, "Optimize me!");
9627 static void simplify_sl(struct compile_state *state, struct triple *ins)
9629 if (is_simple_const(RHS(ins, 1))) {
9631 right = read_const(state, ins, RHS(ins, 1));
9632 if (right >= (size_of(state, ins->type))) {
9633 warning(state, ins, "left shift count >= width of type");
9636 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9637 ulong_t left, right;
9638 left = read_const(state, ins, RHS(ins, 0));
9639 right = read_const(state, ins, RHS(ins, 1));
9640 mkconst(state, ins, left << right);
9644 static void simplify_usr(struct compile_state *state, struct triple *ins)
9646 if (is_simple_const(RHS(ins, 1))) {
9648 right = read_const(state, ins, RHS(ins, 1));
9649 if (right >= (size_of(state, ins->type))) {
9650 warning(state, ins, "right shift count >= width of type");
9653 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9654 ulong_t left, right;
9655 left = read_const(state, ins, RHS(ins, 0));
9656 right = read_const(state, ins, RHS(ins, 1));
9657 mkconst(state, ins, left >> right);
9661 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9663 if (is_simple_const(RHS(ins, 1))) {
9665 right = read_const(state, ins, RHS(ins, 1));
9666 if (right >= (size_of(state, ins->type))) {
9667 warning(state, ins, "right shift count >= width of type");
9670 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9672 left = read_sconst(state, ins, RHS(ins, 0));
9673 right = read_sconst(state, ins, RHS(ins, 1));
9674 mkconst(state, ins, left >> right);
9678 static void simplify_and(struct compile_state *state, struct triple *ins)
9680 struct triple *left, *right;
9682 right = RHS(ins, 1);
9684 if (is_simple_const(left) && is_simple_const(right)) {
9686 lval = read_const(state, ins, left);
9687 rval = read_const(state, ins, right);
9688 mkconst(state, ins, lval & rval);
9690 else if (is_zero(right) || is_zero(left)) {
9691 mkconst(state, ins, 0);
9695 static void simplify_or(struct compile_state *state, struct triple *ins)
9697 struct triple *left, *right;
9699 right = RHS(ins, 1);
9701 if (is_simple_const(left) && is_simple_const(right)) {
9703 lval = read_const(state, ins, left);
9704 rval = read_const(state, ins, right);
9705 mkconst(state, ins, lval | rval);
9707 #if 0 /* I need to handle type mismatches here... */
9708 else if (is_zero(right)) {
9709 mkcopy(state, ins, left);
9711 else if (is_zero(left)) {
9712 mkcopy(state, ins, right);
9717 static void simplify_xor(struct compile_state *state, struct triple *ins)
9719 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9720 ulong_t left, right;
9721 left = read_const(state, ins, RHS(ins, 0));
9722 right = read_const(state, ins, RHS(ins, 1));
9723 mkconst(state, ins, left ^ right);
9727 static void simplify_pos(struct compile_state *state, struct triple *ins)
9729 if (is_const(RHS(ins, 0))) {
9730 mkconst(state, ins, RHS(ins, 0)->u.cval);
9733 mkcopy(state, ins, RHS(ins, 0));
9737 static void simplify_neg(struct compile_state *state, struct triple *ins)
9739 if (is_simple_const(RHS(ins, 0))) {
9741 left = read_const(state, ins, RHS(ins, 0));
9742 mkconst(state, ins, -left);
9744 else if (RHS(ins, 0)->op == OP_NEG) {
9745 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9749 static void simplify_invert(struct compile_state *state, struct triple *ins)
9751 if (is_simple_const(RHS(ins, 0))) {
9753 left = read_const(state, ins, RHS(ins, 0));
9754 mkconst(state, ins, ~left);
9758 static void simplify_eq(struct compile_state *state, struct triple *ins)
9760 struct triple *left, *right;
9762 right = RHS(ins, 1);
9764 if (is_const(left) && is_const(right)) {
9766 val = const_eq(state, ins, left, right);
9768 mkconst(state, ins, val == 1);
9771 else if (left == right) {
9772 mkconst(state, ins, 1);
9776 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9778 struct triple *left, *right;
9780 right = RHS(ins, 1);
9782 if (is_const(left) && is_const(right)) {
9784 val = const_eq(state, ins, left, right);
9786 mkconst(state, ins, val != 1);
9789 if (left == right) {
9790 mkconst(state, ins, 0);
9794 static void simplify_sless(struct compile_state *state, struct triple *ins)
9796 struct triple *left, *right;
9798 right = RHS(ins, 1);
9800 if (is_const(left) && is_const(right)) {
9802 val = const_scmp(state, ins, left, right);
9803 if ((val >= -1) && (val <= 1)) {
9804 mkconst(state, ins, val < 0);
9807 else if (left == right) {
9808 mkconst(state, ins, 0);
9812 static void simplify_uless(struct compile_state *state, struct triple *ins)
9814 struct triple *left, *right;
9816 right = RHS(ins, 1);
9818 if (is_const(left) && is_const(right)) {
9820 val = const_ucmp(state, ins, left, right);
9821 if ((val >= -1) && (val <= 1)) {
9822 mkconst(state, ins, val < 0);
9825 else if (is_zero(right)) {
9826 mkconst(state, ins, 0);
9828 else if (left == right) {
9829 mkconst(state, ins, 0);
9833 static void simplify_smore(struct compile_state *state, struct triple *ins)
9835 struct triple *left, *right;
9837 right = RHS(ins, 1);
9839 if (is_const(left) && is_const(right)) {
9841 val = const_scmp(state, ins, left, right);
9842 if ((val >= -1) && (val <= 1)) {
9843 mkconst(state, ins, val > 0);
9846 else if (left == right) {
9847 mkconst(state, ins, 0);
9851 static void simplify_umore(struct compile_state *state, struct triple *ins)
9853 struct triple *left, *right;
9855 right = RHS(ins, 1);
9857 if (is_const(left) && is_const(right)) {
9859 val = const_ucmp(state, ins, left, right);
9860 if ((val >= -1) && (val <= 1)) {
9861 mkconst(state, ins, val > 0);
9864 else if (is_zero(left)) {
9865 mkconst(state, ins, 0);
9867 else if (left == right) {
9868 mkconst(state, ins, 0);
9873 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9875 struct triple *left, *right;
9877 right = RHS(ins, 1);
9879 if (is_const(left) && is_const(right)) {
9881 val = const_scmp(state, ins, left, right);
9882 if ((val >= -1) && (val <= 1)) {
9883 mkconst(state, ins, val <= 0);
9886 else if (left == right) {
9887 mkconst(state, ins, 1);
9891 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9893 struct triple *left, *right;
9895 right = RHS(ins, 1);
9897 if (is_const(left) && is_const(right)) {
9899 val = const_ucmp(state, ins, left, right);
9900 if ((val >= -1) && (val <= 1)) {
9901 mkconst(state, ins, val <= 0);
9904 else if (is_zero(left)) {
9905 mkconst(state, ins, 1);
9907 else if (left == right) {
9908 mkconst(state, ins, 1);
9912 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9914 struct triple *left, *right;
9916 right = RHS(ins, 1);
9918 if (is_const(left) && is_const(right)) {
9920 val = const_scmp(state, ins, left, right);
9921 if ((val >= -1) && (val <= 1)) {
9922 mkconst(state, ins, val >= 0);
9925 else if (left == right) {
9926 mkconst(state, ins, 1);
9930 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9932 struct triple *left, *right;
9934 right = RHS(ins, 1);
9936 if (is_const(left) && is_const(right)) {
9938 val = const_ucmp(state, ins, left, right);
9939 if ((val >= -1) && (val <= 1)) {
9940 mkconst(state, ins, val >= 0);
9943 else if (is_zero(right)) {
9944 mkconst(state, ins, 1);
9946 else if (left == right) {
9947 mkconst(state, ins, 1);
9951 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9956 if (is_const(rhs)) {
9957 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9959 /* Otherwise if I am the only user... */
9960 else if ((rhs->use) &&
9961 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9963 /* Invert a boolean operation */
9965 case OP_LTRUE: rhs->op = OP_LFALSE; break;
9966 case OP_LFALSE: rhs->op = OP_LTRUE; break;
9967 case OP_EQ: rhs->op = OP_NOTEQ; break;
9968 case OP_NOTEQ: rhs->op = OP_EQ; break;
9969 case OP_SLESS: rhs->op = OP_SMOREEQ; break;
9970 case OP_ULESS: rhs->op = OP_UMOREEQ; break;
9971 case OP_SMORE: rhs->op = OP_SLESSEQ; break;
9972 case OP_UMORE: rhs->op = OP_ULESSEQ; break;
9973 case OP_SLESSEQ: rhs->op = OP_SMORE; break;
9974 case OP_ULESSEQ: rhs->op = OP_UMORE; break;
9975 case OP_SMOREEQ: rhs->op = OP_SLESS; break;
9976 case OP_UMOREEQ: rhs->op = OP_ULESS; break;
9982 mkcopy(state, ins, rhs);
9987 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9992 if (is_const(rhs)) {
9993 mkconst(state, ins, const_ltrue(state, ins, rhs));
9995 else switch(rhs->op) {
9996 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
9997 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
9998 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9999 mkcopy(state, ins, rhs);
10004 static void simplify_load(struct compile_state *state, struct triple *ins)
10006 struct triple *addr, *sdecl, *blob;
10008 /* If I am doing a load with a constant pointer from a constant
10009 * table get the value.
10011 addr = RHS(ins, 0);
10012 if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
10013 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
10014 (blob->op == OP_BLOBCONST)) {
10015 unsigned char buffer[SIZEOF_WORD];
10016 size_t reg_size, mem_size;
10019 reg_size = reg_size_of(state, ins->type);
10020 if (reg_size > REG_SIZEOF_REG) {
10021 internal_error(state, ins, "load size greater than register");
10023 mem_size = size_of(state, ins->type);
10024 src = blob->u.blob;
10025 src += addr->u.cval;
10027 memset(buffer, 0, sizeof(buffer));
10028 memcpy(buffer, src, bits_to_bytes(mem_size));
10031 case SIZEOF_I8: val = *((uint8_t *) buffer); break;
10032 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
10033 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
10034 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
10036 internal_error(state, ins, "mem_size: %d not handled",
10041 mkconst(state, ins, val);
10045 static void simplify_uextract(struct compile_state *state, struct triple *ins)
10047 if (is_simple_const(RHS(ins, 0))) {
10050 val = read_const(state, ins, RHS(ins, 0));
10052 mask <<= ins->u.bitfield.size;
10054 val >>= ins->u.bitfield.offset;
10056 mkconst(state, ins, val);
10060 static void simplify_sextract(struct compile_state *state, struct triple *ins)
10062 if (is_simple_const(RHS(ins, 0))) {
10066 val = read_const(state, ins, RHS(ins, 0));
10068 mask <<= ins->u.bitfield.size;
10070 val >>= ins->u.bitfield.offset;
10072 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
10074 sval >>= (SIZEOF_LONG - ins->u.bitfield.size);
10075 mkconst(state, ins, sval);
10079 static void simplify_deposit(struct compile_state *state, struct triple *ins)
10081 if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
10084 targ = read_const(state, ins, RHS(ins, 0));
10085 val = read_const(state, ins, RHS(ins, 1));
10087 mask <<= ins->u.bitfield.size;
10089 mask <<= ins->u.bitfield.offset;
10091 val <<= ins->u.bitfield.offset;
10094 mkconst(state, ins, targ);
10098 static void simplify_copy(struct compile_state *state, struct triple *ins)
10100 struct triple *right;
10101 right = RHS(ins, 0);
10102 if (is_subset_type(ins->type, right->type)) {
10103 ins->type = right->type;
10105 if (equiv_types(ins->type, right->type)) {
10106 ins->op = OP_COPY;/* I don't need to convert if the types match */
10108 if (ins->op == OP_COPY) {
10109 internal_error(state, ins, "type mismatch on copy");
10112 if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
10113 struct triple *sdecl;
10115 sdecl = MISC(right, 0);
10116 offset = right->u.cval;
10117 mkaddr_const(state, ins, sdecl, offset);
10119 else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
10120 switch(right->op) {
10124 left = read_const(state, ins, right);
10125 /* Ensure I have not overflowed the destination. */
10126 if (size_of(state, right->type) > size_of(state, ins->type)) {
10129 mask <<= size_of(state, ins->type);
10133 /* Ensure I am properly sign extended */
10134 if (size_of(state, right->type) < size_of(state, ins->type) &&
10135 is_signed(right->type)) {
10138 shift = SIZEOF_LONG - size_of(state, right->type);
10144 mkconst(state, ins, left);
10148 internal_error(state, ins, "uknown constant");
10154 static int phi_present(struct block *block)
10156 struct triple *ptr;
10160 ptr = block->first;
10162 if (ptr->op == OP_PHI) {
10166 } while(ptr != block->last);
10170 static int phi_dependency(struct block *block)
10172 /* A block has a phi dependency if a phi function
10173 * depends on that block to exist, and makes a block
10174 * that is otherwise useless unsafe to remove.
10177 struct block_set *edge;
10178 for(edge = block->edges; edge; edge = edge->next) {
10179 if (phi_present(edge->member)) {
10187 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10189 struct triple *targ;
10190 targ = TARG(ins, 0);
10191 /* During scc_transform temporary triples are allocated that
10192 * loop back onto themselves. If I see one don't advance the
10195 while(triple_is_structural(state, targ) &&
10196 (targ->next != targ) && (targ->next != state->first)) {
10203 static void simplify_branch(struct compile_state *state, struct triple *ins)
10205 int simplified, loops;
10206 if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10207 internal_error(state, ins, "not branch");
10209 if (ins->use != 0) {
10210 internal_error(state, ins, "branch use");
10212 /* The challenge here with simplify branch is that I need to
10213 * make modifications to the control flow graph as well
10214 * as to the branch instruction itself. That is handled
10215 * by rebuilding the basic blocks after simplify all is called.
10218 /* If we have a branch to an unconditional branch update
10219 * our target. But watch out for dependencies from phi
10221 * Also only do this a limited number of times so
10222 * we don't get into an infinite loop.
10226 struct triple *targ;
10228 targ = branch_target(state, ins);
10229 if ((targ != ins) && (targ->op == OP_BRANCH) &&
10230 !phi_dependency(targ->u.block))
10232 unuse_triple(TARG(ins, 0), ins);
10233 TARG(ins, 0) = TARG(targ, 0);
10234 use_triple(TARG(ins, 0), ins);
10237 } while(simplified && (++loops < 20));
10239 /* If we have a conditional branch with a constant condition
10240 * make it an unconditional branch.
10242 if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10243 struct triple *targ;
10245 value = read_const(state, ins, RHS(ins, 0));
10246 unuse_triple(RHS(ins, 0), ins);
10247 targ = TARG(ins, 0);
10250 ins->op = OP_BRANCH;
10252 unuse_triple(ins->next, ins);
10253 TARG(ins, 0) = targ;
10256 unuse_triple(targ, ins);
10257 TARG(ins, 0) = ins->next;
10261 /* If we have a branch to the next instruction,
10264 if (TARG(ins, 0) == ins->next) {
10265 unuse_triple(TARG(ins, 0), ins);
10266 if (ins->op == OP_CBRANCH) {
10267 unuse_triple(RHS(ins, 0), ins);
10268 unuse_triple(ins->next, ins);
10276 internal_error(state, ins, "noop use != 0");
10281 static void simplify_label(struct compile_state *state, struct triple *ins)
10283 /* Ignore volatile labels */
10284 if (!triple_is_pure(state, ins, ins->id)) {
10287 if (ins->use == 0) {
10290 else if (ins->prev->op == OP_LABEL) {
10291 /* In general it is not safe to merge one label that
10292 * imediately follows another. The problem is that the empty
10293 * looking block may have phi functions that depend on it.
10295 if (!phi_dependency(ins->prev->u.block)) {
10296 struct triple_set *user, *next;
10298 for(user = ins->use; user; user = next) {
10299 struct triple *use, **expr;
10301 use = user->member;
10302 expr = triple_targ(state, use, 0);
10303 for(;expr; expr = triple_targ(state, use, expr)) {
10304 if (*expr == ins) {
10306 unuse_triple(ins, use);
10307 use_triple(ins->prev, use);
10313 internal_error(state, ins, "noop use != 0");
10319 static void simplify_phi(struct compile_state *state, struct triple *ins)
10321 struct triple **slot;
10322 struct triple *value;
10325 slot = &RHS(ins, 0);
10330 /* See if all of the rhs members of a phi have the same value */
10331 if (slot[0] && is_simple_const(slot[0])) {
10332 cvalue = read_const(state, ins, slot[0]);
10333 for(i = 1; i < zrhs; i++) {
10335 !is_simple_const(slot[i]) ||
10336 !equiv_types(slot[0]->type, slot[i]->type) ||
10337 (cvalue != read_const(state, ins, slot[i]))) {
10342 mkconst(state, ins, cvalue);
10347 /* See if all of rhs members of a phi are the same */
10349 for(i = 1; i < zrhs; i++) {
10350 if (slot[i] != value) {
10355 /* If the phi has a single value just copy it */
10356 if (!is_subset_type(ins->type, value->type)) {
10357 internal_error(state, ins, "bad input type to phi");
10359 /* Make the types match */
10360 if (!equiv_types(ins->type, value->type)) {
10361 ins->type = value->type;
10363 /* Now make the actual copy */
10364 mkcopy(state, ins, value);
10370 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10372 if (is_simple_const(RHS(ins, 0))) {
10374 left = read_const(state, ins, RHS(ins, 0));
10375 mkconst(state, ins, bsf(left));
10379 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10381 if (is_simple_const(RHS(ins, 0))) {
10383 left = read_const(state, ins, RHS(ins, 0));
10384 mkconst(state, ins, bsr(left));
10389 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10390 static const struct simplify_table {
10392 unsigned long flag;
10393 } table_simplify[] = {
10394 #define simplify_sdivt simplify_noop
10395 #define simplify_udivt simplify_noop
10396 #define simplify_piece simplify_noop
10398 [OP_SDIVT ] = { simplify_sdivt, COMPILER_SIMPLIFY_ARITH },
10399 [OP_UDIVT ] = { simplify_udivt, COMPILER_SIMPLIFY_ARITH },
10400 [OP_SMUL ] = { simplify_smul, COMPILER_SIMPLIFY_ARITH },
10401 [OP_UMUL ] = { simplify_umul, COMPILER_SIMPLIFY_ARITH },
10402 [OP_SDIV ] = { simplify_sdiv, COMPILER_SIMPLIFY_ARITH },
10403 [OP_UDIV ] = { simplify_udiv, COMPILER_SIMPLIFY_ARITH },
10404 [OP_SMOD ] = { simplify_smod, COMPILER_SIMPLIFY_ARITH },
10405 [OP_UMOD ] = { simplify_umod, COMPILER_SIMPLIFY_ARITH },
10406 [OP_ADD ] = { simplify_add, COMPILER_SIMPLIFY_ARITH },
10407 [OP_SUB ] = { simplify_sub, COMPILER_SIMPLIFY_ARITH },
10408 [OP_SL ] = { simplify_sl, COMPILER_SIMPLIFY_SHIFT },
10409 [OP_USR ] = { simplify_usr, COMPILER_SIMPLIFY_SHIFT },
10410 [OP_SSR ] = { simplify_ssr, COMPILER_SIMPLIFY_SHIFT },
10411 [OP_AND ] = { simplify_and, COMPILER_SIMPLIFY_BITWISE },
10412 [OP_XOR ] = { simplify_xor, COMPILER_SIMPLIFY_BITWISE },
10413 [OP_OR ] = { simplify_or, COMPILER_SIMPLIFY_BITWISE },
10414 [OP_POS ] = { simplify_pos, COMPILER_SIMPLIFY_ARITH },
10415 [OP_NEG ] = { simplify_neg, COMPILER_SIMPLIFY_ARITH },
10416 [OP_INVERT ] = { simplify_invert, COMPILER_SIMPLIFY_BITWISE },
10418 [OP_EQ ] = { simplify_eq, COMPILER_SIMPLIFY_LOGICAL },
10419 [OP_NOTEQ ] = { simplify_noteq, COMPILER_SIMPLIFY_LOGICAL },
10420 [OP_SLESS ] = { simplify_sless, COMPILER_SIMPLIFY_LOGICAL },
10421 [OP_ULESS ] = { simplify_uless, COMPILER_SIMPLIFY_LOGICAL },
10422 [OP_SMORE ] = { simplify_smore, COMPILER_SIMPLIFY_LOGICAL },
10423 [OP_UMORE ] = { simplify_umore, COMPILER_SIMPLIFY_LOGICAL },
10424 [OP_SLESSEQ ] = { simplify_slesseq, COMPILER_SIMPLIFY_LOGICAL },
10425 [OP_ULESSEQ ] = { simplify_ulesseq, COMPILER_SIMPLIFY_LOGICAL },
10426 [OP_SMOREEQ ] = { simplify_smoreeq, COMPILER_SIMPLIFY_LOGICAL },
10427 [OP_UMOREEQ ] = { simplify_umoreeq, COMPILER_SIMPLIFY_LOGICAL },
10428 [OP_LFALSE ] = { simplify_lfalse, COMPILER_SIMPLIFY_LOGICAL },
10429 [OP_LTRUE ] = { simplify_ltrue, COMPILER_SIMPLIFY_LOGICAL },
10431 [OP_LOAD ] = { simplify_load, COMPILER_SIMPLIFY_OP },
10432 [OP_STORE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10434 [OP_UEXTRACT ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10435 [OP_SEXTRACT ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10436 [OP_DEPOSIT ] = { simplify_deposit, COMPILER_SIMPLIFY_BITFIELD },
10438 [OP_NOOP ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10440 [OP_INTCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10441 [OP_BLOBCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10442 [OP_ADDRCONST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10443 [OP_UNKNOWNVAL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10445 [OP_WRITE ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10446 [OP_READ ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10447 [OP_COPY ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10448 [OP_CONVERT ] = { simplify_copy, COMPILER_SIMPLIFY_COPY },
10449 [OP_PIECE ] = { simplify_piece, COMPILER_SIMPLIFY_OP },
10450 [OP_ASM ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10452 [OP_DOT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10453 [OP_INDEX ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10455 [OP_LIST ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10456 [OP_BRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10457 [OP_CBRANCH ] = { simplify_branch, COMPILER_SIMPLIFY_BRANCH },
10458 [OP_CALL ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10459 [OP_RET ] = { simplify_noop, COMPILER_SIMPLIFY_BRANCH },
10460 [OP_LABEL ] = { simplify_label, COMPILER_SIMPLIFY_LABEL },
10461 [OP_ADECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10462 [OP_SDECL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10463 [OP_PHI ] = { simplify_phi, COMPILER_SIMPLIFY_PHI },
10465 [OP_INB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10466 [OP_INW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10467 [OP_INL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10468 [OP_OUTB ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10469 [OP_OUTW ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10470 [OP_OUTL ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10471 [OP_BSF ] = { simplify_bsf, COMPILER_SIMPLIFY_OP },
10472 [OP_BSR ] = { simplify_bsr, COMPILER_SIMPLIFY_OP },
10473 [OP_RDMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10474 [OP_WRMSR ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10475 [OP_HLT ] = { simplify_noop, COMPILER_SIMPLIFY_OP },
10478 static inline void debug_simplify(struct compile_state *state,
10479 simplify_t do_simplify, struct triple *ins)
10481 #if DEBUG_SIMPLIFY_HIRES
10482 if (state->functions_joined && (do_simplify != simplify_noop)) {
10483 /* High resolution debugging mode */
10484 fprintf(state->dbgout, "simplifing: ");
10485 display_triple(state->dbgout, ins);
10488 do_simplify(state, ins);
10489 #if DEBUG_SIMPLIFY_HIRES
10490 if (state->functions_joined && (do_simplify != simplify_noop)) {
10491 /* High resolution debugging mode */
10492 fprintf(state->dbgout, "simplified: ");
10493 display_triple(state->dbgout, ins);
10497 static void simplify(struct compile_state *state, struct triple *ins)
10500 simplify_t do_simplify;
10501 if (ins == &unknown_triple) {
10502 internal_error(state, ins, "simplifying the unknown triple?");
10507 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10511 do_simplify = table_simplify[op].func;
10514 !(state->compiler->flags & table_simplify[op].flag)) {
10515 do_simplify = simplify_noop;
10517 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10518 do_simplify = simplify_noop;
10521 if (!do_simplify) {
10522 internal_error(state, ins, "cannot simplify op: %d %s",
10526 debug_simplify(state, do_simplify, ins);
10527 } while(ins->op != op);
10530 static void rebuild_ssa_form(struct compile_state *state);
10532 static void simplify_all(struct compile_state *state)
10534 struct triple *ins, *first;
10535 if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10538 first = state->first;
10541 simplify(state, ins);
10543 } while(ins != first->prev);
10546 simplify(state, ins);
10548 }while(ins != first);
10549 rebuild_ssa_form(state);
10551 print_blocks(state, __func__, state->dbgout);
10556 * ============================
10559 static void register_builtin_function(struct compile_state *state,
10560 const char *name, int op, struct type *rtype, ...)
10562 struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10563 struct triple *def, *arg, *result, *work, *last, *first, *retvar, *ret;
10564 struct hash_entry *ident;
10565 struct file_state file;
10571 /* Dummy file state to get debug handling right */
10572 memset(&file, 0, sizeof(file));
10573 file.basename = "<built-in>";
10575 file.report_line = 1;
10576 file.report_name = file.basename;
10577 file.prev = state->file;
10578 state->file = &file;
10579 state->function = name;
10581 /* Find the Parameter count */
10582 valid_op(state, op);
10583 parameters = table_ops[op].rhs;
10584 if (parameters < 0 ) {
10585 internal_error(state, 0, "Invalid builtin parameter count");
10588 /* Find the function type */
10589 ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10590 ftype->elements = parameters;
10591 next = &ftype->right;
10592 va_start(args, rtype);
10593 for(i = 0; i < parameters; i++) {
10594 atype = va_arg(args, struct type *);
10598 *next = new_type(TYPE_PRODUCT, *next, atype);
10599 next = &((*next)->right);
10603 *next = &void_type;
10607 /* Get the initial closure type */
10608 ctype = new_type(TYPE_JOIN, &void_type, 0);
10609 ctype->elements = 1;
10611 /* Get the return type */
10612 crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10613 crtype->elements = 2;
10615 /* Generate the needed triples */
10616 def = triple(state, OP_LIST, ftype, 0, 0);
10617 first = label(state);
10618 RHS(def, 0) = first;
10619 result = flatten(state, first, variable(state, crtype));
10620 retvar = flatten(state, first, variable(state, &void_ptr_type));
10621 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10623 /* Now string them together */
10624 param = ftype->right;
10625 for(i = 0; i < parameters; i++) {
10626 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10627 atype = param->left;
10631 arg = flatten(state, first, variable(state, atype));
10632 param = param->right;
10634 work = new_triple(state, op, rtype, -1, parameters);
10635 generate_lhs_pieces(state, work);
10636 for(i = 0; i < parameters; i++) {
10637 RHS(work, i) = read_expr(state, farg(state, def, i));
10639 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10640 work = write_expr(state, deref_index(state, result, 1), work);
10642 work = flatten(state, first, work);
10643 last = flatten(state, first, label(state));
10644 ret = flatten(state, first, ret);
10645 name_len = strlen(name);
10646 ident = lookup(state, name, name_len);
10647 ftype->type_ident = ident;
10648 symbol(state, ident, &ident->sym_ident, def, ftype);
10650 state->file = file.prev;
10651 state->function = 0;
10652 state->main_function = 0;
10654 if (!state->functions) {
10655 state->functions = def;
10657 insert_triple(state, state->functions, def);
10659 if (state->compiler->debug & DEBUG_INLINE) {
10660 FILE *fp = state->dbgout;
10663 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10664 display_func(state, fp, def);
10665 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10669 static struct type *partial_struct(struct compile_state *state,
10670 const char *field_name, struct type *type, struct type *rest)
10672 struct hash_entry *field_ident;
10673 struct type *result;
10674 int field_name_len;
10676 field_name_len = strlen(field_name);
10677 field_ident = lookup(state, field_name, field_name_len);
10679 result = clone_type(0, type);
10680 result->field_ident = field_ident;
10683 result = new_type(TYPE_PRODUCT, result, rest);
10688 static struct type *register_builtin_type(struct compile_state *state,
10689 const char *name, struct type *type)
10691 struct hash_entry *ident;
10694 name_len = strlen(name);
10695 ident = lookup(state, name, name_len);
10697 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10698 ulong_t elements = 0;
10699 struct type *field;
10700 type = new_type(TYPE_STRUCT, type, 0);
10701 field = type->left;
10702 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10704 field = field->right;
10707 symbol(state, ident, &ident->sym_tag, 0, type);
10708 type->type_ident = ident;
10709 type->elements = elements;
10711 symbol(state, ident, &ident->sym_ident, 0, type);
10712 ident->tok = TOK_TYPE_NAME;
10717 static void register_builtins(struct compile_state *state)
10719 struct type *div_type, *ldiv_type;
10720 struct type *udiv_type, *uldiv_type;
10721 struct type *msr_type;
10723 div_type = register_builtin_type(state, "__builtin_div_t",
10724 partial_struct(state, "quot", &int_type,
10725 partial_struct(state, "rem", &int_type, 0)));
10726 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10727 partial_struct(state, "quot", &long_type,
10728 partial_struct(state, "rem", &long_type, 0)));
10729 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10730 partial_struct(state, "quot", &uint_type,
10731 partial_struct(state, "rem", &uint_type, 0)));
10732 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10733 partial_struct(state, "quot", &ulong_type,
10734 partial_struct(state, "rem", &ulong_type, 0)));
10736 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
10737 &int_type, &int_type);
10738 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
10739 &long_type, &long_type);
10740 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
10741 &uint_type, &uint_type);
10742 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10743 &ulong_type, &ulong_type);
10745 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
10747 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10749 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
10752 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
10753 &uchar_type, &ushort_type);
10754 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
10755 &ushort_type, &ushort_type);
10756 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
10757 &uint_type, &ushort_type);
10759 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
10761 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
10764 msr_type = register_builtin_type(state, "__builtin_msr_t",
10765 partial_struct(state, "lo", &ulong_type,
10766 partial_struct(state, "hi", &ulong_type, 0)));
10768 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10770 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10771 &ulong_type, &ulong_type, &ulong_type);
10773 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
10777 static struct type *declarator(
10778 struct compile_state *state, struct type *type,
10779 struct hash_entry **ident, int need_ident);
10780 static void decl(struct compile_state *state, struct triple *first);
10781 static struct type *specifier_qualifier_list(struct compile_state *state);
10782 static int isdecl_specifier(int tok);
10783 static struct type *decl_specifiers(struct compile_state *state);
10784 static int istype(int tok);
10785 static struct triple *expr(struct compile_state *state);
10786 static struct triple *assignment_expr(struct compile_state *state);
10787 static struct type *type_name(struct compile_state *state);
10788 static void statement(struct compile_state *state, struct triple *first);
10790 static struct triple *call_expr(
10791 struct compile_state *state, struct triple *func)
10793 struct triple *def;
10794 struct type *param, *type;
10795 ulong_t pvals, index;
10797 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10798 error(state, 0, "Called object is not a function");
10800 if (func->op != OP_LIST) {
10801 internal_error(state, 0, "improper function");
10803 eat(state, TOK_LPAREN);
10804 /* Find the return type without any specifiers */
10805 type = clone_type(0, func->type->left);
10806 /* Count the number of rhs entries for OP_FCALL */
10807 param = func->type->right;
10809 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10811 param = param->right;
10813 if ((param->type & TYPE_MASK) != TYPE_VOID) {
10816 def = new_triple(state, OP_FCALL, type, -1, pvals);
10817 MISC(def, 0) = func;
10819 param = func->type->right;
10820 for(index = 0; index < pvals; index++) {
10821 struct triple *val;
10822 struct type *arg_type;
10823 val = read_expr(state, assignment_expr(state));
10825 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10826 arg_type = param->left;
10828 write_compatible(state, arg_type, val->type);
10829 RHS(def, index) = val;
10830 if (index != (pvals - 1)) {
10831 eat(state, TOK_COMMA);
10832 param = param->right;
10835 eat(state, TOK_RPAREN);
10840 static struct triple *character_constant(struct compile_state *state)
10842 struct triple *def;
10844 const signed char *str, *end;
10847 eat(state, TOK_LIT_CHAR);
10848 tk = &state->token[0];
10849 str = tk->val.str + 1;
10850 str_len = tk->str_len - 2;
10851 if (str_len <= 0) {
10852 error(state, 0, "empty character constant");
10854 end = str + str_len;
10855 c = char_value(state, &str, end);
10857 error(state, 0, "multibyte character constant not supported");
10859 def = int_const(state, &char_type, (ulong_t)((long_t)c));
10863 static struct triple *string_constant(struct compile_state *state)
10865 struct triple *def;
10868 const signed char *str, *end;
10869 signed char *buf, *ptr;
10873 type = new_type(TYPE_ARRAY, &char_type, 0);
10874 type->elements = 0;
10875 /* The while loop handles string concatenation */
10877 eat(state, TOK_LIT_STRING);
10878 tk = &state->token[0];
10879 str = tk->val.str + 1;
10880 str_len = tk->str_len - 2;
10882 error(state, 0, "negative string constant length");
10884 end = str + str_len;
10886 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10887 memcpy(buf, ptr, type->elements);
10888 ptr = buf + type->elements;
10890 *ptr++ = char_value(state, &str, end);
10891 } while(str < end);
10892 type->elements = ptr - buf;
10893 } while(peek(state) == TOK_LIT_STRING);
10895 type->elements += 1;
10896 def = triple(state, OP_BLOBCONST, type, 0, 0);
10903 static struct triple *integer_constant(struct compile_state *state)
10905 struct triple *def;
10912 eat(state, TOK_LIT_INT);
10913 tk = &state->token[0];
10915 decimal = (tk->val.str[0] != '0');
10916 val = strtoul(tk->val.str, &end, 0);
10917 if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10918 error(state, 0, "Integer constant to large");
10921 if ((*end == 'u') || (*end == 'U')) {
10925 if ((*end == 'l') || (*end == 'L')) {
10929 if ((*end == 'u') || (*end == 'U')) {
10934 error(state, 0, "Junk at end of integer constant");
10937 type = &ulong_type;
10941 if (!decimal && (val > LONG_T_MAX)) {
10942 type = &ulong_type;
10947 if (val > UINT_T_MAX) {
10948 type = &ulong_type;
10953 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10956 else if (!decimal && (val > LONG_T_MAX)) {
10957 type = &ulong_type;
10959 else if (val > INT_T_MAX) {
10963 def = int_const(state, type, val);
10967 static struct triple *primary_expr(struct compile_state *state)
10969 struct triple *def;
10975 struct hash_entry *ident;
10976 /* Here ident is either:
10980 eat(state, TOK_IDENT);
10981 ident = state->token[0].ident;
10982 if (!ident->sym_ident) {
10983 error(state, 0, "%s undeclared", ident->name);
10985 def = ident->sym_ident->def;
10988 case TOK_ENUM_CONST:
10990 struct hash_entry *ident;
10991 /* Here ident is an enumeration constant */
10992 eat(state, TOK_ENUM_CONST);
10993 ident = state->token[0].ident;
10994 if (!ident->sym_ident) {
10995 error(state, 0, "%s undeclared", ident->name);
10997 def = ident->sym_ident->def;
11001 eat(state, TOK_LPAREN);
11003 eat(state, TOK_RPAREN);
11006 def = integer_constant(state);
11008 case TOK_LIT_FLOAT:
11009 eat(state, TOK_LIT_FLOAT);
11010 error(state, 0, "Floating point constants not supported");
11015 def = character_constant(state);
11017 case TOK_LIT_STRING:
11018 def = string_constant(state);
11022 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
11027 static struct triple *postfix_expr(struct compile_state *state)
11029 struct triple *def;
11031 def = primary_expr(state);
11033 struct triple *left;
11037 switch((tok = peek(state))) {
11039 eat(state, TOK_LBRACKET);
11040 def = mk_subscript_expr(state, left, expr(state));
11041 eat(state, TOK_RBRACKET);
11044 def = call_expr(state, def);
11048 struct hash_entry *field;
11049 eat(state, TOK_DOT);
11050 eat(state, TOK_IDENT);
11051 field = state->token[0].ident;
11052 def = deref_field(state, def, field);
11057 struct hash_entry *field;
11058 eat(state, TOK_ARROW);
11059 eat(state, TOK_IDENT);
11060 field = state->token[0].ident;
11061 def = mk_deref_expr(state, read_expr(state, def));
11062 def = deref_field(state, def, field);
11066 eat(state, TOK_PLUSPLUS);
11067 def = mk_post_inc_expr(state, left);
11069 case TOK_MINUSMINUS:
11070 eat(state, TOK_MINUSMINUS);
11071 def = mk_post_dec_expr(state, left);
11081 static struct triple *cast_expr(struct compile_state *state);
11083 static struct triple *unary_expr(struct compile_state *state)
11085 struct triple *def, *right;
11087 switch((tok = peek(state))) {
11089 eat(state, TOK_PLUSPLUS);
11090 def = mk_pre_inc_expr(state, unary_expr(state));
11092 case TOK_MINUSMINUS:
11093 eat(state, TOK_MINUSMINUS);
11094 def = mk_pre_dec_expr(state, unary_expr(state));
11097 eat(state, TOK_AND);
11098 def = mk_addr_expr(state, cast_expr(state), 0);
11101 eat(state, TOK_STAR);
11102 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
11105 eat(state, TOK_PLUS);
11106 right = read_expr(state, cast_expr(state));
11107 arithmetic(state, right);
11108 def = integral_promotion(state, right);
11111 eat(state, TOK_MINUS);
11112 right = read_expr(state, cast_expr(state));
11113 arithmetic(state, right);
11114 def = integral_promotion(state, right);
11115 def = triple(state, OP_NEG, def->type, def, 0);
11118 eat(state, TOK_TILDE);
11119 right = read_expr(state, cast_expr(state));
11120 integral(state, right);
11121 def = integral_promotion(state, right);
11122 def = triple(state, OP_INVERT, def->type, def, 0);
11125 eat(state, TOK_BANG);
11126 right = read_expr(state, cast_expr(state));
11127 bool(state, right);
11128 def = lfalse_expr(state, right);
11134 eat(state, TOK_SIZEOF);
11135 tok1 = peek(state);
11136 tok2 = peek2(state);
11137 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11138 eat(state, TOK_LPAREN);
11139 type = type_name(state);
11140 eat(state, TOK_RPAREN);
11143 struct triple *expr;
11144 expr = unary_expr(state);
11146 release_expr(state, expr);
11148 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11155 eat(state, TOK_ALIGNOF);
11156 tok1 = peek(state);
11157 tok2 = peek2(state);
11158 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11159 eat(state, TOK_LPAREN);
11160 type = type_name(state);
11161 eat(state, TOK_RPAREN);
11164 struct triple *expr;
11165 expr = unary_expr(state);
11167 release_expr(state, expr);
11169 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11173 def = postfix_expr(state);
11179 static struct triple *cast_expr(struct compile_state *state)
11181 struct triple *def;
11183 tok1 = peek(state);
11184 tok2 = peek2(state);
11185 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11187 eat(state, TOK_LPAREN);
11188 type = type_name(state);
11189 eat(state, TOK_RPAREN);
11190 def = mk_cast_expr(state, type, cast_expr(state));
11193 def = unary_expr(state);
11198 static struct triple *mult_expr(struct compile_state *state)
11200 struct triple *def;
11202 def = cast_expr(state);
11204 struct triple *left, *right;
11205 struct type *result_type;
11208 switch(tok = (peek(state))) {
11212 left = read_expr(state, def);
11213 arithmetic(state, left);
11217 right = read_expr(state, cast_expr(state));
11218 arithmetic(state, right);
11220 result_type = arithmetic_result(state, left, right);
11221 sign = is_signed(result_type);
11224 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11225 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
11226 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
11228 def = triple(state, op, result_type, left, right);
11238 static struct triple *add_expr(struct compile_state *state)
11240 struct triple *def;
11242 def = mult_expr(state);
11245 switch( peek(state)) {
11247 eat(state, TOK_PLUS);
11248 def = mk_add_expr(state, def, mult_expr(state));
11251 eat(state, TOK_MINUS);
11252 def = mk_sub_expr(state, def, mult_expr(state));
11262 static struct triple *shift_expr(struct compile_state *state)
11264 struct triple *def;
11266 def = add_expr(state);
11268 struct triple *left, *right;
11271 switch((tok = peek(state))) {
11274 left = read_expr(state, def);
11275 integral(state, left);
11276 left = integral_promotion(state, left);
11280 right = read_expr(state, add_expr(state));
11281 integral(state, right);
11282 right = integral_promotion(state, right);
11284 op = (tok == TOK_SL)? OP_SL :
11285 is_signed(left->type)? OP_SSR: OP_USR;
11287 def = triple(state, op, left->type, left, right);
11297 static struct triple *relational_expr(struct compile_state *state)
11299 #warning "Extend relational exprs to work on more than arithmetic types"
11300 struct triple *def;
11302 def = shift_expr(state);
11304 struct triple *left, *right;
11305 struct type *arg_type;
11308 switch((tok = peek(state))) {
11313 left = read_expr(state, def);
11314 arithmetic(state, left);
11318 right = read_expr(state, shift_expr(state));
11319 arithmetic(state, right);
11321 arg_type = arithmetic_result(state, left, right);
11322 sign = is_signed(arg_type);
11325 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
11326 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
11327 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11328 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11330 def = triple(state, op, &int_type, left, right);
11340 static struct triple *equality_expr(struct compile_state *state)
11342 #warning "Extend equality exprs to work on more than arithmetic types"
11343 struct triple *def;
11345 def = relational_expr(state);
11347 struct triple *left, *right;
11350 switch((tok = peek(state))) {
11353 left = read_expr(state, def);
11354 arithmetic(state, left);
11356 right = read_expr(state, relational_expr(state));
11357 arithmetic(state, right);
11358 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11359 def = triple(state, op, &int_type, left, right);
11369 static struct triple *and_expr(struct compile_state *state)
11371 struct triple *def;
11372 def = equality_expr(state);
11373 while(peek(state) == TOK_AND) {
11374 struct triple *left, *right;
11375 struct type *result_type;
11376 left = read_expr(state, def);
11377 integral(state, left);
11378 eat(state, TOK_AND);
11379 right = read_expr(state, equality_expr(state));
11380 integral(state, right);
11381 result_type = arithmetic_result(state, left, right);
11382 def = triple(state, OP_AND, result_type, left, right);
11387 static struct triple *xor_expr(struct compile_state *state)
11389 struct triple *def;
11390 def = and_expr(state);
11391 while(peek(state) == TOK_XOR) {
11392 struct triple *left, *right;
11393 struct type *result_type;
11394 left = read_expr(state, def);
11395 integral(state, left);
11396 eat(state, TOK_XOR);
11397 right = read_expr(state, and_expr(state));
11398 integral(state, right);
11399 result_type = arithmetic_result(state, left, right);
11400 def = triple(state, OP_XOR, result_type, left, right);
11405 static struct triple *or_expr(struct compile_state *state)
11407 struct triple *def;
11408 def = xor_expr(state);
11409 while(peek(state) == TOK_OR) {
11410 struct triple *left, *right;
11411 struct type *result_type;
11412 left = read_expr(state, def);
11413 integral(state, left);
11414 eat(state, TOK_OR);
11415 right = read_expr(state, xor_expr(state));
11416 integral(state, right);
11417 result_type = arithmetic_result(state, left, right);
11418 def = triple(state, OP_OR, result_type, left, right);
11423 static struct triple *land_expr(struct compile_state *state)
11425 struct triple *def;
11426 def = or_expr(state);
11427 while(peek(state) == TOK_LOGAND) {
11428 struct triple *left, *right;
11429 left = read_expr(state, def);
11431 eat(state, TOK_LOGAND);
11432 right = read_expr(state, or_expr(state));
11433 bool(state, right);
11435 def = mkland_expr(state,
11436 ltrue_expr(state, left),
11437 ltrue_expr(state, right));
11442 static struct triple *lor_expr(struct compile_state *state)
11444 struct triple *def;
11445 def = land_expr(state);
11446 while(peek(state) == TOK_LOGOR) {
11447 struct triple *left, *right;
11448 left = read_expr(state, def);
11450 eat(state, TOK_LOGOR);
11451 right = read_expr(state, land_expr(state));
11452 bool(state, right);
11454 def = mklor_expr(state,
11455 ltrue_expr(state, left),
11456 ltrue_expr(state, right));
11461 static struct triple *conditional_expr(struct compile_state *state)
11463 struct triple *def;
11464 def = lor_expr(state);
11465 if (peek(state) == TOK_QUEST) {
11466 struct triple *test, *left, *right;
11468 test = ltrue_expr(state, read_expr(state, def));
11469 eat(state, TOK_QUEST);
11470 left = read_expr(state, expr(state));
11471 eat(state, TOK_COLON);
11472 right = read_expr(state, conditional_expr(state));
11474 def = mkcond_expr(state, test, left, right);
11479 static struct triple *eval_const_expr(
11480 struct compile_state *state, struct triple *expr)
11482 struct triple *def;
11483 if (is_const(expr)) {
11487 /* If we don't start out as a constant simplify into one */
11488 struct triple *head, *ptr;
11489 head = label(state); /* dummy initial triple */
11490 flatten(state, head, expr);
11491 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11492 simplify(state, ptr);
11494 /* Remove the constant value the tail of the list */
11496 def->prev->next = def->next;
11497 def->next->prev = def->prev;
11498 def->next = def->prev = def;
11499 if (!is_const(def)) {
11500 error(state, 0, "Not a constant expression");
11502 /* Free the intermediate expressions */
11503 while(head->next != head) {
11504 release_triple(state, head->next);
11506 free_triple(state, head);
11511 static struct triple *constant_expr(struct compile_state *state)
11513 return eval_const_expr(state, conditional_expr(state));
11516 static struct triple *assignment_expr(struct compile_state *state)
11518 struct triple *def, *left, *right;
11520 /* The C grammer in K&R shows assignment expressions
11521 * only taking unary expressions as input on their
11522 * left hand side. But specifies the precedence of
11523 * assignemnt as the lowest operator except for comma.
11525 * Allowing conditional expressions on the left hand side
11526 * of an assignement results in a grammar that accepts
11527 * a larger set of statements than standard C. As long
11528 * as the subset of the grammar that is standard C behaves
11529 * correctly this should cause no problems.
11531 * For the extra token strings accepted by the grammar
11532 * none of them should produce a valid lvalue, so they
11533 * should not produce functioning programs.
11535 * GCC has this bug as well, so surprises should be minimal.
11537 def = conditional_expr(state);
11539 switch((tok = peek(state))) {
11541 lvalue(state, left);
11542 eat(state, TOK_EQ);
11543 def = write_expr(state, left,
11544 read_expr(state, assignment_expr(state)));
11549 lvalue(state, left);
11550 arithmetic(state, left);
11552 right = read_expr(state, assignment_expr(state));
11553 arithmetic(state, right);
11555 sign = is_signed(left->type);
11558 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11559 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
11560 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
11562 def = write_expr(state, left,
11563 triple(state, op, left->type,
11564 read_expr(state, left), right));
11567 lvalue(state, left);
11568 eat(state, TOK_PLUSEQ);
11569 def = write_expr(state, left,
11570 mk_add_expr(state, left, assignment_expr(state)));
11573 lvalue(state, left);
11574 eat(state, TOK_MINUSEQ);
11575 def = write_expr(state, left,
11576 mk_sub_expr(state, left, assignment_expr(state)));
11583 lvalue(state, left);
11584 integral(state, left);
11586 right = read_expr(state, assignment_expr(state));
11587 integral(state, right);
11588 right = integral_promotion(state, right);
11589 sign = is_signed(left->type);
11592 case TOK_SLEQ: op = OP_SL; break;
11593 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
11594 case TOK_ANDEQ: op = OP_AND; break;
11595 case TOK_XOREQ: op = OP_XOR; break;
11596 case TOK_OREQ: op = OP_OR; break;
11598 def = write_expr(state, left,
11599 triple(state, op, left->type,
11600 read_expr(state, left), right));
11606 static struct triple *expr(struct compile_state *state)
11608 struct triple *def;
11609 def = assignment_expr(state);
11610 while(peek(state) == TOK_COMMA) {
11611 eat(state, TOK_COMMA);
11612 def = mkprog(state, def, assignment_expr(state), 0);
11617 static void expr_statement(struct compile_state *state, struct triple *first)
11619 if (peek(state) != TOK_SEMI) {
11620 /* lvalue conversions always apply except when certian operators
11621 * are applied. I apply the lvalue conversions here
11622 * as I know no more operators will be applied.
11624 flatten(state, first, lvalue_conversion(state, expr(state)));
11626 eat(state, TOK_SEMI);
11629 static void if_statement(struct compile_state *state, struct triple *first)
11631 struct triple *test, *jmp1, *jmp2, *middle, *end;
11633 jmp1 = jmp2 = middle = 0;
11634 eat(state, TOK_IF);
11635 eat(state, TOK_LPAREN);
11636 test = expr(state);
11638 /* Cleanup and invert the test */
11639 test = lfalse_expr(state, read_expr(state, test));
11640 eat(state, TOK_RPAREN);
11641 /* Generate the needed pieces */
11642 middle = label(state);
11643 jmp1 = branch(state, middle, test);
11644 /* Thread the pieces together */
11645 flatten(state, first, test);
11646 flatten(state, first, jmp1);
11647 flatten(state, first, label(state));
11648 statement(state, first);
11649 if (peek(state) == TOK_ELSE) {
11650 eat(state, TOK_ELSE);
11651 /* Generate the rest of the pieces */
11652 end = label(state);
11653 jmp2 = branch(state, end, 0);
11654 /* Thread them together */
11655 flatten(state, first, jmp2);
11656 flatten(state, first, middle);
11657 statement(state, first);
11658 flatten(state, first, end);
11661 flatten(state, first, middle);
11665 static void for_statement(struct compile_state *state, struct triple *first)
11667 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11668 struct triple *label1, *label2, *label3;
11669 struct hash_entry *ident;
11671 eat(state, TOK_FOR);
11672 eat(state, TOK_LPAREN);
11673 head = test = tail = jmp1 = jmp2 = 0;
11674 if (peek(state) != TOK_SEMI) {
11675 head = expr(state);
11677 eat(state, TOK_SEMI);
11678 if (peek(state) != TOK_SEMI) {
11679 test = expr(state);
11681 test = ltrue_expr(state, read_expr(state, test));
11683 eat(state, TOK_SEMI);
11684 if (peek(state) != TOK_RPAREN) {
11685 tail = expr(state);
11687 eat(state, TOK_RPAREN);
11688 /* Generate the needed pieces */
11689 label1 = label(state);
11690 label2 = label(state);
11691 label3 = label(state);
11693 jmp1 = branch(state, label3, 0);
11694 jmp2 = branch(state, label1, test);
11697 jmp2 = branch(state, label1, 0);
11699 end = label(state);
11700 /* Remember where break and continue go */
11701 start_scope(state);
11702 ident = state->i_break;
11703 symbol(state, ident, &ident->sym_ident, end, end->type);
11704 ident = state->i_continue;
11705 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11706 /* Now include the body */
11707 flatten(state, first, head);
11708 flatten(state, first, jmp1);
11709 flatten(state, first, label1);
11710 statement(state, first);
11711 flatten(state, first, label2);
11712 flatten(state, first, tail);
11713 flatten(state, first, label3);
11714 flatten(state, first, test);
11715 flatten(state, first, jmp2);
11716 flatten(state, first, end);
11717 /* Cleanup the break/continue scope */
11721 static void while_statement(struct compile_state *state, struct triple *first)
11723 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11724 struct hash_entry *ident;
11725 eat(state, TOK_WHILE);
11726 eat(state, TOK_LPAREN);
11727 test = expr(state);
11729 test = ltrue_expr(state, read_expr(state, test));
11730 eat(state, TOK_RPAREN);
11731 /* Generate the needed pieces */
11732 label1 = label(state);
11733 label2 = label(state);
11734 jmp1 = branch(state, label2, 0);
11735 jmp2 = branch(state, label1, test);
11736 end = label(state);
11737 /* Remember where break and continue go */
11738 start_scope(state);
11739 ident = state->i_break;
11740 symbol(state, ident, &ident->sym_ident, end, end->type);
11741 ident = state->i_continue;
11742 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11743 /* Thread them together */
11744 flatten(state, first, jmp1);
11745 flatten(state, first, label1);
11746 statement(state, first);
11747 flatten(state, first, label2);
11748 flatten(state, first, test);
11749 flatten(state, first, jmp2);
11750 flatten(state, first, end);
11751 /* Cleanup the break/continue scope */
11755 static void do_statement(struct compile_state *state, struct triple *first)
11757 struct triple *label1, *label2, *test, *end;
11758 struct hash_entry *ident;
11759 eat(state, TOK_DO);
11760 /* Generate the needed pieces */
11761 label1 = label(state);
11762 label2 = label(state);
11763 end = label(state);
11764 /* Remember where break and continue go */
11765 start_scope(state);
11766 ident = state->i_break;
11767 symbol(state, ident, &ident->sym_ident, end, end->type);
11768 ident = state->i_continue;
11769 symbol(state, ident, &ident->sym_ident, label2, label2->type);
11770 /* Now include the body */
11771 flatten(state, first, label1);
11772 statement(state, first);
11773 /* Cleanup the break/continue scope */
11775 /* Eat the rest of the loop */
11776 eat(state, TOK_WHILE);
11777 eat(state, TOK_LPAREN);
11778 test = read_expr(state, expr(state));
11780 eat(state, TOK_RPAREN);
11781 eat(state, TOK_SEMI);
11782 /* Thread the pieces together */
11783 test = ltrue_expr(state, test);
11784 flatten(state, first, label2);
11785 flatten(state, first, test);
11786 flatten(state, first, branch(state, label1, test));
11787 flatten(state, first, end);
11791 static void return_statement(struct compile_state *state, struct triple *first)
11793 struct triple *jmp, *mv, *dest, *var, *val;
11795 eat(state, TOK_RETURN);
11797 #warning "FIXME implement a more general excess branch elimination"
11799 /* If we have a return value do some more work */
11800 if (peek(state) != TOK_SEMI) {
11801 val = read_expr(state, expr(state));
11803 eat(state, TOK_SEMI);
11805 /* See if this last statement in a function */
11806 last = ((peek(state) == TOK_RBRACE) &&
11807 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11809 /* Find the return variable */
11810 var = fresult(state, state->main_function);
11812 /* Find the return destination */
11813 dest = state->i_return->sym_ident->def;
11815 /* If needed generate a jump instruction */
11817 jmp = branch(state, dest, 0);
11819 /* If needed generate an assignment instruction */
11821 mv = write_expr(state, deref_index(state, var, 1), val);
11823 /* Now put the code together */
11825 flatten(state, first, mv);
11826 flatten(state, first, jmp);
11829 flatten(state, first, jmp);
11833 static void break_statement(struct compile_state *state, struct triple *first)
11835 struct triple *dest;
11836 eat(state, TOK_BREAK);
11837 eat(state, TOK_SEMI);
11838 if (!state->i_break->sym_ident) {
11839 error(state, 0, "break statement not within loop or switch");
11841 dest = state->i_break->sym_ident->def;
11842 flatten(state, first, branch(state, dest, 0));
11845 static void continue_statement(struct compile_state *state, struct triple *first)
11847 struct triple *dest;
11848 eat(state, TOK_CONTINUE);
11849 eat(state, TOK_SEMI);
11850 if (!state->i_continue->sym_ident) {
11851 error(state, 0, "continue statement outside of a loop");
11853 dest = state->i_continue->sym_ident->def;
11854 flatten(state, first, branch(state, dest, 0));
11857 static void goto_statement(struct compile_state *state, struct triple *first)
11859 struct hash_entry *ident;
11860 eat(state, TOK_GOTO);
11861 eat(state, TOK_IDENT);
11862 ident = state->token[0].ident;
11863 if (!ident->sym_label) {
11864 /* If this is a forward branch allocate the label now,
11865 * it will be flattend in the appropriate location later.
11867 struct triple *ins;
11868 ins = label(state);
11869 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11871 eat(state, TOK_SEMI);
11873 flatten(state, first, branch(state, ident->sym_label->def, 0));
11876 static void labeled_statement(struct compile_state *state, struct triple *first)
11878 struct triple *ins;
11879 struct hash_entry *ident;
11880 eat(state, TOK_IDENT);
11882 ident = state->token[0].ident;
11883 if (ident->sym_label && ident->sym_label->def) {
11884 ins = ident->sym_label->def;
11885 put_occurance(ins->occurance);
11886 ins->occurance = new_occurance(state);
11889 ins = label(state);
11890 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11892 if (ins->id & TRIPLE_FLAG_FLATTENED) {
11893 error(state, 0, "label %s already defined", ident->name);
11895 flatten(state, first, ins);
11897 eat(state, TOK_COLON);
11898 statement(state, first);
11901 static void switch_statement(struct compile_state *state, struct triple *first)
11903 struct triple *value, *top, *end, *dbranch;
11904 struct hash_entry *ident;
11906 /* See if we have a valid switch statement */
11907 eat(state, TOK_SWITCH);
11908 eat(state, TOK_LPAREN);
11909 value = expr(state);
11910 integral(state, value);
11911 value = read_expr(state, value);
11912 eat(state, TOK_RPAREN);
11913 /* Generate the needed pieces */
11914 top = label(state);
11915 end = label(state);
11916 dbranch = branch(state, end, 0);
11917 /* Remember where case branches and break goes */
11918 start_scope(state);
11919 ident = state->i_switch;
11920 symbol(state, ident, &ident->sym_ident, value, value->type);
11921 ident = state->i_case;
11922 symbol(state, ident, &ident->sym_ident, top, top->type);
11923 ident = state->i_break;
11924 symbol(state, ident, &ident->sym_ident, end, end->type);
11925 ident = state->i_default;
11926 symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11927 /* Thread them together */
11928 flatten(state, first, value);
11929 flatten(state, first, top);
11930 flatten(state, first, dbranch);
11931 statement(state, first);
11932 flatten(state, first, end);
11933 /* Cleanup the switch scope */
11937 static void case_statement(struct compile_state *state, struct triple *first)
11939 struct triple *cvalue, *dest, *test, *jmp;
11940 struct triple *ptr, *value, *top, *dbranch;
11942 /* See if w have a valid case statement */
11943 eat(state, TOK_CASE);
11944 cvalue = constant_expr(state);
11945 integral(state, cvalue);
11946 if (cvalue->op != OP_INTCONST) {
11947 error(state, 0, "integer constant expected");
11949 eat(state, TOK_COLON);
11950 if (!state->i_case->sym_ident) {
11951 error(state, 0, "case statement not within a switch");
11954 /* Lookup the interesting pieces */
11955 top = state->i_case->sym_ident->def;
11956 value = state->i_switch->sym_ident->def;
11957 dbranch = state->i_default->sym_ident->def;
11959 /* See if this case label has already been used */
11960 for(ptr = top; ptr != dbranch; ptr = ptr->next) {
11961 if (ptr->op != OP_EQ) {
11964 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
11965 error(state, 0, "duplicate case %d statement",
11969 /* Generate the needed pieces */
11970 dest = label(state);
11971 test = triple(state, OP_EQ, &int_type, value, cvalue);
11972 jmp = branch(state, dest, test);
11973 /* Thread the pieces together */
11974 flatten(state, dbranch, test);
11975 flatten(state, dbranch, jmp);
11976 flatten(state, dbranch, label(state));
11977 flatten(state, first, dest);
11978 statement(state, first);
11981 static void default_statement(struct compile_state *state, struct triple *first)
11983 struct triple *dest;
11984 struct triple *dbranch, *end;
11986 /* See if we have a valid default statement */
11987 eat(state, TOK_DEFAULT);
11988 eat(state, TOK_COLON);
11990 if (!state->i_case->sym_ident) {
11991 error(state, 0, "default statement not within a switch");
11994 /* Lookup the interesting pieces */
11995 dbranch = state->i_default->sym_ident->def;
11996 end = state->i_break->sym_ident->def;
11998 /* See if a default statement has already happened */
11999 if (TARG(dbranch, 0) != end) {
12000 error(state, 0, "duplicate default statement");
12003 /* Generate the needed pieces */
12004 dest = label(state);
12006 /* Blame the branch on the default statement */
12007 put_occurance(dbranch->occurance);
12008 dbranch->occurance = new_occurance(state);
12010 /* Thread the pieces together */
12011 TARG(dbranch, 0) = dest;
12012 use_triple(dest, dbranch);
12013 flatten(state, first, dest);
12014 statement(state, first);
12017 static void asm_statement(struct compile_state *state, struct triple *first)
12019 struct asm_info *info;
12021 struct triple *constraint;
12022 struct triple *expr;
12023 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12024 struct triple *def, *asm_str;
12025 int out, in, clobbers, more, colons, i;
12029 eat(state, TOK_ASM);
12030 /* For now ignore the qualifiers */
12031 switch(peek(state)) {
12033 eat(state, TOK_CONST);
12036 eat(state, TOK_VOLATILE);
12037 flags |= TRIPLE_FLAG_VOLATILE;
12040 eat(state, TOK_LPAREN);
12041 asm_str = string_constant(state);
12044 out = in = clobbers = 0;
12046 if ((colons == 0) && (peek(state) == TOK_COLON)) {
12047 eat(state, TOK_COLON);
12049 more = (peek(state) == TOK_LIT_STRING);
12051 struct triple *var;
12052 struct triple *constraint;
12055 if (out > MAX_LHS) {
12056 error(state, 0, "Maximum output count exceeded.");
12058 constraint = string_constant(state);
12059 str = constraint->u.blob;
12060 if (str[0] != '=') {
12061 error(state, 0, "Output constraint does not start with =");
12063 constraint->u.blob = str + 1;
12064 eat(state, TOK_LPAREN);
12065 var = conditional_expr(state);
12066 eat(state, TOK_RPAREN);
12068 lvalue(state, var);
12069 out_param[out].constraint = constraint;
12070 out_param[out].expr = var;
12071 if (peek(state) == TOK_COMMA) {
12072 eat(state, TOK_COMMA);
12079 if ((colons == 1) && (peek(state) == TOK_COLON)) {
12080 eat(state, TOK_COLON);
12082 more = (peek(state) == TOK_LIT_STRING);
12084 struct triple *val;
12085 struct triple *constraint;
12088 if (in > MAX_RHS) {
12089 error(state, 0, "Maximum input count exceeded.");
12091 constraint = string_constant(state);
12092 str = constraint->u.blob;
12093 if (digitp(str[0] && str[1] == '\0')) {
12095 val = digval(str[0]);
12096 if ((val < 0) || (val >= out)) {
12097 error(state, 0, "Invalid input constraint %d", val);
12100 eat(state, TOK_LPAREN);
12101 val = conditional_expr(state);
12102 eat(state, TOK_RPAREN);
12104 in_param[in].constraint = constraint;
12105 in_param[in].expr = val;
12106 if (peek(state) == TOK_COMMA) {
12107 eat(state, TOK_COMMA);
12115 if ((colons == 2) && (peek(state) == TOK_COLON)) {
12116 eat(state, TOK_COLON);
12118 more = (peek(state) == TOK_LIT_STRING);
12120 struct triple *clobber;
12122 if ((clobbers + out) > MAX_LHS) {
12123 error(state, 0, "Maximum clobber limit exceeded.");
12125 clobber = string_constant(state);
12127 clob_param[clobbers].constraint = clobber;
12128 if (peek(state) == TOK_COMMA) {
12129 eat(state, TOK_COMMA);
12135 eat(state, TOK_RPAREN);
12136 eat(state, TOK_SEMI);
12139 info = xcmalloc(sizeof(*info), "asm_info");
12140 info->str = asm_str->u.blob;
12141 free_triple(state, asm_str);
12143 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12144 def->u.ainfo = info;
12147 /* Find the register constraints */
12148 for(i = 0; i < out; i++) {
12149 struct triple *constraint;
12150 constraint = out_param[i].constraint;
12151 info->tmpl.lhs[i] = arch_reg_constraint(state,
12152 out_param[i].expr->type, constraint->u.blob);
12153 free_triple(state, constraint);
12155 for(; i - out < clobbers; i++) {
12156 struct triple *constraint;
12157 constraint = clob_param[i - out].constraint;
12158 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12159 free_triple(state, constraint);
12161 for(i = 0; i < in; i++) {
12162 struct triple *constraint;
12164 constraint = in_param[i].constraint;
12165 str = constraint->u.blob;
12166 if (digitp(str[0]) && str[1] == '\0') {
12167 struct reg_info cinfo;
12169 val = digval(str[0]);
12170 cinfo.reg = info->tmpl.lhs[val].reg;
12171 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12172 cinfo.regcm &= info->tmpl.lhs[val].regcm;
12173 if (cinfo.reg == REG_UNSET) {
12174 cinfo.reg = REG_VIRT0 + val;
12176 if (cinfo.regcm == 0) {
12177 error(state, 0, "No registers for %d", val);
12179 info->tmpl.lhs[val] = cinfo;
12180 info->tmpl.rhs[i] = cinfo;
12183 info->tmpl.rhs[i] = arch_reg_constraint(state,
12184 in_param[i].expr->type, str);
12186 free_triple(state, constraint);
12189 /* Now build the helper expressions */
12190 for(i = 0; i < in; i++) {
12191 RHS(def, i) = read_expr(state, in_param[i].expr);
12193 flatten(state, first, def);
12194 for(i = 0; i < (out + clobbers); i++) {
12196 struct triple *piece;
12198 type = out_param[i].expr->type;
12200 size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12201 if (size >= SIZEOF_LONG) {
12202 type = &ulong_type;
12204 else if (size >= SIZEOF_INT) {
12207 else if (size >= SIZEOF_SHORT) {
12208 type = &ushort_type;
12211 type = &uchar_type;
12214 piece = triple(state, OP_PIECE, type, def, 0);
12216 LHS(def, i) = piece;
12217 flatten(state, first, piece);
12219 /* And write the helpers to their destinations */
12220 for(i = 0; i < out; i++) {
12221 struct triple *piece;
12222 piece = LHS(def, i);
12223 flatten(state, first,
12224 write_expr(state, out_param[i].expr, piece));
12229 static int isdecl(int tok)
12252 case TOK_TYPE_NAME: /* typedef name */
12259 static void compound_statement(struct compile_state *state, struct triple *first)
12261 eat(state, TOK_LBRACE);
12262 start_scope(state);
12264 /* statement-list opt */
12265 while (peek(state) != TOK_RBRACE) {
12266 statement(state, first);
12269 eat(state, TOK_RBRACE);
12272 static void statement(struct compile_state *state, struct triple *first)
12276 if (tok == TOK_LBRACE) {
12277 compound_statement(state, first);
12279 else if (tok == TOK_IF) {
12280 if_statement(state, first);
12282 else if (tok == TOK_FOR) {
12283 for_statement(state, first);
12285 else if (tok == TOK_WHILE) {
12286 while_statement(state, first);
12288 else if (tok == TOK_DO) {
12289 do_statement(state, first);
12291 else if (tok == TOK_RETURN) {
12292 return_statement(state, first);
12294 else if (tok == TOK_BREAK) {
12295 break_statement(state, first);
12297 else if (tok == TOK_CONTINUE) {
12298 continue_statement(state, first);
12300 else if (tok == TOK_GOTO) {
12301 goto_statement(state, first);
12303 else if (tok == TOK_SWITCH) {
12304 switch_statement(state, first);
12306 else if (tok == TOK_ASM) {
12307 asm_statement(state, first);
12309 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12310 labeled_statement(state, first);
12312 else if (tok == TOK_CASE) {
12313 case_statement(state, first);
12315 else if (tok == TOK_DEFAULT) {
12316 default_statement(state, first);
12318 else if (isdecl(tok)) {
12319 /* This handles C99 intermixing of statements and decls */
12320 decl(state, first);
12323 expr_statement(state, first);
12327 static struct type *param_decl(struct compile_state *state)
12330 struct hash_entry *ident;
12331 /* Cheat so the declarator will know we are not global */
12332 start_scope(state);
12334 type = decl_specifiers(state);
12335 type = declarator(state, type, &ident, 0);
12336 type->field_ident = ident;
12341 static struct type *param_type_list(struct compile_state *state, struct type *type)
12343 struct type *ftype, **next;
12344 ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12345 next = &ftype->right;
12346 ftype->elements = 1;
12347 while(peek(state) == TOK_COMMA) {
12348 eat(state, TOK_COMMA);
12349 if (peek(state) == TOK_DOTS) {
12350 eat(state, TOK_DOTS);
12351 error(state, 0, "variadic functions not supported");
12354 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12355 next = &((*next)->right);
12362 static struct type *type_name(struct compile_state *state)
12365 type = specifier_qualifier_list(state);
12366 /* abstract-declarator (may consume no tokens) */
12367 type = declarator(state, type, 0, 0);
12371 static struct type *direct_declarator(
12372 struct compile_state *state, struct type *type,
12373 struct hash_entry **ident, int need_ident)
12375 struct type *outer;
12378 arrays_complete(state, type);
12379 switch(peek(state)) {
12381 eat(state, TOK_IDENT);
12383 error(state, 0, "Unexpected identifier found");
12385 /* The name of what we are declaring */
12386 *ident = state->token[0].ident;
12389 eat(state, TOK_LPAREN);
12390 outer = declarator(state, type, ident, need_ident);
12391 eat(state, TOK_RPAREN);
12395 error(state, 0, "Identifier expected");
12401 arrays_complete(state, type);
12402 switch(peek(state)) {
12404 eat(state, TOK_LPAREN);
12405 type = param_type_list(state, type);
12406 eat(state, TOK_RPAREN);
12410 unsigned int qualifiers;
12411 struct triple *value;
12413 eat(state, TOK_LBRACKET);
12414 if (peek(state) != TOK_RBRACKET) {
12415 value = constant_expr(state);
12416 integral(state, value);
12418 eat(state, TOK_RBRACKET);
12420 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12421 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12423 type->elements = value->u.cval;
12424 free_triple(state, value);
12426 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12437 struct type *inner;
12438 arrays_complete(state, type);
12440 for(inner = outer; inner->left; inner = inner->left)
12442 inner->left = type;
12448 static struct type *declarator(
12449 struct compile_state *state, struct type *type,
12450 struct hash_entry **ident, int need_ident)
12452 while(peek(state) == TOK_STAR) {
12453 eat(state, TOK_STAR);
12454 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12456 type = direct_declarator(state, type, ident, need_ident);
12460 static struct type *typedef_name(
12461 struct compile_state *state, unsigned int specifiers)
12463 struct hash_entry *ident;
12465 eat(state, TOK_TYPE_NAME);
12466 ident = state->token[0].ident;
12467 type = ident->sym_ident->type;
12468 specifiers |= type->type & QUAL_MASK;
12469 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
12470 (type->type & (STOR_MASK | QUAL_MASK))) {
12471 type = clone_type(specifiers, type);
12476 static struct type *enum_specifier(
12477 struct compile_state *state, unsigned int spec)
12479 struct hash_entry *ident;
12482 struct type *enum_type;
12485 eat(state, TOK_ENUM);
12487 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12489 ident = state->token[0].ident;
12493 if (!ident || (peek(state) == TOK_LBRACE)) {
12494 struct type **next;
12495 eat(state, TOK_LBRACE);
12496 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12497 enum_type->type_ident = ident;
12498 next = &enum_type->right;
12500 struct hash_entry *eident;
12501 struct triple *value;
12502 struct type *entry;
12503 eat(state, TOK_IDENT);
12504 eident = state->token[0].ident;
12505 if (eident->sym_ident) {
12506 error(state, 0, "%s already declared",
12509 eident->tok = TOK_ENUM_CONST;
12510 if (peek(state) == TOK_EQ) {
12511 struct triple *val;
12512 eat(state, TOK_EQ);
12513 val = constant_expr(state);
12514 integral(state, val);
12515 base = val->u.cval;
12517 value = int_const(state, &int_type, base);
12518 symbol(state, eident, &eident->sym_ident, value, &int_type);
12519 entry = new_type(TYPE_LIST, 0, 0);
12520 entry->field_ident = eident;
12522 next = &entry->right;
12524 if (peek(state) == TOK_COMMA) {
12525 eat(state, TOK_COMMA);
12527 } while(peek(state) != TOK_RBRACE);
12528 eat(state, TOK_RBRACE);
12530 symbol(state, ident, &ident->sym_tag, 0, enum_type);
12533 if (ident && ident->sym_tag &&
12534 ident->sym_tag->type &&
12535 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12536 enum_type = clone_type(spec, ident->sym_tag->type);
12538 else if (ident && !enum_type) {
12539 error(state, 0, "enum %s undeclared", ident->name);
12544 static struct type *struct_declarator(
12545 struct compile_state *state, struct type *type, struct hash_entry **ident)
12547 if (peek(state) != TOK_COLON) {
12548 type = declarator(state, type, ident, 1);
12550 if (peek(state) == TOK_COLON) {
12551 struct triple *value;
12552 eat(state, TOK_COLON);
12553 value = constant_expr(state);
12554 if (value->op != OP_INTCONST) {
12555 error(state, 0, "Invalid constant expression");
12557 if (value->u.cval > size_of(state, type)) {
12558 error(state, 0, "bitfield larger than base type");
12560 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12561 error(state, 0, "bitfield base not an integer type");
12563 type = new_type(TYPE_BITFIELD, type, 0);
12564 type->elements = value->u.cval;
12569 static struct type *struct_or_union_specifier(
12570 struct compile_state *state, unsigned int spec)
12572 struct type *struct_type;
12573 struct hash_entry *ident;
12574 unsigned int type_main;
12575 unsigned int type_join;
12579 switch(peek(state)) {
12581 eat(state, TOK_STRUCT);
12582 type_main = TYPE_STRUCT;
12583 type_join = TYPE_PRODUCT;
12586 eat(state, TOK_UNION);
12587 type_main = TYPE_UNION;
12588 type_join = TYPE_OVERLAP;
12591 eat(state, TOK_STRUCT);
12592 type_main = TYPE_STRUCT;
12593 type_join = TYPE_PRODUCT;
12597 if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12599 ident = state->token[0].ident;
12601 if (!ident || (peek(state) == TOK_LBRACE)) {
12603 struct type **next;
12605 eat(state, TOK_LBRACE);
12606 next = &struct_type;
12608 struct type *base_type;
12610 base_type = specifier_qualifier_list(state);
12613 struct hash_entry *fident;
12615 type = struct_declarator(state, base_type, &fident);
12617 if (peek(state) == TOK_COMMA) {
12619 eat(state, TOK_COMMA);
12621 type = clone_type(0, type);
12622 type->field_ident = fident;
12624 *next = new_type(type_join, *next, type);
12625 next = &((*next)->right);
12630 eat(state, TOK_SEMI);
12631 } while(peek(state) != TOK_RBRACE);
12632 eat(state, TOK_RBRACE);
12633 struct_type = new_type(type_main | spec, struct_type, 0);
12634 struct_type->type_ident = ident;
12635 struct_type->elements = elements;
12637 symbol(state, ident, &ident->sym_tag, 0, struct_type);
12640 if (ident && ident->sym_tag &&
12641 ident->sym_tag->type &&
12642 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12643 struct_type = clone_type(spec, ident->sym_tag->type);
12645 else if (ident && !struct_type) {
12646 error(state, 0, "%s %s undeclared",
12647 (type_main == TYPE_STRUCT)?"struct" : "union",
12650 return struct_type;
12653 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12655 unsigned int specifiers;
12656 switch(peek(state)) {
12658 eat(state, TOK_AUTO);
12659 specifiers = STOR_AUTO;
12662 eat(state, TOK_REGISTER);
12663 specifiers = STOR_REGISTER;
12666 eat(state, TOK_STATIC);
12667 specifiers = STOR_STATIC;
12670 eat(state, TOK_EXTERN);
12671 specifiers = STOR_EXTERN;
12674 eat(state, TOK_TYPEDEF);
12675 specifiers = STOR_TYPEDEF;
12678 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12679 specifiers = STOR_LOCAL;
12682 specifiers = STOR_AUTO;
12688 static unsigned int function_specifier_opt(struct compile_state *state)
12690 /* Ignore the inline keyword */
12691 unsigned int specifiers;
12693 switch(peek(state)) {
12695 eat(state, TOK_INLINE);
12696 specifiers = STOR_INLINE;
12701 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12703 int tok = peek(state);
12707 /* The empty attribute ignore it */
12710 case TOK_ENUM_CONST:
12711 case TOK_TYPE_NAME:
12713 struct hash_entry *ident;
12714 eat(state, TOK_IDENT);
12715 ident = state->token[0].ident;
12717 if (ident == state->i_noinline) {
12718 if (attributes & ATTRIB_ALWAYS_INLINE) {
12719 error(state, 0, "both always_inline and noinline attribtes");
12721 attributes |= ATTRIB_NOINLINE;
12723 else if (ident == state->i_always_inline) {
12724 if (attributes & ATTRIB_NOINLINE) {
12725 error(state, 0, "both noinline and always_inline attribtes");
12727 attributes |= ATTRIB_ALWAYS_INLINE;
12730 error(state, 0, "Unknown attribute:%s", ident->name);
12735 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12741 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12743 type = attrib(state, type);
12744 while(peek(state) == TOK_COMMA) {
12745 eat(state, TOK_COMMA);
12746 type = attrib(state, type);
12751 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12753 if (peek(state) == TOK_ATTRIBUTE) {
12754 eat(state, TOK_ATTRIBUTE);
12755 eat(state, TOK_LPAREN);
12756 eat(state, TOK_LPAREN);
12757 type = attribute_list(state, type);
12758 eat(state, TOK_RPAREN);
12759 eat(state, TOK_RPAREN);
12764 static unsigned int type_qualifiers(struct compile_state *state)
12766 unsigned int specifiers;
12769 specifiers = QUAL_NONE;
12771 switch(peek(state)) {
12773 eat(state, TOK_CONST);
12774 specifiers |= QUAL_CONST;
12777 eat(state, TOK_VOLATILE);
12778 specifiers |= QUAL_VOLATILE;
12781 eat(state, TOK_RESTRICT);
12782 specifiers |= QUAL_RESTRICT;
12792 static struct type *type_specifier(
12793 struct compile_state *state, unsigned int spec)
12797 switch(peek(state)) {
12799 eat(state, TOK_VOID);
12800 type = new_type(TYPE_VOID | spec, 0, 0);
12803 eat(state, TOK_CHAR);
12804 type = new_type(TYPE_CHAR | spec, 0, 0);
12807 eat(state, TOK_SHORT);
12808 if (peek(state) == TOK_INT) {
12809 eat(state, TOK_INT);
12811 type = new_type(TYPE_SHORT | spec, 0, 0);
12814 eat(state, TOK_INT);
12815 type = new_type(TYPE_INT | spec, 0, 0);
12818 eat(state, TOK_LONG);
12819 switch(peek(state)) {
12821 eat(state, TOK_LONG);
12822 error(state, 0, "long long not supported");
12825 eat(state, TOK_DOUBLE);
12826 error(state, 0, "long double not supported");
12829 eat(state, TOK_INT);
12830 type = new_type(TYPE_LONG | spec, 0, 0);
12833 type = new_type(TYPE_LONG | spec, 0, 0);
12838 eat(state, TOK_FLOAT);
12839 error(state, 0, "type float not supported");
12842 eat(state, TOK_DOUBLE);
12843 error(state, 0, "type double not supported");
12846 eat(state, TOK_SIGNED);
12847 switch(peek(state)) {
12849 eat(state, TOK_LONG);
12850 switch(peek(state)) {
12852 eat(state, TOK_LONG);
12853 error(state, 0, "type long long not supported");
12856 eat(state, TOK_INT);
12857 type = new_type(TYPE_LONG | spec, 0, 0);
12860 type = new_type(TYPE_LONG | spec, 0, 0);
12865 eat(state, TOK_INT);
12866 type = new_type(TYPE_INT | spec, 0, 0);
12869 eat(state, TOK_SHORT);
12870 type = new_type(TYPE_SHORT | spec, 0, 0);
12873 eat(state, TOK_CHAR);
12874 type = new_type(TYPE_CHAR | spec, 0, 0);
12877 type = new_type(TYPE_INT | spec, 0, 0);
12882 eat(state, TOK_UNSIGNED);
12883 switch(peek(state)) {
12885 eat(state, TOK_LONG);
12886 switch(peek(state)) {
12888 eat(state, TOK_LONG);
12889 error(state, 0, "unsigned long long not supported");
12892 eat(state, TOK_INT);
12893 type = new_type(TYPE_ULONG | spec, 0, 0);
12896 type = new_type(TYPE_ULONG | spec, 0, 0);
12901 eat(state, TOK_INT);
12902 type = new_type(TYPE_UINT | spec, 0, 0);
12905 eat(state, TOK_SHORT);
12906 type = new_type(TYPE_USHORT | spec, 0, 0);
12909 eat(state, TOK_CHAR);
12910 type = new_type(TYPE_UCHAR | spec, 0, 0);
12913 type = new_type(TYPE_UINT | spec, 0, 0);
12917 /* struct or union specifier */
12920 type = struct_or_union_specifier(state, spec);
12922 /* enum-spefifier */
12924 type = enum_specifier(state, spec);
12927 case TOK_TYPE_NAME:
12928 type = typedef_name(state, spec);
12931 error(state, 0, "bad type specifier %s",
12932 tokens[peek(state)]);
12938 static int istype(int tok)
12956 case TOK_TYPE_NAME:
12964 static struct type *specifier_qualifier_list(struct compile_state *state)
12967 unsigned int specifiers = 0;
12969 /* type qualifiers */
12970 specifiers |= type_qualifiers(state);
12972 /* type specifier */
12973 type = type_specifier(state, specifiers);
12978 static int isdecl_specifier(int tok)
12981 /* storage class specifier */
12987 /* type qualifier */
12991 /* type specifiers */
13001 /* struct or union specifier */
13004 /* enum-spefifier */
13007 case TOK_TYPE_NAME:
13008 /* function specifiers */
13016 static struct type *decl_specifiers(struct compile_state *state)
13019 unsigned int specifiers;
13020 /* I am overly restrictive in the arragement of specifiers supported.
13021 * C is overly flexible in this department it makes interpreting
13022 * the parse tree difficult.
13026 /* storage class specifier */
13027 specifiers |= storage_class_specifier_opt(state);
13029 /* function-specifier */
13030 specifiers |= function_specifier_opt(state);
13033 specifiers |= attributes_opt(state, 0);
13035 /* type qualifier */
13036 specifiers |= type_qualifiers(state);
13038 /* type specifier */
13039 type = type_specifier(state, specifiers);
13043 struct field_info {
13048 static struct field_info designator(struct compile_state *state, struct type *type)
13051 struct field_info info;
13055 switch(peek(state)) {
13058 struct triple *value;
13059 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13060 error(state, 0, "Array designator not in array initializer");
13062 eat(state, TOK_LBRACKET);
13063 value = constant_expr(state);
13064 eat(state, TOK_RBRACKET);
13066 info.type = type->left;
13067 info.offset = value->u.cval * size_of(state, info.type);
13072 struct hash_entry *field;
13073 if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13074 ((type->type & TYPE_MASK) != TYPE_UNION))
13076 error(state, 0, "Struct designator not in struct initializer");
13078 eat(state, TOK_DOT);
13079 eat(state, TOK_IDENT);
13080 field = state->token[0].ident;
13081 info.offset = field_offset(state, type, field);
13082 info.type = field_type(state, type, field);
13086 error(state, 0, "Invalid designator");
13089 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13090 eat(state, TOK_EQ);
13094 static struct triple *initializer(
13095 struct compile_state *state, struct type *type)
13097 struct triple *result;
13098 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13099 if (peek(state) != TOK_LBRACE) {
13100 result = assignment_expr(state);
13101 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13102 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13103 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13104 (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13105 (equiv_types(type->left, result->type->left))) {
13106 type->elements = result->type->elements;
13108 if (is_lvalue(state, result) &&
13109 ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13110 (type->type & TYPE_MASK) != TYPE_ARRAY)
13112 result = lvalue_conversion(state, result);
13114 if (!is_init_compatible(state, type, result->type)) {
13115 error(state, 0, "Incompatible types in initializer");
13117 if (!equiv_types(type, result->type)) {
13118 result = mk_cast_expr(state, type, result);
13124 struct field_info info;
13126 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13127 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13128 internal_error(state, 0, "unknown initializer type");
13131 info.type = type->left;
13132 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13133 info.type = next_field(state, type, 0);
13135 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13138 max_offset = size_of(state, type);
13140 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13141 eat(state, TOK_LBRACE);
13143 struct triple *value;
13144 struct type *value_type;
13150 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13151 info = designator(state, type);
13153 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13154 (info.offset >= max_offset)) {
13155 error(state, 0, "element beyond bounds");
13157 value_type = info.type;
13158 value = eval_const_expr(state, initializer(state, value_type));
13159 value_size = size_of(state, value_type);
13160 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13161 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13162 (max_offset <= info.offset)) {
13166 old_size = max_offset;
13167 max_offset = info.offset + value_size;
13168 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13169 memcpy(buf, old_buf, bits_to_bytes(old_size));
13172 dest = ((char *)buf) + bits_to_bytes(info.offset);
13173 #if DEBUG_INITIALIZER
13174 fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n",
13176 bits_to_bytes(max_offset),
13177 bits_to_bytes(value_size),
13180 if (value->op == OP_BLOBCONST) {
13181 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13183 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13184 #if DEBUG_INITIALIZER
13185 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13187 *((uint8_t *)dest) = value->u.cval & 0xff;
13189 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13190 *((uint16_t *)dest) = value->u.cval & 0xffff;
13192 else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13193 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13196 internal_error(state, 0, "unhandled constant initializer");
13198 free_triple(state, value);
13199 if (peek(state) == TOK_COMMA) {
13200 eat(state, TOK_COMMA);
13203 info.offset += value_size;
13204 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13205 info.type = next_field(state, type, info.type);
13206 info.offset = field_offset(state, type,
13207 info.type->field_ident);
13209 } while(comma && (peek(state) != TOK_RBRACE));
13210 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13211 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13212 type->elements = max_offset / size_of(state, type->left);
13214 eat(state, TOK_RBRACE);
13215 result = triple(state, OP_BLOBCONST, type, 0, 0);
13216 result->u.blob = buf;
13221 static void resolve_branches(struct compile_state *state, struct triple *first)
13223 /* Make a second pass and finish anything outstanding
13224 * with respect to branches. The only outstanding item
13225 * is to see if there are goto to labels that have not
13226 * been defined and to error about them.
13229 struct triple *ins;
13230 /* Also error on branches that do not use their targets */
13233 if (!triple_is_ret(state, ins)) {
13234 struct triple **expr ;
13235 struct triple_set *set;
13236 expr = triple_targ(state, ins, 0);
13237 for(; expr; expr = triple_targ(state, ins, expr)) {
13238 struct triple *targ;
13240 for(set = targ?targ->use:0; set; set = set->next) {
13241 if (set->member == ins) {
13246 internal_error(state, ins, "targ not used");
13251 } while(ins != first);
13252 /* See if there are goto to labels that have not been defined */
13253 for(i = 0; i < HASH_TABLE_SIZE; i++) {
13254 struct hash_entry *entry;
13255 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13256 struct triple *ins;
13257 if (!entry->sym_label) {
13260 ins = entry->sym_label->def;
13261 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13262 error(state, ins, "label `%s' used but not defined",
13269 static struct triple *function_definition(
13270 struct compile_state *state, struct type *type)
13272 struct triple *def, *tmp, *first, *end, *retvar, *result, *ret;
13273 struct triple *fname;
13274 struct type *fname_type;
13275 struct hash_entry *ident;
13276 struct type *param, *crtype, *ctype;
13278 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13279 error(state, 0, "Invalid function header");
13282 /* Verify the function type */
13283 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
13284 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13285 (type->right->field_ident == 0)) {
13286 error(state, 0, "Invalid function parameters");
13288 param = type->right;
13290 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13292 if (!param->left->field_ident) {
13293 error(state, 0, "No identifier for parameter %d\n", i);
13295 param = param->right;
13298 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13299 error(state, 0, "No identifier for paramter %d\n", i);
13302 /* Get a list of statements for this function. */
13303 def = triple(state, OP_LIST, type, 0, 0);
13305 /* Start a new scope for the passed parameters */
13306 start_scope(state);
13308 /* Put a label at the very start of a function */
13309 first = label(state);
13310 RHS(def, 0) = first;
13312 /* Put a label at the very end of a function */
13313 end = label(state);
13314 flatten(state, first, end);
13315 /* Remember where return goes */
13316 ident = state->i_return;
13317 symbol(state, ident, &ident->sym_ident, end, end->type);
13319 /* Get the initial closure type */
13320 ctype = new_type(TYPE_JOIN, &void_type, 0);
13321 ctype->elements = 1;
13323 /* Add a variable for the return value */
13324 crtype = new_type(TYPE_TUPLE,
13325 /* Remove all type qualifiers from the return type */
13326 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13327 crtype->elements = 2;
13328 result = flatten(state, end, variable(state, crtype));
13330 /* Allocate a variable for the return address */
13331 retvar = flatten(state, end, variable(state, &void_ptr_type));
13333 /* Add in the return instruction */
13334 ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13335 ret = flatten(state, first, ret);
13337 /* Walk through the parameters and create symbol table entries
13340 param = type->right;
13341 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13342 ident = param->left->field_ident;
13343 tmp = variable(state, param->left);
13344 var_symbol(state, ident, tmp);
13345 flatten(state, end, tmp);
13346 param = param->right;
13348 if ((param->type & TYPE_MASK) != TYPE_VOID) {
13349 /* And don't forget the last parameter */
13350 ident = param->field_ident;
13351 tmp = variable(state, param);
13352 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13353 flatten(state, end, tmp);
13356 /* Add the declaration static const char __func__ [] = "func-name" */
13357 fname_type = new_type(TYPE_ARRAY,
13358 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13359 fname_type->type |= QUAL_CONST | STOR_STATIC;
13360 fname_type->elements = strlen(state->function) + 1;
13362 fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13363 fname->u.blob = (void *)state->function;
13364 fname = flatten(state, end, fname);
13366 ident = state->i___func__;
13367 symbol(state, ident, &ident->sym_ident, fname, fname_type);
13369 /* Remember which function I am compiling.
13370 * Also assume the last defined function is the main function.
13372 state->main_function = def;
13374 /* Now get the actual function definition */
13375 compound_statement(state, end);
13377 /* Finish anything unfinished with branches */
13378 resolve_branches(state, first);
13380 /* Remove the parameter scope */
13384 /* Remember I have defined a function */
13385 if (!state->functions) {
13386 state->functions = def;
13388 insert_triple(state, state->functions, def);
13390 if (state->compiler->debug & DEBUG_INLINE) {
13391 FILE *fp = state->dbgout;
13394 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13395 display_func(state, fp, def);
13396 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13402 static struct triple *do_decl(struct compile_state *state,
13403 struct type *type, struct hash_entry *ident)
13405 struct triple *def;
13407 /* Clean up the storage types used */
13408 switch (type->type & STOR_MASK) {
13411 /* These are the good types I am aiming for */
13413 case STOR_REGISTER:
13414 type->type &= ~STOR_MASK;
13415 type->type |= STOR_AUTO;
13419 type->type &= ~STOR_MASK;
13420 type->type |= STOR_STATIC;
13424 error(state, 0, "typedef without name");
13426 symbol(state, ident, &ident->sym_ident, 0, type);
13427 ident->tok = TOK_TYPE_NAME;
13431 internal_error(state, 0, "Undefined storage class");
13433 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13434 error(state, 0, "Function prototypes not supported");
13437 ((type->type & STOR_MASK) == STOR_STATIC) &&
13438 ((type->type & QUAL_CONST) == 0)) {
13439 error(state, 0, "non const static variables not supported");
13442 def = variable(state, type);
13443 var_symbol(state, ident, def);
13448 static void decl(struct compile_state *state, struct triple *first)
13450 struct type *base_type, *type;
13451 struct hash_entry *ident;
13452 struct triple *def;
13454 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13455 base_type = decl_specifiers(state);
13457 type = declarator(state, base_type, &ident, 0);
13458 type->type = attributes_opt(state, type->type);
13459 if (global && ident && (peek(state) == TOK_LBRACE)) {
13461 type->type_ident = ident;
13462 state->function = ident->name;
13463 def = function_definition(state, type);
13464 symbol(state, ident, &ident->sym_ident, def, type);
13465 state->function = 0;
13469 flatten(state, first, do_decl(state, type, ident));
13470 /* type or variable definition */
13473 if (peek(state) == TOK_EQ) {
13475 error(state, 0, "cannot assign to a type");
13477 eat(state, TOK_EQ);
13478 flatten(state, first,
13480 ident->sym_ident->def,
13481 initializer(state, type)));
13483 arrays_complete(state, type);
13484 if (peek(state) == TOK_COMMA) {
13485 eat(state, TOK_COMMA);
13487 type = declarator(state, base_type, &ident, 0);
13488 flatten(state, first, do_decl(state, type, ident));
13492 eat(state, TOK_SEMI);
13496 static void decls(struct compile_state *state)
13498 struct triple *list;
13500 list = label(state);
13503 if (tok == TOK_EOF) {
13506 if (tok == TOK_SPACE) {
13507 eat(state, TOK_SPACE);
13510 if (list->next != list) {
13511 error(state, 0, "global variables not supported");
13517 * Function inlining
13519 struct triple_reg_set {
13520 struct triple_reg_set *next;
13521 struct triple *member;
13522 struct triple *new;
13525 struct block *block;
13526 struct triple_reg_set *in;
13527 struct triple_reg_set *out;
13530 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13531 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13532 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13533 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13534 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13535 void (*cb)(struct compile_state *state, struct block *block, void *arg),
13537 static void print_block(
13538 struct compile_state *state, struct block *block, void *arg);
13539 static int do_triple_set(struct triple_reg_set **head,
13540 struct triple *member, struct triple *new_member);
13541 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13542 static struct reg_block *compute_variable_lifetimes(
13543 struct compile_state *state, struct basic_blocks *bb);
13544 static void free_variable_lifetimes(struct compile_state *state,
13545 struct basic_blocks *bb, struct reg_block *blocks);
13546 static void print_live_variables(struct compile_state *state,
13547 struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13550 static struct triple *call(struct compile_state *state,
13551 struct triple *retvar, struct triple *ret_addr,
13552 struct triple *targ, struct triple *ret)
13554 struct triple *call;
13556 if (!retvar || !is_lvalue(state, retvar)) {
13557 internal_error(state, 0, "writing to a non lvalue?");
13559 write_compatible(state, retvar->type, &void_ptr_type);
13561 call = new_triple(state, OP_CALL, &void_type, 1, 0);
13562 TARG(call, 0) = targ;
13563 MISC(call, 0) = ret;
13564 if (!targ || (targ->op != OP_LABEL)) {
13565 internal_error(state, 0, "call not to a label");
13567 if (!ret || (ret->op != OP_RET)) {
13568 internal_error(state, 0, "call not matched with return");
13573 static void walk_functions(struct compile_state *state,
13574 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13577 struct triple *func, *first;
13578 func = first = state->functions;
13580 cb(state, func, arg);
13582 } while(func != first);
13585 static void reverse_walk_functions(struct compile_state *state,
13586 void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13589 struct triple *func, *first;
13590 func = first = state->functions;
13593 cb(state, func, arg);
13594 } while(func != first);
13598 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13600 struct triple *ptr, *first;
13601 if (func->u.cval == 0) {
13604 ptr = first = RHS(func, 0);
13606 if (ptr->op == OP_FCALL) {
13607 struct triple *called_func;
13608 called_func = MISC(ptr, 0);
13609 /* Mark the called function as used */
13610 if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13611 called_func->u.cval++;
13613 /* Remove the called function from the list */
13614 called_func->prev->next = called_func->next;
13615 called_func->next->prev = called_func->prev;
13617 /* Place the called function before me on the list */
13618 called_func->next = func;
13619 called_func->prev = func->prev;
13620 called_func->prev->next = called_func;
13621 called_func->next->prev = called_func;
13624 } while(ptr != first);
13625 func->id |= TRIPLE_FLAG_FLATTENED;
13628 static void mark_live_functions(struct compile_state *state)
13630 /* Ensure state->main_function is the last function in
13631 * the list of functions.
13633 if ((state->main_function->next != state->functions) ||
13634 (state->functions->prev != state->main_function)) {
13635 internal_error(state, 0,
13636 "state->main_function is not at the end of the function list ");
13638 state->main_function->u.cval = 1;
13639 reverse_walk_functions(state, mark_live, 0);
13642 static int local_triple(struct compile_state *state,
13643 struct triple *func, struct triple *ins)
13645 int local = (ins->id & TRIPLE_FLAG_LOCAL);
13648 FILE *fp = state->errout;
13649 fprintf(fp, "global: ");
13650 display_triple(fp, ins);
13656 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
13657 struct occurance *base_occurance)
13659 struct triple *nfunc;
13660 struct triple *nfirst, *ofirst;
13661 struct triple *new, *old;
13663 if (state->compiler->debug & DEBUG_INLINE) {
13664 FILE *fp = state->dbgout;
13667 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13668 display_func(state, fp, ofunc);
13669 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13672 /* Make a new copy of the old function */
13673 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13675 ofirst = old = RHS(ofunc, 0);
13677 struct triple *new;
13678 struct occurance *occurance;
13679 int old_lhs, old_rhs;
13680 old_lhs = old->lhs;
13681 old_rhs = old->rhs;
13682 occurance = inline_occurance(state, base_occurance, old->occurance);
13683 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13684 MISC(old, 0)->u.cval += 1;
13686 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13688 if (!triple_stores_block(state, new)) {
13689 memcpy(&new->u, &old->u, sizeof(new->u));
13692 RHS(nfunc, 0) = nfirst = new;
13695 insert_triple(state, nfirst, new);
13697 new->id |= TRIPLE_FLAG_FLATTENED;
13698 new->id |= old->id & TRIPLE_FLAG_COPY;
13700 /* During the copy remember new as user of old */
13701 use_triple(old, new);
13703 /* Remember which instructions are local */
13704 old->id |= TRIPLE_FLAG_LOCAL;
13706 } while(old != ofirst);
13708 /* Make a second pass to fix up any unresolved references */
13712 struct triple **oexpr, **nexpr;
13714 /* Lookup where the copy is, to join pointers */
13715 count = TRIPLE_SIZE(old);
13716 for(i = 0; i < count; i++) {
13717 oexpr = &old->param[i];
13718 nexpr = &new->param[i];
13719 if (*oexpr && !*nexpr) {
13720 if (!local_triple(state, ofunc, *oexpr)) {
13723 else if ((*oexpr)->use) {
13724 *nexpr = (*oexpr)->use->member;
13726 if (*nexpr == old) {
13727 internal_error(state, 0, "new == old?");
13729 use_triple(*nexpr, new);
13731 if (!*nexpr && *oexpr) {
13732 internal_error(state, 0, "Could not copy %d", i);
13737 } while((old != ofirst) && (new != nfirst));
13739 /* Make a third pass to cleanup the extra useses */
13743 unuse_triple(old, new);
13744 /* Forget which instructions are local */
13745 old->id &= ~TRIPLE_FLAG_LOCAL;
13748 } while ((old != ofirst) && (new != nfirst));
13752 static void expand_inline_call(
13753 struct compile_state *state, struct triple *me, struct triple *fcall)
13755 /* Inline the function call */
13756 struct type *ptype;
13757 struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13758 struct triple *end, *nend;
13761 /* Find the triples */
13762 ofunc = MISC(fcall, 0);
13763 if (ofunc->op != OP_LIST) {
13764 internal_error(state, 0, "improper function");
13766 nfunc = copy_func(state, ofunc, fcall->occurance);
13767 /* Prepend the parameter reading into the new function list */
13768 ptype = nfunc->type->right;
13769 pvals = fcall->rhs;
13770 for(i = 0; i < pvals; i++) {
13771 struct type *atype;
13772 struct triple *arg, *param;
13774 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13775 atype = ptype->left;
13777 param = farg(state, nfunc, i);
13778 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13779 internal_error(state, fcall, "param %d type mismatch", i);
13781 arg = RHS(fcall, i);
13782 flatten(state, fcall, write_expr(state, param, arg));
13783 ptype = ptype->right;
13786 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13787 result = read_expr(state,
13788 deref_index(state, fresult(state, nfunc), 1));
13790 if (state->compiler->debug & DEBUG_INLINE) {
13791 FILE *fp = state->dbgout;
13794 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13795 display_func(state, fp, nfunc);
13796 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13800 * Get rid of the extra triples
13802 /* Remove the read of the return address */
13803 ins = RHS(nfunc, 0)->prev->prev;
13804 if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13805 internal_error(state, ins, "Not return addres read?");
13807 release_triple(state, ins);
13808 /* Remove the return instruction */
13809 ins = RHS(nfunc, 0)->prev;
13810 if (ins->op != OP_RET) {
13811 internal_error(state, ins, "Not return?");
13813 release_triple(state, ins);
13814 /* Remove the retaddres variable */
13815 retvar = fretaddr(state, nfunc);
13816 if ((retvar->lhs != 1) ||
13817 (retvar->op != OP_ADECL) ||
13818 (retvar->next->op != OP_PIECE) ||
13819 (MISC(retvar->next, 0) != retvar)) {
13820 internal_error(state, retvar, "Not the return address?");
13822 release_triple(state, retvar->next);
13823 release_triple(state, retvar);
13825 /* Remove the label at the start of the function */
13826 ins = RHS(nfunc, 0);
13827 if (ins->op != OP_LABEL) {
13828 internal_error(state, ins, "Not label?");
13830 nfirst = ins->next;
13831 free_triple(state, ins);
13832 /* Release the new function header */
13834 free_triple(state, nfunc);
13836 /* Append the new function list onto the return list */
13838 nend = nfirst->prev;
13839 end->next = nfirst;
13840 nfirst->prev = end;
13841 nend->next = fcall;
13842 fcall->prev = nend;
13844 /* Now the result reading code */
13846 result = flatten(state, fcall, result);
13847 propogate_use(state, fcall, result);
13850 /* Release the original fcall instruction */
13851 release_triple(state, fcall);
13858 * Type of the result variable.
13862 * +----------+------------+
13864 * union of closures result_type
13866 * +------------------+---------------+
13868 * closure1 ... closuerN
13870 * +----+--+-+--------+-----+ +----+----+---+-----+
13871 * | | | | | | | | |
13872 * var1 var2 var3 ... varN result var1 var2 ... varN result
13874 * +--------+---------+
13876 * union of closures result_type
13878 * +-----+-------------------+
13880 * closure1 ... closureN
13882 * +-----+---+----+----+ +----+---+----+-----+
13884 * var1 var2 ... varN result var1 var2 ... varN result
13887 static int add_closure_type(struct compile_state *state,
13888 struct triple *func, struct type *closure_type)
13890 struct type *type, *ctype, **next;
13891 struct triple *var, *new_var;
13895 FILE *fp = state->errout;
13896 fprintf(fp, "original_type: ");
13897 name_of(fp, fresult(state, func)->type);
13900 /* find the original type */
13901 var = fresult(state, func);
13903 if (type->elements != 2) {
13904 internal_error(state, var, "bad return type");
13907 /* Find the complete closure type and update it */
13908 ctype = type->left->left;
13909 next = &ctype->left;
13910 while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13911 next = &(*next)->right;
13913 *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13914 ctype->elements += 1;
13917 fprintf(fp, "new_type: ");
13920 fprintf(fp, "ctype: %p %d bits: %d ",
13921 ctype, ctype->elements, reg_size_of(state, ctype));
13922 name_of(fp, ctype);
13926 /* Regenerate the variable with the new type definition */
13927 new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13928 new_var->id |= TRIPLE_FLAG_FLATTENED;
13929 for(i = 0; i < new_var->lhs; i++) {
13930 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13933 /* Point everyone at the new variable */
13934 propogate_use(state, var, new_var);
13936 /* Release the original variable */
13937 for(i = 0; i < var->lhs; i++) {
13938 release_triple(state, LHS(var, i));
13940 release_triple(state, var);
13942 /* Return the index of the added closure type */
13943 return ctype->elements - 1;
13946 static struct triple *closure_expr(struct compile_state *state,
13947 struct triple *func, int closure_idx, int var_idx)
13949 return deref_index(state,
13951 deref_index(state, fresult(state, func), 0),
13957 static void insert_triple_set(
13958 struct triple_reg_set **head, struct triple *member)
13960 struct triple_reg_set *new;
13961 new = xcmalloc(sizeof(*new), "triple_set");
13962 new->member = member;
13968 static int ordered_triple_set(
13969 struct triple_reg_set **head, struct triple *member)
13971 struct triple_reg_set **ptr;
13976 if (member == (*ptr)->member) {
13979 /* keep the list ordered */
13980 if (member->id < (*ptr)->member->id) {
13983 ptr = &(*ptr)->next;
13985 insert_triple_set(ptr, member);
13990 static void free_closure_variables(struct compile_state *state,
13991 struct triple_reg_set **enclose)
13993 struct triple_reg_set *entry, *next;
13994 for(entry = *enclose; entry; entry = next) {
13995 next = entry->next;
13996 do_triple_unset(enclose, entry->member);
14000 static int lookup_closure_index(struct compile_state *state,
14001 struct triple *me, struct triple *val)
14003 struct triple *first, *ins, *next;
14004 first = RHS(me, 0);
14005 ins = next = first;
14007 struct triple *result;
14008 struct triple *index0, *index1, *index2, *read, *write;
14011 if (ins->op != OP_CALL) {
14014 /* I am at a previous call point examine it closely */
14015 if (ins->next->op != OP_LABEL) {
14016 internal_error(state, ins, "call not followed by label");
14018 /* Does this call does not enclose any variables? */
14019 if ((ins->next->next->op != OP_INDEX) ||
14020 (ins->next->next->u.cval != 0) ||
14021 (result = MISC(ins->next->next, 0)) ||
14022 (result->id & TRIPLE_FLAG_LOCAL)) {
14025 index0 = ins->next->next;
14027 * 0 index result < 0 >
14033 for(index0 = ins->next->next;
14034 (index0->op == OP_INDEX) &&
14035 (MISC(index0, 0) == result) &&
14036 (index0->u.cval == 0) ;
14037 index0 = write->next)
14039 index1 = index0->next;
14040 index2 = index1->next;
14041 read = index2->next;
14042 write = read->next;
14043 if ((index0->op != OP_INDEX) ||
14044 (index1->op != OP_INDEX) ||
14045 (index2->op != OP_INDEX) ||
14046 (read->op != OP_READ) ||
14047 (write->op != OP_WRITE) ||
14048 (MISC(index1, 0) != index0) ||
14049 (MISC(index2, 0) != index1) ||
14050 (RHS(read, 0) != index2) ||
14051 (RHS(write, 0) != read)) {
14052 internal_error(state, index0, "bad var read");
14054 if (MISC(write, 0) == val) {
14055 return index2->u.cval;
14058 } while(next != first);
14062 static inline int enclose_triple(struct triple *ins)
14064 return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14067 static void compute_closure_variables(struct compile_state *state,
14068 struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14070 struct triple_reg_set *set, *vars, **last_var;
14071 struct basic_blocks bb;
14072 struct reg_block *rb;
14073 struct block *block;
14074 struct triple *old_result, *first, *ins;
14076 unsigned long used_indicies;
14078 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14079 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14086 /* Find the basic blocks of this function */
14088 bb.first = RHS(me, 0);
14090 if (!triple_is_ret(state, bb.first->prev)) {
14093 old_result = fresult(state, me);
14095 analyze_basic_blocks(state, &bb);
14097 /* Find which variables are currently alive in a given block */
14098 rb = compute_variable_lifetimes(state, &bb);
14100 /* Find the variables that are currently alive */
14101 block = block_of_triple(state, fcall);
14102 if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14103 internal_error(state, fcall, "No reg block? block: %p", block);
14106 #if DEBUG_EXPLICIT_CLOSURES
14107 print_live_variables(state, &bb, rb, state->dbgout);
14108 fflush(state->dbgout);
14111 /* Count the number of triples in the function */
14112 first = RHS(me, 0);
14118 } while(ins != first);
14120 /* Allocate some memory to temorary hold the id info */
14121 info = xcmalloc(sizeof(*info) * (count +1), "info");
14123 /* Mark the local function */
14124 first = RHS(me, 0);
14128 info[idx].id = ins->id;
14129 ins->id = TRIPLE_FLAG_LOCAL | idx;
14132 } while(ins != first);
14135 * Build the list of variables to enclose.
14137 * A target it to put the same variable in the
14138 * same slot for ever call of a given function.
14139 * After coloring this removes all of the variable
14140 * manipulation code.
14142 * The list of variables to enclose is built ordered
14143 * program order because except in corner cases this
14144 * gives me the stability of assignment I need.
14146 * To gurantee that stability I lookup the variables
14147 * to see where they have been used before and
14148 * I build my final list with the assigned indicies.
14151 if (enclose_triple(old_result)) {
14152 ordered_triple_set(&vars, old_result);
14154 for(set = rb[block->vertex].out; set; set = set->next) {
14155 if (!enclose_triple(set->member)) {
14158 if ((set->member == fcall) || (set->member == old_result)) {
14161 if (!local_triple(state, me, set->member)) {
14162 internal_error(state, set->member, "not local?");
14164 ordered_triple_set(&vars, set->member);
14167 /* Lookup the current indicies of the live varialbe */
14170 for(set = vars; set ; set = set->next) {
14171 struct triple *ins;
14174 index = lookup_closure_index(state, me, ins);
14175 info[ID_BITS(ins->id)].index = index;
14179 if (index >= MAX_INDICIES) {
14180 internal_error(state, ins, "index unexpectedly large");
14182 if (used_indicies & (1 << index)) {
14183 internal_error(state, ins, "index previously used?");
14185 /* Remember which indicies have been used */
14186 used_indicies |= (1 << index);
14187 if (index > max_index) {
14192 /* Walk through the live variables and make certain
14193 * everything is assigned an index.
14195 for(set = vars; set; set = set->next) {
14196 struct triple *ins;
14199 index = info[ID_BITS(ins->id)].index;
14203 /* Find the lowest unused index value */
14204 for(index = 0; index < MAX_INDICIES; index++) {
14205 if (!(used_indicies & (1 << index))) {
14209 if (index == MAX_INDICIES) {
14210 internal_error(state, ins, "no free indicies?");
14212 info[ID_BITS(ins->id)].index = index;
14213 /* Remember which indicies have been used */
14214 used_indicies |= (1 << index);
14215 if (index > max_index) {
14220 /* Build the return list of variables with positions matching
14224 last_var = enclose;
14225 for(i = 0; i <= max_index; i++) {
14226 struct triple *var;
14228 if (used_indicies & (1 << i)) {
14229 for(set = vars; set; set = set->next) {
14231 index = info[ID_BITS(set->member->id)].index;
14238 internal_error(state, me, "missing variable");
14241 insert_triple_set(last_var, var);
14242 last_var = &(*last_var)->next;
14245 #if DEBUG_EXPLICIT_CLOSURES
14246 /* Print out the variables to be enclosed */
14247 loc(state->dbgout, state, fcall);
14248 fprintf(state->dbgout, "Alive: \n");
14249 for(set = *enclose; set; set = set->next) {
14250 display_triple(state->dbgout, set->member);
14252 fflush(state->dbgout);
14255 /* Clear the marks */
14258 ins->id = info[ID_BITS(ins->id)].id;
14260 } while(ins != first);
14262 /* Release the ordered list of live variables */
14263 free_closure_variables(state, &vars);
14265 /* Release the storage of the old ids */
14268 /* Release the variable lifetime information */
14269 free_variable_lifetimes(state, &bb, rb);
14271 /* Release the basic blocks of this function */
14272 free_basic_blocks(state, &bb);
14275 static void expand_function_call(
14276 struct compile_state *state, struct triple *me, struct triple *fcall)
14278 /* Generate an ordinary function call */
14279 struct type *closure_type, **closure_next;
14280 struct triple *func, *func_first, *func_last, *retvar;
14281 struct triple *first;
14282 struct type *ptype, *rtype;
14283 struct triple *jmp;
14284 struct triple *ret_addr, *ret_loc, *ret_set;
14285 struct triple_reg_set *enclose, *set;
14286 int closure_idx, pvals, i;
14288 #if DEBUG_EXPLICIT_CLOSURES
14289 FILE *fp = state->dbgout;
14290 fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14291 display_func(state, fp, MISC(fcall, 0));
14292 display_func(state, fp, me);
14293 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14296 /* Find the triples */
14297 func = MISC(fcall, 0);
14298 func_first = RHS(func, 0);
14299 retvar = fretaddr(state, func);
14300 func_last = func_first->prev;
14301 first = fcall->next;
14303 /* Find what I need to enclose */
14304 compute_closure_variables(state, me, fcall, &enclose);
14306 /* Compute the closure type */
14307 closure_type = new_type(TYPE_TUPLE, 0, 0);
14308 closure_type->elements = 0;
14309 closure_next = &closure_type->left;
14310 for(set = enclose; set ; set = set->next) {
14314 type = set->member->type;
14316 if (!*closure_next) {
14317 *closure_next = type;
14319 *closure_next = new_type(TYPE_PRODUCT, *closure_next,
14321 closure_next = &(*closure_next)->right;
14323 closure_type->elements += 1;
14325 if (closure_type->elements == 0) {
14326 closure_type->type = TYPE_VOID;
14330 #if DEBUG_EXPLICIT_CLOSURES
14331 fprintf(state->dbgout, "closure type: ");
14332 name_of(state->dbgout, closure_type);
14333 fprintf(state->dbgout, "\n");
14336 /* Update the called functions closure variable */
14337 closure_idx = add_closure_type(state, func, closure_type);
14339 /* Generate some needed triples */
14340 ret_loc = label(state);
14341 ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14343 /* Pass the parameters to the new function */
14344 ptype = func->type->right;
14345 pvals = fcall->rhs;
14346 for(i = 0; i < pvals; i++) {
14347 struct type *atype;
14348 struct triple *arg, *param;
14350 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14351 atype = ptype->left;
14353 param = farg(state, func, i);
14354 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14355 internal_error(state, fcall, "param type mismatch");
14357 arg = RHS(fcall, i);
14358 flatten(state, first, write_expr(state, param, arg));
14359 ptype = ptype->right;
14361 rtype = func->type->left;
14363 /* Thread the triples together */
14364 ret_loc = flatten(state, first, ret_loc);
14366 /* Save the active variables in the result variable */
14367 for(i = 0, set = enclose; set ; set = set->next, i++) {
14368 if (!set->member) {
14371 flatten(state, ret_loc,
14373 closure_expr(state, func, closure_idx, i),
14374 read_expr(state, set->member)));
14377 /* Initialize the return value */
14378 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14379 flatten(state, ret_loc,
14381 deref_index(state, fresult(state, func), 1),
14382 new_triple(state, OP_UNKNOWNVAL, rtype, 0, 0)));
14385 ret_addr = flatten(state, ret_loc, ret_addr);
14386 ret_set = flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14387 jmp = flatten(state, ret_loc,
14388 call(state, retvar, ret_addr, func_first, func_last));
14390 /* Restore the active variables from the result variable */
14391 for(i = 0, set = enclose; set ; set = set->next, i++) {
14392 struct triple_set *use, *next;
14393 struct triple *new;
14394 if (!set->member || (set->member == fcall)) {
14397 /* Generate an expression for the value */
14398 new = flatten(state, first,
14400 closure_expr(state, func, closure_idx, i)));
14403 /* If the original is an lvalue restore the preserved value */
14404 if (is_lvalue(state, set->member)) {
14405 flatten(state, first,
14406 write_expr(state, set->member, new));
14409 /* If the original is a value update the dominated uses */
14411 #if DEBUG_EXPLICIT_CLOSURES
14412 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14415 /* If fcall dominates the use update the expression */
14416 for(use = set->member->use; use; use = next) {
14417 /* Replace use modifies the use chain and
14418 * removes use, so I must take a copy of the
14419 * next entry early.
14422 if (!tdominates(state, fcall, use->member)) {
14425 replace_use(state, set->member, new, use->member);
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 /* Release the closure variable list */
14443 free_closure_variables(state, &enclose);
14445 if (state->compiler->debug & DEBUG_INLINE) {
14446 FILE *fp = state->dbgout;
14449 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14450 display_func(state, fp, func);
14451 display_func(state, fp, me);
14452 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14458 static int do_inline(struct compile_state *state, struct triple *func)
14463 policy = state->compiler->flags & COMPILER_INLINE_MASK;
14465 case COMPILER_INLINE_ALWAYS:
14467 if (func->type->type & ATTRIB_NOINLINE) {
14468 error(state, func, "noinline with always_inline compiler option");
14471 case COMPILER_INLINE_NEVER:
14473 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14474 error(state, func, "always_inline with noinline compiler option");
14477 case COMPILER_INLINE_DEFAULTON:
14478 switch(func->type->type & STOR_MASK) {
14479 case STOR_STATIC | STOR_INLINE:
14480 case STOR_LOCAL | STOR_INLINE:
14481 case STOR_EXTERN | STOR_INLINE:
14489 case COMPILER_INLINE_DEFAULTOFF:
14490 switch(func->type->type & STOR_MASK) {
14491 case STOR_STATIC | STOR_INLINE:
14492 case STOR_LOCAL | STOR_INLINE:
14493 case STOR_EXTERN | STOR_INLINE:
14501 case COMPILER_INLINE_NOPENALTY:
14502 switch(func->type->type & STOR_MASK) {
14503 case STOR_STATIC | STOR_INLINE:
14504 case STOR_LOCAL | STOR_INLINE:
14505 case STOR_EXTERN | STOR_INLINE:
14509 do_inline = (func->u.cval == 1);
14515 internal_error(state, 0, "Unimplemented inline policy");
14518 /* Force inlining */
14519 if (func->type->type & ATTRIB_NOINLINE) {
14522 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14528 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14530 struct triple *first, *ptr, *next;
14531 /* If the function is not used don't bother */
14532 if (me->u.cval <= 0) {
14535 if (state->compiler->debug & DEBUG_CALLS2) {
14536 FILE *fp = state->dbgout;
14537 fprintf(fp, "in: %s\n",
14538 me->type->type_ident->name);
14541 first = RHS(me, 0);
14542 ptr = next = first;
14544 struct triple *func, *prev;
14548 if (ptr->op != OP_FCALL) {
14551 func = MISC(ptr, 0);
14552 /* See if the function should be inlined */
14553 if (!do_inline(state, func)) {
14554 /* Put a label after the fcall */
14555 post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14558 if (state->compiler->debug & DEBUG_CALLS) {
14559 FILE *fp = state->dbgout;
14560 if (state->compiler->debug & DEBUG_CALLS2) {
14561 loc(fp, state, ptr);
14563 fprintf(fp, "inlining %s\n",
14564 func->type->type_ident->name);
14568 /* Update the function use counts */
14571 /* Replace the fcall with the called function */
14572 expand_inline_call(state, me, ptr);
14575 } while (next != first);
14577 ptr = next = first;
14579 struct triple *prev, *func;
14583 if (ptr->op != OP_FCALL) {
14586 func = MISC(ptr, 0);
14587 if (state->compiler->debug & DEBUG_CALLS) {
14588 FILE *fp = state->dbgout;
14589 if (state->compiler->debug & DEBUG_CALLS2) {
14590 loc(fp, state, ptr);
14592 fprintf(fp, "calling %s\n",
14593 func->type->type_ident->name);
14596 /* Replace the fcall with the instruction sequence
14597 * needed to make the call.
14599 expand_function_call(state, me, ptr);
14601 } while(next != first);
14604 static void inline_functions(struct compile_state *state, struct triple *func)
14606 inline_function(state, func, 0);
14607 reverse_walk_functions(state, inline_function, 0);
14610 static void insert_function(struct compile_state *state,
14611 struct triple *func, void *arg)
14613 struct triple *first, *end, *ffirst, *fend;
14615 if (state->compiler->debug & DEBUG_INLINE) {
14616 FILE *fp = state->errout;
14617 fprintf(fp, "%s func count: %d\n",
14618 func->type->type_ident->name, func->u.cval);
14620 if (func->u.cval == 0) {
14624 /* Find the end points of the lists */
14627 ffirst = RHS(func, 0);
14628 fend = ffirst->prev;
14630 /* splice the lists together */
14631 end->next = ffirst;
14632 ffirst->prev = end;
14633 fend->next = first;
14634 first->prev = fend;
14637 struct triple *input_asm(struct compile_state *state)
14639 struct asm_info *info;
14640 struct triple *def;
14643 info = xcmalloc(sizeof(*info), "asm_info");
14646 out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14647 memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14649 def = new_triple(state, OP_ASM, &void_type, out, 0);
14650 def->u.ainfo = info;
14651 def->id |= TRIPLE_FLAG_VOLATILE;
14653 for(i = 0; i < out; i++) {
14654 struct triple *piece;
14655 piece = triple(state, OP_PIECE, &int_type, def, 0);
14657 LHS(def, i) = piece;
14663 struct triple *output_asm(struct compile_state *state)
14665 struct asm_info *info;
14666 struct triple *def;
14669 info = xcmalloc(sizeof(*info), "asm_info");
14672 in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14673 memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14675 def = new_triple(state, OP_ASM, &void_type, 0, in);
14676 def->u.ainfo = info;
14677 def->id |= TRIPLE_FLAG_VOLATILE;
14682 static void join_functions(struct compile_state *state)
14684 struct triple *jmp, *start, *end, *call, *in, *out, *func;
14685 struct file_state file;
14686 struct type *pnext, *param;
14687 struct type *result_type, *args_type;
14690 /* Be clear the functions have not been joined yet */
14691 state->functions_joined = 0;
14693 /* Dummy file state to get debug handing right */
14694 memset(&file, 0, sizeof(file));
14695 file.basename = "";
14697 file.report_line = 0;
14698 file.report_name = file.basename;
14699 file.prev = state->file;
14700 state->file = &file;
14701 state->function = "";
14703 /* The type of arguments */
14704 args_type = state->main_function->type->right;
14705 /* The return type without any specifiers */
14706 result_type = clone_type(0, state->main_function->type->left);
14709 /* Verify the external arguments */
14710 if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14711 error(state, state->main_function,
14712 "Too many external input arguments");
14714 if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14715 error(state, state->main_function,
14716 "Too many external output arguments");
14719 /* Lay down the basic program structure */
14720 end = label(state);
14721 start = label(state);
14722 start = flatten(state, state->first, start);
14723 end = flatten(state, state->first, end);
14724 in = input_asm(state);
14725 out = output_asm(state);
14726 call = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14727 MISC(call, 0) = state->main_function;
14728 in = flatten(state, state->first, in);
14729 call = flatten(state, state->first, call);
14730 out = flatten(state, state->first, out);
14733 /* Read the external input arguments */
14736 while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14737 struct triple *expr;
14740 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14741 pnext = param->right;
14742 param = param->left;
14744 if (registers_of(state, param) != 1) {
14745 error(state, state->main_function,
14746 "Arg: %d %s requires multiple registers",
14747 idx + 1, param->field_ident->name);
14749 expr = read_expr(state, LHS(in, idx));
14750 RHS(call, idx) = expr;
14751 expr = flatten(state, call, expr);
14752 use_triple(expr, call);
14758 /* Write the external output arguments */
14759 pnext = result_type;
14760 if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14761 pnext = result_type->left;
14763 for(idx = 0; idx < out->rhs; idx++) {
14764 struct triple *expr;
14767 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14768 pnext = param->right;
14769 param = param->left;
14771 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14775 if (registers_of(state, param) != 1) {
14776 error(state, state->main_function,
14777 "Result: %d %s requires multiple registers",
14778 idx, param->field_ident->name);
14780 expr = read_expr(state, call);
14781 if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14782 expr = deref_field(state, expr, param->field_ident);
14785 expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14787 flatten(state, out, expr);
14788 RHS(out, idx) = expr;
14789 use_triple(expr, out);
14792 /* Allocate a dummy containing function */
14793 func = triple(state, OP_LIST,
14794 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14795 func->type->type_ident = lookup(state, "", 0);
14796 RHS(func, 0) = state->first;
14799 /* See which functions are called, and how often */
14800 mark_live_functions(state);
14801 inline_functions(state, func);
14802 walk_functions(state, insert_function, end);
14804 if (start->next != end) {
14805 jmp = flatten(state, start, branch(state, end, 0));
14808 /* OK now the functions have been joined. */
14809 state->functions_joined = 1;
14811 /* Done now cleanup */
14812 state->file = file.prev;
14813 state->function = 0;
14817 * Data structurs for optimation.
14821 static int do_use_block(
14822 struct block *used, struct block_set **head, struct block *user,
14825 struct block_set **ptr, *new;
14832 if ((*ptr)->member == user) {
14835 ptr = &(*ptr)->next;
14837 new = xcmalloc(sizeof(*new), "block_set");
14838 new->member = user;
14849 static int do_unuse_block(
14850 struct block *used, struct block_set **head, struct block *unuser)
14852 struct block_set *use, **ptr;
14858 if (use->member == unuser) {
14860 memset(use, -1, sizeof(*use));
14871 static void use_block(struct block *used, struct block *user)
14874 /* Append new to the head of the list, print_block
14877 count = do_use_block(used, &used->use, user, 1);
14878 used->users += count;
14880 static void unuse_block(struct block *used, struct block *unuser)
14883 count = do_unuse_block(used, &used->use, unuser);
14884 used->users -= count;
14887 static void add_block_edge(struct block *block, struct block *edge, int front)
14890 count = do_use_block(block, &block->edges, edge, front);
14891 block->edge_count += count;
14894 static void remove_block_edge(struct block *block, struct block *edge)
14897 count = do_unuse_block(block, &block->edges, edge);
14898 block->edge_count -= count;
14901 static void idom_block(struct block *idom, struct block *user)
14903 do_use_block(idom, &idom->idominates, user, 0);
14906 static void unidom_block(struct block *idom, struct block *unuser)
14908 do_unuse_block(idom, &idom->idominates, unuser);
14911 static void domf_block(struct block *block, struct block *domf)
14913 do_use_block(block, &block->domfrontier, domf, 0);
14916 static void undomf_block(struct block *block, struct block *undomf)
14918 do_unuse_block(block, &block->domfrontier, undomf);
14921 static void ipdom_block(struct block *ipdom, struct block *user)
14923 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14926 static void unipdom_block(struct block *ipdom, struct block *unuser)
14928 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14931 static void ipdomf_block(struct block *block, struct block *ipdomf)
14933 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
14936 static void unipdomf_block(struct block *block, struct block *unipdomf)
14938 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
14941 static int walk_triples(
14942 struct compile_state *state,
14943 int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
14946 struct triple *ptr;
14948 ptr = state->first;
14950 result = cb(state, ptr, arg);
14951 if (ptr->next->prev != ptr) {
14952 internal_error(state, ptr->next, "bad prev");
14955 } while((result == 0) && (ptr != state->first));
14959 #define PRINT_LIST 1
14960 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
14965 if (op == OP_LIST) {
14970 if ((op == OP_LABEL) && (ins->use)) {
14971 fprintf(fp, "\n%p:\n", ins);
14973 display_triple(fp, ins);
14975 if (triple_is_branch(state, ins) && ins->use &&
14976 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
14977 internal_error(state, ins, "branch used?");
14979 if (triple_is_branch(state, ins)) {
14985 static void print_triples(struct compile_state *state)
14987 if (state->compiler->debug & DEBUG_TRIPLES) {
14988 FILE *fp = state->dbgout;
14989 fprintf(fp, "--------------- triples ---------------\n");
14990 walk_triples(state, do_print_triple, fp);
14996 struct block *block;
14998 static void find_cf_blocks(struct cf_block *cf, struct block *block)
15000 struct block_set *edge;
15001 if (!block || (cf[block->vertex].block == block)) {
15004 cf[block->vertex].block = block;
15005 for(edge = block->edges; edge; edge = edge->next) {
15006 find_cf_blocks(cf, edge->member);
15010 static void print_control_flow(struct compile_state *state,
15011 struct basic_blocks *bb)
15013 struct cf_block *cf;
15015 printf("\ncontrol flow\n");
15016 cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15017 find_cf_blocks(cf, bb->first_block);
15019 for(i = 1; i <= bb->last_vertex; i++) {
15020 struct block *block;
15021 struct block_set *edge;
15022 block = cf[i].block;
15025 printf("(%p) %d:", block, block->vertex);
15026 for(edge = block->edges; edge; edge = edge->next) {
15027 printf(" %d", edge->member->vertex);
15035 static void free_basic_block(struct compile_state *state, struct block *block)
15037 struct block_set *edge, *entry;
15038 struct block *child;
15042 if (block->vertex == -1) {
15045 block->vertex = -1;
15046 for(edge = block->edges; edge; edge = edge->next) {
15047 if (edge->member) {
15048 unuse_block(edge->member, block);
15052 unidom_block(block->idom, block);
15055 if (block->ipdom) {
15056 unipdom_block(block->ipdom, block);
15059 while((entry = block->use)) {
15060 child = entry->member;
15061 unuse_block(block, child);
15062 if (child && (child->vertex != -1)) {
15063 for(edge = child->edges; edge; edge = edge->next) {
15068 while((entry = block->idominates)) {
15069 child = entry->member;
15070 unidom_block(block, child);
15071 if (child && (child->vertex != -1)) {
15075 while((entry = block->domfrontier)) {
15076 child = entry->member;
15077 undomf_block(block, child);
15079 while((entry = block->ipdominates)) {
15080 child = entry->member;
15081 unipdom_block(block, child);
15082 if (child && (child->vertex != -1)) {
15086 while((entry = block->ipdomfrontier)) {
15087 child = entry->member;
15088 unipdomf_block(block, child);
15090 if (block->users != 0) {
15091 internal_error(state, 0, "block still has users");
15093 while((edge = block->edges)) {
15094 child = edge->member;
15095 remove_block_edge(block, child);
15097 if (child && (child->vertex != -1)) {
15098 free_basic_block(state, child);
15101 memset(block, -1, sizeof(*block));
15105 static void free_basic_blocks(struct compile_state *state,
15106 struct basic_blocks *bb)
15108 struct triple *first, *ins;
15109 free_basic_block(state, bb->first_block);
15110 bb->last_vertex = 0;
15111 bb->first_block = bb->last_block = 0;
15115 if (triple_stores_block(state, ins)) {
15119 } while(ins != first);
15123 static struct block *basic_block(struct compile_state *state,
15124 struct basic_blocks *bb, struct triple *first)
15126 struct block *block;
15127 struct triple *ptr;
15128 if (!triple_is_label(state, first)) {
15129 internal_error(state, first, "block does not start with a label");
15131 /* See if this basic block has already been setup */
15132 if (first->u.block != 0) {
15133 return first->u.block;
15135 /* Allocate another basic block structure */
15136 bb->last_vertex += 1;
15137 block = xcmalloc(sizeof(*block), "block");
15138 block->first = block->last = first;
15139 block->vertex = bb->last_vertex;
15142 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) {
15146 /* If ptr->u is not used remember where the baic block is */
15147 if (triple_stores_block(state, ptr)) {
15148 ptr->u.block = block;
15150 if (triple_is_branch(state, ptr)) {
15154 } while (ptr != bb->first);
15155 if ((ptr == bb->first) ||
15156 ((ptr->next == bb->first) && (
15157 triple_is_end(state, ptr) ||
15158 triple_is_ret(state, ptr))))
15160 /* The block has no outflowing edges */
15162 else if (triple_is_label(state, ptr)) {
15163 struct block *next;
15164 next = basic_block(state, bb, ptr);
15165 add_block_edge(block, next, 0);
15166 use_block(next, block);
15168 else if (triple_is_branch(state, ptr)) {
15169 struct triple **expr, *first;
15170 struct block *child;
15171 /* Find the branch targets.
15172 * I special case the first branch as that magically
15173 * avoids some difficult cases for the register allocator.
15175 expr = triple_edge_targ(state, ptr, 0);
15177 internal_error(state, ptr, "branch without targets");
15180 expr = triple_edge_targ(state, ptr, expr);
15181 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15182 if (!*expr) continue;
15183 child = basic_block(state, bb, *expr);
15184 use_block(child, block);
15185 add_block_edge(block, child, 0);
15188 child = basic_block(state, bb, first);
15189 use_block(child, block);
15190 add_block_edge(block, child, 1);
15192 /* Be certain the return block of a call is
15193 * in a basic block. When it is not find
15194 * start of the block, insert a label if
15195 * necessary and build the basic block.
15196 * Then add a fake edge from the start block
15197 * to the return block of the function.
15199 if (state->functions_joined && triple_is_call(state, ptr)
15200 && !block_of_triple(state, MISC(ptr, 0))) {
15201 struct block *tail;
15202 struct triple *start;
15203 start = triple_to_block_start(state, MISC(ptr, 0));
15204 if (!triple_is_label(state, start)) {
15205 start = pre_triple(state,
15206 start, OP_LABEL, &void_type, 0, 0);
15208 tail = basic_block(state, bb, start);
15209 add_block_edge(child, tail, 0);
15210 use_block(tail, child);
15215 internal_error(state, 0, "Bad basic block split");
15219 struct block_set *edge;
15220 FILE *fp = state->errout;
15221 fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15222 block, block->vertex,
15223 block->first, block->last);
15224 for(edge = block->edges; edge; edge = edge->next) {
15225 fprintf(fp, " %10p [%2d]",
15226 edge->member ? edge->member->first : 0,
15227 edge->member ? edge->member->vertex : -1);
15236 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15237 void (*cb)(struct compile_state *state, struct block *block, void *arg),
15240 struct triple *ptr, *first;
15241 struct block *last_block;
15246 if (triple_stores_block(state, ptr)) {
15247 struct block *block;
15248 block = ptr->u.block;
15249 if (block && (block != last_block)) {
15250 cb(state, block, arg);
15252 last_block = block;
15255 } while(ptr != first);
15258 static void print_block(
15259 struct compile_state *state, struct block *block, void *arg)
15261 struct block_set *user, *edge;
15262 struct triple *ptr;
15265 fprintf(fp, "\nblock: %p (%d) ",
15269 for(edge = block->edges; edge; edge = edge->next) {
15270 fprintf(fp, " %p<-%p",
15272 (edge->member && edge->member->use)?
15273 edge->member->use->member : 0);
15276 if (block->first->op == OP_LABEL) {
15277 fprintf(fp, "%p:\n", block->first);
15279 for(ptr = block->first; ; ) {
15280 display_triple(fp, ptr);
15281 if (ptr == block->last)
15284 if (ptr == block->first) {
15285 internal_error(state, 0, "missing block last?");
15288 fprintf(fp, "users %d: ", block->users);
15289 for(user = block->use; user; user = user->next) {
15290 fprintf(fp, "%p (%d) ",
15292 user->member->vertex);
15294 fprintf(fp,"\n\n");
15298 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15300 fprintf(fp, "--------------- blocks ---------------\n");
15301 walk_blocks(state, &state->bb, print_block, fp);
15303 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15305 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15306 fprintf(fp, "After %s\n", func);
15307 romcc_print_blocks(state, fp);
15308 print_control_flow(state, &state->bb);
15312 static void prune_nonblock_triples(struct compile_state *state,
15313 struct basic_blocks *bb)
15315 struct block *block;
15316 struct triple *first, *ins, *next;
15317 /* Delete the triples not in a basic block */
15323 if (ins->op == OP_LABEL) {
15324 block = ins->u.block;
15327 struct triple_set *use;
15328 for(use = ins->use; use; use = use->next) {
15329 struct block *block;
15330 block = block_of_triple(state, use->member);
15332 internal_error(state, ins, "pruning used ins?");
15335 release_triple(state, ins);
15337 if (block && block->last == ins) {
15341 } while(ins != first);
15344 static void setup_basic_blocks(struct compile_state *state,
15345 struct basic_blocks *bb)
15347 if (!triple_stores_block(state, bb->first)) {
15348 internal_error(state, 0, "ins will not store block?");
15350 /* Initialize the state */
15351 bb->first_block = bb->last_block = 0;
15352 bb->last_vertex = 0;
15353 free_basic_blocks(state, bb);
15355 /* Find the basic blocks */
15356 bb->first_block = basic_block(state, bb, bb->first);
15358 /* Be certain the last instruction of a function, or the
15359 * entire program is in a basic block. When it is not find
15360 * the start of the block, insert a label if necessary and build
15361 * basic block. Then add a fake edge from the start block
15362 * to the final block.
15364 if (!block_of_triple(state, bb->first->prev)) {
15365 struct triple *start;
15366 struct block *tail;
15367 start = triple_to_block_start(state, bb->first->prev);
15368 if (!triple_is_label(state, start)) {
15369 start = pre_triple(state,
15370 start, OP_LABEL, &void_type, 0, 0);
15372 tail = basic_block(state, bb, start);
15373 add_block_edge(bb->first_block, tail, 0);
15374 use_block(tail, bb->first_block);
15377 /* Find the last basic block.
15379 bb->last_block = block_of_triple(state, bb->first->prev);
15381 /* Delete the triples not in a basic block */
15382 prune_nonblock_triples(state, bb);
15385 /* If we are debugging print what I have just done */
15386 if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15387 print_blocks(state, state->dbgout);
15388 print_control_flow(state, bb);
15394 struct sdom_block {
15395 struct block *block;
15396 struct sdom_block *sdominates;
15397 struct sdom_block *sdom_next;
15398 struct sdom_block *sdom;
15399 struct sdom_block *label;
15400 struct sdom_block *parent;
15401 struct sdom_block *ancestor;
15406 static void unsdom_block(struct sdom_block *block)
15408 struct sdom_block **ptr;
15409 if (!block->sdom_next) {
15412 ptr = &block->sdom->sdominates;
15414 if ((*ptr) == block) {
15415 *ptr = block->sdom_next;
15418 ptr = &(*ptr)->sdom_next;
15422 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15424 unsdom_block(block);
15425 block->sdom = sdom;
15426 block->sdom_next = sdom->sdominates;
15427 sdom->sdominates = block;
15432 static int initialize_sdblock(struct sdom_block *sd,
15433 struct block *parent, struct block *block, int vertex)
15435 struct block_set *edge;
15436 if (!block || (sd[block->vertex].block == block)) {
15440 /* Renumber the blocks in a convinient fashion */
15441 block->vertex = vertex;
15442 sd[vertex].block = block;
15443 sd[vertex].sdom = &sd[vertex];
15444 sd[vertex].label = &sd[vertex];
15445 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15446 sd[vertex].ancestor = 0;
15447 sd[vertex].vertex = vertex;
15448 for(edge = block->edges; edge; edge = edge->next) {
15449 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15454 static int initialize_spdblock(
15455 struct compile_state *state, struct sdom_block *sd,
15456 struct block *parent, struct block *block, int vertex)
15458 struct block_set *user;
15459 if (!block || (sd[block->vertex].block == block)) {
15463 /* Renumber the blocks in a convinient fashion */
15464 block->vertex = vertex;
15465 sd[vertex].block = block;
15466 sd[vertex].sdom = &sd[vertex];
15467 sd[vertex].label = &sd[vertex];
15468 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
15469 sd[vertex].ancestor = 0;
15470 sd[vertex].vertex = vertex;
15471 for(user = block->use; user; user = user->next) {
15472 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15477 static int setup_spdblocks(struct compile_state *state,
15478 struct basic_blocks *bb, struct sdom_block *sd)
15480 struct block *block;
15482 /* Setup as many sdpblocks as possible without using fake edges */
15483 vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15485 /* Walk through the graph and find unconnected blocks. Add a
15486 * fake edge from the unconnected blocks to the end of the
15489 block = bb->first_block->last->next->u.block;
15490 for(; block && block != bb->first_block; block = block->last->next->u.block) {
15491 if (sd[block->vertex].block == block) {
15494 #if DEBUG_SDP_BLOCKS
15496 FILE *fp = state->errout;
15497 fprintf(fp, "Adding %d\n", vertex +1);
15500 add_block_edge(block, bb->last_block, 0);
15501 use_block(bb->last_block, block);
15503 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15508 static void compress_ancestors(struct sdom_block *v)
15510 /* This procedure assumes ancestor(v) != 0 */
15511 /* if (ancestor(ancestor(v)) != 0) {
15512 * compress(ancestor(ancestor(v)));
15513 * if (semi(label(ancestor(v))) < semi(label(v))) {
15514 * label(v) = label(ancestor(v));
15516 * ancestor(v) = ancestor(ancestor(v));
15519 if (!v->ancestor) {
15522 if (v->ancestor->ancestor) {
15523 compress_ancestors(v->ancestor->ancestor);
15524 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15525 v->label = v->ancestor->label;
15527 v->ancestor = v->ancestor->ancestor;
15531 static void compute_sdom(struct compile_state *state,
15532 struct basic_blocks *bb, struct sdom_block *sd)
15536 * for each v <= pred(w) {
15538 * if (semi[u] < semi[w] {
15539 * semi[w] = semi[u];
15542 * add w to bucket(vertex(semi[w]));
15543 * LINK(parent(w), w);
15546 * for each v <= bucket(parent(w)) {
15547 * delete v from bucket(parent(w));
15549 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15552 for(i = bb->last_vertex; i >= 2; i--) {
15553 struct sdom_block *v, *parent, *next;
15554 struct block_set *user;
15555 struct block *block;
15556 block = sd[i].block;
15557 parent = sd[i].parent;
15559 for(user = block->use; user; user = user->next) {
15560 struct sdom_block *v, *u;
15561 v = &sd[user->member->vertex];
15562 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15563 if (u->sdom->vertex < sd[i].sdom->vertex) {
15564 sd[i].sdom = u->sdom;
15567 sdom_block(sd[i].sdom, &sd[i]);
15568 sd[i].ancestor = parent;
15570 for(v = parent->sdominates; v; v = next) {
15571 struct sdom_block *u;
15572 next = v->sdom_next;
15574 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15575 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
15576 u->block : parent->block;
15581 static void compute_spdom(struct compile_state *state,
15582 struct basic_blocks *bb, struct sdom_block *sd)
15586 * for each v <= pred(w) {
15588 * if (semi[u] < semi[w] {
15589 * semi[w] = semi[u];
15592 * add w to bucket(vertex(semi[w]));
15593 * LINK(parent(w), w);
15596 * for each v <= bucket(parent(w)) {
15597 * delete v from bucket(parent(w));
15599 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15602 for(i = bb->last_vertex; i >= 2; i--) {
15603 struct sdom_block *u, *v, *parent, *next;
15604 struct block_set *edge;
15605 struct block *block;
15606 block = sd[i].block;
15607 parent = sd[i].parent;
15609 for(edge = block->edges; edge; edge = edge->next) {
15610 v = &sd[edge->member->vertex];
15611 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15612 if (u->sdom->vertex < sd[i].sdom->vertex) {
15613 sd[i].sdom = u->sdom;
15616 sdom_block(sd[i].sdom, &sd[i]);
15617 sd[i].ancestor = parent;
15619 for(v = parent->sdominates; v; v = next) {
15620 struct sdom_block *u;
15621 next = v->sdom_next;
15623 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15624 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
15625 u->block : parent->block;
15630 static void compute_idom(struct compile_state *state,
15631 struct basic_blocks *bb, struct sdom_block *sd)
15634 for(i = 2; i <= bb->last_vertex; i++) {
15635 struct block *block;
15636 block = sd[i].block;
15637 if (block->idom->vertex != sd[i].sdom->vertex) {
15638 block->idom = block->idom->idom;
15640 idom_block(block->idom, block);
15642 sd[1].block->idom = 0;
15645 static void compute_ipdom(struct compile_state *state,
15646 struct basic_blocks *bb, struct sdom_block *sd)
15649 for(i = 2; i <= bb->last_vertex; i++) {
15650 struct block *block;
15651 block = sd[i].block;
15652 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15653 block->ipdom = block->ipdom->ipdom;
15655 ipdom_block(block->ipdom, block);
15657 sd[1].block->ipdom = 0;
15661 * Every vertex of a flowgraph G = (V, E, r) except r has
15662 * a unique immediate dominator.
15663 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15664 * rooted at r, called the dominator tree of G, such that
15665 * v dominates w if and only if v is a proper ancestor of w in
15666 * the dominator tree.
15669 * If v and w are vertices of G such that v <= w,
15670 * than any path from v to w must contain a common ancestor
15673 /* Lemma 2: For any vertex w != r, idom(w) -> w */
15674 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
15675 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
15677 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
15678 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
15681 * Let w != r and let u be a vertex for which sdom(u) is
15682 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15683 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15685 /* Lemma 5: Let vertices v,w satisfy v -> w.
15686 * Then v -> idom(w) or idom(w) -> idom(v)
15689 static void find_immediate_dominators(struct compile_state *state,
15690 struct basic_blocks *bb)
15692 struct sdom_block *sd;
15693 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15694 * vi > w for (1 <= i <= k - 1}
15697 * For any vertex w != r.
15699 * {v|(v,w) <= E and v < w } U
15700 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15703 * Let w != r and let u be a vertex for which sdom(u) is
15704 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
15706 * { sdom(w) if sdom(w) = sdom(u),
15708 * { idom(u) otherwise
15710 /* The algorithm consists of the following 4 steps.
15711 * Step 1. Carry out a depth-first search of the problem graph.
15712 * Number the vertices from 1 to N as they are reached during
15713 * the search. Initialize the variables used in succeeding steps.
15714 * Step 2. Compute the semidominators of all vertices by applying
15715 * theorem 4. Carry out the computation vertex by vertex in
15716 * decreasing order by number.
15717 * Step 3. Implicitly define the immediate dominator of each vertex
15718 * by applying Corollary 1.
15719 * Step 4. Explicitly define the immediate dominator of each vertex,
15720 * carrying out the computation vertex by vertex in increasing order
15723 /* Step 1 initialize the basic block information */
15724 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15725 initialize_sdblock(sd, 0, bb->first_block, 0);
15731 /* Step 2 compute the semidominators */
15732 /* Step 3 implicitly define the immediate dominator of each vertex */
15733 compute_sdom(state, bb, sd);
15734 /* Step 4 explicitly define the immediate dominator of each vertex */
15735 compute_idom(state, bb, sd);
15739 static void find_post_dominators(struct compile_state *state,
15740 struct basic_blocks *bb)
15742 struct sdom_block *sd;
15744 /* Step 1 initialize the basic block information */
15745 sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15747 vertex = setup_spdblocks(state, bb, sd);
15748 if (vertex != bb->last_vertex) {
15749 internal_error(state, 0, "missing %d blocks",
15750 bb->last_vertex - vertex);
15753 /* Step 2 compute the semidominators */
15754 /* Step 3 implicitly define the immediate dominator of each vertex */
15755 compute_spdom(state, bb, sd);
15756 /* Step 4 explicitly define the immediate dominator of each vertex */
15757 compute_ipdom(state, bb, sd);
15763 static void find_block_domf(struct compile_state *state, struct block *block)
15765 struct block *child;
15766 struct block_set *user, *edge;
15767 if (block->domfrontier != 0) {
15768 internal_error(state, block->first, "domfrontier present?");
15770 for(user = block->idominates; user; user = user->next) {
15771 child = user->member;
15772 if (child->idom != block) {
15773 internal_error(state, block->first, "bad idom");
15775 find_block_domf(state, child);
15777 for(edge = block->edges; edge; edge = edge->next) {
15778 if (edge->member->idom != block) {
15779 domf_block(block, edge->member);
15782 for(user = block->idominates; user; user = user->next) {
15783 struct block_set *frontier;
15784 child = user->member;
15785 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15786 if (frontier->member->idom != block) {
15787 domf_block(block, frontier->member);
15793 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15795 struct block *child;
15796 struct block_set *user;
15797 if (block->ipdomfrontier != 0) {
15798 internal_error(state, block->first, "ipdomfrontier present?");
15800 for(user = block->ipdominates; user; user = user->next) {
15801 child = user->member;
15802 if (child->ipdom != block) {
15803 internal_error(state, block->first, "bad ipdom");
15805 find_block_ipdomf(state, child);
15807 for(user = block->use; user; user = user->next) {
15808 if (user->member->ipdom != block) {
15809 ipdomf_block(block, user->member);
15812 for(user = block->ipdominates; user; user = user->next) {
15813 struct block_set *frontier;
15814 child = user->member;
15815 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15816 if (frontier->member->ipdom != block) {
15817 ipdomf_block(block, frontier->member);
15823 static void print_dominated(
15824 struct compile_state *state, struct block *block, void *arg)
15826 struct block_set *user;
15829 fprintf(fp, "%d:", block->vertex);
15830 for(user = block->idominates; user; user = user->next) {
15831 fprintf(fp, " %d", user->member->vertex);
15832 if (user->member->idom != block) {
15833 internal_error(state, user->member->first, "bad idom");
15839 static void print_dominated2(
15840 struct compile_state *state, FILE *fp, int depth, struct block *block)
15842 struct block_set *user;
15843 struct triple *ins;
15844 struct occurance *ptr, *ptr2;
15845 const char *filename1, *filename2;
15846 int equal_filenames;
15848 for(i = 0; i < depth; i++) {
15851 fprintf(fp, "%3d: %p (%p - %p) @",
15852 block->vertex, block, block->first, block->last);
15853 ins = block->first;
15854 while(ins != block->last && (ins->occurance->line == 0)) {
15857 ptr = ins->occurance;
15858 ptr2 = block->last->occurance;
15859 filename1 = ptr->filename? ptr->filename : "";
15860 filename2 = ptr2->filename? ptr2->filename : "";
15861 equal_filenames = (strcmp(filename1, filename2) == 0);
15862 if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15863 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15864 } else if (equal_filenames) {
15865 fprintf(fp, " %s:(%d - %d)",
15866 ptr->filename, ptr->line, ptr2->line);
15868 fprintf(fp, " (%s:%d - %s:%d)",
15869 ptr->filename, ptr->line,
15870 ptr2->filename, ptr2->line);
15873 for(user = block->idominates; user; user = user->next) {
15874 print_dominated2(state, fp, depth + 1, user->member);
15878 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15880 fprintf(fp, "\ndominates\n");
15881 walk_blocks(state, bb, print_dominated, fp);
15882 fprintf(fp, "dominates\n");
15883 print_dominated2(state, fp, 0, bb->first_block);
15887 static int print_frontiers(
15888 struct compile_state *state, struct block *block, int vertex)
15890 struct block_set *user, *edge;
15892 if (!block || (block->vertex != vertex + 1)) {
15897 printf("%d:", block->vertex);
15898 for(user = block->domfrontier; user; user = user->next) {
15899 printf(" %d", user->member->vertex);
15903 for(edge = block->edges; edge; edge = edge->next) {
15904 vertex = print_frontiers(state, edge->member, vertex);
15908 static void print_dominance_frontiers(struct compile_state *state,
15909 struct basic_blocks *bb)
15911 printf("\ndominance frontiers\n");
15912 print_frontiers(state, bb->first_block, 0);
15916 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15918 /* Find the immediate dominators */
15919 find_immediate_dominators(state, bb);
15920 /* Find the dominance frontiers */
15921 find_block_domf(state, bb->first_block);
15922 /* If debuging print the print what I have just found */
15923 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15924 print_dominators(state, state->dbgout, bb);
15925 print_dominance_frontiers(state, bb);
15926 print_control_flow(state, bb);
15931 static void print_ipdominated(
15932 struct compile_state *state, struct block *block, void *arg)
15934 struct block_set *user;
15937 fprintf(fp, "%d:", block->vertex);
15938 for(user = block->ipdominates; user; user = user->next) {
15939 fprintf(fp, " %d", user->member->vertex);
15940 if (user->member->ipdom != block) {
15941 internal_error(state, user->member->first, "bad ipdom");
15947 static void print_ipdominators(struct compile_state *state, FILE *fp,
15948 struct basic_blocks *bb)
15950 fprintf(fp, "\nipdominates\n");
15951 walk_blocks(state, bb, print_ipdominated, fp);
15954 static int print_pfrontiers(
15955 struct compile_state *state, struct block *block, int vertex)
15957 struct block_set *user;
15959 if (!block || (block->vertex != vertex + 1)) {
15964 printf("%d:", block->vertex);
15965 for(user = block->ipdomfrontier; user; user = user->next) {
15966 printf(" %d", user->member->vertex);
15969 for(user = block->use; user; user = user->next) {
15970 vertex = print_pfrontiers(state, user->member, vertex);
15974 static void print_ipdominance_frontiers(struct compile_state *state,
15975 struct basic_blocks *bb)
15977 printf("\nipdominance frontiers\n");
15978 print_pfrontiers(state, bb->last_block, 0);
15982 static void analyze_ipdominators(struct compile_state *state,
15983 struct basic_blocks *bb)
15985 /* Find the post dominators */
15986 find_post_dominators(state, bb);
15987 /* Find the control dependencies (post dominance frontiers) */
15988 find_block_ipdomf(state, bb->last_block);
15989 /* If debuging print the print what I have just found */
15990 if (state->compiler->debug & DEBUG_RDOMINATORS) {
15991 print_ipdominators(state, state->dbgout, bb);
15992 print_ipdominance_frontiers(state, bb);
15993 print_control_flow(state, bb);
15997 static int bdominates(struct compile_state *state,
15998 struct block *dom, struct block *sub)
16000 while(sub && (sub != dom)) {
16006 static int tdominates(struct compile_state *state,
16007 struct triple *dom, struct triple *sub)
16009 struct block *bdom, *bsub;
16011 bdom = block_of_triple(state, dom);
16012 bsub = block_of_triple(state, sub);
16013 if (bdom != bsub) {
16014 result = bdominates(state, bdom, bsub);
16017 struct triple *ins;
16019 while((ins != bsub->first) && (ins != dom)) {
16022 result = (ins == dom);
16027 static void analyze_basic_blocks(
16028 struct compile_state *state, struct basic_blocks *bb)
16030 setup_basic_blocks(state, bb);
16031 analyze_idominators(state, bb);
16032 analyze_ipdominators(state, bb);
16035 static void insert_phi_operations(struct compile_state *state)
16038 struct triple *first;
16039 int *has_already, *work;
16040 struct block *work_list, **work_list_tail;
16042 struct triple *var, *vnext;
16044 size = sizeof(int) * (state->bb.last_vertex + 1);
16045 has_already = xcmalloc(size, "has_already");
16046 work = xcmalloc(size, "work");
16049 first = state->first;
16050 for(var = first->next; var != first ; var = vnext) {
16051 struct block *block;
16052 struct triple_set *user, *unext;
16055 if (!triple_is_auto_var(state, var) || !var->use) {
16061 work_list_tail = &work_list;
16062 for(user = var->use; user; user = unext) {
16063 unext = user->next;
16064 if (MISC(var, 0) == user->member) {
16067 if (user->member->op == OP_READ) {
16070 if (user->member->op != OP_WRITE) {
16071 internal_error(state, user->member,
16072 "bad variable access");
16074 block = user->member->u.block;
16076 warning(state, user->member, "dead code");
16077 release_triple(state, user->member);
16080 if (work[block->vertex] >= iter) {
16083 work[block->vertex] = iter;
16084 *work_list_tail = block;
16085 block->work_next = 0;
16086 work_list_tail = &block->work_next;
16088 for(block = work_list; block; block = block->work_next) {
16089 struct block_set *df;
16090 for(df = block->domfrontier; df; df = df->next) {
16091 struct triple *phi;
16092 struct block *front;
16094 front = df->member;
16096 if (has_already[front->vertex] >= iter) {
16099 /* Count how many edges flow into this block */
16100 in_edges = front->users;
16101 /* Insert a phi function for this variable */
16102 get_occurance(var->occurance);
16103 phi = alloc_triple(
16104 state, OP_PHI, var->type, -1, in_edges,
16106 phi->u.block = front;
16107 MISC(phi, 0) = var;
16108 use_triple(var, phi);
16110 if (phi->rhs != in_edges) {
16111 internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16112 phi->rhs, in_edges);
16115 /* Insert the phi functions immediately after the label */
16116 insert_triple(state, front->first->next, phi);
16117 if (front->first == front->last) {
16118 front->last = front->first->next;
16120 has_already[front->vertex] = iter;
16121 transform_to_arch_instruction(state, phi);
16123 /* If necessary plan to visit the basic block */
16124 if (work[front->vertex] >= iter) {
16127 work[front->vertex] = iter;
16128 *work_list_tail = front;
16129 front->work_next = 0;
16130 work_list_tail = &front->work_next;
16134 xfree(has_already);
16140 struct triple_set *top;
16144 static int count_auto_vars(struct compile_state *state)
16146 struct triple *first, *ins;
16148 first = state->first;
16151 if (triple_is_auto_var(state, ins)) {
16155 } while(ins != first);
16159 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16161 struct triple *first, *ins;
16163 first = state->first;
16166 if (triple_is_auto_var(state, ins)) {
16168 stacks[auto_vars].orig_id = ins->id;
16169 ins->id = auto_vars;
16172 } while(ins != first);
16175 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16177 struct triple *first, *ins;
16178 first = state->first;
16181 if (triple_is_auto_var(state, ins)) {
16182 ins->id = stacks[ins->id].orig_id;
16185 } while(ins != first);
16188 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16190 struct triple_set *head;
16191 struct triple *top_val;
16193 head = stacks[var->id].top;
16195 top_val = head->member;
16200 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16202 struct triple_set *new;
16203 /* Append new to the head of the list,
16204 * it's the only sensible behavoir for a stack.
16206 new = xcmalloc(sizeof(*new), "triple_set");
16208 new->next = stacks[var->id].top;
16209 stacks[var->id].top = new;
16212 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16214 struct triple_set *set, **ptr;
16215 ptr = &stacks[var->id].top;
16218 if (set->member == oldval) {
16221 /* Only free one occurance from the stack */
16234 static void fixup_block_phi_variables(
16235 struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16237 struct block_set *set;
16238 struct triple *ptr;
16240 if (!parent || !block)
16242 /* Find the edge I am coming in on */
16244 for(set = block->use; set; set = set->next, edge++) {
16245 if (set->member == parent) {
16250 internal_error(state, 0, "phi input is not on a control predecessor");
16252 for(ptr = block->first; ; ptr = ptr->next) {
16253 if (ptr->op == OP_PHI) {
16254 struct triple *var, *val, **slot;
16255 var = MISC(ptr, 0);
16257 internal_error(state, ptr, "no var???");
16259 /* Find the current value of the variable */
16260 val = peek_triple(stacks, var);
16261 if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16262 internal_error(state, val, "bad value in phi");
16264 if (edge >= ptr->rhs) {
16265 internal_error(state, ptr, "edges > phi rhs");
16267 slot = &RHS(ptr, edge);
16268 if ((*slot != 0) && (*slot != val)) {
16269 internal_error(state, ptr, "phi already bound on this edge");
16272 use_triple(val, ptr);
16274 if (ptr == block->last) {
16281 static void rename_block_variables(
16282 struct compile_state *state, struct stack *stacks, struct block *block)
16284 struct block_set *user, *edge;
16285 struct triple *ptr, *next, *last;
16289 last = block->first;
16291 for(ptr = block->first; !done; ptr = next) {
16293 if (ptr == block->last) {
16297 if (ptr->op == OP_READ) {
16298 struct triple *var, *val;
16300 if (!triple_is_auto_var(state, var)) {
16301 internal_error(state, ptr, "read of non auto var!");
16303 unuse_triple(var, ptr);
16304 /* Find the current value of the variable */
16305 val = peek_triple(stacks, var);
16307 /* Let the optimizer at variables that are not initially
16308 * set. But give it a bogus value so things seem to
16309 * work by accident. This is useful for bitfields because
16310 * setting them always involves a read-modify-write.
16312 if (TYPE_ARITHMETIC(ptr->type->type)) {
16313 val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16314 val->u.cval = 0xdeadbeaf;
16316 val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16320 error(state, ptr, "variable used without being set");
16322 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16323 internal_error(state, val, "bad value in read");
16325 propogate_use(state, ptr, val);
16326 release_triple(state, ptr);
16330 if (ptr->op == OP_WRITE) {
16331 struct triple *var, *val, *tval;
16332 var = MISC(ptr, 0);
16333 if (!triple_is_auto_var(state, var)) {
16334 internal_error(state, ptr, "write to non auto var!");
16336 tval = val = RHS(ptr, 0);
16337 if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16338 triple_is_auto_var(state, val)) {
16339 internal_error(state, ptr, "bad value in write");
16341 /* Insert a cast if the types differ */
16342 if (!is_subset_type(ptr->type, val->type)) {
16343 if (val->op == OP_INTCONST) {
16344 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16345 tval->u.cval = val->u.cval;
16348 tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16349 use_triple(val, tval);
16351 transform_to_arch_instruction(state, tval);
16352 unuse_triple(val, ptr);
16353 RHS(ptr, 0) = tval;
16354 use_triple(tval, ptr);
16356 propogate_use(state, ptr, tval);
16357 unuse_triple(var, ptr);
16358 /* Push OP_WRITE ptr->right onto a stack of variable uses */
16359 push_triple(stacks, var, tval);
16361 if (ptr->op == OP_PHI) {
16362 struct triple *var;
16363 var = MISC(ptr, 0);
16364 if (!triple_is_auto_var(state, var)) {
16365 internal_error(state, ptr, "phi references non auto var!");
16367 /* Push OP_PHI onto a stack of variable uses */
16368 push_triple(stacks, var, ptr);
16372 block->last = last;
16374 /* Fixup PHI functions in the cf successors */
16375 for(edge = block->edges; edge; edge = edge->next) {
16376 fixup_block_phi_variables(state, stacks, block, edge->member);
16378 /* rename variables in the dominated nodes */
16379 for(user = block->idominates; user; user = user->next) {
16380 rename_block_variables(state, stacks, user->member);
16382 /* pop the renamed variable stack */
16383 last = block->first;
16385 for(ptr = block->first; !done ; ptr = next) {
16387 if (ptr == block->last) {
16390 if (ptr->op == OP_WRITE) {
16391 struct triple *var;
16392 var = MISC(ptr, 0);
16393 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16394 pop_triple(stacks, var, RHS(ptr, 0));
16395 release_triple(state, ptr);
16398 if (ptr->op == OP_PHI) {
16399 struct triple *var;
16400 var = MISC(ptr, 0);
16401 /* Pop OP_WRITE ptr->right from the stack of variable uses */
16402 pop_triple(stacks, var, ptr);
16406 block->last = last;
16409 static void rename_variables(struct compile_state *state)
16411 struct stack *stacks;
16414 /* Allocate stacks for the Variables */
16415 auto_vars = count_auto_vars(state);
16416 stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16418 /* Give each auto_var a stack */
16419 number_auto_vars(state, stacks);
16421 /* Rename the variables */
16422 rename_block_variables(state, stacks, state->bb.first_block);
16424 /* Remove the stacks from the auto_vars */
16425 restore_auto_vars(state, stacks);
16429 static void prune_block_variables(struct compile_state *state,
16430 struct block *block)
16432 struct block_set *user;
16433 struct triple *next, *ptr;
16437 for(ptr = block->first; !done; ptr = next) {
16438 /* Be extremely careful I am deleting the list
16439 * as I walk trhough it.
16442 if (ptr == block->last) {
16445 if (triple_is_auto_var(state, ptr)) {
16446 struct triple_set *user, *next;
16447 for(user = ptr->use; user; user = next) {
16448 struct triple *use;
16450 use = user->member;
16451 if (MISC(ptr, 0) == user->member) {
16454 if (use->op != OP_PHI) {
16455 internal_error(state, use, "decl still used");
16457 if (MISC(use, 0) != ptr) {
16458 internal_error(state, use, "bad phi use of decl");
16460 unuse_triple(ptr, use);
16463 if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16464 /* Delete the adecl */
16465 release_triple(state, MISC(ptr, 0));
16466 /* And the piece */
16467 release_triple(state, ptr);
16472 for(user = block->idominates; user; user = user->next) {
16473 prune_block_variables(state, user->member);
16477 struct phi_triple {
16478 struct triple *phi;
16483 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16485 struct triple **slot;
16487 if (live[phi->id].alive) {
16490 live[phi->id].alive = 1;
16492 slot = &RHS(phi, 0);
16493 for(i = 0; i < zrhs; i++) {
16494 struct triple *used;
16496 if (used && (used->op == OP_PHI)) {
16497 keep_phi(state, live, used);
16502 static void prune_unused_phis(struct compile_state *state)
16504 struct triple *first, *phi;
16505 struct phi_triple *live;
16508 /* Find the first instruction */
16509 first = state->first;
16511 /* Count how many phi functions I need to process */
16513 for(phi = first->next; phi != first; phi = phi->next) {
16514 if (phi->op == OP_PHI) {
16519 /* Mark them all dead */
16520 live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16522 for(phi = first->next; phi != first; phi = phi->next) {
16523 if (phi->op != OP_PHI) {
16526 live[phis].alive = 0;
16527 live[phis].orig_id = phi->id;
16528 live[phis].phi = phi;
16533 /* Mark phis alive that are used by non phis */
16534 for(i = 0; i < phis; i++) {
16535 struct triple_set *set;
16536 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16537 if (set->member->op != OP_PHI) {
16538 keep_phi(state, live, live[i].phi);
16544 /* Delete the extraneous phis */
16545 for(i = 0; i < phis; i++) {
16546 struct triple **slot;
16548 if (!live[i].alive) {
16549 release_triple(state, live[i].phi);
16553 slot = &RHS(phi, 0);
16555 for(j = 0; j < zrhs; j++) {
16557 struct triple *unknown;
16558 get_occurance(phi->occurance);
16559 unknown = flatten(state, state->global_pool,
16560 alloc_triple(state, OP_UNKNOWNVAL,
16561 phi->type, 0, 0, phi->occurance));
16563 use_triple(unknown, phi);
16564 transform_to_arch_instruction(state, unknown);
16566 warning(state, phi, "variable not set at index %d on all paths to use", j);
16574 static void transform_to_ssa_form(struct compile_state *state)
16576 insert_phi_operations(state);
16577 rename_variables(state);
16579 prune_block_variables(state, state->bb.first_block);
16580 prune_unused_phis(state);
16582 print_blocks(state, __func__, state->dbgout);
16586 static void clear_vertex(
16587 struct compile_state *state, struct block *block, void *arg)
16589 /* Clear the current blocks vertex and the vertex of all
16590 * of the current blocks neighbors in case there are malformed
16591 * blocks with now instructions at this point.
16593 struct block_set *user, *edge;
16595 for(edge = block->edges; edge; edge = edge->next) {
16596 edge->member->vertex = 0;
16598 for(user = block->use; user; user = user->next) {
16599 user->member->vertex = 0;
16603 static void mark_live_block(
16604 struct compile_state *state, struct block *block, int *next_vertex)
16606 /* See if this is a block that has not been marked */
16607 if (block->vertex != 0) {
16610 block->vertex = *next_vertex;
16612 if (triple_is_branch(state, block->last)) {
16613 struct triple **targ;
16614 targ = triple_edge_targ(state, block->last, 0);
16615 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16619 if (!triple_stores_block(state, *targ)) {
16620 internal_error(state, 0, "bad targ");
16622 mark_live_block(state, (*targ)->u.block, next_vertex);
16624 /* Ensure the last block of a function remains alive */
16625 if (triple_is_call(state, block->last)) {
16626 mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16629 else if (block->last->next != state->first) {
16630 struct triple *ins;
16631 ins = block->last->next;
16632 if (!triple_stores_block(state, ins)) {
16633 internal_error(state, 0, "bad block start");
16635 mark_live_block(state, ins->u.block, next_vertex);
16639 static void transform_from_ssa_form(struct compile_state *state)
16641 /* To get out of ssa form we insert moves on the incoming
16642 * edges to blocks containting phi functions.
16644 struct triple *first;
16645 struct triple *phi, *var, *next;
16648 /* Walk the control flow to see which blocks remain alive */
16649 walk_blocks(state, &state->bb, clear_vertex, 0);
16651 mark_live_block(state, state->bb.first_block, &next_vertex);
16653 /* Walk all of the operations to find the phi functions */
16654 first = state->first;
16655 for(phi = first->next; phi != first ; phi = next) {
16656 struct block_set *set;
16657 struct block *block;
16658 struct triple **slot;
16659 struct triple *var;
16660 struct triple_set *use, *use_next;
16661 int edge, writers, readers;
16663 if (phi->op != OP_PHI) {
16667 block = phi->u.block;
16668 slot = &RHS(phi, 0);
16670 /* If this phi is in a dead block just forget it */
16671 if (block->vertex == 0) {
16672 release_triple(state, phi);
16676 /* Forget uses from code in dead blocks */
16677 for(use = phi->use; use; use = use_next) {
16678 struct block *ublock;
16679 struct triple **expr;
16680 use_next = use->next;
16681 ublock = block_of_triple(state, use->member);
16682 if ((use->member == phi) || (ublock->vertex != 0)) {
16685 expr = triple_rhs(state, use->member, 0);
16686 for(; expr; expr = triple_rhs(state, use->member, expr)) {
16687 if (*expr == phi) {
16691 unuse_triple(phi, use->member);
16693 /* A variable to replace the phi function */
16694 if (registers_of(state, phi->type) != 1) {
16695 internal_error(state, phi, "phi->type does not fit in a single register!");
16697 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16698 var = var->next; /* point at the var */
16700 /* Replaces use of phi with var */
16701 propogate_use(state, phi, var);
16703 /* Count the readers */
16705 for(use = var->use; use; use = use->next) {
16706 if (use->member != MISC(var, 0)) {
16711 /* Walk all of the incoming edges/blocks and insert moves.
16714 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16715 struct block *eblock, *vblock;
16716 struct triple *move;
16717 struct triple *val, *base;
16718 eblock = set->member;
16721 unuse_triple(val, phi);
16722 vblock = block_of_triple(state, val);
16724 /* If we don't have a value that belongs in an OP_WRITE
16727 if (!val || (val == &unknown_triple) || (val == phi)
16728 || (vblock && (vblock->vertex == 0))) {
16731 /* If the value should never occur error */
16733 internal_error(state, val, "no vblock?");
16737 /* If the value occurs in a dead block see if a replacement
16738 * block can be found.
16740 while(eblock && (eblock->vertex == 0)) {
16741 eblock = eblock->idom;
16743 /* If not continue on with the next value. */
16744 if (!eblock || (eblock->vertex == 0)) {
16748 /* If we have an empty incoming block ignore it. */
16749 if (!eblock->first) {
16750 internal_error(state, 0, "empty block?");
16753 /* Make certain the write is placed in the edge block... */
16754 /* Walk through the edge block backwards to find an
16755 * appropriate location for the OP_WRITE.
16757 for(base = eblock->last; base != eblock->first; base = base->prev) {
16758 struct triple **expr;
16759 if (base->op == OP_PIECE) {
16760 base = MISC(base, 0);
16762 if ((base == var) || (base == val)) {
16765 expr = triple_lhs(state, base, 0);
16766 for(; expr; expr = triple_lhs(state, base, expr)) {
16767 if ((*expr) == val) {
16771 expr = triple_rhs(state, base, 0);
16772 for(; expr; expr = triple_rhs(state, base, expr)) {
16773 if ((*expr) == var) {
16779 if (triple_is_branch(state, base)) {
16780 internal_error(state, base,
16781 "Could not insert write to phi");
16783 move = post_triple(state, base, OP_WRITE, var->type, val, var);
16784 use_triple(val, move);
16785 use_triple(var, move);
16788 if (!writers && readers) {
16789 internal_error(state, var, "no value written to in use phi?");
16791 /* If var is not used free it */
16793 release_triple(state, MISC(var, 0));
16794 release_triple(state, var);
16796 /* Release the phi function */
16797 release_triple(state, phi);
16800 /* Walk all of the operations to find the adecls */
16801 for(var = first->next; var != first ; var = var->next) {
16802 struct triple_set *use, *use_next;
16803 if (!triple_is_auto_var(state, var)) {
16807 /* Walk through all of the rhs uses of var and
16808 * replace them with read of var.
16810 for(use = var->use; use; use = use_next) {
16811 struct triple *read, *user;
16812 struct triple **slot;
16814 use_next = use->next;
16815 user = use->member;
16817 /* Generate a read of var */
16818 read = pre_triple(state, user, OP_READ, var->type, var, 0);
16819 use_triple(var, read);
16821 /* Find the rhs uses and see if they need to be replaced */
16824 slot = &RHS(user, 0);
16825 for(i = 0; i < zrhs; i++) {
16826 if (slot[i] == var) {
16831 /* If we did use it cleanup the uses */
16833 unuse_triple(var, user);
16834 use_triple(read, user);
16836 /* If we didn't use it release the extra triple */
16838 release_triple(state, read);
16844 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16845 FILE *fp = state->dbgout; \
16846 fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16849 static void rebuild_ssa_form(struct compile_state *state)
16852 transform_from_ssa_form(state);
16854 state->bb.first = state->first;
16855 free_basic_blocks(state, &state->bb);
16856 analyze_basic_blocks(state, &state->bb);
16858 insert_phi_operations(state);
16860 rename_variables(state);
16863 prune_block_variables(state, state->bb.first_block);
16865 prune_unused_phis(state);
16871 * Register conflict resolution
16872 * =========================================================
16875 static struct reg_info find_def_color(
16876 struct compile_state *state, struct triple *def)
16878 struct triple_set *set;
16879 struct reg_info info;
16880 info.reg = REG_UNSET;
16882 if (!triple_is_def(state, def)) {
16885 info = arch_reg_lhs(state, def, 0);
16886 if (info.reg >= MAX_REGISTERS) {
16887 info.reg = REG_UNSET;
16889 for(set = def->use; set; set = set->next) {
16890 struct reg_info tinfo;
16892 i = find_rhs_use(state, set->member, def);
16896 tinfo = arch_reg_rhs(state, set->member, i);
16897 if (tinfo.reg >= MAX_REGISTERS) {
16898 tinfo.reg = REG_UNSET;
16900 if ((tinfo.reg != REG_UNSET) &&
16901 (info.reg != REG_UNSET) &&
16902 (tinfo.reg != info.reg)) {
16903 internal_error(state, def, "register conflict");
16905 if ((info.regcm & tinfo.regcm) == 0) {
16906 internal_error(state, def, "regcm conflict %x & %x == 0",
16907 info.regcm, tinfo.regcm);
16909 if (info.reg == REG_UNSET) {
16910 info.reg = tinfo.reg;
16912 info.regcm &= tinfo.regcm;
16914 if (info.reg >= MAX_REGISTERS) {
16915 internal_error(state, def, "register out of range");
16920 static struct reg_info find_lhs_pre_color(
16921 struct compile_state *state, struct triple *ins, int index)
16923 struct reg_info info;
16927 if (!zlhs && triple_is_def(state, ins)) {
16930 if (index >= zlhs) {
16931 internal_error(state, ins, "Bad lhs %d", index);
16933 info = arch_reg_lhs(state, ins, index);
16934 for(i = 0; i < zrhs; i++) {
16935 struct reg_info rinfo;
16936 rinfo = arch_reg_rhs(state, ins, i);
16937 if ((info.reg == rinfo.reg) &&
16938 (rinfo.reg >= MAX_REGISTERS)) {
16939 struct reg_info tinfo;
16940 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
16941 info.reg = tinfo.reg;
16942 info.regcm &= tinfo.regcm;
16946 if (info.reg >= MAX_REGISTERS) {
16947 info.reg = REG_UNSET;
16952 static struct reg_info find_rhs_post_color(
16953 struct compile_state *state, struct triple *ins, int index);
16955 static struct reg_info find_lhs_post_color(
16956 struct compile_state *state, struct triple *ins, int index)
16958 struct triple_set *set;
16959 struct reg_info info;
16960 struct triple *lhs;
16961 #if DEBUG_TRIPLE_COLOR
16962 fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
16965 if ((index == 0) && triple_is_def(state, ins)) {
16968 else if (index < ins->lhs) {
16969 lhs = LHS(ins, index);
16972 internal_error(state, ins, "Bad lhs %d", index);
16975 info = arch_reg_lhs(state, ins, index);
16976 if (info.reg >= MAX_REGISTERS) {
16977 info.reg = REG_UNSET;
16979 for(set = lhs->use; set; set = set->next) {
16980 struct reg_info rinfo;
16981 struct triple *user;
16983 user = set->member;
16985 for(i = 0; i < zrhs; i++) {
16986 if (RHS(user, i) != lhs) {
16989 rinfo = find_rhs_post_color(state, user, i);
16990 if ((info.reg != REG_UNSET) &&
16991 (rinfo.reg != REG_UNSET) &&
16992 (info.reg != rinfo.reg)) {
16993 internal_error(state, ins, "register conflict");
16995 if ((info.regcm & rinfo.regcm) == 0) {
16996 internal_error(state, ins, "regcm conflict %x & %x == 0",
16997 info.regcm, rinfo.regcm);
16999 if (info.reg == REG_UNSET) {
17000 info.reg = rinfo.reg;
17002 info.regcm &= rinfo.regcm;
17005 #if DEBUG_TRIPLE_COLOR
17006 fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17007 ins, index, info.reg, info.regcm);
17012 static struct reg_info find_rhs_post_color(
17013 struct compile_state *state, struct triple *ins, int index)
17015 struct reg_info info, rinfo;
17017 #if DEBUG_TRIPLE_COLOR
17018 fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17021 rinfo = arch_reg_rhs(state, ins, index);
17023 if (!zlhs && triple_is_def(state, ins)) {
17027 if (info.reg >= MAX_REGISTERS) {
17028 info.reg = REG_UNSET;
17030 for(i = 0; i < zlhs; i++) {
17031 struct reg_info linfo;
17032 linfo = arch_reg_lhs(state, ins, i);
17033 if ((linfo.reg == rinfo.reg) &&
17034 (linfo.reg >= MAX_REGISTERS)) {
17035 struct reg_info tinfo;
17036 tinfo = find_lhs_post_color(state, ins, i);
17037 if (tinfo.reg >= MAX_REGISTERS) {
17038 tinfo.reg = REG_UNSET;
17040 info.regcm &= linfo.regcm;
17041 info.regcm &= tinfo.regcm;
17042 if (info.reg != REG_UNSET) {
17043 internal_error(state, ins, "register conflict");
17045 if (info.regcm == 0) {
17046 internal_error(state, ins, "regcm conflict");
17048 info.reg = tinfo.reg;
17051 #if DEBUG_TRIPLE_COLOR
17052 fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17053 ins, index, info.reg, info.regcm);
17058 static struct reg_info find_lhs_color(
17059 struct compile_state *state, struct triple *ins, int index)
17061 struct reg_info pre, post, info;
17062 #if DEBUG_TRIPLE_COLOR
17063 fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17066 pre = find_lhs_pre_color(state, ins, index);
17067 post = find_lhs_post_color(state, ins, index);
17068 if ((pre.reg != post.reg) &&
17069 (pre.reg != REG_UNSET) &&
17070 (post.reg != REG_UNSET)) {
17071 internal_error(state, ins, "register conflict");
17073 info.regcm = pre.regcm & post.regcm;
17074 info.reg = pre.reg;
17075 if (info.reg == REG_UNSET) {
17076 info.reg = post.reg;
17078 #if DEBUG_TRIPLE_COLOR
17079 fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17080 ins, index, info.reg, info.regcm,
17081 pre.reg, pre.regcm, post.reg, post.regcm);
17086 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17088 struct triple_set *entry, *next;
17089 struct triple *out;
17090 struct reg_info info, rinfo;
17092 info = arch_reg_lhs(state, ins, 0);
17093 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17094 use_triple(RHS(out, 0), out);
17095 /* Get the users of ins to use out instead */
17096 for(entry = ins->use; entry; entry = next) {
17098 next = entry->next;
17099 if (entry->member == out) {
17102 i = find_rhs_use(state, entry->member, ins);
17106 rinfo = arch_reg_rhs(state, entry->member, i);
17107 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17110 replace_rhs_use(state, ins, out, entry->member);
17112 transform_to_arch_instruction(state, out);
17116 static struct triple *typed_pre_copy(
17117 struct compile_state *state, struct type *type, struct triple *ins, int index)
17119 /* Carefully insert enough operations so that I can
17120 * enter any operation with a GPR32.
17123 struct triple **expr;
17125 struct reg_info info;
17127 if (ins->op == OP_PHI) {
17128 internal_error(state, ins, "pre_copy on a phi?");
17130 classes = arch_type_to_regcm(state, type);
17131 info = arch_reg_rhs(state, ins, index);
17132 expr = &RHS(ins, index);
17133 if ((info.regcm & classes) == 0) {
17134 FILE *fp = state->errout;
17135 fprintf(fp, "src_type: ");
17136 name_of(fp, ins->type);
17137 fprintf(fp, "\ndst_type: ");
17140 internal_error(state, ins, "pre_copy with no register classes");
17143 if (!equiv_types(type, (*expr)->type)) {
17146 in = pre_triple(state, ins, op, type, *expr, 0);
17147 unuse_triple(*expr, ins);
17149 use_triple(RHS(in, 0), in);
17150 use_triple(in, ins);
17151 transform_to_arch_instruction(state, in);
17155 static struct triple *pre_copy(
17156 struct compile_state *state, struct triple *ins, int index)
17158 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17162 static void insert_copies_to_phi(struct compile_state *state)
17164 /* To get out of ssa form we insert moves on the incoming
17165 * edges to blocks containting phi functions.
17167 struct triple *first;
17168 struct triple *phi;
17170 /* Walk all of the operations to find the phi functions */
17171 first = state->first;
17172 for(phi = first->next; phi != first ; phi = phi->next) {
17173 struct block_set *set;
17174 struct block *block;
17175 struct triple **slot, *copy;
17177 if (phi->op != OP_PHI) {
17180 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17181 block = phi->u.block;
17182 slot = &RHS(phi, 0);
17183 /* Phi's that feed into mandatory live range joins
17184 * cause nasty complications. Insert a copy of
17185 * the phi value so I never have to deal with
17186 * that in the rest of the code.
17188 copy = post_copy(state, phi);
17189 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17190 /* Walk all of the incoming edges/blocks and insert moves.
17192 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17193 struct block *eblock;
17194 struct triple *move;
17195 struct triple *val;
17196 struct triple *ptr;
17197 eblock = set->member;
17204 get_occurance(val->occurance);
17205 move = build_triple(state, OP_COPY, val->type, val, 0,
17207 move->u.block = eblock;
17208 move->id |= TRIPLE_FLAG_PRE_SPLIT;
17209 use_triple(val, move);
17212 unuse_triple(val, phi);
17213 use_triple(move, phi);
17215 /* Walk up the dominator tree until I have found the appropriate block */
17216 while(eblock && !tdominates(state, val, eblock->last)) {
17217 eblock = eblock->idom;
17220 internal_error(state, phi, "Cannot find block dominated by %p",
17224 /* Walk through the block backwards to find
17225 * an appropriate location for the OP_COPY.
17227 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17228 struct triple **expr;
17229 if (ptr->op == OP_PIECE) {
17230 ptr = MISC(ptr, 0);
17232 if ((ptr == phi) || (ptr == val)) {
17235 expr = triple_lhs(state, ptr, 0);
17236 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17237 if ((*expr) == val) {
17241 expr = triple_rhs(state, ptr, 0);
17242 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17243 if ((*expr) == phi) {
17249 if (triple_is_branch(state, ptr)) {
17250 internal_error(state, ptr,
17251 "Could not insert write to phi");
17253 insert_triple(state, after_lhs(state, ptr), move);
17254 if (eblock->last == after_lhs(state, ptr)->prev) {
17255 eblock->last = move;
17257 transform_to_arch_instruction(state, move);
17260 print_blocks(state, __func__, state->dbgout);
17263 struct triple_reg_set;
17267 static int do_triple_set(struct triple_reg_set **head,
17268 struct triple *member, struct triple *new_member)
17270 struct triple_reg_set **ptr, *new;
17275 if ((*ptr)->member == member) {
17278 ptr = &(*ptr)->next;
17280 new = xcmalloc(sizeof(*new), "triple_set");
17281 new->member = member;
17282 new->new = new_member;
17288 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17290 struct triple_reg_set *entry, **ptr;
17294 if (entry->member == member) {
17295 *ptr = entry->next;
17300 ptr = &entry->next;
17305 static int in_triple(struct reg_block *rb, struct triple *in)
17307 return do_triple_set(&rb->in, in, 0);
17309 static void unin_triple(struct reg_block *rb, struct triple *unin)
17311 do_triple_unset(&rb->in, unin);
17314 static int out_triple(struct reg_block *rb, struct triple *out)
17316 return do_triple_set(&rb->out, out, 0);
17318 static void unout_triple(struct reg_block *rb, struct triple *unout)
17320 do_triple_unset(&rb->out, unout);
17323 static int initialize_regblock(struct reg_block *blocks,
17324 struct block *block, int vertex)
17326 struct block_set *user;
17327 if (!block || (blocks[block->vertex].block == block)) {
17331 /* Renumber the blocks in a convinient fashion */
17332 block->vertex = vertex;
17333 blocks[vertex].block = block;
17334 blocks[vertex].vertex = vertex;
17335 for(user = block->use; user; user = user->next) {
17336 vertex = initialize_regblock(blocks, user->member, vertex);
17341 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17343 /* Part to piece is a best attempt and it cannot be correct all by
17344 * itself. If various values are read as different sizes in different
17345 * parts of the code this function cannot work. Or rather it cannot
17346 * work in conjunction with compute_variable_liftimes. As the
17347 * analysis will get confused.
17349 struct triple *base;
17351 if (!is_lvalue(state, ins)) {
17356 while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17357 base = MISC(ins, 0);
17360 reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17363 reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17366 internal_error(state, ins, "unhandled part");
17372 if (reg > base->lhs) {
17373 internal_error(state, base, "part out of range?");
17375 ins = LHS(base, reg);
17380 static int this_def(struct compile_state *state,
17381 struct triple *ins, struct triple *other)
17383 if (ins == other) {
17386 if (ins->op == OP_WRITE) {
17387 ins = part_to_piece(state, MISC(ins, 0));
17389 return ins == other;
17392 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17393 struct reg_block *rb, struct block *suc)
17395 /* Read the conditional input set of a successor block
17396 * (i.e. the input to the phi nodes) and place it in the
17397 * current blocks output set.
17399 struct block_set *set;
17400 struct triple *ptr;
17404 /* Find the edge I am coming in on */
17405 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17406 if (set->member == rb->block) {
17411 internal_error(state, 0, "Not coming on a control edge?");
17413 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17414 struct triple **slot, *expr, *ptr2;
17415 int out_change, done2;
17416 done = (ptr == suc->last);
17417 if (ptr->op != OP_PHI) {
17420 slot = &RHS(ptr, 0);
17422 out_change = out_triple(rb, expr);
17426 /* If we don't define the variable also plast it
17427 * in the current blocks input set.
17429 ptr2 = rb->block->first;
17430 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17431 if (this_def(state, ptr2, expr)) {
17434 done2 = (ptr2 == rb->block->last);
17439 change |= in_triple(rb, expr);
17444 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17445 struct reg_block *rb, struct block *suc)
17447 struct triple_reg_set *in_set;
17450 /* Read the input set of a successor block
17451 * and place it in the current blocks output set.
17453 in_set = blocks[suc->vertex].in;
17454 for(; in_set; in_set = in_set->next) {
17455 int out_change, done;
17456 struct triple *first, *last, *ptr;
17457 out_change = out_triple(rb, in_set->member);
17461 /* If we don't define the variable also place it
17462 * in the current blocks input set.
17464 first = rb->block->first;
17465 last = rb->block->last;
17467 for(ptr = first; !done; ptr = ptr->next) {
17468 if (this_def(state, ptr, in_set->member)) {
17471 done = (ptr == last);
17476 change |= in_triple(rb, in_set->member);
17478 change |= phi_in(state, blocks, rb, suc);
17482 static int use_in(struct compile_state *state, struct reg_block *rb)
17484 /* Find the variables we use but don't define and add
17485 * it to the current blocks input set.
17487 #warning "FIXME is this O(N^2) algorithm bad?"
17488 struct block *block;
17489 struct triple *ptr;
17494 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17495 struct triple **expr;
17496 done = (ptr == block->first);
17497 /* The variable a phi function uses depends on the
17498 * control flow, and is handled in phi_in, not
17501 if (ptr->op == OP_PHI) {
17504 expr = triple_rhs(state, ptr, 0);
17505 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17506 struct triple *rhs, *test;
17508 rhs = part_to_piece(state, *expr);
17513 /* See if rhs is defined in this block.
17514 * A write counts as a definition.
17516 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17517 tdone = (test == block->first);
17518 if (this_def(state, test, rhs)) {
17523 /* If I still have a valid rhs add it to in */
17524 change |= in_triple(rb, rhs);
17530 static struct reg_block *compute_variable_lifetimes(
17531 struct compile_state *state, struct basic_blocks *bb)
17533 struct reg_block *blocks;
17536 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17537 initialize_regblock(blocks, bb->last_block, 0);
17541 for(i = 1; i <= bb->last_vertex; i++) {
17542 struct block_set *edge;
17543 struct reg_block *rb;
17545 /* Add the all successor's input set to in */
17546 for(edge = rb->block->edges; edge; edge = edge->next) {
17547 change |= reg_in(state, blocks, rb, edge->member);
17549 /* Add use to in... */
17550 change |= use_in(state, rb);
17556 static void free_variable_lifetimes(struct compile_state *state,
17557 struct basic_blocks *bb, struct reg_block *blocks)
17560 /* free in_set && out_set on each block */
17561 for(i = 1; i <= bb->last_vertex; i++) {
17562 struct triple_reg_set *entry, *next;
17563 struct reg_block *rb;
17565 for(entry = rb->in; entry ; entry = next) {
17566 next = entry->next;
17567 do_triple_unset(&rb->in, entry->member);
17569 for(entry = rb->out; entry; entry = next) {
17570 next = entry->next;
17571 do_triple_unset(&rb->out, entry->member);
17578 typedef void (*wvl_cb_t)(
17579 struct compile_state *state,
17580 struct reg_block *blocks, struct triple_reg_set *live,
17581 struct reg_block *rb, struct triple *ins, void *arg);
17583 static void walk_variable_lifetimes(struct compile_state *state,
17584 struct basic_blocks *bb, struct reg_block *blocks,
17585 wvl_cb_t cb, void *arg)
17589 for(i = 1; i <= state->bb.last_vertex; i++) {
17590 struct triple_reg_set *live;
17591 struct triple_reg_set *entry, *next;
17592 struct triple *ptr, *prev;
17593 struct reg_block *rb;
17594 struct block *block;
17597 /* Get the blocks */
17601 /* Copy out into live */
17603 for(entry = rb->out; entry; entry = next) {
17604 next = entry->next;
17605 do_triple_set(&live, entry->member, entry->new);
17607 /* Walk through the basic block calculating live */
17608 for(done = 0, ptr = block->last; !done; ptr = prev) {
17609 struct triple **expr;
17612 done = (ptr == block->first);
17614 /* Ensure the current definition is in live */
17615 if (triple_is_def(state, ptr)) {
17616 do_triple_set(&live, ptr, 0);
17619 /* Inform the callback function of what is
17622 cb(state, blocks, live, rb, ptr, arg);
17624 /* Remove the current definition from live */
17625 do_triple_unset(&live, ptr);
17627 /* Add the current uses to live.
17629 * It is safe to skip phi functions because they do
17630 * not have any block local uses, and the block
17631 * output sets already properly account for what
17632 * control flow depedent uses phi functions do have.
17634 if (ptr->op == OP_PHI) {
17637 expr = triple_rhs(state, ptr, 0);
17638 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17639 /* If the triple is not a definition skip it. */
17640 if (!*expr || !triple_is_def(state, *expr)) {
17643 do_triple_set(&live, *expr, 0);
17647 for(entry = live; entry; entry = next) {
17648 next = entry->next;
17649 do_triple_unset(&live, entry->member);
17654 struct print_live_variable_info {
17655 struct reg_block *rb;
17658 static void print_live_variables_block(
17659 struct compile_state *state, struct block *block, void *arg)
17662 struct print_live_variable_info *info = arg;
17663 struct block_set *edge;
17664 FILE *fp = info->fp;
17665 struct reg_block *rb;
17666 struct triple *ptr;
17669 rb = &info->rb[block->vertex];
17671 fprintf(fp, "\nblock: %p (%d),",
17672 block, block->vertex);
17673 for(edge = block->edges; edge; edge = edge->next) {
17674 fprintf(fp, " %p<-%p",
17676 edge->member && edge->member->use?edge->member->use->member : 0);
17680 struct triple_reg_set *in_set;
17681 fprintf(fp, " in:");
17682 for(in_set = rb->in; in_set; in_set = in_set->next) {
17683 fprintf(fp, " %-10p", in_set->member);
17688 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17689 done = (ptr == block->last);
17690 if (ptr->op == OP_PHI) {
17697 for(edge = 0; edge < block->users; edge++) {
17698 fprintf(fp, " in(%d):", edge);
17699 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17700 struct triple **slot;
17701 done = (ptr == block->last);
17702 if (ptr->op != OP_PHI) {
17705 slot = &RHS(ptr, 0);
17706 fprintf(fp, " %-10p", slot[edge]);
17711 if (block->first->op == OP_LABEL) {
17712 fprintf(fp, "%p:\n", block->first);
17714 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17715 done = (ptr == block->last);
17716 display_triple(fp, ptr);
17719 struct triple_reg_set *out_set;
17720 fprintf(fp, " out:");
17721 for(out_set = rb->out; out_set; out_set = out_set->next) {
17722 fprintf(fp, " %-10p", out_set->member);
17729 static void print_live_variables(struct compile_state *state,
17730 struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17732 struct print_live_variable_info info;
17735 fprintf(fp, "\nlive variables by block\n");
17736 walk_blocks(state, bb, print_live_variables_block, &info);
17741 static int count_triples(struct compile_state *state)
17743 struct triple *first, *ins;
17745 first = state->first;
17750 } while (ins != first);
17755 struct dead_triple {
17756 struct triple *triple;
17757 struct dead_triple *work_next;
17758 struct block *block;
17761 #define TRIPLE_FLAG_ALIVE 1
17762 #define TRIPLE_FLAG_FREE 1
17765 static void print_dead_triples(struct compile_state *state,
17766 struct dead_triple *dtriple)
17768 struct triple *first, *ins;
17769 struct dead_triple *dt;
17771 if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17774 fp = state->dbgout;
17775 fprintf(fp, "--------------- dtriples ---------------\n");
17776 first = state->first;
17779 dt = &dtriple[ins->id];
17780 if ((ins->op == OP_LABEL) && (ins->use)) {
17781 fprintf(fp, "\n%p:\n", ins);
17784 (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17785 display_triple(fp, ins);
17786 if (triple_is_branch(state, ins)) {
17790 } while(ins != first);
17795 static void awaken(
17796 struct compile_state *state,
17797 struct dead_triple *dtriple, struct triple **expr,
17798 struct dead_triple ***work_list_tail)
17800 struct triple *triple;
17801 struct dead_triple *dt;
17809 if (triple->id <= 0) {
17810 internal_error(state, triple, "bad triple id: %d",
17813 if (triple->op == OP_NOOP) {
17814 internal_error(state, triple, "awakening noop?");
17817 dt = &dtriple[triple->id];
17818 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17819 dt->flags |= TRIPLE_FLAG_ALIVE;
17820 if (!dt->work_next) {
17821 **work_list_tail = dt;
17822 *work_list_tail = &dt->work_next;
17827 static void eliminate_inefectual_code(struct compile_state *state)
17829 struct block *block;
17830 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17832 struct triple *first, *final, *ins;
17834 if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17838 /* Setup the work list */
17840 work_list_tail = &work_list;
17842 first = state->first;
17843 final = state->first->prev;
17845 /* Count how many triples I have */
17846 triples = count_triples(state);
17848 /* Now put then in an array and mark all of the triples dead */
17849 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17855 dtriple[i].triple = ins;
17856 dtriple[i].block = block_of_triple(state, ins);
17857 dtriple[i].flags = 0;
17858 dtriple[i].old_id = ins->id;
17860 /* See if it is an operation we always keep */
17861 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17862 awaken(state, dtriple, &ins, &work_list_tail);
17866 } while(ins != first);
17868 struct block *block;
17869 struct dead_triple *dt;
17870 struct block_set *user;
17871 struct triple **expr;
17873 work_list = dt->work_next;
17875 work_list_tail = &work_list;
17877 /* Make certain the block the current instruction is in lives */
17878 block = block_of_triple(state, dt->triple);
17879 awaken(state, dtriple, &block->first, &work_list_tail);
17880 if (triple_is_branch(state, block->last)) {
17881 awaken(state, dtriple, &block->last, &work_list_tail);
17883 awaken(state, dtriple, &block->last->next, &work_list_tail);
17886 /* Wake up the data depencencies of this triple */
17889 expr = triple_rhs(state, dt->triple, expr);
17890 awaken(state, dtriple, expr, &work_list_tail);
17893 expr = triple_lhs(state, dt->triple, expr);
17894 awaken(state, dtriple, expr, &work_list_tail);
17897 expr = triple_misc(state, dt->triple, expr);
17898 awaken(state, dtriple, expr, &work_list_tail);
17900 /* Wake up the forward control dependencies */
17902 expr = triple_targ(state, dt->triple, expr);
17903 awaken(state, dtriple, expr, &work_list_tail);
17905 /* Wake up the reverse control dependencies of this triple */
17906 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17907 struct triple *last;
17908 last = user->member->last;
17909 while((last->op == OP_NOOP) && (last != user->member->first)) {
17910 internal_warning(state, last, "awakening noop?");
17913 awaken(state, dtriple, &last, &work_list_tail);
17916 print_dead_triples(state, dtriple);
17917 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
17918 if ((dt->triple->op == OP_NOOP) &&
17919 (dt->flags & TRIPLE_FLAG_ALIVE)) {
17920 internal_error(state, dt->triple, "noop effective?");
17922 dt->triple->id = dt->old_id; /* Restore the color */
17923 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17924 release_triple(state, dt->triple);
17929 rebuild_ssa_form(state);
17931 print_blocks(state, __func__, state->dbgout);
17935 static void insert_mandatory_copies(struct compile_state *state)
17937 struct triple *ins, *first;
17939 /* The object is with a minimum of inserted copies,
17940 * to resolve in fundamental register conflicts between
17941 * register value producers and consumers.
17942 * Theoretically we may be greater than minimal when we
17943 * are inserting copies before instructions but that
17944 * case should be rare.
17946 first = state->first;
17949 struct triple_set *entry, *next;
17950 struct triple *tmp;
17951 struct reg_info info;
17952 unsigned reg, regcm;
17953 int do_post_copy, do_pre_copy;
17955 if (!triple_is_def(state, ins)) {
17958 /* Find the architecture specific color information */
17959 info = find_lhs_pre_color(state, ins, 0);
17960 if (info.reg >= MAX_REGISTERS) {
17961 info.reg = REG_UNSET;
17965 regcm = arch_type_to_regcm(state, ins->type);
17966 do_post_copy = do_pre_copy = 0;
17968 /* Walk through the uses of ins and check for conflicts */
17969 for(entry = ins->use; entry; entry = next) {
17970 struct reg_info rinfo;
17972 next = entry->next;
17973 i = find_rhs_use(state, entry->member, ins);
17978 /* Find the users color requirements */
17979 rinfo = arch_reg_rhs(state, entry->member, i);
17980 if (rinfo.reg >= MAX_REGISTERS) {
17981 rinfo.reg = REG_UNSET;
17984 /* See if I need a pre_copy */
17985 if (rinfo.reg != REG_UNSET) {
17986 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
17991 regcm &= rinfo.regcm;
17992 regcm = arch_regcm_normalize(state, regcm);
17996 /* Always use pre_copies for constants.
17997 * They do not take up any registers until a
17998 * copy places them in one.
18000 if ((info.reg == REG_UNNEEDED) &&
18001 (rinfo.reg != REG_UNNEEDED)) {
18007 (((info.reg != REG_UNSET) &&
18008 (reg != REG_UNSET) &&
18009 (info.reg != reg)) ||
18010 ((info.regcm & regcm) == 0));
18013 regcm = info.regcm;
18014 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18015 for(entry = ins->use; entry; entry = next) {
18016 struct reg_info rinfo;
18018 next = entry->next;
18019 i = find_rhs_use(state, entry->member, ins);
18024 /* Find the users color requirements */
18025 rinfo = arch_reg_rhs(state, entry->member, i);
18026 if (rinfo.reg >= MAX_REGISTERS) {
18027 rinfo.reg = REG_UNSET;
18030 /* Now see if it is time to do the pre_copy */
18031 if (rinfo.reg != REG_UNSET) {
18032 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18033 ((regcm & rinfo.regcm) == 0) ||
18034 /* Don't let a mandatory coalesce sneak
18035 * into a operation that is marked to prevent
18038 ((reg != REG_UNNEEDED) &&
18039 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18040 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18043 struct triple *user;
18044 user = entry->member;
18045 if (RHS(user, i) != ins) {
18046 internal_error(state, user, "bad rhs");
18048 tmp = pre_copy(state, user, i);
18049 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18057 if ((regcm & rinfo.regcm) == 0) {
18059 struct triple *user;
18060 user = entry->member;
18061 if (RHS(user, i) != ins) {
18062 internal_error(state, user, "bad rhs");
18064 tmp = pre_copy(state, user, i);
18065 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18071 regcm &= rinfo.regcm;
18074 if (do_post_copy) {
18075 struct reg_info pre, post;
18076 tmp = post_copy(state, ins);
18077 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18078 pre = arch_reg_lhs(state, ins, 0);
18079 post = arch_reg_lhs(state, tmp, 0);
18080 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18081 internal_error(state, tmp, "useless copy");
18086 } while(ins != first);
18088 print_blocks(state, __func__, state->dbgout);
18092 struct live_range_edge;
18093 struct live_range_def;
18094 struct live_range {
18095 struct live_range_edge *edges;
18096 struct live_range_def *defs;
18097 /* Note. The list pointed to by defs is kept in order.
18098 * That is baring splits in the flow control
18099 * defs dominates defs->next wich dominates defs->next->next
18106 struct live_range *group_next, **group_prev;
18109 struct live_range_edge {
18110 struct live_range_edge *next;
18111 struct live_range *node;
18114 struct live_range_def {
18115 struct live_range_def *next;
18116 struct live_range_def *prev;
18117 struct live_range *lr;
18118 struct triple *def;
18122 #define LRE_HASH_SIZE 2048
18124 struct lre_hash *next;
18125 struct live_range *left;
18126 struct live_range *right;
18131 struct lre_hash *hash[LRE_HASH_SIZE];
18132 struct reg_block *blocks;
18133 struct live_range_def *lrd;
18134 struct live_range *lr;
18135 struct live_range *low, **low_tail;
18136 struct live_range *high, **high_tail;
18139 int passes, max_passes;
18143 struct print_interference_block_info {
18144 struct reg_state *rstate;
18148 static void print_interference_block(
18149 struct compile_state *state, struct block *block, void *arg)
18152 struct print_interference_block_info *info = arg;
18153 struct reg_state *rstate = info->rstate;
18154 struct block_set *edge;
18155 FILE *fp = info->fp;
18156 struct reg_block *rb;
18157 struct triple *ptr;
18160 rb = &rstate->blocks[block->vertex];
18162 fprintf(fp, "\nblock: %p (%d),",
18163 block, block->vertex);
18164 for(edge = block->edges; edge; edge = edge->next) {
18165 fprintf(fp, " %p<-%p",
18167 edge->member && edge->member->use?edge->member->use->member : 0);
18171 struct triple_reg_set *in_set;
18172 fprintf(fp, " in:");
18173 for(in_set = rb->in; in_set; in_set = in_set->next) {
18174 fprintf(fp, " %-10p", in_set->member);
18179 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18180 done = (ptr == block->last);
18181 if (ptr->op == OP_PHI) {
18188 for(edge = 0; edge < block->users; edge++) {
18189 fprintf(fp, " in(%d):", edge);
18190 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18191 struct triple **slot;
18192 done = (ptr == block->last);
18193 if (ptr->op != OP_PHI) {
18196 slot = &RHS(ptr, 0);
18197 fprintf(fp, " %-10p", slot[edge]);
18202 if (block->first->op == OP_LABEL) {
18203 fprintf(fp, "%p:\n", block->first);
18205 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18206 struct live_range *lr;
18210 done = (ptr == block->last);
18211 lr = rstate->lrd[ptr->id].lr;
18214 ptr->id = rstate->lrd[id].orig_id;
18215 SET_REG(ptr->id, lr->color);
18216 display_triple(fp, ptr);
18219 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18220 internal_error(state, ptr, "lr has no defs!");
18222 if (info->need_edges) {
18224 struct live_range_def *lrd;
18225 fprintf(fp, " range:");
18228 fprintf(fp, " %-10p", lrd->def);
18230 } while(lrd != lr->defs);
18233 if (lr->edges > 0) {
18234 struct live_range_edge *edge;
18235 fprintf(fp, " edges:");
18236 for(edge = lr->edges; edge; edge = edge->next) {
18237 struct live_range_def *lrd;
18238 lrd = edge->node->defs;
18240 fprintf(fp, " %-10p", lrd->def);
18242 } while(lrd != edge->node->defs);
18248 /* Do a bunch of sanity checks */
18249 valid_ins(state, ptr);
18250 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18251 internal_error(state, ptr, "Invalid triple id: %d",
18256 struct triple_reg_set *out_set;
18257 fprintf(fp, " out:");
18258 for(out_set = rb->out; out_set; out_set = out_set->next) {
18259 fprintf(fp, " %-10p", out_set->member);
18266 static void print_interference_blocks(
18267 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18269 struct print_interference_block_info info;
18270 info.rstate = rstate;
18272 info.need_edges = need_edges;
18273 fprintf(fp, "\nlive variables by block\n");
18274 walk_blocks(state, &state->bb, print_interference_block, &info);
18278 static unsigned regc_max_size(struct compile_state *state, int classes)
18283 for(i = 0; i < MAX_REGC; i++) {
18284 if (classes & (1 << i)) {
18286 size = arch_regc_size(state, i);
18287 if (size > max_size) {
18295 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18297 unsigned equivs[MAX_REG_EQUIVS];
18299 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18300 internal_error(state, 0, "invalid register");
18302 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18303 internal_error(state, 0, "invalid register");
18305 arch_reg_equivs(state, equivs, reg1);
18306 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18307 if (equivs[i] == reg2) {
18314 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18316 unsigned equivs[MAX_REG_EQUIVS];
18318 if (reg == REG_UNNEEDED) {
18321 arch_reg_equivs(state, equivs, reg);
18322 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18323 used[equivs[i]] = 1;
18328 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18330 unsigned equivs[MAX_REG_EQUIVS];
18332 if (reg == REG_UNNEEDED) {
18335 arch_reg_equivs(state, equivs, reg);
18336 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18337 used[equivs[i]] += 1;
18342 static unsigned int hash_live_edge(
18343 struct live_range *left, struct live_range *right)
18345 unsigned int hash, val;
18346 unsigned long lval, rval;
18347 lval = ((unsigned long)left)/sizeof(struct live_range);
18348 rval = ((unsigned long)right)/sizeof(struct live_range);
18353 hash = (hash *263) + val;
18358 hash = (hash *263) + val;
18360 hash = hash & (LRE_HASH_SIZE - 1);
18364 static struct lre_hash **lre_probe(struct reg_state *rstate,
18365 struct live_range *left, struct live_range *right)
18367 struct lre_hash **ptr;
18368 unsigned int index;
18369 /* Ensure left <= right */
18370 if (left > right) {
18371 struct live_range *tmp;
18376 index = hash_live_edge(left, right);
18378 ptr = &rstate->hash[index];
18380 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18383 ptr = &(*ptr)->next;
18388 static int interfere(struct reg_state *rstate,
18389 struct live_range *left, struct live_range *right)
18391 struct lre_hash **ptr;
18392 ptr = lre_probe(rstate, left, right);
18393 return ptr && *ptr;
18396 static void add_live_edge(struct reg_state *rstate,
18397 struct live_range *left, struct live_range *right)
18399 /* FIXME the memory allocation overhead is noticeable here... */
18400 struct lre_hash **ptr, *new_hash;
18401 struct live_range_edge *edge;
18403 if (left == right) {
18406 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18409 /* Ensure left <= right */
18410 if (left > right) {
18411 struct live_range *tmp;
18416 ptr = lre_probe(rstate, left, right);
18421 fprintf(state->errout, "new_live_edge(%p, %p)\n",
18424 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18425 new_hash->next = *ptr;
18426 new_hash->left = left;
18427 new_hash->right = right;
18430 edge = xmalloc(sizeof(*edge), "live_range_edge");
18431 edge->next = left->edges;
18432 edge->node = right;
18433 left->edges = edge;
18436 edge = xmalloc(sizeof(*edge), "live_range_edge");
18437 edge->next = right->edges;
18439 right->edges = edge;
18440 right->degree += 1;
18443 static void remove_live_edge(struct reg_state *rstate,
18444 struct live_range *left, struct live_range *right)
18446 struct live_range_edge *edge, **ptr;
18447 struct lre_hash **hptr, *entry;
18448 hptr = lre_probe(rstate, left, right);
18449 if (!hptr || !*hptr) {
18453 *hptr = entry->next;
18456 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18458 if (edge->node == right) {
18460 memset(edge, 0, sizeof(*edge));
18466 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18468 if (edge->node == left) {
18470 memset(edge, 0, sizeof(*edge));
18478 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18480 struct live_range_edge *edge, *next;
18481 for(edge = range->edges; edge; edge = next) {
18483 remove_live_edge(rstate, range, edge->node);
18487 static void transfer_live_edges(struct reg_state *rstate,
18488 struct live_range *dest, struct live_range *src)
18490 struct live_range_edge *edge, *next;
18491 for(edge = src->edges; edge; edge = next) {
18492 struct live_range *other;
18494 other = edge->node;
18495 remove_live_edge(rstate, src, other);
18496 add_live_edge(rstate, dest, other);
18501 /* Interference graph...
18503 * new(n) --- Return a graph with n nodes but no edges.
18504 * add(g,x,y) --- Return a graph including g with an between x and y
18505 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18506 * x and y in the graph g
18507 * degree(g, x) --- Return the degree of the node x in the graph g
18508 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18510 * Implement with a hash table && a set of adjcency vectors.
18511 * The hash table supports constant time implementations of add and interfere.
18512 * The adjacency vectors support an efficient implementation of neighbors.
18516 * +---------------------------------------------------+
18517 * | +--------------+ |
18519 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
18521 * -- In simplify implment optimistic coloring... (No backtracking)
18522 * -- Implement Rematerialization it is the only form of spilling we can perform
18523 * Essentially this means dropping a constant from a register because
18524 * we can regenerate it later.
18526 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18527 * coalesce at phi points...
18528 * --- Bias coloring if at all possible do the coalesing a compile time.
18533 static void different_colored(
18534 struct compile_state *state, struct reg_state *rstate,
18535 struct triple *parent, struct triple *ins)
18537 struct live_range *lr;
18538 struct triple **expr;
18539 lr = rstate->lrd[ins->id].lr;
18540 expr = triple_rhs(state, ins, 0);
18541 for(;expr; expr = triple_rhs(state, ins, expr)) {
18542 struct live_range *lr2;
18543 if (!*expr || (*expr == parent) || (*expr == ins)) {
18546 lr2 = rstate->lrd[(*expr)->id].lr;
18547 if (lr->color == lr2->color) {
18548 internal_error(state, ins, "live range too big");
18554 static struct live_range *coalesce_ranges(
18555 struct compile_state *state, struct reg_state *rstate,
18556 struct live_range *lr1, struct live_range *lr2)
18558 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18564 if (!lr1->defs || !lr2->defs) {
18565 internal_error(state, 0,
18566 "cannot coalese dead live ranges");
18568 if ((lr1->color == REG_UNNEEDED) ||
18569 (lr2->color == REG_UNNEEDED)) {
18570 internal_error(state, 0,
18571 "cannot coalesce live ranges without a possible color");
18573 if ((lr1->color != lr2->color) &&
18574 (lr1->color != REG_UNSET) &&
18575 (lr2->color != REG_UNSET)) {
18576 internal_error(state, lr1->defs->def,
18577 "cannot coalesce live ranges of different colors");
18579 color = lr1->color;
18580 if (color == REG_UNSET) {
18581 color = lr2->color;
18583 classes = lr1->classes & lr2->classes;
18585 internal_error(state, lr1->defs->def,
18586 "cannot coalesce live ranges with dissimilar register classes");
18588 if (state->compiler->debug & DEBUG_COALESCING) {
18589 FILE *fp = state->errout;
18590 fprintf(fp, "coalescing:");
18593 fprintf(fp, " %p", lrd->def);
18595 } while(lrd != lr1->defs);
18599 fprintf(fp, " %p", lrd->def);
18601 } while(lrd != lr2->defs);
18604 /* If there is a clear dominate live range put it in lr1,
18605 * For purposes of this test phi functions are
18606 * considered dominated by the definitions that feed into
18609 if ((lr1->defs->prev->def->op == OP_PHI) ||
18610 ((lr2->defs->prev->def->op != OP_PHI) &&
18611 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18612 struct live_range *tmp;
18618 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18619 fprintf(state->errout, "lr1 post\n");
18621 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18622 fprintf(state->errout, "lr1 pre\n");
18624 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
18625 fprintf(state->errout, "lr2 post\n");
18627 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18628 fprintf(state->errout, "lr2 pre\n");
18632 fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18639 /* Append lr2 onto lr1 */
18640 #warning "FIXME should this be a merge instead of a splice?"
18641 /* This FIXME item applies to the correctness of live_range_end
18642 * and to the necessity of making multiple passes of coalesce_live_ranges.
18643 * A failure to find some coalesce opportunities in coaleace_live_ranges
18644 * does not impact the correct of the compiler just the efficiency with
18645 * which registers are allocated.
18648 mid1 = lr1->defs->prev;
18650 end = lr2->defs->prev;
18658 /* Fixup the live range in the added live range defs */
18663 } while(lrd != head);
18665 /* Mark lr2 as free. */
18667 lr2->color = REG_UNNEEDED;
18671 internal_error(state, 0, "lr1->defs == 0 ?");
18674 lr1->color = color;
18675 lr1->classes = classes;
18677 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18678 transfer_live_edges(rstate, lr1, lr2);
18683 static struct live_range_def *live_range_head(
18684 struct compile_state *state, struct live_range *lr,
18685 struct live_range_def *last)
18687 struct live_range_def *result;
18692 else if (!tdominates(state, lr->defs->def, last->next->def)) {
18693 result = last->next;
18698 static struct live_range_def *live_range_end(
18699 struct compile_state *state, struct live_range *lr,
18700 struct live_range_def *last)
18702 struct live_range_def *result;
18705 result = lr->defs->prev;
18707 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18708 result = last->prev;
18714 static void initialize_live_ranges(
18715 struct compile_state *state, struct reg_state *rstate)
18717 struct triple *ins, *first;
18718 size_t count, size;
18721 first = state->first;
18722 /* First count how many instructions I have.
18724 count = count_triples(state);
18725 /* Potentially I need one live range definitions for each
18728 rstate->defs = count;
18729 /* Potentially I need one live range for each instruction
18730 * plus an extra for the dummy live range.
18732 rstate->ranges = count + 1;
18733 size = sizeof(rstate->lrd[0]) * rstate->defs;
18734 rstate->lrd = xcmalloc(size, "live_range_def");
18735 size = sizeof(rstate->lr[0]) * rstate->ranges;
18736 rstate->lr = xcmalloc(size, "live_range");
18738 /* Setup the dummy live range */
18739 rstate->lr[0].classes = 0;
18740 rstate->lr[0].color = REG_UNSET;
18741 rstate->lr[0].defs = 0;
18745 /* If the triple is a variable give it a live range */
18746 if (triple_is_def(state, ins)) {
18747 struct reg_info info;
18748 /* Find the architecture specific color information */
18749 info = find_def_color(state, ins);
18751 rstate->lr[i].defs = &rstate->lrd[j];
18752 rstate->lr[i].color = info.reg;
18753 rstate->lr[i].classes = info.regcm;
18754 rstate->lr[i].degree = 0;
18755 rstate->lrd[j].lr = &rstate->lr[i];
18757 /* Otherwise give the triple the dummy live range. */
18759 rstate->lrd[j].lr = &rstate->lr[0];
18762 /* Initalize the live_range_def */
18763 rstate->lrd[j].next = &rstate->lrd[j];
18764 rstate->lrd[j].prev = &rstate->lrd[j];
18765 rstate->lrd[j].def = ins;
18766 rstate->lrd[j].orig_id = ins->id;
18771 } while(ins != first);
18772 rstate->ranges = i;
18774 /* Make a second pass to handle achitecture specific register
18779 int zlhs, zrhs, i, j;
18780 if (ins->id > rstate->defs) {
18781 internal_error(state, ins, "bad id");
18784 /* Walk through the template of ins and coalesce live ranges */
18786 if ((zlhs == 0) && triple_is_def(state, ins)) {
18791 if (state->compiler->debug & DEBUG_COALESCING2) {
18792 fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18796 for(i = 0; i < zlhs; i++) {
18797 struct reg_info linfo;
18798 struct live_range_def *lhs;
18799 linfo = arch_reg_lhs(state, ins, i);
18800 if (linfo.reg < MAX_REGISTERS) {
18803 if (triple_is_def(state, ins)) {
18804 lhs = &rstate->lrd[ins->id];
18806 lhs = &rstate->lrd[LHS(ins, i)->id];
18809 if (state->compiler->debug & DEBUG_COALESCING2) {
18810 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18811 i, lhs, linfo.reg);
18814 for(j = 0; j < zrhs; j++) {
18815 struct reg_info rinfo;
18816 struct live_range_def *rhs;
18817 rinfo = arch_reg_rhs(state, ins, j);
18818 if (rinfo.reg < MAX_REGISTERS) {
18821 rhs = &rstate->lrd[RHS(ins, j)->id];
18823 if (state->compiler->debug & DEBUG_COALESCING2) {
18824 fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18825 j, rhs, rinfo.reg);
18828 if (rinfo.reg == linfo.reg) {
18829 coalesce_ranges(state, rstate,
18835 } while(ins != first);
18838 static void graph_ins(
18839 struct compile_state *state,
18840 struct reg_block *blocks, struct triple_reg_set *live,
18841 struct reg_block *rb, struct triple *ins, void *arg)
18843 struct reg_state *rstate = arg;
18844 struct live_range *def;
18845 struct triple_reg_set *entry;
18847 /* If the triple is not a definition
18848 * we do not have a definition to add to
18849 * the interference graph.
18851 if (!triple_is_def(state, ins)) {
18854 def = rstate->lrd[ins->id].lr;
18856 /* Create an edge between ins and everything that is
18857 * alive, unless the live_range cannot share
18858 * a physical register with ins.
18860 for(entry = live; entry; entry = entry->next) {
18861 struct live_range *lr;
18862 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18863 internal_error(state, 0, "bad entry?");
18865 lr = rstate->lrd[entry->member->id].lr;
18869 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18872 add_live_edge(rstate, def, lr);
18877 static struct live_range *get_verify_live_range(
18878 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18880 struct live_range *lr;
18881 struct live_range_def *lrd;
18883 if ((ins->id < 0) || (ins->id > rstate->defs)) {
18884 internal_error(state, ins, "bad ins?");
18886 lr = rstate->lrd[ins->id].lr;
18890 if (lrd->def == ins) {
18894 } while(lrd != lr->defs);
18896 internal_error(state, ins, "ins not in live range");
18901 static void verify_graph_ins(
18902 struct compile_state *state,
18903 struct reg_block *blocks, struct triple_reg_set *live,
18904 struct reg_block *rb, struct triple *ins, void *arg)
18906 struct reg_state *rstate = arg;
18907 struct triple_reg_set *entry1, *entry2;
18910 /* Compare live against edges and make certain the code is working */
18911 for(entry1 = live; entry1; entry1 = entry1->next) {
18912 struct live_range *lr1;
18913 lr1 = get_verify_live_range(state, rstate, entry1->member);
18914 for(entry2 = live; entry2; entry2 = entry2->next) {
18915 struct live_range *lr2;
18916 struct live_range_edge *edge2;
18919 if (entry2 == entry1) {
18922 lr2 = get_verify_live_range(state, rstate, entry2->member);
18924 internal_error(state, entry2->member,
18925 "live range with 2 values simultaneously alive");
18927 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
18930 if (!interfere(rstate, lr1, lr2)) {
18931 internal_error(state, entry2->member,
18932 "edges don't interfere?");
18937 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
18939 if (edge2->node == lr1) {
18943 if (lr2_degree != lr2->degree) {
18944 internal_error(state, entry2->member,
18945 "computed degree: %d does not match reported degree: %d\n",
18946 lr2_degree, lr2->degree);
18949 internal_error(state, entry2->member, "missing edge");
18957 static void print_interference_ins(
18958 struct compile_state *state,
18959 struct reg_block *blocks, struct triple_reg_set *live,
18960 struct reg_block *rb, struct triple *ins, void *arg)
18962 struct reg_state *rstate = arg;
18963 struct live_range *lr;
18966 lr = rstate->lrd[ins->id].lr;
18968 ins->id = rstate->lrd[id].orig_id;
18969 SET_REG(ins->id, lr->color);
18970 display_triple(state->dbgout, ins);
18974 struct live_range_def *lrd;
18978 printf(" %-10p", lrd->def);
18980 } while(lrd != lr->defs);
18984 struct triple_reg_set *entry;
18986 for(entry = live; entry; entry = entry->next) {
18987 printf(" %-10p", entry->member);
18992 struct live_range_edge *entry;
18994 for(entry = lr->edges; entry; entry = entry->next) {
18995 struct live_range_def *lrd;
18996 lrd = entry->node->defs;
18998 printf(" %-10p", lrd->def);
19000 } while(lrd != entry->node->defs);
19005 if (triple_is_branch(state, ins)) {
19011 static int coalesce_live_ranges(
19012 struct compile_state *state, struct reg_state *rstate)
19014 /* At the point where a value is moved from one
19015 * register to another that value requires two
19016 * registers, thus increasing register pressure.
19017 * Live range coaleescing reduces the register
19018 * pressure by keeping a value in one register
19021 * In the case of a phi function all paths leading
19022 * into it must be allocated to the same register
19023 * otherwise the phi function may not be removed.
19025 * Forcing a value to stay in a single register
19026 * for an extended period of time does have
19027 * limitations when applied to non homogenous
19030 * The two cases I have identified are:
19031 * 1) Two forced register assignments may
19033 * 2) Registers may go unused because they
19034 * are only good for storing the value
19035 * and not manipulating it.
19037 * Because of this I need to split live ranges,
19038 * even outside of the context of coalesced live
19039 * ranges. The need to split live ranges does
19040 * impose some constraints on live range coalescing.
19042 * - Live ranges may not be coalesced across phi
19043 * functions. This creates a 2 headed live
19044 * range that cannot be sanely split.
19046 * - phi functions (coalesced in initialize_live_ranges)
19047 * are handled as pre split live ranges so we will
19048 * never attempt to split them.
19054 for(i = 0; i <= rstate->ranges; i++) {
19055 struct live_range *lr1;
19056 struct live_range_def *lrd1;
19057 lr1 = &rstate->lr[i];
19061 lrd1 = live_range_end(state, lr1, 0);
19062 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19063 struct triple_set *set;
19064 if (lrd1->def->op != OP_COPY) {
19067 /* Skip copies that are the result of a live range split. */
19068 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19071 for(set = lrd1->def->use; set; set = set->next) {
19072 struct live_range_def *lrd2;
19073 struct live_range *lr2, *res;
19075 lrd2 = &rstate->lrd[set->member->id];
19077 /* Don't coalesce with instructions
19078 * that are the result of a live range
19081 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19084 lr2 = rstate->lrd[set->member->id].lr;
19088 if ((lr1->color != lr2->color) &&
19089 (lr1->color != REG_UNSET) &&
19090 (lr2->color != REG_UNSET)) {
19093 if ((lr1->classes & lr2->classes) == 0) {
19097 if (interfere(rstate, lr1, lr2)) {
19101 res = coalesce_ranges(state, rstate, lr1, lr2);
19115 static void fix_coalesce_conflicts(struct compile_state *state,
19116 struct reg_block *blocks, struct triple_reg_set *live,
19117 struct reg_block *rb, struct triple *ins, void *arg)
19119 int *conflicts = arg;
19120 int zlhs, zrhs, i, j;
19122 /* See if we have a mandatory coalesce operation between
19123 * a lhs and a rhs value. If so and the rhs value is also
19124 * alive then this triple needs to be pre copied. Otherwise
19125 * we would have two definitions in the same live range simultaneously
19129 if ((zlhs == 0) && triple_is_def(state, ins)) {
19133 for(i = 0; i < zlhs; i++) {
19134 struct reg_info linfo;
19135 linfo = arch_reg_lhs(state, ins, i);
19136 if (linfo.reg < MAX_REGISTERS) {
19139 for(j = 0; j < zrhs; j++) {
19140 struct reg_info rinfo;
19141 struct triple *rhs;
19142 struct triple_reg_set *set;
19145 rinfo = arch_reg_rhs(state, ins, j);
19146 if (rinfo.reg != linfo.reg) {
19150 for(set = live; set && !found; set = set->next) {
19151 if (set->member == rhs) {
19156 struct triple *copy;
19157 copy = pre_copy(state, ins, j);
19158 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19166 static int correct_coalesce_conflicts(
19167 struct compile_state *state, struct reg_block *blocks)
19171 walk_variable_lifetimes(state, &state->bb, blocks,
19172 fix_coalesce_conflicts, &conflicts);
19176 static void replace_set_use(struct compile_state *state,
19177 struct triple_reg_set *head, struct triple *orig, struct triple *new)
19179 struct triple_reg_set *set;
19180 for(set = head; set; set = set->next) {
19181 if (set->member == orig) {
19187 static void replace_block_use(struct compile_state *state,
19188 struct reg_block *blocks, struct triple *orig, struct triple *new)
19191 #warning "WISHLIST visit just those blocks that need it *"
19192 for(i = 1; i <= state->bb.last_vertex; i++) {
19193 struct reg_block *rb;
19195 replace_set_use(state, rb->in, orig, new);
19196 replace_set_use(state, rb->out, orig, new);
19200 static void color_instructions(struct compile_state *state)
19202 struct triple *ins, *first;
19203 first = state->first;
19206 if (triple_is_def(state, ins)) {
19207 struct reg_info info;
19208 info = find_lhs_color(state, ins, 0);
19209 if (info.reg >= MAX_REGISTERS) {
19210 info.reg = REG_UNSET;
19212 SET_INFO(ins->id, info);
19215 } while(ins != first);
19218 static struct reg_info read_lhs_color(
19219 struct compile_state *state, struct triple *ins, int index)
19221 struct reg_info info;
19222 if ((index == 0) && triple_is_def(state, ins)) {
19223 info.reg = ID_REG(ins->id);
19224 info.regcm = ID_REGCM(ins->id);
19226 else if (index < ins->lhs) {
19227 info = read_lhs_color(state, LHS(ins, index), 0);
19230 internal_error(state, ins, "Bad lhs %d", index);
19231 info.reg = REG_UNSET;
19237 static struct triple *resolve_tangle(
19238 struct compile_state *state, struct triple *tangle)
19240 struct reg_info info, uinfo;
19241 struct triple_set *set, *next;
19242 struct triple *copy;
19244 #warning "WISHLIST recalculate all affected instructions colors"
19245 info = find_lhs_color(state, tangle, 0);
19246 for(set = tangle->use; set; set = next) {
19247 struct triple *user;
19250 user = set->member;
19252 for(i = 0; i < zrhs; i++) {
19253 if (RHS(user, i) != tangle) {
19256 uinfo = find_rhs_post_color(state, user, i);
19257 if (uinfo.reg == info.reg) {
19258 copy = pre_copy(state, user, i);
19259 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19260 SET_INFO(copy->id, uinfo);
19265 uinfo = find_lhs_pre_color(state, tangle, 0);
19266 if (uinfo.reg == info.reg) {
19267 struct reg_info linfo;
19268 copy = post_copy(state, tangle);
19269 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19270 linfo = find_lhs_color(state, copy, 0);
19271 SET_INFO(copy->id, linfo);
19273 info = find_lhs_color(state, tangle, 0);
19274 SET_INFO(tangle->id, info);
19280 static void fix_tangles(struct compile_state *state,
19281 struct reg_block *blocks, struct triple_reg_set *live,
19282 struct reg_block *rb, struct triple *ins, void *arg)
19284 int *tangles = arg;
19285 struct triple *tangle;
19287 char used[MAX_REGISTERS];
19288 struct triple_reg_set *set;
19291 /* Find out which registers have multiple uses at this point */
19292 memset(used, 0, sizeof(used));
19293 for(set = live; set; set = set->next) {
19294 struct reg_info info;
19295 info = read_lhs_color(state, set->member, 0);
19296 if (info.reg == REG_UNSET) {
19299 reg_inc_used(state, used, info.reg);
19302 /* Now find the least dominated definition of a register in
19303 * conflict I have seen so far.
19305 for(set = live; set; set = set->next) {
19306 struct reg_info info;
19307 info = read_lhs_color(state, set->member, 0);
19308 if (used[info.reg] < 2) {
19311 /* Changing copies that feed into phi functions
19314 if (set->member->use &&
19315 (set->member->use->member->op == OP_PHI)) {
19318 if (!tangle || tdominates(state, set->member, tangle)) {
19319 tangle = set->member;
19322 /* If I have found a tangle resolve it */
19324 struct triple *post_copy;
19326 post_copy = resolve_tangle(state, tangle);
19328 replace_block_use(state, blocks, tangle, post_copy);
19330 if (post_copy && (tangle != ins)) {
19331 replace_set_use(state, live, tangle, post_copy);
19338 static int correct_tangles(
19339 struct compile_state *state, struct reg_block *blocks)
19343 color_instructions(state);
19344 walk_variable_lifetimes(state, &state->bb, blocks,
19345 fix_tangles, &tangles);
19350 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19351 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19353 struct triple *find_constrained_def(
19354 struct compile_state *state, struct live_range *range, struct triple *constrained)
19356 struct live_range_def *lrd, *lrd_next;
19357 lrd_next = range->defs;
19359 struct reg_info info;
19363 lrd_next = lrd->next;
19365 regcm = arch_type_to_regcm(state, lrd->def->type);
19366 info = find_lhs_color(state, lrd->def, 0);
19367 regcm = arch_regcm_reg_normalize(state, regcm);
19368 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19369 /* If the 2 register class masks are equal then
19370 * the current register class is not constrained.
19372 if (regcm == info.regcm) {
19376 /* If there is just one use.
19377 * That use cannot accept a larger register class.
19378 * There are no intervening definitions except
19379 * definitions that feed into that use.
19380 * Then a triple is not constrained.
19381 * FIXME handle this case!
19383 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19386 /* Of the constrained live ranges deal with the
19387 * least dominated one first.
19389 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19390 fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19391 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19393 if (!constrained ||
19394 tdominates(state, lrd->def, constrained))
19396 constrained = lrd->def;
19398 } while(lrd_next != range->defs);
19399 return constrained;
19402 static int split_constrained_ranges(
19403 struct compile_state *state, struct reg_state *rstate,
19404 struct live_range *range)
19406 /* Walk through the edges in conflict and our current live
19407 * range, and find definitions that are more severly constrained
19408 * than they type of data they contain require.
19410 * Then pick one of those ranges and relax the constraints.
19412 struct live_range_edge *edge;
19413 struct triple *constrained;
19416 for(edge = range->edges; edge; edge = edge->next) {
19417 constrained = find_constrained_def(state, edge->node, constrained);
19419 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19420 if (!constrained) {
19421 constrained = find_constrained_def(state, range, constrained);
19424 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19425 fprintf(state->errout, "constrained: ");
19426 display_triple(state->errout, constrained);
19429 ids_from_rstate(state, rstate);
19430 cleanup_rstate(state, rstate);
19431 resolve_tangle(state, constrained);
19433 return !!constrained;
19436 static int split_ranges(
19437 struct compile_state *state, struct reg_state *rstate,
19438 char *used, struct live_range *range)
19441 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19442 fprintf(state->errout, "split_ranges %d %s %p\n",
19443 rstate->passes, tops(range->defs->def->op), range->defs->def);
19445 if ((range->color == REG_UNNEEDED) ||
19446 (rstate->passes >= rstate->max_passes)) {
19449 split = split_constrained_ranges(state, rstate, range);
19451 /* Ideally I would split the live range that will not be used
19452 * for the longest period of time in hopes that this will
19453 * (a) allow me to spill a register or
19454 * (b) allow me to place a value in another register.
19456 * So far I don't have a test case for this, the resolving
19457 * of mandatory constraints has solved all of my
19458 * know issues. So I have choosen not to write any
19459 * code until I cat get a better feel for cases where
19460 * it would be useful to have.
19463 #warning "WISHLIST implement live range splitting..."
19465 if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19466 FILE *fp = state->errout;
19467 print_interference_blocks(state, rstate, fp, 0);
19468 print_dominators(state, fp, &state->bb);
19473 static FILE *cgdebug_fp(struct compile_state *state)
19477 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19478 fp = state->errout;
19480 if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19481 fp = state->dbgout;
19486 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19489 fp = cgdebug_fp(state);
19492 va_start(args, fmt);
19493 vfprintf(fp, fmt, args);
19498 static void cgdebug_flush(struct compile_state *state)
19501 fp = cgdebug_fp(state);
19507 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19510 fp = cgdebug_fp(state);
19512 loc(fp, state, ins);
19516 static int select_free_color(struct compile_state *state,
19517 struct reg_state *rstate, struct live_range *range)
19519 struct triple_set *entry;
19520 struct live_range_def *lrd;
19521 struct live_range_def *phi;
19522 struct live_range_edge *edge;
19523 char used[MAX_REGISTERS];
19524 struct triple **expr;
19526 /* Instead of doing just the trivial color select here I try
19527 * a few extra things because a good color selection will help reduce
19531 /* Find the registers currently in use */
19532 memset(used, 0, sizeof(used));
19533 for(edge = range->edges; edge; edge = edge->next) {
19534 if (edge->node->color == REG_UNSET) {
19537 reg_fill_used(state, used, edge->node->color);
19540 if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19543 for(edge = range->edges; edge; edge = edge->next) {
19546 cgdebug_printf(state, "\n%s edges: %d",
19547 tops(range->defs->def->op), i);
19548 cgdebug_loc(state, range->defs->def);
19549 cgdebug_printf(state, "\n");
19550 for(i = 0; i < MAX_REGISTERS; i++) {
19552 cgdebug_printf(state, "used: %s\n",
19558 /* If a color is already assigned see if it will work */
19559 if (range->color != REG_UNSET) {
19560 struct live_range_def *lrd;
19561 if (!used[range->color]) {
19564 for(edge = range->edges; edge; edge = edge->next) {
19565 if (edge->node->color != range->color) {
19568 warning(state, edge->node->defs->def, "edge: ");
19569 lrd = edge->node->defs;
19571 warning(state, lrd->def, " %p %s",
19572 lrd->def, tops(lrd->def->op));
19574 } while(lrd != edge->node->defs);
19577 warning(state, range->defs->def, "def: ");
19579 warning(state, lrd->def, " %p %s",
19580 lrd->def, tops(lrd->def->op));
19582 } while(lrd != range->defs);
19583 internal_error(state, range->defs->def,
19584 "live range with already used color %s",
19585 arch_reg_str(range->color));
19588 /* If I feed into an expression reuse it's color.
19589 * This should help remove copies in the case of 2 register instructions
19590 * and phi functions.
19593 lrd = live_range_end(state, range, 0);
19594 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19595 entry = lrd->def->use;
19596 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19597 struct live_range_def *insd;
19599 insd = &rstate->lrd[entry->member->id];
19600 if (insd->lr->defs == 0) {
19603 if (!phi && (insd->def->op == OP_PHI) &&
19604 !interfere(rstate, range, insd->lr)) {
19607 if (insd->lr->color == REG_UNSET) {
19610 regcm = insd->lr->classes;
19611 if (((regcm & range->classes) == 0) ||
19612 (used[insd->lr->color])) {
19615 if (interfere(rstate, range, insd->lr)) {
19618 range->color = insd->lr->color;
19621 /* If I feed into a phi function reuse it's color or the color
19622 * of something else that feeds into the phi function.
19625 if (phi->lr->color != REG_UNSET) {
19626 if (used[phi->lr->color]) {
19627 range->color = phi->lr->color;
19631 expr = triple_rhs(state, phi->def, 0);
19632 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19633 struct live_range *lr;
19638 lr = rstate->lrd[(*expr)->id].lr;
19639 if (lr->color == REG_UNSET) {
19642 regcm = lr->classes;
19643 if (((regcm & range->classes) == 0) ||
19644 (used[lr->color])) {
19647 if (interfere(rstate, range, lr)) {
19650 range->color = lr->color;
19654 /* If I don't interfere with a rhs node reuse it's color */
19655 lrd = live_range_head(state, range, 0);
19656 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19657 expr = triple_rhs(state, lrd->def, 0);
19658 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19659 struct live_range *lr;
19664 lr = rstate->lrd[(*expr)->id].lr;
19665 if (lr->color == REG_UNSET) {
19668 regcm = lr->classes;
19669 if (((regcm & range->classes) == 0) ||
19670 (used[lr->color])) {
19673 if (interfere(rstate, range, lr)) {
19676 range->color = lr->color;
19680 /* If I have not opportunitically picked a useful color
19681 * pick the first color that is free.
19683 if (range->color == REG_UNSET) {
19685 arch_select_free_register(state, used, range->classes);
19687 if (range->color == REG_UNSET) {
19688 struct live_range_def *lrd;
19690 if (split_ranges(state, rstate, used, range)) {
19693 for(edge = range->edges; edge; edge = edge->next) {
19694 warning(state, edge->node->defs->def, "edge reg %s",
19695 arch_reg_str(edge->node->color));
19696 lrd = edge->node->defs;
19698 warning(state, lrd->def, " %s %p",
19699 tops(lrd->def->op), lrd->def);
19701 } while(lrd != edge->node->defs);
19703 warning(state, range->defs->def, "range: ");
19706 warning(state, lrd->def, " %s %p",
19707 tops(lrd->def->op), lrd->def);
19709 } while(lrd != range->defs);
19711 warning(state, range->defs->def, "classes: %x",
19713 for(i = 0; i < MAX_REGISTERS; i++) {
19715 warning(state, range->defs->def, "used: %s",
19719 error(state, range->defs->def, "too few registers");
19721 range->classes &= arch_reg_regcm(state, range->color);
19722 if ((range->color == REG_UNSET) || (range->classes == 0)) {
19723 internal_error(state, range->defs->def, "select_free_color did not?");
19728 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19731 struct live_range_edge *edge;
19732 struct live_range *range;
19734 cgdebug_printf(state, "Lo: ");
19735 range = rstate->low;
19736 if (*range->group_prev != range) {
19737 internal_error(state, 0, "lo: *prev != range?");
19739 *range->group_prev = range->group_next;
19740 if (range->group_next) {
19741 range->group_next->group_prev = range->group_prev;
19743 if (&range->group_next == rstate->low_tail) {
19744 rstate->low_tail = range->group_prev;
19746 if (rstate->low == range) {
19747 internal_error(state, 0, "low: next != prev?");
19750 else if (rstate->high) {
19751 cgdebug_printf(state, "Hi: ");
19752 range = rstate->high;
19753 if (*range->group_prev != range) {
19754 internal_error(state, 0, "hi: *prev != range?");
19756 *range->group_prev = range->group_next;
19757 if (range->group_next) {
19758 range->group_next->group_prev = range->group_prev;
19760 if (&range->group_next == rstate->high_tail) {
19761 rstate->high_tail = range->group_prev;
19763 if (rstate->high == range) {
19764 internal_error(state, 0, "high: next != prev?");
19770 cgdebug_printf(state, " %d\n", range - rstate->lr);
19771 range->group_prev = 0;
19772 for(edge = range->edges; edge; edge = edge->next) {
19773 struct live_range *node;
19775 /* Move nodes from the high to the low list */
19776 if (node->group_prev && (node->color == REG_UNSET) &&
19777 (node->degree == regc_max_size(state, node->classes))) {
19778 if (*node->group_prev != node) {
19779 internal_error(state, 0, "move: *prev != node?");
19781 *node->group_prev = node->group_next;
19782 if (node->group_next) {
19783 node->group_next->group_prev = node->group_prev;
19785 if (&node->group_next == rstate->high_tail) {
19786 rstate->high_tail = node->group_prev;
19788 cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19789 node->group_prev = rstate->low_tail;
19790 node->group_next = 0;
19791 *rstate->low_tail = node;
19792 rstate->low_tail = &node->group_next;
19793 if (*node->group_prev != node) {
19794 internal_error(state, 0, "move2: *prev != node?");
19799 colored = color_graph(state, rstate);
19801 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19802 cgdebug_loc(state, range->defs->def);
19803 cgdebug_flush(state);
19804 colored = select_free_color(state, rstate, range);
19806 cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19812 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19814 struct live_range *lr;
19815 struct live_range_edge *edge;
19816 struct triple *ins, *first;
19817 char used[MAX_REGISTERS];
19818 first = state->first;
19821 if (triple_is_def(state, ins)) {
19822 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19823 internal_error(state, ins,
19824 "triple without a live range def");
19826 lr = rstate->lrd[ins->id].lr;
19827 if (lr->color == REG_UNSET) {
19828 internal_error(state, ins,
19829 "triple without a color");
19831 /* Find the registers used by the edges */
19832 memset(used, 0, sizeof(used));
19833 for(edge = lr->edges; edge; edge = edge->next) {
19834 if (edge->node->color == REG_UNSET) {
19835 internal_error(state, 0,
19836 "live range without a color");
19838 reg_fill_used(state, used, edge->node->color);
19840 if (used[lr->color]) {
19841 internal_error(state, ins,
19842 "triple with already used color");
19846 } while(ins != first);
19849 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19851 struct live_range_def *lrd;
19852 struct live_range *lr;
19853 struct triple *first, *ins;
19854 first = state->first;
19857 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19858 internal_error(state, ins,
19859 "triple without a live range");
19861 lrd = &rstate->lrd[ins->id];
19863 ins->id = lrd->orig_id;
19864 SET_REG(ins->id, lr->color);
19866 } while (ins != first);
19869 static struct live_range *merge_sort_lr(
19870 struct live_range *first, struct live_range *last)
19872 struct live_range *mid, *join, **join_tail, *pick;
19874 size = (last - first) + 1;
19876 mid = first + size/2;
19877 first = merge_sort_lr(first, mid -1);
19878 mid = merge_sort_lr(mid, last);
19882 /* merge the two lists */
19883 while(first && mid) {
19884 if ((first->degree < mid->degree) ||
19885 ((first->degree == mid->degree) &&
19886 (first->length < mid->length))) {
19888 first = first->group_next;
19890 first->group_prev = 0;
19895 mid = mid->group_next;
19897 mid->group_prev = 0;
19900 pick->group_next = 0;
19901 pick->group_prev = join_tail;
19903 join_tail = &pick->group_next;
19905 /* Splice the remaining list */
19906 pick = (first)? first : mid;
19909 pick->group_prev = join_tail;
19913 if (!first->defs) {
19921 static void ids_from_rstate(struct compile_state *state,
19922 struct reg_state *rstate)
19924 struct triple *ins, *first;
19925 if (!rstate->defs) {
19928 /* Display the graph if desired */
19929 if (state->compiler->debug & DEBUG_INTERFERENCE) {
19930 FILE *fp = state->dbgout;
19931 print_interference_blocks(state, rstate, fp, 0);
19932 print_control_flow(state, &state->bb);
19935 first = state->first;
19939 struct live_range_def *lrd;
19940 lrd = &rstate->lrd[ins->id];
19941 ins->id = lrd->orig_id;
19944 } while(ins != first);
19947 static void cleanup_live_edges(struct reg_state *rstate)
19950 /* Free the edges on each node */
19951 for(i = 1; i <= rstate->ranges; i++) {
19952 remove_live_edges(rstate, &rstate->lr[i]);
19956 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
19958 cleanup_live_edges(rstate);
19959 xfree(rstate->lrd);
19962 /* Free the variable lifetime information */
19963 if (rstate->blocks) {
19964 free_variable_lifetimes(state, &state->bb, rstate->blocks);
19967 rstate->ranges = 0;
19970 rstate->blocks = 0;
19973 static void verify_consistency(struct compile_state *state);
19974 static void allocate_registers(struct compile_state *state)
19976 struct reg_state rstate;
19979 /* Clear out the reg_state */
19980 memset(&rstate, 0, sizeof(rstate));
19981 rstate.max_passes = state->compiler->max_allocation_passes;
19984 struct live_range **point, **next;
19989 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19990 FILE *fp = state->errout;
19991 fprintf(fp, "pass: %d\n", rstate.passes);
19996 ids_from_rstate(state, &rstate);
19998 /* Cleanup the temporary data structures */
19999 cleanup_rstate(state, &rstate);
20001 /* Compute the variable lifetimes */
20002 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20004 /* Fix invalid mandatory live range coalesce conflicts */
20005 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
20007 /* Fix two simultaneous uses of the same register.
20008 * In a few pathlogical cases a partial untangle moves
20009 * the tangle to a part of the graph we won't revisit.
20010 * So we keep looping until we have no more tangle fixes
20014 tangles = correct_tangles(state, rstate.blocks);
20018 print_blocks(state, "resolve_tangles", state->dbgout);
20019 verify_consistency(state);
20021 /* Allocate and initialize the live ranges */
20022 initialize_live_ranges(state, &rstate);
20024 /* Note currently doing coalescing in a loop appears to
20025 * buys me nothing. The code is left this way in case
20026 * there is some value in it. Or if a future bugfix
20027 * yields some benefit.
20030 if (state->compiler->debug & DEBUG_COALESCING) {
20031 fprintf(state->errout, "coalescing\n");
20034 /* Remove any previous live edge calculations */
20035 cleanup_live_edges(&rstate);
20037 /* Compute the interference graph */
20038 walk_variable_lifetimes(
20039 state, &state->bb, rstate.blocks,
20040 graph_ins, &rstate);
20042 /* Display the interference graph if desired */
20043 if (state->compiler->debug & DEBUG_INTERFERENCE) {
20044 print_interference_blocks(state, &rstate, state->dbgout, 1);
20045 printf("\nlive variables by instruction\n");
20046 walk_variable_lifetimes(
20047 state, &state->bb, rstate.blocks,
20048 print_interference_ins, &rstate);
20051 coalesced = coalesce_live_ranges(state, &rstate);
20053 if (state->compiler->debug & DEBUG_COALESCING) {
20054 fprintf(state->errout, "coalesced: %d\n", coalesced);
20056 } while(coalesced);
20058 #if DEBUG_CONSISTENCY > 1
20060 fprintf(state->errout, "verify_graph_ins...\n");
20062 /* Verify the interference graph */
20063 walk_variable_lifetimes(
20064 state, &state->bb, rstate.blocks,
20065 verify_graph_ins, &rstate);
20067 fprintf(state->errout, "verify_graph_ins done\n");
20071 /* Build the groups low and high. But with the nodes
20072 * first sorted by degree order.
20074 rstate.low_tail = &rstate.low;
20075 rstate.high_tail = &rstate.high;
20076 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20078 rstate.high->group_prev = &rstate.high;
20080 for(point = &rstate.high; *point; point = &(*point)->group_next)
20082 rstate.high_tail = point;
20083 /* Walk through the high list and move everything that needs
20086 for(point = &rstate.high; *point; point = next) {
20087 struct live_range *range;
20088 next = &(*point)->group_next;
20091 /* If it has a low degree or it already has a color
20092 * place the node in low.
20094 if ((range->degree < regc_max_size(state, range->classes)) ||
20095 (range->color != REG_UNSET)) {
20096 cgdebug_printf(state, "Lo: %5d degree %5d%s\n",
20097 range - rstate.lr, range->degree,
20098 (range->color != REG_UNSET) ? " (colored)": "");
20099 *range->group_prev = range->group_next;
20100 if (range->group_next) {
20101 range->group_next->group_prev = range->group_prev;
20103 if (&range->group_next == rstate.high_tail) {
20104 rstate.high_tail = range->group_prev;
20106 range->group_prev = rstate.low_tail;
20107 range->group_next = 0;
20108 *rstate.low_tail = range;
20109 rstate.low_tail = &range->group_next;
20113 cgdebug_printf(state, "hi: %5d degree %5d%s\n",
20114 range - rstate.lr, range->degree,
20115 (range->color != REG_UNSET) ? " (colored)": "");
20118 /* Color the live_ranges */
20119 colored = color_graph(state, &rstate);
20121 } while (!colored);
20123 /* Verify the graph was properly colored */
20124 verify_colors(state, &rstate);
20126 /* Move the colors from the graph to the triples */
20127 color_triples(state, &rstate);
20129 /* Cleanup the temporary data structures */
20130 cleanup_rstate(state, &rstate);
20132 /* Display the new graph */
20133 print_blocks(state, __func__, state->dbgout);
20136 /* Sparce Conditional Constant Propogation
20137 * =========================================
20141 struct lattice_node {
20143 struct triple *def;
20144 struct ssa_edge *out;
20145 struct flow_block *fblock;
20146 struct triple *val;
20147 /* lattice high val == def
20148 * lattice const is_const(val)
20149 * lattice low other
20153 struct lattice_node *src;
20154 struct lattice_node *dst;
20155 struct ssa_edge *work_next;
20156 struct ssa_edge *work_prev;
20157 struct ssa_edge *out_next;
20160 struct flow_block *src;
20161 struct flow_block *dst;
20162 struct flow_edge *work_next;
20163 struct flow_edge *work_prev;
20164 struct flow_edge *in_next;
20165 struct flow_edge *out_next;
20168 #define MAX_FLOW_BLOCK_EDGES 3
20169 struct flow_block {
20170 struct block *block;
20171 struct flow_edge *in;
20172 struct flow_edge *out;
20173 struct flow_edge *edges;
20178 struct lattice_node *lattice;
20179 struct ssa_edge *ssa_edges;
20180 struct flow_block *flow_blocks;
20181 struct flow_edge *flow_work_list;
20182 struct ssa_edge *ssa_work_list;
20186 static int is_scc_const(struct compile_state *state, struct triple *ins)
20188 return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20191 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20193 return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20196 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20198 return is_scc_const(state, lnode->val);
20201 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20203 return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20209 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
20210 struct flow_edge *fedge)
20212 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20213 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20215 fedge->src->block?fedge->src->block->last->id: 0,
20216 fedge->dst->block?fedge->dst->block->first->id: 0);
20218 if ((fedge == scc->flow_work_list) ||
20219 (fedge->work_next != fedge) ||
20220 (fedge->work_prev != fedge)) {
20222 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20223 fprintf(state->errout, "dupped fedge: %p\n",
20228 if (!scc->flow_work_list) {
20229 scc->flow_work_list = fedge;
20230 fedge->work_next = fedge->work_prev = fedge;
20233 struct flow_edge *ftail;
20234 ftail = scc->flow_work_list->work_prev;
20235 fedge->work_next = ftail->work_next;
20236 fedge->work_prev = ftail;
20237 fedge->work_next->work_prev = fedge;
20238 fedge->work_prev->work_next = fedge;
20242 static struct flow_edge *scc_next_fedge(
20243 struct compile_state *state, struct scc_state *scc)
20245 struct flow_edge *fedge;
20246 fedge = scc->flow_work_list;
20248 fedge->work_next->work_prev = fedge->work_prev;
20249 fedge->work_prev->work_next = fedge->work_next;
20250 if (fedge->work_next != fedge) {
20251 scc->flow_work_list = fedge->work_next;
20253 scc->flow_work_list = 0;
20255 fedge->work_next = fedge->work_prev = fedge;
20260 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20261 struct ssa_edge *sedge)
20263 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20264 fprintf(state->errout, "adding sedge: %5d (%4d -> %5d)\n",
20265 sedge - scc->ssa_edges,
20266 sedge->src->def->id,
20267 sedge->dst->def->id);
20269 if ((sedge == scc->ssa_work_list) ||
20270 (sedge->work_next != sedge) ||
20271 (sedge->work_prev != sedge)) {
20273 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20274 fprintf(state->errout, "dupped sedge: %5d\n",
20275 sedge - scc->ssa_edges);
20279 if (!scc->ssa_work_list) {
20280 scc->ssa_work_list = sedge;
20281 sedge->work_next = sedge->work_prev = sedge;
20284 struct ssa_edge *stail;
20285 stail = scc->ssa_work_list->work_prev;
20286 sedge->work_next = stail->work_next;
20287 sedge->work_prev = stail;
20288 sedge->work_next->work_prev = sedge;
20289 sedge->work_prev->work_next = sedge;
20293 static struct ssa_edge *scc_next_sedge(
20294 struct compile_state *state, struct scc_state *scc)
20296 struct ssa_edge *sedge;
20297 sedge = scc->ssa_work_list;
20299 sedge->work_next->work_prev = sedge->work_prev;
20300 sedge->work_prev->work_next = sedge->work_next;
20301 if (sedge->work_next != sedge) {
20302 scc->ssa_work_list = sedge->work_next;
20304 scc->ssa_work_list = 0;
20306 sedge->work_next = sedge->work_prev = sedge;
20312 static void initialize_scc_state(
20313 struct compile_state *state, struct scc_state *scc)
20315 int ins_count, ssa_edge_count;
20316 int ins_index, ssa_edge_index, fblock_index;
20317 struct triple *first, *ins;
20318 struct block *block;
20319 struct flow_block *fblock;
20321 memset(scc, 0, sizeof(*scc));
20323 /* Inialize pass zero find out how much memory we need */
20324 first = state->first;
20326 ins_count = ssa_edge_count = 0;
20328 struct triple_set *edge;
20330 for(edge = ins->use; edge; edge = edge->next) {
20334 } while(ins != first);
20335 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20336 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20337 ins_count, ssa_edge_count, state->bb.last_vertex);
20339 scc->ins_count = ins_count;
20341 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20343 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20345 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1),
20348 /* Initialize pass one collect up the nodes */
20351 ins_index = ssa_edge_index = fblock_index = 0;
20354 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20355 block = ins->u.block;
20357 internal_error(state, ins, "label without block");
20360 block->vertex = fblock_index;
20361 fblock = &scc->flow_blocks[fblock_index];
20362 fblock->block = block;
20363 fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20367 struct lattice_node *lnode;
20369 lnode = &scc->lattice[ins_index];
20372 lnode->fblock = fblock;
20373 lnode->val = ins; /* LATTICE HIGH */
20374 if (lnode->val->op == OP_UNKNOWNVAL) {
20375 lnode->val = 0; /* LATTICE LOW by definition */
20377 lnode->old_id = ins->id;
20378 ins->id = ins_index;
20381 } while(ins != first);
20382 /* Initialize pass two collect up the edges */
20388 struct triple_set *edge;
20389 struct ssa_edge **stail;
20390 struct lattice_node *lnode;
20391 lnode = &scc->lattice[ins->id];
20393 stail = &lnode->out;
20394 for(edge = ins->use; edge; edge = edge->next) {
20395 struct ssa_edge *sedge;
20396 ssa_edge_index += 1;
20397 sedge = &scc->ssa_edges[ssa_edge_index];
20399 stail = &sedge->out_next;
20400 sedge->src = lnode;
20401 sedge->dst = &scc->lattice[edge->member->id];
20402 sedge->work_next = sedge->work_prev = sedge;
20403 sedge->out_next = 0;
20406 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20407 struct flow_edge *fedge, **ftail;
20408 struct block_set *bedge;
20409 block = ins->u.block;
20410 fblock = &scc->flow_blocks[block->vertex];
20413 ftail = &fblock->out;
20415 fedge = fblock->edges;
20416 bedge = block->edges;
20417 for(; bedge; bedge = bedge->next, fedge++) {
20418 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20419 if (fedge->dst->block != bedge->member) {
20420 internal_error(state, 0, "block mismatch");
20423 ftail = &fedge->out_next;
20424 fedge->out_next = 0;
20426 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20427 fedge->src = fblock;
20428 fedge->work_next = fedge->work_prev = fedge;
20429 fedge->executable = 0;
20433 } while (ins != first);
20438 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20439 struct flow_edge **ftail;
20440 struct block_set *bedge;
20441 block = ins->u.block;
20442 fblock = &scc->flow_blocks[block->vertex];
20443 ftail = &fblock->in;
20444 for(bedge = block->use; bedge; bedge = bedge->next) {
20445 struct block *src_block;
20446 struct flow_block *sfblock;
20447 struct flow_edge *sfedge;
20448 src_block = bedge->member;
20449 sfblock = &scc->flow_blocks[src_block->vertex];
20450 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20451 if (sfedge->dst == fblock) {
20456 internal_error(state, 0, "edge mismatch");
20459 ftail = &sfedge->in_next;
20460 sfedge->in_next = 0;
20464 } while(ins != first);
20465 /* Setup a dummy block 0 as a node above the start node */
20467 struct flow_block *fblock, *dst;
20468 struct flow_edge *fedge;
20469 fblock = &scc->flow_blocks[0];
20471 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20473 fblock->out = fblock->edges;
20474 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20475 fedge = fblock->edges;
20476 fedge->src = fblock;
20478 fedge->work_next = fedge;
20479 fedge->work_prev = fedge;
20480 fedge->in_next = fedge->dst->in;
20481 fedge->out_next = 0;
20482 fedge->executable = 0;
20483 fedge->dst->in = fedge;
20485 /* Initialize the work lists */
20486 scc->flow_work_list = 0;
20487 scc->ssa_work_list = 0;
20488 scc_add_fedge(state, scc, fedge);
20490 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20491 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20492 ins_index, ssa_edge_index, fblock_index);
20497 static void free_scc_state(
20498 struct compile_state *state, struct scc_state *scc)
20501 for(i = 0; i < state->bb.last_vertex + 1; i++) {
20502 struct flow_block *fblock;
20503 fblock = &scc->flow_blocks[i];
20504 if (fblock->edges) {
20505 xfree(fblock->edges);
20509 xfree(scc->flow_blocks);
20510 xfree(scc->ssa_edges);
20511 xfree(scc->lattice);
20515 static struct lattice_node *triple_to_lattice(
20516 struct compile_state *state, struct scc_state *scc, struct triple *ins)
20518 if (ins->id <= 0) {
20519 internal_error(state, ins, "bad id");
20521 return &scc->lattice[ins->id];
20524 static struct triple *preserve_lval(
20525 struct compile_state *state, struct lattice_node *lnode)
20527 struct triple *old;
20528 /* Preserve the original value */
20530 old = dup_triple(state, lnode->val);
20531 if (lnode->val != lnode->def) {
20541 static int lval_changed(struct compile_state *state,
20542 struct triple *old, struct lattice_node *lnode)
20545 /* See if the lattice value has changed */
20547 if (!old && !lnode->val) {
20551 lnode->val && old &&
20552 (memcmp(lnode->val->param, old->param,
20553 TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20554 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20564 static void scc_debug_lnode(
20565 struct compile_state *state, struct scc_state *scc,
20566 struct lattice_node *lnode, int changed)
20568 if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20569 display_triple_changes(state->errout, lnode->val, lnode->def);
20571 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20572 FILE *fp = state->errout;
20573 struct triple *val, **expr;
20574 val = lnode->val? lnode->val : lnode->def;
20575 fprintf(fp, "%p %s %3d %10s (",
20577 ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20579 tops(lnode->def->op));
20580 expr = triple_rhs(state, lnode->def, 0);
20581 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20583 fprintf(fp, " %d", (*expr)->id);
20586 if (val->op == OP_INTCONST) {
20587 fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20589 fprintf(fp, " ) -> %s %s\n",
20590 (is_lattice_hi(state, lnode)? "hi":
20591 is_lattice_const(state, lnode)? "const" : "lo"),
20592 changed? "changed" : ""
20597 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20598 struct lattice_node *lnode)
20601 struct triple *old, *scratch;
20602 struct triple **dexpr, **vexpr;
20605 /* Store the original value */
20606 old = preserve_lval(state, lnode);
20608 /* Reinitialize the value */
20609 lnode->val = scratch = dup_triple(state, lnode->def);
20610 scratch->id = lnode->old_id;
20611 scratch->next = scratch;
20612 scratch->prev = scratch;
20615 count = TRIPLE_SIZE(scratch);
20616 for(i = 0; i < count; i++) {
20617 dexpr = &lnode->def->param[i];
20618 vexpr = &scratch->param[i];
20620 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20621 (i >= TRIPLE_TARG_OFF(scratch))) &&
20623 struct lattice_node *tmp;
20624 tmp = triple_to_lattice(state, scc, *dexpr);
20625 *vexpr = (tmp->val)? tmp->val : tmp->def;
20628 if (triple_is_branch(state, scratch)) {
20629 scratch->next = lnode->def->next;
20631 /* Recompute the value */
20632 #warning "FIXME see if simplify does anything bad"
20633 /* So far it looks like only the strength reduction
20634 * optimization are things I need to worry about.
20636 simplify(state, scratch);
20637 /* Cleanup my value */
20638 if (scratch->use) {
20639 internal_error(state, lnode->def, "scratch used?");
20641 if ((scratch->prev != scratch) ||
20642 ((scratch->next != scratch) &&
20643 (!triple_is_branch(state, lnode->def) ||
20644 (scratch->next != lnode->def->next)))) {
20645 internal_error(state, lnode->def, "scratch in list?");
20647 /* undo any uses... */
20648 count = TRIPLE_SIZE(scratch);
20649 for(i = 0; i < count; i++) {
20650 vexpr = &scratch->param[i];
20652 unuse_triple(*vexpr, scratch);
20655 if (lnode->val->op == OP_UNKNOWNVAL) {
20656 lnode->val = 0; /* Lattice low by definition */
20658 /* Find the case when I am lattice high */
20660 (lnode->val->op == lnode->def->op) &&
20661 (memcmp(lnode->val->param, lnode->def->param,
20662 count * sizeof(lnode->val->param[0])) == 0) &&
20663 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20664 lnode->val = lnode->def;
20666 /* Only allow lattice high when all of my inputs
20667 * are also lattice high. Occassionally I can
20668 * have constants with a lattice low input, so
20669 * I do not need to check that case.
20671 if (is_lattice_hi(state, lnode)) {
20672 struct lattice_node *tmp;
20674 rhs = lnode->val->rhs;
20675 for(i = 0; i < rhs; i++) {
20676 tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20677 if (!is_lattice_hi(state, tmp)) {
20683 /* Find the cases that are always lattice lo */
20685 triple_is_def(state, lnode->val) &&
20686 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20689 /* See if the lattice value has changed */
20690 changed = lval_changed(state, old, lnode);
20691 /* See if this value should not change */
20692 if ((lnode->val != lnode->def) &&
20693 (( !triple_is_def(state, lnode->def) &&
20694 !triple_is_cbranch(state, lnode->def)) ||
20695 (lnode->def->op == OP_PIECE))) {
20696 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20698 internal_warning(state, lnode->def, "non def changes value?");
20703 /* See if we need to free the scratch value */
20704 if (lnode->val != scratch) {
20712 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20713 struct lattice_node *lnode)
20715 struct lattice_node *cond;
20716 struct flow_edge *left, *right;
20719 /* Update the branch value */
20720 changed = compute_lnode_val(state, scc, lnode);
20721 scc_debug_lnode(state, scc, lnode, changed);
20723 /* This only applies to conditional branches */
20724 if (!triple_is_cbranch(state, lnode->def)) {
20725 internal_error(state, lnode->def, "not a conditional branch");
20728 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20729 struct flow_edge *fedge;
20730 FILE *fp = state->errout;
20731 fprintf(fp, "%s: %d (",
20732 tops(lnode->def->op),
20735 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20736 fprintf(fp, " %d", fedge->dst->block->vertex);
20739 if (lnode->def->rhs > 0) {
20740 fprintf(fp, " <- %d",
20741 RHS(lnode->def, 0)->id);
20745 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20746 for(left = cond->fblock->out; left; left = left->out_next) {
20747 if (left->dst->block->first == lnode->def->next) {
20752 internal_error(state, lnode->def, "Cannot find left branch edge");
20754 for(right = cond->fblock->out; right; right = right->out_next) {
20755 if (right->dst->block->first == TARG(lnode->def, 0)) {
20760 internal_error(state, lnode->def, "Cannot find right branch edge");
20762 /* I should only come here if the controlling expressions value
20763 * has changed, which means it must be either a constant or lo.
20765 if (is_lattice_hi(state, cond)) {
20766 internal_error(state, cond->def, "condition high?");
20769 if (is_lattice_lo(state, cond)) {
20770 scc_add_fedge(state, scc, left);
20771 scc_add_fedge(state, scc, right);
20773 else if (cond->val->u.cval) {
20774 scc_add_fedge(state, scc, right);
20776 scc_add_fedge(state, scc, left);
20782 static void scc_add_sedge_dst(struct compile_state *state,
20783 struct scc_state *scc, struct ssa_edge *sedge)
20785 if (triple_is_cbranch(state, sedge->dst->def)) {
20786 scc_visit_cbranch(state, scc, sedge->dst);
20788 else if (triple_is_def(state, sedge->dst->def)) {
20789 scc_add_sedge(state, scc, sedge);
20793 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
20794 struct lattice_node *lnode)
20796 struct lattice_node *tmp;
20797 struct triple **slot, *old;
20798 struct flow_edge *fedge;
20801 if (lnode->def->op != OP_PHI) {
20802 internal_error(state, lnode->def, "not phi");
20804 /* Store the original value */
20805 old = preserve_lval(state, lnode);
20807 /* default to lattice high */
20808 lnode->val = lnode->def;
20809 slot = &RHS(lnode->def, 0);
20811 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20812 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20813 fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n",
20815 fedge->dst->block->vertex,
20819 if (!fedge->executable) {
20822 if (!slot[index]) {
20823 internal_error(state, lnode->def, "no phi value");
20825 tmp = triple_to_lattice(state, scc, slot[index]);
20826 /* meet(X, lattice low) = lattice low */
20827 if (is_lattice_lo(state, tmp)) {
20830 /* meet(X, lattice high) = X */
20831 else if (is_lattice_hi(state, tmp)) {
20832 lnode->val = lnode->val;
20834 /* meet(lattice high, X) = X */
20835 else if (is_lattice_hi(state, lnode)) {
20836 lnode->val = dup_triple(state, tmp->val);
20837 /* Only change the type if necessary */
20838 if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20839 lnode->val->type = lnode->def->type;
20842 /* meet(const, const) = const or lattice low */
20843 else if (!constants_equal(state, lnode->val, tmp->val)) {
20847 /* meet(lattice low, X) = lattice low */
20848 if (is_lattice_lo(state, lnode)) {
20853 changed = lval_changed(state, old, lnode);
20854 scc_debug_lnode(state, scc, lnode, changed);
20856 /* If the lattice value has changed update the work lists. */
20858 struct ssa_edge *sedge;
20859 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20860 scc_add_sedge_dst(state, scc, sedge);
20866 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20867 struct lattice_node *lnode)
20871 if (!triple_is_def(state, lnode->def)) {
20872 internal_warning(state, lnode->def, "not visiting an expression?");
20874 changed = compute_lnode_val(state, scc, lnode);
20875 scc_debug_lnode(state, scc, lnode, changed);
20878 struct ssa_edge *sedge;
20879 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20880 scc_add_sedge_dst(state, scc, sedge);
20885 static void scc_writeback_values(
20886 struct compile_state *state, struct scc_state *scc)
20888 struct triple *first, *ins;
20889 first = state->first;
20892 struct lattice_node *lnode;
20893 lnode = triple_to_lattice(state, scc, ins);
20894 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20895 if (is_lattice_hi(state, lnode) &&
20896 (lnode->val->op != OP_NOOP))
20898 struct flow_edge *fedge;
20901 for(fedge = lnode->fblock->in;
20902 !executable && fedge; fedge = fedge->in_next) {
20903 executable |= fedge->executable;
20906 internal_warning(state, lnode->def,
20907 "lattice node %d %s->%s still high?",
20909 tops(lnode->def->op),
20910 tops(lnode->val->op));
20916 ins->id = lnode->old_id;
20917 if (lnode->val && (lnode->val != ins)) {
20918 /* See if it something I know how to write back */
20919 switch(lnode->val->op) {
20921 mkconst(state, ins, lnode->val->u.cval);
20924 mkaddr_const(state, ins,
20925 MISC(lnode->val, 0), lnode->val->u.cval);
20928 /* By default don't copy the changes,
20929 * recompute them in place instead.
20931 simplify(state, ins);
20934 if (is_const(lnode->val) &&
20935 !constants_equal(state, lnode->val, ins)) {
20936 internal_error(state, 0, "constants not equal");
20938 /* Free the lattice nodes */
20943 } while(ins != first);
20946 static void scc_transform(struct compile_state *state)
20948 struct scc_state scc;
20949 if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
20953 initialize_scc_state(state, &scc);
20955 while(scc.flow_work_list || scc.ssa_work_list) {
20956 struct flow_edge *fedge;
20957 struct ssa_edge *sedge;
20958 struct flow_edge *fptr;
20959 while((fedge = scc_next_fedge(state, &scc))) {
20960 struct block *block;
20961 struct triple *ptr;
20962 struct flow_block *fblock;
20965 if (fedge->executable) {
20969 internal_error(state, 0, "fedge without dst");
20972 internal_error(state, 0, "fedge without src");
20974 fedge->executable = 1;
20975 fblock = fedge->dst;
20976 block = fblock->block;
20978 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
20979 if (fptr->executable) {
20984 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20985 fprintf(state->errout, "vertex: %d reps: %d\n",
20986 block->vertex, reps);
20990 for(ptr = block->first; !done; ptr = ptr->next) {
20991 struct lattice_node *lnode;
20992 done = (ptr == block->last);
20993 lnode = &scc.lattice[ptr->id];
20994 if (ptr->op == OP_PHI) {
20995 scc_visit_phi(state, &scc, lnode);
20997 else if ((reps == 1) && triple_is_def(state, ptr))
20999 scc_visit_expr(state, &scc, lnode);
21002 /* Add unconditional branch edges */
21003 if (!triple_is_cbranch(state, fblock->block->last)) {
21004 struct flow_edge *out;
21005 for(out = fblock->out; out; out = out->out_next) {
21006 scc_add_fedge(state, &scc, out);
21010 while((sedge = scc_next_sedge(state, &scc))) {
21011 struct lattice_node *lnode;
21012 struct flow_block *fblock;
21013 lnode = sedge->dst;
21014 fblock = lnode->fblock;
21016 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21017 fprintf(state->errout, "sedge: %5d (%5d -> %5d)\n",
21018 sedge - scc.ssa_edges,
21019 sedge->src->def->id,
21020 sedge->dst->def->id);
21023 if (lnode->def->op == OP_PHI) {
21024 scc_visit_phi(state, &scc, lnode);
21027 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21028 if (fptr->executable) {
21033 scc_visit_expr(state, &scc, lnode);
21039 scc_writeback_values(state, &scc);
21040 free_scc_state(state, &scc);
21041 rebuild_ssa_form(state);
21043 print_blocks(state, __func__, state->dbgout);
21047 static void transform_to_arch_instructions(struct compile_state *state)
21049 struct triple *ins, *first;
21050 first = state->first;
21053 ins = transform_to_arch_instruction(state, ins);
21054 } while(ins != first);
21056 print_blocks(state, __func__, state->dbgout);
21059 #if DEBUG_CONSISTENCY
21060 static void verify_uses(struct compile_state *state)
21062 struct triple *first, *ins;
21063 struct triple_set *set;
21064 first = state->first;
21067 struct triple **expr;
21068 expr = triple_rhs(state, ins, 0);
21069 for(; expr; expr = triple_rhs(state, ins, expr)) {
21070 struct triple *rhs;
21072 for(set = rhs?rhs->use:0; set; set = set->next) {
21073 if (set->member == ins) {
21078 internal_error(state, ins, "rhs not used");
21081 expr = triple_lhs(state, ins, 0);
21082 for(; expr; expr = triple_lhs(state, ins, expr)) {
21083 struct triple *lhs;
21085 for(set = lhs?lhs->use:0; set; set = set->next) {
21086 if (set->member == ins) {
21091 internal_error(state, ins, "lhs not used");
21094 expr = triple_misc(state, ins, 0);
21095 if (ins->op != OP_PHI) {
21096 for(; expr; expr = triple_targ(state, ins, expr)) {
21097 struct triple *misc;
21099 for(set = misc?misc->use:0; set; set = set->next) {
21100 if (set->member == ins) {
21105 internal_error(state, ins, "misc not used");
21109 if (!triple_is_ret(state, ins)) {
21110 expr = triple_targ(state, ins, 0);
21111 for(; expr; expr = triple_targ(state, ins, expr)) {
21112 struct triple *targ;
21114 for(set = targ?targ->use:0; set; set = set->next) {
21115 if (set->member == ins) {
21120 internal_error(state, ins, "targ not used");
21125 } while(ins != first);
21128 static void verify_blocks_present(struct compile_state *state)
21130 struct triple *first, *ins;
21131 if (!state->bb.first_block) {
21134 first = state->first;
21137 valid_ins(state, ins);
21138 if (triple_stores_block(state, ins)) {
21139 if (!ins->u.block) {
21140 internal_error(state, ins,
21141 "%p not in a block?", ins);
21145 } while(ins != first);
21150 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21152 struct block_set *bedge;
21153 struct block *targ;
21154 targ = block_of_triple(state, edge);
21155 for(bedge = block->edges; bedge; bedge = bedge->next) {
21156 if (bedge->member == targ) {
21163 static void verify_blocks(struct compile_state *state)
21165 struct triple *ins;
21166 struct block *block;
21168 block = state->bb.first_block;
21175 struct block_set *user, *edge;
21177 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21178 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21179 internal_error(state, ins, "inconsitent block specified");
21181 valid_ins(state, ins);
21184 for(user = block->use; user; user = user->next) {
21186 if (!user->member->first) {
21187 internal_error(state, block->first, "user is empty");
21189 if ((block == state->bb.last_block) &&
21190 (user->member == state->bb.first_block)) {
21193 for(edge = user->member->edges; edge; edge = edge->next) {
21194 if (edge->member == block) {
21199 internal_error(state, user->member->first,
21200 "user does not use block");
21203 if (triple_is_branch(state, block->last)) {
21204 struct triple **expr;
21205 expr = triple_edge_targ(state, block->last, 0);
21206 for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21207 if (*expr && !edge_present(state, block, *expr)) {
21208 internal_error(state, block->last, "no edge to targ");
21212 if (!triple_is_ubranch(state, block->last) &&
21213 (block != state->bb.last_block) &&
21214 !edge_present(state, block, block->last->next)) {
21215 internal_error(state, block->last, "no edge to block->last->next");
21217 for(edge = block->edges; edge; edge = edge->next) {
21218 for(user = edge->member->use; user; user = user->next) {
21219 if (user->member == block) {
21223 if (!user || user->member != block) {
21224 internal_error(state, block->first,
21225 "block does not use edge");
21227 if (!edge->member->first) {
21228 internal_error(state, block->first, "edge block is empty");
21231 if (block->users != users) {
21232 internal_error(state, block->first,
21233 "computed users %d != stored users %d",
21234 users, block->users);
21236 if (!triple_stores_block(state, block->last->next)) {
21237 internal_error(state, block->last->next,
21238 "cannot find next block");
21240 block = block->last->next->u.block;
21242 internal_error(state, block->last->next,
21245 } while(block != state->bb.first_block);
21246 if (blocks != state->bb.last_vertex) {
21247 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21248 blocks, state->bb.last_vertex);
21252 static void verify_domination(struct compile_state *state)
21254 struct triple *first, *ins;
21255 struct triple_set *set;
21256 if (!state->bb.first_block) {
21260 first = state->first;
21263 for(set = ins->use; set; set = set->next) {
21264 struct triple **slot;
21265 struct triple *use_point;
21268 zrhs = set->member->rhs;
21269 slot = &RHS(set->member, 0);
21270 /* See if the use is on the right hand side */
21271 for(i = 0; i < zrhs; i++) {
21272 if (slot[i] == ins) {
21277 use_point = set->member;
21278 if (set->member->op == OP_PHI) {
21279 struct block_set *bset;
21281 bset = set->member->u.block->use;
21282 for(edge = 0; bset && (edge < i); edge++) {
21286 internal_error(state, set->member,
21287 "no edge for phi rhs %d", i);
21289 use_point = bset->member->last;
21293 !tdominates(state, ins, use_point)) {
21294 if (is_const(ins)) {
21295 internal_warning(state, ins,
21296 "non dominated rhs use point?");
21299 internal_error(state, ins,
21300 "non dominated rhs use point?");
21305 } while(ins != first);
21308 static void verify_rhs(struct compile_state *state)
21310 struct triple *first, *ins;
21311 first = state->first;
21314 struct triple **slot;
21317 slot = &RHS(ins, 0);
21318 for(i = 0; i < zrhs; i++) {
21319 if (slot[i] == 0) {
21320 internal_error(state, ins,
21321 "missing rhs %d on %s",
21324 if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21325 internal_error(state, ins,
21326 "ins == rhs[%d] on %s",
21331 } while(ins != first);
21334 static void verify_piece(struct compile_state *state)
21336 struct triple *first, *ins;
21337 first = state->first;
21340 struct triple *ptr;
21343 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21344 if (ptr != LHS(ins, i)) {
21345 internal_error(state, ins, "malformed lhs on %s",
21348 if (ptr->op != OP_PIECE) {
21349 internal_error(state, ins, "bad lhs op %s at %d on %s",
21350 tops(ptr->op), i, tops(ins->op));
21352 if (ptr->u.cval != i) {
21353 internal_error(state, ins, "bad u.cval of %d %d expected",
21358 } while(ins != first);
21361 static void verify_ins_colors(struct compile_state *state)
21363 struct triple *first, *ins;
21365 first = state->first;
21369 } while(ins != first);
21372 static void verify_unknown(struct compile_state *state)
21374 struct triple *first, *ins;
21375 if ( (unknown_triple.next != &unknown_triple) ||
21376 (unknown_triple.prev != &unknown_triple) ||
21378 (unknown_triple.use != 0) ||
21380 (unknown_triple.op != OP_UNKNOWNVAL) ||
21381 (unknown_triple.lhs != 0) ||
21382 (unknown_triple.rhs != 0) ||
21383 (unknown_triple.misc != 0) ||
21384 (unknown_triple.targ != 0) ||
21385 (unknown_triple.template_id != 0) ||
21386 (unknown_triple.id != -1) ||
21387 (unknown_triple.type != &unknown_type) ||
21388 (unknown_triple.occurance != &dummy_occurance) ||
21389 (unknown_triple.param[0] != 0) ||
21390 (unknown_triple.param[1] != 0)) {
21391 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21393 if ( (dummy_occurance.count != 2) ||
21394 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21395 (strcmp(dummy_occurance.function, "") != 0) ||
21396 (dummy_occurance.col != 0) ||
21397 (dummy_occurance.parent != 0)) {
21398 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21400 if ( (unknown_type.type != TYPE_UNKNOWN)) {
21401 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21403 first = state->first;
21407 if (ins == &unknown_triple) {
21408 internal_error(state, ins, "unknown triple in list");
21410 params = TRIPLE_SIZE(ins);
21411 for(i = 0; i < params; i++) {
21412 if (ins->param[i] == &unknown_triple) {
21413 internal_error(state, ins, "unknown triple used!");
21417 } while(ins != first);
21420 static void verify_types(struct compile_state *state)
21422 struct triple *first, *ins;
21423 first = state->first;
21426 struct type *invalid;
21427 invalid = invalid_type(state, ins->type);
21429 FILE *fp = state->errout;
21430 fprintf(fp, "type: ");
21431 name_of(fp, ins->type);
21433 fprintf(fp, "invalid type: ");
21434 name_of(fp, invalid);
21436 internal_error(state, ins, "invalid ins type");
21438 } while(ins != first);
21441 static void verify_copy(struct compile_state *state)
21443 struct triple *first, *ins, *next;
21444 first = state->first;
21445 next = ins = first;
21449 if (ins->op != OP_COPY) {
21452 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21453 FILE *fp = state->errout;
21454 fprintf(fp, "src type: ");
21455 name_of(fp, RHS(ins, 0)->type);
21457 fprintf(fp, "dst type: ");
21458 name_of(fp, ins->type);
21460 internal_error(state, ins, "type mismatch in copy");
21462 } while(next != first);
21465 static void verify_consistency(struct compile_state *state)
21467 verify_unknown(state);
21468 verify_uses(state);
21469 verify_blocks_present(state);
21470 verify_blocks(state);
21471 verify_domination(state);
21473 verify_piece(state);
21474 verify_ins_colors(state);
21475 verify_types(state);
21476 verify_copy(state);
21477 if (state->compiler->debug & DEBUG_VERIFICATION) {
21478 fprintf(state->dbgout, "consistency verified\n");
21482 static void verify_consistency(struct compile_state *state) {}
21483 #endif /* DEBUG_CONSISTENCY */
21485 static void optimize(struct compile_state *state)
21487 /* Join all of the functions into one giant function */
21488 join_functions(state);
21490 /* Dump what the instruction graph intially looks like */
21491 print_triples(state);
21493 /* Replace structures with simpler data types */
21494 decompose_compound_types(state);
21495 print_triples(state);
21497 verify_consistency(state);
21498 /* Analize the intermediate code */
21499 state->bb.first = state->first;
21500 analyze_basic_blocks(state, &state->bb);
21502 /* Transform the code to ssa form. */
21504 * The transformation to ssa form puts a phi function
21505 * on each of edge of a dominance frontier where that
21506 * phi function might be needed. At -O2 if we don't
21507 * eleminate the excess phi functions we can get an
21508 * exponential code size growth. So I kill the extra
21509 * phi functions early and I kill them often.
21511 transform_to_ssa_form(state);
21512 verify_consistency(state);
21514 /* Remove dead code */
21515 eliminate_inefectual_code(state);
21516 verify_consistency(state);
21518 /* Do strength reduction and simple constant optimizations */
21519 simplify_all(state);
21520 verify_consistency(state);
21521 /* Propogate constants throughout the code */
21522 scc_transform(state);
21523 verify_consistency(state);
21524 #warning "WISHLIST implement single use constants (least possible register pressure)"
21525 #warning "WISHLIST implement induction variable elimination"
21526 /* Select architecture instructions and an initial partial
21527 * coloring based on architecture constraints.
21529 transform_to_arch_instructions(state);
21530 verify_consistency(state);
21532 /* Remove dead code */
21533 eliminate_inefectual_code(state);
21534 verify_consistency(state);
21536 /* Color all of the variables to see if they will fit in registers */
21537 insert_copies_to_phi(state);
21538 verify_consistency(state);
21540 insert_mandatory_copies(state);
21541 verify_consistency(state);
21543 allocate_registers(state);
21544 verify_consistency(state);
21546 /* Remove the optimization information.
21547 * This is more to check for memory consistency than to free memory.
21549 free_basic_blocks(state, &state->bb);
21552 static void print_op_asm(struct compile_state *state,
21553 struct triple *ins, FILE *fp)
21555 struct asm_info *info;
21557 unsigned lhs, rhs, i;
21558 info = ins->u.ainfo;
21561 /* Don't count the clobbers in lhs */
21562 for(i = 0; i < lhs; i++) {
21563 if (LHS(ins, i)->type == &void_type) {
21568 fprintf(fp, "#ASM\n");
21570 for(ptr = info->str; *ptr; ptr++) {
21572 unsigned long param;
21573 struct triple *piece;
21583 param = strtoul(ptr, &next, 10);
21585 error(state, ins, "Invalid asm template");
21587 if (param >= (lhs + rhs)) {
21588 error(state, ins, "Invalid param %%%u in asm template",
21591 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21593 arch_reg_str(ID_REG(piece->id)));
21596 fprintf(fp, "\n#NOT ASM\n");
21600 /* Only use the low x86 byte registers. This allows me
21601 * allocate the entire register when a byte register is used.
21603 #define X86_4_8BIT_GPRS 1
21606 #define X86_MMX_REGS (1<<0)
21607 #define X86_XMM_REGS (1<<1)
21608 #define X86_NOOP_COPY (1<<2)
21610 /* The x86 register classes */
21611 #define REGC_FLAGS 0
21612 #define REGC_GPR8 1
21613 #define REGC_GPR16 2
21614 #define REGC_GPR32 3
21615 #define REGC_DIVIDEND64 4
21616 #define REGC_DIVIDEND32 5
21619 #define REGC_GPR32_8 8
21620 #define REGC_GPR16_8 9
21621 #define REGC_GPR8_LO 10
21622 #define REGC_IMM32 11
21623 #define REGC_IMM16 12
21624 #define REGC_IMM8 13
21625 #define LAST_REGC REGC_IMM8
21626 #if LAST_REGC >= MAX_REGC
21627 #error "MAX_REGC is to low"
21630 /* Register class masks */
21631 #define REGCM_FLAGS (1 << REGC_FLAGS)
21632 #define REGCM_GPR8 (1 << REGC_GPR8)
21633 #define REGCM_GPR16 (1 << REGC_GPR16)
21634 #define REGCM_GPR32 (1 << REGC_GPR32)
21635 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21636 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21637 #define REGCM_MMX (1 << REGC_MMX)
21638 #define REGCM_XMM (1 << REGC_XMM)
21639 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
21640 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
21641 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
21642 #define REGCM_IMM32 (1 << REGC_IMM32)
21643 #define REGCM_IMM16 (1 << REGC_IMM16)
21644 #define REGCM_IMM8 (1 << REGC_IMM8)
21645 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
21646 #define REGCM_IMMALL (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21648 /* The x86 registers */
21649 #define REG_EFLAGS 2
21650 #define REGC_FLAGS_FIRST REG_EFLAGS
21651 #define REGC_FLAGS_LAST REG_EFLAGS
21660 #define REGC_GPR8_LO_FIRST REG_AL
21661 #define REGC_GPR8_LO_LAST REG_DL
21662 #define REGC_GPR8_FIRST REG_AL
21663 #define REGC_GPR8_LAST REG_DH
21672 #define REGC_GPR16_FIRST REG_AX
21673 #define REGC_GPR16_LAST REG_SP
21682 #define REGC_GPR32_FIRST REG_EAX
21683 #define REGC_GPR32_LAST REG_ESP
21684 #define REG_EDXEAX 27
21685 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21686 #define REGC_DIVIDEND64_LAST REG_EDXEAX
21687 #define REG_DXAX 28
21688 #define REGC_DIVIDEND32_FIRST REG_DXAX
21689 #define REGC_DIVIDEND32_LAST REG_DXAX
21690 #define REG_MMX0 29
21691 #define REG_MMX1 30
21692 #define REG_MMX2 31
21693 #define REG_MMX3 32
21694 #define REG_MMX4 33
21695 #define REG_MMX5 34
21696 #define REG_MMX6 35
21697 #define REG_MMX7 36
21698 #define REGC_MMX_FIRST REG_MMX0
21699 #define REGC_MMX_LAST REG_MMX7
21700 #define REG_XMM0 37
21701 #define REG_XMM1 38
21702 #define REG_XMM2 39
21703 #define REG_XMM3 40
21704 #define REG_XMM4 41
21705 #define REG_XMM5 42
21706 #define REG_XMM6 43
21707 #define REG_XMM7 44
21708 #define REGC_XMM_FIRST REG_XMM0
21709 #define REGC_XMM_LAST REG_XMM7
21710 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21711 #define LAST_REG REG_XMM7
21713 #define REGC_GPR32_8_FIRST REG_EAX
21714 #define REGC_GPR32_8_LAST REG_EDX
21715 #define REGC_GPR16_8_FIRST REG_AX
21716 #define REGC_GPR16_8_LAST REG_DX
21718 #define REGC_IMM8_FIRST -1
21719 #define REGC_IMM8_LAST -1
21720 #define REGC_IMM16_FIRST -2
21721 #define REGC_IMM16_LAST -1
21722 #define REGC_IMM32_FIRST -4
21723 #define REGC_IMM32_LAST -1
21725 #if LAST_REG >= MAX_REGISTERS
21726 #error "MAX_REGISTERS to low"
21730 static unsigned regc_size[LAST_REGC +1] = {
21731 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
21732 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
21733 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
21734 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
21735 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21736 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21737 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
21738 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
21739 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
21740 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
21741 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
21747 static const struct {
21749 } regcm_bound[LAST_REGC + 1] = {
21750 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
21751 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
21752 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
21753 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
21754 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21755 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21756 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
21757 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
21758 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
21759 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
21760 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
21761 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
21762 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
21763 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
21766 #if ARCH_INPUT_REGS != 4
21767 #error ARCH_INPUT_REGS size mismatch
21769 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21770 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21771 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21772 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21773 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21776 #if ARCH_OUTPUT_REGS != 4
21777 #error ARCH_INPUT_REGS size mismatch
21779 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21780 { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21781 { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21782 { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21783 { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21786 static void init_arch_state(struct arch_state *arch)
21788 memset(arch, 0, sizeof(*arch));
21789 arch->features = 0;
21792 static const struct compiler_flag arch_flags[] = {
21793 { "mmx", X86_MMX_REGS },
21794 { "sse", X86_XMM_REGS },
21795 { "noop-copy", X86_NOOP_COPY },
21798 static const struct compiler_flag arch_cpus[] = {
21800 { "p2", X86_MMX_REGS },
21801 { "p3", X86_MMX_REGS | X86_XMM_REGS },
21802 { "p4", X86_MMX_REGS | X86_XMM_REGS },
21803 { "k7", X86_MMX_REGS },
21804 { "k8", X86_MMX_REGS | X86_XMM_REGS },
21805 { "c3", X86_MMX_REGS },
21806 { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21809 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21816 if (strncmp(flag, "no-", 3) == 0) {
21820 if (act && strncmp(flag, "cpu=", 4) == 0) {
21822 result = set_flag(arch_cpus, &arch->features, 1, flag);
21825 result = set_flag(arch_flags, &arch->features, act, flag);
21830 static void arch_usage(FILE *fp)
21832 flag_usage(fp, arch_flags, "-m", "-mno-");
21833 flag_usage(fp, arch_cpus, "-mcpu=", 0);
21836 static unsigned arch_regc_size(struct compile_state *state, int class)
21838 if ((class < 0) || (class > LAST_REGC)) {
21841 return regc_size[class];
21844 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21846 /* See if two register classes may have overlapping registers */
21847 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21848 REGCM_GPR32_8 | REGCM_GPR32 |
21849 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21851 /* Special case for the immediates */
21852 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21853 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21854 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21855 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
21858 return (regcm1 & regcm2) ||
21859 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21862 static void arch_reg_equivs(
21863 struct compile_state *state, unsigned *equiv, int reg)
21865 if ((reg < 0) || (reg > LAST_REG)) {
21866 internal_error(state, 0, "invalid register");
21871 #if X86_4_8BIT_GPRS
21875 *equiv++ = REG_EAX;
21876 *equiv++ = REG_DXAX;
21877 *equiv++ = REG_EDXEAX;
21880 #if X86_4_8BIT_GPRS
21884 *equiv++ = REG_EAX;
21885 *equiv++ = REG_DXAX;
21886 *equiv++ = REG_EDXEAX;
21889 #if X86_4_8BIT_GPRS
21893 *equiv++ = REG_EBX;
21897 #if X86_4_8BIT_GPRS
21901 *equiv++ = REG_EBX;
21904 #if X86_4_8BIT_GPRS
21908 *equiv++ = REG_ECX;
21912 #if X86_4_8BIT_GPRS
21916 *equiv++ = REG_ECX;
21919 #if X86_4_8BIT_GPRS
21923 *equiv++ = REG_EDX;
21924 *equiv++ = REG_DXAX;
21925 *equiv++ = REG_EDXEAX;
21928 #if X86_4_8BIT_GPRS
21932 *equiv++ = REG_EDX;
21933 *equiv++ = REG_DXAX;
21934 *equiv++ = REG_EDXEAX;
21939 *equiv++ = REG_EAX;
21940 *equiv++ = REG_DXAX;
21941 *equiv++ = REG_EDXEAX;
21946 *equiv++ = REG_EBX;
21951 *equiv++ = REG_ECX;
21956 *equiv++ = REG_EDX;
21957 *equiv++ = REG_DXAX;
21958 *equiv++ = REG_EDXEAX;
21961 *equiv++ = REG_ESI;
21964 *equiv++ = REG_EDI;
21967 *equiv++ = REG_EBP;
21970 *equiv++ = REG_ESP;
21976 *equiv++ = REG_DXAX;
21977 *equiv++ = REG_EDXEAX;
21993 *equiv++ = REG_DXAX;
21994 *equiv++ = REG_EDXEAX;
22015 *equiv++ = REG_EAX;
22016 *equiv++ = REG_EDX;
22017 *equiv++ = REG_EDXEAX;
22026 *equiv++ = REG_EAX;
22027 *equiv++ = REG_EDX;
22028 *equiv++ = REG_DXAX;
22031 *equiv++ = REG_UNSET;
22034 static unsigned arch_avail_mask(struct compile_state *state)
22036 unsigned avail_mask;
22037 /* REGCM_GPR8 is not available */
22038 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
22039 REGCM_GPR32 | REGCM_GPR32_8 |
22040 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22041 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22042 if (state->arch->features & X86_MMX_REGS) {
22043 avail_mask |= REGCM_MMX;
22045 if (state->arch->features & X86_XMM_REGS) {
22046 avail_mask |= REGCM_XMM;
22051 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22053 unsigned mask, result;
22057 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22058 if ((result & mask) == 0) {
22061 if (class > LAST_REGC) {
22064 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22065 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22066 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22067 result |= (1 << class2);
22071 result &= arch_avail_mask(state);
22075 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22077 /* Like arch_regcm_normalize except immediate register classes are excluded */
22078 regcm = arch_regcm_normalize(state, regcm);
22079 /* Remove the immediate register classes */
22080 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22085 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22090 for(class = 0; class <= LAST_REGC; class++) {
22091 if ((reg >= regcm_bound[class].first) &&
22092 (reg <= regcm_bound[class].last)) {
22093 mask |= (1 << class);
22097 internal_error(state, 0, "reg %d not in any class", reg);
22102 static struct reg_info arch_reg_constraint(
22103 struct compile_state *state, struct type *type, const char *constraint)
22105 static const struct {
22109 } constraints[] = {
22110 { 'r', REGCM_GPR32, REG_UNSET },
22111 { 'g', REGCM_GPR32, REG_UNSET },
22112 { 'p', REGCM_GPR32, REG_UNSET },
22113 { 'q', REGCM_GPR8_LO, REG_UNSET },
22114 { 'Q', REGCM_GPR32_8, REG_UNSET },
22115 { 'x', REGCM_XMM, REG_UNSET },
22116 { 'y', REGCM_MMX, REG_UNSET },
22117 { 'a', REGCM_GPR32, REG_EAX },
22118 { 'b', REGCM_GPR32, REG_EBX },
22119 { 'c', REGCM_GPR32, REG_ECX },
22120 { 'd', REGCM_GPR32, REG_EDX },
22121 { 'D', REGCM_GPR32, REG_EDI },
22122 { 'S', REGCM_GPR32, REG_ESI },
22123 { '\0', 0, REG_UNSET },
22125 unsigned int regcm;
22126 unsigned int mask, reg;
22127 struct reg_info result;
22129 regcm = arch_type_to_regcm(state, type);
22132 for(ptr = constraint; *ptr; ptr++) {
22137 for(i = 0; constraints[i].class != '\0'; i++) {
22138 if (constraints[i].class == *ptr) {
22142 if (constraints[i].class == '\0') {
22143 error(state, 0, "invalid register constraint ``%c''", *ptr);
22146 if ((constraints[i].mask & regcm) == 0) {
22147 error(state, 0, "invalid register class %c specified",
22150 mask |= constraints[i].mask;
22151 if (constraints[i].reg != REG_UNSET) {
22152 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22153 error(state, 0, "Only one register may be specified");
22155 reg = constraints[i].reg;
22159 result.regcm = mask;
22163 static struct reg_info arch_reg_clobber(
22164 struct compile_state *state, const char *clobber)
22166 struct reg_info result;
22167 if (strcmp(clobber, "memory") == 0) {
22168 result.reg = REG_UNSET;
22171 else if (strcmp(clobber, "eax") == 0) {
22172 result.reg = REG_EAX;
22173 result.regcm = REGCM_GPR32;
22175 else if (strcmp(clobber, "ebx") == 0) {
22176 result.reg = REG_EBX;
22177 result.regcm = REGCM_GPR32;
22179 else if (strcmp(clobber, "ecx") == 0) {
22180 result.reg = REG_ECX;
22181 result.regcm = REGCM_GPR32;
22183 else if (strcmp(clobber, "edx") == 0) {
22184 result.reg = REG_EDX;
22185 result.regcm = REGCM_GPR32;
22187 else if (strcmp(clobber, "esi") == 0) {
22188 result.reg = REG_ESI;
22189 result.regcm = REGCM_GPR32;
22191 else if (strcmp(clobber, "edi") == 0) {
22192 result.reg = REG_EDI;
22193 result.regcm = REGCM_GPR32;
22195 else if (strcmp(clobber, "ebp") == 0) {
22196 result.reg = REG_EBP;
22197 result.regcm = REGCM_GPR32;
22199 else if (strcmp(clobber, "esp") == 0) {
22200 result.reg = REG_ESP;
22201 result.regcm = REGCM_GPR32;
22203 else if (strcmp(clobber, "cc") == 0) {
22204 result.reg = REG_EFLAGS;
22205 result.regcm = REGCM_FLAGS;
22207 else if ((strncmp(clobber, "xmm", 3) == 0) &&
22208 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22209 result.reg = REG_XMM0 + octdigval(clobber[3]);
22210 result.regcm = REGCM_XMM;
22212 else if ((strncmp(clobber, "mm", 2) == 0) &&
22213 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22214 result.reg = REG_MMX0 + octdigval(clobber[3]);
22215 result.regcm = REGCM_MMX;
22218 error(state, 0, "unknown register name `%s' in asm",
22220 result.reg = REG_UNSET;
22226 static int do_select_reg(struct compile_state *state,
22227 char *used, int reg, unsigned classes)
22233 mask = arch_reg_regcm(state, reg);
22234 return (classes & mask) ? reg : REG_UNSET;
22237 static int arch_select_free_register(
22238 struct compile_state *state, char *used, int classes)
22240 /* Live ranges with the most neighbors are colored first.
22242 * Generally it does not matter which colors are given
22243 * as the register allocator attempts to color live ranges
22244 * in an order where you are guaranteed not to run out of colors.
22246 * Occasionally the register allocator cannot find an order
22247 * of register selection that will find a free color. To
22248 * increase the odds the register allocator will work when
22249 * it guesses first give out registers from register classes
22250 * least likely to run out of registers.
22255 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22256 reg = do_select_reg(state, used, i, classes);
22258 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22259 reg = do_select_reg(state, used, i, classes);
22261 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22262 reg = do_select_reg(state, used, i, classes);
22264 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22265 reg = do_select_reg(state, used, i, classes);
22267 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22268 reg = do_select_reg(state, used, i, classes);
22270 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22271 reg = do_select_reg(state, used, i, classes);
22273 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22274 reg = do_select_reg(state, used, i, classes);
22276 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22277 reg = do_select_reg(state, used, i, classes);
22279 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22280 reg = do_select_reg(state, used, i, classes);
22286 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
22288 #warning "FIXME force types smaller (if legal) before I get here"
22291 switch(type->type & TYPE_MASK) {
22298 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22299 REGCM_GPR16 | REGCM_GPR16_8 |
22300 REGCM_GPR32 | REGCM_GPR32_8 |
22301 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22302 REGCM_MMX | REGCM_XMM |
22303 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22307 mask = REGCM_GPR16 | REGCM_GPR16_8 |
22308 REGCM_GPR32 | REGCM_GPR32_8 |
22309 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22310 REGCM_MMX | REGCM_XMM |
22311 REGCM_IMM32 | REGCM_IMM16;
22319 mask = REGCM_GPR32 | REGCM_GPR32_8 |
22320 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22321 REGCM_MMX | REGCM_XMM |
22326 mask = arch_type_to_regcm(state, type->left);
22329 mask = arch_type_to_regcm(state, type->left) &
22330 arch_type_to_regcm(state, type->right);
22332 case TYPE_BITFIELD:
22333 mask = arch_type_to_regcm(state, type->left);
22336 fprintf(state->errout, "type: ");
22337 name_of(state->errout, type);
22338 fprintf(state->errout, "\n");
22339 internal_error(state, 0, "no register class for type");
22342 mask = arch_regcm_normalize(state, mask);
22346 static int is_imm32(struct triple *imm)
22348 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
22349 (imm->op == OP_ADDRCONST);
22352 static int is_imm16(struct triple *imm)
22354 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22356 static int is_imm8(struct triple *imm)
22358 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22361 static int get_imm32(struct triple *ins, struct triple **expr)
22363 struct triple *imm;
22365 while(imm->op == OP_COPY) {
22368 if (!is_imm32(imm)) {
22371 unuse_triple(*expr, ins);
22372 use_triple(imm, ins);
22377 static int get_imm8(struct triple *ins, struct triple **expr)
22379 struct triple *imm;
22381 while(imm->op == OP_COPY) {
22384 if (!is_imm8(imm)) {
22387 unuse_triple(*expr, ins);
22388 use_triple(imm, ins);
22393 #define TEMPLATE_NOP 0
22394 #define TEMPLATE_INTCONST8 1
22395 #define TEMPLATE_INTCONST32 2
22396 #define TEMPLATE_UNKNOWNVAL 3
22397 #define TEMPLATE_COPY8_REG 5
22398 #define TEMPLATE_COPY16_REG 6
22399 #define TEMPLATE_COPY32_REG 7
22400 #define TEMPLATE_COPY_IMM8 8
22401 #define TEMPLATE_COPY_IMM16 9
22402 #define TEMPLATE_COPY_IMM32 10
22403 #define TEMPLATE_PHI8 11
22404 #define TEMPLATE_PHI16 12
22405 #define TEMPLATE_PHI32 13
22406 #define TEMPLATE_STORE8 14
22407 #define TEMPLATE_STORE16 15
22408 #define TEMPLATE_STORE32 16
22409 #define TEMPLATE_LOAD8 17
22410 #define TEMPLATE_LOAD16 18
22411 #define TEMPLATE_LOAD32 19
22412 #define TEMPLATE_BINARY8_REG 20
22413 #define TEMPLATE_BINARY16_REG 21
22414 #define TEMPLATE_BINARY32_REG 22
22415 #define TEMPLATE_BINARY8_IMM 23
22416 #define TEMPLATE_BINARY16_IMM 24
22417 #define TEMPLATE_BINARY32_IMM 25
22418 #define TEMPLATE_SL8_CL 26
22419 #define TEMPLATE_SL16_CL 27
22420 #define TEMPLATE_SL32_CL 28
22421 #define TEMPLATE_SL8_IMM 29
22422 #define TEMPLATE_SL16_IMM 30
22423 #define TEMPLATE_SL32_IMM 31
22424 #define TEMPLATE_UNARY8 32
22425 #define TEMPLATE_UNARY16 33
22426 #define TEMPLATE_UNARY32 34
22427 #define TEMPLATE_CMP8_REG 35
22428 #define TEMPLATE_CMP16_REG 36
22429 #define TEMPLATE_CMP32_REG 37
22430 #define TEMPLATE_CMP8_IMM 38
22431 #define TEMPLATE_CMP16_IMM 39
22432 #define TEMPLATE_CMP32_IMM 40
22433 #define TEMPLATE_TEST8 41
22434 #define TEMPLATE_TEST16 42
22435 #define TEMPLATE_TEST32 43
22436 #define TEMPLATE_SET 44
22437 #define TEMPLATE_JMP 45
22438 #define TEMPLATE_RET 46
22439 #define TEMPLATE_INB_DX 47
22440 #define TEMPLATE_INB_IMM 48
22441 #define TEMPLATE_INW_DX 49
22442 #define TEMPLATE_INW_IMM 50
22443 #define TEMPLATE_INL_DX 51
22444 #define TEMPLATE_INL_IMM 52
22445 #define TEMPLATE_OUTB_DX 53
22446 #define TEMPLATE_OUTB_IMM 54
22447 #define TEMPLATE_OUTW_DX 55
22448 #define TEMPLATE_OUTW_IMM 56
22449 #define TEMPLATE_OUTL_DX 57
22450 #define TEMPLATE_OUTL_IMM 58
22451 #define TEMPLATE_BSF 59
22452 #define TEMPLATE_RDMSR 60
22453 #define TEMPLATE_WRMSR 61
22454 #define TEMPLATE_UMUL8 62
22455 #define TEMPLATE_UMUL16 63
22456 #define TEMPLATE_UMUL32 64
22457 #define TEMPLATE_DIV8 65
22458 #define TEMPLATE_DIV16 66
22459 #define TEMPLATE_DIV32 67
22460 #define LAST_TEMPLATE TEMPLATE_DIV32
22461 #if LAST_TEMPLATE >= MAX_TEMPLATES
22462 #error "MAX_TEMPLATES to low"
22465 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22466 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
22467 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22470 static struct ins_template templates[] = {
22473 [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22474 [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22475 [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22476 [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22477 [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22478 [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22479 [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22480 [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22481 [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22482 [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22483 [10] = { REG_UNNEEDED, REGCM_IMMALL },
22484 [11] = { REG_UNNEEDED, REGCM_IMMALL },
22485 [12] = { REG_UNNEEDED, REGCM_IMMALL },
22486 [13] = { REG_UNNEEDED, REGCM_IMMALL },
22487 [14] = { REG_UNNEEDED, REGCM_IMMALL },
22488 [15] = { REG_UNNEEDED, REGCM_IMMALL },
22489 [16] = { REG_UNNEEDED, REGCM_IMMALL },
22490 [17] = { REG_UNNEEDED, REGCM_IMMALL },
22491 [18] = { REG_UNNEEDED, REGCM_IMMALL },
22492 [19] = { REG_UNNEEDED, REGCM_IMMALL },
22493 [20] = { REG_UNNEEDED, REGCM_IMMALL },
22494 [21] = { REG_UNNEEDED, REGCM_IMMALL },
22495 [22] = { REG_UNNEEDED, REGCM_IMMALL },
22496 [23] = { REG_UNNEEDED, REGCM_IMMALL },
22497 [24] = { REG_UNNEEDED, REGCM_IMMALL },
22498 [25] = { REG_UNNEEDED, REGCM_IMMALL },
22499 [26] = { REG_UNNEEDED, REGCM_IMMALL },
22500 [27] = { REG_UNNEEDED, REGCM_IMMALL },
22501 [28] = { REG_UNNEEDED, REGCM_IMMALL },
22502 [29] = { REG_UNNEEDED, REGCM_IMMALL },
22503 [30] = { REG_UNNEEDED, REGCM_IMMALL },
22504 [31] = { REG_UNNEEDED, REGCM_IMMALL },
22505 [32] = { REG_UNNEEDED, REGCM_IMMALL },
22506 [33] = { REG_UNNEEDED, REGCM_IMMALL },
22507 [34] = { REG_UNNEEDED, REGCM_IMMALL },
22508 [35] = { REG_UNNEEDED, REGCM_IMMALL },
22509 [36] = { REG_UNNEEDED, REGCM_IMMALL },
22510 [37] = { REG_UNNEEDED, REGCM_IMMALL },
22511 [38] = { REG_UNNEEDED, REGCM_IMMALL },
22512 [39] = { REG_UNNEEDED, REGCM_IMMALL },
22513 [40] = { REG_UNNEEDED, REGCM_IMMALL },
22514 [41] = { REG_UNNEEDED, REGCM_IMMALL },
22515 [42] = { REG_UNNEEDED, REGCM_IMMALL },
22516 [43] = { REG_UNNEEDED, REGCM_IMMALL },
22517 [44] = { REG_UNNEEDED, REGCM_IMMALL },
22518 [45] = { REG_UNNEEDED, REGCM_IMMALL },
22519 [46] = { REG_UNNEEDED, REGCM_IMMALL },
22520 [47] = { REG_UNNEEDED, REGCM_IMMALL },
22521 [48] = { REG_UNNEEDED, REGCM_IMMALL },
22522 [49] = { REG_UNNEEDED, REGCM_IMMALL },
22523 [50] = { REG_UNNEEDED, REGCM_IMMALL },
22524 [51] = { REG_UNNEEDED, REGCM_IMMALL },
22525 [52] = { REG_UNNEEDED, REGCM_IMMALL },
22526 [53] = { REG_UNNEEDED, REGCM_IMMALL },
22527 [54] = { REG_UNNEEDED, REGCM_IMMALL },
22528 [55] = { REG_UNNEEDED, REGCM_IMMALL },
22529 [56] = { REG_UNNEEDED, REGCM_IMMALL },
22530 [57] = { REG_UNNEEDED, REGCM_IMMALL },
22531 [58] = { REG_UNNEEDED, REGCM_IMMALL },
22532 [59] = { REG_UNNEEDED, REGCM_IMMALL },
22533 [60] = { REG_UNNEEDED, REGCM_IMMALL },
22534 [61] = { REG_UNNEEDED, REGCM_IMMALL },
22535 [62] = { REG_UNNEEDED, REGCM_IMMALL },
22536 [63] = { REG_UNNEEDED, REGCM_IMMALL },
22539 [TEMPLATE_INTCONST8] = {
22540 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22542 [TEMPLATE_INTCONST32] = {
22543 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22545 [TEMPLATE_UNKNOWNVAL] = {
22546 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22548 [TEMPLATE_COPY8_REG] = {
22549 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22550 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22552 [TEMPLATE_COPY16_REG] = {
22553 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22554 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22556 [TEMPLATE_COPY32_REG] = {
22557 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22558 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22560 [TEMPLATE_COPY_IMM8] = {
22561 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22562 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22564 [TEMPLATE_COPY_IMM16] = {
22565 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22566 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22568 [TEMPLATE_COPY_IMM32] = {
22569 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22570 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22572 [TEMPLATE_PHI8] = {
22573 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22574 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22576 [TEMPLATE_PHI16] = {
22577 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22578 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22580 [TEMPLATE_PHI32] = {
22581 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22582 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22584 [TEMPLATE_STORE8] = {
22586 [0] = { REG_UNSET, REGCM_GPR32 },
22587 [1] = { REG_UNSET, REGCM_GPR8_LO },
22590 [TEMPLATE_STORE16] = {
22592 [0] = { REG_UNSET, REGCM_GPR32 },
22593 [1] = { REG_UNSET, REGCM_GPR16 },
22596 [TEMPLATE_STORE32] = {
22598 [0] = { REG_UNSET, REGCM_GPR32 },
22599 [1] = { REG_UNSET, REGCM_GPR32 },
22602 [TEMPLATE_LOAD8] = {
22603 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22604 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22606 [TEMPLATE_LOAD16] = {
22607 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22608 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22610 [TEMPLATE_LOAD32] = {
22611 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22612 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22614 [TEMPLATE_BINARY8_REG] = {
22615 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22617 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22618 [1] = { REG_UNSET, REGCM_GPR8_LO },
22621 [TEMPLATE_BINARY16_REG] = {
22622 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22624 [0] = { REG_VIRT0, REGCM_GPR16 },
22625 [1] = { REG_UNSET, REGCM_GPR16 },
22628 [TEMPLATE_BINARY32_REG] = {
22629 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22631 [0] = { REG_VIRT0, REGCM_GPR32 },
22632 [1] = { REG_UNSET, REGCM_GPR32 },
22635 [TEMPLATE_BINARY8_IMM] = {
22636 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22638 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22639 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22642 [TEMPLATE_BINARY16_IMM] = {
22643 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22645 [0] = { REG_VIRT0, REGCM_GPR16 },
22646 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22649 [TEMPLATE_BINARY32_IMM] = {
22650 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22652 [0] = { REG_VIRT0, REGCM_GPR32 },
22653 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22656 [TEMPLATE_SL8_CL] = {
22657 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22659 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22660 [1] = { REG_CL, REGCM_GPR8_LO },
22663 [TEMPLATE_SL16_CL] = {
22664 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22666 [0] = { REG_VIRT0, REGCM_GPR16 },
22667 [1] = { REG_CL, REGCM_GPR8_LO },
22670 [TEMPLATE_SL32_CL] = {
22671 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22673 [0] = { REG_VIRT0, REGCM_GPR32 },
22674 [1] = { REG_CL, REGCM_GPR8_LO },
22677 [TEMPLATE_SL8_IMM] = {
22678 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22680 [0] = { REG_VIRT0, REGCM_GPR8_LO },
22681 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22684 [TEMPLATE_SL16_IMM] = {
22685 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22687 [0] = { REG_VIRT0, REGCM_GPR16 },
22688 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22691 [TEMPLATE_SL32_IMM] = {
22692 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22694 [0] = { REG_VIRT0, REGCM_GPR32 },
22695 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22698 [TEMPLATE_UNARY8] = {
22699 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22700 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22702 [TEMPLATE_UNARY16] = {
22703 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22704 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22706 [TEMPLATE_UNARY32] = {
22707 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22708 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22710 [TEMPLATE_CMP8_REG] = {
22711 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22713 [0] = { REG_UNSET, REGCM_GPR8_LO },
22714 [1] = { REG_UNSET, REGCM_GPR8_LO },
22717 [TEMPLATE_CMP16_REG] = {
22718 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22720 [0] = { REG_UNSET, REGCM_GPR16 },
22721 [1] = { REG_UNSET, REGCM_GPR16 },
22724 [TEMPLATE_CMP32_REG] = {
22725 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22727 [0] = { REG_UNSET, REGCM_GPR32 },
22728 [1] = { REG_UNSET, REGCM_GPR32 },
22731 [TEMPLATE_CMP8_IMM] = {
22732 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22734 [0] = { REG_UNSET, REGCM_GPR8_LO },
22735 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22738 [TEMPLATE_CMP16_IMM] = {
22739 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22741 [0] = { REG_UNSET, REGCM_GPR16 },
22742 [1] = { REG_UNNEEDED, REGCM_IMM16 },
22745 [TEMPLATE_CMP32_IMM] = {
22746 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22748 [0] = { REG_UNSET, REGCM_GPR32 },
22749 [1] = { REG_UNNEEDED, REGCM_IMM32 },
22752 [TEMPLATE_TEST8] = {
22753 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22754 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22756 [TEMPLATE_TEST16] = {
22757 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22758 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22760 [TEMPLATE_TEST32] = {
22761 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22762 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22765 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22766 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22769 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22772 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22774 [TEMPLATE_INB_DX] = {
22775 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22776 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22778 [TEMPLATE_INB_IMM] = {
22779 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
22780 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22782 [TEMPLATE_INW_DX] = {
22783 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22784 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22786 [TEMPLATE_INW_IMM] = {
22787 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22788 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22790 [TEMPLATE_INL_DX] = {
22791 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22792 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22794 [TEMPLATE_INL_IMM] = {
22795 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22796 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22798 [TEMPLATE_OUTB_DX] = {
22800 [0] = { REG_AL, REGCM_GPR8_LO },
22801 [1] = { REG_DX, REGCM_GPR16 },
22804 [TEMPLATE_OUTB_IMM] = {
22806 [0] = { REG_AL, REGCM_GPR8_LO },
22807 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22810 [TEMPLATE_OUTW_DX] = {
22812 [0] = { REG_AX, REGCM_GPR16 },
22813 [1] = { REG_DX, REGCM_GPR16 },
22816 [TEMPLATE_OUTW_IMM] = {
22818 [0] = { REG_AX, REGCM_GPR16 },
22819 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22822 [TEMPLATE_OUTL_DX] = {
22824 [0] = { REG_EAX, REGCM_GPR32 },
22825 [1] = { REG_DX, REGCM_GPR16 },
22828 [TEMPLATE_OUTL_IMM] = {
22830 [0] = { REG_EAX, REGCM_GPR32 },
22831 [1] = { REG_UNNEEDED, REGCM_IMM8 },
22835 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22836 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22838 [TEMPLATE_RDMSR] = {
22840 [0] = { REG_EAX, REGCM_GPR32 },
22841 [1] = { REG_EDX, REGCM_GPR32 },
22843 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22845 [TEMPLATE_WRMSR] = {
22847 [0] = { REG_ECX, REGCM_GPR32 },
22848 [1] = { REG_EAX, REGCM_GPR32 },
22849 [2] = { REG_EDX, REGCM_GPR32 },
22852 [TEMPLATE_UMUL8] = {
22853 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22855 [0] = { REG_AL, REGCM_GPR8_LO },
22856 [1] = { REG_UNSET, REGCM_GPR8_LO },
22859 [TEMPLATE_UMUL16] = {
22860 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22862 [0] = { REG_AX, REGCM_GPR16 },
22863 [1] = { REG_UNSET, REGCM_GPR16 },
22866 [TEMPLATE_UMUL32] = {
22867 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22869 [0] = { REG_EAX, REGCM_GPR32 },
22870 [1] = { REG_UNSET, REGCM_GPR32 },
22873 [TEMPLATE_DIV8] = {
22875 [0] = { REG_AL, REGCM_GPR8_LO },
22876 [1] = { REG_AH, REGCM_GPR8 },
22879 [0] = { REG_AX, REGCM_GPR16 },
22880 [1] = { REG_UNSET, REGCM_GPR8_LO },
22883 [TEMPLATE_DIV16] = {
22885 [0] = { REG_AX, REGCM_GPR16 },
22886 [1] = { REG_DX, REGCM_GPR16 },
22889 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
22890 [1] = { REG_UNSET, REGCM_GPR16 },
22893 [TEMPLATE_DIV32] = {
22895 [0] = { REG_EAX, REGCM_GPR32 },
22896 [1] = { REG_EDX, REGCM_GPR32 },
22899 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
22900 [1] = { REG_UNSET, REGCM_GPR32 },
22905 static void fixup_branch(struct compile_state *state,
22906 struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
22907 struct triple *left, struct triple *right)
22909 struct triple *test;
22911 internal_error(state, branch, "no branch test?");
22913 test = pre_triple(state, branch,
22914 cmp_op, cmp_type, left, right);
22915 test->template_id = TEMPLATE_TEST32;
22916 if (cmp_op == OP_CMP) {
22917 test->template_id = TEMPLATE_CMP32_REG;
22918 if (get_imm32(test, &RHS(test, 1))) {
22919 test->template_id = TEMPLATE_CMP32_IMM;
22922 use_triple(RHS(test, 0), test);
22923 use_triple(RHS(test, 1), test);
22924 unuse_triple(RHS(branch, 0), branch);
22925 RHS(branch, 0) = test;
22926 branch->op = jmp_op;
22927 branch->template_id = TEMPLATE_JMP;
22928 use_triple(RHS(branch, 0), branch);
22931 static void fixup_branches(struct compile_state *state,
22932 struct triple *cmp, struct triple *use, int jmp_op)
22934 struct triple_set *entry, *next;
22935 for(entry = use->use; entry; entry = next) {
22936 next = entry->next;
22937 if (entry->member->op == OP_COPY) {
22938 fixup_branches(state, cmp, entry->member, jmp_op);
22940 else if (entry->member->op == OP_CBRANCH) {
22941 struct triple *branch;
22942 struct triple *left, *right;
22944 left = RHS(cmp, 0);
22945 if (cmp->rhs > 1) {
22946 right = RHS(cmp, 1);
22948 branch = entry->member;
22949 fixup_branch(state, branch, jmp_op,
22950 cmp->op, cmp->type, left, right);
22955 static void bool_cmp(struct compile_state *state,
22956 struct triple *ins, int cmp_op, int jmp_op, int set_op)
22958 struct triple_set *entry, *next;
22959 struct triple *set, *convert;
22961 /* Put a barrier up before the cmp which preceeds the
22962 * copy instruction. If a set actually occurs this gives
22963 * us a chance to move variables in registers out of the way.
22966 /* Modify the comparison operator */
22968 ins->template_id = TEMPLATE_TEST32;
22969 if (cmp_op == OP_CMP) {
22970 ins->template_id = TEMPLATE_CMP32_REG;
22971 if (get_imm32(ins, &RHS(ins, 1))) {
22972 ins->template_id = TEMPLATE_CMP32_IMM;
22975 /* Generate the instruction sequence that will transform the
22976 * result of the comparison into a logical value.
22978 set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
22979 use_triple(ins, set);
22980 set->template_id = TEMPLATE_SET;
22983 if (!equiv_types(ins->type, set->type)) {
22984 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
22985 use_triple(set, convert);
22986 convert->template_id = TEMPLATE_COPY32_REG;
22989 for(entry = ins->use; entry; entry = next) {
22990 next = entry->next;
22991 if (entry->member == set) {
22994 replace_rhs_use(state, ins, convert, entry->member);
22996 fixup_branches(state, ins, convert, jmp_op);
22999 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
23001 struct ins_template *template;
23002 struct reg_info result;
23004 if (ins->op == OP_PIECE) {
23005 index = ins->u.cval;
23006 ins = MISC(ins, 0);
23009 if (triple_is_def(state, ins)) {
23012 if (index >= zlhs) {
23013 internal_error(state, ins, "index %d out of range for %s",
23014 index, tops(ins->op));
23018 template = &ins->u.ainfo->tmpl;
23021 if (ins->template_id > LAST_TEMPLATE) {
23022 internal_error(state, ins, "bad template number %d",
23025 template = &templates[ins->template_id];
23028 result = template->lhs[index];
23029 result.regcm = arch_regcm_normalize(state, result.regcm);
23030 if (result.reg != REG_UNNEEDED) {
23031 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23033 if (result.regcm == 0) {
23034 internal_error(state, ins, "lhs %d regcm == 0", index);
23039 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23041 struct reg_info result;
23042 struct ins_template *template;
23043 if ((index > ins->rhs) ||
23044 (ins->op == OP_PIECE)) {
23045 internal_error(state, ins, "index %d out of range for %s\n",
23046 index, tops(ins->op));
23050 template = &ins->u.ainfo->tmpl;
23056 if (ins->template_id > LAST_TEMPLATE) {
23057 internal_error(state, ins, "bad template number %d",
23060 template = &templates[ins->template_id];
23063 result = template->rhs[index];
23064 result.regcm = arch_regcm_normalize(state, result.regcm);
23065 if (result.regcm == 0) {
23066 internal_error(state, ins, "rhs %d regcm == 0", index);
23071 static struct triple *mod_div(struct compile_state *state,
23072 struct triple *ins, int div_op, int index)
23074 struct triple *div, *piece0, *piece1;
23076 /* Generate the appropriate division instruction */
23077 div = post_triple(state, ins, div_op, ins->type, 0, 0);
23078 RHS(div, 0) = RHS(ins, 0);
23079 RHS(div, 1) = RHS(ins, 1);
23080 piece0 = LHS(div, 0);
23081 piece1 = LHS(div, 1);
23082 div->template_id = TEMPLATE_DIV32;
23083 use_triple(RHS(div, 0), div);
23084 use_triple(RHS(div, 1), div);
23085 use_triple(LHS(div, 0), div);
23086 use_triple(LHS(div, 1), div);
23088 /* Replate uses of ins with the appropriate piece of the div */
23089 propogate_use(state, ins, LHS(div, index));
23090 release_triple(state, ins);
23092 /* Return the address of the next instruction */
23093 return piece1->next;
23096 static int noop_adecl(struct triple *adecl)
23098 struct triple_set *use;
23099 /* It's a noop if it doesn't specify stoorage */
23100 if (adecl->lhs == 0) {
23103 /* Is the adecl used? If not it's a noop */
23104 for(use = adecl->use; use ; use = use->next) {
23105 if ((use->member->op != OP_PIECE) ||
23106 (MISC(use->member, 0) != adecl)) {
23113 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23115 struct triple *mask, *nmask, *shift;
23116 struct triple *val, *val_mask, *val_shift;
23117 struct triple *targ, *targ_mask;
23118 struct triple *new;
23119 ulong_t the_mask, the_nmask;
23121 targ = RHS(ins, 0);
23124 /* Get constant for the mask value */
23126 the_mask <<= ins->u.bitfield.size;
23128 the_mask <<= ins->u.bitfield.offset;
23129 mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23130 mask->u.cval = the_mask;
23132 /* Get the inverted mask value */
23133 the_nmask = ~the_mask;
23134 nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23135 nmask->u.cval = the_nmask;
23137 /* Get constant for the shift value */
23138 shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23139 shift->u.cval = ins->u.bitfield.offset;
23141 /* Shift and mask the source value */
23143 if (shift->u.cval != 0) {
23144 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23145 use_triple(val, val_shift);
23146 use_triple(shift, val_shift);
23148 val_mask = val_shift;
23149 if (is_signed(val->type)) {
23150 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23151 use_triple(val_shift, val_mask);
23152 use_triple(mask, val_mask);
23155 /* Mask the target value */
23156 targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23157 use_triple(targ, targ_mask);
23158 use_triple(nmask, targ_mask);
23160 /* Now combined them together */
23161 new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23162 use_triple(targ_mask, new);
23163 use_triple(val_mask, new);
23165 /* Move all of the users over to the new expression */
23166 propogate_use(state, ins, new);
23168 /* Delete the original triple */
23169 release_triple(state, ins);
23171 /* Restart the transformation at mask */
23175 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23177 struct triple *mask, *shift;
23178 struct triple *val, *val_mask, *val_shift;
23183 /* Get constant for the mask value */
23185 the_mask <<= ins->u.bitfield.size;
23187 mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23188 mask->u.cval = the_mask;
23190 /* Get constant for the right shift value */
23191 shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23192 shift->u.cval = ins->u.bitfield.offset;
23194 /* Shift arithmetic right, to correct the sign */
23196 if (shift->u.cval != 0) {
23198 if (ins->op == OP_SEXTRACT) {
23203 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23204 use_triple(val, val_shift);
23205 use_triple(shift, val_shift);
23208 /* Finally mask the value */
23209 val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23210 use_triple(val_shift, val_mask);
23211 use_triple(mask, val_mask);
23213 /* Move all of the users over to the new expression */
23214 propogate_use(state, ins, val_mask);
23216 /* Release the original instruction */
23217 release_triple(state, ins);
23223 static struct triple *transform_to_arch_instruction(
23224 struct compile_state *state, struct triple *ins)
23226 /* Transform from generic 3 address instructions
23227 * to archtecture specific instructions.
23228 * And apply architecture specific constraints to instructions.
23229 * Copies are inserted to preserve the register flexibility
23230 * of 3 address instructions.
23232 struct triple *next, *value;
23237 ins->template_id = TEMPLATE_INTCONST32;
23238 if (ins->u.cval < 256) {
23239 ins->template_id = TEMPLATE_INTCONST8;
23243 ins->template_id = TEMPLATE_INTCONST32;
23245 case OP_UNKNOWNVAL:
23246 ins->template_id = TEMPLATE_UNKNOWNVAL;
23252 ins->template_id = TEMPLATE_NOP;
23256 size = size_of(state, ins->type);
23257 value = RHS(ins, 0);
23258 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23259 ins->template_id = TEMPLATE_COPY_IMM8;
23261 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23262 ins->template_id = TEMPLATE_COPY_IMM16;
23264 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23265 ins->template_id = TEMPLATE_COPY_IMM32;
23267 else if (is_const(value)) {
23268 internal_error(state, ins, "bad constant passed to copy");
23270 else if (size <= SIZEOF_I8) {
23271 ins->template_id = TEMPLATE_COPY8_REG;
23273 else if (size <= SIZEOF_I16) {
23274 ins->template_id = TEMPLATE_COPY16_REG;
23276 else if (size <= SIZEOF_I32) {
23277 ins->template_id = TEMPLATE_COPY32_REG;
23280 internal_error(state, ins, "bad type passed to copy");
23284 size = size_of(state, ins->type);
23285 if (size <= SIZEOF_I8) {
23286 ins->template_id = TEMPLATE_PHI8;
23288 else if (size <= SIZEOF_I16) {
23289 ins->template_id = TEMPLATE_PHI16;
23291 else if (size <= SIZEOF_I32) {
23292 ins->template_id = TEMPLATE_PHI32;
23295 internal_error(state, ins, "bad type passed to phi");
23299 /* Adecls should always be treated as dead code and
23300 * removed. If we are not optimizing they may linger.
23302 if (!noop_adecl(ins)) {
23303 internal_error(state, ins, "adecl remains?");
23305 ins->template_id = TEMPLATE_NOP;
23306 next = after_lhs(state, ins);
23309 switch(ins->type->type & TYPE_MASK) {
23310 case TYPE_CHAR: case TYPE_UCHAR:
23311 ins->template_id = TEMPLATE_STORE8;
23313 case TYPE_SHORT: case TYPE_USHORT:
23314 ins->template_id = TEMPLATE_STORE16;
23316 case TYPE_INT: case TYPE_UINT:
23317 case TYPE_LONG: case TYPE_ULONG:
23319 ins->template_id = TEMPLATE_STORE32;
23322 internal_error(state, ins, "unknown type in store");
23327 switch(ins->type->type & TYPE_MASK) {
23328 case TYPE_CHAR: case TYPE_UCHAR:
23329 case TYPE_SHORT: case TYPE_USHORT:
23330 case TYPE_INT: case TYPE_UINT:
23331 case TYPE_LONG: case TYPE_ULONG:
23335 internal_error(state, ins, "unknown type in load");
23338 ins->template_id = TEMPLATE_LOAD32;
23346 ins->template_id = TEMPLATE_BINARY32_REG;
23347 if (get_imm32(ins, &RHS(ins, 1))) {
23348 ins->template_id = TEMPLATE_BINARY32_IMM;
23353 ins->template_id = TEMPLATE_DIV32;
23354 next = after_lhs(state, ins);
23357 ins->template_id = TEMPLATE_UMUL32;
23360 next = mod_div(state, ins, OP_UDIVT, 0);
23363 next = mod_div(state, ins, OP_SDIVT, 0);
23366 next = mod_div(state, ins, OP_UDIVT, 1);
23369 next = mod_div(state, ins, OP_SDIVT, 1);
23374 ins->template_id = TEMPLATE_SL32_CL;
23375 if (get_imm8(ins, &RHS(ins, 1))) {
23376 ins->template_id = TEMPLATE_SL32_IMM;
23377 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23378 typed_pre_copy(state, &uchar_type, ins, 1);
23383 ins->template_id = TEMPLATE_UNARY32;
23386 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
23389 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23392 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23395 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23398 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23401 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23404 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23407 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23410 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23413 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23416 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23419 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23423 ins->template_id = TEMPLATE_NOP;
23426 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST,
23427 RHS(ins, 0)->type, RHS(ins, 0), 0);
23430 ins->template_id = TEMPLATE_NOP;
23433 ins->template_id = TEMPLATE_RET;
23439 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23440 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23441 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23443 if (get_imm8(ins, &RHS(ins, 0))) {
23444 ins->template_id += 1;
23451 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23452 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23453 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23455 if (get_imm8(ins, &RHS(ins, 1))) {
23456 ins->template_id += 1;
23461 ins->template_id = TEMPLATE_BSF;
23464 ins->template_id = TEMPLATE_RDMSR;
23465 next = after_lhs(state, ins);
23468 ins->template_id = TEMPLATE_WRMSR;
23471 ins->template_id = TEMPLATE_NOP;
23474 ins->template_id = TEMPLATE_NOP;
23475 next = after_lhs(state, ins);
23477 /* Already transformed instructions */
23479 ins->template_id = TEMPLATE_TEST32;
23482 ins->template_id = TEMPLATE_CMP32_REG;
23483 if (get_imm32(ins, &RHS(ins, 1))) {
23484 ins->template_id = TEMPLATE_CMP32_IMM;
23488 ins->template_id = TEMPLATE_NOP;
23490 case OP_JMP_EQ: case OP_JMP_NOTEQ:
23491 case OP_JMP_SLESS: case OP_JMP_ULESS:
23492 case OP_JMP_SMORE: case OP_JMP_UMORE:
23493 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23494 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23495 ins->template_id = TEMPLATE_JMP;
23497 case OP_SET_EQ: case OP_SET_NOTEQ:
23498 case OP_SET_SLESS: case OP_SET_ULESS:
23499 case OP_SET_SMORE: case OP_SET_UMORE:
23500 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23501 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23502 ins->template_id = TEMPLATE_SET;
23505 next = x86_deposit(state, ins);
23509 next = x86_extract(state, ins);
23511 /* Unhandled instructions */
23514 internal_error(state, ins, "unhandled ins: %d %s",
23515 ins->op, tops(ins->op));
23521 static long next_label(struct compile_state *state)
23523 static long label_counter = 1000;
23524 return ++label_counter;
23526 static void generate_local_labels(struct compile_state *state)
23528 struct triple *first, *label;
23529 first = state->first;
23532 if ((label->op == OP_LABEL) ||
23533 (label->op == OP_SDECL)) {
23535 label->u.cval = next_label(state);
23541 label = label->next;
23542 } while(label != first);
23545 static int check_reg(struct compile_state *state,
23546 struct triple *triple, int classes)
23550 reg = ID_REG(triple->id);
23551 if (reg == REG_UNSET) {
23552 internal_error(state, triple, "register not set");
23554 mask = arch_reg_regcm(state, reg);
23555 if (!(classes & mask)) {
23556 internal_error(state, triple, "reg %d in wrong class",
23564 #error "Registers have renumberd fix arch_reg_str"
23566 static const char *arch_regs[] = {
23570 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23571 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23572 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23575 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23576 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
23577 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23579 static const char *arch_reg_str(int reg)
23581 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23584 return arch_regs[reg];
23587 static const char *reg(struct compile_state *state, struct triple *triple,
23591 reg = check_reg(state, triple, classes);
23592 return arch_reg_str(reg);
23595 static int arch_reg_size(int reg)
23599 if (reg == REG_EFLAGS) {
23602 else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23605 else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23608 else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23611 else if (reg == REG_EDXEAX) {
23614 else if (reg == REG_DXAX) {
23617 else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23620 else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23626 static int reg_size(struct compile_state *state, struct triple *ins)
23629 reg = ID_REG(ins->id);
23630 if (reg == REG_UNSET) {
23631 internal_error(state, ins, "register not set");
23633 return arch_reg_size(reg);
23638 const char *type_suffix(struct compile_state *state, struct type *type)
23640 const char *suffix;
23641 switch(size_of(state, type)) {
23642 case SIZEOF_I8: suffix = "b"; break;
23643 case SIZEOF_I16: suffix = "w"; break;
23644 case SIZEOF_I32: suffix = "l"; break;
23646 internal_error(state, 0, "unknown suffix");
23653 static void print_const_val(
23654 struct compile_state *state, struct triple *ins, FILE *fp)
23658 fprintf(fp, " $%ld ",
23659 (long)(ins->u.cval));
23662 if ((MISC(ins, 0)->op != OP_SDECL) &&
23663 (MISC(ins, 0)->op != OP_LABEL))
23665 internal_error(state, ins, "bad base for addrconst");
23667 if (MISC(ins, 0)->u.cval <= 0) {
23668 internal_error(state, ins, "unlabeled constant");
23670 fprintf(fp, " $L%s%lu+%lu ",
23671 state->compiler->label_prefix,
23672 (unsigned long)(MISC(ins, 0)->u.cval),
23673 (unsigned long)(ins->u.cval));
23676 internal_error(state, ins, "unknown constant type");
23681 static void print_const(struct compile_state *state,
23682 struct triple *ins, FILE *fp)
23686 switch(ins->type->type & TYPE_MASK) {
23689 fprintf(fp, ".byte 0x%02lx\n",
23690 (unsigned long)(ins->u.cval));
23694 fprintf(fp, ".short 0x%04lx\n",
23695 (unsigned long)(ins->u.cval));
23702 fprintf(fp, ".int %lu\n",
23703 (unsigned long)(ins->u.cval));
23706 fprintf(state->errout, "type: ");
23707 name_of(state->errout, ins->type);
23708 fprintf(state->errout, "\n");
23709 internal_error(state, ins, "Unknown constant type. Val: %lu",
23710 (unsigned long)(ins->u.cval));
23715 if ((MISC(ins, 0)->op != OP_SDECL) &&
23716 (MISC(ins, 0)->op != OP_LABEL)) {
23717 internal_error(state, ins, "bad base for addrconst");
23719 if (MISC(ins, 0)->u.cval <= 0) {
23720 internal_error(state, ins, "unlabeled constant");
23722 fprintf(fp, ".int L%s%lu+%lu\n",
23723 state->compiler->label_prefix,
23724 (unsigned long)(MISC(ins, 0)->u.cval),
23725 (unsigned long)(ins->u.cval));
23729 unsigned char *blob;
23731 size = size_of_in_bytes(state, ins->type);
23732 blob = ins->u.blob;
23733 for(i = 0; i < size; i++) {
23734 fprintf(fp, ".byte 0x%02x\n",
23740 internal_error(state, ins, "Unknown constant type");
23745 #define TEXT_SECTION ".rom.text"
23746 #define DATA_SECTION ".rom.data"
23748 static long get_const_pool_ref(
23749 struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23753 ref = next_label(state);
23754 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23755 fprintf(fp, ".balign %d\n", align_of_in_bytes(state, ins->type));
23756 fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23757 print_const(state, ins, fp);
23758 fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23760 fprintf(fp, ".fill %d, 1, 0\n", fill_bytes);
23762 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23766 static long get_mask_pool_ref(
23767 struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23770 if (mask == 0xff) {
23773 else if (mask == 0xffff) {
23778 internal_error(state, ins, "unhandled mask value");
23783 static void print_binary_op(struct compile_state *state,
23784 const char *op, struct triple *ins, FILE *fp)
23787 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23788 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23789 internal_error(state, ins, "invalid register assignment");
23791 if (is_const(RHS(ins, 1))) {
23792 fprintf(fp, "\t%s ", op);
23793 print_const_val(state, RHS(ins, 1), fp);
23794 fprintf(fp, ", %s\n",
23795 reg(state, RHS(ins, 0), mask));
23798 unsigned lmask, rmask;
23800 lreg = check_reg(state, RHS(ins, 0), mask);
23801 rreg = check_reg(state, RHS(ins, 1), mask);
23802 lmask = arch_reg_regcm(state, lreg);
23803 rmask = arch_reg_regcm(state, rreg);
23804 mask = lmask & rmask;
23805 fprintf(fp, "\t%s %s, %s\n",
23807 reg(state, RHS(ins, 1), mask),
23808 reg(state, RHS(ins, 0), mask));
23811 static void print_unary_op(struct compile_state *state,
23812 const char *op, struct triple *ins, FILE *fp)
23815 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23816 fprintf(fp, "\t%s %s\n",
23818 reg(state, RHS(ins, 0), mask));
23821 static void print_op_shift(struct compile_state *state,
23822 const char *op, struct triple *ins, FILE *fp)
23825 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23826 if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23827 internal_error(state, ins, "invalid register assignment");
23829 if (is_const(RHS(ins, 1))) {
23830 fprintf(fp, "\t%s ", op);
23831 print_const_val(state, RHS(ins, 1), fp);
23832 fprintf(fp, ", %s\n",
23833 reg(state, RHS(ins, 0), mask));
23836 fprintf(fp, "\t%s %s, %s\n",
23838 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23839 reg(state, RHS(ins, 0), mask));
23843 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23850 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23851 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23852 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23854 internal_error(state, ins, "not an in operation");
23858 dreg = check_reg(state, ins, mask);
23859 if (!reg_is_reg(state, dreg, REG_EAX)) {
23860 internal_error(state, ins, "dst != %%eax");
23862 if (is_const(RHS(ins, 0))) {
23863 fprintf(fp, "\t%s ", op);
23864 print_const_val(state, RHS(ins, 0), fp);
23865 fprintf(fp, ", %s\n",
23866 reg(state, ins, mask));
23870 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23871 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23872 internal_error(state, ins, "src != %%dx");
23874 fprintf(fp, "\t%s %s, %s\n",
23876 reg(state, RHS(ins, 0), REGCM_GPR16),
23877 reg(state, ins, mask));
23881 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
23888 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
23889 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
23890 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
23892 internal_error(state, ins, "not an out operation");
23896 lreg = check_reg(state, RHS(ins, 0), mask);
23897 if (!reg_is_reg(state, lreg, REG_EAX)) {
23898 internal_error(state, ins, "src != %%eax");
23900 if (is_const(RHS(ins, 1))) {
23901 fprintf(fp, "\t%s %s,",
23902 op, reg(state, RHS(ins, 0), mask));
23903 print_const_val(state, RHS(ins, 1), fp);
23908 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
23909 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23910 internal_error(state, ins, "dst != %%dx");
23912 fprintf(fp, "\t%s %s, %s\n",
23914 reg(state, RHS(ins, 0), mask),
23915 reg(state, RHS(ins, 1), REGCM_GPR16));
23919 static void print_op_move(struct compile_state *state,
23920 struct triple *ins, FILE *fp)
23922 /* op_move is complex because there are many types
23923 * of registers we can move between.
23924 * Because OP_COPY will be introduced in arbitrary locations
23925 * OP_COPY must not affect flags.
23926 * OP_CONVERT can change the flags and it is the only operation
23927 * where it is expected the types in the registers can change.
23929 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
23930 struct triple *dst, *src;
23931 if (state->arch->features & X86_NOOP_COPY) {
23934 if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
23939 internal_error(state, ins, "unknown move operation");
23942 if (reg_size(state, dst) < size_of(state, dst->type)) {
23943 internal_error(state, ins, "Invalid destination register");
23945 if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
23946 fprintf(state->errout, "src type: ");
23947 name_of(state->errout, src->type);
23948 fprintf(state->errout, "\n");
23949 fprintf(state->errout, "dst type: ");
23950 name_of(state->errout, dst->type);
23951 fprintf(state->errout, "\n");
23952 internal_error(state, ins, "Type mismatch for OP_COPY");
23955 if (!is_const(src)) {
23956 int src_reg, dst_reg;
23957 int src_regcm, dst_regcm;
23958 src_reg = ID_REG(src->id);
23959 dst_reg = ID_REG(dst->id);
23960 src_regcm = arch_reg_regcm(state, src_reg);
23961 dst_regcm = arch_reg_regcm(state, dst_reg);
23962 /* If the class is the same just move the register */
23963 if (src_regcm & dst_regcm &
23964 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
23965 if ((src_reg != dst_reg) || !omit_copy) {
23966 fprintf(fp, "\tmov %s, %s\n",
23967 reg(state, src, src_regcm),
23968 reg(state, dst, dst_regcm));
23971 /* Move 32bit to 16bit */
23972 else if ((src_regcm & REGCM_GPR32) &&
23973 (dst_regcm & REGCM_GPR16)) {
23974 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
23975 if ((src_reg != dst_reg) || !omit_copy) {
23976 fprintf(fp, "\tmovw %s, %s\n",
23977 arch_reg_str(src_reg),
23978 arch_reg_str(dst_reg));
23981 /* Move from 32bit gprs to 16bit gprs */
23982 else if ((src_regcm & REGCM_GPR32) &&
23983 (dst_regcm & REGCM_GPR16)) {
23984 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
23985 if ((src_reg != dst_reg) || !omit_copy) {
23986 fprintf(fp, "\tmov %s, %s\n",
23987 arch_reg_str(src_reg),
23988 arch_reg_str(dst_reg));
23991 /* Move 32bit to 8bit */
23992 else if ((src_regcm & REGCM_GPR32_8) &&
23993 (dst_regcm & REGCM_GPR8_LO))
23995 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
23996 if ((src_reg != dst_reg) || !omit_copy) {
23997 fprintf(fp, "\tmovb %s, %s\n",
23998 arch_reg_str(src_reg),
23999 arch_reg_str(dst_reg));
24002 /* Move 16bit to 8bit */
24003 else if ((src_regcm & REGCM_GPR16_8) &&
24004 (dst_regcm & REGCM_GPR8_LO))
24006 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24007 if ((src_reg != dst_reg) || !omit_copy) {
24008 fprintf(fp, "\tmovb %s, %s\n",
24009 arch_reg_str(src_reg),
24010 arch_reg_str(dst_reg));
24013 /* Move 8/16bit to 16/32bit */
24014 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
24015 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24017 op = is_signed(src->type)? "movsx": "movzx";
24018 fprintf(fp, "\t%s %s, %s\n",
24020 reg(state, src, src_regcm),
24021 reg(state, dst, dst_regcm));
24023 /* Move between sse registers */
24024 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24025 if ((src_reg != dst_reg) || !omit_copy) {
24026 fprintf(fp, "\tmovdqa %s, %s\n",
24027 reg(state, src, src_regcm),
24028 reg(state, dst, dst_regcm));
24031 /* Move between mmx registers */
24032 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24033 if ((src_reg != dst_reg) || !omit_copy) {
24034 fprintf(fp, "\tmovq %s, %s\n",
24035 reg(state, src, src_regcm),
24036 reg(state, dst, dst_regcm));
24039 /* Move from sse to mmx registers */
24040 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24041 fprintf(fp, "\tmovdq2q %s, %s\n",
24042 reg(state, src, src_regcm),
24043 reg(state, dst, dst_regcm));
24045 /* Move from mmx to sse registers */
24046 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24047 fprintf(fp, "\tmovq2dq %s, %s\n",
24048 reg(state, src, src_regcm),
24049 reg(state, dst, dst_regcm));
24051 /* Move between 32bit gprs & mmx/sse registers */
24052 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24053 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24054 fprintf(fp, "\tmovd %s, %s\n",
24055 reg(state, src, src_regcm),
24056 reg(state, dst, dst_regcm));
24058 /* Move from 16bit gprs & mmx/sse registers */
24059 else if ((src_regcm & REGCM_GPR16) &&
24060 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24063 op = is_signed(src->type)? "movsx":"movzx";
24064 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24065 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24067 arch_reg_str(src_reg),
24068 arch_reg_str(mid_reg),
24069 arch_reg_str(mid_reg),
24070 arch_reg_str(dst_reg));
24072 /* Move from mmx/sse registers to 16bit gprs */
24073 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24074 (dst_regcm & REGCM_GPR16)) {
24075 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24076 fprintf(fp, "\tmovd %s, %s\n",
24077 arch_reg_str(src_reg),
24078 arch_reg_str(dst_reg));
24080 /* Move from gpr to 64bit dividend */
24081 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
24082 (dst_regcm & REGCM_DIVIDEND64)) {
24083 const char *extend;
24084 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24085 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24086 arch_reg_str(src_reg),
24089 /* Move from 64bit gpr to gpr */
24090 else if ((src_regcm & REGCM_DIVIDEND64) &&
24091 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24092 if (dst_regcm & REGCM_GPR32) {
24095 else if (dst_regcm & REGCM_GPR16) {
24098 else if (dst_regcm & REGCM_GPR8_LO) {
24101 fprintf(fp, "\tmov %s, %s\n",
24102 arch_reg_str(src_reg),
24103 arch_reg_str(dst_reg));
24105 /* Move from mmx/sse registers to 64bit gpr */
24106 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24107 (dst_regcm & REGCM_DIVIDEND64)) {
24108 const char *extend;
24109 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24110 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24111 arch_reg_str(src_reg),
24114 /* Move from 64bit gpr to mmx/sse register */
24115 else if ((src_regcm & REGCM_DIVIDEND64) &&
24116 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24117 fprintf(fp, "\tmovd %%eax, %s\n",
24118 arch_reg_str(dst_reg));
24120 #if X86_4_8BIT_GPRS
24121 /* Move from 8bit gprs to mmx/sse registers */
24122 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24123 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24126 op = is_signed(src->type)? "movsx":"movzx";
24127 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24128 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24130 reg(state, src, src_regcm),
24131 arch_reg_str(mid_reg),
24132 arch_reg_str(mid_reg),
24133 reg(state, dst, dst_regcm));
24135 /* Move from mmx/sse registers and 8bit gprs */
24136 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24137 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24139 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24140 fprintf(fp, "\tmovd %s, %s\n",
24141 reg(state, src, src_regcm),
24142 arch_reg_str(mid_reg));
24144 /* Move from 32bit gprs to 8bit gprs */
24145 else if ((src_regcm & REGCM_GPR32) &&
24146 (dst_regcm & REGCM_GPR8_LO)) {
24147 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24148 if ((src_reg != dst_reg) || !omit_copy) {
24149 fprintf(fp, "\tmov %s, %s\n",
24150 arch_reg_str(src_reg),
24151 arch_reg_str(dst_reg));
24154 /* Move from 16bit gprs to 8bit gprs */
24155 else if ((src_regcm & REGCM_GPR16) &&
24156 (dst_regcm & REGCM_GPR8_LO)) {
24157 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24158 if ((src_reg != dst_reg) || !omit_copy) {
24159 fprintf(fp, "\tmov %s, %s\n",
24160 arch_reg_str(src_reg),
24161 arch_reg_str(dst_reg));
24164 #endif /* X86_4_8BIT_GPRS */
24166 if ((src_regcm & ~REGCM_FLAGS) == 0) {
24167 internal_error(state, ins, "attempt to copy from %%eflags!");
24169 internal_error(state, ins, "unknown copy type");
24176 dst_size = size_of(state, dst->type);
24177 dst_reg = ID_REG(dst->id);
24178 dst_regcm = arch_reg_regcm(state, dst_reg);
24179 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24180 fprintf(fp, "\tmov ");
24181 print_const_val(state, src, fp);
24182 fprintf(fp, ", %s\n",
24183 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24185 else if (dst_regcm & REGCM_DIVIDEND64) {
24186 if (dst_size > SIZEOF_I32) {
24187 internal_error(state, ins, "%dbit constant...", dst_size);
24189 fprintf(fp, "\tmov $0, %%edx\n");
24190 fprintf(fp, "\tmov ");
24191 print_const_val(state, src, fp);
24192 fprintf(fp, ", %%eax\n");
24194 else if (dst_regcm & REGCM_DIVIDEND32) {
24195 if (dst_size > SIZEOF_I16) {
24196 internal_error(state, ins, "%dbit constant...", dst_size);
24198 fprintf(fp, "\tmov $0, %%dx\n");
24199 fprintf(fp, "\tmov ");
24200 print_const_val(state, src, fp);
24201 fprintf(fp, ", %%ax");
24203 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24205 if (dst_size > SIZEOF_I32) {
24206 internal_error(state, ins, "%d bit constant...", dst_size);
24208 ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24209 fprintf(fp, "\tmovd L%s%lu, %s\n",
24210 state->compiler->label_prefix, ref,
24211 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24214 internal_error(state, ins, "unknown copy immediate type");
24217 /* Leave now if this is not a type conversion */
24218 if (ins->op != OP_CONVERT) {
24221 /* Now make certain I have not logically overflowed the destination */
24222 if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24223 (size_of(state, dst->type) < reg_size(state, dst)))
24225 unsigned long mask;
24228 if (size_of(state, dst->type) >= 32) {
24229 fprintf(state->errout, "dst type: ");
24230 name_of(state->errout, dst->type);
24231 fprintf(state->errout, "\n");
24232 internal_error(state, dst, "unhandled dst type size");
24235 mask <<= size_of(state, dst->type);
24238 dst_reg = ID_REG(dst->id);
24239 dst_regcm = arch_reg_regcm(state, dst_reg);
24241 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24242 fprintf(fp, "\tand $0x%lx, %s\n",
24243 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24245 else if (dst_regcm & REGCM_MMX) {
24247 ref = get_mask_pool_ref(state, dst, mask, fp);
24248 fprintf(fp, "\tpand L%s%lu, %s\n",
24249 state->compiler->label_prefix, ref,
24250 reg(state, dst, REGCM_MMX));
24252 else if (dst_regcm & REGCM_XMM) {
24254 ref = get_mask_pool_ref(state, dst, mask, fp);
24255 fprintf(fp, "\tpand L%s%lu, %s\n",
24256 state->compiler->label_prefix, ref,
24257 reg(state, dst, REGCM_XMM));
24260 fprintf(state->errout, "dst type: ");
24261 name_of(state->errout, dst->type);
24262 fprintf(state->errout, "\n");
24263 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24264 internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24267 /* Make certain I am properly sign extended */
24268 if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24269 (is_signed(src->type)))
24271 int bits, reg_bits, shift_bits;
24275 bits = size_of(state, src->type);
24276 reg_bits = reg_size(state, dst);
24277 if (reg_bits > 32) {
24280 shift_bits = reg_bits - size_of(state, src->type);
24281 dst_reg = ID_REG(dst->id);
24282 dst_regcm = arch_reg_regcm(state, dst_reg);
24284 if (shift_bits < 0) {
24285 internal_error(state, dst, "negative shift?");
24288 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24289 fprintf(fp, "\tshl $%d, %s\n",
24291 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24292 fprintf(fp, "\tsar $%d, %s\n",
24294 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24296 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24297 fprintf(fp, "\tpslld $%d, %s\n",
24299 reg(state, dst, REGCM_MMX | REGCM_XMM));
24300 fprintf(fp, "\tpsrad $%d, %s\n",
24302 reg(state, dst, REGCM_MMX | REGCM_XMM));
24305 fprintf(state->errout, "dst type: ");
24306 name_of(state->errout, dst->type);
24307 fprintf(state->errout, "\n");
24308 fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24309 internal_error(state, dst, "failed to signed extend value");
24314 static void print_op_load(struct compile_state *state,
24315 struct triple *ins, FILE *fp)
24317 struct triple *dst, *src;
24321 if (is_const(src) || is_const(dst)) {
24322 internal_error(state, ins, "unknown load operation");
24324 switch(ins->type->type & TYPE_MASK) {
24325 case TYPE_CHAR: op = "movsbl"; break;
24326 case TYPE_UCHAR: op = "movzbl"; break;
24327 case TYPE_SHORT: op = "movswl"; break;
24328 case TYPE_USHORT: op = "movzwl"; break;
24329 case TYPE_INT: case TYPE_UINT:
24330 case TYPE_LONG: case TYPE_ULONG:
24335 internal_error(state, ins, "unknown type in load");
24336 op = "<invalid opcode>";
24339 fprintf(fp, "\t%s (%s), %s\n",
24341 reg(state, src, REGCM_GPR32),
24342 reg(state, dst, REGCM_GPR32));
24346 static void print_op_store(struct compile_state *state,
24347 struct triple *ins, FILE *fp)
24349 struct triple *dst, *src;
24352 if (is_const(src) && (src->op == OP_INTCONST)) {
24354 value = (long_t)(src->u.cval);
24355 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24356 type_suffix(state, src->type),
24358 reg(state, dst, REGCM_GPR32));
24360 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24361 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24362 type_suffix(state, src->type),
24363 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24364 (unsigned long)(dst->u.cval));
24367 if (is_const(src) || is_const(dst)) {
24368 internal_error(state, ins, "unknown store operation");
24370 fprintf(fp, "\tmov%s %s, (%s)\n",
24371 type_suffix(state, src->type),
24372 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24373 reg(state, dst, REGCM_GPR32));
24379 static void print_op_smul(struct compile_state *state,
24380 struct triple *ins, FILE *fp)
24382 if (!is_const(RHS(ins, 1))) {
24383 fprintf(fp, "\timul %s, %s\n",
24384 reg(state, RHS(ins, 1), REGCM_GPR32),
24385 reg(state, RHS(ins, 0), REGCM_GPR32));
24388 fprintf(fp, "\timul ");
24389 print_const_val(state, RHS(ins, 1), fp);
24390 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24394 static void print_op_cmp(struct compile_state *state,
24395 struct triple *ins, FILE *fp)
24399 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24400 dreg = check_reg(state, ins, REGCM_FLAGS);
24401 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24402 internal_error(state, ins, "bad dest register for cmp");
24404 if (is_const(RHS(ins, 1))) {
24405 fprintf(fp, "\tcmp ");
24406 print_const_val(state, RHS(ins, 1), fp);
24407 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24410 unsigned lmask, rmask;
24412 lreg = check_reg(state, RHS(ins, 0), mask);
24413 rreg = check_reg(state, RHS(ins, 1), mask);
24414 lmask = arch_reg_regcm(state, lreg);
24415 rmask = arch_reg_regcm(state, rreg);
24416 mask = lmask & rmask;
24417 fprintf(fp, "\tcmp %s, %s\n",
24418 reg(state, RHS(ins, 1), mask),
24419 reg(state, RHS(ins, 0), mask));
24423 static void print_op_test(struct compile_state *state,
24424 struct triple *ins, FILE *fp)
24427 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24428 fprintf(fp, "\ttest %s, %s\n",
24429 reg(state, RHS(ins, 0), mask),
24430 reg(state, RHS(ins, 0), mask));
24433 static void print_op_branch(struct compile_state *state,
24434 struct triple *branch, FILE *fp)
24436 const char *bop = "j";
24437 if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24438 if (branch->rhs != 0) {
24439 internal_error(state, branch, "jmp with condition?");
24444 struct triple *ptr;
24445 if (branch->rhs != 1) {
24446 internal_error(state, branch, "jmpcc without condition?");
24448 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24449 if ((RHS(branch, 0)->op != OP_CMP) &&
24450 (RHS(branch, 0)->op != OP_TEST)) {
24451 internal_error(state, branch, "bad branch test");
24453 #warning "FIXME I have observed instructions between the test and branch instructions"
24454 ptr = RHS(branch, 0);
24455 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24456 if (ptr->op != OP_COPY) {
24457 internal_error(state, branch, "branch does not follow test");
24460 switch(branch->op) {
24461 case OP_JMP_EQ: bop = "jz"; break;
24462 case OP_JMP_NOTEQ: bop = "jnz"; break;
24463 case OP_JMP_SLESS: bop = "jl"; break;
24464 case OP_JMP_ULESS: bop = "jb"; break;
24465 case OP_JMP_SMORE: bop = "jg"; break;
24466 case OP_JMP_UMORE: bop = "ja"; break;
24467 case OP_JMP_SLESSEQ: bop = "jle"; break;
24468 case OP_JMP_ULESSEQ: bop = "jbe"; break;
24469 case OP_JMP_SMOREEQ: bop = "jge"; break;
24470 case OP_JMP_UMOREEQ: bop = "jae"; break;
24472 internal_error(state, branch, "Invalid branch op");
24478 if (branch->op == OP_CALL) {
24479 fprintf(fp, "\t/* call */\n");
24482 fprintf(fp, "\t%s L%s%lu\n",
24484 state->compiler->label_prefix,
24485 (unsigned long)(TARG(branch, 0)->u.cval));
24488 static void print_op_ret(struct compile_state *state,
24489 struct triple *branch, FILE *fp)
24491 fprintf(fp, "\tjmp *%s\n",
24492 reg(state, RHS(branch, 0), REGCM_GPR32));
24495 static void print_op_set(struct compile_state *state,
24496 struct triple *set, FILE *fp)
24498 const char *sop = "set";
24499 if (set->rhs != 1) {
24500 internal_error(state, set, "setcc without condition?");
24502 check_reg(state, RHS(set, 0), REGCM_FLAGS);
24503 if ((RHS(set, 0)->op != OP_CMP) &&
24504 (RHS(set, 0)->op != OP_TEST)) {
24505 internal_error(state, set, "bad set test");
24507 if (RHS(set, 0)->next != set) {
24508 internal_error(state, set, "set does not follow test");
24511 case OP_SET_EQ: sop = "setz"; break;
24512 case OP_SET_NOTEQ: sop = "setnz"; break;
24513 case OP_SET_SLESS: sop = "setl"; break;
24514 case OP_SET_ULESS: sop = "setb"; break;
24515 case OP_SET_SMORE: sop = "setg"; break;
24516 case OP_SET_UMORE: sop = "seta"; break;
24517 case OP_SET_SLESSEQ: sop = "setle"; break;
24518 case OP_SET_ULESSEQ: sop = "setbe"; break;
24519 case OP_SET_SMOREEQ: sop = "setge"; break;
24520 case OP_SET_UMOREEQ: sop = "setae"; break;
24522 internal_error(state, set, "Invalid set op");
24525 fprintf(fp, "\t%s %s\n",
24526 sop, reg(state, set, REGCM_GPR8_LO));
24529 static void print_op_bit_scan(struct compile_state *state,
24530 struct triple *ins, FILE *fp)
24534 case OP_BSF: op = "bsf"; break;
24535 case OP_BSR: op = "bsr"; break;
24537 internal_error(state, ins, "unknown bit scan");
24547 reg(state, RHS(ins, 0), REGCM_GPR32),
24548 reg(state, ins, REGCM_GPR32),
24549 reg(state, ins, REGCM_GPR32));
24553 static void print_sdecl(struct compile_state *state,
24554 struct triple *ins, FILE *fp)
24556 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24557 fprintf(fp, ".balign %d\n", align_of_in_bytes(state, ins->type));
24558 fprintf(fp, "L%s%lu:\n",
24559 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24560 print_const(state, MISC(ins, 0), fp);
24561 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24565 static void print_instruction(struct compile_state *state,
24566 struct triple *ins, FILE *fp)
24568 /* Assumption: after I have exted the register allocator
24569 * everything is in a valid register.
24573 print_op_asm(state, ins, fp);
24575 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
24576 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
24577 case OP_AND: print_binary_op(state, "and", ins, fp); break;
24578 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
24579 case OP_OR: print_binary_op(state, "or", ins, fp); break;
24580 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
24581 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
24582 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
24583 case OP_POS: break;
24584 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
24585 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24590 /* Don't generate anything here for constants */
24592 /* Don't generate anything for variable declarations. */
24594 case OP_UNKNOWNVAL:
24595 fprintf(fp, " /* unknown %s */\n",
24596 reg(state, ins, REGCM_ALL));
24599 print_sdecl(state, ins, fp);
24603 print_op_move(state, ins, fp);
24606 print_op_load(state, ins, fp);
24609 print_op_store(state, ins, fp);
24612 print_op_smul(state, ins, fp);
24614 case OP_CMP: print_op_cmp(state, ins, fp); break;
24615 case OP_TEST: print_op_test(state, ins, fp); break;
24617 case OP_JMP_EQ: case OP_JMP_NOTEQ:
24618 case OP_JMP_SLESS: case OP_JMP_ULESS:
24619 case OP_JMP_SMORE: case OP_JMP_UMORE:
24620 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24621 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24623 print_op_branch(state, ins, fp);
24626 print_op_ret(state, ins, fp);
24628 case OP_SET_EQ: case OP_SET_NOTEQ:
24629 case OP_SET_SLESS: case OP_SET_ULESS:
24630 case OP_SET_SMORE: case OP_SET_UMORE:
24631 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24632 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24633 print_op_set(state, ins, fp);
24635 case OP_INB: case OP_INW: case OP_INL:
24636 print_op_in(state, ins, fp);
24638 case OP_OUTB: case OP_OUTW: case OP_OUTL:
24639 print_op_out(state, ins, fp);
24643 print_op_bit_scan(state, ins, fp);
24646 after_lhs(state, ins);
24647 fprintf(fp, "\trdmsr\n");
24650 fprintf(fp, "\twrmsr\n");
24653 fprintf(fp, "\thlt\n");
24656 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24659 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24662 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24668 fprintf(fp, "L%s%lu:\n",
24669 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24672 /* Ignore adecls with no registers error otherwise */
24673 if (!noop_adecl(ins)) {
24674 internal_error(state, ins, "adecl remains?");
24677 /* Ignore OP_PIECE */
24680 /* Operations that should never get here */
24681 case OP_SDIV: case OP_UDIV:
24682 case OP_SMOD: case OP_UMOD:
24683 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
24684 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
24685 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24687 internal_error(state, ins, "unknown op: %d %s",
24688 ins->op, tops(ins->op));
24693 static void print_instructions(struct compile_state *state)
24695 struct triple *first, *ins;
24696 int print_location;
24697 struct occurance *last_occurance;
24699 int max_inline_depth;
24700 max_inline_depth = 0;
24701 print_location = 1;
24702 last_occurance = 0;
24703 fp = state->output;
24704 /* Masks for common sizes */
24705 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24706 fprintf(fp, ".balign 16\n");
24707 fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24708 fprintf(fp, ".int 0xff, 0, 0, 0\n");
24709 fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24710 fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24711 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24712 first = state->first;
24715 if (print_location &&
24716 last_occurance != ins->occurance) {
24717 if (!ins->occurance->parent) {
24718 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24719 ins->occurance->function,
24720 ins->occurance->filename,
24721 ins->occurance->line,
24722 ins->occurance->col);
24725 struct occurance *ptr;
24727 fprintf(fp, "\t/*\n");
24729 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24731 fprintf(fp, "\t * %s,%s:%d.%d\n",
24737 fprintf(fp, "\t */\n");
24738 if (inline_depth > max_inline_depth) {
24739 max_inline_depth = inline_depth;
24742 if (last_occurance) {
24743 put_occurance(last_occurance);
24745 get_occurance(ins->occurance);
24746 last_occurance = ins->occurance;
24749 print_instruction(state, ins, fp);
24751 } while(ins != first);
24752 if (print_location) {
24753 fprintf(fp, "/* max inline depth %d */\n",
24758 static void generate_code(struct compile_state *state)
24760 generate_local_labels(state);
24761 print_instructions(state);
24765 static void print_preprocessed_tokens(struct compile_state *state)
24771 const char *filename;
24772 fp = state->output;
24773 tk = &state->token[0];
24777 const char *token_str;
24779 if (tok == TOK_EOF) {
24784 tk->ident ? tk->ident->name :
24785 tk->str_len ? tk->val.str :
24788 if ((state->file->line != line) ||
24789 (state->file->basename != filename)) {
24791 if ((state->file->basename == filename) &&
24792 (line < state->file->line)) {
24793 while(line < state->file->line) {
24799 fprintf(fp, "\n#line %d \"%s\"\n",
24800 state->file->line, state->file->basename);
24802 line = state->file->line;
24803 filename = state->file->basename;
24804 col = get_col(state->file) - strlen(token_str);
24805 for(i = 0; i < col; i++) {
24810 fprintf(fp, "%s ", token_str);
24812 if (state->compiler->debug & DEBUG_TOKENS) {
24813 loc(state->dbgout, state, 0);
24814 fprintf(state->dbgout, "%s <- `%s'\n",
24815 tokens[tok], token_str);
24820 static void compile(const char *filename,
24821 struct compiler_state *compiler, struct arch_state *arch)
24824 struct compile_state state;
24825 struct triple *ptr;
24826 memset(&state, 0, sizeof(state));
24827 state.compiler = compiler;
24830 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24831 memset(&state.token[i], 0, sizeof(state.token[i]));
24832 state.token[i].tok = -1;
24834 /* Remember the output descriptors */
24835 state.errout = stderr;
24836 state.dbgout = stdout;
24837 /* Remember the output filename */
24838 state.output = fopen(state.compiler->ofilename, "w");
24839 if (!state.output) {
24840 error(&state, 0, "Cannot open output file %s\n",
24841 state.compiler->ofilename);
24843 /* Make certain a good cleanup happens */
24844 exit_state = &state;
24845 atexit(exit_cleanup);
24847 /* Prep the preprocessor */
24848 state.if_depth = 0;
24849 memset(state.if_bytes, 0, sizeof(state.if_bytes));
24850 /* register the C keywords */
24851 register_keywords(&state);
24852 /* register the keywords the macro preprocessor knows */
24853 register_macro_keywords(&state);
24854 /* generate some builtin macros */
24855 register_builtin_macros(&state);
24856 /* Memorize where some special keywords are. */
24857 state.i_switch = lookup(&state, "switch", 6);
24858 state.i_case = lookup(&state, "case", 4);
24859 state.i_continue = lookup(&state, "continue", 8);
24860 state.i_break = lookup(&state, "break", 5);
24861 state.i_default = lookup(&state, "default", 7);
24862 state.i_return = lookup(&state, "return", 6);
24863 /* Memorize where predefined macros are. */
24864 state.i_defined = lookup(&state, "defined", 7);
24865 state.i___VA_ARGS__ = lookup(&state, "__VA_ARGS__", 11);
24866 state.i___FILE__ = lookup(&state, "__FILE__", 8);
24867 state.i___LINE__ = lookup(&state, "__LINE__", 8);
24868 /* Memorize where predefined identifiers are. */
24869 state.i___func__ = lookup(&state, "__func__", 8);
24870 /* Memorize where some attribute keywords are. */
24871 state.i_noinline = lookup(&state, "noinline", 8);
24872 state.i_always_inline = lookup(&state, "always_inline", 13);
24874 /* Process the command line macros */
24875 process_cmdline_macros(&state);
24877 /* Allocate beginning bounding labels for the function list */
24878 state.first = label(&state);
24879 state.first->id |= TRIPLE_FLAG_VOLATILE;
24880 use_triple(state.first, state.first);
24881 ptr = label(&state);
24882 ptr->id |= TRIPLE_FLAG_VOLATILE;
24883 use_triple(ptr, ptr);
24884 flatten(&state, state.first, ptr);
24886 /* Allocate a label for the pool of global variables */
24887 state.global_pool = label(&state);
24888 state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
24889 flatten(&state, state.first, state.global_pool);
24891 /* Enter the globl definition scope */
24892 start_scope(&state);
24893 register_builtins(&state);
24894 compile_file(&state, filename, 1);
24896 /* Stop if all we want is preprocessor output */
24897 if (state.compiler->flags & COMPILER_CPP_ONLY) {
24898 print_preprocessed_tokens(&state);
24904 /* Exit the global definition scope */
24907 /* Now that basic compilation has happened
24908 * optimize the intermediate code
24912 generate_code(&state);
24913 if (state.compiler->debug) {
24914 fprintf(state.errout, "done\n");
24919 static void version(FILE *fp)
24921 fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
24924 static void usage(void)
24929 "\nUsage: romcc [options] <source>.c\n"
24930 "Compile a C source file generating a binary that does not implicilty use RAM\n"
24932 "-o <output file name>\n"
24933 "-f<option> Specify a generic compiler option\n"
24934 "-m<option> Specify a arch dependent option\n"
24935 "-- Specify this is the last option\n"
24936 "\nGeneric compiler options:\n"
24938 compiler_usage(fp);
24940 "\nArchitecture compiler options:\n"
24948 static void arg_error(char *fmt, ...)
24951 va_start(args, fmt);
24952 vfprintf(stderr, fmt, args);
24958 int main(int argc, char **argv)
24960 const char *filename;
24961 struct compiler_state compiler;
24962 struct arch_state arch;
24966 /* I don't want any surprises */
24967 setlocale(LC_ALL, "C");
24969 init_compiler_state(&compiler);
24970 init_arch_state(&arch);
24974 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
24975 compiler.ofilename = argv[2];
24979 else if (!all_opts && argv[1][0] == '-') {
24982 if (strcmp(argv[1], "--") == 0) {
24986 else if (strncmp(argv[1], "-E", 2) == 0) {
24987 result = compiler_encode_flag(&compiler, argv[1]);
24989 else if (strncmp(argv[1], "-O", 2) == 0) {
24990 result = compiler_encode_flag(&compiler, argv[1]);
24992 else if (strncmp(argv[1], "-I", 2) == 0) {
24993 result = compiler_encode_flag(&compiler, argv[1]);
24995 else if (strncmp(argv[1], "-D", 2) == 0) {
24996 result = compiler_encode_flag(&compiler, argv[1]);
24998 else if (strncmp(argv[1], "-U", 2) == 0) {
24999 result = compiler_encode_flag(&compiler, argv[1]);
25001 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25002 result = compiler_encode_flag(&compiler, argv[1]+2);
25004 else if (strncmp(argv[1], "-f", 2) == 0) {
25005 result = compiler_encode_flag(&compiler, argv[1]+2);
25007 else if (strncmp(argv[1], "-m", 2) == 0) {
25008 result = arch_encode_flag(&arch, argv[1]+2);
25011 arg_error("Invalid option specified: %s\n",
25019 arg_error("Only one filename may be specified\n");
25021 filename = argv[1];
25027 arg_error("No filename specified\n");
25029 compile(filename, &compiler, &arch);