14 #define DEBUG_ERROR_MESSAGES 0
15 #define DEBUG_COLOR_GRAPH 0
17 #define DEBUG_CONSISTENCY 2
18 #define DEBUG_RANGE_CONFLICTS 0
19 #define DEBUG_COALESCING 0
20 #define DEBUG_SDP_BLOCKS 0
21 #define DEBUG_TRIPLE_COLOR 0
23 #warning "FIXME boundary cases with small types in larger registers"
24 #warning "FIXME give clear error messages about unused variables"
25 #warning "FIXME properly handle multi dimensional arrays"
27 /* Control flow graph of a loop without goto.
38 * |\ GGG HHH | continue;
66 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
67 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
70 * [] == DFlocal(X) U DF(X)
73 * Dominator graph of the same nodes.
77 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
79 * CCC CCC: [ ] ( BBB, JJJ )
81 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
83 * FFF FFF: [ ] ( BBB )
85 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
90 * BBB and JJJ are definitely the dominance frontier.
91 * Where do I place phi functions and how do I make that decision.
94 static void die(char *fmt, ...)
99 vfprintf(stderr, fmt, args);
106 #define MALLOC_STRONG_DEBUG
107 static void *xmalloc(size_t size, const char *name)
112 die("Cannot malloc %ld bytes to hold %s: %s\n",
113 size + 0UL, name, strerror(errno));
118 static void *xcmalloc(size_t size, const char *name)
121 buf = xmalloc(size, name);
122 memset(buf, 0, size);
126 static void xfree(const void *ptr)
131 static char *xstrdup(const char *str)
136 new = xmalloc(len + 1, "xstrdup string");
137 memcpy(new, str, len);
142 static void xchdir(const char *path)
144 if (chdir(path) != 0) {
145 die("chdir to %s failed: %s\n",
146 path, strerror(errno));
150 static int exists(const char *dirname, const char *filename)
154 if (access(filename, O_RDONLY) < 0) {
155 if ((errno != EACCES) && (errno != EROFS)) {
163 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
167 off_t size, progress;
176 fd = open(filename, O_RDONLY);
178 die("Cannot open '%s' : %s\n",
179 filename, strerror(errno));
181 result = fstat(fd, &stats);
183 die("Cannot stat: %s: %s\n",
184 filename, strerror(errno));
186 size = stats.st_size;
188 buf = xmalloc(size +2, filename);
189 buf[size] = '\n'; /* Make certain the file is newline terminated */
190 buf[size+1] = '\0'; /* Null terminate the file for good measure */
192 while(progress < size) {
193 result = read(fd, buf + progress, size - progress);
195 if ((errno == EINTR) || (errno == EAGAIN))
197 die("read on %s of %ld bytes failed: %s\n",
198 filename, (size - progress)+ 0UL, strerror(errno));
204 die("Close of %s failed: %s\n",
205 filename, strerror(errno));
210 /* Long on the destination platform */
211 typedef unsigned long ulong_t;
215 struct file_state *prev;
216 const char *basename;
224 const char *report_name;
225 const char *report_dir;
230 struct hash_entry *ident;
238 /* I have two classes of types:
240 * Logical types. (The type the C standard says the operation is of)
242 * The operational types are:
257 * No memory is useable by the compiler.
258 * There is no floating point support.
259 * All operations take place in general purpose registers.
260 * There is one type of general purpose register.
261 * Unsigned longs are stored in that general purpose register.
264 /* Operations on general purpose registers.
283 #define OP_POS 16 /* Dummy positive operator don't use it */
293 #define OP_SLESSEQ 26
294 #define OP_ULESSEQ 27
295 #define OP_SMOREEQ 28
296 #define OP_UMOREEQ 29
298 #define OP_LFALSE 30 /* Test if the expression is logically false */
299 #define OP_LTRUE 31 /* Test if the expression is logcially true */
303 /* For OP_STORE ->type holds the type
304 * RHS(0) holds the destination address
305 * RHS(1) holds the value to store.
310 #define OP_MIN_CONST 50
311 #define OP_MAX_CONST 59
312 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
313 #define OP_INTCONST 50
314 /* For OP_INTCONST ->type holds the type.
315 * ->u.cval holds the constant value.
317 #define OP_BLOBCONST 51
318 /* For OP_BLOBCONST ->type holds the layout and size
319 * information. u.blob holds a pointer to the raw binary
320 * data for the constant initializer.
322 #define OP_ADDRCONST 52
323 /* For OP_ADDRCONST ->type holds the type.
324 * MISC(0) holds the reference to the static variable.
325 * ->u.cval holds an offset from that value.
329 /* OP_WRITE moves one pseudo register to another.
330 * RHS(0) holds the destination pseudo register, which must be an OP_DECL.
331 * RHS(1) holds the psuedo to move.
335 /* OP_READ reads the value of a variable and makes
336 * it available for the pseudo operation.
337 * Useful for things like def-use chains.
338 * RHS(0) holds points to the triple to read from.
341 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
344 /* OP_PIECE returns one piece of a instruction that returns a structure.
345 * MISC(0) is the instruction
346 * u.cval is the LHS piece of the instruction to return.
349 /* OP_ASM holds a sequence of assembly instructions, the result
350 * of a C asm directive.
351 * RHS(x) holds input value x to the assembly sequence.
352 * LHS(x) holds the output value x from the assembly sequence.
353 * u.blob holds the string of assembly instructions.
357 /* OP_DEREF generates an lvalue from a pointer.
358 * RHS(0) holds the pointer value.
359 * OP_DEREF serves as a place holder to indicate all necessary
360 * checks have been done to indicate a value is an lvalue.
363 /* OP_DOT references a submember of a structure lvalue.
364 * RHS(0) holds the lvalue.
365 * ->u.field holds the name of the field we want.
367 * Not seen outside of expressions.
370 /* OP_VAL returns the value of a subexpression of the current expression.
371 * Useful for operators that have side effects.
372 * RHS(0) holds the expression.
373 * MISC(0) holds the subexpression of RHS(0) that is the
374 * value of the expression.
376 * Not seen outside of expressions.
379 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
380 * Not seen outside of expressions.
383 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
384 * Not seen outside of expressions.
387 /* OP_CODE performas a C ? : operation.
388 * RHS(0) holds the test.
389 * RHS(1) holds the expression to evaluate if the test returns true.
390 * RHS(2) holds the expression to evaluate if the test returns false.
391 * Not seen outside of expressions.
394 /* OP_COMMA performacs a C comma operation.
395 * That is RHS(0) is evaluated, then RHS(1)
396 * and the value of RHS(1) is returned.
397 * Not seen outside of expressions.
401 /* OP_CALL performs a procedure call.
402 * MISC(0) holds a pointer to the OP_LIST of a function
403 * RHS(x) holds argument x of a function
405 * Currently not seen outside of expressions.
407 #define OP_VAL_VEC 74
408 /* OP_VAL_VEC is an array of triples that are either variable
409 * or values for a structure or an array.
410 * RHS(x) holds element x of the vector.
411 * triple->type->elements holds the size of the vector.
416 /* OP_LIST Holds a list of statements, and a result value.
417 * RHS(0) holds the list of statements.
418 * MISC(0) holds the value of the statements.
421 #define OP_BRANCH 81 /* branch */
422 /* For branch instructions
423 * TARG(0) holds the branch target.
424 * RHS(0) if present holds the branch condition.
425 * ->next holds where to branch to if the branch is not taken.
426 * The branch target can only be a decl...
430 /* OP_LABEL is a triple that establishes an target for branches.
431 * ->use is the list of all branches that use this label.
435 /* OP_DECL is a triple that establishes an lvalue for assignments.
436 * ->use is a list of statements that use the variable.
440 /* OP_SDECL is a triple that establishes a variable of static
442 * ->use is a list of statements that use the variable.
443 * MISC(0) holds the initializer expression.
448 /* OP_PHI is a triple used in SSA form code.
449 * It is used when multiple code paths merge and a variable needs
450 * a single assignment from any of those code paths.
451 * The operation is a cross between OP_DECL and OP_WRITE, which
452 * is what OP_PHI is geneared from.
454 * RHS(x) points to the value from code path x
455 * The number of RHS entries is the number of control paths into the block
456 * in which OP_PHI resides. The elements of the array point to point
457 * to the variables OP_PHI is derived from.
459 * MISC(0) holds a pointer to the orginal OP_DECL node.
462 /* Architecture specific instructions */
465 #define OP_SET_EQ 102
466 #define OP_SET_NOTEQ 103
467 #define OP_SET_SLESS 104
468 #define OP_SET_ULESS 105
469 #define OP_SET_SMORE 106
470 #define OP_SET_UMORE 107
471 #define OP_SET_SLESSEQ 108
472 #define OP_SET_ULESSEQ 109
473 #define OP_SET_SMOREEQ 110
474 #define OP_SET_UMOREEQ 111
477 #define OP_JMP_EQ 113
478 #define OP_JMP_NOTEQ 114
479 #define OP_JMP_SLESS 115
480 #define OP_JMP_ULESS 116
481 #define OP_JMP_SMORE 117
482 #define OP_JMP_UMORE 118
483 #define OP_JMP_SLESSEQ 119
484 #define OP_JMP_ULESSEQ 120
485 #define OP_JMP_SMOREEQ 121
486 #define OP_JMP_UMOREEQ 122
488 /* Builtin operators that it is just simpler to use the compiler for */
506 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
508 #define BLOCK 8 /* Triple stores the current block */
509 unsigned char lhs, rhs, misc, targ;
512 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
520 static const struct op_info table_ops[] = {
521 [OP_SDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "sdivt"),
522 [OP_UDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "udivt"),
523 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
524 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
525 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
526 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
527 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
528 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
529 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
530 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
531 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
532 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
533 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
534 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
535 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
536 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
537 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
538 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
539 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
541 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
542 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
543 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
544 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
545 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
546 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
547 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
548 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
549 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
550 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
551 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
552 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
554 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "load"),
555 [OP_STORE ] = OP( 0, 2, 0, 0, IMPURE | BLOCK , "store"),
557 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK, "noop"),
559 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
560 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
561 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
563 [OP_WRITE ] = OP( 0, 2, 0, 0, PURE | BLOCK, "write"),
564 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
565 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
566 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF, "piece"),
567 [OP_ASM ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
568 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
569 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "dot"),
571 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
572 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "land"),
573 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "lor"),
574 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF | BLOCK, "cond"),
575 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "comma"),
576 /* Call is special most it can stand in for anything so it depends on context */
577 [OP_CALL ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
578 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
579 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
581 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
582 /* The number of targets for OP_BRANCH depends on context */
583 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
584 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "label"),
585 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "adecl"),
586 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK, "sdecl"),
587 /* The number of RHS elements of OP_PHI depend upon context */
588 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
590 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
591 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
592 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
593 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
594 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
595 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
596 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
597 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
598 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
599 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
600 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
601 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
602 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK, "jmp"),
603 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_eq"),
604 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_noteq"),
605 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_sless"),
606 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_uless"),
607 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smore"),
608 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umore"),
609 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
610 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
611 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
612 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
614 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
615 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
616 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
617 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
618 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
619 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
620 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
621 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
622 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
623 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
624 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
627 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
629 static const char *tops(int index)
631 static const char unknown[] = "unknown op";
635 if (index > OP_MAX) {
638 return table_ops[index].name;
645 struct triple_set *next;
646 struct triple *member;
656 const char *filename;
657 const char *function;
660 struct occurance *parent;
663 struct triple *next, *prev;
664 struct triple_set *use;
667 unsigned char template_id;
668 unsigned short sizes;
669 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
670 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0xff)
671 #define TRIPLE_MISC(SIZES) (((SIZES) >> 12) & 0x03)
672 #define TRIPLE_TARG(SIZES) (((SIZES) >> 14) & 0x03)
673 #define TRIPLE_SIZE(SIZES) \
674 (TRIPLE_LHS(SIZES) + \
675 TRIPLE_RHS(SIZES) + \
676 TRIPLE_MISC(SIZES) + \
678 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
679 ((((LHS) & 0x0f) << 0) | \
680 (((RHS) & 0xff) << 4) | \
681 (((MISC) & 0x03) << 12) | \
682 (((TARG) & 0x03) << 14))
683 #define TRIPLE_LHS_OFF(SIZES) (0)
684 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
685 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
686 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
687 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
688 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
689 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
690 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
691 unsigned id; /* A scratch value and finally the register */
692 #define TRIPLE_FLAG_FLATTENED (1 << 31)
693 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
694 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
695 struct occurance *occurance;
700 struct hash_entry *field;
701 struct asm_info *ainfo;
703 struct triple *param[2];
710 struct ins_template {
711 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
715 struct ins_template tmpl;
720 struct block_set *next;
721 struct block *member;
724 struct block *work_next;
725 struct block *left, *right;
726 struct triple *first, *last;
728 struct block_set *use;
729 struct block_set *idominates;
730 struct block_set *domfrontier;
732 struct block_set *ipdominates;
733 struct block_set *ipdomfrontier;
741 struct hash_entry *ident;
748 struct hash_entry *ident;
754 struct hash_entry *next;
758 struct macro *sym_define;
759 struct symbol *sym_label;
760 struct symbol *sym_struct;
761 struct symbol *sym_ident;
764 #define HASH_TABLE_SIZE 2048
766 struct compile_state {
767 const char *label_prefix;
768 const char *ofilename;
770 struct file_state *file;
771 struct occurance *last_occurance;
772 const char *function;
773 struct token token[4];
774 struct hash_entry *hash_table[HASH_TABLE_SIZE];
775 struct hash_entry *i_continue;
776 struct hash_entry *i_break;
778 int if_depth, if_value;
780 struct file_state *macro_file;
781 struct triple *main_function;
782 struct block *first_block, *last_block;
789 /* visibility global/local */
790 /* static/auto duration */
791 /* typedef, register, inline */
793 #define STOR_MASK 0x000f
795 #define STOR_GLOBAL 0x0001
797 #define STOR_PERM 0x0002
798 /* Storage specifiers */
799 #define STOR_AUTO 0x0000
800 #define STOR_STATIC 0x0002
801 #define STOR_EXTERN 0x0003
802 #define STOR_REGISTER 0x0004
803 #define STOR_TYPEDEF 0x0008
804 #define STOR_INLINE 0x000c
807 #define QUAL_MASK 0x0070
808 #define QUAL_NONE 0x0000
809 #define QUAL_CONST 0x0010
810 #define QUAL_VOLATILE 0x0020
811 #define QUAL_RESTRICT 0x0040
814 #define TYPE_MASK 0x1f00
815 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
816 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
817 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
818 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
819 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
820 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
821 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
822 #define TYPE_DEFAULT 0x0000
823 #define TYPE_VOID 0x0100
824 #define TYPE_CHAR 0x0200
825 #define TYPE_UCHAR 0x0300
826 #define TYPE_SHORT 0x0400
827 #define TYPE_USHORT 0x0500
828 #define TYPE_INT 0x0600
829 #define TYPE_UINT 0x0700
830 #define TYPE_LONG 0x0800
831 #define TYPE_ULONG 0x0900
832 #define TYPE_LLONG 0x0a00 /* long long */
833 #define TYPE_ULLONG 0x0b00
834 #define TYPE_FLOAT 0x0c00
835 #define TYPE_DOUBLE 0x0d00
836 #define TYPE_LDOUBLE 0x0e00 /* long double */
837 #define TYPE_STRUCT 0x1000
838 #define TYPE_ENUM 0x1100
839 #define TYPE_POINTER 0x1200
841 * type->left holds the type pointed to.
843 #define TYPE_FUNCTION 0x1300
844 /* For TYPE_FUNCTION:
845 * type->left holds the return type.
846 * type->right holds the...
848 #define TYPE_PRODUCT 0x1400
849 /* TYPE_PRODUCT is a basic building block when defining structures
850 * type->left holds the type that appears first in memory.
851 * type->right holds the type that appears next in memory.
853 #define TYPE_OVERLAP 0x1500
854 /* TYPE_OVERLAP is a basic building block when defining unions
855 * type->left and type->right holds to types that overlap
856 * each other in memory.
858 #define TYPE_ARRAY 0x1600
859 /* TYPE_ARRAY is a basic building block when definitng arrays.
860 * type->left holds the type we are an array of.
861 * type-> holds the number of elements.
864 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
868 struct type *left, *right;
870 struct hash_entry *field_ident;
871 struct hash_entry *type_ident;
874 #define MAX_REGISTERS 75
875 #define MAX_REG_EQUIVS 16
876 #define REGISTER_BITS 16
877 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
878 #define TEMPLATE_BITS 7
879 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
882 #define REG_UNNEEDED 1
883 #define REG_VIRT0 (MAX_REGISTERS + 0)
884 #define REG_VIRT1 (MAX_REGISTERS + 1)
885 #define REG_VIRT2 (MAX_REGISTERS + 2)
886 #define REG_VIRT3 (MAX_REGISTERS + 3)
887 #define REG_VIRT4 (MAX_REGISTERS + 4)
888 #define REG_VIRT5 (MAX_REGISTERS + 5)
889 #define REG_VIRT6 (MAX_REGISTERS + 5)
890 #define REG_VIRT7 (MAX_REGISTERS + 5)
891 #define REG_VIRT8 (MAX_REGISTERS + 5)
892 #define REG_VIRT9 (MAX_REGISTERS + 5)
894 /* Provision for 8 register classes */
896 #define REGC_SHIFT REGISTER_BITS
897 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
898 #define REG_MASK (MAX_VIRT_REGISTERS -1)
899 #define ID_REG(ID) ((ID) & REG_MASK)
900 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
901 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
902 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
903 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
904 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
906 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
907 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
908 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
909 static void arch_reg_equivs(
910 struct compile_state *state, unsigned *equiv, int reg);
911 static int arch_select_free_register(
912 struct compile_state *state, char *used, int classes);
913 static unsigned arch_regc_size(struct compile_state *state, int class);
914 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
915 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
916 static const char *arch_reg_str(int reg);
917 static struct reg_info arch_reg_constraint(
918 struct compile_state *state, struct type *type, const char *constraint);
919 static struct reg_info arch_reg_clobber(
920 struct compile_state *state, const char *clobber);
921 static struct reg_info arch_reg_lhs(struct compile_state *state,
922 struct triple *ins, int index);
923 static struct reg_info arch_reg_rhs(struct compile_state *state,
924 struct triple *ins, int index);
925 static struct triple *transform_to_arch_instruction(
926 struct compile_state *state, struct triple *ins);
930 #define DEBUG_ABORT_ON_ERROR 0x0001
931 #define DEBUG_INTERMEDIATE_CODE 0x0002
932 #define DEBUG_CONTROL_FLOW 0x0004
933 #define DEBUG_BASIC_BLOCKS 0x0008
934 #define DEBUG_FDOMINATORS 0x0010
935 #define DEBUG_RDOMINATORS 0x0020
936 #define DEBUG_TRIPLES 0x0040
937 #define DEBUG_INTERFERENCE 0x0080
938 #define DEBUG_ARCH_CODE 0x0100
939 #define DEBUG_CODE_ELIMINATION 0x0200
940 #define DEBUG_INSERTED_COPIES 0x0400
942 #define GLOBAL_SCOPE_DEPTH 1
943 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
945 static void compile_file(struct compile_state *old_state, const char *filename, int local);
947 static void do_cleanup(struct compile_state *state)
950 fclose(state->output);
951 unlink(state->ofilename);
955 static int get_col(struct file_state *file)
959 ptr = file->line_start;
961 for(col = 0; ptr < end; ptr++) {
966 col = (col & ~7) + 8;
972 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
975 if (triple && triple->occurance) {
976 struct occurance *spot;
977 spot = triple->occurance;
978 while(spot->parent) {
981 fprintf(fp, "%s:%d.%d: ",
982 spot->filename, spot->line, spot->col);
988 col = get_col(state->file);
989 fprintf(fp, "%s:%d.%d: ",
990 state->file->report_name, state->file->report_line, col);
993 static void __internal_error(struct compile_state *state, struct triple *ptr,
998 loc(stderr, state, ptr);
1000 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
1002 fprintf(stderr, "Internal compiler error: ");
1003 vfprintf(stderr, fmt, args);
1004 fprintf(stderr, "\n");
1011 static void __internal_warning(struct compile_state *state, struct triple *ptr,
1015 va_start(args, fmt);
1016 loc(stderr, state, ptr);
1018 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
1020 fprintf(stderr, "Internal compiler warning: ");
1021 vfprintf(stderr, fmt, args);
1022 fprintf(stderr, "\n");
1028 static void __error(struct compile_state *state, struct triple *ptr,
1032 va_start(args, fmt);
1033 loc(stderr, state, ptr);
1034 vfprintf(stderr, fmt, args);
1036 fprintf(stderr, "\n");
1038 if (state->debug & DEBUG_ABORT_ON_ERROR) {
1044 static void __warning(struct compile_state *state, struct triple *ptr,
1048 va_start(args, fmt);
1049 loc(stderr, state, ptr);
1050 fprintf(stderr, "warning: ");
1051 vfprintf(stderr, fmt, args);
1052 fprintf(stderr, "\n");
1056 #if DEBUG_ERROR_MESSAGES
1057 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1058 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1059 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1060 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1062 # define internal_error __internal_error
1063 # define internal_warning __internal_warning
1064 # define error __error
1065 # define warning __warning
1067 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1069 static void valid_op(struct compile_state *state, int op)
1071 char *fmt = "invalid op: %d";
1073 internal_error(state, 0, fmt, op);
1076 internal_error(state, 0, fmt, op);
1080 static void valid_ins(struct compile_state *state, struct triple *ptr)
1082 valid_op(state, ptr->op);
1085 static void process_trigraphs(struct compile_state *state)
1087 char *src, *dest, *end;
1088 struct file_state *file;
1090 src = dest = file->buf;
1091 end = file->buf + file->size;
1092 while((end - src) >= 3) {
1093 if ((src[0] == '?') && (src[1] == '?')) {
1096 case '=': c = '#'; break;
1097 case '/': c = '\\'; break;
1098 case '\'': c = '^'; break;
1099 case '(': c = '['; break;
1100 case ')': c = ']'; break;
1101 case '!': c = '!'; break;
1102 case '<': c = '{'; break;
1103 case '>': c = '}'; break;
1104 case '-': c = '~'; break;
1121 file->size = dest - file->buf;
1124 static void splice_lines(struct compile_state *state)
1126 char *src, *dest, *end;
1127 struct file_state *file;
1129 src = dest = file->buf;
1130 end = file->buf + file->size;
1131 while((end - src) >= 2) {
1132 if ((src[0] == '\\') && (src[1] == '\n')) {
1142 file->size = dest - file->buf;
1145 static struct type void_type;
1146 static void use_triple(struct triple *used, struct triple *user)
1148 struct triple_set **ptr, *new;
1155 if ((*ptr)->member == user) {
1158 ptr = &(*ptr)->next;
1160 /* Append new to the head of the list,
1161 * copy_func and rename_block_variables
1164 new = xcmalloc(sizeof(*new), "triple_set");
1166 new->next = used->use;
1170 static void unuse_triple(struct triple *used, struct triple *unuser)
1172 struct triple_set *use, **ptr;
1179 if (use->member == unuser) {
1189 static void put_occurance(struct occurance *occurance)
1191 occurance->count -= 1;
1192 if (occurance->count <= 0) {
1193 if (occurance->parent) {
1194 put_occurance(occurance->parent);
1200 static void get_occurance(struct occurance *occurance)
1202 occurance->count += 1;
1206 static struct occurance *new_occurance(struct compile_state *state)
1208 struct occurance *result, *last;
1209 const char *filename;
1210 const char *function;
1218 filename = state->file->report_name;
1219 line = state->file->report_line;
1220 col = get_col(state->file);
1222 if (state->function) {
1223 function = state->function;
1225 last = state->last_occurance;
1227 (last->col == col) &&
1228 (last->line == line) &&
1229 (last->function == function) &&
1230 (strcmp(last->filename, filename) == 0)) {
1231 get_occurance(last);
1235 state->last_occurance = 0;
1236 put_occurance(last);
1238 result = xmalloc(sizeof(*result), "occurance");
1240 result->filename = filename;
1241 result->function = function;
1242 result->line = line;
1245 state->last_occurance = result;
1249 static struct occurance *inline_occurance(struct compile_state *state,
1250 struct occurance *new, struct occurance *orig)
1252 struct occurance *result, *last;
1253 last = state->last_occurance;
1255 (last->parent == orig) &&
1256 (last->col == new->col) &&
1257 (last->line == new->line) &&
1258 (last->function == new->function) &&
1259 (last->filename == new->filename)) {
1260 get_occurance(last);
1264 state->last_occurance = 0;
1265 put_occurance(last);
1267 get_occurance(orig);
1268 result = xmalloc(sizeof(*result), "occurance");
1270 result->filename = new->filename;
1271 result->function = new->function;
1272 result->line = new->line;
1273 result->col = new->col;
1274 result->parent = orig;
1275 state->last_occurance = result;
1280 static struct occurance dummy_occurance = {
1282 .filename = __FILE__,
1289 /* The zero triple is used as a place holder when we are removing pointers
1290 * from a triple. Having allows certain sanity checks to pass even
1291 * when the original triple that was pointed to is gone.
1293 static struct triple zero_triple = {
1294 .next = &zero_triple,
1295 .prev = &zero_triple,
1298 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1299 .id = -1, /* An invalid id */
1300 .u = { .cval = 0, },
1301 .occurance = &dummy_occurance,
1302 .param = { [0] = 0, [1] = 0, },
1306 static unsigned short triple_sizes(struct compile_state *state,
1307 int op, struct type *type, int lhs_wanted, int rhs_wanted,
1308 struct occurance *occurance)
1310 int lhs, rhs, misc, targ;
1311 struct triple dummy;
1313 dummy.occurance = occurance;
1314 valid_op(state, op);
1315 lhs = table_ops[op].lhs;
1316 rhs = table_ops[op].rhs;
1317 misc = table_ops[op].misc;
1318 targ = table_ops[op].targ;
1321 if (op == OP_CALL) {
1324 param = type->right;
1325 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1327 param = param->right;
1329 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1333 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1334 lhs = type->left->elements;
1337 else if (op == OP_VAL_VEC) {
1338 rhs = type->elements;
1340 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1343 else if (op == OP_ASM) {
1347 if ((rhs < 0) || (rhs > MAX_RHS)) {
1348 internal_error(state, &dummy, "bad rhs %d", rhs);
1350 if ((lhs < 0) || (lhs > MAX_LHS)) {
1351 internal_error(state, &dummy, "bad lhs");
1353 if ((misc < 0) || (misc > MAX_MISC)) {
1354 internal_error(state, &dummy, "bad misc");
1356 if ((targ < 0) || (targ > MAX_TARG)) {
1357 internal_error(state, &dummy, "bad targs");
1359 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1362 static struct triple *alloc_triple(struct compile_state *state,
1363 int op, struct type *type, int lhs, int rhs,
1364 struct occurance *occurance)
1366 size_t size, sizes, extra_count, min_count;
1368 sizes = triple_sizes(state, op, type, lhs, rhs, occurance);
1370 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1371 extra_count = TRIPLE_SIZE(sizes);
1372 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1374 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1375 ret = xcmalloc(size, "tripple");
1381 ret->occurance = occurance;
1385 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1388 int src_lhs, src_rhs, src_size;
1389 src_lhs = TRIPLE_LHS(src->sizes);
1390 src_rhs = TRIPLE_RHS(src->sizes);
1391 src_size = TRIPLE_SIZE(src->sizes);
1392 get_occurance(src->occurance);
1393 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1395 memcpy(dup, src, sizeof(*src));
1396 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1400 static struct triple *new_triple(struct compile_state *state,
1401 int op, struct type *type, int lhs, int rhs)
1404 struct occurance *occurance;
1405 occurance = new_occurance(state);
1406 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1410 static struct triple *build_triple(struct compile_state *state,
1411 int op, struct type *type, struct triple *left, struct triple *right,
1412 struct occurance *occurance)
1416 ret = alloc_triple(state, op, type, -1, -1, occurance);
1417 count = TRIPLE_SIZE(ret->sizes);
1419 ret->param[0] = left;
1422 ret->param[1] = right;
1427 static struct triple *triple(struct compile_state *state,
1428 int op, struct type *type, struct triple *left, struct triple *right)
1432 ret = new_triple(state, op, type, -1, -1);
1433 count = TRIPLE_SIZE(ret->sizes);
1435 ret->param[0] = left;
1438 ret->param[1] = right;
1443 static struct triple *branch(struct compile_state *state,
1444 struct triple *targ, struct triple *test)
1447 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1451 TARG(ret, 0) = targ;
1452 /* record the branch target was used */
1453 if (!targ || (targ->op != OP_LABEL)) {
1454 internal_error(state, 0, "branch not to label");
1455 use_triple(targ, ret);
1461 static void insert_triple(struct compile_state *state,
1462 struct triple *first, struct triple *ptr)
1465 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1466 internal_error(state, ptr, "expression already used");
1469 ptr->prev = first->prev;
1470 ptr->prev->next = ptr;
1471 ptr->next->prev = ptr;
1472 if ((ptr->prev->op == OP_BRANCH) &&
1473 TRIPLE_RHS(ptr->prev->sizes)) {
1474 unuse_triple(first, ptr->prev);
1475 use_triple(ptr, ptr->prev);
1480 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1482 /* This function is used to determine if u.block
1483 * is utilized to store the current block number.
1486 valid_ins(state, ins);
1487 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1488 return stores_block;
1491 static struct block *block_of_triple(struct compile_state *state,
1494 struct triple *first;
1495 first = RHS(state->main_function, 0);
1496 while(ins != first && !triple_stores_block(state, ins)) {
1497 if (ins == ins->prev) {
1498 internal_error(state, 0, "ins == ins->prev?");
1502 if (!triple_stores_block(state, ins)) {
1503 internal_error(state, ins, "Cannot find block");
1505 return ins->u.block;
1508 static struct triple *pre_triple(struct compile_state *state,
1509 struct triple *base,
1510 int op, struct type *type, struct triple *left, struct triple *right)
1512 struct block *block;
1514 /* If I am an OP_PIECE jump to the real instruction */
1515 if (base->op == OP_PIECE) {
1516 base = MISC(base, 0);
1518 block = block_of_triple(state, base);
1519 get_occurance(base->occurance);
1520 ret = build_triple(state, op, type, left, right, base->occurance);
1521 if (triple_stores_block(state, ret)) {
1522 ret->u.block = block;
1524 insert_triple(state, base, ret);
1525 if (block->first == base) {
1531 static struct triple *post_triple(struct compile_state *state,
1532 struct triple *base,
1533 int op, struct type *type, struct triple *left, struct triple *right)
1535 struct block *block;
1538 /* If I am an OP_PIECE jump to the real instruction */
1539 if (base->op == OP_PIECE) {
1540 base = MISC(base, 0);
1542 /* If I have a left hand side skip over it */
1543 zlhs = TRIPLE_LHS(base->sizes);
1545 base = LHS(base, zlhs - 1);
1548 block = block_of_triple(state, base);
1549 get_occurance(base->occurance);
1550 ret = build_triple(state, op, type, left, right, base->occurance);
1551 if (triple_stores_block(state, ret)) {
1552 ret->u.block = block;
1554 insert_triple(state, base->next, ret);
1555 if (block->last == base) {
1561 static struct triple *label(struct compile_state *state)
1563 /* Labels don't get a type */
1564 struct triple *result;
1565 result = triple(state, OP_LABEL, &void_type, 0, 0);
1569 static void display_triple(FILE *fp, struct triple *ins)
1571 struct occurance *ptr;
1575 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1578 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1581 reg = arch_reg_str(ID_REG(ins->id));
1582 if (ins->op == OP_INTCONST) {
1583 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx> ",
1584 ins, pre, post, reg, ins->template_id, tops(ins->op),
1587 else if (ins->op == OP_ADDRCONST) {
1588 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1589 ins, pre, post, reg, ins->template_id, tops(ins->op),
1590 MISC(ins, 0), ins->u.cval);
1594 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s",
1595 ins, pre, post, reg, ins->template_id, tops(ins->op));
1596 count = TRIPLE_SIZE(ins->sizes);
1597 for(i = 0; i < count; i++) {
1598 fprintf(fp, " %-10p", ins->param[i]);
1605 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1606 fprintf(fp, " %s,%s:%d.%d",
1615 struct triple_set *user;
1616 for(user = ptr->use; user; user = user->next) {
1617 fprintf(fp, "use: %p\n", user->member);
1624 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1626 /* Does the triple have no side effects.
1627 * I.e. Rexecuting the triple with the same arguments
1628 * gives the same value.
1631 valid_ins(state, ins);
1632 pure = PURE_BITS(table_ops[ins->op].flags);
1633 if ((pure != PURE) && (pure != IMPURE)) {
1634 internal_error(state, 0, "Purity of %s not known\n",
1637 return pure == PURE;
1640 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1642 /* This function is used to determine which triples need
1646 valid_ins(state, ins);
1647 is_branch = (table_ops[ins->op].targ != 0);
1651 static int triple_is_cond_branch(struct compile_state *state, struct triple *ins)
1653 /* A conditional branch has the condition argument as a single
1656 return triple_is_branch(state, ins) &&
1657 (TRIPLE_RHS(ins->sizes) == 1);
1660 static int triple_is_uncond_branch(struct compile_state *state, struct triple *ins)
1662 /* A unconditional branch has no RHS parameters.
1664 return triple_is_branch(state, ins) &&
1665 (TRIPLE_RHS(ins->sizes) == 0);
1668 static int triple_is_def(struct compile_state *state, struct triple *ins)
1670 /* This function is used to determine which triples need
1674 valid_ins(state, ins);
1675 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1679 static struct triple **triple_iter(struct compile_state *state,
1680 size_t count, struct triple **vector,
1681 struct triple *ins, struct triple **last)
1683 struct triple **ret;
1689 else if ((last >= vector) && (last < (vector + count - 1))) {
1697 static struct triple **triple_lhs(struct compile_state *state,
1698 struct triple *ins, struct triple **last)
1700 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1704 static struct triple **triple_rhs(struct compile_state *state,
1705 struct triple *ins, struct triple **last)
1707 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1711 static struct triple **triple_misc(struct compile_state *state,
1712 struct triple *ins, struct triple **last)
1714 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1718 static struct triple **triple_targ(struct compile_state *state,
1719 struct triple *ins, struct triple **last)
1722 struct triple **ret, **vector;
1724 count = TRIPLE_TARG(ins->sizes);
1725 vector = &TARG(ins, 0);
1730 else if ((last >= vector) && (last < (vector + count - 1))) {
1733 else if ((last == (vector + count - 1)) &&
1734 TRIPLE_RHS(ins->sizes)) {
1742 static void verify_use(struct compile_state *state,
1743 struct triple *user, struct triple *used)
1746 size = TRIPLE_SIZE(user->sizes);
1747 for(i = 0; i < size; i++) {
1748 if (user->param[i] == used) {
1752 if (triple_is_branch(state, user)) {
1753 if (user->next == used) {
1758 internal_error(state, user, "%s(%p) does not use %s(%p)",
1759 tops(user->op), user, tops(used->op), used);
1763 static int find_rhs_use(struct compile_state *state,
1764 struct triple *user, struct triple *used)
1766 struct triple **param;
1768 verify_use(state, user, used);
1769 size = TRIPLE_RHS(user->sizes);
1770 param = &RHS(user, 0);
1771 for(i = 0; i < size; i++) {
1772 if (param[i] == used) {
1779 static void free_triple(struct compile_state *state, struct triple *ptr)
1782 size = sizeof(*ptr) - sizeof(ptr->param) +
1783 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1784 ptr->prev->next = ptr->next;
1785 ptr->next->prev = ptr->prev;
1787 internal_error(state, ptr, "ptr->use != 0");
1789 put_occurance(ptr->occurance);
1790 memset(ptr, -1, size);
1794 static void release_triple(struct compile_state *state, struct triple *ptr)
1796 struct triple_set *set, *next;
1797 struct triple **expr;
1798 struct block *block;
1799 /* Make certain the we are not the first or last element of a block */
1800 block = block_of_triple(state, ptr);
1801 if (block && (block->last == ptr)) {
1802 block->last = ptr->prev;
1804 if (block && (block->first == ptr)) {
1805 block->first = ptr->next;
1807 /* Remove ptr from use chains where it is the user */
1808 expr = triple_rhs(state, ptr, 0);
1809 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1811 unuse_triple(*expr, ptr);
1814 expr = triple_lhs(state, ptr, 0);
1815 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1817 unuse_triple(*expr, ptr);
1820 expr = triple_misc(state, ptr, 0);
1821 for(; expr; expr = triple_misc(state, ptr, expr)) {
1823 unuse_triple(*expr, ptr);
1826 expr = triple_targ(state, ptr, 0);
1827 for(; expr; expr = triple_targ(state, ptr, expr)) {
1829 unuse_triple(*expr, ptr);
1832 /* Reomve ptr from use chains where it is used */
1833 for(set = ptr->use; set; set = next) {
1835 expr = triple_rhs(state, set->member, 0);
1836 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1838 *expr = &zero_triple;
1841 expr = triple_lhs(state, set->member, 0);
1842 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1844 *expr = &zero_triple;
1847 expr = triple_misc(state, set->member, 0);
1848 for(; expr; expr = triple_misc(state, set->member, expr)) {
1850 *expr = &zero_triple;
1853 expr = triple_targ(state, set->member, 0);
1854 for(; expr; expr = triple_targ(state, set->member, expr)) {
1856 *expr = &zero_triple;
1859 unuse_triple(ptr, set->member);
1861 free_triple(state, ptr);
1864 static void print_triple(struct compile_state *state, struct triple *ptr);
1866 #define TOK_UNKNOWN 0
1869 #define TOK_LBRACE 3
1870 #define TOK_RBRACE 4
1874 #define TOK_LBRACKET 8
1875 #define TOK_RBRACKET 9
1876 #define TOK_LPAREN 10
1877 #define TOK_RPAREN 11
1882 #define TOK_TIMESEQ 16
1883 #define TOK_DIVEQ 17
1884 #define TOK_MODEQ 18
1885 #define TOK_PLUSEQ 19
1886 #define TOK_MINUSEQ 20
1889 #define TOK_ANDEQ 23
1890 #define TOK_XOREQ 24
1893 #define TOK_NOTEQ 27
1894 #define TOK_QUEST 28
1895 #define TOK_LOGOR 29
1896 #define TOK_LOGAND 30
1900 #define TOK_LESSEQ 34
1901 #define TOK_MOREEQ 35
1905 #define TOK_MINUS 39
1908 #define TOK_PLUSPLUS 42
1909 #define TOK_MINUSMINUS 43
1911 #define TOK_ARROW 45
1913 #define TOK_TILDE 47
1914 #define TOK_LIT_STRING 48
1915 #define TOK_LIT_CHAR 49
1916 #define TOK_LIT_INT 50
1917 #define TOK_LIT_FLOAT 51
1918 #define TOK_MACRO 52
1919 #define TOK_CONCATENATE 53
1921 #define TOK_IDENT 54
1922 #define TOK_STRUCT_NAME 55
1923 #define TOK_ENUM_CONST 56
1924 #define TOK_TYPE_NAME 57
1927 #define TOK_BREAK 59
1930 #define TOK_CONST 62
1931 #define TOK_CONTINUE 63
1932 #define TOK_DEFAULT 64
1934 #define TOK_DOUBLE 66
1937 #define TOK_EXTERN 69
1938 #define TOK_FLOAT 70
1942 #define TOK_INLINE 74
1945 #define TOK_REGISTER 77
1946 #define TOK_RESTRICT 78
1947 #define TOK_RETURN 79
1948 #define TOK_SHORT 80
1949 #define TOK_SIGNED 81
1950 #define TOK_SIZEOF 82
1951 #define TOK_STATIC 83
1952 #define TOK_STRUCT 84
1953 #define TOK_SWITCH 85
1954 #define TOK_TYPEDEF 86
1955 #define TOK_UNION 87
1956 #define TOK_UNSIGNED 88
1958 #define TOK_VOLATILE 90
1959 #define TOK_WHILE 91
1961 #define TOK_ATTRIBUTE 93
1962 #define TOK_ALIGNOF 94
1963 #define TOK_FIRST_KEYWORD TOK_AUTO
1964 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1966 #define TOK_DEFINE 100
1967 #define TOK_UNDEF 101
1968 #define TOK_INCLUDE 102
1969 #define TOK_LINE 103
1970 #define TOK_ERROR 104
1971 #define TOK_WARNING 105
1972 #define TOK_PRAGMA 106
1973 #define TOK_IFDEF 107
1974 #define TOK_IFNDEF 108
1975 #define TOK_ELIF 109
1976 #define TOK_ENDIF 110
1978 #define TOK_FIRST_MACRO TOK_DEFINE
1979 #define TOK_LAST_MACRO TOK_ENDIF
1983 static const char *tokens[] = {
1984 [TOK_UNKNOWN ] = "unknown",
1985 [TOK_SPACE ] = ":space:",
1987 [TOK_LBRACE ] = "{",
1988 [TOK_RBRACE ] = "}",
1992 [TOK_LBRACKET ] = "[",
1993 [TOK_RBRACKET ] = "]",
1994 [TOK_LPAREN ] = "(",
1995 [TOK_RPAREN ] = ")",
1997 [TOK_DOTS ] = "...",
2000 [TOK_TIMESEQ ] = "*=",
2001 [TOK_DIVEQ ] = "/=",
2002 [TOK_MODEQ ] = "%=",
2003 [TOK_PLUSEQ ] = "+=",
2004 [TOK_MINUSEQ ] = "-=",
2005 [TOK_SLEQ ] = "<<=",
2006 [TOK_SREQ ] = ">>=",
2007 [TOK_ANDEQ ] = "&=",
2008 [TOK_XOREQ ] = "^=",
2011 [TOK_NOTEQ ] = "!=",
2013 [TOK_LOGOR ] = "||",
2014 [TOK_LOGAND ] = "&&",
2018 [TOK_LESSEQ ] = "<=",
2019 [TOK_MOREEQ ] = ">=",
2026 [TOK_PLUSPLUS ] = "++",
2027 [TOK_MINUSMINUS ] = "--",
2029 [TOK_ARROW ] = "->",
2032 [TOK_LIT_STRING ] = ":string:",
2033 [TOK_IDENT ] = ":ident:",
2034 [TOK_TYPE_NAME ] = ":typename:",
2035 [TOK_LIT_CHAR ] = ":char:",
2036 [TOK_LIT_INT ] = ":integer:",
2037 [TOK_LIT_FLOAT ] = ":float:",
2039 [TOK_CONCATENATE ] = "##",
2041 [TOK_AUTO ] = "auto",
2042 [TOK_BREAK ] = "break",
2043 [TOK_CASE ] = "case",
2044 [TOK_CHAR ] = "char",
2045 [TOK_CONST ] = "const",
2046 [TOK_CONTINUE ] = "continue",
2047 [TOK_DEFAULT ] = "default",
2049 [TOK_DOUBLE ] = "double",
2050 [TOK_ELSE ] = "else",
2051 [TOK_ENUM ] = "enum",
2052 [TOK_EXTERN ] = "extern",
2053 [TOK_FLOAT ] = "float",
2055 [TOK_GOTO ] = "goto",
2057 [TOK_INLINE ] = "inline",
2059 [TOK_LONG ] = "long",
2060 [TOK_REGISTER ] = "register",
2061 [TOK_RESTRICT ] = "restrict",
2062 [TOK_RETURN ] = "return",
2063 [TOK_SHORT ] = "short",
2064 [TOK_SIGNED ] = "signed",
2065 [TOK_SIZEOF ] = "sizeof",
2066 [TOK_STATIC ] = "static",
2067 [TOK_STRUCT ] = "struct",
2068 [TOK_SWITCH ] = "switch",
2069 [TOK_TYPEDEF ] = "typedef",
2070 [TOK_UNION ] = "union",
2071 [TOK_UNSIGNED ] = "unsigned",
2072 [TOK_VOID ] = "void",
2073 [TOK_VOLATILE ] = "volatile",
2074 [TOK_WHILE ] = "while",
2076 [TOK_ATTRIBUTE ] = "__attribute__",
2077 [TOK_ALIGNOF ] = "__alignof__",
2079 [TOK_DEFINE ] = "define",
2080 [TOK_UNDEF ] = "undef",
2081 [TOK_INCLUDE ] = "include",
2082 [TOK_LINE ] = "line",
2083 [TOK_ERROR ] = "error",
2084 [TOK_WARNING ] = "warning",
2085 [TOK_PRAGMA ] = "pragma",
2086 [TOK_IFDEF ] = "ifdef",
2087 [TOK_IFNDEF ] = "ifndef",
2088 [TOK_ELIF ] = "elif",
2089 [TOK_ENDIF ] = "endif",
2094 static unsigned int hash(const char *str, int str_len)
2098 end = str + str_len;
2100 for(; str < end; str++) {
2101 hash = (hash *263) + *str;
2103 hash = hash & (HASH_TABLE_SIZE -1);
2107 static struct hash_entry *lookup(
2108 struct compile_state *state, const char *name, int name_len)
2110 struct hash_entry *entry;
2112 index = hash(name, name_len);
2113 entry = state->hash_table[index];
2115 ((entry->name_len != name_len) ||
2116 (memcmp(entry->name, name, name_len) != 0))) {
2117 entry = entry->next;
2121 /* Get a private copy of the name */
2122 new_name = xmalloc(name_len + 1, "hash_name");
2123 memcpy(new_name, name, name_len);
2124 new_name[name_len] = '\0';
2126 /* Create a new hash entry */
2127 entry = xcmalloc(sizeof(*entry), "hash_entry");
2128 entry->next = state->hash_table[index];
2129 entry->name = new_name;
2130 entry->name_len = name_len;
2132 /* Place the new entry in the hash table */
2133 state->hash_table[index] = entry;
2138 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2140 struct hash_entry *entry;
2142 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2143 (entry->tok == TOK_ENUM_CONST) ||
2144 ((entry->tok >= TOK_FIRST_KEYWORD) &&
2145 (entry->tok <= TOK_LAST_KEYWORD)))) {
2146 tk->tok = entry->tok;
2150 static void ident_to_macro(struct compile_state *state, struct token *tk)
2152 struct hash_entry *entry;
2155 (entry->tok >= TOK_FIRST_MACRO) &&
2156 (entry->tok <= TOK_LAST_MACRO)) {
2157 tk->tok = entry->tok;
2161 static void hash_keyword(
2162 struct compile_state *state, const char *keyword, int tok)
2164 struct hash_entry *entry;
2165 entry = lookup(state, keyword, strlen(keyword));
2166 if (entry && entry->tok != TOK_UNKNOWN) {
2167 die("keyword %s already hashed", keyword);
2173 struct compile_state *state, struct hash_entry *ident,
2174 struct symbol **chain, struct triple *def, struct type *type)
2177 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2178 error(state, 0, "%s already defined", ident->name);
2180 sym = xcmalloc(sizeof(*sym), "symbol");
2184 sym->scope_depth = state->scope_depth;
2189 static void label_symbol(struct compile_state *state,
2190 struct hash_entry *ident, struct triple *label)
2193 if (ident->sym_label) {
2194 error(state, 0, "label %s already defined", ident->name);
2196 sym = xcmalloc(sizeof(*sym), "label");
2199 sym->type = &void_type;
2200 sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2202 ident->sym_label = sym;
2205 static void start_scope(struct compile_state *state)
2207 state->scope_depth++;
2210 static void end_scope_syms(struct symbol **chain, int depth)
2212 struct symbol *sym, *next;
2214 while(sym && (sym->scope_depth == depth)) {
2222 static void end_scope(struct compile_state *state)
2226 /* Walk through the hash table and remove all symbols
2227 * in the current scope.
2229 depth = state->scope_depth;
2230 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2231 struct hash_entry *entry;
2232 entry = state->hash_table[i];
2234 end_scope_syms(&entry->sym_label, depth);
2235 end_scope_syms(&entry->sym_struct, depth);
2236 end_scope_syms(&entry->sym_ident, depth);
2237 entry = entry->next;
2240 state->scope_depth = depth - 1;
2243 static void register_keywords(struct compile_state *state)
2245 hash_keyword(state, "auto", TOK_AUTO);
2246 hash_keyword(state, "break", TOK_BREAK);
2247 hash_keyword(state, "case", TOK_CASE);
2248 hash_keyword(state, "char", TOK_CHAR);
2249 hash_keyword(state, "const", TOK_CONST);
2250 hash_keyword(state, "continue", TOK_CONTINUE);
2251 hash_keyword(state, "default", TOK_DEFAULT);
2252 hash_keyword(state, "do", TOK_DO);
2253 hash_keyword(state, "double", TOK_DOUBLE);
2254 hash_keyword(state, "else", TOK_ELSE);
2255 hash_keyword(state, "enum", TOK_ENUM);
2256 hash_keyword(state, "extern", TOK_EXTERN);
2257 hash_keyword(state, "float", TOK_FLOAT);
2258 hash_keyword(state, "for", TOK_FOR);
2259 hash_keyword(state, "goto", TOK_GOTO);
2260 hash_keyword(state, "if", TOK_IF);
2261 hash_keyword(state, "inline", TOK_INLINE);
2262 hash_keyword(state, "int", TOK_INT);
2263 hash_keyword(state, "long", TOK_LONG);
2264 hash_keyword(state, "register", TOK_REGISTER);
2265 hash_keyword(state, "restrict", TOK_RESTRICT);
2266 hash_keyword(state, "return", TOK_RETURN);
2267 hash_keyword(state, "short", TOK_SHORT);
2268 hash_keyword(state, "signed", TOK_SIGNED);
2269 hash_keyword(state, "sizeof", TOK_SIZEOF);
2270 hash_keyword(state, "static", TOK_STATIC);
2271 hash_keyword(state, "struct", TOK_STRUCT);
2272 hash_keyword(state, "switch", TOK_SWITCH);
2273 hash_keyword(state, "typedef", TOK_TYPEDEF);
2274 hash_keyword(state, "union", TOK_UNION);
2275 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2276 hash_keyword(state, "void", TOK_VOID);
2277 hash_keyword(state, "volatile", TOK_VOLATILE);
2278 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2279 hash_keyword(state, "while", TOK_WHILE);
2280 hash_keyword(state, "asm", TOK_ASM);
2281 hash_keyword(state, "__asm__", TOK_ASM);
2282 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2283 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2286 static void register_macro_keywords(struct compile_state *state)
2288 hash_keyword(state, "define", TOK_DEFINE);
2289 hash_keyword(state, "undef", TOK_UNDEF);
2290 hash_keyword(state, "include", TOK_INCLUDE);
2291 hash_keyword(state, "line", TOK_LINE);
2292 hash_keyword(state, "error", TOK_ERROR);
2293 hash_keyword(state, "warning", TOK_WARNING);
2294 hash_keyword(state, "pragma", TOK_PRAGMA);
2295 hash_keyword(state, "ifdef", TOK_IFDEF);
2296 hash_keyword(state, "ifndef", TOK_IFNDEF);
2297 hash_keyword(state, "elif", TOK_ELIF);
2298 hash_keyword(state, "endif", TOK_ENDIF);
2301 static int spacep(int c)
2317 static int digitp(int c)
2321 case '0': case '1': case '2': case '3': case '4':
2322 case '5': case '6': case '7': case '8': case '9':
2328 static int digval(int c)
2331 if ((c >= '0') && (c <= '9')) {
2337 static int hexdigitp(int c)
2341 case '0': case '1': case '2': case '3': case '4':
2342 case '5': case '6': case '7': case '8': case '9':
2343 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2344 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2350 static int hexdigval(int c)
2353 if ((c >= '0') && (c <= '9')) {
2356 else if ((c >= 'A') && (c <= 'F')) {
2357 val = 10 + (c - 'A');
2359 else if ((c >= 'a') && (c <= 'f')) {
2360 val = 10 + (c - 'a');
2365 static int octdigitp(int c)
2369 case '0': case '1': case '2': case '3':
2370 case '4': case '5': case '6': case '7':
2376 static int octdigval(int c)
2379 if ((c >= '0') && (c <= '7')) {
2385 static int letterp(int c)
2389 case 'a': case 'b': case 'c': case 'd': case 'e':
2390 case 'f': case 'g': case 'h': case 'i': case 'j':
2391 case 'k': case 'l': case 'm': case 'n': case 'o':
2392 case 'p': case 'q': case 'r': case 's': case 't':
2393 case 'u': case 'v': case 'w': case 'x': case 'y':
2395 case 'A': case 'B': case 'C': case 'D': case 'E':
2396 case 'F': case 'G': case 'H': case 'I': case 'J':
2397 case 'K': case 'L': case 'M': case 'N': case 'O':
2398 case 'P': case 'Q': case 'R': case 'S': case 'T':
2399 case 'U': case 'V': case 'W': case 'X': case 'Y':
2408 static int char_value(struct compile_state *state,
2409 const signed char **strp, const signed char *end)
2411 const signed char *str;
2415 if ((c == '\\') && (str < end)) {
2417 case 'n': c = '\n'; str++; break;
2418 case 't': c = '\t'; str++; break;
2419 case 'v': c = '\v'; str++; break;
2420 case 'b': c = '\b'; str++; break;
2421 case 'r': c = '\r'; str++; break;
2422 case 'f': c = '\f'; str++; break;
2423 case 'a': c = '\a'; str++; break;
2424 case '\\': c = '\\'; str++; break;
2425 case '?': c = '?'; str++; break;
2426 case '\'': c = '\''; str++; break;
2427 case '"': c = '"'; break;
2431 while((str < end) && hexdigitp(*str)) {
2433 c += hexdigval(*str);
2437 case '0': case '1': case '2': case '3':
2438 case '4': case '5': case '6': case '7':
2440 while((str < end) && octdigitp(*str)) {
2442 c += octdigval(*str);
2447 error(state, 0, "Invalid character constant");
2455 static char *after_digits(char *ptr, char *end)
2457 while((ptr < end) && digitp(*ptr)) {
2463 static char *after_octdigits(char *ptr, char *end)
2465 while((ptr < end) && octdigitp(*ptr)) {
2471 static char *after_hexdigits(char *ptr, char *end)
2473 while((ptr < end) && hexdigitp(*ptr)) {
2479 static void save_string(struct compile_state *state,
2480 struct token *tk, char *start, char *end, const char *id)
2484 /* Create a private copy of the string */
2485 str_len = end - start + 1;
2486 str = xmalloc(str_len + 1, id);
2487 memcpy(str, start, str_len);
2488 str[str_len] = '\0';
2490 /* Store the copy in the token */
2492 tk->str_len = str_len;
2494 static void next_token(struct compile_state *state, int index)
2496 struct file_state *file;
2504 tk = &state->token[index];
2507 token = tokp = file->pos;
2508 end = file->buf + file->size;
2515 if ((tokp + 1) < end) {
2519 if ((tokp + 2) < end) {
2523 if ((tokp + 3) < end) {
2531 else if (spacep(c)) {
2533 while ((tokp < end) && spacep(c)) {
2536 file->report_line++;
2537 file->line_start = tokp + 1;
2546 else if ((c == '/') && (c1 == '/')) {
2548 for(tokp += 2; tokp < end; tokp++) {
2552 file->report_line++;
2553 file->line_start = tokp +1;
2559 else if ((c == '/') && (c1 == '*')) {
2563 line_start = file->line_start;
2564 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2568 line_start = tokp +1;
2570 else if ((c == '*') && (tokp[1] == '/')) {
2576 if (tok == TOK_UNKNOWN) {
2577 error(state, 0, "unterminated comment");
2579 file->report_line += line - file->line;
2581 file->line_start = line_start;
2583 /* string constants */
2584 else if ((c == '"') ||
2585 ((c == 'L') && (c1 == '"'))) {
2590 line_start = file->line_start;
2596 for(tokp += 1; tokp < end; tokp++) {
2600 line_start = tokp + 1;
2602 else if ((c == '\\') && (tokp +1 < end)) {
2605 else if (c == '"') {
2606 tok = TOK_LIT_STRING;
2610 if (tok == TOK_UNKNOWN) {
2611 error(state, 0, "unterminated string constant");
2613 if (line != file->line) {
2614 warning(state, 0, "multiline string constant");
2616 file->report_line += line - file->line;
2618 file->line_start = line_start;
2620 /* Save the string value */
2621 save_string(state, tk, token, tokp, "literal string");
2623 /* character constants */
2624 else if ((c == '\'') ||
2625 ((c == 'L') && (c1 == '\''))) {
2630 line_start = file->line_start;
2636 for(tokp += 1; tokp < end; tokp++) {
2640 line_start = tokp + 1;
2642 else if ((c == '\\') && (tokp +1 < end)) {
2645 else if (c == '\'') {
2650 if (tok == TOK_UNKNOWN) {
2651 error(state, 0, "unterminated character constant");
2653 if (line != file->line) {
2654 warning(state, 0, "multiline character constant");
2656 file->report_line += line - file->line;
2658 file->line_start = line_start;
2660 /* Save the character value */
2661 save_string(state, tk, token, tokp, "literal character");
2663 /* integer and floating constants
2669 * Floating constants
2670 * {digits}.{digits}[Ee][+-]?{digits}
2672 * {digits}[Ee][+-]?{digits}
2673 * .{digits}[Ee][+-]?{digits}
2677 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2682 next = after_digits(tokp, end);
2687 if (next[0] == '.') {
2688 new = after_digits(next, end);
2689 is_float = (new != next);
2692 if ((next[0] == 'e') || (next[0] == 'E')) {
2693 if (((next + 1) < end) &&
2694 ((next[1] == '+') || (next[1] == '-'))) {
2697 new = after_digits(next, end);
2698 is_float = (new != next);
2702 tok = TOK_LIT_FLOAT;
2703 if ((next < end) && (
2712 if (!is_float && digitp(c)) {
2714 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2715 next = after_hexdigits(tokp + 2, end);
2717 else if (c == '0') {
2718 next = after_octdigits(tokp, end);
2721 next = after_digits(tokp, end);
2723 /* crazy integer suffixes */
2725 ((next[0] == 'u') || (next[0] == 'U'))) {
2728 ((next[0] == 'l') || (next[0] == 'L'))) {
2732 else if ((next < end) &&
2733 ((next[0] == 'l') || (next[0] == 'L'))) {
2736 ((next[0] == 'u') || (next[0] == 'U'))) {
2743 /* Save the integer/floating point value */
2744 save_string(state, tk, token, tokp, "literal number");
2747 else if (letterp(c)) {
2749 for(tokp += 1; tokp < end; tokp++) {
2751 if (!letterp(c) && !digitp(c)) {
2756 tk->ident = lookup(state, token, tokp +1 - token);
2758 /* C99 alternate macro characters */
2759 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2761 tok = TOK_CONCATENATE;
2763 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2764 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2765 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2766 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2767 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2768 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2769 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2770 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2771 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2772 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2773 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2774 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2775 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2776 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2777 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2778 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2779 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2780 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2781 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2782 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2783 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2784 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2785 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2786 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2787 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2788 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2789 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2790 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2791 else if (c == ';') { tok = TOK_SEMI; }
2792 else if (c == '{') { tok = TOK_LBRACE; }
2793 else if (c == '}') { tok = TOK_RBRACE; }
2794 else if (c == ',') { tok = TOK_COMMA; }
2795 else if (c == '=') { tok = TOK_EQ; }
2796 else if (c == ':') { tok = TOK_COLON; }
2797 else if (c == '[') { tok = TOK_LBRACKET; }
2798 else if (c == ']') { tok = TOK_RBRACKET; }
2799 else if (c == '(') { tok = TOK_LPAREN; }
2800 else if (c == ')') { tok = TOK_RPAREN; }
2801 else if (c == '*') { tok = TOK_STAR; }
2802 else if (c == '>') { tok = TOK_MORE; }
2803 else if (c == '<') { tok = TOK_LESS; }
2804 else if (c == '?') { tok = TOK_QUEST; }
2805 else if (c == '|') { tok = TOK_OR; }
2806 else if (c == '&') { tok = TOK_AND; }
2807 else if (c == '^') { tok = TOK_XOR; }
2808 else if (c == '+') { tok = TOK_PLUS; }
2809 else if (c == '-') { tok = TOK_MINUS; }
2810 else if (c == '/') { tok = TOK_DIV; }
2811 else if (c == '%') { tok = TOK_MOD; }
2812 else if (c == '!') { tok = TOK_BANG; }
2813 else if (c == '.') { tok = TOK_DOT; }
2814 else if (c == '~') { tok = TOK_TILDE; }
2815 else if (c == '#') { tok = TOK_MACRO; }
2816 if (tok == TOK_MACRO) {
2817 /* Only match preprocessor directives at the start of a line */
2819 for(ptr = file->line_start; spacep(*ptr); ptr++)
2825 if (tok == TOK_UNKNOWN) {
2826 error(state, 0, "unknown token");
2829 file->pos = tokp + 1;
2831 if (tok == TOK_IDENT) {
2832 ident_to_keyword(state, tk);
2834 /* Don't return space tokens. */
2835 if (tok == TOK_SPACE) {
2840 static void compile_macro(struct compile_state *state, struct token *tk)
2842 struct file_state *file;
2843 struct hash_entry *ident;
2845 file = xmalloc(sizeof(*file), "file_state");
2846 file->basename = xstrdup(tk->ident->name);
2847 file->dirname = xstrdup("");
2848 file->size = ident->sym_define->buf_len;
2849 file->buf = xmalloc(file->size +2, file->basename);
2850 memcpy(file->buf, ident->sym_define->buf, file->size);
2851 file->buf[file->size] = '\n';
2852 file->buf[file->size + 1] = '\0';
2853 file->pos = file->buf;
2854 file->line_start = file->pos;
2856 file->report_line = 1;
2857 file->report_name = file->basename;
2858 file->report_dir = file->dirname;
2859 file->prev = state->file;
2864 static int mpeek(struct compile_state *state, int index)
2868 tk = &state->token[index + 1];
2869 if (tk->tok == -1) {
2870 next_token(state, index + 1);
2874 if ((tk->tok == TOK_EOF) &&
2875 (state->file != state->macro_file) &&
2876 (state->file->prev)) {
2877 struct file_state *file = state->file;
2878 state->file = file->prev;
2879 /* file->basename is used keep it */
2880 if (file->report_dir != file->dirname) {
2881 xfree(file->report_dir);
2883 xfree(file->dirname);
2886 next_token(state, index + 1);
2889 else if (tk->ident && tk->ident->sym_define) {
2890 compile_macro(state, tk);
2891 next_token(state, index + 1);
2895 /* Don't show the token on the next line */
2896 if (state->macro_line < state->macro_file->line) {
2899 return state->token[index +1].tok;
2902 static void meat(struct compile_state *state, int index, int tok)
2906 next_tok = mpeek(state, index);
2907 if (next_tok != tok) {
2908 const char *name1, *name2;
2909 name1 = tokens[next_tok];
2911 if (next_tok == TOK_IDENT) {
2912 name2 = state->token[index + 1].ident->name;
2914 error(state, 0, "found %s %s expected %s",
2915 name1, name2, tokens[tok]);
2917 /* Free the old token value */
2918 if (state->token[index].str_len) {
2919 memset((void *)(state->token[index].val.str), -1,
2920 state->token[index].str_len);
2921 xfree(state->token[index].val.str);
2923 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2924 state->token[i] = state->token[i + 1];
2926 memset(&state->token[i], 0, sizeof(state->token[i]));
2927 state->token[i].tok = -1;
2930 static long_t mcexpr(struct compile_state *state, int index);
2932 static long_t mprimary_expr(struct compile_state *state, int index)
2936 tok = mpeek(state, index);
2937 while(state->token[index + 1].ident &&
2938 state->token[index + 1].ident->sym_define) {
2939 meat(state, index, tok);
2940 compile_macro(state, &state->token[index]);
2941 tok = mpeek(state, index);
2945 meat(state, index, TOK_LPAREN);
2946 val = mcexpr(state, index);
2947 meat(state, index, TOK_RPAREN);
2952 meat(state, index, TOK_LIT_INT);
2954 val = strtol(state->token[index].val.str, &end, 0);
2955 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2956 (errno == ERANGE)) {
2957 error(state, 0, "Integer constant to large");
2962 meat(state, index, TOK_LIT_INT);
2967 static long_t munary_expr(struct compile_state *state, int index)
2970 switch(mpeek(state, index)) {
2972 meat(state, index, TOK_PLUS);
2973 val = munary_expr(state, index);
2977 meat(state, index, TOK_MINUS);
2978 val = munary_expr(state, index);
2982 meat(state, index, TOK_BANG);
2983 val = munary_expr(state, index);
2987 meat(state, index, TOK_BANG);
2988 val = munary_expr(state, index);
2992 val = mprimary_expr(state, index);
2998 static long_t mmul_expr(struct compile_state *state, int index)
3002 val = munary_expr(state, index);
3006 switch(mpeek(state, index)) {
3008 meat(state, index, TOK_STAR);
3009 right = munary_expr(state, index);
3013 meat(state, index, TOK_DIV);
3014 right = munary_expr(state, index);
3018 meat(state, index, TOK_MOD);
3019 right = munary_expr(state, index);
3031 static long_t madd_expr(struct compile_state *state, int index)
3035 val = mmul_expr(state, index);
3039 switch(mpeek(state, index)) {
3041 meat(state, index, TOK_PLUS);
3042 right = mmul_expr(state, index);
3046 meat(state, index, TOK_MINUS);
3047 right = mmul_expr(state, index);
3059 static long_t mshift_expr(struct compile_state *state, int index)
3063 val = madd_expr(state, index);
3067 switch(mpeek(state, index)) {
3069 meat(state, index, TOK_SL);
3070 right = madd_expr(state, index);
3074 meat(state, index, TOK_SR);
3075 right = madd_expr(state, index);
3087 static long_t mrel_expr(struct compile_state *state, int index)
3091 val = mshift_expr(state, index);
3095 switch(mpeek(state, index)) {
3097 meat(state, index, TOK_LESS);
3098 right = mshift_expr(state, index);
3102 meat(state, index, TOK_MORE);
3103 right = mshift_expr(state, index);
3107 meat(state, index, TOK_LESSEQ);
3108 right = mshift_expr(state, index);
3112 meat(state, index, TOK_MOREEQ);
3113 right = mshift_expr(state, index);
3124 static long_t meq_expr(struct compile_state *state, int index)
3128 val = mrel_expr(state, index);
3132 switch(mpeek(state, index)) {
3134 meat(state, index, TOK_EQEQ);
3135 right = mrel_expr(state, index);
3139 meat(state, index, TOK_NOTEQ);
3140 right = mrel_expr(state, index);
3151 static long_t mand_expr(struct compile_state *state, int index)
3154 val = meq_expr(state, index);
3155 if (mpeek(state, index) == TOK_AND) {
3157 meat(state, index, TOK_AND);
3158 right = meq_expr(state, index);
3164 static long_t mxor_expr(struct compile_state *state, int index)
3167 val = mand_expr(state, index);
3168 if (mpeek(state, index) == TOK_XOR) {
3170 meat(state, index, TOK_XOR);
3171 right = mand_expr(state, index);
3177 static long_t mor_expr(struct compile_state *state, int index)
3180 val = mxor_expr(state, index);
3181 if (mpeek(state, index) == TOK_OR) {
3183 meat(state, index, TOK_OR);
3184 right = mxor_expr(state, index);
3190 static long_t mland_expr(struct compile_state *state, int index)
3193 val = mor_expr(state, index);
3194 if (mpeek(state, index) == TOK_LOGAND) {
3196 meat(state, index, TOK_LOGAND);
3197 right = mor_expr(state, index);
3202 static long_t mlor_expr(struct compile_state *state, int index)
3205 val = mland_expr(state, index);
3206 if (mpeek(state, index) == TOK_LOGOR) {
3208 meat(state, index, TOK_LOGOR);
3209 right = mland_expr(state, index);
3215 static long_t mcexpr(struct compile_state *state, int index)
3217 return mlor_expr(state, index);
3219 static void preprocess(struct compile_state *state, int index)
3221 /* Doing much more with the preprocessor would require
3222 * a parser and a major restructuring.
3223 * Postpone that for later.
3225 struct file_state *file;
3231 tk = &state->token[index];
3232 state->macro_line = line = file->line;
3233 state->macro_file = file;
3235 next_token(state, index);
3236 ident_to_macro(state, tk);
3237 if (tk->tok == TOK_IDENT) {
3238 error(state, 0, "undefined preprocessing directive `%s'",
3245 override_line = strtoul(tk->val.str, 0, 10);
3246 next_token(state, index);
3247 /* I have a cpp line marker parse it */
3248 if (tk->tok == TOK_LIT_STRING) {
3249 const char *token, *base;
3251 int name_len, dir_len;
3252 name = xmalloc(tk->str_len, "report_name");
3253 token = tk->val.str + 1;
3254 base = strrchr(token, '/');
3255 name_len = tk->str_len -2;
3257 dir_len = base - token;
3259 name_len -= base - token;
3264 memcpy(name, base, name_len);
3265 name[name_len] = '\0';
3266 dir = xmalloc(dir_len + 1, "report_dir");
3267 memcpy(dir, token, dir_len);
3268 dir[dir_len] = '\0';
3269 file->report_line = override_line - 1;
3270 file->report_name = name;
3271 file->report_dir = dir;
3276 meat(state, index, TOK_LINE);
3277 meat(state, index, TOK_LIT_INT);
3278 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3279 if (mpeek(state, index) == TOK_LIT_STRING) {
3280 const char *token, *base;
3282 int name_len, dir_len;
3283 meat(state, index, TOK_LIT_STRING);
3284 name = xmalloc(tk->str_len, "report_name");
3285 token = tk->val.str + 1;
3286 name_len = tk->str_len - 2;
3288 dir_len = base - token;
3290 name_len -= base - token;
3295 memcpy(name, base, name_len);
3296 name[name_len] = '\0';
3297 dir = xmalloc(dir_len + 1, "report_dir");
3298 memcpy(dir, token, dir_len);
3299 dir[dir_len] = '\0';
3300 file->report_name = name;
3301 file->report_dir = dir;
3306 if (state->if_value < 0) {
3309 warning(state, 0, "Ignoring preprocessor directive: %s",
3313 error(state, 0, "#elif not supported");
3314 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3315 if (state->if_depth == 0) {
3316 error(state, 0, "#elif without #if");
3318 /* If the #if was taken the #elif just disables the following code */
3319 if (state->if_value >= 0) {
3320 state->if_value = - state->if_value;
3322 /* If the previous #if was not taken see if the #elif enables the
3325 else if ((state->if_value < 0) &&
3326 (state->if_depth == - state->if_value))
3328 if (mcexpr(state, index) != 0) {
3329 state->if_value = state->if_depth;
3332 state->if_value = - state->if_depth;
3338 if (state->if_value < 0) {
3341 if (mcexpr(state, index) != 0) {
3342 state->if_value = state->if_depth;
3345 state->if_value = - state->if_depth;
3350 if (state->if_value < 0) {
3353 next_token(state, index);
3354 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3355 error(state, 0, "Invalid macro name");
3357 if (tk->ident->sym_define == 0) {
3358 state->if_value = state->if_depth;
3361 state->if_value = - state->if_depth;
3366 if (state->if_value < 0) {
3369 next_token(state, index);
3370 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3371 error(state, 0, "Invalid macro name");
3373 if (tk->ident->sym_define != 0) {
3374 state->if_value = state->if_depth;
3377 state->if_value = - state->if_depth;
3381 if (state->if_depth == 0) {
3382 error(state, 0, "#else without #if");
3384 if ((state->if_value >= 0) ||
3385 ((state->if_value < 0) &&
3386 (state->if_depth == -state->if_value)))
3388 state->if_value = - state->if_value;
3392 if (state->if_depth == 0) {
3393 error(state, 0, "#endif without #if");
3395 if ((state->if_value >= 0) ||
3396 ((state->if_value < 0) &&
3397 (state->if_depth == -state->if_value)))
3399 state->if_value = state->if_depth - 1;
3405 struct hash_entry *ident;
3406 struct macro *macro;
3409 if (state->if_value < 0) /* quit early when #if'd out */
3412 meat(state, index, TOK_IDENT);
3416 if (*file->pos == '(') {
3417 #warning "FIXME macros with arguments not supported"
3418 error(state, 0, "Macros with arguments not supported");
3421 /* Find the end of the line to get an estimate of
3422 * the macro's length.
3424 for(ptr = file->pos; *ptr != '\n'; ptr++)
3427 if (ident->sym_define != 0) {
3428 error(state, 0, "macro %s already defined\n", ident->name);
3430 macro = xmalloc(sizeof(*macro), "macro");
3431 macro->ident = ident;
3432 macro->buf_len = ptr - file->pos +1;
3433 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3435 memcpy(macro->buf, file->pos, macro->buf_len);
3436 macro->buf[macro->buf_len] = '\n';
3437 macro->buf[macro->buf_len +1] = '\0';
3439 ident->sym_define = macro;
3446 /* Find the end of the line */
3447 for(end = file->pos; *end != '\n'; end++)
3449 len = (end - file->pos);
3450 if (state->if_value >= 0) {
3451 error(state, 0, "%*.*s", len, len, file->pos);
3460 /* Find the end of the line */
3461 for(end = file->pos; *end != '\n'; end++)
3463 len = (end - file->pos);
3464 if (state->if_value >= 0) {
3465 warning(state, 0, "%*.*s", len, len, file->pos);
3477 next_token(state, index);
3478 if (tk->tok == TOK_LIT_STRING) {
3481 name = xmalloc(tk->str_len, "include");
3482 token = tk->val.str +1;
3483 name_len = tk->str_len -2;
3484 if (*token == '"') {
3488 memcpy(name, token, name_len);
3489 name[name_len] = '\0';
3492 else if (tk->tok == TOK_LESS) {
3495 for(end = start; *end != '\n'; end++) {
3501 error(state, 0, "Unterminated included directive");
3503 name = xmalloc(end - start + 1, "include");
3504 memcpy(name, start, end - start);
3505 name[end - start] = '\0';
3510 error(state, 0, "Invalid include directive");
3512 /* Error if there are any characters after the include */
3513 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3520 error(state, 0, "garbage after include directive");
3523 if (state->if_value >= 0) {
3524 compile_file(state, name, local);
3527 next_token(state, index);
3531 /* Ignore # without a following ident */
3532 if (tk->tok == TOK_IDENT) {
3533 error(state, 0, "Invalid preprocessor directive: %s",
3538 /* Consume the rest of the macro line */
3540 tok = mpeek(state, index);
3541 meat(state, index, tok);
3542 } while(tok != TOK_EOF);
3546 static void token(struct compile_state *state, int index)
3548 struct file_state *file;
3552 tk = &state->token[index];
3553 next_token(state, index);
3557 if (tk->tok == TOK_EOF && file->prev) {
3558 state->file = file->prev;
3559 /* file->basename is used keep it */
3560 xfree(file->dirname);
3563 next_token(state, index);
3566 else if (tk->tok == TOK_MACRO) {
3567 preprocess(state, index);
3570 else if (tk->ident && tk->ident->sym_define) {
3571 compile_macro(state, tk);
3572 next_token(state, index);
3575 else if (state->if_value < 0) {
3576 next_token(state, index);
3582 static int peek(struct compile_state *state)
3584 if (state->token[1].tok == -1) {
3587 return state->token[1].tok;
3590 static int peek2(struct compile_state *state)
3592 if (state->token[1].tok == -1) {
3595 if (state->token[2].tok == -1) {
3598 return state->token[2].tok;
3601 static void eat(struct compile_state *state, int tok)
3605 next_tok = peek(state);
3606 if (next_tok != tok) {
3607 const char *name1, *name2;
3608 name1 = tokens[next_tok];
3610 if (next_tok == TOK_IDENT) {
3611 name2 = state->token[1].ident->name;
3613 error(state, 0, "\tfound %s %s expected %s",
3614 name1, name2 ,tokens[tok]);
3616 /* Free the old token value */
3617 if (state->token[0].str_len) {
3618 xfree((void *)(state->token[0].val.str));
3620 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3621 state->token[i] = state->token[i + 1];
3623 memset(&state->token[i], 0, sizeof(state->token[i]));
3624 state->token[i].tok = -1;
3627 #warning "FIXME do not hardcode the include paths"
3628 static char *include_paths[] = {
3629 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3630 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3631 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3635 static void compile_file(struct compile_state *state, const char *filename, int local)
3638 const char *subdir, *base;
3640 struct file_state *file;
3642 file = xmalloc(sizeof(*file), "file_state");
3644 base = strrchr(filename, '/');
3647 subdir_len = base - filename;
3654 basename = xmalloc(strlen(base) +1, "basename");
3655 strcpy(basename, base);
3656 file->basename = basename;
3658 if (getcwd(cwd, sizeof(cwd)) == 0) {
3659 die("cwd buffer to small");
3662 if (subdir[0] == '/') {
3663 file->dirname = xmalloc(subdir_len + 1, "dirname");
3664 memcpy(file->dirname, subdir, subdir_len);
3665 file->dirname[subdir_len] = '\0';
3671 /* Find the appropriate directory... */
3673 if (!state->file && exists(cwd, filename)) {
3676 if (local && state->file && exists(state->file->dirname, filename)) {
3677 dir = state->file->dirname;
3679 for(path = include_paths; !dir && *path; path++) {
3680 if (exists(*path, filename)) {
3685 error(state, 0, "Cannot find `%s'\n", filename);
3687 dirlen = strlen(dir);
3688 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3689 memcpy(file->dirname, dir, dirlen);
3690 file->dirname[dirlen] = '/';
3691 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3692 file->dirname[dirlen + 1 + subdir_len] = '\0';
3694 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3697 file->pos = file->buf;
3698 file->line_start = file->pos;
3701 file->report_line = 1;
3702 file->report_name = file->basename;
3703 file->report_dir = file->dirname;
3705 file->prev = state->file;
3708 process_trigraphs(state);
3709 splice_lines(state);
3712 /* Type helper functions */
3714 static struct type *new_type(
3715 unsigned int type, struct type *left, struct type *right)
3717 struct type *result;
3718 result = xmalloc(sizeof(*result), "type");
3719 result->type = type;
3720 result->left = left;
3721 result->right = right;
3722 result->field_ident = 0;
3723 result->type_ident = 0;
3727 static struct type *clone_type(unsigned int specifiers, struct type *old)
3729 struct type *result;
3730 result = xmalloc(sizeof(*result), "type");
3731 memcpy(result, old, sizeof(*result));
3732 result->type &= TYPE_MASK;
3733 result->type |= specifiers;
3737 #define SIZEOF_SHORT 2
3738 #define SIZEOF_INT 4
3739 #define SIZEOF_LONG (sizeof(long_t))
3741 #define ALIGNOF_SHORT 2
3742 #define ALIGNOF_INT 4
3743 #define ALIGNOF_LONG (sizeof(long_t))
3745 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3746 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3747 static inline ulong_t mask_uint(ulong_t x)
3749 if (SIZEOF_INT < SIZEOF_LONG) {
3750 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3755 #define MASK_UINT(X) (mask_uint(X))
3756 #define MASK_ULONG(X) (X)
3758 static struct type void_type = { .type = TYPE_VOID };
3759 static struct type char_type = { .type = TYPE_CHAR };
3760 static struct type uchar_type = { .type = TYPE_UCHAR };
3761 static struct type short_type = { .type = TYPE_SHORT };
3762 static struct type ushort_type = { .type = TYPE_USHORT };
3763 static struct type int_type = { .type = TYPE_INT };
3764 static struct type uint_type = { .type = TYPE_UINT };
3765 static struct type long_type = { .type = TYPE_LONG };
3766 static struct type ulong_type = { .type = TYPE_ULONG };
3768 static struct triple *variable(struct compile_state *state, struct type *type)
3770 struct triple *result;
3771 if ((type->type & STOR_MASK) != STOR_PERM) {
3772 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3773 result = triple(state, OP_ADECL, type, 0, 0);
3776 struct triple **vector;
3778 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3779 vector = &result->param[0];
3783 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3784 vector[index] = variable(state, field->left);
3785 field = field->right;
3788 vector[index] = variable(state, field);
3792 result = triple(state, OP_SDECL, type, 0, 0);
3797 static void stor_of(FILE *fp, struct type *type)
3799 switch(type->type & STOR_MASK) {
3801 fprintf(fp, "auto ");
3804 fprintf(fp, "static ");
3807 fprintf(fp, "extern ");
3810 fprintf(fp, "register ");
3813 fprintf(fp, "typedef ");
3816 fprintf(fp, "inline ");
3820 static void qual_of(FILE *fp, struct type *type)
3822 if (type->type & QUAL_CONST) {
3823 fprintf(fp, " const");
3825 if (type->type & QUAL_VOLATILE) {
3826 fprintf(fp, " volatile");
3828 if (type->type & QUAL_RESTRICT) {
3829 fprintf(fp, " restrict");
3833 static void name_of(FILE *fp, struct type *type)
3836 switch(type->type & TYPE_MASK) {
3838 fprintf(fp, "void");
3842 fprintf(fp, "signed char");
3846 fprintf(fp, "unsigned char");
3850 fprintf(fp, "signed short");
3854 fprintf(fp, "unsigned short");
3858 fprintf(fp, "signed int");
3862 fprintf(fp, "unsigned int");
3866 fprintf(fp, "signed long");
3870 fprintf(fp, "unsigned long");
3874 name_of(fp, type->left);
3880 name_of(fp, type->left);
3882 name_of(fp, type->right);
3885 fprintf(fp, "enum %s", type->type_ident->name);
3889 fprintf(fp, "struct %s", type->type_ident->name);
3894 name_of(fp, type->left);
3895 fprintf(fp, " (*)(");
3896 name_of(fp, type->right);
3901 name_of(fp, type->left);
3902 fprintf(fp, " [%ld]", type->elements);
3905 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3910 static size_t align_of(struct compile_state *state, struct type *type)
3914 switch(type->type & TYPE_MASK) {
3924 align = ALIGNOF_SHORT;
3929 align = ALIGNOF_INT;
3934 align = ALIGNOF_LONG;
3939 size_t left_align, right_align;
3940 left_align = align_of(state, type->left);
3941 right_align = align_of(state, type->right);
3942 align = (left_align >= right_align) ? left_align : right_align;
3946 align = align_of(state, type->left);
3949 align = align_of(state, type->left);
3952 error(state, 0, "alignof not yet defined for type\n");
3958 static size_t needed_padding(size_t offset, size_t align)
3962 if (offset % align) {
3963 padding = align - (offset % align);
3967 static size_t size_of(struct compile_state *state, struct type *type)
3971 switch(type->type & TYPE_MASK) {
3981 size = SIZEOF_SHORT;
3997 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3998 align = align_of(state, type->left);
3999 pad = needed_padding(size, align);
4000 size = size + pad + size_of(state, type->left);
4003 align = align_of(state, type);
4004 pad = needed_padding(size, align);
4005 size = size + pad + sizeof(type);
4010 size_t size_left, size_right;
4011 size_left = size_of(state, type->left);
4012 size_right = size_of(state, type->right);
4013 size = (size_left >= size_right)? size_left : size_right;
4017 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4018 internal_error(state, 0, "Invalid array type");
4020 size = size_of(state, type->left) * type->elements;
4024 size = size_of(state, type->left);
4027 internal_error(state, 0, "sizeof not yet defined for type\n");
4033 static size_t field_offset(struct compile_state *state,
4034 struct type *type, struct hash_entry *field)
4036 struct type *member;
4038 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4039 internal_error(state, 0, "field_offset only works on structures");
4042 member = type->left;
4043 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4044 align = align_of(state, member->left);
4045 size += needed_padding(size, align);
4046 if (member->left->field_ident == field) {
4047 member = member->left;
4050 size += size_of(state, member->left);
4051 member = member->right;
4053 align = align_of(state, member);
4054 size += needed_padding(size, align);
4055 if (member->field_ident != field) {
4056 error(state, 0, "member %s not present", field->name);
4061 static struct type *field_type(struct compile_state *state,
4062 struct type *type, struct hash_entry *field)
4064 struct type *member;
4065 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4066 internal_error(state, 0, "field_type only works on structures");
4068 member = type->left;
4069 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4070 if (member->left->field_ident == field) {
4071 member = member->left;
4074 member = member->right;
4076 if (member->field_ident != field) {
4077 error(state, 0, "member %s not present", field->name);
4082 static struct type *next_field(struct compile_state *state,
4083 struct type *type, struct type *prev_member)
4085 struct type *member;
4086 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4087 internal_error(state, 0, "next_field only works on structures");
4089 member = type->left;
4090 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4092 member = member->left;
4095 if (member->left == prev_member) {
4098 member = member->right;
4100 if (member == prev_member) {
4104 internal_error(state, 0, "prev_member %s not present",
4105 prev_member->field_ident->name);
4110 static struct triple *struct_field(struct compile_state *state,
4111 struct triple *decl, struct hash_entry *field)
4113 struct triple **vector;
4117 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4120 if (decl->op != OP_VAL_VEC) {
4121 internal_error(state, 0, "Invalid struct variable");
4124 internal_error(state, 0, "Missing structure field");
4127 vector = &RHS(decl, 0);
4129 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4130 if (type->left->field_ident == field) {
4137 if (type->field_ident != field) {
4138 internal_error(state, 0, "field %s not found?", field->name);
4140 return vector[index];
4143 static void arrays_complete(struct compile_state *state, struct type *type)
4145 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4146 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4147 error(state, 0, "array size not specified");
4149 arrays_complete(state, type->left);
4153 static unsigned int do_integral_promotion(unsigned int type)
4156 if (TYPE_INTEGER(type) &&
4157 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4163 static unsigned int do_arithmetic_conversion(
4164 unsigned int left, unsigned int right)
4168 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4169 return TYPE_LDOUBLE;
4171 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4174 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4177 left = do_integral_promotion(left);
4178 right = do_integral_promotion(right);
4179 /* If both operands have the same size done */
4180 if (left == right) {
4183 /* If both operands have the same signedness pick the larger */
4184 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4185 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4187 /* If the signed type can hold everything use it */
4188 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4191 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4194 /* Convert to the unsigned type with the same rank as the signed type */
4195 else if (TYPE_SIGNED(left)) {
4196 return TYPE_MKUNSIGNED(left);
4199 return TYPE_MKUNSIGNED(right);
4203 /* see if two types are the same except for qualifiers */
4204 static int equiv_types(struct type *left, struct type *right)
4207 /* Error if the basic types do not match */
4208 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4211 type = left->type & TYPE_MASK;
4212 /* If the basic types match and it is a void type we are done */
4213 if (type == TYPE_VOID) {
4216 /* if the basic types match and it is an arithmetic type we are done */
4217 if (TYPE_ARITHMETIC(type)) {
4220 /* If it is a pointer type recurse and keep testing */
4221 if (type == TYPE_POINTER) {
4222 return equiv_types(left->left, right->left);
4224 else if (type == TYPE_ARRAY) {
4225 return (left->elements == right->elements) &&
4226 equiv_types(left->left, right->left);
4228 /* test for struct/union equality */
4229 else if (type == TYPE_STRUCT) {
4230 return left->type_ident == right->type_ident;
4232 /* Test for equivalent functions */
4233 else if (type == TYPE_FUNCTION) {
4234 return equiv_types(left->left, right->left) &&
4235 equiv_types(left->right, right->right);
4237 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4238 else if (type == TYPE_PRODUCT) {
4239 return equiv_types(left->left, right->left) &&
4240 equiv_types(left->right, right->right);
4242 /* We should see TYPE_OVERLAP */
4248 static int equiv_ptrs(struct type *left, struct type *right)
4250 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4251 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4254 return equiv_types(left->left, right->left);
4257 static struct type *compatible_types(struct type *left, struct type *right)
4259 struct type *result;
4260 unsigned int type, qual_type;
4261 /* Error if the basic types do not match */
4262 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4265 type = left->type & TYPE_MASK;
4266 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4268 /* if the basic types match and it is an arithmetic type we are done */
4269 if (TYPE_ARITHMETIC(type)) {
4270 result = new_type(qual_type, 0, 0);
4272 /* If it is a pointer type recurse and keep testing */
4273 else if (type == TYPE_POINTER) {
4274 result = compatible_types(left->left, right->left);
4276 result = new_type(qual_type, result, 0);
4279 /* test for struct/union equality */
4280 else if (type == TYPE_STRUCT) {
4281 if (left->type_ident == right->type_ident) {
4285 /* Test for equivalent functions */
4286 else if (type == TYPE_FUNCTION) {
4287 struct type *lf, *rf;
4288 lf = compatible_types(left->left, right->left);
4289 rf = compatible_types(left->right, right->right);
4291 result = new_type(qual_type, lf, rf);
4294 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4295 else if (type == TYPE_PRODUCT) {
4296 struct type *lf, *rf;
4297 lf = compatible_types(left->left, right->left);
4298 rf = compatible_types(left->right, right->right);
4300 result = new_type(qual_type, lf, rf);
4304 /* Nothing else is compatible */
4309 static struct type *compatible_ptrs(struct type *left, struct type *right)
4311 struct type *result;
4312 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4313 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4316 result = compatible_types(left->left, right->left);
4318 unsigned int qual_type;
4319 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4320 result = new_type(qual_type, result, 0);
4325 static struct triple *integral_promotion(
4326 struct compile_state *state, struct triple *def)
4330 /* As all operations are carried out in registers
4331 * the values are converted on load I just convert
4332 * logical type of the operand.
4334 if (TYPE_INTEGER(type->type)) {
4335 unsigned int int_type;
4336 int_type = type->type & ~TYPE_MASK;
4337 int_type |= do_integral_promotion(type->type);
4338 if (int_type != type->type) {
4339 def->type = new_type(int_type, 0, 0);
4346 static void arithmetic(struct compile_state *state, struct triple *def)
4348 if (!TYPE_ARITHMETIC(def->type->type)) {
4349 error(state, 0, "arithmetic type expexted");
4353 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4355 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4356 error(state, def, "pointer or arithmetic type expected");
4360 static int is_integral(struct triple *ins)
4362 return TYPE_INTEGER(ins->type->type);
4365 static void integral(struct compile_state *state, struct triple *def)
4367 if (!is_integral(def)) {
4368 error(state, 0, "integral type expected");
4373 static void bool(struct compile_state *state, struct triple *def)
4375 if (!TYPE_ARITHMETIC(def->type->type) &&
4376 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4377 error(state, 0, "arithmetic or pointer type expected");
4381 static int is_signed(struct type *type)
4383 return !!TYPE_SIGNED(type->type);
4386 /* Is this value located in a register otherwise it must be in memory */
4387 static int is_in_reg(struct compile_state *state, struct triple *def)
4390 if (def->op == OP_ADECL) {
4393 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4396 else if (def->op == OP_VAL_VEC) {
4397 in_reg = is_in_reg(state, RHS(def, 0));
4399 else if (def->op == OP_DOT) {
4400 in_reg = is_in_reg(state, RHS(def, 0));
4403 internal_error(state, 0, "unknown expr storage location");
4409 /* Is this a stable variable location otherwise it must be a temporary */
4410 static int is_stable(struct compile_state *state, struct triple *def)
4417 if ((def->op == OP_ADECL) ||
4418 (def->op == OP_SDECL) ||
4419 (def->op == OP_DEREF) ||
4420 (def->op == OP_BLOBCONST)) {
4423 else if (def->op == OP_DOT) {
4424 ret = is_stable(state, RHS(def, 0));
4426 else if (def->op == OP_VAL_VEC) {
4427 struct triple **vector;
4430 vector = &RHS(def, 0);
4431 for(i = 0; i < def->type->elements; i++) {
4432 if (!is_stable(state, vector[i])) {
4441 static int is_lvalue(struct compile_state *state, struct triple *def)
4448 if (!is_stable(state, def)) {
4451 if (def->op == OP_DOT) {
4452 ret = is_lvalue(state, RHS(def, 0));
4457 static void clvalue(struct compile_state *state, struct triple *def)
4460 internal_error(state, def, "nothing where lvalue expected?");
4462 if (!is_lvalue(state, def)) {
4463 error(state, def, "lvalue expected");
4466 static void lvalue(struct compile_state *state, struct triple *def)
4468 clvalue(state, def);
4469 if (def->type->type & QUAL_CONST) {
4470 error(state, def, "modifable lvalue expected");
4474 static int is_pointer(struct triple *def)
4476 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4479 static void pointer(struct compile_state *state, struct triple *def)
4481 if (!is_pointer(def)) {
4482 error(state, def, "pointer expected");
4486 static struct triple *int_const(
4487 struct compile_state *state, struct type *type, ulong_t value)
4489 struct triple *result;
4490 switch(type->type & TYPE_MASK) {
4492 case TYPE_INT: case TYPE_UINT:
4493 case TYPE_LONG: case TYPE_ULONG:
4496 internal_error(state, 0, "constant for unkown type");
4498 result = triple(state, OP_INTCONST, type, 0, 0);
4499 result->u.cval = value;
4504 static struct triple *do_mk_addr_expr(struct compile_state *state,
4505 struct triple *expr, struct type *type, ulong_t offset)
4507 struct triple *result;
4508 clvalue(state, expr);
4510 type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
4513 if (expr->op == OP_ADECL) {
4514 error(state, expr, "address of auto variables not supported");
4516 else if (expr->op == OP_SDECL) {
4517 result = triple(state, OP_ADDRCONST, type, 0, 0);
4518 MISC(result, 0) = expr;
4519 result->u.cval = offset;
4521 else if (expr->op == OP_DEREF) {
4522 result = triple(state, OP_ADD, type,
4524 int_const(state, &ulong_type, offset));
4529 static struct triple *mk_addr_expr(
4530 struct compile_state *state, struct triple *expr, ulong_t offset)
4532 return do_mk_addr_expr(state, expr, expr->type, offset);
4535 static struct triple *mk_deref_expr(
4536 struct compile_state *state, struct triple *expr)
4538 struct type *base_type;
4539 pointer(state, expr);
4540 base_type = expr->type->left;
4541 return triple(state, OP_DEREF, base_type, expr, 0);
4544 static struct triple *array_to_pointer(struct compile_state *state, struct triple *def)
4546 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4549 TYPE_POINTER | (def->type->type & QUAL_MASK),
4550 def->type->left, 0);
4551 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
4552 struct triple *addrconst;
4553 if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
4554 internal_error(state, def, "bad array constant");
4556 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
4557 MISC(addrconst, 0) = def;
4561 def = triple(state, OP_COPY, type, def, 0);
4567 static struct triple *deref_field(
4568 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4570 struct triple *result;
4571 struct type *type, *member;
4573 internal_error(state, 0, "No field passed to deref_field");
4577 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4578 error(state, 0, "request for member %s in something not a struct or union",
4581 member = field_type(state, type, field);
4582 if ((type->type & STOR_MASK) == STOR_PERM) {
4583 /* Do the pointer arithmetic to get a deref the field */
4585 offset = field_offset(state, type, field);
4586 result = do_mk_addr_expr(state, expr, member, offset);
4587 result = mk_deref_expr(state, result);
4590 /* Find the variable for the field I want. */
4591 result = triple(state, OP_DOT, member, expr, 0);
4592 result->u.field = field;
4597 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4603 if (!is_stable(state, def)) {
4606 /* Tranform an array to a pointer to the first element */
4608 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4609 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4610 return array_to_pointer(state, def);
4612 if (is_in_reg(state, def)) {
4617 return triple(state, op, def->type, def, 0);
4620 static void write_compatible(struct compile_state *state,
4621 struct type *dest, struct type *rval)
4624 /* Both operands have arithmetic type */
4625 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4628 /* One operand is a pointer and the other is a pointer to void */
4629 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4630 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4631 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4632 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4635 /* If both types are the same without qualifiers we are good */
4636 else if (equiv_ptrs(dest, rval)) {
4639 /* test for struct/union equality */
4640 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4641 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4642 (dest->type_ident == rval->type_ident)) {
4646 error(state, 0, "Incompatible types in assignment");
4650 static struct triple *write_expr(
4651 struct compile_state *state, struct triple *dest, struct triple *rval)
4658 internal_error(state, 0, "missing rval");
4661 if (rval->op == OP_LIST) {
4662 internal_error(state, 0, "expression of type OP_LIST?");
4664 if (!is_lvalue(state, dest)) {
4665 internal_error(state, 0, "writing to a non lvalue?");
4667 if (dest->type->type & QUAL_CONST) {
4668 internal_error(state, 0, "modifable lvalue expexted");
4671 write_compatible(state, dest->type, rval->type);
4673 /* Now figure out which assignment operator to use */
4675 if (is_in_reg(state, dest)) {
4680 def = triple(state, op, dest->type, dest, rval);
4684 static struct triple *init_expr(
4685 struct compile_state *state, struct triple *dest, struct triple *rval)
4691 internal_error(state, 0, "missing rval");
4693 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4694 rval = read_expr(state, rval);
4695 def = write_expr(state, dest, rval);
4698 /* Fill in the array size if necessary */
4699 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4700 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4701 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4702 dest->type->elements = rval->type->elements;
4705 if (!equiv_types(dest->type, rval->type)) {
4706 error(state, 0, "Incompatible types in inializer");
4708 MISC(dest, 0) = rval;
4709 insert_triple(state, dest, rval);
4710 rval->id |= TRIPLE_FLAG_FLATTENED;
4711 use_triple(MISC(dest, 0), dest);
4716 struct type *arithmetic_result(
4717 struct compile_state *state, struct triple *left, struct triple *right)
4720 /* Sanity checks to ensure I am working with arithmetic types */
4721 arithmetic(state, left);
4722 arithmetic(state, right);
4724 do_arithmetic_conversion(
4726 right->type->type), 0, 0);
4730 struct type *ptr_arithmetic_result(
4731 struct compile_state *state, struct triple *left, struct triple *right)
4734 /* Sanity checks to ensure I am working with the proper types */
4735 ptr_arithmetic(state, left);
4736 arithmetic(state, right);
4737 if (TYPE_ARITHMETIC(left->type->type) &&
4738 TYPE_ARITHMETIC(right->type->type)) {
4739 type = arithmetic_result(state, left, right);
4741 else if (TYPE_PTR(left->type->type)) {
4745 internal_error(state, 0, "huh?");
4752 /* boolean helper function */
4754 static struct triple *ltrue_expr(struct compile_state *state,
4755 struct triple *expr)
4758 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4759 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4760 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4761 /* If the expression is already boolean do nothing */
4764 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4770 static struct triple *lfalse_expr(struct compile_state *state,
4771 struct triple *expr)
4773 return triple(state, OP_LFALSE, &int_type, expr, 0);
4776 static struct triple *cond_expr(
4777 struct compile_state *state,
4778 struct triple *test, struct triple *left, struct triple *right)
4781 struct type *result_type;
4782 unsigned int left_type, right_type;
4784 left_type = left->type->type;
4785 right_type = right->type->type;
4787 /* Both operands have arithmetic type */
4788 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4789 result_type = arithmetic_result(state, left, right);
4791 /* Both operands have void type */
4792 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4793 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4794 result_type = &void_type;
4796 /* pointers to the same type... */
4797 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4800 /* Both operands are pointers and left is a pointer to void */
4801 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4802 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4803 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4804 result_type = right->type;
4806 /* Both operands are pointers and right is a pointer to void */
4807 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4808 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4809 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4810 result_type = left->type;
4813 error(state, 0, "Incompatible types in conditional expression");
4815 /* Cleanup and invert the test */
4816 test = lfalse_expr(state, read_expr(state, test));
4817 def = new_triple(state, OP_COND, result_type, 0, 3);
4818 def->param[0] = test;
4819 def->param[1] = left;
4820 def->param[2] = right;
4825 static int expr_depth(struct compile_state *state, struct triple *ins)
4829 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4832 else if (ins->op == OP_DEREF) {
4833 count = expr_depth(state, RHS(ins, 0)) - 1;
4835 else if (ins->op == OP_VAL) {
4836 count = expr_depth(state, RHS(ins, 0)) - 1;
4838 else if (ins->op == OP_COMMA) {
4840 ldepth = expr_depth(state, RHS(ins, 0));
4841 rdepth = expr_depth(state, RHS(ins, 1));
4842 count = (ldepth >= rdepth)? ldepth : rdepth;
4844 else if (ins->op == OP_CALL) {
4845 /* Don't figure the depth of a call just guess it is huge */
4849 struct triple **expr;
4850 expr = triple_rhs(state, ins, 0);
4851 for(;expr; expr = triple_rhs(state, ins, expr)) {
4854 depth = expr_depth(state, *expr);
4855 if (depth > count) {
4864 static struct triple *flatten(
4865 struct compile_state *state, struct triple *first, struct triple *ptr);
4867 static struct triple *flatten_generic(
4868 struct compile_state *state, struct triple *first, struct triple *ptr)
4872 struct triple **ins;
4875 /* Only operations with just a rhs should come here */
4876 rhs = TRIPLE_RHS(ptr->sizes);
4877 lhs = TRIPLE_LHS(ptr->sizes);
4878 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4879 internal_error(state, ptr, "unexpected args for: %d %s",
4880 ptr->op, tops(ptr->op));
4882 /* Find the depth of the rhs elements */
4883 for(i = 0; i < rhs; i++) {
4884 vector[i].ins = &RHS(ptr, i);
4885 vector[i].depth = expr_depth(state, *vector[i].ins);
4887 /* Selection sort the rhs */
4888 for(i = 0; i < rhs; i++) {
4890 for(j = i + 1; j < rhs; j++ ) {
4891 if (vector[j].depth > vector[max].depth) {
4896 struct rhs_vector tmp;
4898 vector[i] = vector[max];
4902 /* Now flatten the rhs elements */
4903 for(i = 0; i < rhs; i++) {
4904 *vector[i].ins = flatten(state, first, *vector[i].ins);
4905 use_triple(*vector[i].ins, ptr);
4908 /* Now flatten the lhs elements */
4909 for(i = 0; i < lhs; i++) {
4910 struct triple **ins = &LHS(ptr, i);
4911 *ins = flatten(state, first, *ins);
4912 use_triple(*ins, ptr);
4917 static struct triple *flatten_land(
4918 struct compile_state *state, struct triple *first, struct triple *ptr)
4920 struct triple *left, *right;
4921 struct triple *val, *test, *jmp, *label1, *end;
4923 /* Find the triples */
4925 right = RHS(ptr, 1);
4927 /* Generate the needed triples */
4930 /* Thread the triples together */
4931 val = flatten(state, first, variable(state, ptr->type));
4932 left = flatten(state, first, write_expr(state, val, left));
4933 test = flatten(state, first,
4934 lfalse_expr(state, read_expr(state, val)));
4935 jmp = flatten(state, first, branch(state, end, test));
4936 label1 = flatten(state, first, label(state));
4937 right = flatten(state, first, write_expr(state, val, right));
4938 TARG(jmp, 0) = flatten(state, first, end);
4940 /* Now give the caller something to chew on */
4941 return read_expr(state, val);
4944 static struct triple *flatten_lor(
4945 struct compile_state *state, struct triple *first, struct triple *ptr)
4947 struct triple *left, *right;
4948 struct triple *val, *jmp, *label1, *end;
4950 /* Find the triples */
4952 right = RHS(ptr, 1);
4954 /* Generate the needed triples */
4957 /* Thread the triples together */
4958 val = flatten(state, first, variable(state, ptr->type));
4959 left = flatten(state, first, write_expr(state, val, left));
4960 jmp = flatten(state, first, branch(state, end, left));
4961 label1 = flatten(state, first, label(state));
4962 right = flatten(state, first, write_expr(state, val, right));
4963 TARG(jmp, 0) = flatten(state, first, end);
4966 /* Now give the caller something to chew on */
4967 return read_expr(state, val);
4970 static struct triple *flatten_cond(
4971 struct compile_state *state, struct triple *first, struct triple *ptr)
4973 struct triple *test, *left, *right;
4974 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4976 /* Find the triples */
4979 right = RHS(ptr, 2);
4981 /* Generate the needed triples */
4983 middle = label(state);
4985 /* Thread the triples together */
4986 val = flatten(state, first, variable(state, ptr->type));
4987 test = flatten(state, first, test);
4988 jmp1 = flatten(state, first, branch(state, middle, test));
4989 label1 = flatten(state, first, label(state));
4990 left = flatten(state, first, left);
4991 mv1 = flatten(state, first, write_expr(state, val, left));
4992 jmp2 = flatten(state, first, branch(state, end, 0));
4993 TARG(jmp1, 0) = flatten(state, first, middle);
4994 right = flatten(state, first, right);
4995 mv2 = flatten(state, first, write_expr(state, val, right));
4996 TARG(jmp2, 0) = flatten(state, first, end);
4998 /* Now give the caller something to chew on */
4999 return read_expr(state, val);
5002 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
5003 struct occurance *base_occurance)
5005 struct triple *nfunc;
5006 struct triple *nfirst, *ofirst;
5007 struct triple *new, *old;
5010 fprintf(stdout, "\n");
5011 loc(stdout, state, 0);
5012 fprintf(stdout, "\n__________ copy_func _________\n");
5013 print_triple(state, ofunc);
5014 fprintf(stdout, "__________ copy_func _________ done\n\n");
5017 /* Make a new copy of the old function */
5018 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
5020 ofirst = old = RHS(ofunc, 0);
5023 struct occurance *occurance;
5024 int old_lhs, old_rhs;
5025 old_lhs = TRIPLE_LHS(old->sizes);
5026 old_rhs = TRIPLE_RHS(old->sizes);
5027 occurance = inline_occurance(state, base_occurance, old->occurance);
5028 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
5030 if (!triple_stores_block(state, new)) {
5031 memcpy(&new->u, &old->u, sizeof(new->u));
5034 RHS(nfunc, 0) = nfirst = new;
5037 insert_triple(state, nfirst, new);
5039 new->id |= TRIPLE_FLAG_FLATTENED;
5041 /* During the copy remember new as user of old */
5042 use_triple(old, new);
5044 /* Populate the return type if present */
5045 if (old == MISC(ofunc, 0)) {
5046 MISC(nfunc, 0) = new;
5049 } while(old != ofirst);
5051 /* Make a second pass to fix up any unresolved references */
5055 struct triple **oexpr, **nexpr;
5057 /* Lookup where the copy is, to join pointers */
5058 count = TRIPLE_SIZE(old->sizes);
5059 for(i = 0; i < count; i++) {
5060 oexpr = &old->param[i];
5061 nexpr = &new->param[i];
5062 if (!*nexpr && *oexpr && (*oexpr)->use) {
5063 *nexpr = (*oexpr)->use->member;
5064 if (*nexpr == old) {
5065 internal_error(state, 0, "new == old?");
5067 use_triple(*nexpr, new);
5069 if (!*nexpr && *oexpr) {
5070 internal_error(state, 0, "Could not copy %d\n", i);
5075 } while((old != ofirst) && (new != nfirst));
5077 /* Make a third pass to cleanup the extra useses */
5081 unuse_triple(old, new);
5084 } while ((old != ofirst) && (new != nfirst));
5088 static struct triple *flatten_call(
5089 struct compile_state *state, struct triple *first, struct triple *ptr)
5091 /* Inline the function call */
5093 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5094 struct triple *end, *nend;
5097 /* Find the triples */
5098 ofunc = MISC(ptr, 0);
5099 if (ofunc->op != OP_LIST) {
5100 internal_error(state, 0, "improper function");
5102 nfunc = copy_func(state, ofunc, ptr->occurance);
5103 nfirst = RHS(nfunc, 0)->next;
5104 /* Prepend the parameter reading into the new function list */
5105 ptype = nfunc->type->right;
5106 param = RHS(nfunc, 0)->next;
5107 pvals = TRIPLE_RHS(ptr->sizes);
5108 for(i = 0; i < pvals; i++) {
5112 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5113 atype = ptype->left;
5115 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5116 param = param->next;
5119 flatten(state, nfirst, write_expr(state, param, arg));
5120 ptype = ptype->right;
5121 param = param->next;
5124 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5125 result = read_expr(state, MISC(nfunc,0));
5128 fprintf(stdout, "\n");
5129 loc(stdout, state, 0);
5130 fprintf(stdout, "\n__________ flatten_call _________\n");
5131 print_triple(state, nfunc);
5132 fprintf(stdout, "__________ flatten_call _________ done\n\n");
5135 /* Get rid of the extra triples */
5136 nfirst = RHS(nfunc, 0)->next;
5137 free_triple(state, RHS(nfunc, 0));
5139 free_triple(state, nfunc);
5141 /* Append the new function list onto the return list */
5143 nend = nfirst->prev;
5152 static struct triple *flatten(
5153 struct compile_state *state, struct triple *first, struct triple *ptr)
5155 struct triple *orig_ptr;
5160 /* Only flatten triples once */
5161 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5166 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5170 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5171 return MISC(ptr, 0);
5174 ptr = flatten_land(state, first, ptr);
5177 ptr = flatten_lor(state, first, ptr);
5180 ptr = flatten_cond(state, first, ptr);
5183 ptr = flatten_call(state, first, ptr);
5187 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5188 use_triple(RHS(ptr, 0), ptr);
5191 use_triple(TARG(ptr, 0), ptr);
5192 if (TRIPLE_RHS(ptr->sizes)) {
5193 use_triple(RHS(ptr, 0), ptr);
5194 if (ptr->next != ptr) {
5195 use_triple(ptr->next, ptr);
5200 insert_triple(state, first, ptr);
5201 ptr->id |= TRIPLE_FLAG_FLATTENED;
5202 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5203 use_triple(MISC(ptr, 0), ptr);
5206 /* Since OP_DEREF is just a marker delete it when I flatten it */
5208 RHS(orig_ptr, 0) = 0;
5209 free_triple(state, orig_ptr);
5213 struct triple *base;
5215 if (base->op == OP_DEREF) {
5216 struct triple *left;
5218 offset = field_offset(state, base->type, ptr->u.field);
5219 left = RHS(base, 0);
5220 ptr = triple(state, OP_ADD, left->type,
5221 read_expr(state, left),
5222 int_const(state, &ulong_type, offset));
5223 free_triple(state, base);
5225 else if (base->op == OP_VAL_VEC) {
5226 base = flatten(state, first, base);
5227 ptr = struct_field(state, base, ptr->u.field);
5232 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5233 use_triple(MISC(ptr, 0), ptr);
5234 use_triple(ptr, MISC(ptr, 0));
5238 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5239 use_triple(MISC(ptr, 0), ptr);
5244 /* Flatten the easy cases we don't override */
5245 ptr = flatten_generic(state, first, ptr);
5248 } while(ptr && (ptr != orig_ptr));
5250 insert_triple(state, first, ptr);
5251 ptr->id |= TRIPLE_FLAG_FLATTENED;
5256 static void release_expr(struct compile_state *state, struct triple *expr)
5258 struct triple *head;
5259 head = label(state);
5260 flatten(state, head, expr);
5261 while(head->next != head) {
5262 release_triple(state, head->next);
5264 free_triple(state, head);
5267 static int replace_rhs_use(struct compile_state *state,
5268 struct triple *orig, struct triple *new, struct triple *use)
5270 struct triple **expr;
5273 expr = triple_rhs(state, use, 0);
5274 for(;expr; expr = triple_rhs(state, use, expr)) {
5275 if (*expr == orig) {
5281 unuse_triple(orig, use);
5282 use_triple(new, use);
5287 static int replace_lhs_use(struct compile_state *state,
5288 struct triple *orig, struct triple *new, struct triple *use)
5290 struct triple **expr;
5293 expr = triple_lhs(state, use, 0);
5294 for(;expr; expr = triple_lhs(state, use, expr)) {
5295 if (*expr == orig) {
5301 unuse_triple(orig, use);
5302 use_triple(new, use);
5307 static void propogate_use(struct compile_state *state,
5308 struct triple *orig, struct triple *new)
5310 struct triple_set *user, *next;
5311 for(user = orig->use; user; user = next) {
5317 found |= replace_rhs_use(state, orig, new, use);
5318 found |= replace_lhs_use(state, orig, new, use);
5320 internal_error(state, use, "use without use");
5324 internal_error(state, orig, "used after propogate_use");
5330 * ===========================
5333 static struct triple *mk_add_expr(
5334 struct compile_state *state, struct triple *left, struct triple *right)
5336 struct type *result_type;
5337 /* Put pointer operands on the left */
5338 if (is_pointer(right)) {
5344 left = read_expr(state, left);
5345 right = read_expr(state, right);
5346 result_type = ptr_arithmetic_result(state, left, right);
5347 if (is_pointer(left)) {
5348 right = triple(state,
5349 is_signed(right->type)? OP_SMUL : OP_UMUL,
5352 int_const(state, &ulong_type,
5353 size_of(state, left->type->left)));
5355 return triple(state, OP_ADD, result_type, left, right);
5358 static struct triple *mk_sub_expr(
5359 struct compile_state *state, struct triple *left, struct triple *right)
5361 struct type *result_type;
5362 result_type = ptr_arithmetic_result(state, left, right);
5363 left = read_expr(state, left);
5364 right = read_expr(state, right);
5365 if (is_pointer(left)) {
5366 right = triple(state,
5367 is_signed(right->type)? OP_SMUL : OP_UMUL,
5370 int_const(state, &ulong_type,
5371 size_of(state, left->type->left)));
5373 return triple(state, OP_SUB, result_type, left, right);
5376 static struct triple *mk_pre_inc_expr(
5377 struct compile_state *state, struct triple *def)
5381 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5382 return triple(state, OP_VAL, def->type,
5383 write_expr(state, def, val),
5387 static struct triple *mk_pre_dec_expr(
5388 struct compile_state *state, struct triple *def)
5392 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5393 return triple(state, OP_VAL, def->type,
5394 write_expr(state, def, val),
5398 static struct triple *mk_post_inc_expr(
5399 struct compile_state *state, struct triple *def)
5403 val = read_expr(state, def);
5404 return triple(state, OP_VAL, def->type,
5405 write_expr(state, def,
5406 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5410 static struct triple *mk_post_dec_expr(
5411 struct compile_state *state, struct triple *def)
5415 val = read_expr(state, def);
5416 return triple(state, OP_VAL, def->type,
5417 write_expr(state, def,
5418 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5422 static struct triple *mk_subscript_expr(
5423 struct compile_state *state, struct triple *left, struct triple *right)
5425 left = read_expr(state, left);
5426 right = read_expr(state, right);
5427 if (!is_pointer(left) && !is_pointer(right)) {
5428 error(state, left, "subscripted value is not a pointer");
5430 return mk_deref_expr(state, mk_add_expr(state, left, right));
5434 * Compile time evaluation
5435 * ===========================
5437 static int is_const(struct triple *ins)
5439 return IS_CONST_OP(ins->op);
5442 static int constants_equal(struct compile_state *state,
5443 struct triple *left, struct triple *right)
5446 if (!is_const(left) || !is_const(right)) {
5449 else if (left->op != right->op) {
5452 else if (!equiv_types(left->type, right->type)) {
5459 if (left->u.cval == right->u.cval) {
5465 size_t lsize, rsize;
5466 lsize = size_of(state, left->type);
5467 rsize = size_of(state, right->type);
5468 if (lsize != rsize) {
5471 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5477 if ((MISC(left, 0) == MISC(right, 0)) &&
5478 (left->u.cval == right->u.cval)) {
5483 internal_error(state, left, "uknown constant type");
5490 static int is_zero(struct triple *ins)
5492 return is_const(ins) && (ins->u.cval == 0);
5495 static int is_one(struct triple *ins)
5497 return is_const(ins) && (ins->u.cval == 1);
5500 static long_t bit_count(ulong_t value)
5505 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5516 static long_t bsr(ulong_t value)
5519 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5530 static long_t bsf(ulong_t value)
5533 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5544 static long_t log2(ulong_t value)
5549 static long_t tlog2(struct triple *ins)
5551 return log2(ins->u.cval);
5554 static int is_pow2(struct triple *ins)
5556 ulong_t value, mask;
5558 if (!is_const(ins)) {
5561 value = ins->u.cval;
5568 return ((value & mask) == value);
5571 static ulong_t read_const(struct compile_state *state,
5572 struct triple *ins, struct triple **expr)
5576 switch(rhs->type->type &TYPE_MASK) {
5588 internal_error(state, rhs, "bad type to read_const\n");
5594 static long_t read_sconst(struct triple *ins, struct triple **expr)
5598 return (long_t)(rhs->u.cval);
5601 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5603 struct triple **expr;
5604 expr = triple_rhs(state, ins, 0);
5605 for(;expr;expr = triple_rhs(state, ins, expr)) {
5607 unuse_triple(*expr, ins);
5613 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5615 struct triple **expr;
5616 expr = triple_lhs(state, ins, 0);
5617 for(;expr;expr = triple_lhs(state, ins, expr)) {
5618 unuse_triple(*expr, ins);
5623 static void check_lhs(struct compile_state *state, struct triple *ins)
5625 struct triple **expr;
5626 expr = triple_lhs(state, ins, 0);
5627 for(;expr;expr = triple_lhs(state, ins, expr)) {
5628 internal_error(state, ins, "unexpected lhs");
5632 static void check_targ(struct compile_state *state, struct triple *ins)
5634 struct triple **expr;
5635 expr = triple_targ(state, ins, 0);
5636 for(;expr;expr = triple_targ(state, ins, expr)) {
5637 internal_error(state, ins, "unexpected targ");
5641 static void wipe_ins(struct compile_state *state, struct triple *ins)
5643 /* Becareful which instructions you replace the wiped
5644 * instruction with, as there are not enough slots
5645 * in all instructions to hold all others.
5647 check_targ(state, ins);
5648 unuse_rhs(state, ins);
5649 unuse_lhs(state, ins);
5652 static void mkcopy(struct compile_state *state,
5653 struct triple *ins, struct triple *rhs)
5655 wipe_ins(state, ins);
5657 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5659 use_triple(RHS(ins, 0), ins);
5662 static void mkconst(struct compile_state *state,
5663 struct triple *ins, ulong_t value)
5665 if (!is_integral(ins) && !is_pointer(ins)) {
5666 internal_error(state, ins, "unknown type to make constant\n");
5668 wipe_ins(state, ins);
5669 ins->op = OP_INTCONST;
5670 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5671 ins->u.cval = value;
5674 static void mkaddr_const(struct compile_state *state,
5675 struct triple *ins, struct triple *sdecl, ulong_t value)
5677 if (sdecl->op != OP_SDECL) {
5678 internal_error(state, ins, "bad base for addrconst");
5680 wipe_ins(state, ins);
5681 ins->op = OP_ADDRCONST;
5682 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5683 MISC(ins, 0) = sdecl;
5684 ins->u.cval = value;
5685 use_triple(sdecl, ins);
5688 /* Transform multicomponent variables into simple register variables */
5689 static void flatten_structures(struct compile_state *state)
5691 struct triple *ins, *first;
5692 first = RHS(state->main_function, 0);
5694 /* Pass one expand structure values into valvecs.
5698 struct triple *next;
5700 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5701 if (ins->op == OP_VAL_VEC) {
5704 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5705 struct triple *def, **vector;
5712 get_occurance(ins->occurance);
5713 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5716 vector = &RHS(next, 0);
5717 tptr = next->type->left;
5718 for(i = 0; i < next->type->elements; i++) {
5719 struct triple *sfield;
5722 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5723 mtype = mtype->left;
5725 sfield = deref_field(state, def, mtype->field_ident);
5728 state, op, mtype, sfield, 0);
5729 put_occurance(vector[i]->occurance);
5730 get_occurance(next->occurance);
5731 vector[i]->occurance = next->occurance;
5734 propogate_use(state, ins, next);
5735 flatten(state, ins, next);
5736 free_triple(state, ins);
5738 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5739 struct triple *src, *dst, **vector;
5747 get_occurance(ins->occurance);
5748 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5751 vector = &RHS(next, 0);
5752 tptr = next->type->left;
5753 for(i = 0; i < ins->type->elements; i++) {
5754 struct triple *dfield, *sfield;
5757 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5758 mtype = mtype->left;
5760 sfield = deref_field(state, src, mtype->field_ident);
5761 dfield = deref_field(state, dst, mtype->field_ident);
5763 state, op, mtype, dfield, sfield);
5764 put_occurance(vector[i]->occurance);
5765 get_occurance(next->occurance);
5766 vector[i]->occurance = next->occurance;
5769 propogate_use(state, ins, next);
5770 flatten(state, ins, next);
5771 free_triple(state, ins);
5775 } while(ins != first);
5776 /* Pass two flatten the valvecs.
5780 struct triple *next;
5782 if (ins->op == OP_VAL_VEC) {
5783 release_triple(state, ins);
5786 } while(ins != first);
5787 /* Pass three verify the state and set ->id to 0.
5791 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5792 if ((ins->op != OP_BLOBCONST) && (ins->op != OP_SDECL) &&
5793 ((ins->type->type & TYPE_MASK) == TYPE_STRUCT)) {
5794 internal_error(state, ins, "STRUCT_TYPE remains?");
5796 if (ins->op == OP_DOT) {
5797 internal_error(state, ins, "OP_DOT remains?");
5799 if (ins->op == OP_VAL_VEC) {
5800 internal_error(state, ins, "OP_VAL_VEC remains?");
5803 } while(ins != first);
5806 /* For those operations that cannot be simplified */
5807 static void simplify_noop(struct compile_state *state, struct triple *ins)
5812 static void simplify_smul(struct compile_state *state, struct triple *ins)
5814 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5817 RHS(ins, 0) = RHS(ins, 1);
5820 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5822 left = read_sconst(ins, &RHS(ins, 0));
5823 right = read_sconst(ins, &RHS(ins, 1));
5824 mkconst(state, ins, left * right);
5826 else if (is_zero(RHS(ins, 1))) {
5827 mkconst(state, ins, 0);
5829 else if (is_one(RHS(ins, 1))) {
5830 mkcopy(state, ins, RHS(ins, 0));
5832 else if (is_pow2(RHS(ins, 1))) {
5834 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5836 insert_triple(state, ins, val);
5837 unuse_triple(RHS(ins, 1), ins);
5838 use_triple(val, ins);
5843 static void simplify_umul(struct compile_state *state, struct triple *ins)
5845 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5848 RHS(ins, 0) = RHS(ins, 1);
5851 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5852 ulong_t left, right;
5853 left = read_const(state, ins, &RHS(ins, 0));
5854 right = read_const(state, ins, &RHS(ins, 1));
5855 mkconst(state, ins, left * right);
5857 else if (is_zero(RHS(ins, 1))) {
5858 mkconst(state, ins, 0);
5860 else if (is_one(RHS(ins, 1))) {
5861 mkcopy(state, ins, RHS(ins, 0));
5863 else if (is_pow2(RHS(ins, 1))) {
5865 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5867 insert_triple(state, ins, val);
5868 unuse_triple(RHS(ins, 1), ins);
5869 use_triple(val, ins);
5874 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5876 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5878 left = read_sconst(ins, &RHS(ins, 0));
5879 right = read_sconst(ins, &RHS(ins, 1));
5880 mkconst(state, ins, left / right);
5882 else if (is_zero(RHS(ins, 0))) {
5883 mkconst(state, ins, 0);
5885 else if (is_zero(RHS(ins, 1))) {
5886 error(state, ins, "division by zero");
5888 else if (is_one(RHS(ins, 1))) {
5889 mkcopy(state, ins, RHS(ins, 0));
5891 else if (is_pow2(RHS(ins, 1))) {
5893 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5895 insert_triple(state, ins, val);
5896 unuse_triple(RHS(ins, 1), ins);
5897 use_triple(val, ins);
5902 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5904 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5905 ulong_t left, right;
5906 left = read_const(state, ins, &RHS(ins, 0));
5907 right = read_const(state, ins, &RHS(ins, 1));
5908 mkconst(state, ins, left / right);
5910 else if (is_zero(RHS(ins, 0))) {
5911 mkconst(state, ins, 0);
5913 else if (is_zero(RHS(ins, 1))) {
5914 error(state, ins, "division by zero");
5916 else if (is_one(RHS(ins, 1))) {
5917 mkcopy(state, ins, RHS(ins, 0));
5919 else if (is_pow2(RHS(ins, 1))) {
5921 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5923 insert_triple(state, ins, val);
5924 unuse_triple(RHS(ins, 1), ins);
5925 use_triple(val, ins);
5930 static void simplify_smod(struct compile_state *state, struct triple *ins)
5932 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5934 left = read_const(state, ins, &RHS(ins, 0));
5935 right = read_const(state, ins, &RHS(ins, 1));
5936 mkconst(state, ins, left % right);
5938 else if (is_zero(RHS(ins, 0))) {
5939 mkconst(state, ins, 0);
5941 else if (is_zero(RHS(ins, 1))) {
5942 error(state, ins, "division by zero");
5944 else if (is_one(RHS(ins, 1))) {
5945 mkconst(state, ins, 0);
5947 else if (is_pow2(RHS(ins, 1))) {
5949 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5951 insert_triple(state, ins, val);
5952 unuse_triple(RHS(ins, 1), ins);
5953 use_triple(val, ins);
5957 static void simplify_umod(struct compile_state *state, struct triple *ins)
5959 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5960 ulong_t left, right;
5961 left = read_const(state, ins, &RHS(ins, 0));
5962 right = read_const(state, ins, &RHS(ins, 1));
5963 mkconst(state, ins, left % right);
5965 else if (is_zero(RHS(ins, 0))) {
5966 mkconst(state, ins, 0);
5968 else if (is_zero(RHS(ins, 1))) {
5969 error(state, ins, "division by zero");
5971 else if (is_one(RHS(ins, 1))) {
5972 mkconst(state, ins, 0);
5974 else if (is_pow2(RHS(ins, 1))) {
5976 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5978 insert_triple(state, ins, val);
5979 unuse_triple(RHS(ins, 1), ins);
5980 use_triple(val, ins);
5985 static void simplify_add(struct compile_state *state, struct triple *ins)
5987 /* start with the pointer on the left */
5988 if (is_pointer(RHS(ins, 1))) {
5991 RHS(ins, 0) = RHS(ins, 1);
5994 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5995 if (RHS(ins, 0)->op == OP_INTCONST) {
5996 ulong_t left, right;
5997 left = read_const(state, ins, &RHS(ins, 0));
5998 right = read_const(state, ins, &RHS(ins, 1));
5999 mkconst(state, ins, left + right);
6001 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
6002 struct triple *sdecl;
6003 ulong_t left, right;
6004 sdecl = MISC(RHS(ins, 0), 0);
6005 left = RHS(ins, 0)->u.cval;
6006 right = RHS(ins, 1)->u.cval;
6007 mkaddr_const(state, ins, sdecl, left + right);
6010 internal_warning(state, ins, "Optimize me!");
6013 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
6016 RHS(ins, 1) = RHS(ins, 0);
6021 static void simplify_sub(struct compile_state *state, struct triple *ins)
6023 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6024 if (RHS(ins, 0)->op == OP_INTCONST) {
6025 ulong_t left, right;
6026 left = read_const(state, ins, &RHS(ins, 0));
6027 right = read_const(state, ins, &RHS(ins, 1));
6028 mkconst(state, ins, left - right);
6030 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
6031 struct triple *sdecl;
6032 ulong_t left, right;
6033 sdecl = MISC(RHS(ins, 0), 0);
6034 left = RHS(ins, 0)->u.cval;
6035 right = RHS(ins, 1)->u.cval;
6036 mkaddr_const(state, ins, sdecl, left - right);
6039 internal_warning(state, ins, "Optimize me!");
6044 static void simplify_sl(struct compile_state *state, struct triple *ins)
6046 if (is_const(RHS(ins, 1))) {
6048 right = read_const(state, ins, &RHS(ins, 1));
6049 if (right >= (size_of(state, ins->type)*8)) {
6050 warning(state, ins, "left shift count >= width of type");
6053 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6054 ulong_t left, right;
6055 left = read_const(state, ins, &RHS(ins, 0));
6056 right = read_const(state, ins, &RHS(ins, 1));
6057 mkconst(state, ins, left << right);
6061 static void simplify_usr(struct compile_state *state, struct triple *ins)
6063 if (is_const(RHS(ins, 1))) {
6065 right = read_const(state, ins, &RHS(ins, 1));
6066 if (right >= (size_of(state, ins->type)*8)) {
6067 warning(state, ins, "right shift count >= width of type");
6070 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6071 ulong_t left, right;
6072 left = read_const(state, ins, &RHS(ins, 0));
6073 right = read_const(state, ins, &RHS(ins, 1));
6074 mkconst(state, ins, left >> right);
6078 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6080 if (is_const(RHS(ins, 1))) {
6082 right = read_const(state, ins, &RHS(ins, 1));
6083 if (right >= (size_of(state, ins->type)*8)) {
6084 warning(state, ins, "right shift count >= width of type");
6087 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6089 left = read_sconst(ins, &RHS(ins, 0));
6090 right = read_sconst(ins, &RHS(ins, 1));
6091 mkconst(state, ins, left >> right);
6095 static void simplify_and(struct compile_state *state, struct triple *ins)
6097 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6098 ulong_t left, right;
6099 left = read_const(state, ins, &RHS(ins, 0));
6100 right = read_const(state, ins, &RHS(ins, 1));
6101 mkconst(state, ins, left & right);
6105 static void simplify_or(struct compile_state *state, struct triple *ins)
6107 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6108 ulong_t left, right;
6109 left = read_const(state, ins, &RHS(ins, 0));
6110 right = read_const(state, ins, &RHS(ins, 1));
6111 mkconst(state, ins, left | right);
6115 static void simplify_xor(struct compile_state *state, struct triple *ins)
6117 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6118 ulong_t left, right;
6119 left = read_const(state, ins, &RHS(ins, 0));
6120 right = read_const(state, ins, &RHS(ins, 1));
6121 mkconst(state, ins, left ^ right);
6125 static void simplify_pos(struct compile_state *state, struct triple *ins)
6127 if (is_const(RHS(ins, 0))) {
6128 mkconst(state, ins, RHS(ins, 0)->u.cval);
6131 mkcopy(state, ins, RHS(ins, 0));
6135 static void simplify_neg(struct compile_state *state, struct triple *ins)
6137 if (is_const(RHS(ins, 0))) {
6139 left = read_const(state, ins, &RHS(ins, 0));
6140 mkconst(state, ins, -left);
6142 else if (RHS(ins, 0)->op == OP_NEG) {
6143 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6147 static void simplify_invert(struct compile_state *state, struct triple *ins)
6149 if (is_const(RHS(ins, 0))) {
6151 left = read_const(state, ins, &RHS(ins, 0));
6152 mkconst(state, ins, ~left);
6156 static void simplify_eq(struct compile_state *state, struct triple *ins)
6158 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6159 ulong_t left, right;
6160 left = read_const(state, ins, &RHS(ins, 0));
6161 right = read_const(state, ins, &RHS(ins, 1));
6162 mkconst(state, ins, left == right);
6164 else if (RHS(ins, 0) == RHS(ins, 1)) {
6165 mkconst(state, ins, 1);
6169 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6171 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6172 ulong_t left, right;
6173 left = read_const(state, ins, &RHS(ins, 0));
6174 right = read_const(state, ins, &RHS(ins, 1));
6175 mkconst(state, ins, left != right);
6177 else if (RHS(ins, 0) == RHS(ins, 1)) {
6178 mkconst(state, ins, 0);
6182 static void simplify_sless(struct compile_state *state, struct triple *ins)
6184 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6186 left = read_sconst(ins, &RHS(ins, 0));
6187 right = read_sconst(ins, &RHS(ins, 1));
6188 mkconst(state, ins, left < right);
6190 else if (RHS(ins, 0) == RHS(ins, 1)) {
6191 mkconst(state, ins, 0);
6195 static void simplify_uless(struct compile_state *state, struct triple *ins)
6197 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6198 ulong_t left, right;
6199 left = read_const(state, ins, &RHS(ins, 0));
6200 right = read_const(state, ins, &RHS(ins, 1));
6201 mkconst(state, ins, left < right);
6203 else if (is_zero(RHS(ins, 0))) {
6204 mkconst(state, ins, 1);
6206 else if (RHS(ins, 0) == RHS(ins, 1)) {
6207 mkconst(state, ins, 0);
6211 static void simplify_smore(struct compile_state *state, struct triple *ins)
6213 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6215 left = read_sconst(ins, &RHS(ins, 0));
6216 right = read_sconst(ins, &RHS(ins, 1));
6217 mkconst(state, ins, left > right);
6219 else if (RHS(ins, 0) == RHS(ins, 1)) {
6220 mkconst(state, ins, 0);
6224 static void simplify_umore(struct compile_state *state, struct triple *ins)
6226 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6227 ulong_t left, right;
6228 left = read_const(state, ins, &RHS(ins, 0));
6229 right = read_const(state, ins, &RHS(ins, 1));
6230 mkconst(state, ins, left > right);
6232 else if (is_zero(RHS(ins, 1))) {
6233 mkconst(state, ins, 1);
6235 else if (RHS(ins, 0) == RHS(ins, 1)) {
6236 mkconst(state, ins, 0);
6241 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6243 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6245 left = read_sconst(ins, &RHS(ins, 0));
6246 right = read_sconst(ins, &RHS(ins, 1));
6247 mkconst(state, ins, left <= right);
6249 else if (RHS(ins, 0) == RHS(ins, 1)) {
6250 mkconst(state, ins, 1);
6254 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6256 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6257 ulong_t left, right;
6258 left = read_const(state, ins, &RHS(ins, 0));
6259 right = read_const(state, ins, &RHS(ins, 1));
6260 mkconst(state, ins, left <= right);
6262 else if (is_zero(RHS(ins, 0))) {
6263 mkconst(state, ins, 1);
6265 else if (RHS(ins, 0) == RHS(ins, 1)) {
6266 mkconst(state, ins, 1);
6270 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6272 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6274 left = read_sconst(ins, &RHS(ins, 0));
6275 right = read_sconst(ins, &RHS(ins, 1));
6276 mkconst(state, ins, left >= right);
6278 else if (RHS(ins, 0) == RHS(ins, 1)) {
6279 mkconst(state, ins, 1);
6283 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6285 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6286 ulong_t left, right;
6287 left = read_const(state, ins, &RHS(ins, 0));
6288 right = read_const(state, ins, &RHS(ins, 1));
6289 mkconst(state, ins, left >= right);
6291 else if (is_zero(RHS(ins, 1))) {
6292 mkconst(state, ins, 1);
6294 else if (RHS(ins, 0) == RHS(ins, 1)) {
6295 mkconst(state, ins, 1);
6299 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6301 if (is_const(RHS(ins, 0))) {
6303 left = read_const(state, ins, &RHS(ins, 0));
6304 mkconst(state, ins, left == 0);
6306 /* Otherwise if I am the only user... */
6307 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6309 /* Invert a boolean operation */
6310 switch(RHS(ins, 0)->op) {
6311 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
6312 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
6313 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
6314 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
6315 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
6316 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
6317 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
6318 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
6319 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
6320 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
6321 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
6322 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
6328 mkcopy(state, ins, RHS(ins, 0));
6333 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6335 if (is_const(RHS(ins, 0))) {
6337 left = read_const(state, ins, &RHS(ins, 0));
6338 mkconst(state, ins, left != 0);
6340 else switch(RHS(ins, 0)->op) {
6341 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
6342 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
6343 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6344 mkcopy(state, ins, RHS(ins, 0));
6349 static void simplify_copy(struct compile_state *state, struct triple *ins)
6351 if (is_const(RHS(ins, 0))) {
6352 switch(RHS(ins, 0)->op) {
6356 left = read_const(state, ins, &RHS(ins, 0));
6357 mkconst(state, ins, left);
6362 struct triple *sdecl;
6364 sdecl = MISC(RHS(ins, 0), 0);
6365 offset = RHS(ins, 0)->u.cval;
6366 mkaddr_const(state, ins, sdecl, offset);
6370 internal_error(state, ins, "uknown constant");
6376 static void simplify_branch(struct compile_state *state, struct triple *ins)
6378 struct block *block;
6379 if (ins->op != OP_BRANCH) {
6380 internal_error(state, ins, "not branch");
6382 if (ins->use != 0) {
6383 internal_error(state, ins, "branch use");
6385 #warning "FIXME implement simplify branch."
6386 /* The challenge here with simplify branch is that I need to
6387 * make modifications to the control flow graph as well
6388 * as to the branch instruction itself.
6390 block = ins->u.block;
6392 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6393 struct triple *targ;
6395 value = read_const(state, ins, &RHS(ins, 0));
6396 unuse_triple(RHS(ins, 0), ins);
6397 targ = TARG(ins, 0);
6398 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6400 unuse_triple(ins->next, ins);
6401 TARG(ins, 0) = targ;
6404 unuse_triple(targ, ins);
6405 TARG(ins, 0) = ins->next;
6407 #warning "FIXME handle the case of making a branch unconditional"
6409 if (TARG(ins, 0) == ins->next) {
6410 unuse_triple(ins->next, ins);
6411 if (TRIPLE_RHS(ins->sizes)) {
6412 unuse_triple(RHS(ins, 0), ins);
6413 unuse_triple(ins->next, ins);
6415 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6418 internal_error(state, ins, "noop use != 0");
6420 #warning "FIXME handle the case of killing a branch"
6424 int phi_present(struct block *block)
6432 if (ptr->op == OP_PHI) {
6436 } while(ptr != block->last);
6440 static void simplify_label(struct compile_state *state, struct triple *ins)
6442 #warning "FIXME enable simplify_label"
6443 struct triple *first, *last;
6444 first = RHS(state->main_function, 0);
6446 /* Ignore the first and last instructions */
6447 if ((ins == first) || (ins == last)) {
6450 if (ins->use == 0) {
6453 else if (ins->prev->op == OP_LABEL) {
6454 struct block *block;
6455 block = ins->prev->u.block;
6456 /* In general it is not safe to merge one label that
6457 * imediately follows another. The problem is that the empty
6458 * looking block may have phi functions that depend on it.
6461 (!phi_present(block->left) &&
6462 !phi_present(block->right)))
6464 struct triple_set *user, *next;
6466 for(user = ins->use; user; user = next) {
6470 if (TARG(use, 0) == ins) {
6471 TARG(use, 0) = ins->prev;
6472 unuse_triple(ins, use);
6473 use_triple(ins->prev, use);
6477 internal_error(state, ins, "noop use != 0");
6483 static void simplify_phi(struct compile_state *state, struct triple *ins)
6485 struct triple **expr;
6487 expr = triple_rhs(state, ins, 0);
6488 if (!*expr || !is_const(*expr)) {
6491 value = read_const(state, ins, expr);
6492 for(;expr;expr = triple_rhs(state, ins, expr)) {
6493 if (!*expr || !is_const(*expr)) {
6496 if (value != read_const(state, ins, expr)) {
6500 mkconst(state, ins, value);
6504 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6506 if (is_const(RHS(ins, 0))) {
6508 left = read_const(state, ins, &RHS(ins, 0));
6509 mkconst(state, ins, bsf(left));
6513 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6515 if (is_const(RHS(ins, 0))) {
6517 left = read_const(state, ins, &RHS(ins, 0));
6518 mkconst(state, ins, bsr(left));
6523 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6524 static const simplify_t table_simplify[] = {
6526 #define simplify_sdivt simplify_noop
6527 #define simplify_udivt simplify_noop
6530 #define simplify_smul simplify_noop
6531 #define simplify_umul simplify_noop
6532 #define simplify_sdiv simplify_noop
6533 #define simplify_udiv simplify_noop
6534 #define simplify_smod simplify_noop
6535 #define simplify_umod simplify_noop
6538 #define simplify_add simplify_noop
6539 #define simplify_sub simplify_noop
6542 #define simplify_sl simplify_noop
6543 #define simplify_usr simplify_noop
6544 #define simplify_ssr simplify_noop
6547 #define simplify_and simplify_noop
6548 #define simplify_xor simplify_noop
6549 #define simplify_or simplify_noop
6552 #define simplify_pos simplify_noop
6553 #define simplify_neg simplify_noop
6554 #define simplify_invert simplify_noop
6558 #define simplify_eq simplify_noop
6559 #define simplify_noteq simplify_noop
6562 #define simplify_sless simplify_noop
6563 #define simplify_uless simplify_noop
6564 #define simplify_smore simplify_noop
6565 #define simplify_umore simplify_noop
6568 #define simplify_slesseq simplify_noop
6569 #define simplify_ulesseq simplify_noop
6570 #define simplify_smoreeq simplify_noop
6571 #define simplify_umoreeq simplify_noop
6574 #define simplify_lfalse simplify_noop
6577 #define simplify_ltrue simplify_noop
6581 #define simplify_copy simplify_noop
6585 #define simplify_branch simplify_noop
6588 #define simplify_label simplify_noop
6592 #define simplify_phi simplify_noop
6596 #define simplify_bsf simplify_noop
6597 #define simplify_bsr simplify_noop
6600 [OP_SDIVT ] = simplify_sdivt,
6601 [OP_UDIVT ] = simplify_udivt,
6602 [OP_SMUL ] = simplify_smul,
6603 [OP_UMUL ] = simplify_umul,
6604 [OP_SDIV ] = simplify_sdiv,
6605 [OP_UDIV ] = simplify_udiv,
6606 [OP_SMOD ] = simplify_smod,
6607 [OP_UMOD ] = simplify_umod,
6608 [OP_ADD ] = simplify_add,
6609 [OP_SUB ] = simplify_sub,
6610 [OP_SL ] = simplify_sl,
6611 [OP_USR ] = simplify_usr,
6612 [OP_SSR ] = simplify_ssr,
6613 [OP_AND ] = simplify_and,
6614 [OP_XOR ] = simplify_xor,
6615 [OP_OR ] = simplify_or,
6616 [OP_POS ] = simplify_pos,
6617 [OP_NEG ] = simplify_neg,
6618 [OP_INVERT ] = simplify_invert,
6620 [OP_EQ ] = simplify_eq,
6621 [OP_NOTEQ ] = simplify_noteq,
6622 [OP_SLESS ] = simplify_sless,
6623 [OP_ULESS ] = simplify_uless,
6624 [OP_SMORE ] = simplify_smore,
6625 [OP_UMORE ] = simplify_umore,
6626 [OP_SLESSEQ ] = simplify_slesseq,
6627 [OP_ULESSEQ ] = simplify_ulesseq,
6628 [OP_SMOREEQ ] = simplify_smoreeq,
6629 [OP_UMOREEQ ] = simplify_umoreeq,
6630 [OP_LFALSE ] = simplify_lfalse,
6631 [OP_LTRUE ] = simplify_ltrue,
6633 [OP_LOAD ] = simplify_noop,
6634 [OP_STORE ] = simplify_noop,
6636 [OP_NOOP ] = simplify_noop,
6638 [OP_INTCONST ] = simplify_noop,
6639 [OP_BLOBCONST ] = simplify_noop,
6640 [OP_ADDRCONST ] = simplify_noop,
6642 [OP_WRITE ] = simplify_noop,
6643 [OP_READ ] = simplify_noop,
6644 [OP_COPY ] = simplify_copy,
6645 [OP_PIECE ] = simplify_noop,
6646 [OP_ASM ] = simplify_noop,
6648 [OP_DOT ] = simplify_noop,
6649 [OP_VAL_VEC ] = simplify_noop,
6651 [OP_LIST ] = simplify_noop,
6652 [OP_BRANCH ] = simplify_branch,
6653 [OP_LABEL ] = simplify_label,
6654 [OP_ADECL ] = simplify_noop,
6655 [OP_SDECL ] = simplify_noop,
6656 [OP_PHI ] = simplify_phi,
6658 [OP_INB ] = simplify_noop,
6659 [OP_INW ] = simplify_noop,
6660 [OP_INL ] = simplify_noop,
6661 [OP_OUTB ] = simplify_noop,
6662 [OP_OUTW ] = simplify_noop,
6663 [OP_OUTL ] = simplify_noop,
6664 [OP_BSF ] = simplify_bsf,
6665 [OP_BSR ] = simplify_bsr,
6666 [OP_RDMSR ] = simplify_noop,
6667 [OP_WRMSR ] = simplify_noop,
6668 [OP_HLT ] = simplify_noop,
6671 static void simplify(struct compile_state *state, struct triple *ins)
6674 simplify_t do_simplify;
6678 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6682 do_simplify = table_simplify[op];
6685 internal_error(state, ins, "cannot simplify op: %d %s\n",
6689 do_simplify(state, ins);
6690 } while(ins->op != op);
6693 static void simplify_all(struct compile_state *state)
6695 struct triple *ins, *first;
6696 first = RHS(state->main_function, 0);
6699 simplify(state, ins);
6701 }while(ins != first);
6706 * ============================
6709 static void register_builtin_function(struct compile_state *state,
6710 const char *name, int op, struct type *rtype, ...)
6712 struct type *ftype, *atype, *param, **next;
6713 struct triple *def, *arg, *result, *work, *last, *first;
6714 struct hash_entry *ident;
6715 struct file_state file;
6721 /* Dummy file state to get debug handling right */
6722 memset(&file, 0, sizeof(file));
6723 file.basename = "<built-in>";
6725 file.report_line = 1;
6726 file.report_name = file.basename;
6727 file.prev = state->file;
6728 state->file = &file;
6729 state->function = name;
6731 /* Find the Parameter count */
6732 valid_op(state, op);
6733 parameters = table_ops[op].rhs;
6734 if (parameters < 0 ) {
6735 internal_error(state, 0, "Invalid builtin parameter count");
6738 /* Find the function type */
6739 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6740 next = &ftype->right;
6741 va_start(args, rtype);
6742 for(i = 0; i < parameters; i++) {
6743 atype = va_arg(args, struct type *);
6747 *next = new_type(TYPE_PRODUCT, *next, atype);
6748 next = &((*next)->right);
6756 /* Generate the needed triples */
6757 def = triple(state, OP_LIST, ftype, 0, 0);
6758 first = label(state);
6759 RHS(def, 0) = first;
6761 /* Now string them together */
6762 param = ftype->right;
6763 for(i = 0; i < parameters; i++) {
6764 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6765 atype = param->left;
6769 arg = flatten(state, first, variable(state, atype));
6770 param = param->right;
6773 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6774 result = flatten(state, first, variable(state, rtype));
6776 MISC(def, 0) = result;
6777 work = new_triple(state, op, rtype, -1, parameters);
6778 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6779 RHS(work, i) = read_expr(state, arg);
6781 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6783 /* Populate the LHS with the target registers */
6784 work = flatten(state, first, work);
6785 work->type = &void_type;
6786 param = rtype->left;
6787 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6788 internal_error(state, 0, "Invalid result type");
6790 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6791 for(i = 0; i < rtype->elements; i++) {
6792 struct triple *piece;
6794 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6795 atype = param->left;
6797 if (!TYPE_ARITHMETIC(atype->type) &&
6798 !TYPE_PTR(atype->type)) {
6799 internal_error(state, 0, "Invalid lhs type");
6801 piece = triple(state, OP_PIECE, atype, work, 0);
6803 LHS(work, i) = piece;
6804 RHS(val, i) = piece;
6809 work = write_expr(state, result, work);
6811 work = flatten(state, first, work);
6812 last = flatten(state, first, label(state));
6813 name_len = strlen(name);
6814 ident = lookup(state, name, name_len);
6815 symbol(state, ident, &ident->sym_ident, def, ftype);
6817 state->file = file.prev;
6818 state->function = 0;
6820 fprintf(stdout, "\n");
6821 loc(stdout, state, 0);
6822 fprintf(stdout, "\n__________ builtin_function _________\n");
6823 print_triple(state, def);
6824 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6828 static struct type *partial_struct(struct compile_state *state,
6829 const char *field_name, struct type *type, struct type *rest)
6831 struct hash_entry *field_ident;
6832 struct type *result;
6835 field_name_len = strlen(field_name);
6836 field_ident = lookup(state, field_name, field_name_len);
6838 result = clone_type(0, type);
6839 result->field_ident = field_ident;
6842 result = new_type(TYPE_PRODUCT, result, rest);
6847 static struct type *register_builtin_type(struct compile_state *state,
6848 const char *name, struct type *type)
6850 struct hash_entry *ident;
6853 name_len = strlen(name);
6854 ident = lookup(state, name, name_len);
6856 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6857 ulong_t elements = 0;
6859 type = new_type(TYPE_STRUCT, type, 0);
6861 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6863 field = field->right;
6866 symbol(state, ident, &ident->sym_struct, 0, type);
6867 type->type_ident = ident;
6868 type->elements = elements;
6870 symbol(state, ident, &ident->sym_ident, 0, type);
6871 ident->tok = TOK_TYPE_NAME;
6876 static void register_builtins(struct compile_state *state)
6878 struct type *div_type, *ldiv_type;
6879 struct type *udiv_type, *uldiv_type;
6880 struct type *msr_type;
6882 div_type = register_builtin_type(state, "__builtin_div_t",
6883 partial_struct(state, "quot", &int_type,
6884 partial_struct(state, "rem", &int_type, 0)));
6885 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
6886 partial_struct(state, "quot", &long_type,
6887 partial_struct(state, "rem", &long_type, 0)));
6888 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
6889 partial_struct(state, "quot", &uint_type,
6890 partial_struct(state, "rem", &uint_type, 0)));
6891 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
6892 partial_struct(state, "quot", &ulong_type,
6893 partial_struct(state, "rem", &ulong_type, 0)));
6895 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
6896 &int_type, &int_type);
6897 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
6898 &long_type, &long_type);
6899 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
6900 &uint_type, &uint_type);
6901 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
6902 &ulong_type, &ulong_type);
6904 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6906 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6908 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6911 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6912 &uchar_type, &ushort_type);
6913 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6914 &ushort_type, &ushort_type);
6915 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6916 &uint_type, &ushort_type);
6918 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6920 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6923 msr_type = register_builtin_type(state, "__builtin_msr_t",
6924 partial_struct(state, "lo", &ulong_type,
6925 partial_struct(state, "hi", &ulong_type, 0)));
6927 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6929 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6930 &ulong_type, &ulong_type, &ulong_type);
6932 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6936 static struct type *declarator(
6937 struct compile_state *state, struct type *type,
6938 struct hash_entry **ident, int need_ident);
6939 static void decl(struct compile_state *state, struct triple *first);
6940 static struct type *specifier_qualifier_list(struct compile_state *state);
6941 static int isdecl_specifier(int tok);
6942 static struct type *decl_specifiers(struct compile_state *state);
6943 static int istype(int tok);
6944 static struct triple *expr(struct compile_state *state);
6945 static struct triple *assignment_expr(struct compile_state *state);
6946 static struct type *type_name(struct compile_state *state);
6947 static void statement(struct compile_state *state, struct triple *fist);
6949 static struct triple *call_expr(
6950 struct compile_state *state, struct triple *func)
6953 struct type *param, *type;
6954 ulong_t pvals, index;
6956 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6957 error(state, 0, "Called object is not a function");
6959 if (func->op != OP_LIST) {
6960 internal_error(state, 0, "improper function");
6962 eat(state, TOK_LPAREN);
6963 /* Find the return type without any specifiers */
6964 type = clone_type(0, func->type->left);
6965 def = new_triple(state, OP_CALL, func->type, -1, -1);
6968 pvals = TRIPLE_RHS(def->sizes);
6969 MISC(def, 0) = func;
6971 param = func->type->right;
6972 for(index = 0; index < pvals; index++) {
6974 struct type *arg_type;
6975 val = read_expr(state, assignment_expr(state));
6977 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6978 arg_type = param->left;
6980 write_compatible(state, arg_type, val->type);
6981 RHS(def, index) = val;
6982 if (index != (pvals - 1)) {
6983 eat(state, TOK_COMMA);
6984 param = param->right;
6987 eat(state, TOK_RPAREN);
6992 static struct triple *character_constant(struct compile_state *state)
6996 const signed char *str, *end;
6999 eat(state, TOK_LIT_CHAR);
7000 tk = &state->token[0];
7001 str = tk->val.str + 1;
7002 str_len = tk->str_len - 2;
7004 error(state, 0, "empty character constant");
7006 end = str + str_len;
7007 c = char_value(state, &str, end);
7009 error(state, 0, "multibyte character constant not supported");
7011 def = int_const(state, &char_type, (ulong_t)((long_t)c));
7015 static struct triple *string_constant(struct compile_state *state)
7020 const signed char *str, *end;
7021 signed char *buf, *ptr;
7025 type = new_type(TYPE_ARRAY, &char_type, 0);
7027 /* The while loop handles string concatenation */
7029 eat(state, TOK_LIT_STRING);
7030 tk = &state->token[0];
7031 str = tk->val.str + 1;
7032 str_len = tk->str_len - 2;
7034 error(state, 0, "negative string constant length");
7036 end = str + str_len;
7038 buf = xmalloc(type->elements + str_len + 1, "string_constant");
7039 memcpy(buf, ptr, type->elements);
7040 ptr = buf + type->elements;
7042 *ptr++ = char_value(state, &str, end);
7044 type->elements = ptr - buf;
7045 } while(peek(state) == TOK_LIT_STRING);
7047 type->elements += 1;
7048 def = triple(state, OP_BLOBCONST, type, 0, 0);
7054 static struct triple *integer_constant(struct compile_state *state)
7063 eat(state, TOK_LIT_INT);
7064 tk = &state->token[0];
7066 decimal = (tk->val.str[0] != '0');
7067 val = strtoul(tk->val.str, &end, 0);
7068 if ((val == ULONG_MAX) && (errno == ERANGE)) {
7069 error(state, 0, "Integer constant to large");
7072 if ((*end == 'u') || (*end == 'U')) {
7076 if ((*end == 'l') || (*end == 'L')) {
7080 if ((*end == 'u') || (*end == 'U')) {
7085 error(state, 0, "Junk at end of integer constant");
7092 if (!decimal && (val > LONG_MAX)) {
7098 if (val > UINT_MAX) {
7104 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
7107 else if (!decimal && (val > LONG_MAX)) {
7110 else if (val > INT_MAX) {
7114 def = int_const(state, type, val);
7118 static struct triple *primary_expr(struct compile_state *state)
7126 struct hash_entry *ident;
7127 /* Here ident is either:
7130 * an enumeration constant.
7132 eat(state, TOK_IDENT);
7133 ident = state->token[0].ident;
7134 if (!ident->sym_ident) {
7135 error(state, 0, "%s undeclared", ident->name);
7137 def = ident->sym_ident->def;
7140 case TOK_ENUM_CONST:
7141 /* Here ident is an enumeration constant */
7142 eat(state, TOK_ENUM_CONST);
7147 eat(state, TOK_LPAREN);
7149 eat(state, TOK_RPAREN);
7152 def = integer_constant(state);
7155 eat(state, TOK_LIT_FLOAT);
7156 error(state, 0, "Floating point constants not supported");
7161 def = character_constant(state);
7163 case TOK_LIT_STRING:
7164 def = string_constant(state);
7168 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7173 static struct triple *postfix_expr(struct compile_state *state)
7177 def = primary_expr(state);
7179 struct triple *left;
7183 switch((tok = peek(state))) {
7185 eat(state, TOK_LBRACKET);
7186 def = mk_subscript_expr(state, left, expr(state));
7187 eat(state, TOK_RBRACKET);
7190 def = call_expr(state, def);
7194 struct hash_entry *field;
7195 eat(state, TOK_DOT);
7196 eat(state, TOK_IDENT);
7197 field = state->token[0].ident;
7198 def = deref_field(state, def, field);
7203 struct hash_entry *field;
7204 eat(state, TOK_ARROW);
7205 eat(state, TOK_IDENT);
7206 field = state->token[0].ident;
7207 def = mk_deref_expr(state, read_expr(state, def));
7208 def = deref_field(state, def, field);
7212 eat(state, TOK_PLUSPLUS);
7213 def = mk_post_inc_expr(state, left);
7215 case TOK_MINUSMINUS:
7216 eat(state, TOK_MINUSMINUS);
7217 def = mk_post_dec_expr(state, left);
7227 static struct triple *cast_expr(struct compile_state *state);
7229 static struct triple *unary_expr(struct compile_state *state)
7231 struct triple *def, *right;
7233 switch((tok = peek(state))) {
7235 eat(state, TOK_PLUSPLUS);
7236 def = mk_pre_inc_expr(state, unary_expr(state));
7238 case TOK_MINUSMINUS:
7239 eat(state, TOK_MINUSMINUS);
7240 def = mk_pre_dec_expr(state, unary_expr(state));
7243 eat(state, TOK_AND);
7244 def = mk_addr_expr(state, cast_expr(state), 0);
7247 eat(state, TOK_STAR);
7248 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7251 eat(state, TOK_PLUS);
7252 right = read_expr(state, cast_expr(state));
7253 arithmetic(state, right);
7254 def = integral_promotion(state, right);
7257 eat(state, TOK_MINUS);
7258 right = read_expr(state, cast_expr(state));
7259 arithmetic(state, right);
7260 def = integral_promotion(state, right);
7261 def = triple(state, OP_NEG, def->type, def, 0);
7264 eat(state, TOK_TILDE);
7265 right = read_expr(state, cast_expr(state));
7266 integral(state, right);
7267 def = integral_promotion(state, right);
7268 def = triple(state, OP_INVERT, def->type, def, 0);
7271 eat(state, TOK_BANG);
7272 right = read_expr(state, cast_expr(state));
7274 def = lfalse_expr(state, right);
7280 eat(state, TOK_SIZEOF);
7282 tok2 = peek2(state);
7283 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7284 eat(state, TOK_LPAREN);
7285 type = type_name(state);
7286 eat(state, TOK_RPAREN);
7289 struct triple *expr;
7290 expr = unary_expr(state);
7292 release_expr(state, expr);
7294 def = int_const(state, &ulong_type, size_of(state, type));
7301 eat(state, TOK_ALIGNOF);
7303 tok2 = peek2(state);
7304 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7305 eat(state, TOK_LPAREN);
7306 type = type_name(state);
7307 eat(state, TOK_RPAREN);
7310 struct triple *expr;
7311 expr = unary_expr(state);
7313 release_expr(state, expr);
7315 def = int_const(state, &ulong_type, align_of(state, type));
7319 def = postfix_expr(state);
7325 static struct triple *cast_expr(struct compile_state *state)
7330 tok2 = peek2(state);
7331 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7333 eat(state, TOK_LPAREN);
7334 type = type_name(state);
7335 eat(state, TOK_RPAREN);
7336 def = read_expr(state, cast_expr(state));
7337 def = triple(state, OP_COPY, type, def, 0);
7340 def = unary_expr(state);
7345 static struct triple *mult_expr(struct compile_state *state)
7349 def = cast_expr(state);
7351 struct triple *left, *right;
7352 struct type *result_type;
7355 switch(tok = (peek(state))) {
7359 left = read_expr(state, def);
7360 arithmetic(state, left);
7364 right = read_expr(state, cast_expr(state));
7365 arithmetic(state, right);
7367 result_type = arithmetic_result(state, left, right);
7368 sign = is_signed(result_type);
7371 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7372 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
7373 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
7375 def = triple(state, op, result_type, left, right);
7385 static struct triple *add_expr(struct compile_state *state)
7389 def = mult_expr(state);
7392 switch( peek(state)) {
7394 eat(state, TOK_PLUS);
7395 def = mk_add_expr(state, def, mult_expr(state));
7398 eat(state, TOK_MINUS);
7399 def = mk_sub_expr(state, def, mult_expr(state));
7409 static struct triple *shift_expr(struct compile_state *state)
7413 def = add_expr(state);
7415 struct triple *left, *right;
7418 switch((tok = peek(state))) {
7421 left = read_expr(state, def);
7422 integral(state, left);
7423 left = integral_promotion(state, left);
7427 right = read_expr(state, add_expr(state));
7428 integral(state, right);
7429 right = integral_promotion(state, right);
7431 op = (tok == TOK_SL)? OP_SL :
7432 is_signed(left->type)? OP_SSR: OP_USR;
7434 def = triple(state, op, left->type, left, right);
7444 static struct triple *relational_expr(struct compile_state *state)
7446 #warning "Extend relational exprs to work on more than arithmetic types"
7449 def = shift_expr(state);
7451 struct triple *left, *right;
7452 struct type *arg_type;
7455 switch((tok = peek(state))) {
7460 left = read_expr(state, def);
7461 arithmetic(state, left);
7465 right = read_expr(state, shift_expr(state));
7466 arithmetic(state, right);
7468 arg_type = arithmetic_result(state, left, right);
7469 sign = is_signed(arg_type);
7472 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7473 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7474 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7475 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7477 def = triple(state, op, &int_type, left, right);
7487 static struct triple *equality_expr(struct compile_state *state)
7489 #warning "Extend equality exprs to work on more than arithmetic types"
7492 def = relational_expr(state);
7494 struct triple *left, *right;
7497 switch((tok = peek(state))) {
7500 left = read_expr(state, def);
7501 arithmetic(state, left);
7503 right = read_expr(state, relational_expr(state));
7504 arithmetic(state, right);
7505 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7506 def = triple(state, op, &int_type, left, right);
7516 static struct triple *and_expr(struct compile_state *state)
7519 def = equality_expr(state);
7520 while(peek(state) == TOK_AND) {
7521 struct triple *left, *right;
7522 struct type *result_type;
7523 left = read_expr(state, def);
7524 integral(state, left);
7525 eat(state, TOK_AND);
7526 right = read_expr(state, equality_expr(state));
7527 integral(state, right);
7528 result_type = arithmetic_result(state, left, right);
7529 def = triple(state, OP_AND, result_type, left, right);
7534 static struct triple *xor_expr(struct compile_state *state)
7537 def = and_expr(state);
7538 while(peek(state) == TOK_XOR) {
7539 struct triple *left, *right;
7540 struct type *result_type;
7541 left = read_expr(state, def);
7542 integral(state, left);
7543 eat(state, TOK_XOR);
7544 right = read_expr(state, and_expr(state));
7545 integral(state, right);
7546 result_type = arithmetic_result(state, left, right);
7547 def = triple(state, OP_XOR, result_type, left, right);
7552 static struct triple *or_expr(struct compile_state *state)
7555 def = xor_expr(state);
7556 while(peek(state) == TOK_OR) {
7557 struct triple *left, *right;
7558 struct type *result_type;
7559 left = read_expr(state, def);
7560 integral(state, left);
7562 right = read_expr(state, xor_expr(state));
7563 integral(state, right);
7564 result_type = arithmetic_result(state, left, right);
7565 def = triple(state, OP_OR, result_type, left, right);
7570 static struct triple *land_expr(struct compile_state *state)
7573 def = or_expr(state);
7574 while(peek(state) == TOK_LOGAND) {
7575 struct triple *left, *right;
7576 left = read_expr(state, def);
7578 eat(state, TOK_LOGAND);
7579 right = read_expr(state, or_expr(state));
7582 def = triple(state, OP_LAND, &int_type,
7583 ltrue_expr(state, left),
7584 ltrue_expr(state, right));
7589 static struct triple *lor_expr(struct compile_state *state)
7592 def = land_expr(state);
7593 while(peek(state) == TOK_LOGOR) {
7594 struct triple *left, *right;
7595 left = read_expr(state, def);
7597 eat(state, TOK_LOGOR);
7598 right = read_expr(state, land_expr(state));
7601 def = triple(state, OP_LOR, &int_type,
7602 ltrue_expr(state, left),
7603 ltrue_expr(state, right));
7608 static struct triple *conditional_expr(struct compile_state *state)
7611 def = lor_expr(state);
7612 if (peek(state) == TOK_QUEST) {
7613 struct triple *test, *left, *right;
7615 test = ltrue_expr(state, read_expr(state, def));
7616 eat(state, TOK_QUEST);
7617 left = read_expr(state, expr(state));
7618 eat(state, TOK_COLON);
7619 right = read_expr(state, conditional_expr(state));
7621 def = cond_expr(state, test, left, right);
7626 static struct triple *eval_const_expr(
7627 struct compile_state *state, struct triple *expr)
7630 if (is_const(expr)) {
7634 /* If we don't start out as a constant simplify into one */
7635 struct triple *head, *ptr;
7636 head = label(state); /* dummy initial triple */
7637 flatten(state, head, expr);
7638 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7639 simplify(state, ptr);
7641 /* Remove the constant value the tail of the list */
7643 def->prev->next = def->next;
7644 def->next->prev = def->prev;
7645 def->next = def->prev = def;
7646 if (!is_const(def)) {
7647 error(state, 0, "Not a constant expression");
7649 /* Free the intermediate expressions */
7650 while(head->next != head) {
7651 release_triple(state, head->next);
7653 free_triple(state, head);
7658 static struct triple *constant_expr(struct compile_state *state)
7660 return eval_const_expr(state, conditional_expr(state));
7663 static struct triple *assignment_expr(struct compile_state *state)
7665 struct triple *def, *left, *right;
7667 /* The C grammer in K&R shows assignment expressions
7668 * only taking unary expressions as input on their
7669 * left hand side. But specifies the precedence of
7670 * assignemnt as the lowest operator except for comma.
7672 * Allowing conditional expressions on the left hand side
7673 * of an assignement results in a grammar that accepts
7674 * a larger set of statements than standard C. As long
7675 * as the subset of the grammar that is standard C behaves
7676 * correctly this should cause no problems.
7678 * For the extra token strings accepted by the grammar
7679 * none of them should produce a valid lvalue, so they
7680 * should not produce functioning programs.
7682 * GCC has this bug as well, so surprises should be minimal.
7684 def = conditional_expr(state);
7686 switch((tok = peek(state))) {
7688 lvalue(state, left);
7690 def = write_expr(state, left,
7691 read_expr(state, assignment_expr(state)));
7696 lvalue(state, left);
7697 arithmetic(state, left);
7699 right = read_expr(state, assignment_expr(state));
7700 arithmetic(state, right);
7702 sign = is_signed(left->type);
7705 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7706 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7707 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7709 def = write_expr(state, left,
7710 triple(state, op, left->type,
7711 read_expr(state, left), right));
7714 lvalue(state, left);
7715 eat(state, TOK_PLUSEQ);
7716 def = write_expr(state, left,
7717 mk_add_expr(state, left, assignment_expr(state)));
7720 lvalue(state, left);
7721 eat(state, TOK_MINUSEQ);
7722 def = write_expr(state, left,
7723 mk_sub_expr(state, left, assignment_expr(state)));
7730 lvalue(state, left);
7731 integral(state, left);
7733 right = read_expr(state, assignment_expr(state));
7734 integral(state, right);
7735 right = integral_promotion(state, right);
7736 sign = is_signed(left->type);
7739 case TOK_SLEQ: op = OP_SL; break;
7740 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7741 case TOK_ANDEQ: op = OP_AND; break;
7742 case TOK_XOREQ: op = OP_XOR; break;
7743 case TOK_OREQ: op = OP_OR; break;
7745 def = write_expr(state, left,
7746 triple(state, op, left->type,
7747 read_expr(state, left), right));
7753 static struct triple *expr(struct compile_state *state)
7756 def = assignment_expr(state);
7757 while(peek(state) == TOK_COMMA) {
7758 struct triple *left, *right;
7760 eat(state, TOK_COMMA);
7761 right = assignment_expr(state);
7762 def = triple(state, OP_COMMA, right->type, left, right);
7767 static void expr_statement(struct compile_state *state, struct triple *first)
7769 if (peek(state) != TOK_SEMI) {
7770 flatten(state, first, expr(state));
7772 eat(state, TOK_SEMI);
7775 static void if_statement(struct compile_state *state, struct triple *first)
7777 struct triple *test, *jmp1, *jmp2, *middle, *end;
7779 jmp1 = jmp2 = middle = 0;
7781 eat(state, TOK_LPAREN);
7784 /* Cleanup and invert the test */
7785 test = lfalse_expr(state, read_expr(state, test));
7786 eat(state, TOK_RPAREN);
7787 /* Generate the needed pieces */
7788 middle = label(state);
7789 jmp1 = branch(state, middle, test);
7790 /* Thread the pieces together */
7791 flatten(state, first, test);
7792 flatten(state, first, jmp1);
7793 flatten(state, first, label(state));
7794 statement(state, first);
7795 if (peek(state) == TOK_ELSE) {
7796 eat(state, TOK_ELSE);
7797 /* Generate the rest of the pieces */
7799 jmp2 = branch(state, end, 0);
7800 /* Thread them together */
7801 flatten(state, first, jmp2);
7802 flatten(state, first, middle);
7803 statement(state, first);
7804 flatten(state, first, end);
7807 flatten(state, first, middle);
7811 static void for_statement(struct compile_state *state, struct triple *first)
7813 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7814 struct triple *label1, *label2, *label3;
7815 struct hash_entry *ident;
7817 eat(state, TOK_FOR);
7818 eat(state, TOK_LPAREN);
7819 head = test = tail = jmp1 = jmp2 = 0;
7820 if (peek(state) != TOK_SEMI) {
7823 eat(state, TOK_SEMI);
7824 if (peek(state) != TOK_SEMI) {
7827 test = ltrue_expr(state, read_expr(state, test));
7829 eat(state, TOK_SEMI);
7830 if (peek(state) != TOK_RPAREN) {
7833 eat(state, TOK_RPAREN);
7834 /* Generate the needed pieces */
7835 label1 = label(state);
7836 label2 = label(state);
7837 label3 = label(state);
7839 jmp1 = branch(state, label3, 0);
7840 jmp2 = branch(state, label1, test);
7843 jmp2 = branch(state, label1, 0);
7846 /* Remember where break and continue go */
7848 ident = state->i_break;
7849 symbol(state, ident, &ident->sym_ident, end, end->type);
7850 ident = state->i_continue;
7851 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7852 /* Now include the body */
7853 flatten(state, first, head);
7854 flatten(state, first, jmp1);
7855 flatten(state, first, label1);
7856 statement(state, first);
7857 flatten(state, first, label2);
7858 flatten(state, first, tail);
7859 flatten(state, first, label3);
7860 flatten(state, first, test);
7861 flatten(state, first, jmp2);
7862 flatten(state, first, end);
7863 /* Cleanup the break/continue scope */
7867 static void while_statement(struct compile_state *state, struct triple *first)
7869 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7870 struct hash_entry *ident;
7871 eat(state, TOK_WHILE);
7872 eat(state, TOK_LPAREN);
7875 test = ltrue_expr(state, read_expr(state, test));
7876 eat(state, TOK_RPAREN);
7877 /* Generate the needed pieces */
7878 label1 = label(state);
7879 label2 = label(state);
7880 jmp1 = branch(state, label2, 0);
7881 jmp2 = branch(state, label1, test);
7883 /* Remember where break and continue go */
7885 ident = state->i_break;
7886 symbol(state, ident, &ident->sym_ident, end, end->type);
7887 ident = state->i_continue;
7888 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7889 /* Thread them together */
7890 flatten(state, first, jmp1);
7891 flatten(state, first, label1);
7892 statement(state, first);
7893 flatten(state, first, label2);
7894 flatten(state, first, test);
7895 flatten(state, first, jmp2);
7896 flatten(state, first, end);
7897 /* Cleanup the break/continue scope */
7901 static void do_statement(struct compile_state *state, struct triple *first)
7903 struct triple *label1, *label2, *test, *end;
7904 struct hash_entry *ident;
7906 /* Generate the needed pieces */
7907 label1 = label(state);
7908 label2 = label(state);
7910 /* Remember where break and continue go */
7912 ident = state->i_break;
7913 symbol(state, ident, &ident->sym_ident, end, end->type);
7914 ident = state->i_continue;
7915 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7916 /* Now include the body */
7917 flatten(state, first, label1);
7918 statement(state, first);
7919 /* Cleanup the break/continue scope */
7921 /* Eat the rest of the loop */
7922 eat(state, TOK_WHILE);
7923 eat(state, TOK_LPAREN);
7924 test = read_expr(state, expr(state));
7926 eat(state, TOK_RPAREN);
7927 eat(state, TOK_SEMI);
7928 /* Thread the pieces together */
7929 test = ltrue_expr(state, test);
7930 flatten(state, first, label2);
7931 flatten(state, first, test);
7932 flatten(state, first, branch(state, label1, test));
7933 flatten(state, first, end);
7937 static void return_statement(struct compile_state *state, struct triple *first)
7939 struct triple *jmp, *mv, *dest, *var, *val;
7941 eat(state, TOK_RETURN);
7943 #warning "FIXME implement a more general excess branch elimination"
7945 /* If we have a return value do some more work */
7946 if (peek(state) != TOK_SEMI) {
7947 val = read_expr(state, expr(state));
7949 eat(state, TOK_SEMI);
7951 /* See if this last statement in a function */
7952 last = ((peek(state) == TOK_RBRACE) &&
7953 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7955 /* Find the return variable */
7956 var = MISC(state->main_function, 0);
7957 /* Find the return destination */
7958 dest = RHS(state->main_function, 0)->prev;
7960 /* If needed generate a jump instruction */
7962 jmp = branch(state, dest, 0);
7964 /* If needed generate an assignment instruction */
7966 mv = write_expr(state, var, val);
7968 /* Now put the code together */
7970 flatten(state, first, mv);
7971 flatten(state, first, jmp);
7974 flatten(state, first, jmp);
7978 static void break_statement(struct compile_state *state, struct triple *first)
7980 struct triple *dest;
7981 eat(state, TOK_BREAK);
7982 eat(state, TOK_SEMI);
7983 if (!state->i_break->sym_ident) {
7984 error(state, 0, "break statement not within loop or switch");
7986 dest = state->i_break->sym_ident->def;
7987 flatten(state, first, branch(state, dest, 0));
7990 static void continue_statement(struct compile_state *state, struct triple *first)
7992 struct triple *dest;
7993 eat(state, TOK_CONTINUE);
7994 eat(state, TOK_SEMI);
7995 if (!state->i_continue->sym_ident) {
7996 error(state, 0, "continue statement outside of a loop");
7998 dest = state->i_continue->sym_ident->def;
7999 flatten(state, first, branch(state, dest, 0));
8002 static void goto_statement(struct compile_state *state, struct triple *first)
8004 struct hash_entry *ident;
8005 eat(state, TOK_GOTO);
8006 eat(state, TOK_IDENT);
8007 ident = state->token[0].ident;
8008 if (!ident->sym_label) {
8009 /* If this is a forward branch allocate the label now,
8010 * it will be flattend in the appropriate location later.
8014 label_symbol(state, ident, ins);
8016 eat(state, TOK_SEMI);
8018 flatten(state, first, branch(state, ident->sym_label->def, 0));
8021 static void labeled_statement(struct compile_state *state, struct triple *first)
8024 struct hash_entry *ident;
8025 eat(state, TOK_IDENT);
8027 ident = state->token[0].ident;
8028 if (ident->sym_label && ident->sym_label->def) {
8029 ins = ident->sym_label->def;
8030 put_occurance(ins->occurance);
8031 ins->occurance = new_occurance(state);
8035 label_symbol(state, ident, ins);
8037 if (ins->id & TRIPLE_FLAG_FLATTENED) {
8038 error(state, 0, "label %s already defined", ident->name);
8040 flatten(state, first, ins);
8042 eat(state, TOK_COLON);
8043 statement(state, first);
8046 static void switch_statement(struct compile_state *state, struct triple *first)
8049 eat(state, TOK_SWITCH);
8050 eat(state, TOK_LPAREN);
8052 eat(state, TOK_RPAREN);
8053 statement(state, first);
8054 error(state, 0, "switch statements are not implemented");
8058 static void case_statement(struct compile_state *state, struct triple *first)
8061 eat(state, TOK_CASE);
8062 constant_expr(state);
8063 eat(state, TOK_COLON);
8064 statement(state, first);
8065 error(state, 0, "case statements are not implemented");
8069 static void default_statement(struct compile_state *state, struct triple *first)
8072 eat(state, TOK_DEFAULT);
8073 eat(state, TOK_COLON);
8074 statement(state, first);
8075 error(state, 0, "default statements are not implemented");
8079 static void asm_statement(struct compile_state *state, struct triple *first)
8081 struct asm_info *info;
8083 struct triple *constraint;
8084 struct triple *expr;
8085 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
8086 struct triple *def, *asm_str;
8087 int out, in, clobbers, more, colons, i;
8089 eat(state, TOK_ASM);
8090 /* For now ignore the qualifiers */
8091 switch(peek(state)) {
8093 eat(state, TOK_CONST);
8096 eat(state, TOK_VOLATILE);
8099 eat(state, TOK_LPAREN);
8100 asm_str = string_constant(state);
8103 out = in = clobbers = 0;
8105 if ((colons == 0) && (peek(state) == TOK_COLON)) {
8106 eat(state, TOK_COLON);
8108 more = (peek(state) == TOK_LIT_STRING);
8111 struct triple *constraint;
8114 if (out > MAX_LHS) {
8115 error(state, 0, "Maximum output count exceeded.");
8117 constraint = string_constant(state);
8118 str = constraint->u.blob;
8119 if (str[0] != '=') {
8120 error(state, 0, "Output constraint does not start with =");
8122 constraint->u.blob = str + 1;
8123 eat(state, TOK_LPAREN);
8124 var = conditional_expr(state);
8125 eat(state, TOK_RPAREN);
8128 out_param[out].constraint = constraint;
8129 out_param[out].expr = var;
8130 if (peek(state) == TOK_COMMA) {
8131 eat(state, TOK_COMMA);
8138 if ((colons == 1) && (peek(state) == TOK_COLON)) {
8139 eat(state, TOK_COLON);
8141 more = (peek(state) == TOK_LIT_STRING);
8144 struct triple *constraint;
8148 error(state, 0, "Maximum input count exceeded.");
8150 constraint = string_constant(state);
8151 str = constraint->u.blob;
8152 if (digitp(str[0] && str[1] == '\0')) {
8154 val = digval(str[0]);
8155 if ((val < 0) || (val >= out)) {
8156 error(state, 0, "Invalid input constraint %d", val);
8159 eat(state, TOK_LPAREN);
8160 val = conditional_expr(state);
8161 eat(state, TOK_RPAREN);
8163 in_param[in].constraint = constraint;
8164 in_param[in].expr = val;
8165 if (peek(state) == TOK_COMMA) {
8166 eat(state, TOK_COMMA);
8174 if ((colons == 2) && (peek(state) == TOK_COLON)) {
8175 eat(state, TOK_COLON);
8177 more = (peek(state) == TOK_LIT_STRING);
8179 struct triple *clobber;
8181 if ((clobbers + out) > MAX_LHS) {
8182 error(state, 0, "Maximum clobber limit exceeded.");
8184 clobber = string_constant(state);
8185 eat(state, TOK_RPAREN);
8187 clob_param[clobbers].constraint = clobber;
8188 if (peek(state) == TOK_COMMA) {
8189 eat(state, TOK_COMMA);
8195 eat(state, TOK_RPAREN);
8196 eat(state, TOK_SEMI);
8199 info = xcmalloc(sizeof(*info), "asm_info");
8200 info->str = asm_str->u.blob;
8201 free_triple(state, asm_str);
8203 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8204 def->u.ainfo = info;
8206 /* Find the register constraints */
8207 for(i = 0; i < out; i++) {
8208 struct triple *constraint;
8209 constraint = out_param[i].constraint;
8210 info->tmpl.lhs[i] = arch_reg_constraint(state,
8211 out_param[i].expr->type, constraint->u.blob);
8212 free_triple(state, constraint);
8214 for(; i - out < clobbers; i++) {
8215 struct triple *constraint;
8216 constraint = clob_param[i - out].constraint;
8217 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8218 free_triple(state, constraint);
8220 for(i = 0; i < in; i++) {
8221 struct triple *constraint;
8223 constraint = in_param[i].constraint;
8224 str = constraint->u.blob;
8225 if (digitp(str[0]) && str[1] == '\0') {
8226 struct reg_info cinfo;
8228 val = digval(str[0]);
8229 cinfo.reg = info->tmpl.lhs[val].reg;
8230 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8231 cinfo.regcm &= info->tmpl.lhs[val].regcm;
8232 if (cinfo.reg == REG_UNSET) {
8233 cinfo.reg = REG_VIRT0 + val;
8235 if (cinfo.regcm == 0) {
8236 error(state, 0, "No registers for %d", val);
8238 info->tmpl.lhs[val] = cinfo;
8239 info->tmpl.rhs[i] = cinfo;
8242 info->tmpl.rhs[i] = arch_reg_constraint(state,
8243 in_param[i].expr->type, str);
8245 free_triple(state, constraint);
8248 /* Now build the helper expressions */
8249 for(i = 0; i < in; i++) {
8250 RHS(def, i) = read_expr(state,in_param[i].expr);
8252 flatten(state, first, def);
8253 for(i = 0; i < out; i++) {
8254 struct triple *piece;
8255 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8257 LHS(def, i) = piece;
8258 flatten(state, first,
8259 write_expr(state, out_param[i].expr, piece));
8261 for(; i - out < clobbers; i++) {
8262 struct triple *piece;
8263 piece = triple(state, OP_PIECE, &void_type, def, 0);
8265 LHS(def, i) = piece;
8266 flatten(state, first, piece);
8271 static int isdecl(int tok)
8294 case TOK_TYPE_NAME: /* typedef name */
8301 static void compound_statement(struct compile_state *state, struct triple *first)
8303 eat(state, TOK_LBRACE);
8306 /* statement-list opt */
8307 while (peek(state) != TOK_RBRACE) {
8308 statement(state, first);
8311 eat(state, TOK_RBRACE);
8314 static void statement(struct compile_state *state, struct triple *first)
8318 if (tok == TOK_LBRACE) {
8319 compound_statement(state, first);
8321 else if (tok == TOK_IF) {
8322 if_statement(state, first);
8324 else if (tok == TOK_FOR) {
8325 for_statement(state, first);
8327 else if (tok == TOK_WHILE) {
8328 while_statement(state, first);
8330 else if (tok == TOK_DO) {
8331 do_statement(state, first);
8333 else if (tok == TOK_RETURN) {
8334 return_statement(state, first);
8336 else if (tok == TOK_BREAK) {
8337 break_statement(state, first);
8339 else if (tok == TOK_CONTINUE) {
8340 continue_statement(state, first);
8342 else if (tok == TOK_GOTO) {
8343 goto_statement(state, first);
8345 else if (tok == TOK_SWITCH) {
8346 switch_statement(state, first);
8348 else if (tok == TOK_ASM) {
8349 asm_statement(state, first);
8351 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8352 labeled_statement(state, first);
8354 else if (tok == TOK_CASE) {
8355 case_statement(state, first);
8357 else if (tok == TOK_DEFAULT) {
8358 default_statement(state, first);
8360 else if (isdecl(tok)) {
8361 /* This handles C99 intermixing of statements and decls */
8365 expr_statement(state, first);
8369 static struct type *param_decl(struct compile_state *state)
8372 struct hash_entry *ident;
8373 /* Cheat so the declarator will know we are not global */
8376 type = decl_specifiers(state);
8377 type = declarator(state, type, &ident, 0);
8378 type->field_ident = ident;
8383 static struct type *param_type_list(struct compile_state *state, struct type *type)
8385 struct type *ftype, **next;
8386 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8387 next = &ftype->right;
8388 while(peek(state) == TOK_COMMA) {
8389 eat(state, TOK_COMMA);
8390 if (peek(state) == TOK_DOTS) {
8391 eat(state, TOK_DOTS);
8392 error(state, 0, "variadic functions not supported");
8395 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8396 next = &((*next)->right);
8403 static struct type *type_name(struct compile_state *state)
8406 type = specifier_qualifier_list(state);
8407 /* abstract-declarator (may consume no tokens) */
8408 type = declarator(state, type, 0, 0);
8412 static struct type *direct_declarator(
8413 struct compile_state *state, struct type *type,
8414 struct hash_entry **ident, int need_ident)
8419 arrays_complete(state, type);
8420 switch(peek(state)) {
8422 eat(state, TOK_IDENT);
8424 error(state, 0, "Unexpected identifier found");
8426 /* The name of what we are declaring */
8427 *ident = state->token[0].ident;
8430 eat(state, TOK_LPAREN);
8431 outer = declarator(state, type, ident, need_ident);
8432 eat(state, TOK_RPAREN);
8436 error(state, 0, "Identifier expected");
8442 arrays_complete(state, type);
8443 switch(peek(state)) {
8445 eat(state, TOK_LPAREN);
8446 type = param_type_list(state, type);
8447 eat(state, TOK_RPAREN);
8451 unsigned int qualifiers;
8452 struct triple *value;
8454 eat(state, TOK_LBRACKET);
8455 if (peek(state) != TOK_RBRACKET) {
8456 value = constant_expr(state);
8457 integral(state, value);
8459 eat(state, TOK_RBRACKET);
8461 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8462 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8464 type->elements = value->u.cval;
8465 free_triple(state, value);
8467 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8479 arrays_complete(state, type);
8481 for(inner = outer; inner->left; inner = inner->left)
8489 static struct type *declarator(
8490 struct compile_state *state, struct type *type,
8491 struct hash_entry **ident, int need_ident)
8493 while(peek(state) == TOK_STAR) {
8494 eat(state, TOK_STAR);
8495 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8497 type = direct_declarator(state, type, ident, need_ident);
8502 static struct type *typedef_name(
8503 struct compile_state *state, unsigned int specifiers)
8505 struct hash_entry *ident;
8507 eat(state, TOK_TYPE_NAME);
8508 ident = state->token[0].ident;
8509 type = ident->sym_ident->type;
8510 specifiers |= type->type & QUAL_MASK;
8511 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8512 (type->type & (STOR_MASK | QUAL_MASK))) {
8513 type = clone_type(specifiers, type);
8518 static struct type *enum_specifier(
8519 struct compile_state *state, unsigned int specifiers)
8525 eat(state, TOK_ENUM);
8527 if (tok == TOK_IDENT) {
8528 eat(state, TOK_IDENT);
8530 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8531 eat(state, TOK_LBRACE);
8533 eat(state, TOK_IDENT);
8534 if (peek(state) == TOK_EQ) {
8536 constant_expr(state);
8538 if (peek(state) == TOK_COMMA) {
8539 eat(state, TOK_COMMA);
8541 } while(peek(state) != TOK_RBRACE);
8542 eat(state, TOK_RBRACE);
8548 static struct type *struct_declarator(
8549 struct compile_state *state, struct type *type, struct hash_entry **ident)
8553 if (tok != TOK_COLON) {
8554 type = declarator(state, type, ident, 1);
8556 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8557 struct triple *value;
8558 eat(state, TOK_COLON);
8559 value = constant_expr(state);
8560 #warning "FIXME implement bitfields to reduce register usage"
8561 error(state, 0, "bitfields not yet implemented");
8566 static struct type *struct_or_union_specifier(
8567 struct compile_state *state, unsigned int spec)
8569 struct type *struct_type;
8570 struct hash_entry *ident;
8571 unsigned int type_join;
8575 switch(peek(state)) {
8577 eat(state, TOK_STRUCT);
8578 type_join = TYPE_PRODUCT;
8581 eat(state, TOK_UNION);
8582 type_join = TYPE_OVERLAP;
8583 error(state, 0, "unions not yet supported\n");
8586 eat(state, TOK_STRUCT);
8587 type_join = TYPE_PRODUCT;
8591 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8593 ident = state->token[0].ident;
8595 if (!ident || (peek(state) == TOK_LBRACE)) {
8599 eat(state, TOK_LBRACE);
8600 next = &struct_type;
8602 struct type *base_type;
8604 base_type = specifier_qualifier_list(state);
8607 struct hash_entry *fident;
8609 type = struct_declarator(state, base_type, &fident);
8611 if (peek(state) == TOK_COMMA) {
8613 eat(state, TOK_COMMA);
8615 type = clone_type(0, type);
8616 type->field_ident = fident;
8618 *next = new_type(type_join, *next, type);
8619 next = &((*next)->right);
8624 eat(state, TOK_SEMI);
8625 } while(peek(state) != TOK_RBRACE);
8626 eat(state, TOK_RBRACE);
8627 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8628 struct_type->type_ident = ident;
8629 struct_type->elements = elements;
8630 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8632 if (ident && ident->sym_struct) {
8633 struct_type = clone_type(spec, ident->sym_struct->type);
8635 else if (ident && !ident->sym_struct) {
8636 error(state, 0, "struct %s undeclared", ident->name);
8641 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8643 unsigned int specifiers;
8644 switch(peek(state)) {
8646 eat(state, TOK_AUTO);
8647 specifiers = STOR_AUTO;
8650 eat(state, TOK_REGISTER);
8651 specifiers = STOR_REGISTER;
8654 eat(state, TOK_STATIC);
8655 specifiers = STOR_STATIC;
8658 eat(state, TOK_EXTERN);
8659 specifiers = STOR_EXTERN;
8662 eat(state, TOK_TYPEDEF);
8663 specifiers = STOR_TYPEDEF;
8666 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8667 specifiers = STOR_STATIC;
8670 specifiers = STOR_AUTO;
8676 static unsigned int function_specifier_opt(struct compile_state *state)
8678 /* Ignore the inline keyword */
8679 unsigned int specifiers;
8681 switch(peek(state)) {
8683 eat(state, TOK_INLINE);
8684 specifiers = STOR_INLINE;
8689 static unsigned int type_qualifiers(struct compile_state *state)
8691 unsigned int specifiers;
8694 specifiers = QUAL_NONE;
8696 switch(peek(state)) {
8698 eat(state, TOK_CONST);
8699 specifiers = QUAL_CONST;
8702 eat(state, TOK_VOLATILE);
8703 specifiers = QUAL_VOLATILE;
8706 eat(state, TOK_RESTRICT);
8707 specifiers = QUAL_RESTRICT;
8717 static struct type *type_specifier(
8718 struct compile_state *state, unsigned int spec)
8722 switch(peek(state)) {
8724 eat(state, TOK_VOID);
8725 type = new_type(TYPE_VOID | spec, 0, 0);
8728 eat(state, TOK_CHAR);
8729 type = new_type(TYPE_CHAR | spec, 0, 0);
8732 eat(state, TOK_SHORT);
8733 if (peek(state) == TOK_INT) {
8734 eat(state, TOK_INT);
8736 type = new_type(TYPE_SHORT | spec, 0, 0);
8739 eat(state, TOK_INT);
8740 type = new_type(TYPE_INT | spec, 0, 0);
8743 eat(state, TOK_LONG);
8744 switch(peek(state)) {
8746 eat(state, TOK_LONG);
8747 error(state, 0, "long long not supported");
8750 eat(state, TOK_DOUBLE);
8751 error(state, 0, "long double not supported");
8754 eat(state, TOK_INT);
8755 type = new_type(TYPE_LONG | spec, 0, 0);
8758 type = new_type(TYPE_LONG | spec, 0, 0);
8763 eat(state, TOK_FLOAT);
8764 error(state, 0, "type float not supported");
8767 eat(state, TOK_DOUBLE);
8768 error(state, 0, "type double not supported");
8771 eat(state, TOK_SIGNED);
8772 switch(peek(state)) {
8774 eat(state, TOK_LONG);
8775 switch(peek(state)) {
8777 eat(state, TOK_LONG);
8778 error(state, 0, "type long long not supported");
8781 eat(state, TOK_INT);
8782 type = new_type(TYPE_LONG | spec, 0, 0);
8785 type = new_type(TYPE_LONG | spec, 0, 0);
8790 eat(state, TOK_INT);
8791 type = new_type(TYPE_INT | spec, 0, 0);
8794 eat(state, TOK_SHORT);
8795 type = new_type(TYPE_SHORT | spec, 0, 0);
8798 eat(state, TOK_CHAR);
8799 type = new_type(TYPE_CHAR | spec, 0, 0);
8802 type = new_type(TYPE_INT | spec, 0, 0);
8807 eat(state, TOK_UNSIGNED);
8808 switch(peek(state)) {
8810 eat(state, TOK_LONG);
8811 switch(peek(state)) {
8813 eat(state, TOK_LONG);
8814 error(state, 0, "unsigned long long not supported");
8817 eat(state, TOK_INT);
8818 type = new_type(TYPE_ULONG | spec, 0, 0);
8821 type = new_type(TYPE_ULONG | spec, 0, 0);
8826 eat(state, TOK_INT);
8827 type = new_type(TYPE_UINT | spec, 0, 0);
8830 eat(state, TOK_SHORT);
8831 type = new_type(TYPE_USHORT | spec, 0, 0);
8834 eat(state, TOK_CHAR);
8835 type = new_type(TYPE_UCHAR | spec, 0, 0);
8838 type = new_type(TYPE_UINT | spec, 0, 0);
8842 /* struct or union specifier */
8845 type = struct_or_union_specifier(state, spec);
8847 /* enum-spefifier */
8849 type = enum_specifier(state, spec);
8853 type = typedef_name(state, spec);
8856 error(state, 0, "bad type specifier %s",
8857 tokens[peek(state)]);
8863 static int istype(int tok)
8889 static struct type *specifier_qualifier_list(struct compile_state *state)
8892 unsigned int specifiers = 0;
8894 /* type qualifiers */
8895 specifiers |= type_qualifiers(state);
8897 /* type specifier */
8898 type = type_specifier(state, specifiers);
8903 static int isdecl_specifier(int tok)
8906 /* storage class specifier */
8912 /* type qualifier */
8916 /* type specifiers */
8926 /* struct or union specifier */
8929 /* enum-spefifier */
8933 /* function specifiers */
8941 static struct type *decl_specifiers(struct compile_state *state)
8944 unsigned int specifiers;
8945 /* I am overly restrictive in the arragement of specifiers supported.
8946 * C is overly flexible in this department it makes interpreting
8947 * the parse tree difficult.
8951 /* storage class specifier */
8952 specifiers |= storage_class_specifier_opt(state);
8954 /* function-specifier */
8955 specifiers |= function_specifier_opt(state);
8957 /* type qualifier */
8958 specifiers |= type_qualifiers(state);
8960 /* type specifier */
8961 type = type_specifier(state, specifiers);
8970 static struct field_info designator(struct compile_state *state, struct type *type)
8973 struct field_info info;
8977 switch(peek(state)) {
8980 struct triple *value;
8981 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8982 error(state, 0, "Array designator not in array initializer");
8984 eat(state, TOK_LBRACKET);
8985 value = constant_expr(state);
8986 eat(state, TOK_RBRACKET);
8988 info.type = type->left;
8989 info.offset = value->u.cval * size_of(state, info.type);
8994 struct hash_entry *field;
8995 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
8996 error(state, 0, "Struct designator not in struct initializer");
8998 eat(state, TOK_DOT);
8999 eat(state, TOK_IDENT);
9000 field = state->token[0].ident;
9001 info.offset = field_offset(state, type, field);
9002 info.type = field_type(state, type, field);
9006 error(state, 0, "Invalid designator");
9009 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
9014 static struct triple *initializer(
9015 struct compile_state *state, struct type *type)
9017 struct triple *result;
9018 if (peek(state) != TOK_LBRACE) {
9019 result = assignment_expr(state);
9024 struct field_info info;
9026 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
9027 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
9028 internal_error(state, 0, "unknown initializer type");
9031 info.type = type->left;
9032 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
9033 info.type = next_field(state, type, 0);
9035 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
9038 max_offset = size_of(state, type);
9040 buf = xcmalloc(max_offset, "initializer");
9041 eat(state, TOK_LBRACE);
9043 struct triple *value;
9044 struct type *value_type;
9050 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
9051 info = designator(state, type);
9053 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
9054 (info.offset >= max_offset)) {
9055 error(state, 0, "element beyond bounds");
9057 value_type = info.type;
9058 value = eval_const_expr(state, initializer(state, value_type));
9059 value_size = size_of(state, value_type);
9060 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
9061 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
9062 (max_offset <= info.offset)) {
9066 old_size = max_offset;
9067 max_offset = info.offset + value_size;
9068 buf = xmalloc(max_offset, "initializer");
9069 memcpy(buf, old_buf, old_size);
9072 dest = ((char *)buf) + info.offset;
9073 if (value->op == OP_BLOBCONST) {
9074 memcpy(dest, value->u.blob, value_size);
9076 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
9077 *((uint8_t *)dest) = value->u.cval & 0xff;
9079 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
9080 *((uint16_t *)dest) = value->u.cval & 0xffff;
9082 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
9083 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
9086 internal_error(state, 0, "unhandled constant initializer");
9088 free_triple(state, value);
9089 if (peek(state) == TOK_COMMA) {
9090 eat(state, TOK_COMMA);
9093 info.offset += value_size;
9094 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
9095 info.type = next_field(state, type, info.type);
9096 info.offset = field_offset(state, type,
9097 info.type->field_ident);
9099 } while(comma && (peek(state) != TOK_RBRACE));
9100 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
9101 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
9102 type->elements = max_offset / size_of(state, type->left);
9104 eat(state, TOK_RBRACE);
9105 result = triple(state, OP_BLOBCONST, type, 0, 0);
9106 result->u.blob = buf;
9111 static void resolve_branches(struct compile_state *state)
9113 /* Make a second pass and finish anything outstanding
9114 * with respect to branches. The only outstanding item
9115 * is to see if there are goto to labels that have not
9116 * been defined and to error about them.
9119 for(i = 0; i < HASH_TABLE_SIZE; i++) {
9120 struct hash_entry *entry;
9121 for(entry = state->hash_table[i]; entry; entry = entry->next) {
9123 if (!entry->sym_label) {
9126 ins = entry->sym_label->def;
9127 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
9128 error(state, ins, "label `%s' used but not defined",
9135 static struct triple *function_definition(
9136 struct compile_state *state, struct type *type)
9138 struct triple *def, *tmp, *first, *end;
9139 struct hash_entry *ident;
9142 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
9143 error(state, 0, "Invalid function header");
9146 /* Verify the function type */
9147 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
9148 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
9149 (type->right->field_ident == 0)) {
9150 error(state, 0, "Invalid function parameters");
9152 param = type->right;
9154 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9156 if (!param->left->field_ident) {
9157 error(state, 0, "No identifier for parameter %d\n", i);
9159 param = param->right;
9162 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9163 error(state, 0, "No identifier for paramter %d\n", i);
9166 /* Get a list of statements for this function. */
9167 def = triple(state, OP_LIST, type, 0, 0);
9169 /* Start a new scope for the passed parameters */
9172 /* Put a label at the very start of a function */
9173 first = label(state);
9174 RHS(def, 0) = first;
9176 /* Put a label at the very end of a function */
9178 flatten(state, first, end);
9180 /* Walk through the parameters and create symbol table entries
9183 param = type->right;
9184 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9185 ident = param->left->field_ident;
9186 tmp = variable(state, param->left);
9187 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9188 flatten(state, end, tmp);
9189 param = param->right;
9191 if ((param->type & TYPE_MASK) != TYPE_VOID) {
9192 /* And don't forget the last parameter */
9193 ident = param->field_ident;
9194 tmp = variable(state, param);
9195 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9196 flatten(state, end, tmp);
9198 /* Add a variable for the return value */
9200 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9201 /* Remove all type qualifiers from the return type */
9202 tmp = variable(state, clone_type(0, type->left));
9203 flatten(state, end, tmp);
9204 /* Remember where the return value is */
9208 /* Remember which function I am compiling.
9209 * Also assume the last defined function is the main function.
9211 state->main_function = def;
9213 /* Now get the actual function definition */
9214 compound_statement(state, end);
9216 /* Finish anything unfinished with branches */
9217 resolve_branches(state);
9219 /* Remove the parameter scope */
9223 fprintf(stdout, "\n");
9224 loc(stdout, state, 0);
9225 fprintf(stdout, "\n__________ function_definition _________\n");
9226 print_triple(state, def);
9227 fprintf(stdout, "__________ function_definition _________ done\n\n");
9233 static struct triple *do_decl(struct compile_state *state,
9234 struct type *type, struct hash_entry *ident)
9238 /* Clean up the storage types used */
9239 switch (type->type & STOR_MASK) {
9242 /* These are the good types I am aiming for */
9245 type->type &= ~STOR_MASK;
9246 type->type |= STOR_AUTO;
9249 type->type &= ~STOR_MASK;
9250 type->type |= STOR_STATIC;
9254 error(state, 0, "typedef without name");
9256 symbol(state, ident, &ident->sym_ident, 0, type);
9257 ident->tok = TOK_TYPE_NAME;
9261 internal_error(state, 0, "Undefined storage class");
9263 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
9264 error(state, 0, "Function prototypes not supported");
9267 ((type->type & STOR_MASK) == STOR_STATIC) &&
9268 ((type->type & QUAL_CONST) == 0)) {
9269 error(state, 0, "non const static variables not supported");
9272 def = variable(state, type);
9273 symbol(state, ident, &ident->sym_ident, def, type);
9278 static void decl(struct compile_state *state, struct triple *first)
9280 struct type *base_type, *type;
9281 struct hash_entry *ident;
9284 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9285 base_type = decl_specifiers(state);
9287 type = declarator(state, base_type, &ident, 0);
9288 if (global && ident && (peek(state) == TOK_LBRACE)) {
9290 state->function = ident->name;
9291 def = function_definition(state, type);
9292 symbol(state, ident, &ident->sym_ident, def, type);
9293 state->function = 0;
9297 flatten(state, first, do_decl(state, type, ident));
9298 /* type or variable definition */
9301 if (peek(state) == TOK_EQ) {
9303 error(state, 0, "cannot assign to a type");
9306 flatten(state, first,
9308 ident->sym_ident->def,
9309 initializer(state, type)));
9311 arrays_complete(state, type);
9312 if (peek(state) == TOK_COMMA) {
9313 eat(state, TOK_COMMA);
9315 type = declarator(state, base_type, &ident, 0);
9316 flatten(state, first, do_decl(state, type, ident));
9320 eat(state, TOK_SEMI);
9324 static void decls(struct compile_state *state)
9326 struct triple *list;
9328 list = label(state);
9331 if (tok == TOK_EOF) {
9334 if (tok == TOK_SPACE) {
9335 eat(state, TOK_SPACE);
9338 if (list->next != list) {
9339 error(state, 0, "global variables not supported");
9345 * Data structurs for optimation.
9348 static void do_use_block(
9349 struct block *used, struct block_set **head, struct block *user,
9352 struct block_set **ptr, *new;
9359 if ((*ptr)->member == user) {
9362 ptr = &(*ptr)->next;
9364 new = xcmalloc(sizeof(*new), "block_set");
9375 static void do_unuse_block(
9376 struct block *used, struct block_set **head, struct block *unuser)
9378 struct block_set *use, **ptr;
9382 if (use->member == unuser) {
9384 memset(use, -1, sizeof(*use));
9393 static void use_block(struct block *used, struct block *user)
9395 /* Append new to the head of the list, print_block
9398 do_use_block(used, &used->use, user, 1);
9401 static void unuse_block(struct block *used, struct block *unuser)
9403 do_unuse_block(used, &used->use, unuser);
9407 static void idom_block(struct block *idom, struct block *user)
9409 do_use_block(idom, &idom->idominates, user, 0);
9412 static void unidom_block(struct block *idom, struct block *unuser)
9414 do_unuse_block(idom, &idom->idominates, unuser);
9417 static void domf_block(struct block *block, struct block *domf)
9419 do_use_block(block, &block->domfrontier, domf, 0);
9422 static void undomf_block(struct block *block, struct block *undomf)
9424 do_unuse_block(block, &block->domfrontier, undomf);
9427 static void ipdom_block(struct block *ipdom, struct block *user)
9429 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9432 static void unipdom_block(struct block *ipdom, struct block *unuser)
9434 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9437 static void ipdomf_block(struct block *block, struct block *ipdomf)
9439 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9442 static void unipdomf_block(struct block *block, struct block *unipdomf)
9444 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9449 static int do_walk_triple(struct compile_state *state,
9450 struct triple *ptr, int depth,
9451 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9454 result = cb(state, ptr, depth);
9455 if ((result == 0) && (ptr->op == OP_LIST)) {
9456 struct triple *list;
9460 result = do_walk_triple(state, ptr, depth + 1, cb);
9461 if (ptr->next->prev != ptr) {
9462 internal_error(state, ptr->next, "bad prev");
9466 } while((result == 0) && (ptr != RHS(list, 0)));
9471 static int walk_triple(
9472 struct compile_state *state,
9474 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9476 return do_walk_triple(state, ptr, 0, cb);
9479 static void do_print_prefix(int depth)
9482 for(i = 0; i < depth; i++) {
9487 #define PRINT_LIST 1
9488 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9492 if (op == OP_LIST) {
9497 if ((op == OP_LABEL) && (ins->use)) {
9498 printf("\n%p:\n", ins);
9500 do_print_prefix(depth);
9501 display_triple(stdout, ins);
9503 if ((ins->op == OP_BRANCH) && ins->use) {
9504 internal_error(state, ins, "branch used?");
9506 if (triple_is_branch(state, ins)) {
9512 static void print_triple(struct compile_state *state, struct triple *ins)
9514 walk_triple(state, ins, do_print_triple);
9517 static void print_triples(struct compile_state *state)
9519 print_triple(state, state->main_function);
9523 struct block *block;
9525 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9527 if (!block || (cf[block->vertex].block == block)) {
9530 cf[block->vertex].block = block;
9531 find_cf_blocks(cf, block->left);
9532 find_cf_blocks(cf, block->right);
9535 static void print_control_flow(struct compile_state *state)
9537 struct cf_block *cf;
9539 printf("\ncontrol flow\n");
9540 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9541 find_cf_blocks(cf, state->first_block);
9543 for(i = 1; i <= state->last_vertex; i++) {
9544 struct block *block;
9545 block = cf[i].block;
9548 printf("(%p) %d:", block, block->vertex);
9550 printf(" %d", block->left->vertex);
9552 if (block->right && (block->right != block->left)) {
9553 printf(" %d", block->right->vertex);
9562 static struct block *basic_block(struct compile_state *state,
9563 struct triple *first)
9565 struct block *block;
9566 struct triple *ptr, *final;
9568 if (first->op != OP_LABEL) {
9569 internal_error(state, 0, "block does not start with a label");
9571 /* See if this basic block has already been setup */
9572 if (first->u.block != 0) {
9573 return first->u.block;
9575 /* Lookup the final instruction.
9576 * It is important that the final instruction has it's own
9579 final = RHS(state->main_function, 0)->prev;
9580 /* Allocate another basic block structure */
9581 state->last_vertex += 1;
9582 block = xcmalloc(sizeof(*block), "block");
9583 block->first = block->last = first;
9584 block->vertex = state->last_vertex;
9587 if ((ptr != first) && (ptr->op == OP_LABEL) &&
9588 ((ptr->use) || ptr == final)) {
9592 /* If ptr->u is not used remember where the baic block is */
9593 if (triple_stores_block(state, ptr)) {
9594 ptr->u.block = block;
9596 if (ptr->op == OP_BRANCH) {
9600 } while (ptr != RHS(state->main_function, 0));
9601 if (ptr == RHS(state->main_function, 0))
9604 if (op == OP_LABEL) {
9605 block->left = basic_block(state, ptr);
9607 use_block(block->left, block);
9609 else if (op == OP_BRANCH) {
9611 /* Trace the branch target */
9612 block->right = basic_block(state, TARG(ptr, 0));
9613 use_block(block->right, block);
9614 /* If there is a test trace the branch as well */
9615 if (TRIPLE_RHS(ptr->sizes)) {
9616 block->left = basic_block(state, ptr->next);
9617 use_block(block->left, block);
9621 internal_error(state, 0, "Bad basic block split");
9627 static void walk_blocks(struct compile_state *state,
9628 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9631 struct triple *ptr, *first;
9632 struct block *last_block;
9634 first = RHS(state->main_function, 0);
9637 struct block *block;
9638 if (triple_stores_block(state, ptr)) {
9639 block = ptr->u.block;
9640 if (block && (block != last_block)) {
9641 cb(state, block, arg);
9645 if (block && (block->last == ptr)) {
9649 } while(ptr != first);
9652 static void print_block(
9653 struct compile_state *state, struct block *block, void *arg)
9655 struct block_set *user;
9659 fprintf(fp, "\nblock: %p (%d) %p<-%p %p<-%p\n",
9663 block->left && block->left->use?block->left->use->member : 0,
9665 block->right && block->right->use?block->right->use->member : 0);
9666 if (block->first->op == OP_LABEL) {
9667 fprintf(fp, "%p:\n", block->first);
9669 for(ptr = block->first; ; ptr = ptr->next) {
9670 display_triple(fp, ptr);
9671 if (ptr == block->last)
9674 fprintf(fp, "users %d: ", block->users);
9675 for(user = block->use; user; user = user->next) {
9676 fprintf(fp, "%p (%d) ",
9678 user->member->vertex);
9684 static void print_blocks(struct compile_state *state, FILE *fp)
9686 fprintf(fp, "--------------- blocks ---------------\n");
9687 walk_blocks(state, print_block, fp);
9690 static void prune_nonblock_triples(struct compile_state *state)
9692 struct block *block;
9693 struct triple *first, *ins, *next;
9694 /* Delete the triples not in a basic block */
9695 first = RHS(state->main_function, 0);
9700 if (ins->op == OP_LABEL) {
9701 block = ins->u.block;
9704 release_triple(state, ins);
9706 if (block && block->last == ins) {
9710 } while(ins != first);
9713 static void setup_basic_blocks(struct compile_state *state)
9715 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9716 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9717 internal_error(state, 0, "ins will not store block?");
9719 /* Find the basic blocks */
9720 state->last_vertex = 0;
9721 state->first_block = basic_block(state, RHS(state->main_function,0));
9722 /* Delete the triples not in a basic block */
9723 prune_nonblock_triples(state);
9724 /* Find the last basic block */
9725 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9726 if (!state->last_block) {
9727 internal_error(state, 0, "end not used?");
9729 /* If we are debugging print what I have just done */
9730 if (state->debug & DEBUG_BASIC_BLOCKS) {
9731 print_blocks(state, stdout);
9732 print_control_flow(state);
9736 static void free_basic_block(struct compile_state *state, struct block *block)
9738 struct block_set *entry, *next;
9739 struct block *child;
9743 if (block->vertex == -1) {
9748 unuse_block(block->left, block);
9751 unuse_block(block->right, block);
9754 unidom_block(block->idom, block);
9758 unipdom_block(block->ipdom, block);
9761 for(entry = block->use; entry; entry = next) {
9763 child = entry->member;
9764 unuse_block(block, child);
9765 if (child->left == block) {
9768 if (child->right == block) {
9772 for(entry = block->idominates; entry; entry = next) {
9774 child = entry->member;
9775 unidom_block(block, child);
9778 for(entry = block->domfrontier; entry; entry = next) {
9780 child = entry->member;
9781 undomf_block(block, child);
9783 for(entry = block->ipdominates; entry; entry = next) {
9785 child = entry->member;
9786 unipdom_block(block, child);
9789 for(entry = block->ipdomfrontier; entry; entry = next) {
9791 child = entry->member;
9792 unipdomf_block(block, child);
9794 if (block->users != 0) {
9795 internal_error(state, 0, "block still has users");
9797 free_basic_block(state, block->left);
9799 free_basic_block(state, block->right);
9801 memset(block, -1, sizeof(*block));
9805 static void free_basic_blocks(struct compile_state *state)
9807 struct triple *first, *ins;
9808 free_basic_block(state, state->first_block);
9809 state->last_vertex = 0;
9810 state->first_block = state->last_block = 0;
9811 first = RHS(state->main_function, 0);
9814 if (triple_stores_block(state, ins)) {
9818 } while(ins != first);
9823 struct block *block;
9824 struct sdom_block *sdominates;
9825 struct sdom_block *sdom_next;
9826 struct sdom_block *sdom;
9827 struct sdom_block *label;
9828 struct sdom_block *parent;
9829 struct sdom_block *ancestor;
9834 static void unsdom_block(struct sdom_block *block)
9836 struct sdom_block **ptr;
9837 if (!block->sdom_next) {
9840 ptr = &block->sdom->sdominates;
9842 if ((*ptr) == block) {
9843 *ptr = block->sdom_next;
9846 ptr = &(*ptr)->sdom_next;
9850 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9852 unsdom_block(block);
9854 block->sdom_next = sdom->sdominates;
9855 sdom->sdominates = block;
9860 static int initialize_sdblock(struct sdom_block *sd,
9861 struct block *parent, struct block *block, int vertex)
9863 if (!block || (sd[block->vertex].block == block)) {
9867 /* Renumber the blocks in a convinient fashion */
9868 block->vertex = vertex;
9869 sd[vertex].block = block;
9870 sd[vertex].sdom = &sd[vertex];
9871 sd[vertex].label = &sd[vertex];
9872 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9873 sd[vertex].ancestor = 0;
9874 sd[vertex].vertex = vertex;
9875 vertex = initialize_sdblock(sd, block, block->left, vertex);
9876 vertex = initialize_sdblock(sd, block, block->right, vertex);
9880 static int initialize_sdpblock(
9881 struct compile_state *state, struct sdom_block *sd,
9882 struct block *parent, struct block *block, int vertex)
9884 struct block_set *user;
9885 if (!block || (sd[block->vertex].block == block)) {
9889 /* Renumber the blocks in a convinient fashion */
9890 block->vertex = vertex;
9891 sd[vertex].block = block;
9892 sd[vertex].sdom = &sd[vertex];
9893 sd[vertex].label = &sd[vertex];
9894 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9895 sd[vertex].ancestor = 0;
9896 sd[vertex].vertex = vertex;
9897 for(user = block->use; user; user = user->next) {
9898 vertex = initialize_sdpblock(state, sd, block, user->member, vertex);
9903 static int setup_sdpblocks(struct compile_state *state, struct sdom_block *sd)
9905 struct block *block;
9907 /* Setup as many sdpblocks as possible without using fake edges */
9908 vertex = initialize_sdpblock(state, sd, 0, state->last_block, 0);
9910 /* Walk through the graph and find unconnected blocks. If
9911 * we can, add a fake edge from the unconnected blocks to the
9914 block = state->first_block->last->next->u.block;
9915 for(; block && block != state->first_block; block = block->last->next->u.block) {
9916 if (sd[block->vertex].block == block) {
9919 if (block->left != 0) {
9923 #if DEBUG_SDP_BLOCKS
9924 fprintf(stderr, "Adding %d\n", vertex +1);
9927 block->left = state->last_block;
9928 use_block(block->left, block);
9929 vertex = initialize_sdpblock(state, sd, state->last_block, block, vertex);
9934 static void compress_ancestors(struct sdom_block *v)
9936 /* This procedure assumes ancestor(v) != 0 */
9937 /* if (ancestor(ancestor(v)) != 0) {
9938 * compress(ancestor(ancestor(v)));
9939 * if (semi(label(ancestor(v))) < semi(label(v))) {
9940 * label(v) = label(ancestor(v));
9942 * ancestor(v) = ancestor(ancestor(v));
9948 if (v->ancestor->ancestor) {
9949 compress_ancestors(v->ancestor->ancestor);
9950 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9951 v->label = v->ancestor->label;
9953 v->ancestor = v->ancestor->ancestor;
9957 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9961 * for each v <= pred(w) {
9963 * if (semi[u] < semi[w] {
9964 * semi[w] = semi[u];
9967 * add w to bucket(vertex(semi[w]));
9968 * LINK(parent(w), w);
9971 * for each v <= bucket(parent(w)) {
9972 * delete v from bucket(parent(w));
9974 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9977 for(i = state->last_vertex; i >= 2; i--) {
9978 struct sdom_block *v, *parent, *next;
9979 struct block_set *user;
9980 struct block *block;
9981 block = sd[i].block;
9982 parent = sd[i].parent;
9984 for(user = block->use; user; user = user->next) {
9985 struct sdom_block *v, *u;
9986 v = &sd[user->member->vertex];
9987 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9988 if (u->sdom->vertex < sd[i].sdom->vertex) {
9989 sd[i].sdom = u->sdom;
9992 sdom_block(sd[i].sdom, &sd[i]);
9993 sd[i].ancestor = parent;
9995 for(v = parent->sdominates; v; v = next) {
9996 struct sdom_block *u;
9997 next = v->sdom_next;
9999 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
10000 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
10001 u->block : parent->block;
10006 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
10010 * for each v <= pred(w) {
10012 * if (semi[u] < semi[w] {
10013 * semi[w] = semi[u];
10016 * add w to bucket(vertex(semi[w]));
10017 * LINK(parent(w), w);
10020 * for each v <= bucket(parent(w)) {
10021 * delete v from bucket(parent(w));
10023 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
10026 for(i = state->last_vertex; i >= 2; i--) {
10027 struct sdom_block *u, *v, *parent, *next;
10028 struct block *block;
10029 block = sd[i].block;
10030 parent = sd[i].parent;
10033 v = &sd[block->left->vertex];
10034 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10035 if (u->sdom->vertex < sd[i].sdom->vertex) {
10036 sd[i].sdom = u->sdom;
10039 if (block->right && (block->right != block->left)) {
10040 v = &sd[block->right->vertex];
10041 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10042 if (u->sdom->vertex < sd[i].sdom->vertex) {
10043 sd[i].sdom = u->sdom;
10046 sdom_block(sd[i].sdom, &sd[i]);
10047 sd[i].ancestor = parent;
10049 for(v = parent->sdominates; v; v = next) {
10050 struct sdom_block *u;
10051 next = v->sdom_next;
10053 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
10054 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
10055 u->block : parent->block;
10060 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
10063 for(i = 2; i <= state->last_vertex; i++) {
10064 struct block *block;
10065 block = sd[i].block;
10066 if (block->idom->vertex != sd[i].sdom->vertex) {
10067 block->idom = block->idom->idom;
10069 idom_block(block->idom, block);
10071 sd[1].block->idom = 0;
10074 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
10077 for(i = 2; i <= state->last_vertex; i++) {
10078 struct block *block;
10079 block = sd[i].block;
10080 if (block->ipdom->vertex != sd[i].sdom->vertex) {
10081 block->ipdom = block->ipdom->ipdom;
10083 ipdom_block(block->ipdom, block);
10085 sd[1].block->ipdom = 0;
10089 * Every vertex of a flowgraph G = (V, E, r) except r has
10090 * a unique immediate dominator.
10091 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
10092 * rooted at r, called the dominator tree of G, such that
10093 * v dominates w if and only if v is a proper ancestor of w in
10094 * the dominator tree.
10097 * If v and w are vertices of G such that v <= w,
10098 * than any path from v to w must contain a common ancestor
10101 /* Lemma 2: For any vertex w != r, idom(w) -> w */
10102 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
10103 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
10105 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
10106 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
10109 * Let w != r and let u be a vertex for which sdom(u) is
10110 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
10111 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
10113 /* Lemma 5: Let vertices v,w satisfy v -> w.
10114 * Then v -> idom(w) or idom(w) -> idom(v)
10117 static void find_immediate_dominators(struct compile_state *state)
10119 struct sdom_block *sd;
10120 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
10121 * vi > w for (1 <= i <= k - 1}
10124 * For any vertex w != r.
10126 * {v|(v,w) <= E and v < w } U
10127 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
10130 * Let w != r and let u be a vertex for which sdom(u) is
10131 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
10133 * { sdom(w) if sdom(w) = sdom(u),
10135 * { idom(u) otherwise
10137 /* The algorithm consists of the following 4 steps.
10138 * Step 1. Carry out a depth-first search of the problem graph.
10139 * Number the vertices from 1 to N as they are reached during
10140 * the search. Initialize the variables used in succeeding steps.
10141 * Step 2. Compute the semidominators of all vertices by applying
10142 * theorem 4. Carry out the computation vertex by vertex in
10143 * decreasing order by number.
10144 * Step 3. Implicitly define the immediate dominator of each vertex
10145 * by applying Corollary 1.
10146 * Step 4. Explicitly define the immediate dominator of each vertex,
10147 * carrying out the computation vertex by vertex in increasing order
10150 /* Step 1 initialize the basic block information */
10151 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10152 initialize_sdblock(sd, 0, state->first_block, 0);
10158 /* Step 2 compute the semidominators */
10159 /* Step 3 implicitly define the immediate dominator of each vertex */
10160 compute_sdom(state, sd);
10161 /* Step 4 explicitly define the immediate dominator of each vertex */
10162 compute_idom(state, sd);
10166 static void find_post_dominators(struct compile_state *state)
10168 struct sdom_block *sd;
10170 /* Step 1 initialize the basic block information */
10171 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10173 vertex = setup_sdpblocks(state, sd);
10174 if (vertex != state->last_vertex) {
10175 internal_error(state, 0, "missing %d blocks\n",
10176 state->last_vertex - vertex);
10179 /* Step 2 compute the semidominators */
10180 /* Step 3 implicitly define the immediate dominator of each vertex */
10181 compute_spdom(state, sd);
10182 /* Step 4 explicitly define the immediate dominator of each vertex */
10183 compute_ipdom(state, sd);
10189 static void find_block_domf(struct compile_state *state, struct block *block)
10191 struct block *child;
10192 struct block_set *user;
10193 if (block->domfrontier != 0) {
10194 internal_error(state, block->first, "domfrontier present?");
10196 for(user = block->idominates; user; user = user->next) {
10197 child = user->member;
10198 if (child->idom != block) {
10199 internal_error(state, block->first, "bad idom");
10201 find_block_domf(state, child);
10203 if (block->left && block->left->idom != block) {
10204 domf_block(block, block->left);
10206 if (block->right && block->right->idom != block) {
10207 domf_block(block, block->right);
10209 for(user = block->idominates; user; user = user->next) {
10210 struct block_set *frontier;
10211 child = user->member;
10212 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10213 if (frontier->member->idom != block) {
10214 domf_block(block, frontier->member);
10220 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10222 struct block *child;
10223 struct block_set *user;
10224 if (block->ipdomfrontier != 0) {
10225 internal_error(state, block->first, "ipdomfrontier present?");
10227 for(user = block->ipdominates; user; user = user->next) {
10228 child = user->member;
10229 if (child->ipdom != block) {
10230 internal_error(state, block->first, "bad ipdom");
10232 find_block_ipdomf(state, child);
10234 if (block->left && block->left->ipdom != block) {
10235 ipdomf_block(block, block->left);
10237 if (block->right && block->right->ipdom != block) {
10238 ipdomf_block(block, block->right);
10240 for(user = block->idominates; user; user = user->next) {
10241 struct block_set *frontier;
10242 child = user->member;
10243 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10244 if (frontier->member->ipdom != block) {
10245 ipdomf_block(block, frontier->member);
10251 static void print_dominated(
10252 struct compile_state *state, struct block *block, void *arg)
10254 struct block_set *user;
10257 fprintf(fp, "%d:", block->vertex);
10258 for(user = block->idominates; user; user = user->next) {
10259 fprintf(fp, " %d", user->member->vertex);
10260 if (user->member->idom != block) {
10261 internal_error(state, user->member->first, "bad idom");
10267 static void print_dominators(struct compile_state *state, FILE *fp)
10269 fprintf(fp, "\ndominates\n");
10270 walk_blocks(state, print_dominated, fp);
10274 static int print_frontiers(
10275 struct compile_state *state, struct block *block, int vertex)
10277 struct block_set *user;
10279 if (!block || (block->vertex != vertex + 1)) {
10284 printf("%d:", block->vertex);
10285 for(user = block->domfrontier; user; user = user->next) {
10286 printf(" %d", user->member->vertex);
10290 vertex = print_frontiers(state, block->left, vertex);
10291 vertex = print_frontiers(state, block->right, vertex);
10294 static void print_dominance_frontiers(struct compile_state *state)
10296 printf("\ndominance frontiers\n");
10297 print_frontiers(state, state->first_block, 0);
10301 static void analyze_idominators(struct compile_state *state)
10303 /* Find the immediate dominators */
10304 find_immediate_dominators(state);
10305 /* Find the dominance frontiers */
10306 find_block_domf(state, state->first_block);
10307 /* If debuging print the print what I have just found */
10308 if (state->debug & DEBUG_FDOMINATORS) {
10309 print_dominators(state, stdout);
10310 print_dominance_frontiers(state);
10311 print_control_flow(state);
10317 static void print_ipdominated(
10318 struct compile_state *state, struct block *block, void *arg)
10320 struct block_set *user;
10323 fprintf(fp, "%d:", block->vertex);
10324 for(user = block->ipdominates; user; user = user->next) {
10325 fprintf(fp, " %d", user->member->vertex);
10326 if (user->member->ipdom != block) {
10327 internal_error(state, user->member->first, "bad ipdom");
10333 static void print_ipdominators(struct compile_state *state, FILE *fp)
10335 fprintf(fp, "\nipdominates\n");
10336 walk_blocks(state, print_ipdominated, fp);
10339 static int print_pfrontiers(
10340 struct compile_state *state, struct block *block, int vertex)
10342 struct block_set *user;
10344 if (!block || (block->vertex != vertex + 1)) {
10349 printf("%d:", block->vertex);
10350 for(user = block->ipdomfrontier; user; user = user->next) {
10351 printf(" %d", user->member->vertex);
10354 for(user = block->use; user; user = user->next) {
10355 vertex = print_pfrontiers(state, user->member, vertex);
10359 static void print_ipdominance_frontiers(struct compile_state *state)
10361 printf("\nipdominance frontiers\n");
10362 print_pfrontiers(state, state->last_block, 0);
10366 static void analyze_ipdominators(struct compile_state *state)
10368 /* Find the post dominators */
10369 find_post_dominators(state);
10370 /* Find the control dependencies (post dominance frontiers) */
10371 find_block_ipdomf(state, state->last_block);
10372 /* If debuging print the print what I have just found */
10373 if (state->debug & DEBUG_RDOMINATORS) {
10374 print_ipdominators(state, stdout);
10375 print_ipdominance_frontiers(state);
10376 print_control_flow(state);
10380 static int bdominates(struct compile_state *state,
10381 struct block *dom, struct block *sub)
10383 while(sub && (sub != dom)) {
10389 static int tdominates(struct compile_state *state,
10390 struct triple *dom, struct triple *sub)
10392 struct block *bdom, *bsub;
10394 bdom = block_of_triple(state, dom);
10395 bsub = block_of_triple(state, sub);
10396 if (bdom != bsub) {
10397 result = bdominates(state, bdom, bsub);
10400 struct triple *ins;
10402 while((ins != bsub->first) && (ins != dom)) {
10405 result = (ins == dom);
10410 static void insert_phi_operations(struct compile_state *state)
10413 struct triple *first;
10414 int *has_already, *work;
10415 struct block *work_list, **work_list_tail;
10417 struct triple *var, *vnext;
10419 size = sizeof(int) * (state->last_vertex + 1);
10420 has_already = xcmalloc(size, "has_already");
10421 work = xcmalloc(size, "work");
10424 first = RHS(state->main_function, 0);
10425 for(var = first->next; var != first ; var = vnext) {
10426 struct block *block;
10427 struct triple_set *user, *unext;
10429 if ((var->op != OP_ADECL) || !var->use) {
10434 work_list_tail = &work_list;
10435 for(user = var->use; user; user = unext) {
10436 unext = user->next;
10437 if (user->member->op == OP_READ) {
10440 if (user->member->op != OP_WRITE) {
10441 internal_error(state, user->member,
10442 "bad variable access");
10444 block = user->member->u.block;
10446 warning(state, user->member, "dead code");
10447 release_triple(state, user->member);
10450 if (work[block->vertex] >= iter) {
10453 work[block->vertex] = iter;
10454 *work_list_tail = block;
10455 block->work_next = 0;
10456 work_list_tail = &block->work_next;
10458 for(block = work_list; block; block = block->work_next) {
10459 struct block_set *df;
10460 for(df = block->domfrontier; df; df = df->next) {
10461 struct triple *phi;
10462 struct block *front;
10464 front = df->member;
10466 if (has_already[front->vertex] >= iter) {
10469 /* Count how many edges flow into this block */
10470 in_edges = front->users;
10471 /* Insert a phi function for this variable */
10472 get_occurance(var->occurance);
10473 phi = alloc_triple(
10474 state, OP_PHI, var->type, -1, in_edges,
10476 phi->u.block = front;
10477 MISC(phi, 0) = var;
10478 use_triple(var, phi);
10479 /* Insert the phi functions immediately after the label */
10480 insert_triple(state, front->first->next, phi);
10481 if (front->first == front->last) {
10482 front->last = front->first->next;
10484 has_already[front->vertex] = iter;
10486 /* If necessary plan to visit the basic block */
10487 if (work[front->vertex] >= iter) {
10490 work[front->vertex] = iter;
10491 *work_list_tail = front;
10492 front->work_next = 0;
10493 work_list_tail = &front->work_next;
10497 xfree(has_already);
10502 static int count_and_number_adecls(struct compile_state *state)
10504 struct triple *first, *ins;
10506 first = RHS(state->main_function, 0);
10509 if (ins->op == OP_ADECL) {
10514 } while(ins != first);
10518 static struct triple *peek_triple(struct triple_set **stacks, struct triple *var)
10520 struct triple_set *head;
10521 struct triple *top_val;
10523 head = stacks[var->id];
10525 top_val = head->member;
10530 static void push_triple(struct triple_set **stacks, struct triple *var, struct triple *val)
10532 struct triple_set *new;
10533 /* Append new to the head of the list,
10534 * it's the only sensible behavoir for a stack.
10536 new = xcmalloc(sizeof(*new), "triple_set");
10538 new->next = stacks[var->id];
10539 stacks[var->id] = new;
10542 static void pop_triple(struct triple_set **stacks, struct triple *var, struct triple *oldval)
10544 struct triple_set *set, **ptr;
10545 ptr = &stacks[var->id];
10548 if (set->member == oldval) {
10551 /* Only free one occurance from the stack */
10564 static void fixup_block_phi_variables(
10565 struct compile_state *state, struct triple_set **stacks, struct block *parent, struct block *block)
10567 struct block_set *set;
10568 struct triple *ptr;
10570 if (!parent || !block)
10572 /* Find the edge I am coming in on */
10574 for(set = block->use; set; set = set->next, edge++) {
10575 if (set->member == parent) {
10580 internal_error(state, 0, "phi input is not on a control predecessor");
10582 for(ptr = block->first; ; ptr = ptr->next) {
10583 if (ptr->op == OP_PHI) {
10584 struct triple *var, *val, **slot;
10585 var = MISC(ptr, 0);
10587 internal_error(state, ptr, "no var???");
10589 /* Find the current value of the variable */
10590 val = peek_triple(stacks, var);
10591 if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
10592 internal_error(state, val, "bad value in phi");
10594 if (edge >= TRIPLE_RHS(ptr->sizes)) {
10595 internal_error(state, ptr, "edges > phi rhs");
10597 slot = &RHS(ptr, edge);
10598 if ((*slot != 0) && (*slot != val)) {
10599 internal_error(state, ptr, "phi already bound on this edge");
10602 use_triple(val, ptr);
10604 if (ptr == block->last) {
10611 static void rename_block_variables(
10612 struct compile_state *state, struct triple_set **stacks, struct block *block)
10614 struct block_set *user;
10615 struct triple *ptr, *next, *last;
10619 last = block->first;
10621 for(ptr = block->first; !done; ptr = next) {
10623 if (ptr == block->last) {
10627 if (ptr->op == OP_READ) {
10628 struct triple *var, *val;
10630 unuse_triple(var, ptr);
10631 /* Find the current value of the variable */
10632 val = peek_triple(stacks, var);
10634 error(state, ptr, "variable used without being set");
10636 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10637 internal_error(state, val, "bad value in read");
10639 propogate_use(state, ptr, val);
10640 release_triple(state, ptr);
10644 if (ptr->op == OP_WRITE) {
10645 struct triple *var, *val, *tval;
10647 tval = val = RHS(ptr, 1);
10648 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10649 internal_error(state, ptr, "bad value in write");
10651 /* Insert a copy if the types differ */
10652 if (!equiv_types(ptr->type, val->type)) {
10653 if (val->op == OP_INTCONST) {
10654 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
10655 tval->u.cval = val->u.cval;
10658 tval = pre_triple(state, ptr, OP_COPY, ptr->type, val, 0);
10659 use_triple(val, tval);
10661 unuse_triple(val, ptr);
10662 RHS(ptr, 1) = tval;
10663 use_triple(tval, ptr);
10665 propogate_use(state, ptr, tval);
10666 unuse_triple(var, ptr);
10667 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10668 push_triple(stacks, var, tval);
10670 if (ptr->op == OP_PHI) {
10671 struct triple *var;
10672 var = MISC(ptr, 0);
10673 /* Push OP_PHI onto a stack of variable uses */
10674 push_triple(stacks, var, ptr);
10678 block->last = last;
10680 /* Fixup PHI functions in the cf successors */
10681 fixup_block_phi_variables(state, stacks, block, block->left);
10682 fixup_block_phi_variables(state, stacks, block, block->right);
10683 /* rename variables in the dominated nodes */
10684 for(user = block->idominates; user; user = user->next) {
10685 rename_block_variables(state, stacks, user->member);
10687 /* pop the renamed variable stack */
10688 last = block->first;
10690 for(ptr = block->first; !done ; ptr = next) {
10692 if (ptr == block->last) {
10695 if (ptr->op == OP_WRITE) {
10696 struct triple *var;
10698 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10699 pop_triple(stacks, var, RHS(ptr, 1));
10700 release_triple(state, ptr);
10703 if (ptr->op == OP_PHI) {
10704 struct triple *var;
10705 var = MISC(ptr, 0);
10706 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10707 pop_triple(stacks, var, ptr);
10711 block->last = last;
10714 static void prune_block_variables(struct compile_state *state,
10715 struct block *block)
10717 struct block_set *user;
10718 struct triple *next, *last, *ptr;
10720 last = block->first;
10722 for(ptr = block->first; !done; ptr = next) {
10724 if (ptr == block->last) {
10727 if (ptr->op == OP_ADECL) {
10728 struct triple_set *user, *next;
10729 for(user = ptr->use; user; user = next) {
10730 struct triple *use;
10732 use = user->member;
10733 if (use->op != OP_PHI) {
10734 internal_error(state, use, "decl still used");
10736 if (MISC(use, 0) != ptr) {
10737 internal_error(state, use, "bad phi use of decl");
10739 unuse_triple(ptr, use);
10742 release_triple(state, ptr);
10747 block->last = last;
10748 for(user = block->idominates; user; user = user->next) {
10749 prune_block_variables(state, user->member);
10753 struct phi_triple {
10754 struct triple *phi;
10759 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
10761 struct triple **slot;
10763 if (live[phi->id].alive) {
10766 live[phi->id].alive = 1;
10767 zrhs = TRIPLE_RHS(phi->sizes);
10768 slot = &RHS(phi, 0);
10769 for(i = 0; i < zrhs; i++) {
10770 struct triple *used;
10772 if (used && (used->op == OP_PHI)) {
10773 keep_phi(state, live, used);
10778 static void prune_unused_phis(struct compile_state *state)
10780 struct triple *first, *phi;
10781 struct phi_triple *live;
10785 /* Find the first instruction */
10786 first = RHS(state->main_function, 0);
10788 /* Count how many phi functions I need to process */
10790 for(phi = first->next; phi != first; phi = phi->next) {
10791 if (phi->op == OP_PHI) {
10796 /* Mark them all dead */
10797 live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
10799 for(phi = first->next; phi != first; phi = phi->next) {
10800 if (phi->op != OP_PHI) {
10803 live[phis].alive = 0;
10804 live[phis].orig_id = phi->id;
10805 live[phis].phi = phi;
10810 /* Mark phis alive that are used by non phis */
10811 for(i = 0; i < phis; i++) {
10812 struct triple_set *set;
10813 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
10814 if (set->member->op != OP_PHI) {
10815 keep_phi(state, live, live[i].phi);
10821 /* Delete the extraneous phis */
10822 for(i = 0; i < phis; i++) {
10823 struct triple **slot;
10825 if (!live[i].alive) {
10826 release_triple(state, live[i].phi);
10830 slot = &RHS(phi, 0);
10831 zrhs = TRIPLE_RHS(phi->sizes);
10832 for(j = 0; j < zrhs; j++) {
10834 error(state, phi, "variable not set on all paths to use");
10842 static void transform_to_ssa_form(struct compile_state *state)
10844 struct triple_set **stacks;
10846 insert_phi_operations(state);
10848 printf("@%s:%d\n", __FILE__, __LINE__);
10849 print_blocks(state, stdout);
10852 /* Allocate stacks for the Variables */
10853 adecls = count_and_number_adecls(state);
10854 stacks = xcmalloc(sizeof(stacks[0])*(adecls + 1), "adecl stacks");
10855 rename_block_variables(state, stacks, state->first_block);
10858 prune_block_variables(state, state->first_block);
10861 prune_unused_phis(state);
10867 static void clear_vertex(
10868 struct compile_state *state, struct block *block, void *arg)
10873 static void mark_live_block(
10874 struct compile_state *state, struct block *block, int *next_vertex)
10876 /* See if this is a block that has not been marked */
10877 if (block->vertex != 0) {
10880 block->vertex = *next_vertex;
10882 if (triple_is_branch(state, block->last)) {
10883 struct triple **targ;
10884 targ = triple_targ(state, block->last, 0);
10885 for(; targ; targ = triple_targ(state, block->last, targ)) {
10889 if (!triple_stores_block(state, *targ)) {
10890 internal_error(state, 0, "bad targ");
10892 mark_live_block(state, (*targ)->u.block, next_vertex);
10895 else if (block->last->next != RHS(state->main_function, 0)) {
10896 struct triple *ins;
10897 ins = block->last->next;
10898 if (!triple_stores_block(state, ins)) {
10899 internal_error(state, 0, "bad block start");
10901 mark_live_block(state, ins->u.block, next_vertex);
10905 static void transform_from_ssa_form(struct compile_state *state)
10907 /* To get out of ssa form we insert moves on the incoming
10908 * edges to blocks containting phi functions.
10910 struct triple *first;
10911 struct triple *phi, *next;
10914 /* Walk the control flow to see which blocks remain alive */
10915 walk_blocks(state, clear_vertex, 0);
10917 mark_live_block(state, state->first_block, &next_vertex);
10919 /* Walk all of the operations to find the phi functions */
10920 first = RHS(state->main_function, 0);
10921 for(phi = first->next; phi != first ; phi = next) {
10922 struct block_set *set;
10923 struct block *block;
10924 struct triple **slot;
10925 struct triple *var, *read;
10926 struct triple_set *use, *use_next;
10929 if (phi->op != OP_PHI) {
10932 block = phi->u.block;
10933 slot = &RHS(phi, 0);
10935 /* Forget uses from code in dead blocks */
10936 for(use = phi->use; use; use = use_next) {
10937 struct block *ublock;
10938 struct triple **expr;
10939 use_next = use->next;
10940 ublock = block_of_triple(state, use->member);
10941 if ((use->member == phi) || (ublock->vertex != 0)) {
10944 expr = triple_rhs(state, use->member, 0);
10945 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10946 if (*expr == phi) {
10950 unuse_triple(phi, use->member);
10953 #warning "CHECK_ME does the OP_ADECL need to be placed somewhere that dominates all of the incoming phi edges?"
10954 /* A variable to replace the phi function */
10955 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10956 /* A read of the single value that is set into the variable */
10957 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10958 use_triple(var, read);
10960 /* Replaces uses of the phi with variable reads */
10961 propogate_use(state, phi, read);
10963 /* Walk all of the incoming edges/blocks and insert moves.
10965 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10966 struct block *eblock;
10967 struct triple *move;
10968 struct triple *val, *base;
10969 eblock = set->member;
10972 unuse_triple(val, phi);
10974 if (!val || (val == &zero_triple) ||
10975 (block->vertex == 0) || (eblock->vertex == 0) ||
10976 (val == phi) || (val == read)) {
10980 /* Make certain the write is placed in the edge block... */
10981 base = eblock->first;
10982 if (block_of_triple(state, val) == eblock) {
10985 move = post_triple(state, base, OP_WRITE, phi->type, var, val);
10986 use_triple(val, move);
10987 use_triple(var, move);
10989 /* See if there are any writers of var */
10991 for(use = var->use; use; use = use->next) {
10992 if ((use->member->op == OP_WRITE) &&
10993 (RHS(use->member, 0) == var)) {
10997 /* If var is not used free it */
10999 unuse_triple(var, read);
11000 free_triple(state, read);
11001 free_triple(state, var);
11004 /* Release the phi function */
11005 release_triple(state, phi);
11012 * Register conflict resolution
11013 * =========================================================
11016 static struct reg_info find_def_color(
11017 struct compile_state *state, struct triple *def)
11019 struct triple_set *set;
11020 struct reg_info info;
11021 info.reg = REG_UNSET;
11023 if (!triple_is_def(state, def)) {
11026 info = arch_reg_lhs(state, def, 0);
11027 if (info.reg >= MAX_REGISTERS) {
11028 info.reg = REG_UNSET;
11030 for(set = def->use; set; set = set->next) {
11031 struct reg_info tinfo;
11033 i = find_rhs_use(state, set->member, def);
11037 tinfo = arch_reg_rhs(state, set->member, i);
11038 if (tinfo.reg >= MAX_REGISTERS) {
11039 tinfo.reg = REG_UNSET;
11041 if ((tinfo.reg != REG_UNSET) &&
11042 (info.reg != REG_UNSET) &&
11043 (tinfo.reg != info.reg)) {
11044 internal_error(state, def, "register conflict");
11046 if ((info.regcm & tinfo.regcm) == 0) {
11047 internal_error(state, def, "regcm conflict %x & %x == 0",
11048 info.regcm, tinfo.regcm);
11050 if (info.reg == REG_UNSET) {
11051 info.reg = tinfo.reg;
11053 info.regcm &= tinfo.regcm;
11055 if (info.reg >= MAX_REGISTERS) {
11056 internal_error(state, def, "register out of range");
11061 static struct reg_info find_lhs_pre_color(
11062 struct compile_state *state, struct triple *ins, int index)
11064 struct reg_info info;
11066 zrhs = TRIPLE_RHS(ins->sizes);
11067 zlhs = TRIPLE_LHS(ins->sizes);
11068 if (!zlhs && triple_is_def(state, ins)) {
11071 if (index >= zlhs) {
11072 internal_error(state, ins, "Bad lhs %d", index);
11074 info = arch_reg_lhs(state, ins, index);
11075 for(i = 0; i < zrhs; i++) {
11076 struct reg_info rinfo;
11077 rinfo = arch_reg_rhs(state, ins, i);
11078 if ((info.reg == rinfo.reg) &&
11079 (rinfo.reg >= MAX_REGISTERS)) {
11080 struct reg_info tinfo;
11081 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
11082 info.reg = tinfo.reg;
11083 info.regcm &= tinfo.regcm;
11087 if (info.reg >= MAX_REGISTERS) {
11088 info.reg = REG_UNSET;
11093 static struct reg_info find_rhs_post_color(
11094 struct compile_state *state, struct triple *ins, int index);
11096 static struct reg_info find_lhs_post_color(
11097 struct compile_state *state, struct triple *ins, int index)
11099 struct triple_set *set;
11100 struct reg_info info;
11101 struct triple *lhs;
11102 #if DEBUG_TRIPLE_COLOR
11103 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
11106 if ((index == 0) && triple_is_def(state, ins)) {
11109 else if (index < TRIPLE_LHS(ins->sizes)) {
11110 lhs = LHS(ins, index);
11113 internal_error(state, ins, "Bad lhs %d", index);
11116 info = arch_reg_lhs(state, ins, index);
11117 if (info.reg >= MAX_REGISTERS) {
11118 info.reg = REG_UNSET;
11120 for(set = lhs->use; set; set = set->next) {
11121 struct reg_info rinfo;
11122 struct triple *user;
11124 user = set->member;
11125 zrhs = TRIPLE_RHS(user->sizes);
11126 for(i = 0; i < zrhs; i++) {
11127 if (RHS(user, i) != lhs) {
11130 rinfo = find_rhs_post_color(state, user, i);
11131 if ((info.reg != REG_UNSET) &&
11132 (rinfo.reg != REG_UNSET) &&
11133 (info.reg != rinfo.reg)) {
11134 internal_error(state, ins, "register conflict");
11136 if ((info.regcm & rinfo.regcm) == 0) {
11137 internal_error(state, ins, "regcm conflict %x & %x == 0",
11138 info.regcm, rinfo.regcm);
11140 if (info.reg == REG_UNSET) {
11141 info.reg = rinfo.reg;
11143 info.regcm &= rinfo.regcm;
11146 #if DEBUG_TRIPLE_COLOR
11147 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
11148 ins, index, info.reg, info.regcm);
11153 static struct reg_info find_rhs_post_color(
11154 struct compile_state *state, struct triple *ins, int index)
11156 struct reg_info info, rinfo;
11158 #if DEBUG_TRIPLE_COLOR
11159 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
11162 rinfo = arch_reg_rhs(state, ins, index);
11163 zlhs = TRIPLE_LHS(ins->sizes);
11164 if (!zlhs && triple_is_def(state, ins)) {
11168 if (info.reg >= MAX_REGISTERS) {
11169 info.reg = REG_UNSET;
11171 for(i = 0; i < zlhs; i++) {
11172 struct reg_info linfo;
11173 linfo = arch_reg_lhs(state, ins, i);
11174 if ((linfo.reg == rinfo.reg) &&
11175 (linfo.reg >= MAX_REGISTERS)) {
11176 struct reg_info tinfo;
11177 tinfo = find_lhs_post_color(state, ins, i);
11178 if (tinfo.reg >= MAX_REGISTERS) {
11179 tinfo.reg = REG_UNSET;
11181 info.regcm &= linfo.regcm;
11182 info.regcm &= tinfo.regcm;
11183 if (info.reg != REG_UNSET) {
11184 internal_error(state, ins, "register conflict");
11186 if (info.regcm == 0) {
11187 internal_error(state, ins, "regcm conflict");
11189 info.reg = tinfo.reg;
11192 #if DEBUG_TRIPLE_COLOR
11193 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
11194 ins, index, info.reg, info.regcm);
11199 static struct reg_info find_lhs_color(
11200 struct compile_state *state, struct triple *ins, int index)
11202 struct reg_info pre, post, info;
11203 #if DEBUG_TRIPLE_COLOR
11204 fprintf(stderr, "find_lhs_color(%p, %d)\n",
11207 pre = find_lhs_pre_color(state, ins, index);
11208 post = find_lhs_post_color(state, ins, index);
11209 if ((pre.reg != post.reg) &&
11210 (pre.reg != REG_UNSET) &&
11211 (post.reg != REG_UNSET)) {
11212 internal_error(state, ins, "register conflict");
11214 info.regcm = pre.regcm & post.regcm;
11215 info.reg = pre.reg;
11216 if (info.reg == REG_UNSET) {
11217 info.reg = post.reg;
11219 #if DEBUG_TRIPLE_COLOR
11220 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
11221 ins, index, info.reg, info.regcm,
11222 pre.reg, pre.regcm, post.reg, post.regcm);
11227 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
11229 struct triple_set *entry, *next;
11230 struct triple *out;
11231 struct reg_info info, rinfo;
11233 info = arch_reg_lhs(state, ins, 0);
11234 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
11235 use_triple(RHS(out, 0), out);
11236 /* Get the users of ins to use out instead */
11237 for(entry = ins->use; entry; entry = next) {
11239 next = entry->next;
11240 if (entry->member == out) {
11243 i = find_rhs_use(state, entry->member, ins);
11247 rinfo = arch_reg_rhs(state, entry->member, i);
11248 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
11251 replace_rhs_use(state, ins, out, entry->member);
11253 transform_to_arch_instruction(state, out);
11257 static struct triple *typed_pre_copy(
11258 struct compile_state *state, struct type *type, struct triple *ins, int index)
11260 /* Carefully insert enough operations so that I can
11261 * enter any operation with a GPR32.
11264 struct triple **expr;
11266 struct reg_info info;
11267 if (ins->op == OP_PHI) {
11268 internal_error(state, ins, "pre_copy on a phi?");
11270 classes = arch_type_to_regcm(state, type);
11271 info = arch_reg_rhs(state, ins, index);
11272 expr = &RHS(ins, index);
11273 if ((info.regcm & classes) == 0) {
11274 internal_error(state, ins, "pre_copy with no register classes");
11276 in = pre_triple(state, ins, OP_COPY, type, *expr, 0);
11277 unuse_triple(*expr, ins);
11279 use_triple(RHS(in, 0), in);
11280 use_triple(in, ins);
11281 transform_to_arch_instruction(state, in);
11285 static struct triple *pre_copy(
11286 struct compile_state *state, struct triple *ins, int index)
11288 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
11292 static void insert_copies_to_phi(struct compile_state *state)
11294 /* To get out of ssa form we insert moves on the incoming
11295 * edges to blocks containting phi functions.
11297 struct triple *first;
11298 struct triple *phi;
11300 /* Walk all of the operations to find the phi functions */
11301 first = RHS(state->main_function, 0);
11302 for(phi = first->next; phi != first ; phi = phi->next) {
11303 struct block_set *set;
11304 struct block *block;
11305 struct triple **slot, *copy;
11307 if (phi->op != OP_PHI) {
11310 phi->id |= TRIPLE_FLAG_POST_SPLIT;
11311 block = phi->u.block;
11312 slot = &RHS(phi, 0);
11313 /* Phi's that feed into mandatory live range joins
11314 * cause nasty complications. Insert a copy of
11315 * the phi value so I never have to deal with
11316 * that in the rest of the code.
11318 copy = post_copy(state, phi);
11319 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
11320 /* Walk all of the incoming edges/blocks and insert moves.
11322 for(edge = 0, set = block->use; set; set = set->next, edge++) {
11323 struct block *eblock;
11324 struct triple *move;
11325 struct triple *val;
11326 struct triple *ptr;
11327 eblock = set->member;
11334 get_occurance(val->occurance);
11335 move = build_triple(state, OP_COPY, phi->type, val, 0,
11337 move->u.block = eblock;
11338 move->id |= TRIPLE_FLAG_PRE_SPLIT;
11339 use_triple(val, move);
11342 unuse_triple(val, phi);
11343 use_triple(move, phi);
11345 /* Walk up the dominator tree until I have found the appropriate block */
11346 while(eblock && !tdominates(state, val, eblock->last)) {
11347 eblock = eblock->idom;
11350 internal_error(state, phi, "Cannot find block dominated by %p",
11354 /* Walk through the block backwards to find
11355 * an appropriate location for the OP_COPY.
11357 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
11358 struct triple **expr;
11359 if ((ptr == phi) || (ptr == val)) {
11362 expr = triple_rhs(state, ptr, 0);
11363 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11364 if ((*expr) == phi) {
11370 if (triple_is_branch(state, ptr)) {
11371 internal_error(state, ptr,
11372 "Could not insert write to phi");
11374 insert_triple(state, ptr->next, move);
11375 if (eblock->last == ptr) {
11376 eblock->last = move;
11378 transform_to_arch_instruction(state, move);
11383 struct triple_reg_set {
11384 struct triple_reg_set *next;
11385 struct triple *member;
11386 struct triple *new;
11390 struct block *block;
11391 struct triple_reg_set *in;
11392 struct triple_reg_set *out;
11396 static int do_triple_set(struct triple_reg_set **head,
11397 struct triple *member, struct triple *new_member)
11399 struct triple_reg_set **ptr, *new;
11404 if ((*ptr)->member == member) {
11407 ptr = &(*ptr)->next;
11409 new = xcmalloc(sizeof(*new), "triple_set");
11410 new->member = member;
11411 new->new = new_member;
11417 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11419 struct triple_reg_set *entry, **ptr;
11423 if (entry->member == member) {
11424 *ptr = entry->next;
11429 ptr = &entry->next;
11434 static int in_triple(struct reg_block *rb, struct triple *in)
11436 return do_triple_set(&rb->in, in, 0);
11438 static void unin_triple(struct reg_block *rb, struct triple *unin)
11440 do_triple_unset(&rb->in, unin);
11443 static int out_triple(struct reg_block *rb, struct triple *out)
11445 return do_triple_set(&rb->out, out, 0);
11447 static void unout_triple(struct reg_block *rb, struct triple *unout)
11449 do_triple_unset(&rb->out, unout);
11452 static int initialize_regblock(struct reg_block *blocks,
11453 struct block *block, int vertex)
11455 struct block_set *user;
11456 if (!block || (blocks[block->vertex].block == block)) {
11460 /* Renumber the blocks in a convinient fashion */
11461 block->vertex = vertex;
11462 blocks[vertex].block = block;
11463 blocks[vertex].vertex = vertex;
11464 for(user = block->use; user; user = user->next) {
11465 vertex = initialize_regblock(blocks, user->member, vertex);
11470 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11471 struct reg_block *rb, struct block *suc)
11473 /* Read the conditional input set of a successor block
11474 * (i.e. the input to the phi nodes) and place it in the
11475 * current blocks output set.
11477 struct block_set *set;
11478 struct triple *ptr;
11482 /* Find the edge I am coming in on */
11483 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11484 if (set->member == rb->block) {
11489 internal_error(state, 0, "Not coming on a control edge?");
11491 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11492 struct triple **slot, *expr, *ptr2;
11493 int out_change, done2;
11494 done = (ptr == suc->last);
11495 if (ptr->op != OP_PHI) {
11498 slot = &RHS(ptr, 0);
11500 out_change = out_triple(rb, expr);
11504 /* If we don't define the variable also plast it
11505 * in the current blocks input set.
11507 ptr2 = rb->block->first;
11508 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11509 if (ptr2 == expr) {
11512 done2 = (ptr2 == rb->block->last);
11517 change |= in_triple(rb, expr);
11522 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11523 struct reg_block *rb, struct block *suc)
11525 struct triple_reg_set *in_set;
11528 /* Read the input set of a successor block
11529 * and place it in the current blocks output set.
11531 in_set = blocks[suc->vertex].in;
11532 for(; in_set; in_set = in_set->next) {
11533 int out_change, done;
11534 struct triple *first, *last, *ptr;
11535 out_change = out_triple(rb, in_set->member);
11539 /* If we don't define the variable also place it
11540 * in the current blocks input set.
11542 first = rb->block->first;
11543 last = rb->block->last;
11545 for(ptr = first; !done; ptr = ptr->next) {
11546 if (ptr == in_set->member) {
11549 done = (ptr == last);
11554 change |= in_triple(rb, in_set->member);
11556 change |= phi_in(state, blocks, rb, suc);
11561 static int use_in(struct compile_state *state, struct reg_block *rb)
11563 /* Find the variables we use but don't define and add
11564 * it to the current blocks input set.
11566 #warning "FIXME is this O(N^2) algorithm bad?"
11567 struct block *block;
11568 struct triple *ptr;
11573 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11574 struct triple **expr;
11575 done = (ptr == block->first);
11576 /* The variable a phi function uses depends on the
11577 * control flow, and is handled in phi_in, not
11580 if (ptr->op == OP_PHI) {
11583 expr = triple_rhs(state, ptr, 0);
11584 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11585 struct triple *rhs, *test;
11591 /* See if rhs is defined in this block */
11592 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11593 tdone = (test == block->first);
11599 /* If I still have a valid rhs add it to in */
11600 change |= in_triple(rb, rhs);
11606 static struct reg_block *compute_variable_lifetimes(
11607 struct compile_state *state)
11609 struct reg_block *blocks;
11612 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11613 initialize_regblock(blocks, state->last_block, 0);
11617 for(i = 1; i <= state->last_vertex; i++) {
11618 struct reg_block *rb;
11620 /* Add the left successor's input set to in */
11621 if (rb->block->left) {
11622 change |= reg_in(state, blocks, rb, rb->block->left);
11624 /* Add the right successor's input set to in */
11625 if ((rb->block->right) &&
11626 (rb->block->right != rb->block->left)) {
11627 change |= reg_in(state, blocks, rb, rb->block->right);
11629 /* Add use to in... */
11630 change |= use_in(state, rb);
11636 static void free_variable_lifetimes(
11637 struct compile_state *state, struct reg_block *blocks)
11640 /* free in_set && out_set on each block */
11641 for(i = 1; i <= state->last_vertex; i++) {
11642 struct triple_reg_set *entry, *next;
11643 struct reg_block *rb;
11645 for(entry = rb->in; entry ; entry = next) {
11646 next = entry->next;
11647 do_triple_unset(&rb->in, entry->member);
11649 for(entry = rb->out; entry; entry = next) {
11650 next = entry->next;
11651 do_triple_unset(&rb->out, entry->member);
11658 typedef void (*wvl_cb_t)(
11659 struct compile_state *state,
11660 struct reg_block *blocks, struct triple_reg_set *live,
11661 struct reg_block *rb, struct triple *ins, void *arg);
11663 static void walk_variable_lifetimes(struct compile_state *state,
11664 struct reg_block *blocks, wvl_cb_t cb, void *arg)
11668 for(i = 1; i <= state->last_vertex; i++) {
11669 struct triple_reg_set *live;
11670 struct triple_reg_set *entry, *next;
11671 struct triple *ptr, *prev;
11672 struct reg_block *rb;
11673 struct block *block;
11676 /* Get the blocks */
11680 /* Copy out into live */
11682 for(entry = rb->out; entry; entry = next) {
11683 next = entry->next;
11684 do_triple_set(&live, entry->member, entry->new);
11686 /* Walk through the basic block calculating live */
11687 for(done = 0, ptr = block->last; !done; ptr = prev) {
11688 struct triple **expr;
11691 done = (ptr == block->first);
11693 /* Ensure the current definition is in live */
11694 if (triple_is_def(state, ptr)) {
11695 do_triple_set(&live, ptr, 0);
11698 /* Inform the callback function of what is
11701 cb(state, blocks, live, rb, ptr, arg);
11703 /* Remove the current definition from live */
11704 do_triple_unset(&live, ptr);
11706 /* Add the current uses to live.
11708 * It is safe to skip phi functions because they do
11709 * not have any block local uses, and the block
11710 * output sets already properly account for what
11711 * control flow depedent uses phi functions do have.
11713 if (ptr->op == OP_PHI) {
11716 expr = triple_rhs(state, ptr, 0);
11717 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11718 /* If the triple is not a definition skip it. */
11719 if (!*expr || !triple_is_def(state, *expr)) {
11722 do_triple_set(&live, *expr, 0);
11726 for(entry = live; entry; entry = next) {
11727 next = entry->next;
11728 do_triple_unset(&live, entry->member);
11733 static int count_triples(struct compile_state *state)
11735 struct triple *first, *ins;
11737 first = RHS(state->main_function, 0);
11742 } while (ins != first);
11747 struct dead_triple {
11748 struct triple *triple;
11749 struct dead_triple *work_next;
11750 struct block *block;
11753 #define TRIPLE_FLAG_ALIVE 1
11757 static void awaken(
11758 struct compile_state *state,
11759 struct dead_triple *dtriple, struct triple **expr,
11760 struct dead_triple ***work_list_tail)
11762 struct triple *triple;
11763 struct dead_triple *dt;
11771 if (triple->id <= 0) {
11772 internal_error(state, triple, "bad triple id: %d",
11775 if (triple->op == OP_NOOP) {
11776 internal_warning(state, triple, "awakening noop?");
11779 dt = &dtriple[triple->id];
11780 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11781 dt->flags |= TRIPLE_FLAG_ALIVE;
11782 if (!dt->work_next) {
11783 **work_list_tail = dt;
11784 *work_list_tail = &dt->work_next;
11789 static void eliminate_inefectual_code(struct compile_state *state)
11791 struct block *block;
11792 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11794 struct triple *first, *ins;
11796 /* Setup the work list */
11798 work_list_tail = &work_list;
11800 first = RHS(state->main_function, 0);
11802 /* Count how many triples I have */
11803 triples = count_triples(state);
11805 /* Now put then in an array and mark all of the triples dead */
11806 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11812 if (ins->op == OP_LABEL) {
11813 block = ins->u.block;
11815 dtriple[i].triple = ins;
11816 dtriple[i].block = block;
11817 dtriple[i].flags = 0;
11818 dtriple[i].color = ins->id;
11820 /* See if it is an operation we always keep */
11821 #warning "FIXME handle the case of killing a branch instruction"
11822 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11823 awaken(state, dtriple, &ins, &work_list_tail);
11826 /* Unconditionally keep the very last instruction */
11827 else if (ins->next == first) {
11828 awaken(state, dtriple, &ins, &work_list_tail);
11833 } while(ins != first);
11835 struct dead_triple *dt;
11836 struct block_set *user;
11837 struct triple **expr;
11839 work_list = dt->work_next;
11841 work_list_tail = &work_list;
11843 /* Wake up the data depencencies of this triple */
11846 expr = triple_rhs(state, dt->triple, expr);
11847 awaken(state, dtriple, expr, &work_list_tail);
11850 expr = triple_lhs(state, dt->triple, expr);
11851 awaken(state, dtriple, expr, &work_list_tail);
11854 expr = triple_misc(state, dt->triple, expr);
11855 awaken(state, dtriple, expr, &work_list_tail);
11857 /* Wake up the forward control dependencies */
11859 expr = triple_targ(state, dt->triple, expr);
11860 awaken(state, dtriple, expr, &work_list_tail);
11862 /* Wake up the reverse control dependencies of this triple */
11863 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11864 awaken(state, dtriple, &user->member->last, &work_list_tail);
11867 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11868 if ((dt->triple->op == OP_NOOP) &&
11869 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11870 internal_error(state, dt->triple, "noop effective?");
11872 dt->triple->id = dt->color; /* Restore the color */
11873 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11874 #warning "FIXME handle the case of killing a basic block"
11875 if (dt->block->first == dt->triple) {
11878 if (dt->block->last == dt->triple) {
11879 dt->block->last = dt->triple->prev;
11881 release_triple(state, dt->triple);
11888 static void insert_mandatory_copies(struct compile_state *state)
11890 struct triple *ins, *first;
11892 /* The object is with a minimum of inserted copies,
11893 * to resolve in fundamental register conflicts between
11894 * register value producers and consumers.
11895 * Theoretically we may be greater than minimal when we
11896 * are inserting copies before instructions but that
11897 * case should be rare.
11899 first = RHS(state->main_function, 0);
11902 struct triple_set *entry, *next;
11903 struct triple *tmp;
11904 struct reg_info info;
11905 unsigned reg, regcm;
11906 int do_post_copy, do_pre_copy;
11908 if (!triple_is_def(state, ins)) {
11911 /* Find the architecture specific color information */
11912 info = arch_reg_lhs(state, ins, 0);
11913 if (info.reg >= MAX_REGISTERS) {
11914 info.reg = REG_UNSET;
11918 regcm = arch_type_to_regcm(state, ins->type);
11919 do_post_copy = do_pre_copy = 0;
11921 /* Walk through the uses of ins and check for conflicts */
11922 for(entry = ins->use; entry; entry = next) {
11923 struct reg_info rinfo;
11925 next = entry->next;
11926 i = find_rhs_use(state, entry->member, ins);
11931 /* Find the users color requirements */
11932 rinfo = arch_reg_rhs(state, entry->member, i);
11933 if (rinfo.reg >= MAX_REGISTERS) {
11934 rinfo.reg = REG_UNSET;
11937 /* See if I need a pre_copy */
11938 if (rinfo.reg != REG_UNSET) {
11939 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11944 regcm &= rinfo.regcm;
11945 regcm = arch_regcm_normalize(state, regcm);
11949 /* Always use pre_copies for constants.
11950 * They do not take up any registers until a
11951 * copy places them in one.
11953 if ((info.reg == REG_UNNEEDED) &&
11954 (rinfo.reg != REG_UNNEEDED)) {
11960 (((info.reg != REG_UNSET) &&
11961 (reg != REG_UNSET) &&
11962 (info.reg != reg)) ||
11963 ((info.regcm & regcm) == 0));
11966 regcm = info.regcm;
11967 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
11968 for(entry = ins->use; entry; entry = next) {
11969 struct reg_info rinfo;
11971 next = entry->next;
11972 i = find_rhs_use(state, entry->member, ins);
11977 /* Find the users color requirements */
11978 rinfo = arch_reg_rhs(state, entry->member, i);
11979 if (rinfo.reg >= MAX_REGISTERS) {
11980 rinfo.reg = REG_UNSET;
11983 /* Now see if it is time to do the pre_copy */
11984 if (rinfo.reg != REG_UNSET) {
11985 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11986 ((regcm & rinfo.regcm) == 0) ||
11987 /* Don't let a mandatory coalesce sneak
11988 * into a operation that is marked to prevent
11991 ((reg != REG_UNNEEDED) &&
11992 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11993 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11996 struct triple *user;
11997 user = entry->member;
11998 if (RHS(user, i) != ins) {
11999 internal_error(state, user, "bad rhs");
12001 tmp = pre_copy(state, user, i);
12002 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
12010 if ((regcm & rinfo.regcm) == 0) {
12012 struct triple *user;
12013 user = entry->member;
12014 if (RHS(user, i) != ins) {
12015 internal_error(state, user, "bad rhs");
12017 tmp = pre_copy(state, user, i);
12018 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
12024 regcm &= rinfo.regcm;
12027 if (do_post_copy) {
12028 struct reg_info pre, post;
12029 tmp = post_copy(state, ins);
12030 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
12031 pre = arch_reg_lhs(state, ins, 0);
12032 post = arch_reg_lhs(state, tmp, 0);
12033 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
12034 internal_error(state, tmp, "useless copy");
12039 } while(ins != first);
12043 struct live_range_edge;
12044 struct live_range_def;
12045 struct live_range {
12046 struct live_range_edge *edges;
12047 struct live_range_def *defs;
12048 /* Note. The list pointed to by defs is kept in order.
12049 * That is baring splits in the flow control
12050 * defs dominates defs->next wich dominates defs->next->next
12057 struct live_range *group_next, **group_prev;
12060 struct live_range_edge {
12061 struct live_range_edge *next;
12062 struct live_range *node;
12065 struct live_range_def {
12066 struct live_range_def *next;
12067 struct live_range_def *prev;
12068 struct live_range *lr;
12069 struct triple *def;
12073 #define LRE_HASH_SIZE 2048
12075 struct lre_hash *next;
12076 struct live_range *left;
12077 struct live_range *right;
12082 struct lre_hash *hash[LRE_HASH_SIZE];
12083 struct reg_block *blocks;
12084 struct live_range_def *lrd;
12085 struct live_range *lr;
12086 struct live_range *low, **low_tail;
12087 struct live_range *high, **high_tail;
12090 int passes, max_passes;
12091 #define MAX_ALLOCATION_PASSES 100
12096 struct print_interference_block_info {
12097 struct reg_state *rstate;
12101 static void print_interference_block(
12102 struct compile_state *state, struct block *block, void *arg)
12105 struct print_interference_block_info *info = arg;
12106 struct reg_state *rstate = info->rstate;
12107 FILE *fp = info->fp;
12108 struct reg_block *rb;
12109 struct triple *ptr;
12112 rb = &rstate->blocks[block->vertex];
12114 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
12118 block->left && block->left->use?block->left->use->member : 0,
12120 block->right && block->right->use?block->right->use->member : 0);
12122 struct triple_reg_set *in_set;
12123 fprintf(fp, " in:");
12124 for(in_set = rb->in; in_set; in_set = in_set->next) {
12125 fprintf(fp, " %-10p", in_set->member);
12130 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12131 done = (ptr == block->last);
12132 if (ptr->op == OP_PHI) {
12139 for(edge = 0; edge < block->users; edge++) {
12140 fprintf(fp, " in(%d):", edge);
12141 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12142 struct triple **slot;
12143 done = (ptr == block->last);
12144 if (ptr->op != OP_PHI) {
12147 slot = &RHS(ptr, 0);
12148 fprintf(fp, " %-10p", slot[edge]);
12153 if (block->first->op == OP_LABEL) {
12154 fprintf(fp, "%p:\n", block->first);
12156 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12157 struct live_range *lr;
12161 done = (ptr == block->last);
12162 lr = rstate->lrd[ptr->id].lr;
12165 ptr->id = rstate->lrd[id].orig_id;
12166 SET_REG(ptr->id, lr->color);
12167 display_triple(fp, ptr);
12170 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
12171 internal_error(state, ptr, "lr has no defs!");
12173 if (info->need_edges) {
12175 struct live_range_def *lrd;
12176 fprintf(fp, " range:");
12179 fprintf(fp, " %-10p", lrd->def);
12181 } while(lrd != lr->defs);
12184 if (lr->edges > 0) {
12185 struct live_range_edge *edge;
12186 fprintf(fp, " edges:");
12187 for(edge = lr->edges; edge; edge = edge->next) {
12188 struct live_range_def *lrd;
12189 lrd = edge->node->defs;
12191 fprintf(fp, " %-10p", lrd->def);
12193 } while(lrd != edge->node->defs);
12199 /* Do a bunch of sanity checks */
12200 valid_ins(state, ptr);
12201 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
12202 internal_error(state, ptr, "Invalid triple id: %d",
12207 struct triple_reg_set *out_set;
12208 fprintf(fp, " out:");
12209 for(out_set = rb->out; out_set; out_set = out_set->next) {
12210 fprintf(fp, " %-10p", out_set->member);
12217 static void print_interference_blocks(
12218 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
12220 struct print_interference_block_info info;
12221 info.rstate = rstate;
12223 info.need_edges = need_edges;
12224 fprintf(fp, "\nlive variables by block\n");
12225 walk_blocks(state, print_interference_block, &info);
12229 static unsigned regc_max_size(struct compile_state *state, int classes)
12234 for(i = 0; i < MAX_REGC; i++) {
12235 if (classes & (1 << i)) {
12237 size = arch_regc_size(state, i);
12238 if (size > max_size) {
12246 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
12248 unsigned equivs[MAX_REG_EQUIVS];
12250 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
12251 internal_error(state, 0, "invalid register");
12253 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
12254 internal_error(state, 0, "invalid register");
12256 arch_reg_equivs(state, equivs, reg1);
12257 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12258 if (equivs[i] == reg2) {
12265 static void reg_fill_used(struct compile_state *state, char *used, int reg)
12267 unsigned equivs[MAX_REG_EQUIVS];
12269 if (reg == REG_UNNEEDED) {
12272 arch_reg_equivs(state, equivs, reg);
12273 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12274 used[equivs[i]] = 1;
12279 static void reg_inc_used(struct compile_state *state, char *used, int reg)
12281 unsigned equivs[MAX_REG_EQUIVS];
12283 if (reg == REG_UNNEEDED) {
12286 arch_reg_equivs(state, equivs, reg);
12287 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12288 used[equivs[i]] += 1;
12293 static unsigned int hash_live_edge(
12294 struct live_range *left, struct live_range *right)
12296 unsigned int hash, val;
12297 unsigned long lval, rval;
12298 lval = ((unsigned long)left)/sizeof(struct live_range);
12299 rval = ((unsigned long)right)/sizeof(struct live_range);
12304 hash = (hash *263) + val;
12309 hash = (hash *263) + val;
12311 hash = hash & (LRE_HASH_SIZE - 1);
12315 static struct lre_hash **lre_probe(struct reg_state *rstate,
12316 struct live_range *left, struct live_range *right)
12318 struct lre_hash **ptr;
12319 unsigned int index;
12320 /* Ensure left <= right */
12321 if (left > right) {
12322 struct live_range *tmp;
12327 index = hash_live_edge(left, right);
12329 ptr = &rstate->hash[index];
12331 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
12334 ptr = &(*ptr)->next;
12339 static int interfere(struct reg_state *rstate,
12340 struct live_range *left, struct live_range *right)
12342 struct lre_hash **ptr;
12343 ptr = lre_probe(rstate, left, right);
12344 return ptr && *ptr;
12347 static void add_live_edge(struct reg_state *rstate,
12348 struct live_range *left, struct live_range *right)
12350 /* FIXME the memory allocation overhead is noticeable here... */
12351 struct lre_hash **ptr, *new_hash;
12352 struct live_range_edge *edge;
12354 if (left == right) {
12357 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
12360 /* Ensure left <= right */
12361 if (left > right) {
12362 struct live_range *tmp;
12367 ptr = lre_probe(rstate, left, right);
12372 fprintf(stderr, "new_live_edge(%p, %p)\n",
12375 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
12376 new_hash->next = *ptr;
12377 new_hash->left = left;
12378 new_hash->right = right;
12381 edge = xmalloc(sizeof(*edge), "live_range_edge");
12382 edge->next = left->edges;
12383 edge->node = right;
12384 left->edges = edge;
12387 edge = xmalloc(sizeof(*edge), "live_range_edge");
12388 edge->next = right->edges;
12390 right->edges = edge;
12391 right->degree += 1;
12394 static void remove_live_edge(struct reg_state *rstate,
12395 struct live_range *left, struct live_range *right)
12397 struct live_range_edge *edge, **ptr;
12398 struct lre_hash **hptr, *entry;
12399 hptr = lre_probe(rstate, left, right);
12400 if (!hptr || !*hptr) {
12404 *hptr = entry->next;
12407 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
12409 if (edge->node == right) {
12411 memset(edge, 0, sizeof(*edge));
12417 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
12419 if (edge->node == left) {
12421 memset(edge, 0, sizeof(*edge));
12429 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
12431 struct live_range_edge *edge, *next;
12432 for(edge = range->edges; edge; edge = next) {
12434 remove_live_edge(rstate, range, edge->node);
12438 static void transfer_live_edges(struct reg_state *rstate,
12439 struct live_range *dest, struct live_range *src)
12441 struct live_range_edge *edge, *next;
12442 for(edge = src->edges; edge; edge = next) {
12443 struct live_range *other;
12445 other = edge->node;
12446 remove_live_edge(rstate, src, other);
12447 add_live_edge(rstate, dest, other);
12452 /* Interference graph...
12454 * new(n) --- Return a graph with n nodes but no edges.
12455 * add(g,x,y) --- Return a graph including g with an between x and y
12456 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
12457 * x and y in the graph g
12458 * degree(g, x) --- Return the degree of the node x in the graph g
12459 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
12461 * Implement with a hash table && a set of adjcency vectors.
12462 * The hash table supports constant time implementations of add and interfere.
12463 * The adjacency vectors support an efficient implementation of neighbors.
12467 * +---------------------------------------------------+
12468 * | +--------------+ |
12470 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
12472 * -- In simplify implment optimistic coloring... (No backtracking)
12473 * -- Implement Rematerialization it is the only form of spilling we can perform
12474 * Essentially this means dropping a constant from a register because
12475 * we can regenerate it later.
12477 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
12478 * coalesce at phi points...
12479 * --- Bias coloring if at all possible do the coalesing a compile time.
12484 static void different_colored(
12485 struct compile_state *state, struct reg_state *rstate,
12486 struct triple *parent, struct triple *ins)
12488 struct live_range *lr;
12489 struct triple **expr;
12490 lr = rstate->lrd[ins->id].lr;
12491 expr = triple_rhs(state, ins, 0);
12492 for(;expr; expr = triple_rhs(state, ins, expr)) {
12493 struct live_range *lr2;
12494 if (!*expr || (*expr == parent) || (*expr == ins)) {
12497 lr2 = rstate->lrd[(*expr)->id].lr;
12498 if (lr->color == lr2->color) {
12499 internal_error(state, ins, "live range too big");
12505 static struct live_range *coalesce_ranges(
12506 struct compile_state *state, struct reg_state *rstate,
12507 struct live_range *lr1, struct live_range *lr2)
12509 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
12515 if (!lr1->defs || !lr2->defs) {
12516 internal_error(state, 0,
12517 "cannot coalese dead live ranges");
12519 if ((lr1->color == REG_UNNEEDED) ||
12520 (lr2->color == REG_UNNEEDED)) {
12521 internal_error(state, 0,
12522 "cannot coalesce live ranges without a possible color");
12524 if ((lr1->color != lr2->color) &&
12525 (lr1->color != REG_UNSET) &&
12526 (lr2->color != REG_UNSET)) {
12527 internal_error(state, lr1->defs->def,
12528 "cannot coalesce live ranges of different colors");
12530 color = lr1->color;
12531 if (color == REG_UNSET) {
12532 color = lr2->color;
12534 classes = lr1->classes & lr2->classes;
12536 internal_error(state, lr1->defs->def,
12537 "cannot coalesce live ranges with dissimilar register classes");
12539 #if DEBUG_COALESCING
12540 fprintf(stderr, "coalescing:");
12543 fprintf(stderr, " %p", lrd->def);
12545 } while(lrd != lr1->defs);
12546 fprintf(stderr, " |");
12549 fprintf(stderr, " %p", lrd->def);
12551 } while(lrd != lr2->defs);
12552 fprintf(stderr, "\n");
12554 /* If there is a clear dominate live range put it in lr1,
12555 * For purposes of this test phi functions are
12556 * considered dominated by the definitions that feed into
12559 if ((lr1->defs->prev->def->op == OP_PHI) ||
12560 ((lr2->defs->prev->def->op != OP_PHI) &&
12561 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12562 struct live_range *tmp;
12568 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12569 fprintf(stderr, "lr1 post\n");
12571 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12572 fprintf(stderr, "lr1 pre\n");
12574 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12575 fprintf(stderr, "lr2 post\n");
12577 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12578 fprintf(stderr, "lr2 pre\n");
12582 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12589 /* Append lr2 onto lr1 */
12590 #warning "FIXME should this be a merge instead of a splice?"
12591 /* This FIXME item applies to the correctness of live_range_end
12592 * and to the necessity of making multiple passes of coalesce_live_ranges.
12593 * A failure to find some coalesce opportunities in coaleace_live_ranges
12594 * does not impact the correct of the compiler just the efficiency with
12595 * which registers are allocated.
12598 mid1 = lr1->defs->prev;
12600 end = lr2->defs->prev;
12608 /* Fixup the live range in the added live range defs */
12613 } while(lrd != head);
12615 /* Mark lr2 as free. */
12617 lr2->color = REG_UNNEEDED;
12621 internal_error(state, 0, "lr1->defs == 0 ?");
12624 lr1->color = color;
12625 lr1->classes = classes;
12627 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12628 transfer_live_edges(rstate, lr1, lr2);
12633 static struct live_range_def *live_range_head(
12634 struct compile_state *state, struct live_range *lr,
12635 struct live_range_def *last)
12637 struct live_range_def *result;
12642 else if (!tdominates(state, lr->defs->def, last->next->def)) {
12643 result = last->next;
12648 static struct live_range_def *live_range_end(
12649 struct compile_state *state, struct live_range *lr,
12650 struct live_range_def *last)
12652 struct live_range_def *result;
12655 result = lr->defs->prev;
12657 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12658 result = last->prev;
12664 static void initialize_live_ranges(
12665 struct compile_state *state, struct reg_state *rstate)
12667 struct triple *ins, *first;
12668 size_t count, size;
12671 first = RHS(state->main_function, 0);
12672 /* First count how many instructions I have.
12674 count = count_triples(state);
12675 /* Potentially I need one live range definitions for each
12678 rstate->defs = count;
12679 /* Potentially I need one live range for each instruction
12680 * plus an extra for the dummy live range.
12682 rstate->ranges = count + 1;
12683 size = sizeof(rstate->lrd[0]) * rstate->defs;
12684 rstate->lrd = xcmalloc(size, "live_range_def");
12685 size = sizeof(rstate->lr[0]) * rstate->ranges;
12686 rstate->lr = xcmalloc(size, "live_range");
12688 /* Setup the dummy live range */
12689 rstate->lr[0].classes = 0;
12690 rstate->lr[0].color = REG_UNSET;
12691 rstate->lr[0].defs = 0;
12695 /* If the triple is a variable give it a live range */
12696 if (triple_is_def(state, ins)) {
12697 struct reg_info info;
12698 /* Find the architecture specific color information */
12699 info = find_def_color(state, ins);
12701 rstate->lr[i].defs = &rstate->lrd[j];
12702 rstate->lr[i].color = info.reg;
12703 rstate->lr[i].classes = info.regcm;
12704 rstate->lr[i].degree = 0;
12705 rstate->lrd[j].lr = &rstate->lr[i];
12707 /* Otherwise give the triple the dummy live range. */
12709 rstate->lrd[j].lr = &rstate->lr[0];
12712 /* Initalize the live_range_def */
12713 rstate->lrd[j].next = &rstate->lrd[j];
12714 rstate->lrd[j].prev = &rstate->lrd[j];
12715 rstate->lrd[j].def = ins;
12716 rstate->lrd[j].orig_id = ins->id;
12721 } while(ins != first);
12722 rstate->ranges = i;
12724 /* Make a second pass to handle achitecture specific register
12729 int zlhs, zrhs, i, j;
12730 if (ins->id > rstate->defs) {
12731 internal_error(state, ins, "bad id");
12734 /* Walk through the template of ins and coalesce live ranges */
12735 zlhs = TRIPLE_LHS(ins->sizes);
12736 if ((zlhs == 0) && triple_is_def(state, ins)) {
12739 zrhs = TRIPLE_RHS(ins->sizes);
12741 #if DEBUG_COALESCING > 1
12742 fprintf(stderr, "mandatory coalesce: %p %d %d\n",
12745 for(i = 0; i < zlhs; i++) {
12746 struct reg_info linfo;
12747 struct live_range_def *lhs;
12748 linfo = arch_reg_lhs(state, ins, i);
12749 if (linfo.reg < MAX_REGISTERS) {
12752 if (triple_is_def(state, ins)) {
12753 lhs = &rstate->lrd[ins->id];
12755 lhs = &rstate->lrd[LHS(ins, i)->id];
12757 #if DEBUG_COALESCING > 1
12758 fprintf(stderr, "coalesce lhs(%d): %p %d\n",
12759 i, lhs, linfo.reg);
12762 for(j = 0; j < zrhs; j++) {
12763 struct reg_info rinfo;
12764 struct live_range_def *rhs;
12765 rinfo = arch_reg_rhs(state, ins, j);
12766 if (rinfo.reg < MAX_REGISTERS) {
12769 rhs = &rstate->lrd[RHS(ins, j)->id];
12770 #if DEBUG_COALESCING > 1
12771 fprintf(stderr, "coalesce rhs(%d): %p %d\n",
12772 j, rhs, rinfo.reg);
12775 if (rinfo.reg == linfo.reg) {
12776 coalesce_ranges(state, rstate,
12782 } while(ins != first);
12785 static void graph_ins(
12786 struct compile_state *state,
12787 struct reg_block *blocks, struct triple_reg_set *live,
12788 struct reg_block *rb, struct triple *ins, void *arg)
12790 struct reg_state *rstate = arg;
12791 struct live_range *def;
12792 struct triple_reg_set *entry;
12794 /* If the triple is not a definition
12795 * we do not have a definition to add to
12796 * the interference graph.
12798 if (!triple_is_def(state, ins)) {
12801 def = rstate->lrd[ins->id].lr;
12803 /* Create an edge between ins and everything that is
12804 * alive, unless the live_range cannot share
12805 * a physical register with ins.
12807 for(entry = live; entry; entry = entry->next) {
12808 struct live_range *lr;
12809 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12810 internal_error(state, 0, "bad entry?");
12812 lr = rstate->lrd[entry->member->id].lr;
12816 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12819 add_live_edge(rstate, def, lr);
12824 static struct live_range *get_verify_live_range(
12825 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12827 struct live_range *lr;
12828 struct live_range_def *lrd;
12830 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12831 internal_error(state, ins, "bad ins?");
12833 lr = rstate->lrd[ins->id].lr;
12837 if (lrd->def == ins) {
12841 } while(lrd != lr->defs);
12843 internal_error(state, ins, "ins not in live range");
12848 static void verify_graph_ins(
12849 struct compile_state *state,
12850 struct reg_block *blocks, struct triple_reg_set *live,
12851 struct reg_block *rb, struct triple *ins, void *arg)
12853 struct reg_state *rstate = arg;
12854 struct triple_reg_set *entry1, *entry2;
12857 /* Compare live against edges and make certain the code is working */
12858 for(entry1 = live; entry1; entry1 = entry1->next) {
12859 struct live_range *lr1;
12860 lr1 = get_verify_live_range(state, rstate, entry1->member);
12861 for(entry2 = live; entry2; entry2 = entry2->next) {
12862 struct live_range *lr2;
12863 struct live_range_edge *edge2;
12866 if (entry2 == entry1) {
12869 lr2 = get_verify_live_range(state, rstate, entry2->member);
12871 internal_error(state, entry2->member,
12872 "live range with 2 values simultaneously alive");
12874 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12877 if (!interfere(rstate, lr1, lr2)) {
12878 internal_error(state, entry2->member,
12879 "edges don't interfere?");
12884 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12886 if (edge2->node == lr1) {
12890 if (lr2_degree != lr2->degree) {
12891 internal_error(state, entry2->member,
12892 "computed degree: %d does not match reported degree: %d\n",
12893 lr2_degree, lr2->degree);
12896 internal_error(state, entry2->member, "missing edge");
12904 static void print_interference_ins(
12905 struct compile_state *state,
12906 struct reg_block *blocks, struct triple_reg_set *live,
12907 struct reg_block *rb, struct triple *ins, void *arg)
12909 struct reg_state *rstate = arg;
12910 struct live_range *lr;
12913 lr = rstate->lrd[ins->id].lr;
12915 ins->id = rstate->lrd[id].orig_id;
12916 SET_REG(ins->id, lr->color);
12917 display_triple(stdout, ins);
12921 struct live_range_def *lrd;
12925 printf(" %-10p", lrd->def);
12927 } while(lrd != lr->defs);
12931 struct triple_reg_set *entry;
12933 for(entry = live; entry; entry = entry->next) {
12934 printf(" %-10p", entry->member);
12939 struct live_range_edge *entry;
12941 for(entry = lr->edges; entry; entry = entry->next) {
12942 struct live_range_def *lrd;
12943 lrd = entry->node->defs;
12945 printf(" %-10p", lrd->def);
12947 } while(lrd != entry->node->defs);
12952 if (triple_is_branch(state, ins)) {
12958 static int coalesce_live_ranges(
12959 struct compile_state *state, struct reg_state *rstate)
12961 /* At the point where a value is moved from one
12962 * register to another that value requires two
12963 * registers, thus increasing register pressure.
12964 * Live range coaleescing reduces the register
12965 * pressure by keeping a value in one register
12968 * In the case of a phi function all paths leading
12969 * into it must be allocated to the same register
12970 * otherwise the phi function may not be removed.
12972 * Forcing a value to stay in a single register
12973 * for an extended period of time does have
12974 * limitations when applied to non homogenous
12977 * The two cases I have identified are:
12978 * 1) Two forced register assignments may
12980 * 2) Registers may go unused because they
12981 * are only good for storing the value
12982 * and not manipulating it.
12984 * Because of this I need to split live ranges,
12985 * even outside of the context of coalesced live
12986 * ranges. The need to split live ranges does
12987 * impose some constraints on live range coalescing.
12989 * - Live ranges may not be coalesced across phi
12990 * functions. This creates a 2 headed live
12991 * range that cannot be sanely split.
12993 * - phi functions (coalesced in initialize_live_ranges)
12994 * are handled as pre split live ranges so we will
12995 * never attempt to split them.
13001 for(i = 0; i <= rstate->ranges; i++) {
13002 struct live_range *lr1;
13003 struct live_range_def *lrd1;
13004 lr1 = &rstate->lr[i];
13008 lrd1 = live_range_end(state, lr1, 0);
13009 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
13010 struct triple_set *set;
13011 if (lrd1->def->op != OP_COPY) {
13014 /* Skip copies that are the result of a live range split. */
13015 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
13018 for(set = lrd1->def->use; set; set = set->next) {
13019 struct live_range_def *lrd2;
13020 struct live_range *lr2, *res;
13022 lrd2 = &rstate->lrd[set->member->id];
13024 /* Don't coalesce with instructions
13025 * that are the result of a live range
13028 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
13031 lr2 = rstate->lrd[set->member->id].lr;
13035 if ((lr1->color != lr2->color) &&
13036 (lr1->color != REG_UNSET) &&
13037 (lr2->color != REG_UNSET)) {
13040 if ((lr1->classes & lr2->classes) == 0) {
13044 if (interfere(rstate, lr1, lr2)) {
13048 res = coalesce_ranges(state, rstate, lr1, lr2);
13062 static void fix_coalesce_conflicts(struct compile_state *state,
13063 struct reg_block *blocks, struct triple_reg_set *live,
13064 struct reg_block *rb, struct triple *ins, void *arg)
13066 int *conflicts = arg;
13067 int zlhs, zrhs, i, j;
13069 /* See if we have a mandatory coalesce operation between
13070 * a lhs and a rhs value. If so and the rhs value is also
13071 * alive then this triple needs to be pre copied. Otherwise
13072 * we would have two definitions in the same live range simultaneously
13075 zlhs = TRIPLE_LHS(ins->sizes);
13076 if ((zlhs == 0) && triple_is_def(state, ins)) {
13079 zrhs = TRIPLE_RHS(ins->sizes);
13080 for(i = 0; i < zlhs; i++) {
13081 struct reg_info linfo;
13082 linfo = arch_reg_lhs(state, ins, i);
13083 if (linfo.reg < MAX_REGISTERS) {
13086 for(j = 0; j < zrhs; j++) {
13087 struct reg_info rinfo;
13088 struct triple *rhs;
13089 struct triple_reg_set *set;
13092 rinfo = arch_reg_rhs(state, ins, j);
13093 if (rinfo.reg != linfo.reg) {
13097 for(set = live; set && !found; set = set->next) {
13098 if (set->member == rhs) {
13103 struct triple *copy;
13104 copy = pre_copy(state, ins, j);
13105 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13113 static int correct_coalesce_conflicts(
13114 struct compile_state *state, struct reg_block *blocks)
13118 walk_variable_lifetimes(state, blocks, fix_coalesce_conflicts, &conflicts);
13122 static void replace_set_use(struct compile_state *state,
13123 struct triple_reg_set *head, struct triple *orig, struct triple *new)
13125 struct triple_reg_set *set;
13126 for(set = head; set; set = set->next) {
13127 if (set->member == orig) {
13133 static void replace_block_use(struct compile_state *state,
13134 struct reg_block *blocks, struct triple *orig, struct triple *new)
13137 #warning "WISHLIST visit just those blocks that need it *"
13138 for(i = 1; i <= state->last_vertex; i++) {
13139 struct reg_block *rb;
13141 replace_set_use(state, rb->in, orig, new);
13142 replace_set_use(state, rb->out, orig, new);
13146 static void color_instructions(struct compile_state *state)
13148 struct triple *ins, *first;
13149 first = RHS(state->main_function, 0);
13152 if (triple_is_def(state, ins)) {
13153 struct reg_info info;
13154 info = find_lhs_color(state, ins, 0);
13155 if (info.reg >= MAX_REGISTERS) {
13156 info.reg = REG_UNSET;
13158 SET_INFO(ins->id, info);
13161 } while(ins != first);
13164 static struct reg_info read_lhs_color(
13165 struct compile_state *state, struct triple *ins, int index)
13167 struct reg_info info;
13168 if ((index == 0) && triple_is_def(state, ins)) {
13169 info.reg = ID_REG(ins->id);
13170 info.regcm = ID_REGCM(ins->id);
13172 else if (index < TRIPLE_LHS(ins->sizes)) {
13173 info = read_lhs_color(state, LHS(ins, index), 0);
13176 internal_error(state, ins, "Bad lhs %d", index);
13177 info.reg = REG_UNSET;
13183 static struct triple *resolve_tangle(
13184 struct compile_state *state, struct triple *tangle)
13186 struct reg_info info, uinfo;
13187 struct triple_set *set, *next;
13188 struct triple *copy;
13190 #warning "WISHLIST recalculate all affected instructions colors"
13191 info = find_lhs_color(state, tangle, 0);
13192 for(set = tangle->use; set; set = next) {
13193 struct triple *user;
13196 user = set->member;
13197 zrhs = TRIPLE_RHS(user->sizes);
13198 for(i = 0; i < zrhs; i++) {
13199 if (RHS(user, i) != tangle) {
13202 uinfo = find_rhs_post_color(state, user, i);
13203 if (uinfo.reg == info.reg) {
13204 copy = pre_copy(state, user, i);
13205 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13206 SET_INFO(copy->id, uinfo);
13211 uinfo = find_lhs_pre_color(state, tangle, 0);
13212 if (uinfo.reg == info.reg) {
13213 struct reg_info linfo;
13214 copy = post_copy(state, tangle);
13215 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13216 linfo = find_lhs_color(state, copy, 0);
13217 SET_INFO(copy->id, linfo);
13219 info = find_lhs_color(state, tangle, 0);
13220 SET_INFO(tangle->id, info);
13226 static void fix_tangles(struct compile_state *state,
13227 struct reg_block *blocks, struct triple_reg_set *live,
13228 struct reg_block *rb, struct triple *ins, void *arg)
13230 int *tangles = arg;
13231 struct triple *tangle;
13233 char used[MAX_REGISTERS];
13234 struct triple_reg_set *set;
13237 /* Find out which registers have multiple uses at this point */
13238 memset(used, 0, sizeof(used));
13239 for(set = live; set; set = set->next) {
13240 struct reg_info info;
13241 info = read_lhs_color(state, set->member, 0);
13242 if (info.reg == REG_UNSET) {
13245 reg_inc_used(state, used, info.reg);
13248 /* Now find the least dominated definition of a register in
13249 * conflict I have seen so far.
13251 for(set = live; set; set = set->next) {
13252 struct reg_info info;
13253 info = read_lhs_color(state, set->member, 0);
13254 if (used[info.reg] < 2) {
13257 /* Changing copies that feed into phi functions
13260 if (set->member->use &&
13261 (set->member->use->member->op == OP_PHI)) {
13264 if (!tangle || tdominates(state, set->member, tangle)) {
13265 tangle = set->member;
13268 /* If I have found a tangle resolve it */
13270 struct triple *post_copy;
13272 post_copy = resolve_tangle(state, tangle);
13274 replace_block_use(state, blocks, tangle, post_copy);
13276 if (post_copy && (tangle != ins)) {
13277 replace_set_use(state, live, tangle, post_copy);
13284 static int correct_tangles(
13285 struct compile_state *state, struct reg_block *blocks)
13289 color_instructions(state);
13290 walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
13295 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
13296 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
13298 struct triple *find_constrained_def(
13299 struct compile_state *state, struct live_range *range, struct triple *constrained)
13301 struct live_range_def *lrd;
13304 struct reg_info info;
13306 int is_constrained;
13307 regcm = arch_type_to_regcm(state, lrd->def->type);
13308 info = find_lhs_color(state, lrd->def, 0);
13309 regcm = arch_regcm_reg_normalize(state, regcm);
13310 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
13311 /* If the 2 register class masks are not equal the
13312 * the current register class is constrained.
13314 is_constrained = regcm != info.regcm;
13316 /* Of the constrained live ranges deal with the
13317 * least dominated one first.
13319 if (is_constrained) {
13320 #if DEBUG_RANGE_CONFLICTS
13321 fprintf(stderr, "canidate: %p %-8s regcm: %x %x\n",
13322 lrd->def, tops(lrd->def->op), regcm, info.regcm);
13324 if (!constrained ||
13325 tdominates(state, lrd->def, constrained))
13327 constrained = lrd->def;
13331 } while(lrd != range->defs);
13332 return constrained;
13335 static int split_constrained_ranges(
13336 struct compile_state *state, struct reg_state *rstate,
13337 struct live_range *range)
13339 /* Walk through the edges in conflict and our current live
13340 * range, and find definitions that are more severly constrained
13341 * than they type of data they contain require.
13343 * Then pick one of those ranges and relax the constraints.
13345 struct live_range_edge *edge;
13346 struct triple *constrained;
13349 for(edge = range->edges; edge; edge = edge->next) {
13350 constrained = find_constrained_def(state, edge->node, constrained);
13352 if (!constrained) {
13353 constrained = find_constrained_def(state, range, constrained);
13355 #if DEBUG_RANGE_CONFLICTS
13356 fprintf(stderr, "constrained: %p %-8s\n",
13357 constrained, tops(constrained->op));
13360 ids_from_rstate(state, rstate);
13361 cleanup_rstate(state, rstate);
13362 resolve_tangle(state, constrained);
13364 return !!constrained;
13367 static int split_ranges(
13368 struct compile_state *state, struct reg_state *rstate,
13369 char *used, struct live_range *range)
13372 #if DEBUG_RANGE_CONFLICTS
13373 fprintf(stderr, "split_ranges %d %s %p\n",
13374 rstate->passes, tops(range->defs->def->op), range->defs->def);
13376 if ((range->color == REG_UNNEEDED) ||
13377 (rstate->passes >= rstate->max_passes)) {
13380 split = split_constrained_ranges(state, rstate, range);
13382 /* Ideally I would split the live range that will not be used
13383 * for the longest period of time in hopes that this will
13384 * (a) allow me to spill a register or
13385 * (b) allow me to place a value in another register.
13387 * So far I don't have a test case for this, the resolving
13388 * of mandatory constraints has solved all of my
13389 * know issues. So I have choosen not to write any
13390 * code until I cat get a better feel for cases where
13391 * it would be useful to have.
13394 #warning "WISHLIST implement live range splitting..."
13395 if ((DEBUG_RANGE_CONFLICTS > 1) &&
13396 (!split || (DEBUG_RANGE_CONFLICTS > 2))) {
13397 print_interference_blocks(state, rstate, stderr, 0);
13398 print_dominators(state, stderr);
13403 #if DEBUG_COLOR_GRAPH > 1
13404 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13405 #define cgdebug_flush() fflush(stdout)
13406 #define cgdebug_loc(STATE, TRIPLE) loc(stdout, STATE, TRIPLE)
13407 #elif DEBUG_COLOR_GRAPH == 1
13408 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13409 #define cgdebug_flush() fflush(stderr)
13410 #define cgdebug_loc(STATE, TRIPLE) loc(stderr, STATE, TRIPLE)
13412 #define cgdebug_printf(...)
13413 #define cgdebug_flush()
13414 #define cgdebug_loc(STATE, TRIPLE)
13418 static int select_free_color(struct compile_state *state,
13419 struct reg_state *rstate, struct live_range *range)
13421 struct triple_set *entry;
13422 struct live_range_def *lrd;
13423 struct live_range_def *phi;
13424 struct live_range_edge *edge;
13425 char used[MAX_REGISTERS];
13426 struct triple **expr;
13428 /* Instead of doing just the trivial color select here I try
13429 * a few extra things because a good color selection will help reduce
13433 /* Find the registers currently in use */
13434 memset(used, 0, sizeof(used));
13435 for(edge = range->edges; edge; edge = edge->next) {
13436 if (edge->node->color == REG_UNSET) {
13439 reg_fill_used(state, used, edge->node->color);
13441 #if DEBUG_COLOR_GRAPH > 1
13445 for(edge = range->edges; edge; edge = edge->next) {
13448 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
13449 tops(range->def->op), i,
13450 range->def->filename, range->def->line, range->def->col);
13451 for(i = 0; i < MAX_REGISTERS; i++) {
13453 cgdebug_printf("used: %s\n",
13460 /* If a color is already assigned see if it will work */
13461 if (range->color != REG_UNSET) {
13462 struct live_range_def *lrd;
13463 if (!used[range->color]) {
13466 for(edge = range->edges; edge; edge = edge->next) {
13467 if (edge->node->color != range->color) {
13470 warning(state, edge->node->defs->def, "edge: ");
13471 lrd = edge->node->defs;
13473 warning(state, lrd->def, " %p %s",
13474 lrd->def, tops(lrd->def->op));
13476 } while(lrd != edge->node->defs);
13479 warning(state, range->defs->def, "def: ");
13481 warning(state, lrd->def, " %p %s",
13482 lrd->def, tops(lrd->def->op));
13484 } while(lrd != range->defs);
13485 internal_error(state, range->defs->def,
13486 "live range with already used color %s",
13487 arch_reg_str(range->color));
13490 /* If I feed into an expression reuse it's color.
13491 * This should help remove copies in the case of 2 register instructions
13492 * and phi functions.
13495 lrd = live_range_end(state, range, 0);
13496 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13497 entry = lrd->def->use;
13498 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13499 struct live_range_def *insd;
13501 insd = &rstate->lrd[entry->member->id];
13502 if (insd->lr->defs == 0) {
13505 if (!phi && (insd->def->op == OP_PHI) &&
13506 !interfere(rstate, range, insd->lr)) {
13509 if (insd->lr->color == REG_UNSET) {
13512 regcm = insd->lr->classes;
13513 if (((regcm & range->classes) == 0) ||
13514 (used[insd->lr->color])) {
13517 if (interfere(rstate, range, insd->lr)) {
13520 range->color = insd->lr->color;
13523 /* If I feed into a phi function reuse it's color or the color
13524 * of something else that feeds into the phi function.
13527 if (phi->lr->color != REG_UNSET) {
13528 if (used[phi->lr->color]) {
13529 range->color = phi->lr->color;
13533 expr = triple_rhs(state, phi->def, 0);
13534 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13535 struct live_range *lr;
13540 lr = rstate->lrd[(*expr)->id].lr;
13541 if (lr->color == REG_UNSET) {
13544 regcm = lr->classes;
13545 if (((regcm & range->classes) == 0) ||
13546 (used[lr->color])) {
13549 if (interfere(rstate, range, lr)) {
13552 range->color = lr->color;
13556 /* If I don't interfere with a rhs node reuse it's color */
13557 lrd = live_range_head(state, range, 0);
13558 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13559 expr = triple_rhs(state, lrd->def, 0);
13560 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13561 struct live_range *lr;
13566 lr = rstate->lrd[(*expr)->id].lr;
13567 if (lr->color == REG_UNSET) {
13570 regcm = lr->classes;
13571 if (((regcm & range->classes) == 0) ||
13572 (used[lr->color])) {
13575 if (interfere(rstate, range, lr)) {
13578 range->color = lr->color;
13582 /* If I have not opportunitically picked a useful color
13583 * pick the first color that is free.
13585 if (range->color == REG_UNSET) {
13587 arch_select_free_register(state, used, range->classes);
13589 if (range->color == REG_UNSET) {
13590 struct live_range_def *lrd;
13592 if (split_ranges(state, rstate, used, range)) {
13595 for(edge = range->edges; edge; edge = edge->next) {
13596 warning(state, edge->node->defs->def, "edge reg %s",
13597 arch_reg_str(edge->node->color));
13598 lrd = edge->node->defs;
13600 warning(state, lrd->def, " %s %p",
13601 tops(lrd->def->op), lrd->def);
13603 } while(lrd != edge->node->defs);
13605 warning(state, range->defs->def, "range: ");
13608 warning(state, lrd->def, " %s %p",
13609 tops(lrd->def->op), lrd->def);
13611 } while(lrd != range->defs);
13613 warning(state, range->defs->def, "classes: %x",
13615 for(i = 0; i < MAX_REGISTERS; i++) {
13617 warning(state, range->defs->def, "used: %s",
13621 #if DEBUG_COLOR_GRAPH < 2
13622 error(state, range->defs->def, "too few registers");
13624 internal_error(state, range->defs->def, "too few registers");
13627 range->classes &= arch_reg_regcm(state, range->color);
13628 if ((range->color == REG_UNSET) || (range->classes == 0)) {
13629 internal_error(state, range->defs->def, "select_free_color did not?");
13634 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13637 struct live_range_edge *edge;
13638 struct live_range *range;
13640 cgdebug_printf("Lo: ");
13641 range = rstate->low;
13642 if (*range->group_prev != range) {
13643 internal_error(state, 0, "lo: *prev != range?");
13645 *range->group_prev = range->group_next;
13646 if (range->group_next) {
13647 range->group_next->group_prev = range->group_prev;
13649 if (&range->group_next == rstate->low_tail) {
13650 rstate->low_tail = range->group_prev;
13652 if (rstate->low == range) {
13653 internal_error(state, 0, "low: next != prev?");
13656 else if (rstate->high) {
13657 cgdebug_printf("Hi: ");
13658 range = rstate->high;
13659 if (*range->group_prev != range) {
13660 internal_error(state, 0, "hi: *prev != range?");
13662 *range->group_prev = range->group_next;
13663 if (range->group_next) {
13664 range->group_next->group_prev = range->group_prev;
13666 if (&range->group_next == rstate->high_tail) {
13667 rstate->high_tail = range->group_prev;
13669 if (rstate->high == range) {
13670 internal_error(state, 0, "high: next != prev?");
13676 cgdebug_printf(" %d\n", range - rstate->lr);
13677 range->group_prev = 0;
13678 for(edge = range->edges; edge; edge = edge->next) {
13679 struct live_range *node;
13681 /* Move nodes from the high to the low list */
13682 if (node->group_prev && (node->color == REG_UNSET) &&
13683 (node->degree == regc_max_size(state, node->classes))) {
13684 if (*node->group_prev != node) {
13685 internal_error(state, 0, "move: *prev != node?");
13687 *node->group_prev = node->group_next;
13688 if (node->group_next) {
13689 node->group_next->group_prev = node->group_prev;
13691 if (&node->group_next == rstate->high_tail) {
13692 rstate->high_tail = node->group_prev;
13694 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13695 node->group_prev = rstate->low_tail;
13696 node->group_next = 0;
13697 *rstate->low_tail = node;
13698 rstate->low_tail = &node->group_next;
13699 if (*node->group_prev != node) {
13700 internal_error(state, 0, "move2: *prev != node?");
13705 colored = color_graph(state, rstate);
13707 cgdebug_printf("Coloring %d @", range - rstate->lr);
13708 cgdebug_loc(state, range->defs->def);
13710 colored = select_free_color(state, rstate, range);
13711 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13716 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13718 struct live_range *lr;
13719 struct live_range_edge *edge;
13720 struct triple *ins, *first;
13721 char used[MAX_REGISTERS];
13722 first = RHS(state->main_function, 0);
13725 if (triple_is_def(state, ins)) {
13726 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13727 internal_error(state, ins,
13728 "triple without a live range def");
13730 lr = rstate->lrd[ins->id].lr;
13731 if (lr->color == REG_UNSET) {
13732 internal_error(state, ins,
13733 "triple without a color");
13735 /* Find the registers used by the edges */
13736 memset(used, 0, sizeof(used));
13737 for(edge = lr->edges; edge; edge = edge->next) {
13738 if (edge->node->color == REG_UNSET) {
13739 internal_error(state, 0,
13740 "live range without a color");
13742 reg_fill_used(state, used, edge->node->color);
13744 if (used[lr->color]) {
13745 internal_error(state, ins,
13746 "triple with already used color");
13750 } while(ins != first);
13753 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13755 struct live_range *lr;
13756 struct triple *first, *ins;
13757 first = RHS(state->main_function, 0);
13760 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13761 internal_error(state, ins,
13762 "triple without a live range");
13764 lr = rstate->lrd[ins->id].lr;
13765 SET_REG(ins->id, lr->color);
13767 } while (ins != first);
13770 static struct live_range *merge_sort_lr(
13771 struct live_range *first, struct live_range *last)
13773 struct live_range *mid, *join, **join_tail, *pick;
13775 size = (last - first) + 1;
13777 mid = first + size/2;
13778 first = merge_sort_lr(first, mid -1);
13779 mid = merge_sort_lr(mid, last);
13783 /* merge the two lists */
13784 while(first && mid) {
13785 if ((first->degree < mid->degree) ||
13786 ((first->degree == mid->degree) &&
13787 (first->length < mid->length))) {
13789 first = first->group_next;
13791 first->group_prev = 0;
13796 mid = mid->group_next;
13798 mid->group_prev = 0;
13801 pick->group_next = 0;
13802 pick->group_prev = join_tail;
13804 join_tail = &pick->group_next;
13806 /* Splice the remaining list */
13807 pick = (first)? first : mid;
13810 pick->group_prev = join_tail;
13814 if (!first->defs) {
13822 static void ids_from_rstate(struct compile_state *state,
13823 struct reg_state *rstate)
13825 struct triple *ins, *first;
13826 if (!rstate->defs) {
13829 /* Display the graph if desired */
13830 if (state->debug & DEBUG_INTERFERENCE) {
13831 print_blocks(state, stdout);
13832 print_control_flow(state);
13834 first = RHS(state->main_function, 0);
13838 struct live_range_def *lrd;
13839 lrd = &rstate->lrd[ins->id];
13840 ins->id = lrd->orig_id;
13843 } while(ins != first);
13846 static void cleanup_live_edges(struct reg_state *rstate)
13849 /* Free the edges on each node */
13850 for(i = 1; i <= rstate->ranges; i++) {
13851 remove_live_edges(rstate, &rstate->lr[i]);
13855 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13857 cleanup_live_edges(rstate);
13858 xfree(rstate->lrd);
13861 /* Free the variable lifetime information */
13862 if (rstate->blocks) {
13863 free_variable_lifetimes(state, rstate->blocks);
13866 rstate->ranges = 0;
13869 rstate->blocks = 0;
13872 static void verify_consistency(struct compile_state *state);
13873 static void allocate_registers(struct compile_state *state)
13875 struct reg_state rstate;
13878 /* Clear out the reg_state */
13879 memset(&rstate, 0, sizeof(rstate));
13880 rstate.max_passes = MAX_ALLOCATION_PASSES;
13883 struct live_range **point, **next;
13888 #if DEBUG_RANGE_CONFLICTS
13889 fprintf(stderr, "pass: %d\n", rstate.passes);
13893 ids_from_rstate(state, &rstate);
13895 /* Cleanup the temporary data structures */
13896 cleanup_rstate(state, &rstate);
13898 /* Compute the variable lifetimes */
13899 rstate.blocks = compute_variable_lifetimes(state);
13901 /* Fix invalid mandatory live range coalesce conflicts */
13902 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
13904 /* Fix two simultaneous uses of the same register.
13905 * In a few pathlogical cases a partial untangle moves
13906 * the tangle to a part of the graph we won't revisit.
13907 * So we keep looping until we have no more tangle fixes
13911 tangles = correct_tangles(state, rstate.blocks);
13914 if (state->debug & DEBUG_INSERTED_COPIES) {
13915 printf("After resolve_tangles\n");
13916 print_blocks(state, stdout);
13917 print_control_flow(state);
13919 verify_consistency(state);
13921 /* Allocate and initialize the live ranges */
13922 initialize_live_ranges(state, &rstate);
13924 /* Note current doing coalescing in a loop appears to
13925 * buys me nothing. The code is left this way in case
13926 * there is some value in it. Or if a future bugfix
13927 * yields some benefit.
13930 #if DEBUG_COALESCING
13931 fprintf(stderr, "coalescing\n");
13933 /* Remove any previous live edge calculations */
13934 cleanup_live_edges(&rstate);
13936 /* Compute the interference graph */
13937 walk_variable_lifetimes(
13938 state, rstate.blocks, graph_ins, &rstate);
13940 /* Display the interference graph if desired */
13941 if (state->debug & DEBUG_INTERFERENCE) {
13942 print_interference_blocks(state, &rstate, stdout, 1);
13943 printf("\nlive variables by instruction\n");
13944 walk_variable_lifetimes(
13945 state, rstate.blocks,
13946 print_interference_ins, &rstate);
13949 coalesced = coalesce_live_ranges(state, &rstate);
13951 #if DEBUG_COALESCING
13952 fprintf(stderr, "coalesced: %d\n", coalesced);
13954 } while(coalesced);
13956 #if DEBUG_CONSISTENCY > 1
13958 fprintf(stderr, "verify_graph_ins...\n");
13960 /* Verify the interference graph */
13961 walk_variable_lifetimes(
13962 state, rstate.blocks, verify_graph_ins, &rstate);
13964 fprintf(stderr, "verify_graph_ins done\n");
13968 /* Build the groups low and high. But with the nodes
13969 * first sorted by degree order.
13971 rstate.low_tail = &rstate.low;
13972 rstate.high_tail = &rstate.high;
13973 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13975 rstate.high->group_prev = &rstate.high;
13977 for(point = &rstate.high; *point; point = &(*point)->group_next)
13979 rstate.high_tail = point;
13980 /* Walk through the high list and move everything that needs
13983 for(point = &rstate.high; *point; point = next) {
13984 struct live_range *range;
13985 next = &(*point)->group_next;
13988 /* If it has a low degree or it already has a color
13989 * place the node in low.
13991 if ((range->degree < regc_max_size(state, range->classes)) ||
13992 (range->color != REG_UNSET)) {
13993 cgdebug_printf("Lo: %5d degree %5d%s\n",
13994 range - rstate.lr, range->degree,
13995 (range->color != REG_UNSET) ? " (colored)": "");
13996 *range->group_prev = range->group_next;
13997 if (range->group_next) {
13998 range->group_next->group_prev = range->group_prev;
14000 if (&range->group_next == rstate.high_tail) {
14001 rstate.high_tail = range->group_prev;
14003 range->group_prev = rstate.low_tail;
14004 range->group_next = 0;
14005 *rstate.low_tail = range;
14006 rstate.low_tail = &range->group_next;
14010 cgdebug_printf("hi: %5d degree %5d%s\n",
14011 range - rstate.lr, range->degree,
14012 (range->color != REG_UNSET) ? " (colored)": "");
14015 /* Color the live_ranges */
14016 colored = color_graph(state, &rstate);
14018 } while (!colored);
14020 /* Verify the graph was properly colored */
14021 verify_colors(state, &rstate);
14023 /* Move the colors from the graph to the triples */
14024 color_triples(state, &rstate);
14026 /* Cleanup the temporary data structures */
14027 cleanup_rstate(state, &rstate);
14030 /* Sparce Conditional Constant Propogation
14031 * =========================================
14035 struct lattice_node {
14037 struct triple *def;
14038 struct ssa_edge *out;
14039 struct flow_block *fblock;
14040 struct triple *val;
14041 /* lattice high val && !is_const(val)
14042 * lattice const is_const(val)
14043 * lattice low val == 0
14047 struct lattice_node *src;
14048 struct lattice_node *dst;
14049 struct ssa_edge *work_next;
14050 struct ssa_edge *work_prev;
14051 struct ssa_edge *out_next;
14054 struct flow_block *src;
14055 struct flow_block *dst;
14056 struct flow_edge *work_next;
14057 struct flow_edge *work_prev;
14058 struct flow_edge *in_next;
14059 struct flow_edge *out_next;
14062 struct flow_block {
14063 struct block *block;
14064 struct flow_edge *in;
14065 struct flow_edge *out;
14066 struct flow_edge left, right;
14071 struct lattice_node *lattice;
14072 struct ssa_edge *ssa_edges;
14073 struct flow_block *flow_blocks;
14074 struct flow_edge *flow_work_list;
14075 struct ssa_edge *ssa_work_list;
14079 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
14080 struct flow_edge *fedge)
14082 if (!scc->flow_work_list) {
14083 scc->flow_work_list = fedge;
14084 fedge->work_next = fedge->work_prev = fedge;
14087 struct flow_edge *ftail;
14088 ftail = scc->flow_work_list->work_prev;
14089 fedge->work_next = ftail->work_next;
14090 fedge->work_prev = ftail;
14091 fedge->work_next->work_prev = fedge;
14092 fedge->work_prev->work_next = fedge;
14096 static struct flow_edge *scc_next_fedge(
14097 struct compile_state *state, struct scc_state *scc)
14099 struct flow_edge *fedge;
14100 fedge = scc->flow_work_list;
14102 fedge->work_next->work_prev = fedge->work_prev;
14103 fedge->work_prev->work_next = fedge->work_next;
14104 if (fedge->work_next != fedge) {
14105 scc->flow_work_list = fedge->work_next;
14107 scc->flow_work_list = 0;
14113 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
14114 struct ssa_edge *sedge)
14116 if (!scc->ssa_work_list) {
14117 scc->ssa_work_list = sedge;
14118 sedge->work_next = sedge->work_prev = sedge;
14121 struct ssa_edge *stail;
14122 stail = scc->ssa_work_list->work_prev;
14123 sedge->work_next = stail->work_next;
14124 sedge->work_prev = stail;
14125 sedge->work_next->work_prev = sedge;
14126 sedge->work_prev->work_next = sedge;
14130 static struct ssa_edge *scc_next_sedge(
14131 struct compile_state *state, struct scc_state *scc)
14133 struct ssa_edge *sedge;
14134 sedge = scc->ssa_work_list;
14136 sedge->work_next->work_prev = sedge->work_prev;
14137 sedge->work_prev->work_next = sedge->work_next;
14138 if (sedge->work_next != sedge) {
14139 scc->ssa_work_list = sedge->work_next;
14141 scc->ssa_work_list = 0;
14147 static void initialize_scc_state(
14148 struct compile_state *state, struct scc_state *scc)
14150 int ins_count, ssa_edge_count;
14151 int ins_index, ssa_edge_index, fblock_index;
14152 struct triple *first, *ins;
14153 struct block *block;
14154 struct flow_block *fblock;
14156 memset(scc, 0, sizeof(*scc));
14158 /* Inialize pass zero find out how much memory we need */
14159 first = RHS(state->main_function, 0);
14161 ins_count = ssa_edge_count = 0;
14163 struct triple_set *edge;
14165 for(edge = ins->use; edge; edge = edge->next) {
14169 } while(ins != first);
14171 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
14172 ins_count, ssa_edge_count, state->last_vertex);
14174 scc->ins_count = ins_count;
14176 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
14178 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
14180 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
14183 /* Initialize pass one collect up the nodes */
14186 ins_index = ssa_edge_index = fblock_index = 0;
14189 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14190 block = ins->u.block;
14192 internal_error(state, ins, "label without block");
14195 block->vertex = fblock_index;
14196 fblock = &scc->flow_blocks[fblock_index];
14197 fblock->block = block;
14200 struct lattice_node *lnode;
14202 lnode = &scc->lattice[ins_index];
14205 lnode->fblock = fblock;
14206 lnode->val = ins; /* LATTICE HIGH */
14207 lnode->old_id = ins->id;
14208 ins->id = ins_index;
14211 } while(ins != first);
14212 /* Initialize pass two collect up the edges */
14217 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14218 struct flow_edge *fedge, **ftail;
14219 struct block_set *bedge;
14220 block = ins->u.block;
14221 fblock = &scc->flow_blocks[block->vertex];
14224 ftail = &fblock->out;
14226 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
14227 if (fblock->left.dst->block != block->left) {
14228 internal_error(state, 0, "block mismatch");
14230 fblock->left.out_next = 0;
14231 *ftail = &fblock->left;
14232 ftail = &fblock->left.out_next;
14234 if (block->right) {
14235 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
14236 if (fblock->right.dst->block != block->right) {
14237 internal_error(state, 0, "block mismatch");
14239 fblock->right.out_next = 0;
14240 *ftail = &fblock->right;
14241 ftail = &fblock->right.out_next;
14243 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
14244 fedge->src = fblock;
14245 fedge->work_next = fedge->work_prev = fedge;
14246 fedge->executable = 0;
14248 ftail = &fblock->in;
14249 for(bedge = block->use; bedge; bedge = bedge->next) {
14250 struct block *src_block;
14251 struct flow_block *sfblock;
14252 struct flow_edge *sfedge;
14253 src_block = bedge->member;
14254 sfblock = &scc->flow_blocks[src_block->vertex];
14256 if (src_block->left == block) {
14257 sfedge = &sfblock->left;
14259 sfedge = &sfblock->right;
14262 ftail = &sfedge->in_next;
14263 sfedge->in_next = 0;
14267 struct triple_set *edge;
14268 struct ssa_edge **stail;
14269 struct lattice_node *lnode;
14270 lnode = &scc->lattice[ins->id];
14272 stail = &lnode->out;
14273 for(edge = ins->use; edge; edge = edge->next) {
14274 struct ssa_edge *sedge;
14275 ssa_edge_index += 1;
14276 sedge = &scc->ssa_edges[ssa_edge_index];
14278 stail = &sedge->out_next;
14279 sedge->src = lnode;
14280 sedge->dst = &scc->lattice[edge->member->id];
14281 sedge->work_next = sedge->work_prev = sedge;
14282 sedge->out_next = 0;
14286 } while(ins != first);
14287 /* Setup a dummy block 0 as a node above the start node */
14289 struct flow_block *fblock, *dst;
14290 struct flow_edge *fedge;
14291 fblock = &scc->flow_blocks[0];
14294 fblock->out = &fblock->left;
14295 dst = &scc->flow_blocks[state->first_block->vertex];
14296 fedge = &fblock->left;
14297 fedge->src = fblock;
14299 fedge->work_next = fedge;
14300 fedge->work_prev = fedge;
14301 fedge->in_next = fedge->dst->in;
14302 fedge->out_next = 0;
14303 fedge->executable = 0;
14304 fedge->dst->in = fedge;
14306 /* Initialize the work lists */
14307 scc->flow_work_list = 0;
14308 scc->ssa_work_list = 0;
14309 scc_add_fedge(state, scc, fedge);
14312 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14313 ins_index, ssa_edge_index, fblock_index);
14318 static void free_scc_state(
14319 struct compile_state *state, struct scc_state *scc)
14321 xfree(scc->flow_blocks);
14322 xfree(scc->ssa_edges);
14323 xfree(scc->lattice);
14327 static struct lattice_node *triple_to_lattice(
14328 struct compile_state *state, struct scc_state *scc, struct triple *ins)
14330 if (ins->id <= 0) {
14331 internal_error(state, ins, "bad id");
14333 return &scc->lattice[ins->id];
14336 static struct triple *preserve_lval(
14337 struct compile_state *state, struct lattice_node *lnode)
14339 struct triple *old;
14340 /* Preserve the original value */
14342 old = dup_triple(state, lnode->val);
14343 if (lnode->val != lnode->def) {
14353 static int lval_changed(struct compile_state *state,
14354 struct triple *old, struct lattice_node *lnode)
14357 /* See if the lattice value has changed */
14359 if (!old && !lnode->val) {
14362 if (changed && lnode->val && !is_const(lnode->val)) {
14366 lnode->val && old &&
14367 (memcmp(lnode->val->param, old->param,
14368 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14369 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14379 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
14380 struct lattice_node *lnode)
14382 struct lattice_node *tmp;
14383 struct triple **slot, *old;
14384 struct flow_edge *fedge;
14386 if (lnode->def->op != OP_PHI) {
14387 internal_error(state, lnode->def, "not phi");
14389 /* Store the original value */
14390 old = preserve_lval(state, lnode);
14392 /* default to lattice high */
14393 lnode->val = lnode->def;
14394 slot = &RHS(lnode->def, 0);
14396 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14397 if (!fedge->executable) {
14400 if (!slot[index]) {
14401 internal_error(state, lnode->def, "no phi value");
14403 tmp = triple_to_lattice(state, scc, slot[index]);
14404 /* meet(X, lattice low) = lattice low */
14408 /* meet(X, lattice high) = X */
14409 else if (!tmp->val) {
14410 lnode->val = lnode->val;
14412 /* meet(lattice high, X) = X */
14413 else if (!is_const(lnode->val)) {
14414 lnode->val = dup_triple(state, tmp->val);
14415 lnode->val->type = lnode->def->type;
14417 /* meet(const, const) = const or lattice low */
14418 else if (!constants_equal(state, lnode->val, tmp->val)) {
14426 fprintf(stderr, "phi: %d -> %s\n",
14428 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14430 /* If the lattice value has changed update the work lists. */
14431 if (lval_changed(state, old, lnode)) {
14432 struct ssa_edge *sedge;
14433 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14434 scc_add_sedge(state, scc, sedge);
14439 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14440 struct lattice_node *lnode)
14443 struct triple *old, *scratch;
14444 struct triple **dexpr, **vexpr;
14447 /* Store the original value */
14448 old = preserve_lval(state, lnode);
14450 /* Reinitialize the value */
14451 lnode->val = scratch = dup_triple(state, lnode->def);
14452 scratch->id = lnode->old_id;
14453 scratch->next = scratch;
14454 scratch->prev = scratch;
14457 count = TRIPLE_SIZE(scratch->sizes);
14458 for(i = 0; i < count; i++) {
14459 dexpr = &lnode->def->param[i];
14460 vexpr = &scratch->param[i];
14462 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14463 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14465 struct lattice_node *tmp;
14466 tmp = triple_to_lattice(state, scc, *dexpr);
14467 *vexpr = (tmp->val)? tmp->val : tmp->def;
14470 if (scratch->op == OP_BRANCH) {
14471 scratch->next = lnode->def->next;
14473 /* Recompute the value */
14474 #warning "FIXME see if simplify does anything bad"
14475 /* So far it looks like only the strength reduction
14476 * optimization are things I need to worry about.
14478 simplify(state, scratch);
14479 /* Cleanup my value */
14480 if (scratch->use) {
14481 internal_error(state, lnode->def, "scratch used?");
14483 if ((scratch->prev != scratch) ||
14484 ((scratch->next != scratch) &&
14485 ((lnode->def->op != OP_BRANCH) ||
14486 (scratch->next != lnode->def->next)))) {
14487 internal_error(state, lnode->def, "scratch in list?");
14489 /* undo any uses... */
14490 count = TRIPLE_SIZE(scratch->sizes);
14491 for(i = 0; i < count; i++) {
14492 vexpr = &scratch->param[i];
14494 unuse_triple(*vexpr, scratch);
14497 if (!is_const(scratch)) {
14498 for(i = 0; i < count; i++) {
14499 dexpr = &lnode->def->param[i];
14500 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14501 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14503 struct lattice_node *tmp;
14504 tmp = triple_to_lattice(state, scc, *dexpr);
14512 (lnode->val->op == lnode->def->op) &&
14513 (memcmp(lnode->val->param, lnode->def->param,
14514 count * sizeof(lnode->val->param[0])) == 0) &&
14515 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14516 lnode->val = lnode->def;
14518 /* Find the cases that are always lattice lo */
14520 triple_is_def(state, lnode->val) &&
14521 !triple_is_pure(state, lnode->val)) {
14525 (lnode->val->op == OP_SDECL) &&
14526 (lnode->val != lnode->def)) {
14527 internal_error(state, lnode->def, "bad sdecl");
14529 /* See if the lattice value has changed */
14530 changed = lval_changed(state, old, lnode);
14531 if (lnode->val != scratch) {
14537 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14538 struct lattice_node *lnode)
14540 struct lattice_node *cond;
14543 struct flow_edge *fedge;
14544 fprintf(stderr, "branch: %d (",
14547 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14548 fprintf(stderr, " %d", fedge->dst->block->vertex);
14550 fprintf(stderr, " )");
14551 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14552 fprintf(stderr, " <- %d",
14553 RHS(lnode->def, 0)->id);
14555 fprintf(stderr, "\n");
14558 if (lnode->def->op != OP_BRANCH) {
14559 internal_error(state, lnode->def, "not branch");
14561 /* This only applies to conditional branches */
14562 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14565 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14566 if (cond->val && !is_const(cond->val)) {
14567 #warning "FIXME do I need to do something here?"
14568 warning(state, cond->def, "condition not constant?");
14571 if (cond->val == 0) {
14572 scc_add_fedge(state, scc, cond->fblock->out);
14573 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14575 else if (cond->val->u.cval) {
14576 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14579 scc_add_fedge(state, scc, cond->fblock->out);
14584 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14585 struct lattice_node *lnode)
14589 changed = compute_lnode_val(state, scc, lnode);
14592 struct triple **expr;
14593 fprintf(stderr, "expr: %3d %10s (",
14594 lnode->def->id, tops(lnode->def->op));
14595 expr = triple_rhs(state, lnode->def, 0);
14596 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14598 fprintf(stderr, " %d", (*expr)->id);
14601 fprintf(stderr, " ) -> %s\n",
14602 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14605 if (lnode->def->op == OP_BRANCH) {
14606 scc_visit_branch(state, scc, lnode);
14609 else if (changed) {
14610 struct ssa_edge *sedge;
14611 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14612 scc_add_sedge(state, scc, sedge);
14617 static void scc_writeback_values(
14618 struct compile_state *state, struct scc_state *scc)
14620 struct triple *first, *ins;
14621 first = RHS(state->main_function, 0);
14624 struct lattice_node *lnode;
14625 lnode = triple_to_lattice(state, scc, ins);
14627 ins->id = lnode->old_id;
14629 if (lnode->val && !is_const(lnode->val)) {
14630 warning(state, lnode->def,
14631 "lattice node still high?");
14634 if (lnode->val && (lnode->val != ins)) {
14635 /* See if it something I know how to write back */
14636 switch(lnode->val->op) {
14638 mkconst(state, ins, lnode->val->u.cval);
14641 mkaddr_const(state, ins,
14642 MISC(lnode->val, 0), lnode->val->u.cval);
14645 /* By default don't copy the changes,
14646 * recompute them in place instead.
14648 simplify(state, ins);
14651 if (is_const(lnode->val) &&
14652 !constants_equal(state, lnode->val, ins)) {
14653 internal_error(state, 0, "constants not equal");
14655 /* Free the lattice nodes */
14660 } while(ins != first);
14663 static void scc_transform(struct compile_state *state)
14665 struct scc_state scc;
14667 initialize_scc_state(state, &scc);
14669 while(scc.flow_work_list || scc.ssa_work_list) {
14670 struct flow_edge *fedge;
14671 struct ssa_edge *sedge;
14672 struct flow_edge *fptr;
14673 while((fedge = scc_next_fedge(state, &scc))) {
14674 struct block *block;
14675 struct triple *ptr;
14676 struct flow_block *fblock;
14679 if (fedge->executable) {
14683 internal_error(state, 0, "fedge without dst");
14686 internal_error(state, 0, "fedge without src");
14688 fedge->executable = 1;
14689 fblock = fedge->dst;
14690 block = fblock->block;
14692 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14693 if (fptr->executable) {
14698 fprintf(stderr, "vertex: %d time: %d\n",
14699 block->vertex, time);
14703 for(ptr = block->first; !done; ptr = ptr->next) {
14704 struct lattice_node *lnode;
14705 done = (ptr == block->last);
14706 lnode = &scc.lattice[ptr->id];
14707 if (ptr->op == OP_PHI) {
14708 scc_visit_phi(state, &scc, lnode);
14710 else if (time == 1) {
14711 scc_visit_expr(state, &scc, lnode);
14714 if (fblock->out && !fblock->out->out_next) {
14715 scc_add_fedge(state, &scc, fblock->out);
14718 while((sedge = scc_next_sedge(state, &scc))) {
14719 struct lattice_node *lnode;
14720 struct flow_block *fblock;
14721 lnode = sedge->dst;
14722 fblock = lnode->fblock;
14724 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14725 sedge - scc.ssa_edges,
14726 sedge->src->def->id,
14727 sedge->dst->def->id);
14729 if (lnode->def->op == OP_PHI) {
14730 scc_visit_phi(state, &scc, lnode);
14733 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14734 if (fptr->executable) {
14739 scc_visit_expr(state, &scc, lnode);
14745 scc_writeback_values(state, &scc);
14746 free_scc_state(state, &scc);
14750 static void transform_to_arch_instructions(struct compile_state *state)
14752 struct triple *ins, *first;
14753 first = RHS(state->main_function, 0);
14756 ins = transform_to_arch_instruction(state, ins);
14757 } while(ins != first);
14760 #if DEBUG_CONSISTENCY
14761 static void verify_uses(struct compile_state *state)
14763 struct triple *first, *ins;
14764 struct triple_set *set;
14765 first = RHS(state->main_function, 0);
14768 struct triple **expr;
14769 expr = triple_rhs(state, ins, 0);
14770 for(; expr; expr = triple_rhs(state, ins, expr)) {
14771 struct triple *rhs;
14773 for(set = rhs?rhs->use:0; set; set = set->next) {
14774 if (set->member == ins) {
14779 internal_error(state, ins, "rhs not used");
14782 expr = triple_lhs(state, ins, 0);
14783 for(; expr; expr = triple_lhs(state, ins, expr)) {
14784 struct triple *lhs;
14786 for(set = lhs?lhs->use:0; set; set = set->next) {
14787 if (set->member == ins) {
14792 internal_error(state, ins, "lhs not used");
14796 } while(ins != first);
14799 static void verify_blocks_present(struct compile_state *state)
14801 struct triple *first, *ins;
14802 if (!state->first_block) {
14805 first = RHS(state->main_function, 0);
14808 valid_ins(state, ins);
14809 if (triple_stores_block(state, ins)) {
14810 if (!ins->u.block) {
14811 internal_error(state, ins,
14812 "%p not in a block?\n", ins);
14816 } while(ins != first);
14820 static void verify_blocks(struct compile_state *state)
14822 struct triple *ins;
14823 struct block *block;
14825 block = state->first_block;
14832 struct block_set *user;
14834 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14835 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
14836 internal_error(state, ins, "inconsitent block specified");
14838 valid_ins(state, ins);
14841 for(user = block->use; user; user = user->next) {
14843 if ((block == state->last_block) &&
14844 (user->member == state->first_block)) {
14847 if ((user->member->left != block) &&
14848 (user->member->right != block)) {
14849 internal_error(state, user->member->first,
14850 "user does not use block");
14853 if (triple_is_branch(state, block->last) &&
14854 (block->right != block_of_triple(state, TARG(block->last, 0))))
14856 internal_error(state, block->last, "block->right != TARG(0)");
14858 if (!triple_is_uncond_branch(state, block->last) &&
14859 (block != state->last_block) &&
14860 (block->left != block_of_triple(state, block->last->next)))
14862 internal_error(state, block->last, "block->left != block->last->next");
14865 for(user = block->left->use; user; user = user->next) {
14866 if (user->member == block) {
14870 if (!user || user->member != block) {
14871 internal_error(state, block->first,
14872 "block does not use left");
14875 if (block->right) {
14876 for(user = block->right->use; user; user = user->next) {
14877 if (user->member == block) {
14881 if (!user || user->member != block) {
14882 internal_error(state, block->first,
14883 "block does not use right");
14886 if (block->users != users) {
14887 internal_error(state, block->first,
14888 "computed users %d != stored users %d\n",
14889 users, block->users);
14891 if (!triple_stores_block(state, block->last->next)) {
14892 internal_error(state, block->last->next,
14893 "cannot find next block");
14895 block = block->last->next->u.block;
14897 internal_error(state, block->last->next,
14900 } while(block != state->first_block);
14901 if (blocks != state->last_vertex) {
14902 internal_error(state, 0, "computed blocks != stored blocks %d\n",
14903 blocks, state->last_vertex);
14907 static void verify_domination(struct compile_state *state)
14909 struct triple *first, *ins;
14910 struct triple_set *set;
14911 if (!state->first_block) {
14915 first = RHS(state->main_function, 0);
14918 for(set = ins->use; set; set = set->next) {
14919 struct triple **slot;
14920 struct triple *use_point;
14923 zrhs = TRIPLE_RHS(ins->sizes);
14924 slot = &RHS(set->member, 0);
14925 /* See if the use is on the right hand side */
14926 for(i = 0; i < zrhs; i++) {
14927 if (slot[i] == ins) {
14932 use_point = set->member;
14933 if (set->member->op == OP_PHI) {
14934 struct block_set *bset;
14936 bset = set->member->u.block->use;
14937 for(edge = 0; bset && (edge < i); edge++) {
14941 internal_error(state, set->member,
14942 "no edge for phi rhs %d\n", i);
14944 use_point = bset->member->last;
14948 !tdominates(state, ins, use_point)) {
14949 internal_warning(state, ins,
14950 "ins does not dominate rhs use");
14951 internal_error(state, use_point,
14952 "non dominated rhs use point?");
14956 } while(ins != first);
14959 static void verify_piece(struct compile_state *state)
14961 struct triple *first, *ins;
14962 first = RHS(state->main_function, 0);
14965 struct triple *ptr;
14967 lhs = TRIPLE_LHS(ins->sizes);
14968 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14969 if (ptr != LHS(ins, i)) {
14970 internal_error(state, ins, "malformed lhs on %s",
14973 if (ptr->op != OP_PIECE) {
14974 internal_error(state, ins, "bad lhs op %s at %d on %s",
14975 tops(ptr->op), i, tops(ins->op));
14977 if (ptr->u.cval != i) {
14978 internal_error(state, ins, "bad u.cval of %d %d expected",
14983 } while(ins != first);
14985 static void verify_ins_colors(struct compile_state *state)
14987 struct triple *first, *ins;
14989 first = RHS(state->main_function, 0);
14993 } while(ins != first);
14995 static void verify_consistency(struct compile_state *state)
14997 verify_uses(state);
14998 verify_blocks_present(state);
14999 verify_blocks(state);
15000 verify_domination(state);
15001 verify_piece(state);
15002 verify_ins_colors(state);
15005 static void verify_consistency(struct compile_state *state) {}
15006 #endif /* DEBUG_USES */
15008 static void optimize(struct compile_state *state)
15010 if (state->debug & DEBUG_TRIPLES) {
15011 print_triples(state);
15013 /* Replace structures with simpler data types */
15014 flatten_structures(state);
15015 if (state->debug & DEBUG_TRIPLES) {
15016 print_triples(state);
15018 verify_consistency(state);
15019 /* Analize the intermediate code */
15020 setup_basic_blocks(state);
15021 analyze_idominators(state);
15022 analyze_ipdominators(state);
15024 /* Transform the code to ssa form. */
15026 * The transformation to ssa form puts a phi function
15027 * on each of edge of a dominance frontier where that
15028 * phi function might be needed. At -O2 if we don't
15029 * eleminate the excess phi functions we can get an
15030 * exponential code size growth. So I kill the extra
15031 * phi functions early and I kill them often.
15033 transform_to_ssa_form(state);
15034 eliminate_inefectual_code(state);
15036 verify_consistency(state);
15037 if (state->debug & DEBUG_CODE_ELIMINATION) {
15038 fprintf(stdout, "After transform_to_ssa_form\n");
15039 print_blocks(state, stdout);
15041 /* Do strength reduction and simple constant optimizations */
15042 if (state->optimize >= 1) {
15043 simplify_all(state);
15044 transform_from_ssa_form(state);
15045 free_basic_blocks(state);
15046 setup_basic_blocks(state);
15047 analyze_idominators(state);
15048 analyze_ipdominators(state);
15049 transform_to_ssa_form(state);
15050 eliminate_inefectual_code(state);
15052 if (state->debug & DEBUG_CODE_ELIMINATION) {
15053 fprintf(stdout, "After simplify_all\n");
15054 print_blocks(state, stdout);
15056 verify_consistency(state);
15057 /* Propogate constants throughout the code */
15058 if (state->optimize >= 2) {
15059 scc_transform(state);
15060 transform_from_ssa_form(state);
15061 free_basic_blocks(state);
15062 setup_basic_blocks(state);
15063 analyze_idominators(state);
15064 analyze_ipdominators(state);
15065 transform_to_ssa_form(state);
15066 eliminate_inefectual_code(state);
15068 verify_consistency(state);
15069 #warning "WISHLIST implement single use constants (least possible register pressure)"
15070 #warning "WISHLIST implement induction variable elimination"
15071 /* Select architecture instructions and an initial partial
15072 * coloring based on architecture constraints.
15074 transform_to_arch_instructions(state);
15075 verify_consistency(state);
15076 if (state->debug & DEBUG_ARCH_CODE) {
15077 printf("After transform_to_arch_instructions\n");
15078 print_blocks(state, stdout);
15079 print_control_flow(state);
15081 eliminate_inefectual_code(state);
15082 verify_consistency(state);
15083 if (state->debug & DEBUG_CODE_ELIMINATION) {
15084 printf("After eliminate_inefectual_code\n");
15085 print_blocks(state, stdout);
15086 print_control_flow(state);
15088 verify_consistency(state);
15089 /* Color all of the variables to see if they will fit in registers */
15090 insert_copies_to_phi(state);
15091 if (state->debug & DEBUG_INSERTED_COPIES) {
15092 printf("After insert_copies_to_phi\n");
15093 print_blocks(state, stdout);
15094 print_control_flow(state);
15096 verify_consistency(state);
15097 insert_mandatory_copies(state);
15098 if (state->debug & DEBUG_INSERTED_COPIES) {
15099 printf("After insert_mandatory_copies\n");
15100 print_blocks(state, stdout);
15101 print_control_flow(state);
15103 verify_consistency(state);
15104 allocate_registers(state);
15105 verify_consistency(state);
15106 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
15107 print_blocks(state, stdout);
15109 if (state->debug & DEBUG_CONTROL_FLOW) {
15110 print_control_flow(state);
15112 /* Remove the optimization information.
15113 * This is more to check for memory consistency than to free memory.
15115 free_basic_blocks(state);
15118 static void print_op_asm(struct compile_state *state,
15119 struct triple *ins, FILE *fp)
15121 struct asm_info *info;
15123 unsigned lhs, rhs, i;
15124 info = ins->u.ainfo;
15125 lhs = TRIPLE_LHS(ins->sizes);
15126 rhs = TRIPLE_RHS(ins->sizes);
15127 /* Don't count the clobbers in lhs */
15128 for(i = 0; i < lhs; i++) {
15129 if (LHS(ins, i)->type == &void_type) {
15134 fprintf(fp, "#ASM\n");
15136 for(ptr = info->str; *ptr; ptr++) {
15138 unsigned long param;
15139 struct triple *piece;
15149 param = strtoul(ptr, &next, 10);
15151 error(state, ins, "Invalid asm template");
15153 if (param >= (lhs + rhs)) {
15154 error(state, ins, "Invalid param %%%u in asm template",
15157 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
15159 arch_reg_str(ID_REG(piece->id)));
15162 fprintf(fp, "\n#NOT ASM\n");
15166 /* Only use the low x86 byte registers. This allows me
15167 * allocate the entire register when a byte register is used.
15169 #define X86_4_8BIT_GPRS 1
15171 /* Recognized x86 cpu variants */
15179 #define CPU_DEFAULT CPU_I386
15181 /* The x86 register classes */
15182 #define REGC_FLAGS 0
15183 #define REGC_GPR8 1
15184 #define REGC_GPR16 2
15185 #define REGC_GPR32 3
15186 #define REGC_DIVIDEND64 4
15187 #define REGC_DIVIDEND32 5
15190 #define REGC_GPR32_8 8
15191 #define REGC_GPR16_8 9
15192 #define REGC_GPR8_LO 10
15193 #define REGC_IMM32 11
15194 #define REGC_IMM16 12
15195 #define REGC_IMM8 13
15196 #define LAST_REGC REGC_IMM8
15197 #if LAST_REGC >= MAX_REGC
15198 #error "MAX_REGC is to low"
15201 /* Register class masks */
15202 #define REGCM_FLAGS (1 << REGC_FLAGS)
15203 #define REGCM_GPR8 (1 << REGC_GPR8)
15204 #define REGCM_GPR16 (1 << REGC_GPR16)
15205 #define REGCM_GPR32 (1 << REGC_GPR32)
15206 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
15207 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
15208 #define REGCM_MMX (1 << REGC_MMX)
15209 #define REGCM_XMM (1 << REGC_XMM)
15210 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
15211 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
15212 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
15213 #define REGCM_IMM32 (1 << REGC_IMM32)
15214 #define REGCM_IMM16 (1 << REGC_IMM16)
15215 #define REGCM_IMM8 (1 << REGC_IMM8)
15216 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
15218 /* The x86 registers */
15219 #define REG_EFLAGS 2
15220 #define REGC_FLAGS_FIRST REG_EFLAGS
15221 #define REGC_FLAGS_LAST REG_EFLAGS
15230 #define REGC_GPR8_LO_FIRST REG_AL
15231 #define REGC_GPR8_LO_LAST REG_DL
15232 #define REGC_GPR8_FIRST REG_AL
15233 #define REGC_GPR8_LAST REG_DH
15242 #define REGC_GPR16_FIRST REG_AX
15243 #define REGC_GPR16_LAST REG_SP
15252 #define REGC_GPR32_FIRST REG_EAX
15253 #define REGC_GPR32_LAST REG_ESP
15254 #define REG_EDXEAX 27
15255 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
15256 #define REGC_DIVIDEND64_LAST REG_EDXEAX
15257 #define REG_DXAX 28
15258 #define REGC_DIVIDEND32_FIRST REG_DXAX
15259 #define REGC_DIVIDEND32_LAST REG_DXAX
15260 #define REG_MMX0 29
15261 #define REG_MMX1 30
15262 #define REG_MMX2 31
15263 #define REG_MMX3 32
15264 #define REG_MMX4 33
15265 #define REG_MMX5 34
15266 #define REG_MMX6 35
15267 #define REG_MMX7 36
15268 #define REGC_MMX_FIRST REG_MMX0
15269 #define REGC_MMX_LAST REG_MMX7
15270 #define REG_XMM0 37
15271 #define REG_XMM1 38
15272 #define REG_XMM2 39
15273 #define REG_XMM3 40
15274 #define REG_XMM4 41
15275 #define REG_XMM5 42
15276 #define REG_XMM6 43
15277 #define REG_XMM7 44
15278 #define REGC_XMM_FIRST REG_XMM0
15279 #define REGC_XMM_LAST REG_XMM7
15280 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
15281 #define LAST_REG REG_XMM7
15283 #define REGC_GPR32_8_FIRST REG_EAX
15284 #define REGC_GPR32_8_LAST REG_EDX
15285 #define REGC_GPR16_8_FIRST REG_AX
15286 #define REGC_GPR16_8_LAST REG_DX
15288 #define REGC_IMM8_FIRST -1
15289 #define REGC_IMM8_LAST -1
15290 #define REGC_IMM16_FIRST -2
15291 #define REGC_IMM16_LAST -1
15292 #define REGC_IMM32_FIRST -4
15293 #define REGC_IMM32_LAST -1
15295 #if LAST_REG >= MAX_REGISTERS
15296 #error "MAX_REGISTERS to low"
15300 static unsigned regc_size[LAST_REGC +1] = {
15301 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
15302 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
15303 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
15304 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
15305 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
15306 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
15307 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
15308 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
15309 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
15310 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
15311 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
15317 static const struct {
15319 } regcm_bound[LAST_REGC + 1] = {
15320 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
15321 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
15322 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
15323 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
15324 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
15325 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
15326 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
15327 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
15328 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
15329 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
15330 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
15331 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
15332 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
15333 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
15336 static int arch_encode_cpu(const char *cpu)
15342 { "i386", CPU_I386 },
15350 for(ptr = cpus; ptr->name; ptr++) {
15351 if (strcmp(ptr->name, cpu) == 0) {
15358 static unsigned arch_regc_size(struct compile_state *state, int class)
15360 if ((class < 0) || (class > LAST_REGC)) {
15363 return regc_size[class];
15366 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
15368 /* See if two register classes may have overlapping registers */
15369 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
15370 REGCM_GPR32_8 | REGCM_GPR32 |
15371 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
15373 /* Special case for the immediates */
15374 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15375 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
15376 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15377 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
15380 return (regcm1 & regcm2) ||
15381 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
15384 static void arch_reg_equivs(
15385 struct compile_state *state, unsigned *equiv, int reg)
15387 if ((reg < 0) || (reg > LAST_REG)) {
15388 internal_error(state, 0, "invalid register");
15393 #if X86_4_8BIT_GPRS
15397 *equiv++ = REG_EAX;
15398 *equiv++ = REG_DXAX;
15399 *equiv++ = REG_EDXEAX;
15402 #if X86_4_8BIT_GPRS
15406 *equiv++ = REG_EAX;
15407 *equiv++ = REG_DXAX;
15408 *equiv++ = REG_EDXEAX;
15411 #if X86_4_8BIT_GPRS
15415 *equiv++ = REG_EBX;
15419 #if X86_4_8BIT_GPRS
15423 *equiv++ = REG_EBX;
15426 #if X86_4_8BIT_GPRS
15430 *equiv++ = REG_ECX;
15434 #if X86_4_8BIT_GPRS
15438 *equiv++ = REG_ECX;
15441 #if X86_4_8BIT_GPRS
15445 *equiv++ = REG_EDX;
15446 *equiv++ = REG_DXAX;
15447 *equiv++ = REG_EDXEAX;
15450 #if X86_4_8BIT_GPRS
15454 *equiv++ = REG_EDX;
15455 *equiv++ = REG_DXAX;
15456 *equiv++ = REG_EDXEAX;
15461 *equiv++ = REG_EAX;
15462 *equiv++ = REG_DXAX;
15463 *equiv++ = REG_EDXEAX;
15468 *equiv++ = REG_EBX;
15473 *equiv++ = REG_ECX;
15478 *equiv++ = REG_EDX;
15479 *equiv++ = REG_DXAX;
15480 *equiv++ = REG_EDXEAX;
15483 *equiv++ = REG_ESI;
15486 *equiv++ = REG_EDI;
15489 *equiv++ = REG_EBP;
15492 *equiv++ = REG_ESP;
15498 *equiv++ = REG_DXAX;
15499 *equiv++ = REG_EDXEAX;
15515 *equiv++ = REG_DXAX;
15516 *equiv++ = REG_EDXEAX;
15537 *equiv++ = REG_EAX;
15538 *equiv++ = REG_EDX;
15539 *equiv++ = REG_EDXEAX;
15548 *equiv++ = REG_EAX;
15549 *equiv++ = REG_EDX;
15550 *equiv++ = REG_DXAX;
15553 *equiv++ = REG_UNSET;
15556 static unsigned arch_avail_mask(struct compile_state *state)
15558 unsigned avail_mask;
15559 /* REGCM_GPR8 is not available */
15560 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
15561 REGCM_GPR32 | REGCM_GPR32_8 |
15562 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15563 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15564 switch(state->cpu) {
15567 avail_mask |= REGCM_MMX;
15571 avail_mask |= REGCM_MMX | REGCM_XMM;
15577 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15579 unsigned mask, result;
15583 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15584 if ((result & mask) == 0) {
15587 if (class > LAST_REGC) {
15590 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15591 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15592 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15593 result |= (1 << class2);
15597 result &= arch_avail_mask(state);
15601 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
15603 /* Like arch_regcm_normalize except immediate register classes are excluded */
15604 regcm = arch_regcm_normalize(state, regcm);
15605 /* Remove the immediate register classes */
15606 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15611 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15616 for(class = 0; class <= LAST_REGC; class++) {
15617 if ((reg >= regcm_bound[class].first) &&
15618 (reg <= regcm_bound[class].last)) {
15619 mask |= (1 << class);
15623 internal_error(state, 0, "reg %d not in any class", reg);
15628 static struct reg_info arch_reg_constraint(
15629 struct compile_state *state, struct type *type, const char *constraint)
15631 static const struct {
15635 } constraints[] = {
15636 { 'r', REGCM_GPR32, REG_UNSET },
15637 { 'g', REGCM_GPR32, REG_UNSET },
15638 { 'p', REGCM_GPR32, REG_UNSET },
15639 { 'q', REGCM_GPR8_LO, REG_UNSET },
15640 { 'Q', REGCM_GPR32_8, REG_UNSET },
15641 { 'x', REGCM_XMM, REG_UNSET },
15642 { 'y', REGCM_MMX, REG_UNSET },
15643 { 'a', REGCM_GPR32, REG_EAX },
15644 { 'b', REGCM_GPR32, REG_EBX },
15645 { 'c', REGCM_GPR32, REG_ECX },
15646 { 'd', REGCM_GPR32, REG_EDX },
15647 { 'D', REGCM_GPR32, REG_EDI },
15648 { 'S', REGCM_GPR32, REG_ESI },
15649 { '\0', 0, REG_UNSET },
15651 unsigned int regcm;
15652 unsigned int mask, reg;
15653 struct reg_info result;
15655 regcm = arch_type_to_regcm(state, type);
15658 for(ptr = constraint; *ptr; ptr++) {
15663 for(i = 0; constraints[i].class != '\0'; i++) {
15664 if (constraints[i].class == *ptr) {
15668 if (constraints[i].class == '\0') {
15669 error(state, 0, "invalid register constraint ``%c''", *ptr);
15672 if ((constraints[i].mask & regcm) == 0) {
15673 error(state, 0, "invalid register class %c specified",
15676 mask |= constraints[i].mask;
15677 if (constraints[i].reg != REG_UNSET) {
15678 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15679 error(state, 0, "Only one register may be specified");
15681 reg = constraints[i].reg;
15685 result.regcm = mask;
15689 static struct reg_info arch_reg_clobber(
15690 struct compile_state *state, const char *clobber)
15692 struct reg_info result;
15693 if (strcmp(clobber, "memory") == 0) {
15694 result.reg = REG_UNSET;
15697 else if (strcmp(clobber, "%eax") == 0) {
15698 result.reg = REG_EAX;
15699 result.regcm = REGCM_GPR32;
15701 else if (strcmp(clobber, "%ebx") == 0) {
15702 result.reg = REG_EBX;
15703 result.regcm = REGCM_GPR32;
15705 else if (strcmp(clobber, "%ecx") == 0) {
15706 result.reg = REG_ECX;
15707 result.regcm = REGCM_GPR32;
15709 else if (strcmp(clobber, "%edx") == 0) {
15710 result.reg = REG_EDX;
15711 result.regcm = REGCM_GPR32;
15713 else if (strcmp(clobber, "%esi") == 0) {
15714 result.reg = REG_ESI;
15715 result.regcm = REGCM_GPR32;
15717 else if (strcmp(clobber, "%edi") == 0) {
15718 result.reg = REG_EDI;
15719 result.regcm = REGCM_GPR32;
15721 else if (strcmp(clobber, "%ebp") == 0) {
15722 result.reg = REG_EBP;
15723 result.regcm = REGCM_GPR32;
15725 else if (strcmp(clobber, "%esp") == 0) {
15726 result.reg = REG_ESP;
15727 result.regcm = REGCM_GPR32;
15729 else if (strcmp(clobber, "cc") == 0) {
15730 result.reg = REG_EFLAGS;
15731 result.regcm = REGCM_FLAGS;
15733 else if ((strncmp(clobber, "xmm", 3) == 0) &&
15734 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15735 result.reg = REG_XMM0 + octdigval(clobber[3]);
15736 result.regcm = REGCM_XMM;
15738 else if ((strncmp(clobber, "mmx", 3) == 0) &&
15739 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15740 result.reg = REG_MMX0 + octdigval(clobber[3]);
15741 result.regcm = REGCM_MMX;
15744 error(state, 0, "Invalid register clobber");
15745 result.reg = REG_UNSET;
15751 static int do_select_reg(struct compile_state *state,
15752 char *used, int reg, unsigned classes)
15758 mask = arch_reg_regcm(state, reg);
15759 return (classes & mask) ? reg : REG_UNSET;
15762 static int arch_select_free_register(
15763 struct compile_state *state, char *used, int classes)
15765 /* Live ranges with the most neighbors are colored first.
15767 * Generally it does not matter which colors are given
15768 * as the register allocator attempts to color live ranges
15769 * in an order where you are guaranteed not to run out of colors.
15771 * Occasionally the register allocator cannot find an order
15772 * of register selection that will find a free color. To
15773 * increase the odds the register allocator will work when
15774 * it guesses first give out registers from register classes
15775 * least likely to run out of registers.
15780 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15781 reg = do_select_reg(state, used, i, classes);
15783 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15784 reg = do_select_reg(state, used, i, classes);
15786 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
15787 reg = do_select_reg(state, used, i, classes);
15789 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15790 reg = do_select_reg(state, used, i, classes);
15792 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15793 reg = do_select_reg(state, used, i, classes);
15795 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
15796 reg = do_select_reg(state, used, i, classes);
15798 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
15799 reg = do_select_reg(state, used, i, classes);
15801 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
15802 reg = do_select_reg(state, used, i, classes);
15804 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15805 reg = do_select_reg(state, used, i, classes);
15811 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
15813 #warning "FIXME force types smaller (if legal) before I get here"
15816 switch(type->type & TYPE_MASK) {
15823 mask = REGCM_GPR8 | REGCM_GPR8_LO |
15824 REGCM_GPR16 | REGCM_GPR16_8 |
15825 REGCM_GPR32 | REGCM_GPR32_8 |
15826 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15827 REGCM_MMX | REGCM_XMM |
15828 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15832 mask = REGCM_GPR16 | REGCM_GPR16_8 |
15833 REGCM_GPR32 | REGCM_GPR32_8 |
15834 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15835 REGCM_MMX | REGCM_XMM |
15836 REGCM_IMM32 | REGCM_IMM16;
15843 mask = REGCM_GPR32 | REGCM_GPR32_8 |
15844 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15845 REGCM_MMX | REGCM_XMM |
15849 internal_error(state, 0, "no register class for type");
15852 mask = arch_regcm_normalize(state, mask);
15856 static int is_imm32(struct triple *imm)
15858 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15859 (imm->op == OP_ADDRCONST);
15862 static int is_imm16(struct triple *imm)
15864 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15866 static int is_imm8(struct triple *imm)
15868 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15871 static int get_imm32(struct triple *ins, struct triple **expr)
15873 struct triple *imm;
15875 while(imm->op == OP_COPY) {
15878 if (!is_imm32(imm)) {
15881 unuse_triple(*expr, ins);
15882 use_triple(imm, ins);
15887 static int get_imm8(struct triple *ins, struct triple **expr)
15889 struct triple *imm;
15891 while(imm->op == OP_COPY) {
15894 if (!is_imm8(imm)) {
15897 unuse_triple(*expr, ins);
15898 use_triple(imm, ins);
15903 #define TEMPLATE_NOP 0
15904 #define TEMPLATE_INTCONST8 1
15905 #define TEMPLATE_INTCONST32 2
15906 #define TEMPLATE_COPY8_REG 3
15907 #define TEMPLATE_COPY16_REG 4
15908 #define TEMPLATE_COPY32_REG 5
15909 #define TEMPLATE_COPY_IMM8 6
15910 #define TEMPLATE_COPY_IMM16 7
15911 #define TEMPLATE_COPY_IMM32 8
15912 #define TEMPLATE_PHI8 9
15913 #define TEMPLATE_PHI16 10
15914 #define TEMPLATE_PHI32 11
15915 #define TEMPLATE_STORE8 12
15916 #define TEMPLATE_STORE16 13
15917 #define TEMPLATE_STORE32 14
15918 #define TEMPLATE_LOAD8 15
15919 #define TEMPLATE_LOAD16 16
15920 #define TEMPLATE_LOAD32 17
15921 #define TEMPLATE_BINARY8_REG 18
15922 #define TEMPLATE_BINARY16_REG 19
15923 #define TEMPLATE_BINARY32_REG 20
15924 #define TEMPLATE_BINARY8_IMM 21
15925 #define TEMPLATE_BINARY16_IMM 22
15926 #define TEMPLATE_BINARY32_IMM 23
15927 #define TEMPLATE_SL8_CL 24
15928 #define TEMPLATE_SL16_CL 25
15929 #define TEMPLATE_SL32_CL 26
15930 #define TEMPLATE_SL8_IMM 27
15931 #define TEMPLATE_SL16_IMM 28
15932 #define TEMPLATE_SL32_IMM 29
15933 #define TEMPLATE_UNARY8 30
15934 #define TEMPLATE_UNARY16 31
15935 #define TEMPLATE_UNARY32 32
15936 #define TEMPLATE_CMP8_REG 33
15937 #define TEMPLATE_CMP16_REG 34
15938 #define TEMPLATE_CMP32_REG 35
15939 #define TEMPLATE_CMP8_IMM 36
15940 #define TEMPLATE_CMP16_IMM 37
15941 #define TEMPLATE_CMP32_IMM 38
15942 #define TEMPLATE_TEST8 39
15943 #define TEMPLATE_TEST16 40
15944 #define TEMPLATE_TEST32 41
15945 #define TEMPLATE_SET 42
15946 #define TEMPLATE_JMP 43
15947 #define TEMPLATE_INB_DX 44
15948 #define TEMPLATE_INB_IMM 45
15949 #define TEMPLATE_INW_DX 46
15950 #define TEMPLATE_INW_IMM 47
15951 #define TEMPLATE_INL_DX 48
15952 #define TEMPLATE_INL_IMM 49
15953 #define TEMPLATE_OUTB_DX 50
15954 #define TEMPLATE_OUTB_IMM 51
15955 #define TEMPLATE_OUTW_DX 52
15956 #define TEMPLATE_OUTW_IMM 53
15957 #define TEMPLATE_OUTL_DX 54
15958 #define TEMPLATE_OUTL_IMM 55
15959 #define TEMPLATE_BSF 56
15960 #define TEMPLATE_RDMSR 57
15961 #define TEMPLATE_WRMSR 58
15962 #define TEMPLATE_UMUL8 59
15963 #define TEMPLATE_UMUL16 60
15964 #define TEMPLATE_UMUL32 61
15965 #define TEMPLATE_DIV8 62
15966 #define TEMPLATE_DIV16 63
15967 #define TEMPLATE_DIV32 64
15968 #define LAST_TEMPLATE TEMPLATE_DIV32
15969 #if LAST_TEMPLATE >= MAX_TEMPLATES
15970 #error "MAX_TEMPLATES to low"
15973 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
15974 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
15975 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15978 static struct ins_template templates[] = {
15979 [TEMPLATE_NOP] = {},
15980 [TEMPLATE_INTCONST8] = {
15981 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15983 [TEMPLATE_INTCONST32] = {
15984 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15986 [TEMPLATE_COPY8_REG] = {
15987 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15988 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15990 [TEMPLATE_COPY16_REG] = {
15991 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15992 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15994 [TEMPLATE_COPY32_REG] = {
15995 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15996 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15998 [TEMPLATE_COPY_IMM8] = {
15999 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
16000 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16002 [TEMPLATE_COPY_IMM16] = {
16003 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
16004 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
16006 [TEMPLATE_COPY_IMM32] = {
16007 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
16008 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
16010 [TEMPLATE_PHI8] = {
16011 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
16013 [ 0] = { REG_VIRT0, COPY8_REGCM },
16014 [ 1] = { REG_VIRT0, COPY8_REGCM },
16015 [ 2] = { REG_VIRT0, COPY8_REGCM },
16016 [ 3] = { REG_VIRT0, COPY8_REGCM },
16017 [ 4] = { REG_VIRT0, COPY8_REGCM },
16018 [ 5] = { REG_VIRT0, COPY8_REGCM },
16019 [ 6] = { REG_VIRT0, COPY8_REGCM },
16020 [ 7] = { REG_VIRT0, COPY8_REGCM },
16021 [ 8] = { REG_VIRT0, COPY8_REGCM },
16022 [ 9] = { REG_VIRT0, COPY8_REGCM },
16023 [10] = { REG_VIRT0, COPY8_REGCM },
16024 [11] = { REG_VIRT0, COPY8_REGCM },
16025 [12] = { REG_VIRT0, COPY8_REGCM },
16026 [13] = { REG_VIRT0, COPY8_REGCM },
16027 [14] = { REG_VIRT0, COPY8_REGCM },
16028 [15] = { REG_VIRT0, COPY8_REGCM },
16030 [TEMPLATE_PHI16] = {
16031 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
16033 [ 0] = { REG_VIRT0, COPY16_REGCM },
16034 [ 1] = { REG_VIRT0, COPY16_REGCM },
16035 [ 2] = { REG_VIRT0, COPY16_REGCM },
16036 [ 3] = { REG_VIRT0, COPY16_REGCM },
16037 [ 4] = { REG_VIRT0, COPY16_REGCM },
16038 [ 5] = { REG_VIRT0, COPY16_REGCM },
16039 [ 6] = { REG_VIRT0, COPY16_REGCM },
16040 [ 7] = { REG_VIRT0, COPY16_REGCM },
16041 [ 8] = { REG_VIRT0, COPY16_REGCM },
16042 [ 9] = { REG_VIRT0, COPY16_REGCM },
16043 [10] = { REG_VIRT0, COPY16_REGCM },
16044 [11] = { REG_VIRT0, COPY16_REGCM },
16045 [12] = { REG_VIRT0, COPY16_REGCM },
16046 [13] = { REG_VIRT0, COPY16_REGCM },
16047 [14] = { REG_VIRT0, COPY16_REGCM },
16048 [15] = { REG_VIRT0, COPY16_REGCM },
16050 [TEMPLATE_PHI32] = {
16051 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
16053 [ 0] = { REG_VIRT0, COPY32_REGCM },
16054 [ 1] = { REG_VIRT0, COPY32_REGCM },
16055 [ 2] = { REG_VIRT0, COPY32_REGCM },
16056 [ 3] = { REG_VIRT0, COPY32_REGCM },
16057 [ 4] = { REG_VIRT0, COPY32_REGCM },
16058 [ 5] = { REG_VIRT0, COPY32_REGCM },
16059 [ 6] = { REG_VIRT0, COPY32_REGCM },
16060 [ 7] = { REG_VIRT0, COPY32_REGCM },
16061 [ 8] = { REG_VIRT0, COPY32_REGCM },
16062 [ 9] = { REG_VIRT0, COPY32_REGCM },
16063 [10] = { REG_VIRT0, COPY32_REGCM },
16064 [11] = { REG_VIRT0, COPY32_REGCM },
16065 [12] = { REG_VIRT0, COPY32_REGCM },
16066 [13] = { REG_VIRT0, COPY32_REGCM },
16067 [14] = { REG_VIRT0, COPY32_REGCM },
16068 [15] = { REG_VIRT0, COPY32_REGCM },
16070 [TEMPLATE_STORE8] = {
16072 [0] = { REG_UNSET, REGCM_GPR32 },
16073 [1] = { REG_UNSET, REGCM_GPR8_LO },
16076 [TEMPLATE_STORE16] = {
16078 [0] = { REG_UNSET, REGCM_GPR32 },
16079 [1] = { REG_UNSET, REGCM_GPR16 },
16082 [TEMPLATE_STORE32] = {
16084 [0] = { REG_UNSET, REGCM_GPR32 },
16085 [1] = { REG_UNSET, REGCM_GPR32 },
16088 [TEMPLATE_LOAD8] = {
16089 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16090 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16092 [TEMPLATE_LOAD16] = {
16093 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
16094 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16096 [TEMPLATE_LOAD32] = {
16097 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16098 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16100 [TEMPLATE_BINARY8_REG] = {
16101 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16103 [0] = { REG_VIRT0, REGCM_GPR8_LO },
16104 [1] = { REG_UNSET, REGCM_GPR8_LO },
16107 [TEMPLATE_BINARY16_REG] = {
16108 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16110 [0] = { REG_VIRT0, REGCM_GPR16 },
16111 [1] = { REG_UNSET, REGCM_GPR16 },
16114 [TEMPLATE_BINARY32_REG] = {
16115 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16117 [0] = { REG_VIRT0, REGCM_GPR32 },
16118 [1] = { REG_UNSET, REGCM_GPR32 },
16121 [TEMPLATE_BINARY8_IMM] = {
16122 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16124 [0] = { REG_VIRT0, REGCM_GPR8_LO },
16125 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16128 [TEMPLATE_BINARY16_IMM] = {
16129 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16131 [0] = { REG_VIRT0, REGCM_GPR16 },
16132 [1] = { REG_UNNEEDED, REGCM_IMM16 },
16135 [TEMPLATE_BINARY32_IMM] = {
16136 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16138 [0] = { REG_VIRT0, REGCM_GPR32 },
16139 [1] = { REG_UNNEEDED, REGCM_IMM32 },
16142 [TEMPLATE_SL8_CL] = {
16143 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16145 [0] = { REG_VIRT0, REGCM_GPR8_LO },
16146 [1] = { REG_CL, REGCM_GPR8_LO },
16149 [TEMPLATE_SL16_CL] = {
16150 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16152 [0] = { REG_VIRT0, REGCM_GPR16 },
16153 [1] = { REG_CL, REGCM_GPR8_LO },
16156 [TEMPLATE_SL32_CL] = {
16157 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16159 [0] = { REG_VIRT0, REGCM_GPR32 },
16160 [1] = { REG_CL, REGCM_GPR8_LO },
16163 [TEMPLATE_SL8_IMM] = {
16164 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16166 [0] = { REG_VIRT0, REGCM_GPR8_LO },
16167 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16170 [TEMPLATE_SL16_IMM] = {
16171 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16173 [0] = { REG_VIRT0, REGCM_GPR16 },
16174 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16177 [TEMPLATE_SL32_IMM] = {
16178 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16180 [0] = { REG_VIRT0, REGCM_GPR32 },
16181 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16184 [TEMPLATE_UNARY8] = {
16185 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16186 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16188 [TEMPLATE_UNARY16] = {
16189 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16190 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16192 [TEMPLATE_UNARY32] = {
16193 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16194 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16196 [TEMPLATE_CMP8_REG] = {
16197 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16199 [0] = { REG_UNSET, REGCM_GPR8_LO },
16200 [1] = { REG_UNSET, REGCM_GPR8_LO },
16203 [TEMPLATE_CMP16_REG] = {
16204 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16206 [0] = { REG_UNSET, REGCM_GPR16 },
16207 [1] = { REG_UNSET, REGCM_GPR16 },
16210 [TEMPLATE_CMP32_REG] = {
16211 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16213 [0] = { REG_UNSET, REGCM_GPR32 },
16214 [1] = { REG_UNSET, REGCM_GPR32 },
16217 [TEMPLATE_CMP8_IMM] = {
16218 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16220 [0] = { REG_UNSET, REGCM_GPR8_LO },
16221 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16224 [TEMPLATE_CMP16_IMM] = {
16225 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16227 [0] = { REG_UNSET, REGCM_GPR16 },
16228 [1] = { REG_UNNEEDED, REGCM_IMM16 },
16231 [TEMPLATE_CMP32_IMM] = {
16232 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16234 [0] = { REG_UNSET, REGCM_GPR32 },
16235 [1] = { REG_UNNEEDED, REGCM_IMM32 },
16238 [TEMPLATE_TEST8] = {
16239 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16240 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16242 [TEMPLATE_TEST16] = {
16243 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16244 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
16246 [TEMPLATE_TEST32] = {
16247 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16248 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16251 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16252 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16255 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16257 [TEMPLATE_INB_DX] = {
16258 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
16259 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16261 [TEMPLATE_INB_IMM] = {
16262 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
16263 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16265 [TEMPLATE_INW_DX] = {
16266 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16267 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16269 [TEMPLATE_INW_IMM] = {
16270 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16271 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16273 [TEMPLATE_INL_DX] = {
16274 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
16275 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16277 [TEMPLATE_INL_IMM] = {
16278 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
16279 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16281 [TEMPLATE_OUTB_DX] = {
16283 [0] = { REG_AL, REGCM_GPR8_LO },
16284 [1] = { REG_DX, REGCM_GPR16 },
16287 [TEMPLATE_OUTB_IMM] = {
16289 [0] = { REG_AL, REGCM_GPR8_LO },
16290 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16293 [TEMPLATE_OUTW_DX] = {
16295 [0] = { REG_AX, REGCM_GPR16 },
16296 [1] = { REG_DX, REGCM_GPR16 },
16299 [TEMPLATE_OUTW_IMM] = {
16301 [0] = { REG_AX, REGCM_GPR16 },
16302 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16305 [TEMPLATE_OUTL_DX] = {
16307 [0] = { REG_EAX, REGCM_GPR32 },
16308 [1] = { REG_DX, REGCM_GPR16 },
16311 [TEMPLATE_OUTL_IMM] = {
16313 [0] = { REG_EAX, REGCM_GPR32 },
16314 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16318 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16319 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16321 [TEMPLATE_RDMSR] = {
16323 [0] = { REG_EAX, REGCM_GPR32 },
16324 [1] = { REG_EDX, REGCM_GPR32 },
16326 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
16328 [TEMPLATE_WRMSR] = {
16330 [0] = { REG_ECX, REGCM_GPR32 },
16331 [1] = { REG_EAX, REGCM_GPR32 },
16332 [2] = { REG_EDX, REGCM_GPR32 },
16335 [TEMPLATE_UMUL8] = {
16336 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16338 [0] = { REG_AL, REGCM_GPR8_LO },
16339 [1] = { REG_UNSET, REGCM_GPR8_LO },
16342 [TEMPLATE_UMUL16] = {
16343 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
16345 [0] = { REG_AX, REGCM_GPR16 },
16346 [1] = { REG_UNSET, REGCM_GPR16 },
16349 [TEMPLATE_UMUL32] = {
16350 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
16352 [0] = { REG_EAX, REGCM_GPR32 },
16353 [1] = { REG_UNSET, REGCM_GPR32 },
16356 [TEMPLATE_DIV8] = {
16358 [0] = { REG_AL, REGCM_GPR8_LO },
16359 [1] = { REG_AH, REGCM_GPR8 },
16362 [0] = { REG_AX, REGCM_GPR16 },
16363 [1] = { REG_UNSET, REGCM_GPR8_LO },
16366 [TEMPLATE_DIV16] = {
16368 [0] = { REG_AX, REGCM_GPR16 },
16369 [1] = { REG_DX, REGCM_GPR16 },
16372 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
16373 [1] = { REG_UNSET, REGCM_GPR16 },
16376 [TEMPLATE_DIV32] = {
16378 [0] = { REG_EAX, REGCM_GPR32 },
16379 [1] = { REG_EDX, REGCM_GPR32 },
16382 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
16383 [1] = { REG_UNSET, REGCM_GPR32 },
16388 static void fixup_branches(struct compile_state *state,
16389 struct triple *cmp, struct triple *use, int jmp_op)
16391 struct triple_set *entry, *next;
16392 for(entry = use->use; entry; entry = next) {
16393 next = entry->next;
16394 if (entry->member->op == OP_COPY) {
16395 fixup_branches(state, cmp, entry->member, jmp_op);
16397 else if (entry->member->op == OP_BRANCH) {
16398 struct triple *branch, *test;
16399 struct triple *left, *right;
16401 left = RHS(cmp, 0);
16402 if (TRIPLE_RHS(cmp->sizes) > 1) {
16403 right = RHS(cmp, 1);
16405 branch = entry->member;
16406 test = pre_triple(state, branch,
16407 cmp->op, cmp->type, left, right);
16408 test->template_id = TEMPLATE_TEST32;
16409 if (cmp->op == OP_CMP) {
16410 test->template_id = TEMPLATE_CMP32_REG;
16411 if (get_imm32(test, &RHS(test, 1))) {
16412 test->template_id = TEMPLATE_CMP32_IMM;
16415 use_triple(RHS(test, 0), test);
16416 use_triple(RHS(test, 1), test);
16417 unuse_triple(RHS(branch, 0), branch);
16418 RHS(branch, 0) = test;
16419 branch->op = jmp_op;
16420 branch->template_id = TEMPLATE_JMP;
16421 use_triple(RHS(branch, 0), branch);
16426 static void bool_cmp(struct compile_state *state,
16427 struct triple *ins, int cmp_op, int jmp_op, int set_op)
16429 struct triple_set *entry, *next;
16430 struct triple *set;
16432 /* Put a barrier up before the cmp which preceeds the
16433 * copy instruction. If a set actually occurs this gives
16434 * us a chance to move variables in registers out of the way.
16437 /* Modify the comparison operator */
16439 ins->template_id = TEMPLATE_TEST32;
16440 if (cmp_op == OP_CMP) {
16441 ins->template_id = TEMPLATE_CMP32_REG;
16442 if (get_imm32(ins, &RHS(ins, 1))) {
16443 ins->template_id = TEMPLATE_CMP32_IMM;
16446 /* Generate the instruction sequence that will transform the
16447 * result of the comparison into a logical value.
16449 set = post_triple(state, ins, set_op, &char_type, ins, 0);
16450 use_triple(ins, set);
16451 set->template_id = TEMPLATE_SET;
16453 for(entry = ins->use; entry; entry = next) {
16454 next = entry->next;
16455 if (entry->member == set) {
16458 replace_rhs_use(state, ins, set, entry->member);
16460 fixup_branches(state, ins, set, jmp_op);
16463 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
16465 struct triple *next;
16467 lhs = TRIPLE_LHS(ins->sizes);
16468 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
16469 if (next != LHS(ins, i)) {
16470 internal_error(state, ins, "malformed lhs on %s",
16473 if (next->op != OP_PIECE) {
16474 internal_error(state, ins, "bad lhs op %s at %d on %s",
16475 tops(next->op), i, tops(ins->op));
16477 if (next->u.cval != i) {
16478 internal_error(state, ins, "bad u.cval of %d %d expected",
16485 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
16487 struct ins_template *template;
16488 struct reg_info result;
16490 if (ins->op == OP_PIECE) {
16491 index = ins->u.cval;
16492 ins = MISC(ins, 0);
16494 zlhs = TRIPLE_LHS(ins->sizes);
16495 if (triple_is_def(state, ins)) {
16498 if (index >= zlhs) {
16499 internal_error(state, ins, "index %d out of range for %s\n",
16500 index, tops(ins->op));
16504 template = &ins->u.ainfo->tmpl;
16507 if (ins->template_id > LAST_TEMPLATE) {
16508 internal_error(state, ins, "bad template number %d",
16511 template = &templates[ins->template_id];
16514 result = template->lhs[index];
16515 result.regcm = arch_regcm_normalize(state, result.regcm);
16516 if (result.reg != REG_UNNEEDED) {
16517 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
16519 if (result.regcm == 0) {
16520 internal_error(state, ins, "lhs %d regcm == 0", index);
16525 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
16527 struct reg_info result;
16528 struct ins_template *template;
16529 if ((index > TRIPLE_RHS(ins->sizes)) ||
16530 (ins->op == OP_PIECE)) {
16531 internal_error(state, ins, "index %d out of range for %s\n",
16532 index, tops(ins->op));
16536 template = &ins->u.ainfo->tmpl;
16539 if (ins->template_id > LAST_TEMPLATE) {
16540 internal_error(state, ins, "bad template number %d",
16543 template = &templates[ins->template_id];
16546 result = template->rhs[index];
16547 result.regcm = arch_regcm_normalize(state, result.regcm);
16548 if (result.regcm == 0) {
16549 internal_error(state, ins, "rhs %d regcm == 0", index);
16554 static struct triple *mod_div(struct compile_state *state,
16555 struct triple *ins, int div_op, int index)
16557 struct triple *div, *piece0, *piece1;
16559 /* Generate a piece to hold the remainder */
16560 piece1 = post_triple(state, ins, OP_PIECE, ins->type, 0, 0);
16561 piece1->u.cval = 1;
16563 /* Generate a piece to hold the quotient */
16564 piece0 = post_triple(state, ins, OP_PIECE, ins->type, 0, 0);
16565 piece0->u.cval = 0;
16567 /* Generate the appropriate division instruction */
16568 div = post_triple(state, ins, div_op, ins->type, 0, 0);
16569 RHS(div, 0) = RHS(ins, 0);
16570 RHS(div, 1) = RHS(ins, 1);
16571 LHS(div, 0) = piece0;
16572 LHS(div, 1) = piece1;
16573 div->template_id = TEMPLATE_DIV32;
16574 use_triple(RHS(div, 0), div);
16575 use_triple(RHS(div, 1), div);
16576 use_triple(LHS(div, 0), div);
16577 use_triple(LHS(div, 1), div);
16579 /* Hook on piece0 */
16580 MISC(piece0, 0) = div;
16581 use_triple(div, piece0);
16583 /* Hook on piece1 */
16584 MISC(piece1, 0) = div;
16585 use_triple(div, piece1);
16587 /* Replate uses of ins with the appropriate piece of the div */
16588 propogate_use(state, ins, LHS(div, index));
16589 release_triple(state, ins);
16591 /* Return the address of the next instruction */
16592 return piece1->next;
16595 static struct triple *transform_to_arch_instruction(
16596 struct compile_state *state, struct triple *ins)
16598 /* Transform from generic 3 address instructions
16599 * to archtecture specific instructions.
16600 * And apply architecture specific constraints to instructions.
16601 * Copies are inserted to preserve the register flexibility
16602 * of 3 address instructions.
16604 struct triple *next;
16609 ins->template_id = TEMPLATE_INTCONST32;
16610 if (ins->u.cval < 256) {
16611 ins->template_id = TEMPLATE_INTCONST8;
16615 ins->template_id = TEMPLATE_INTCONST32;
16621 ins->template_id = TEMPLATE_NOP;
16624 size = size_of(state, ins->type);
16625 if (is_imm8(RHS(ins, 0)) && (size <= 1)) {
16626 ins->template_id = TEMPLATE_COPY_IMM8;
16628 else if (is_imm16(RHS(ins, 0)) && (size <= 2)) {
16629 ins->template_id = TEMPLATE_COPY_IMM16;
16631 else if (is_imm32(RHS(ins, 0)) && (size <= 4)) {
16632 ins->template_id = TEMPLATE_COPY_IMM32;
16634 else if (is_const(RHS(ins, 0))) {
16635 internal_error(state, ins, "bad constant passed to copy");
16637 else if (size <= 1) {
16638 ins->template_id = TEMPLATE_COPY8_REG;
16640 else if (size <= 2) {
16641 ins->template_id = TEMPLATE_COPY16_REG;
16643 else if (size <= 4) {
16644 ins->template_id = TEMPLATE_COPY32_REG;
16647 internal_error(state, ins, "bad type passed to copy");
16651 size = size_of(state, ins->type);
16653 ins->template_id = TEMPLATE_PHI8;
16655 else if (size <= 2) {
16656 ins->template_id = TEMPLATE_PHI16;
16658 else if (size <= 4) {
16659 ins->template_id = TEMPLATE_PHI32;
16662 internal_error(state, ins, "bad type passed to phi");
16666 switch(ins->type->type & TYPE_MASK) {
16667 case TYPE_CHAR: case TYPE_UCHAR:
16668 ins->template_id = TEMPLATE_STORE8;
16670 case TYPE_SHORT: case TYPE_USHORT:
16671 ins->template_id = TEMPLATE_STORE16;
16673 case TYPE_INT: case TYPE_UINT:
16674 case TYPE_LONG: case TYPE_ULONG:
16676 ins->template_id = TEMPLATE_STORE32;
16679 internal_error(state, ins, "unknown type in store");
16684 switch(ins->type->type & TYPE_MASK) {
16685 case TYPE_CHAR: case TYPE_UCHAR:
16686 ins->template_id = TEMPLATE_LOAD8;
16690 ins->template_id = TEMPLATE_LOAD16;
16697 ins->template_id = TEMPLATE_LOAD32;
16700 internal_error(state, ins, "unknown type in load");
16710 ins->template_id = TEMPLATE_BINARY32_REG;
16711 if (get_imm32(ins, &RHS(ins, 1))) {
16712 ins->template_id = TEMPLATE_BINARY32_IMM;
16717 ins->template_id = TEMPLATE_DIV32;
16718 next = after_lhs(state, ins);
16720 /* FIXME UMUL does not work yet.. */
16722 ins->template_id = TEMPLATE_UMUL32;
16725 next = mod_div(state, ins, OP_UDIVT, 0);
16728 next = mod_div(state, ins, OP_SDIVT, 0);
16731 next = mod_div(state, ins, OP_UDIVT, 1);
16734 next = mod_div(state, ins, OP_SDIVT, 1);
16739 ins->template_id = TEMPLATE_SL32_CL;
16740 if (get_imm8(ins, &RHS(ins, 1))) {
16741 ins->template_id = TEMPLATE_SL32_IMM;
16742 } else if (size_of(state, RHS(ins, 1)->type) > 1) {
16743 typed_pre_copy(state, &char_type, ins, 1);
16748 ins->template_id = TEMPLATE_UNARY32;
16751 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
16754 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16757 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16760 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16763 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16766 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16769 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16772 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16775 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16778 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16781 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16784 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16787 if (TRIPLE_RHS(ins->sizes) > 0) {
16788 internal_error(state, ins, "bad branch test");
16791 ins->template_id = TEMPLATE_NOP;
16797 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16798 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16799 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16801 if (get_imm8(ins, &RHS(ins, 0))) {
16802 ins->template_id += 1;
16809 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16810 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16811 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16813 if (get_imm8(ins, &RHS(ins, 1))) {
16814 ins->template_id += 1;
16819 ins->template_id = TEMPLATE_BSF;
16822 ins->template_id = TEMPLATE_RDMSR;
16823 next = after_lhs(state, ins);
16826 ins->template_id = TEMPLATE_WRMSR;
16829 ins->template_id = TEMPLATE_NOP;
16832 ins->template_id = TEMPLATE_NOP;
16833 next = after_lhs(state, ins);
16835 /* Already transformed instructions */
16837 ins->template_id = TEMPLATE_TEST32;
16840 ins->template_id = TEMPLATE_CMP32_REG;
16841 if (get_imm32(ins, &RHS(ins, 1))) {
16842 ins->template_id = TEMPLATE_CMP32_IMM;
16845 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16846 case OP_JMP_SLESS: case OP_JMP_ULESS:
16847 case OP_JMP_SMORE: case OP_JMP_UMORE:
16848 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16849 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16850 ins->template_id = TEMPLATE_JMP;
16852 case OP_SET_EQ: case OP_SET_NOTEQ:
16853 case OP_SET_SLESS: case OP_SET_ULESS:
16854 case OP_SET_SMORE: case OP_SET_UMORE:
16855 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16856 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16857 ins->template_id = TEMPLATE_SET;
16859 /* Unhandled instructions */
16862 internal_error(state, ins, "unhandled ins: %d %s\n",
16863 ins->op, tops(ins->op));
16869 static long next_label(struct compile_state *state)
16871 static long label_counter = 0;
16872 return ++label_counter;
16874 static void generate_local_labels(struct compile_state *state)
16876 struct triple *first, *label;
16877 first = RHS(state->main_function, 0);
16880 if ((label->op == OP_LABEL) ||
16881 (label->op == OP_SDECL)) {
16883 label->u.cval = next_label(state);
16889 label = label->next;
16890 } while(label != first);
16893 static int check_reg(struct compile_state *state,
16894 struct triple *triple, int classes)
16898 reg = ID_REG(triple->id);
16899 if (reg == REG_UNSET) {
16900 internal_error(state, triple, "register not set");
16902 mask = arch_reg_regcm(state, reg);
16903 if (!(classes & mask)) {
16904 internal_error(state, triple, "reg %d in wrong class",
16910 static const char *arch_reg_str(int reg)
16913 #error "Registers have renumberd fix arch_reg_str"
16915 static const char *regs[] = {
16919 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16920 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16921 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16924 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16925 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
16926 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16928 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16935 static const char *reg(struct compile_state *state, struct triple *triple,
16939 reg = check_reg(state, triple, classes);
16940 return arch_reg_str(reg);
16943 const char *type_suffix(struct compile_state *state, struct type *type)
16945 const char *suffix;
16946 switch(size_of(state, type)) {
16947 case 1: suffix = "b"; break;
16948 case 2: suffix = "w"; break;
16949 case 4: suffix = "l"; break;
16951 internal_error(state, 0, "unknown suffix");
16958 static void print_const_val(
16959 struct compile_state *state, struct triple *ins, FILE *fp)
16963 fprintf(fp, " $%ld ",
16964 (long_t)(ins->u.cval));
16967 if (MISC(ins, 0)->op != OP_SDECL) {
16968 internal_error(state, ins, "bad base for addrconst");
16970 if (MISC(ins, 0)->u.cval <= 0) {
16971 internal_error(state, ins, "unlabeled constant");
16973 fprintf(fp, " $L%s%lu+%lu ",
16974 state->label_prefix,
16975 MISC(ins, 0)->u.cval,
16979 internal_error(state, ins, "unknown constant type");
16984 static void print_const(struct compile_state *state,
16985 struct triple *ins, FILE *fp)
16989 switch(ins->type->type & TYPE_MASK) {
16992 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16996 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
17002 fprintf(fp, ".int %lu\n", ins->u.cval);
17005 internal_error(state, ins, "Unknown constant type");
17009 if (MISC(ins, 0)->op != OP_SDECL) {
17010 internal_error(state, ins, "bad base for addrconst");
17012 if (MISC(ins, 0)->u.cval <= 0) {
17013 internal_error(state, ins, "unlabeled constant");
17015 fprintf(fp, ".int L%s%lu+%lu\n",
17016 state->label_prefix,
17017 MISC(ins, 0)->u.cval,
17022 unsigned char *blob;
17024 size = size_of(state, ins->type);
17025 blob = ins->u.blob;
17026 for(i = 0; i < size; i++) {
17027 fprintf(fp, ".byte 0x%02x\n",
17033 internal_error(state, ins, "Unknown constant type");
17038 #define TEXT_SECTION ".rom.text"
17039 #define DATA_SECTION ".rom.data"
17041 static long get_const_pool_ref(
17042 struct compile_state *state, struct triple *ins, FILE *fp)
17045 ref = next_label(state);
17046 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
17047 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
17048 fprintf(fp, "L%s%lu:\n", state->label_prefix, ref);
17049 print_const(state, ins, fp);
17050 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17054 static void print_binary_op(struct compile_state *state,
17055 const char *op, struct triple *ins, FILE *fp)
17058 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17059 if (RHS(ins, 0)->id != ins->id) {
17060 internal_error(state, ins, "invalid register assignment");
17062 if (is_const(RHS(ins, 1))) {
17063 fprintf(fp, "\t%s ", op);
17064 print_const_val(state, RHS(ins, 1), fp);
17065 fprintf(fp, ", %s\n",
17066 reg(state, RHS(ins, 0), mask));
17069 unsigned lmask, rmask;
17071 lreg = check_reg(state, RHS(ins, 0), mask);
17072 rreg = check_reg(state, RHS(ins, 1), mask);
17073 lmask = arch_reg_regcm(state, lreg);
17074 rmask = arch_reg_regcm(state, rreg);
17075 mask = lmask & rmask;
17076 fprintf(fp, "\t%s %s, %s\n",
17078 reg(state, RHS(ins, 1), mask),
17079 reg(state, RHS(ins, 0), mask));
17082 static void print_unary_op(struct compile_state *state,
17083 const char *op, struct triple *ins, FILE *fp)
17086 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17087 fprintf(fp, "\t%s %s\n",
17089 reg(state, RHS(ins, 0), mask));
17092 static void print_op_shift(struct compile_state *state,
17093 const char *op, struct triple *ins, FILE *fp)
17096 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17097 if (RHS(ins, 0)->id != ins->id) {
17098 internal_error(state, ins, "invalid register assignment");
17100 if (is_const(RHS(ins, 1))) {
17101 fprintf(fp, "\t%s ", op);
17102 print_const_val(state, RHS(ins, 1), fp);
17103 fprintf(fp, ", %s\n",
17104 reg(state, RHS(ins, 0), mask));
17107 fprintf(fp, "\t%s %s, %s\n",
17109 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
17110 reg(state, RHS(ins, 0), mask));
17114 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
17121 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
17122 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
17123 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
17125 internal_error(state, ins, "not an in operation");
17129 dreg = check_reg(state, ins, mask);
17130 if (!reg_is_reg(state, dreg, REG_EAX)) {
17131 internal_error(state, ins, "dst != %%eax");
17133 if (is_const(RHS(ins, 0))) {
17134 fprintf(fp, "\t%s ", op);
17135 print_const_val(state, RHS(ins, 0), fp);
17136 fprintf(fp, ", %s\n",
17137 reg(state, ins, mask));
17141 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
17142 if (!reg_is_reg(state, addr_reg, REG_DX)) {
17143 internal_error(state, ins, "src != %%dx");
17145 fprintf(fp, "\t%s %s, %s\n",
17147 reg(state, RHS(ins, 0), REGCM_GPR16),
17148 reg(state, ins, mask));
17152 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
17159 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
17160 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
17161 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
17163 internal_error(state, ins, "not an out operation");
17167 lreg = check_reg(state, RHS(ins, 0), mask);
17168 if (!reg_is_reg(state, lreg, REG_EAX)) {
17169 internal_error(state, ins, "src != %%eax");
17171 if (is_const(RHS(ins, 1))) {
17172 fprintf(fp, "\t%s %s,",
17173 op, reg(state, RHS(ins, 0), mask));
17174 print_const_val(state, RHS(ins, 1), fp);
17179 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
17180 if (!reg_is_reg(state, addr_reg, REG_DX)) {
17181 internal_error(state, ins, "dst != %%dx");
17183 fprintf(fp, "\t%s %s, %s\n",
17185 reg(state, RHS(ins, 0), mask),
17186 reg(state, RHS(ins, 1), REGCM_GPR16));
17190 static void print_op_move(struct compile_state *state,
17191 struct triple *ins, FILE *fp)
17193 /* op_move is complex because there are many types
17194 * of registers we can move between.
17195 * Because OP_COPY will be introduced in arbitrary locations
17196 * OP_COPY must not affect flags.
17198 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
17199 struct triple *dst, *src;
17200 if (ins->op == OP_COPY) {
17205 internal_error(state, ins, "unknown move operation");
17208 if (!is_const(src)) {
17209 int src_reg, dst_reg;
17210 int src_regcm, dst_regcm;
17211 src_reg = ID_REG(src->id);
17212 dst_reg = ID_REG(dst->id);
17213 src_regcm = arch_reg_regcm(state, src_reg);
17214 dst_regcm = arch_reg_regcm(state, dst_reg);
17215 /* If the class is the same just move the register */
17216 if (src_regcm & dst_regcm &
17217 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
17218 if ((src_reg != dst_reg) || !omit_copy) {
17219 fprintf(fp, "\tmov %s, %s\n",
17220 reg(state, src, src_regcm),
17221 reg(state, dst, dst_regcm));
17224 /* Move 32bit to 16bit */
17225 else if ((src_regcm & REGCM_GPR32) &&
17226 (dst_regcm & REGCM_GPR16)) {
17227 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
17228 if ((src_reg != dst_reg) || !omit_copy) {
17229 fprintf(fp, "\tmovw %s, %s\n",
17230 arch_reg_str(src_reg),
17231 arch_reg_str(dst_reg));
17234 /* Move from 32bit gprs to 16bit gprs */
17235 else if ((src_regcm & REGCM_GPR32) &&
17236 (dst_regcm & REGCM_GPR16)) {
17237 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17238 if ((src_reg != dst_reg) || !omit_copy) {
17239 fprintf(fp, "\tmov %s, %s\n",
17240 arch_reg_str(src_reg),
17241 arch_reg_str(dst_reg));
17244 /* Move 32bit to 8bit */
17245 else if ((src_regcm & REGCM_GPR32_8) &&
17246 (dst_regcm & REGCM_GPR8_LO))
17248 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
17249 if ((src_reg != dst_reg) || !omit_copy) {
17250 fprintf(fp, "\tmovb %s, %s\n",
17251 arch_reg_str(src_reg),
17252 arch_reg_str(dst_reg));
17255 /* Move 16bit to 8bit */
17256 else if ((src_regcm & REGCM_GPR16_8) &&
17257 (dst_regcm & REGCM_GPR8_LO))
17259 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
17260 if ((src_reg != dst_reg) || !omit_copy) {
17261 fprintf(fp, "\tmovb %s, %s\n",
17262 arch_reg_str(src_reg),
17263 arch_reg_str(dst_reg));
17266 /* Move 8/16bit to 16/32bit */
17267 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
17268 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
17270 op = is_signed(src->type)? "movsx": "movzx";
17271 fprintf(fp, "\t%s %s, %s\n",
17273 reg(state, src, src_regcm),
17274 reg(state, dst, dst_regcm));
17276 /* Move between sse registers */
17277 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
17278 if ((src_reg != dst_reg) || !omit_copy) {
17279 fprintf(fp, "\tmovdqa %s, %s\n",
17280 reg(state, src, src_regcm),
17281 reg(state, dst, dst_regcm));
17284 /* Move between mmx registers */
17285 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
17286 if ((src_reg != dst_reg) || !omit_copy) {
17287 fprintf(fp, "\tmovq %s, %s\n",
17288 reg(state, src, src_regcm),
17289 reg(state, dst, dst_regcm));
17292 /* Move from sse to mmx registers */
17293 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
17294 fprintf(fp, "\tmovdq2q %s, %s\n",
17295 reg(state, src, src_regcm),
17296 reg(state, dst, dst_regcm));
17298 /* Move from mmx to sse registers */
17299 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
17300 fprintf(fp, "\tmovq2dq %s, %s\n",
17301 reg(state, src, src_regcm),
17302 reg(state, dst, dst_regcm));
17304 /* Move between 32bit gprs & mmx/sse registers */
17305 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
17306 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
17307 fprintf(fp, "\tmovd %s, %s\n",
17308 reg(state, src, src_regcm),
17309 reg(state, dst, dst_regcm));
17311 /* Move from 16bit gprs & mmx/sse registers */
17312 else if ((src_regcm & REGCM_GPR16) &&
17313 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
17316 op = is_signed(src->type)? "movsx":"movzx";
17317 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17318 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
17320 arch_reg_str(src_reg),
17321 arch_reg_str(mid_reg),
17322 arch_reg_str(mid_reg),
17323 arch_reg_str(dst_reg));
17325 /* Move from mmx/sse registers to 16bit gprs */
17326 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17327 (dst_regcm & REGCM_GPR16)) {
17328 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17329 fprintf(fp, "\tmovd %s, %s\n",
17330 arch_reg_str(src_reg),
17331 arch_reg_str(dst_reg));
17333 /* Move from gpr to 64bit dividend */
17334 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
17335 (dst_regcm & REGCM_DIVIDEND64)) {
17336 const char *extend;
17337 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
17338 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
17339 arch_reg_str(src_reg),
17342 /* Move from 64bit gpr to gpr */
17343 else if ((src_regcm & REGCM_DIVIDEND64) &&
17344 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
17345 if (dst_regcm & REGCM_GPR32) {
17348 else if (dst_regcm & REGCM_GPR16) {
17351 else if (dst_regcm & REGCM_GPR8_LO) {
17354 fprintf(fp, "\tmov %s, %s\n",
17355 arch_reg_str(src_reg),
17356 arch_reg_str(dst_reg));
17358 /* Move from mmx/sse registers to 64bit gpr */
17359 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17360 (dst_regcm & REGCM_DIVIDEND64)) {
17361 const char *extend;
17362 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
17363 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
17364 arch_reg_str(src_reg),
17367 /* Move from 64bit gpr to mmx/sse register */
17368 else if ((src_regcm & REGCM_DIVIDEND64) &&
17369 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
17370 fprintf(fp, "\tmovd %%eax, %s\n",
17371 arch_reg_str(dst_reg));
17373 #if X86_4_8BIT_GPRS
17374 /* Move from 8bit gprs to mmx/sse registers */
17375 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
17376 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
17379 op = is_signed(src->type)? "movsx":"movzx";
17380 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17381 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
17383 reg(state, src, src_regcm),
17384 arch_reg_str(mid_reg),
17385 arch_reg_str(mid_reg),
17386 reg(state, dst, dst_regcm));
17388 /* Move from mmx/sse registers and 8bit gprs */
17389 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17390 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
17392 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17393 fprintf(fp, "\tmovd %s, %s\n",
17394 reg(state, src, src_regcm),
17395 arch_reg_str(mid_reg));
17397 /* Move from 32bit gprs to 8bit gprs */
17398 else if ((src_regcm & REGCM_GPR32) &&
17399 (dst_regcm & REGCM_GPR8_LO)) {
17400 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17401 if ((src_reg != dst_reg) || !omit_copy) {
17402 fprintf(fp, "\tmov %s, %s\n",
17403 arch_reg_str(src_reg),
17404 arch_reg_str(dst_reg));
17407 /* Move from 16bit gprs to 8bit gprs */
17408 else if ((src_regcm & REGCM_GPR16) &&
17409 (dst_regcm & REGCM_GPR8_LO)) {
17410 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
17411 if ((src_reg != dst_reg) || !omit_copy) {
17412 fprintf(fp, "\tmov %s, %s\n",
17413 arch_reg_str(src_reg),
17414 arch_reg_str(dst_reg));
17417 #endif /* X86_4_8BIT_GPRS */
17419 internal_error(state, ins, "unknown copy type");
17425 dst_reg = ID_REG(dst->id);
17426 dst_regcm = arch_reg_regcm(state, dst_reg);
17427 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
17428 fprintf(fp, "\tmov ");
17429 print_const_val(state, src, fp);
17430 fprintf(fp, ", %s\n",
17431 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
17433 else if (dst_regcm & REGCM_DIVIDEND64) {
17434 if (size_of(state, dst->type) > 4) {
17435 internal_error(state, ins, "64bit constant...");
17437 fprintf(fp, "\tmov $0, %%edx\n");
17438 fprintf(fp, "\tmov ");
17439 print_const_val(state, src, fp);
17440 fprintf(fp, ", %%eax\n");
17442 else if (dst_regcm & REGCM_DIVIDEND32) {
17443 if (size_of(state, dst->type) > 2) {
17444 internal_error(state, ins, "32bit constant...");
17446 fprintf(fp, "\tmov $0, %%dx\n");
17447 fprintf(fp, "\tmov ");
17448 print_const_val(state, src, fp);
17449 fprintf(fp, ", %%ax");
17451 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
17453 ref = get_const_pool_ref(state, src, fp);
17454 fprintf(fp, "\tmovq L%s%lu, %s\n",
17455 state->label_prefix, ref,
17456 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
17459 internal_error(state, ins, "unknown copy immediate type");
17464 static void print_op_load(struct compile_state *state,
17465 struct triple *ins, FILE *fp)
17467 struct triple *dst, *src;
17470 if (is_const(src) || is_const(dst)) {
17471 internal_error(state, ins, "unknown load operation");
17473 fprintf(fp, "\tmov (%s), %s\n",
17474 reg(state, src, REGCM_GPR32),
17475 reg(state, dst, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32));
17479 static void print_op_store(struct compile_state *state,
17480 struct triple *ins, FILE *fp)
17482 struct triple *dst, *src;
17485 if (is_const(src) && (src->op == OP_INTCONST)) {
17487 value = (long_t)(src->u.cval);
17488 fprintf(fp, "\tmov%s $%ld, (%s)\n",
17489 type_suffix(state, src->type),
17491 reg(state, dst, REGCM_GPR32));
17493 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
17494 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
17495 type_suffix(state, src->type),
17496 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
17500 if (is_const(src) || is_const(dst)) {
17501 internal_error(state, ins, "unknown store operation");
17503 fprintf(fp, "\tmov%s %s, (%s)\n",
17504 type_suffix(state, src->type),
17505 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
17506 reg(state, dst, REGCM_GPR32));
17512 static void print_op_smul(struct compile_state *state,
17513 struct triple *ins, FILE *fp)
17515 if (!is_const(RHS(ins, 1))) {
17516 fprintf(fp, "\timul %s, %s\n",
17517 reg(state, RHS(ins, 1), REGCM_GPR32),
17518 reg(state, RHS(ins, 0), REGCM_GPR32));
17521 fprintf(fp, "\timul ");
17522 print_const_val(state, RHS(ins, 1), fp);
17523 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
17527 static void print_op_cmp(struct compile_state *state,
17528 struct triple *ins, FILE *fp)
17532 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17533 dreg = check_reg(state, ins, REGCM_FLAGS);
17534 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
17535 internal_error(state, ins, "bad dest register for cmp");
17537 if (is_const(RHS(ins, 1))) {
17538 fprintf(fp, "\tcmp ");
17539 print_const_val(state, RHS(ins, 1), fp);
17540 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
17543 unsigned lmask, rmask;
17545 lreg = check_reg(state, RHS(ins, 0), mask);
17546 rreg = check_reg(state, RHS(ins, 1), mask);
17547 lmask = arch_reg_regcm(state, lreg);
17548 rmask = arch_reg_regcm(state, rreg);
17549 mask = lmask & rmask;
17550 fprintf(fp, "\tcmp %s, %s\n",
17551 reg(state, RHS(ins, 1), mask),
17552 reg(state, RHS(ins, 0), mask));
17556 static void print_op_test(struct compile_state *state,
17557 struct triple *ins, FILE *fp)
17560 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17561 fprintf(fp, "\ttest %s, %s\n",
17562 reg(state, RHS(ins, 0), mask),
17563 reg(state, RHS(ins, 0), mask));
17566 static void print_op_branch(struct compile_state *state,
17567 struct triple *branch, FILE *fp)
17569 const char *bop = "j";
17570 if (branch->op == OP_JMP) {
17571 if (TRIPLE_RHS(branch->sizes) != 0) {
17572 internal_error(state, branch, "jmp with condition?");
17577 struct triple *ptr;
17578 if (TRIPLE_RHS(branch->sizes) != 1) {
17579 internal_error(state, branch, "jmpcc without condition?");
17581 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
17582 if ((RHS(branch, 0)->op != OP_CMP) &&
17583 (RHS(branch, 0)->op != OP_TEST)) {
17584 internal_error(state, branch, "bad branch test");
17586 #warning "FIXME I have observed instructions between the test and branch instructions"
17587 ptr = RHS(branch, 0);
17588 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
17589 if (ptr->op != OP_COPY) {
17590 internal_error(state, branch, "branch does not follow test");
17593 switch(branch->op) {
17594 case OP_JMP_EQ: bop = "jz"; break;
17595 case OP_JMP_NOTEQ: bop = "jnz"; break;
17596 case OP_JMP_SLESS: bop = "jl"; break;
17597 case OP_JMP_ULESS: bop = "jb"; break;
17598 case OP_JMP_SMORE: bop = "jg"; break;
17599 case OP_JMP_UMORE: bop = "ja"; break;
17600 case OP_JMP_SLESSEQ: bop = "jle"; break;
17601 case OP_JMP_ULESSEQ: bop = "jbe"; break;
17602 case OP_JMP_SMOREEQ: bop = "jge"; break;
17603 case OP_JMP_UMOREEQ: bop = "jae"; break;
17605 internal_error(state, branch, "Invalid branch op");
17610 fprintf(fp, "\t%s L%s%lu\n",
17612 state->label_prefix,
17613 TARG(branch, 0)->u.cval);
17616 static void print_op_set(struct compile_state *state,
17617 struct triple *set, FILE *fp)
17619 const char *sop = "set";
17620 if (TRIPLE_RHS(set->sizes) != 1) {
17621 internal_error(state, set, "setcc without condition?");
17623 check_reg(state, RHS(set, 0), REGCM_FLAGS);
17624 if ((RHS(set, 0)->op != OP_CMP) &&
17625 (RHS(set, 0)->op != OP_TEST)) {
17626 internal_error(state, set, "bad set test");
17628 if (RHS(set, 0)->next != set) {
17629 internal_error(state, set, "set does not follow test");
17632 case OP_SET_EQ: sop = "setz"; break;
17633 case OP_SET_NOTEQ: sop = "setnz"; break;
17634 case OP_SET_SLESS: sop = "setl"; break;
17635 case OP_SET_ULESS: sop = "setb"; break;
17636 case OP_SET_SMORE: sop = "setg"; break;
17637 case OP_SET_UMORE: sop = "seta"; break;
17638 case OP_SET_SLESSEQ: sop = "setle"; break;
17639 case OP_SET_ULESSEQ: sop = "setbe"; break;
17640 case OP_SET_SMOREEQ: sop = "setge"; break;
17641 case OP_SET_UMOREEQ: sop = "setae"; break;
17643 internal_error(state, set, "Invalid set op");
17646 fprintf(fp, "\t%s %s\n",
17647 sop, reg(state, set, REGCM_GPR8_LO));
17650 static void print_op_bit_scan(struct compile_state *state,
17651 struct triple *ins, FILE *fp)
17655 case OP_BSF: op = "bsf"; break;
17656 case OP_BSR: op = "bsr"; break;
17658 internal_error(state, ins, "unknown bit scan");
17668 reg(state, RHS(ins, 0), REGCM_GPR32),
17669 reg(state, ins, REGCM_GPR32),
17670 reg(state, ins, REGCM_GPR32));
17674 static void print_sdecl(struct compile_state *state,
17675 struct triple *ins, FILE *fp)
17677 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
17678 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
17679 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17680 print_const(state, MISC(ins, 0), fp);
17681 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17685 static void print_instruction(struct compile_state *state,
17686 struct triple *ins, FILE *fp)
17688 /* Assumption: after I have exted the register allocator
17689 * everything is in a valid register.
17693 print_op_asm(state, ins, fp);
17695 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
17696 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
17697 case OP_AND: print_binary_op(state, "and", ins, fp); break;
17698 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
17699 case OP_OR: print_binary_op(state, "or", ins, fp); break;
17700 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
17701 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
17702 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
17703 case OP_POS: break;
17704 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
17705 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
17709 /* Don't generate anything here for constants */
17711 /* Don't generate anything for variable declarations. */
17714 print_sdecl(state, ins, fp);
17717 print_op_move(state, ins, fp);
17720 print_op_load(state, ins, fp);
17723 print_op_store(state, ins, fp);
17726 print_op_smul(state, ins, fp);
17728 case OP_CMP: print_op_cmp(state, ins, fp); break;
17729 case OP_TEST: print_op_test(state, ins, fp); break;
17731 case OP_JMP_EQ: case OP_JMP_NOTEQ:
17732 case OP_JMP_SLESS: case OP_JMP_ULESS:
17733 case OP_JMP_SMORE: case OP_JMP_UMORE:
17734 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
17735 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
17736 print_op_branch(state, ins, fp);
17738 case OP_SET_EQ: case OP_SET_NOTEQ:
17739 case OP_SET_SLESS: case OP_SET_ULESS:
17740 case OP_SET_SMORE: case OP_SET_UMORE:
17741 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
17742 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
17743 print_op_set(state, ins, fp);
17745 case OP_INB: case OP_INW: case OP_INL:
17746 print_op_in(state, ins, fp);
17748 case OP_OUTB: case OP_OUTW: case OP_OUTL:
17749 print_op_out(state, ins, fp);
17753 print_op_bit_scan(state, ins, fp);
17756 after_lhs(state, ins);
17757 fprintf(fp, "\trdmsr\n");
17760 fprintf(fp, "\twrmsr\n");
17763 fprintf(fp, "\thlt\n");
17766 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17769 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17772 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17778 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17780 /* Ignore OP_PIECE */
17783 /* Operations that should never get here */
17784 case OP_SDIV: case OP_UDIV:
17785 case OP_SMOD: case OP_UMOD:
17786 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
17787 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
17788 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
17790 internal_error(state, ins, "unknown op: %d %s",
17791 ins->op, tops(ins->op));
17796 static void print_instructions(struct compile_state *state)
17798 struct triple *first, *ins;
17799 int print_location;
17800 struct occurance *last_occurance;
17802 int max_inline_depth;
17803 max_inline_depth = 0;
17804 print_location = 1;
17805 last_occurance = 0;
17806 fp = state->output;
17807 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17808 first = RHS(state->main_function, 0);
17811 if (print_location &&
17812 last_occurance != ins->occurance) {
17813 if (!ins->occurance->parent) {
17814 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17815 ins->occurance->function,
17816 ins->occurance->filename,
17817 ins->occurance->line,
17818 ins->occurance->col);
17821 struct occurance *ptr;
17823 fprintf(fp, "\t/*\n");
17825 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17827 fprintf(fp, "\t * %s,%s:%d.%d\n",
17833 fprintf(fp, "\t */\n");
17834 if (inline_depth > max_inline_depth) {
17835 max_inline_depth = inline_depth;
17838 if (last_occurance) {
17839 put_occurance(last_occurance);
17841 get_occurance(ins->occurance);
17842 last_occurance = ins->occurance;
17845 print_instruction(state, ins, fp);
17847 } while(ins != first);
17848 if (print_location) {
17849 fprintf(fp, "/* max inline depth %d */\n",
17854 static void generate_code(struct compile_state *state)
17856 generate_local_labels(state);
17857 print_instructions(state);
17861 static void print_tokens(struct compile_state *state)
17864 tk = &state->token[0];
17869 next_token(state, 0);
17871 loc(stdout, state, 0);
17872 printf("%s <- `%s'\n",
17874 tk->ident ? tk->ident->name :
17875 tk->str_len ? tk->val.str : "");
17877 } while(tk->tok != TOK_EOF);
17880 static void compile(const char *filename, const char *ofilename,
17881 int cpu, int debug, int opt, const char *label_prefix)
17884 struct compile_state state;
17885 memset(&state, 0, sizeof(state));
17887 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17888 memset(&state.token[i], 0, sizeof(state.token[i]));
17889 state.token[i].tok = -1;
17891 /* Remember the debug settings */
17893 state.debug = debug;
17894 state.optimize = opt;
17895 /* Remember the output filename */
17896 state.ofilename = ofilename;
17897 state.output = fopen(state.ofilename, "w");
17898 if (!state.output) {
17899 error(&state, 0, "Cannot open output file %s\n",
17902 /* Remember the label prefix */
17903 state.label_prefix = label_prefix;
17904 /* Prep the preprocessor */
17905 state.if_depth = 0;
17906 state.if_value = 0;
17907 /* register the C keywords */
17908 register_keywords(&state);
17909 /* register the keywords the macro preprocessor knows */
17910 register_macro_keywords(&state);
17911 /* Memorize where some special keywords are. */
17912 state.i_continue = lookup(&state, "continue", 8);
17913 state.i_break = lookup(&state, "break", 5);
17914 /* Enter the globl definition scope */
17915 start_scope(&state);
17916 register_builtins(&state);
17917 compile_file(&state, filename, 1);
17919 print_tokens(&state);
17922 /* Exit the global definition scope */
17925 /* Now that basic compilation has happened
17926 * optimize the intermediate code
17930 generate_code(&state);
17932 fprintf(stderr, "done\n");
17936 static void version(void)
17938 printf("romcc " VERSION " released " RELEASE_DATE "\n");
17941 static void usage(void)
17945 "Usage: romcc <source>.c\n"
17946 "Compile a C source file without using ram\n"
17950 static void arg_error(char *fmt, ...)
17953 va_start(args, fmt);
17954 vfprintf(stderr, fmt, args);
17960 int main(int argc, char **argv)
17962 const char *filename;
17963 const char *ofilename;
17964 const char *label_prefix;
17971 ofilename = "auto.inc";
17975 while((argc > 1) && (argc != last_argc)) {
17977 if (strncmp(argv[1], "--debug=", 8) == 0) {
17978 debug = atoi(argv[1] + 8);
17982 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17983 label_prefix= argv[1] + 15;
17987 else if ((strcmp(argv[1],"-O") == 0) ||
17988 (strcmp(argv[1], "-O1") == 0)) {
17993 else if (strcmp(argv[1],"-O2") == 0) {
17998 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17999 ofilename = argv[2];
18003 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
18004 cpu = arch_encode_cpu(argv[1] + 6);
18005 if (cpu == BAD_CPU) {
18006 arg_error("Invalid cpu specified: %s\n",
18014 arg_error("Wrong argument count %d\n", argc);
18016 filename = argv[1];
18017 compile(filename, ofilename, cpu, debug, optimize, label_prefix);