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"
26 #warning "FIXME fix scc_transform"
28 /* Control flow graph of a loop without goto.
39 * |\ GGG HHH | continue;
67 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
68 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
71 * [] == DFlocal(X) U DF(X)
74 * Dominator graph of the same nodes.
78 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
80 * CCC CCC: [ ] ( BBB, JJJ )
82 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
84 * FFF FFF: [ ] ( BBB )
86 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
91 * BBB and JJJ are definitely the dominance frontier.
92 * Where do I place phi functions and how do I make that decision.
95 static void die(char *fmt, ...)
100 vfprintf(stderr, fmt, args);
107 #define MALLOC_STRONG_DEBUG
108 static void *xmalloc(size_t size, const char *name)
113 die("Cannot malloc %ld bytes to hold %s: %s\n",
114 size + 0UL, name, strerror(errno));
119 static void *xcmalloc(size_t size, const char *name)
122 buf = xmalloc(size, name);
123 memset(buf, 0, size);
127 static void xfree(const void *ptr)
132 static char *xstrdup(const char *str)
137 new = xmalloc(len + 1, "xstrdup string");
138 memcpy(new, str, len);
143 static void xchdir(const char *path)
145 if (chdir(path) != 0) {
146 die("chdir to %s failed: %s\n",
147 path, strerror(errno));
151 static int exists(const char *dirname, const char *filename)
155 if (access(filename, O_RDONLY) < 0) {
156 if ((errno != EACCES) && (errno != EROFS)) {
164 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
168 off_t size, progress;
177 fd = open(filename, O_RDONLY);
179 die("Cannot open '%s' : %s\n",
180 filename, strerror(errno));
182 result = fstat(fd, &stats);
184 die("Cannot stat: %s: %s\n",
185 filename, strerror(errno));
187 size = stats.st_size;
189 buf = xmalloc(size +2, filename);
190 buf[size] = '\n'; /* Make certain the file is newline terminated */
191 buf[size+1] = '\0'; /* Null terminate the file for good measure */
193 while(progress < size) {
194 result = read(fd, buf + progress, size - progress);
196 if ((errno == EINTR) || (errno == EAGAIN))
198 die("read on %s of %ld bytes failed: %s\n",
199 filename, (size - progress)+ 0UL, strerror(errno));
205 die("Close of %s failed: %s\n",
206 filename, strerror(errno));
211 /* Long on the destination platform */
212 typedef unsigned long ulong_t;
216 struct file_state *prev;
217 const char *basename;
225 const char *report_name;
226 const char *report_dir;
231 struct hash_entry *ident;
239 /* I have two classes of types:
241 * Logical types. (The type the C standard says the operation is of)
243 * The operational types are:
258 * No memory is useable by the compiler.
259 * There is no floating point support.
260 * All operations take place in general purpose registers.
261 * There is one type of general purpose register.
262 * Unsigned longs are stored in that general purpose register.
265 /* Operations on general purpose registers.
284 #define OP_POS 16 /* Dummy positive operator don't use it */
294 #define OP_SLESSEQ 26
295 #define OP_ULESSEQ 27
296 #define OP_SMOREEQ 28
297 #define OP_UMOREEQ 29
299 #define OP_LFALSE 30 /* Test if the expression is logically false */
300 #define OP_LTRUE 31 /* Test if the expression is logcially true */
304 /* For OP_STORE ->type holds the type
305 * RHS(0) holds the destination address
306 * RHS(1) holds the value to store.
311 #define OP_MIN_CONST 50
312 #define OP_MAX_CONST 59
313 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
314 #define OP_INTCONST 50
315 /* For OP_INTCONST ->type holds the type.
316 * ->u.cval holds the constant value.
318 #define OP_BLOBCONST 51
319 /* For OP_BLOBCONST ->type holds the layout and size
320 * information. u.blob holds a pointer to the raw binary
321 * data for the constant initializer.
323 #define OP_ADDRCONST 52
324 /* For OP_ADDRCONST ->type holds the type.
325 * MISC(0) holds the reference to the static variable.
326 * ->u.cval holds an offset from that value.
330 /* OP_WRITE moves one pseudo register to another.
331 * RHS(0) holds the destination pseudo register, which must be an OP_DECL.
332 * RHS(1) holds the psuedo to move.
336 /* OP_READ reads the value of a variable and makes
337 * it available for the pseudo operation.
338 * Useful for things like def-use chains.
339 * RHS(0) holds points to the triple to read from.
342 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
345 /* OP_PIECE returns one piece of a instruction that returns a structure.
346 * MISC(0) is the instruction
347 * u.cval is the LHS piece of the instruction to return.
350 /* OP_ASM holds a sequence of assembly instructions, the result
351 * of a C asm directive.
352 * RHS(x) holds input value x to the assembly sequence.
353 * LHS(x) holds the output value x from the assembly sequence.
354 * u.blob holds the string of assembly instructions.
358 /* OP_DEREF generates an lvalue from a pointer.
359 * RHS(0) holds the pointer value.
360 * OP_DEREF serves as a place holder to indicate all necessary
361 * checks have been done to indicate a value is an lvalue.
364 /* OP_DOT references a submember of a structure lvalue.
365 * RHS(0) holds the lvalue.
366 * ->u.field holds the name of the field we want.
368 * Not seen outside of expressions.
371 /* OP_VAL returns the value of a subexpression of the current expression.
372 * Useful for operators that have side effects.
373 * RHS(0) holds the expression.
374 * MISC(0) holds the subexpression of RHS(0) that is the
375 * value of the expression.
377 * Not seen outside of expressions.
380 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
381 * Not seen outside of expressions.
384 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
385 * Not seen outside of expressions.
388 /* OP_CODE performas a C ? : operation.
389 * RHS(0) holds the test.
390 * RHS(1) holds the expression to evaluate if the test returns true.
391 * RHS(2) holds the expression to evaluate if the test returns false.
392 * Not seen outside of expressions.
395 /* OP_COMMA performacs a C comma operation.
396 * That is RHS(0) is evaluated, then RHS(1)
397 * and the value of RHS(1) is returned.
398 * Not seen outside of expressions.
402 /* OP_CALL performs a procedure call.
403 * MISC(0) holds a pointer to the OP_LIST of a function
404 * RHS(x) holds argument x of a function
406 * Currently not seen outside of expressions.
408 #define OP_VAL_VEC 74
409 /* OP_VAL_VEC is an array of triples that are either variable
410 * or values for a structure or an array.
411 * RHS(x) holds element x of the vector.
412 * triple->type->elements holds the size of the vector.
417 /* OP_LIST Holds a list of statements, and a result value.
418 * RHS(0) holds the list of statements.
419 * MISC(0) holds the value of the statements.
422 #define OP_BRANCH 81 /* branch */
423 /* For branch instructions
424 * TARG(0) holds the branch target.
425 * RHS(0) if present holds the branch condition.
426 * ->next holds where to branch to if the branch is not taken.
427 * The branch target can only be a decl...
431 /* OP_LABEL is a triple that establishes an target for branches.
432 * ->use is the list of all branches that use this label.
436 /* OP_DECL is a triple that establishes an lvalue for assignments.
437 * ->use is a list of statements that use the variable.
441 /* OP_SDECL is a triple that establishes a variable of static
443 * ->use is a list of statements that use the variable.
444 * MISC(0) holds the initializer expression.
449 /* OP_PHI is a triple used in SSA form code.
450 * It is used when multiple code paths merge and a variable needs
451 * a single assignment from any of those code paths.
452 * The operation is a cross between OP_DECL and OP_WRITE, which
453 * is what OP_PHI is geneared from.
455 * RHS(x) points to the value from code path x
456 * The number of RHS entries is the number of control paths into the block
457 * in which OP_PHI resides. The elements of the array point to point
458 * to the variables OP_PHI is derived from.
460 * MISC(0) holds a pointer to the orginal OP_DECL node.
463 /* Architecture specific instructions */
466 #define OP_SET_EQ 102
467 #define OP_SET_NOTEQ 103
468 #define OP_SET_SLESS 104
469 #define OP_SET_ULESS 105
470 #define OP_SET_SMORE 106
471 #define OP_SET_UMORE 107
472 #define OP_SET_SLESSEQ 108
473 #define OP_SET_ULESSEQ 109
474 #define OP_SET_SMOREEQ 110
475 #define OP_SET_UMOREEQ 111
478 #define OP_JMP_EQ 113
479 #define OP_JMP_NOTEQ 114
480 #define OP_JMP_SLESS 115
481 #define OP_JMP_ULESS 116
482 #define OP_JMP_SMORE 117
483 #define OP_JMP_UMORE 118
484 #define OP_JMP_SLESSEQ 119
485 #define OP_JMP_ULESSEQ 120
486 #define OP_JMP_SMOREEQ 121
487 #define OP_JMP_UMOREEQ 122
489 /* Builtin operators that it is just simpler to use the compiler for */
507 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
509 #define BLOCK 8 /* Triple stores the current block */
510 unsigned char lhs, rhs, misc, targ;
513 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
521 static const struct op_info table_ops[] = {
522 [OP_SDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "sdivt"),
523 [OP_UDIVT ] = OP( 2, 2, 0, 0, PURE | BLOCK , "udivt"),
524 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
525 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
526 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
527 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
528 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
529 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
530 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
531 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
532 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
533 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
534 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
535 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
536 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
537 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
538 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
539 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
540 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
542 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
543 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
544 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
545 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
546 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
547 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
548 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
549 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
550 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
551 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
552 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
553 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
555 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "load"),
556 [OP_STORE ] = OP( 0, 2, 0, 0, IMPURE | BLOCK , "store"),
558 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK, "noop"),
560 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
561 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
562 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
564 [OP_WRITE ] = OP( 0, 2, 0, 0, PURE | BLOCK, "write"),
565 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
566 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
567 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF, "piece"),
568 [OP_ASM ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
569 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
570 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "dot"),
572 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
573 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "land"),
574 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "lor"),
575 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF | BLOCK, "cond"),
576 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "comma"),
577 /* Call is special most it can stand in for anything so it depends on context */
578 [OP_CALL ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
579 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
580 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
582 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
583 /* The number of targets for OP_BRANCH depends on context */
584 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
585 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "label"),
586 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "adecl"),
587 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK, "sdecl"),
588 /* The number of RHS elements of OP_PHI depend upon context */
589 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
591 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
592 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
593 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
594 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
595 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
596 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
597 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
598 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
599 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
600 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
601 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
602 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
603 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK, "jmp"),
604 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_eq"),
605 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_noteq"),
606 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_sless"),
607 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_uless"),
608 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smore"),
609 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umore"),
610 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
611 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
612 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
613 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
615 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
616 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
617 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
618 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
619 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
620 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
621 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
622 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
623 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
624 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
625 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
628 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
630 static const char *tops(int index)
632 static const char unknown[] = "unknown op";
636 if (index > OP_MAX) {
639 return table_ops[index].name;
646 struct triple_set *next;
647 struct triple *member;
657 const char *filename;
658 const char *function;
661 struct occurance *parent;
664 struct triple *next, *prev;
665 struct triple_set *use;
668 unsigned char template_id;
669 unsigned short sizes;
670 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
671 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0xff)
672 #define TRIPLE_MISC(SIZES) (((SIZES) >> 12) & 0x03)
673 #define TRIPLE_TARG(SIZES) (((SIZES) >> 14) & 0x03)
674 #define TRIPLE_SIZE(SIZES) \
675 (TRIPLE_LHS(SIZES) + \
676 TRIPLE_RHS(SIZES) + \
677 TRIPLE_MISC(SIZES) + \
679 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
680 ((((LHS) & 0x0f) << 0) | \
681 (((RHS) & 0xff) << 4) | \
682 (((MISC) & 0x03) << 12) | \
683 (((TARG) & 0x03) << 14))
684 #define TRIPLE_LHS_OFF(SIZES) (0)
685 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
686 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
687 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
688 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
689 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
690 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
691 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
692 unsigned id; /* A scratch value and finally the register */
693 #define TRIPLE_FLAG_FLATTENED (1 << 31)
694 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
695 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
696 struct occurance *occurance;
701 struct hash_entry *field;
702 struct asm_info *ainfo;
704 struct triple *param[2];
711 struct ins_template {
712 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
716 struct ins_template tmpl;
721 struct block_set *next;
722 struct block *member;
725 struct block *work_next;
726 struct block *left, *right;
727 struct triple *first, *last;
729 struct block_set *use;
730 struct block_set *idominates;
731 struct block_set *domfrontier;
733 struct block_set *ipdominates;
734 struct block_set *ipdomfrontier;
742 struct hash_entry *ident;
749 struct hash_entry *ident;
755 struct hash_entry *next;
759 struct macro *sym_define;
760 struct symbol *sym_label;
761 struct symbol *sym_struct;
762 struct symbol *sym_ident;
765 #define HASH_TABLE_SIZE 2048
767 struct compile_state {
768 const char *label_prefix;
769 const char *ofilename;
771 struct file_state *file;
772 struct occurance *last_occurance;
773 const char *function;
774 struct token token[4];
775 struct hash_entry *hash_table[HASH_TABLE_SIZE];
776 struct hash_entry *i_continue;
777 struct hash_entry *i_break;
779 int if_depth, if_value;
781 struct file_state *macro_file;
782 struct triple *main_function;
783 struct block *first_block, *last_block;
790 /* visibility global/local */
791 /* static/auto duration */
792 /* typedef, register, inline */
794 #define STOR_MASK 0x000f
796 #define STOR_GLOBAL 0x0001
798 #define STOR_PERM 0x0002
799 /* Storage specifiers */
800 #define STOR_AUTO 0x0000
801 #define STOR_STATIC 0x0002
802 #define STOR_EXTERN 0x0003
803 #define STOR_REGISTER 0x0004
804 #define STOR_TYPEDEF 0x0008
805 #define STOR_INLINE 0x000c
808 #define QUAL_MASK 0x0070
809 #define QUAL_NONE 0x0000
810 #define QUAL_CONST 0x0010
811 #define QUAL_VOLATILE 0x0020
812 #define QUAL_RESTRICT 0x0040
815 #define TYPE_MASK 0x1f00
816 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
817 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
818 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
819 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
820 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
821 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
822 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
823 #define TYPE_DEFAULT 0x0000
824 #define TYPE_VOID 0x0100
825 #define TYPE_CHAR 0x0200
826 #define TYPE_UCHAR 0x0300
827 #define TYPE_SHORT 0x0400
828 #define TYPE_USHORT 0x0500
829 #define TYPE_INT 0x0600
830 #define TYPE_UINT 0x0700
831 #define TYPE_LONG 0x0800
832 #define TYPE_ULONG 0x0900
833 #define TYPE_LLONG 0x0a00 /* long long */
834 #define TYPE_ULLONG 0x0b00
835 #define TYPE_FLOAT 0x0c00
836 #define TYPE_DOUBLE 0x0d00
837 #define TYPE_LDOUBLE 0x0e00 /* long double */
838 #define TYPE_STRUCT 0x1000
839 #define TYPE_ENUM 0x1100
840 #define TYPE_POINTER 0x1200
842 * type->left holds the type pointed to.
844 #define TYPE_FUNCTION 0x1300
845 /* For TYPE_FUNCTION:
846 * type->left holds the return type.
847 * type->right holds the...
849 #define TYPE_PRODUCT 0x1400
850 /* TYPE_PRODUCT is a basic building block when defining structures
851 * type->left holds the type that appears first in memory.
852 * type->right holds the type that appears next in memory.
854 #define TYPE_OVERLAP 0x1500
855 /* TYPE_OVERLAP is a basic building block when defining unions
856 * type->left and type->right holds to types that overlap
857 * each other in memory.
859 #define TYPE_ARRAY 0x1600
860 /* TYPE_ARRAY is a basic building block when definitng arrays.
861 * type->left holds the type we are an array of.
862 * type-> holds the number of elements.
865 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
869 struct type *left, *right;
871 struct hash_entry *field_ident;
872 struct hash_entry *type_ident;
875 #define MAX_REGISTERS 75
876 #define MAX_REG_EQUIVS 16
877 #define REGISTER_BITS 16
878 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
879 #define TEMPLATE_BITS 7
880 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
883 #define REG_UNNEEDED 1
884 #define REG_VIRT0 (MAX_REGISTERS + 0)
885 #define REG_VIRT1 (MAX_REGISTERS + 1)
886 #define REG_VIRT2 (MAX_REGISTERS + 2)
887 #define REG_VIRT3 (MAX_REGISTERS + 3)
888 #define REG_VIRT4 (MAX_REGISTERS + 4)
889 #define REG_VIRT5 (MAX_REGISTERS + 5)
890 #define REG_VIRT6 (MAX_REGISTERS + 5)
891 #define REG_VIRT7 (MAX_REGISTERS + 5)
892 #define REG_VIRT8 (MAX_REGISTERS + 5)
893 #define REG_VIRT9 (MAX_REGISTERS + 5)
895 /* Provision for 8 register classes */
897 #define REGC_SHIFT REGISTER_BITS
898 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
899 #define REG_MASK (MAX_VIRT_REGISTERS -1)
900 #define ID_REG(ID) ((ID) & REG_MASK)
901 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
902 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
903 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
904 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
905 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
907 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
908 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
909 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
910 static void arch_reg_equivs(
911 struct compile_state *state, unsigned *equiv, int reg);
912 static int arch_select_free_register(
913 struct compile_state *state, char *used, int classes);
914 static unsigned arch_regc_size(struct compile_state *state, int class);
915 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
916 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
917 static const char *arch_reg_str(int reg);
918 static struct reg_info arch_reg_constraint(
919 struct compile_state *state, struct type *type, const char *constraint);
920 static struct reg_info arch_reg_clobber(
921 struct compile_state *state, const char *clobber);
922 static struct reg_info arch_reg_lhs(struct compile_state *state,
923 struct triple *ins, int index);
924 static struct reg_info arch_reg_rhs(struct compile_state *state,
925 struct triple *ins, int index);
926 static struct triple *transform_to_arch_instruction(
927 struct compile_state *state, struct triple *ins);
931 #define DEBUG_ABORT_ON_ERROR 0x0001
932 #define DEBUG_INTERMEDIATE_CODE 0x0002
933 #define DEBUG_CONTROL_FLOW 0x0004
934 #define DEBUG_BASIC_BLOCKS 0x0008
935 #define DEBUG_FDOMINATORS 0x0010
936 #define DEBUG_RDOMINATORS 0x0020
937 #define DEBUG_TRIPLES 0x0040
938 #define DEBUG_INTERFERENCE 0x0080
939 #define DEBUG_ARCH_CODE 0x0100
940 #define DEBUG_CODE_ELIMINATION 0x0200
941 #define DEBUG_INSERTED_COPIES 0x0400
943 #define GLOBAL_SCOPE_DEPTH 1
944 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
946 static void compile_file(struct compile_state *old_state, const char *filename, int local);
948 static void do_cleanup(struct compile_state *state)
951 fclose(state->output);
952 unlink(state->ofilename);
956 static int get_col(struct file_state *file)
960 ptr = file->line_start;
962 for(col = 0; ptr < end; ptr++) {
967 col = (col & ~7) + 8;
973 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
976 if (triple && triple->occurance) {
977 struct occurance *spot;
978 spot = triple->occurance;
979 while(spot->parent) {
982 fprintf(fp, "%s:%d.%d: ",
983 spot->filename, spot->line, spot->col);
989 col = get_col(state->file);
990 fprintf(fp, "%s:%d.%d: ",
991 state->file->report_name, state->file->report_line, col);
994 static void __internal_error(struct compile_state *state, struct triple *ptr,
999 loc(stderr, state, ptr);
1001 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
1003 fprintf(stderr, "Internal compiler error: ");
1004 vfprintf(stderr, fmt, args);
1005 fprintf(stderr, "\n");
1012 static void __internal_warning(struct compile_state *state, struct triple *ptr,
1016 va_start(args, fmt);
1017 loc(stderr, state, ptr);
1018 fprintf(stderr, "Internal compiler warning: ");
1019 vfprintf(stderr, fmt, args);
1020 fprintf(stderr, "\n");
1026 static void __error(struct compile_state *state, struct triple *ptr,
1030 va_start(args, fmt);
1031 loc(stderr, state, ptr);
1032 vfprintf(stderr, fmt, args);
1034 fprintf(stderr, "\n");
1036 if (state->debug & DEBUG_ABORT_ON_ERROR) {
1042 static void __warning(struct compile_state *state, struct triple *ptr,
1046 va_start(args, fmt);
1047 loc(stderr, state, ptr);
1048 fprintf(stderr, "warning: ");
1049 vfprintf(stderr, fmt, args);
1050 fprintf(stderr, "\n");
1054 #if DEBUG_ERROR_MESSAGES
1055 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1056 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1057 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1058 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1060 # define internal_error __internal_error
1061 # define internal_warning __internal_warning
1062 # define error __error
1063 # define warning __warning
1065 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1067 static void valid_op(struct compile_state *state, int op)
1069 char *fmt = "invalid op: %d";
1071 internal_error(state, 0, fmt, op);
1074 internal_error(state, 0, fmt, op);
1078 static void valid_ins(struct compile_state *state, struct triple *ptr)
1080 valid_op(state, ptr->op);
1083 static void process_trigraphs(struct compile_state *state)
1085 char *src, *dest, *end;
1086 struct file_state *file;
1088 src = dest = file->buf;
1089 end = file->buf + file->size;
1090 while((end - src) >= 3) {
1091 if ((src[0] == '?') && (src[1] == '?')) {
1094 case '=': c = '#'; break;
1095 case '/': c = '\\'; break;
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;
1119 file->size = dest - file->buf;
1122 static void splice_lines(struct compile_state *state)
1124 char *src, *dest, *end;
1125 struct file_state *file;
1127 src = dest = file->buf;
1128 end = file->buf + file->size;
1129 while((end - src) >= 2) {
1130 if ((src[0] == '\\') && (src[1] == '\n')) {
1140 file->size = dest - file->buf;
1143 static struct type void_type;
1144 static void use_triple(struct triple *used, struct triple *user)
1146 struct triple_set **ptr, *new;
1153 if ((*ptr)->member == user) {
1156 ptr = &(*ptr)->next;
1158 /* Append new to the head of the list,
1159 * copy_func and rename_block_variables
1162 new = xcmalloc(sizeof(*new), "triple_set");
1164 new->next = used->use;
1168 static void unuse_triple(struct triple *used, struct triple *unuser)
1170 struct triple_set *use, **ptr;
1177 if (use->member == unuser) {
1187 static void push_triple(struct triple *used, struct triple *user)
1189 struct triple_set *new;
1194 /* Append new to the head of the list,
1195 * it's the only sensible behavoir for a stack.
1197 new = xcmalloc(sizeof(*new), "triple_set");
1199 new->next = used->use;
1203 static void pop_triple(struct triple *used, struct triple *unuser)
1205 struct triple_set *use, **ptr;
1209 if (use->member == unuser) {
1212 /* Only free one occurance from the stack */
1221 static void put_occurance(struct occurance *occurance)
1223 occurance->count -= 1;
1224 if (occurance->count <= 0) {
1225 if (occurance->parent) {
1226 put_occurance(occurance->parent);
1232 static void get_occurance(struct occurance *occurance)
1234 occurance->count += 1;
1238 static struct occurance *new_occurance(struct compile_state *state)
1240 struct occurance *result, *last;
1241 const char *filename;
1242 const char *function;
1250 filename = state->file->report_name;
1251 line = state->file->report_line;
1252 col = get_col(state->file);
1254 if (state->function) {
1255 function = state->function;
1257 last = state->last_occurance;
1259 (last->col == col) &&
1260 (last->line == line) &&
1261 (last->function == function) &&
1262 (strcmp(last->filename, filename) == 0)) {
1263 get_occurance(last);
1267 state->last_occurance = 0;
1268 put_occurance(last);
1270 result = xmalloc(sizeof(*result), "occurance");
1272 result->filename = filename;
1273 result->function = function;
1274 result->line = line;
1277 state->last_occurance = result;
1281 static struct occurance *inline_occurance(struct compile_state *state,
1282 struct occurance *new, struct occurance *orig)
1284 struct occurance *result, *last;
1285 last = state->last_occurance;
1287 (last->parent == orig) &&
1288 (last->col == new->col) &&
1289 (last->line == new->line) &&
1290 (last->function == new->function) &&
1291 (last->filename == new->filename)) {
1292 get_occurance(last);
1296 state->last_occurance = 0;
1297 put_occurance(last);
1299 get_occurance(orig);
1300 result = xmalloc(sizeof(*result), "occurance");
1302 result->filename = new->filename;
1303 result->function = new->function;
1304 result->line = new->line;
1305 result->col = new->col;
1306 result->parent = orig;
1307 state->last_occurance = result;
1312 static struct occurance dummy_occurance = {
1314 .filename = __FILE__,
1321 /* The zero triple is used as a place holder when we are removing pointers
1322 * from a triple. Having allows certain sanity checks to pass even
1323 * when the original triple that was pointed to is gone.
1325 static struct triple zero_triple = {
1326 .next = &zero_triple,
1327 .prev = &zero_triple,
1330 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1331 .id = -1, /* An invalid id */
1332 .u = { .cval = 0, },
1333 .occurance = &dummy_occurance,
1334 .param { [0] = 0, [1] = 0, },
1338 static unsigned short triple_sizes(struct compile_state *state,
1339 int op, struct type *type, int lhs_wanted, int rhs_wanted,
1340 struct occurance *occurance)
1342 int lhs, rhs, misc, targ;
1343 struct triple dummy;
1345 dummy.occurance = occurance;
1346 valid_op(state, op);
1347 lhs = table_ops[op].lhs;
1348 rhs = table_ops[op].rhs;
1349 misc = table_ops[op].misc;
1350 targ = table_ops[op].targ;
1353 if (op == OP_CALL) {
1356 param = type->right;
1357 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1359 param = param->right;
1361 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1365 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1366 lhs = type->left->elements;
1369 else if (op == OP_VAL_VEC) {
1370 rhs = type->elements;
1372 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1375 else if (op == OP_ASM) {
1379 if ((rhs < 0) || (rhs > MAX_RHS)) {
1380 internal_error(state, &dummy, "bad rhs %d", rhs);
1382 if ((lhs < 0) || (lhs > MAX_LHS)) {
1383 internal_error(state, &dummy, "bad lhs");
1385 if ((misc < 0) || (misc > MAX_MISC)) {
1386 internal_error(state, &dummy, "bad misc");
1388 if ((targ < 0) || (targ > MAX_TARG)) {
1389 internal_error(state, &dummy, "bad targs");
1391 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1394 static struct triple *alloc_triple(struct compile_state *state,
1395 int op, struct type *type, int lhs, int rhs,
1396 struct occurance *occurance)
1398 size_t size, sizes, extra_count, min_count;
1400 sizes = triple_sizes(state, op, type, lhs, rhs, occurance);
1402 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1403 extra_count = TRIPLE_SIZE(sizes);
1404 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1406 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1407 ret = xcmalloc(size, "tripple");
1413 ret->occurance = occurance;
1417 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1420 int src_lhs, src_rhs, src_size;
1421 src_lhs = TRIPLE_LHS(src->sizes);
1422 src_rhs = TRIPLE_RHS(src->sizes);
1423 src_size = TRIPLE_SIZE(src->sizes);
1424 get_occurance(src->occurance);
1425 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1427 memcpy(dup, src, sizeof(*src));
1428 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1432 static struct triple *new_triple(struct compile_state *state,
1433 int op, struct type *type, int lhs, int rhs)
1436 struct occurance *occurance;
1437 occurance = new_occurance(state);
1438 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1442 static struct triple *build_triple(struct compile_state *state,
1443 int op, struct type *type, struct triple *left, struct triple *right,
1444 struct occurance *occurance)
1448 ret = alloc_triple(state, op, type, -1, -1, occurance);
1449 count = TRIPLE_SIZE(ret->sizes);
1451 ret->param[0] = left;
1454 ret->param[1] = right;
1459 static struct triple *triple(struct compile_state *state,
1460 int op, struct type *type, struct triple *left, struct triple *right)
1464 ret = new_triple(state, op, type, -1, -1);
1465 count = TRIPLE_SIZE(ret->sizes);
1467 ret->param[0] = left;
1470 ret->param[1] = right;
1475 static struct triple *branch(struct compile_state *state,
1476 struct triple *targ, struct triple *test)
1479 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1483 TARG(ret, 0) = targ;
1484 /* record the branch target was used */
1485 if (!targ || (targ->op != OP_LABEL)) {
1486 internal_error(state, 0, "branch not to label");
1487 use_triple(targ, ret);
1493 static void insert_triple(struct compile_state *state,
1494 struct triple *first, struct triple *ptr)
1497 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1498 internal_error(state, ptr, "expression already used");
1501 ptr->prev = first->prev;
1502 ptr->prev->next = ptr;
1503 ptr->next->prev = ptr;
1504 if ((ptr->prev->op == OP_BRANCH) &&
1505 TRIPLE_RHS(ptr->prev->sizes)) {
1506 unuse_triple(first, ptr->prev);
1507 use_triple(ptr, ptr->prev);
1512 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1514 /* This function is used to determine if u.block
1515 * is utilized to store the current block number.
1518 valid_ins(state, ins);
1519 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1520 return stores_block;
1523 static struct block *block_of_triple(struct compile_state *state,
1526 struct triple *first;
1527 first = RHS(state->main_function, 0);
1528 while(ins != first && !triple_stores_block(state, ins)) {
1529 if (ins == ins->prev) {
1530 internal_error(state, 0, "ins == ins->prev?");
1534 if (!triple_stores_block(state, ins)) {
1535 internal_error(state, ins, "Cannot find block");
1537 return ins->u.block;
1540 static struct triple *pre_triple(struct compile_state *state,
1541 struct triple *base,
1542 int op, struct type *type, struct triple *left, struct triple *right)
1544 struct block *block;
1546 /* If I am an OP_PIECE jump to the real instruction */
1547 if (base->op == OP_PIECE) {
1548 base = MISC(base, 0);
1550 block = block_of_triple(state, base);
1551 get_occurance(base->occurance);
1552 ret = build_triple(state, op, type, left, right, base->occurance);
1553 if (triple_stores_block(state, ret)) {
1554 ret->u.block = block;
1556 insert_triple(state, base, ret);
1557 if (block->first == base) {
1563 static struct triple *post_triple(struct compile_state *state,
1564 struct triple *base,
1565 int op, struct type *type, struct triple *left, struct triple *right)
1567 struct block *block;
1570 /* If I am an OP_PIECE jump to the real instruction */
1571 if (base->op == OP_PIECE) {
1572 base = MISC(base, 0);
1574 /* If I have a left hand side skip over it */
1575 zlhs = TRIPLE_LHS(base->sizes);
1577 base = LHS(base, zlhs - 1);
1580 block = block_of_triple(state, base);
1581 get_occurance(base->occurance);
1582 ret = build_triple(state, op, type, left, right, base->occurance);
1583 if (triple_stores_block(state, ret)) {
1584 ret->u.block = block;
1586 insert_triple(state, base->next, ret);
1587 if (block->last == base) {
1593 static struct triple *label(struct compile_state *state)
1595 /* Labels don't get a type */
1596 struct triple *result;
1597 result = triple(state, OP_LABEL, &void_type, 0, 0);
1601 static void display_triple(FILE *fp, struct triple *ins)
1603 struct occurance *ptr;
1607 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1610 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1613 reg = arch_reg_str(ID_REG(ins->id));
1614 if (ins->op == OP_INTCONST) {
1615 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx> ",
1616 ins, pre, post, reg, ins->template_id, tops(ins->op),
1619 else if (ins->op == OP_ADDRCONST) {
1620 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1621 ins, pre, post, reg, ins->template_id, tops(ins->op),
1622 MISC(ins, 0), ins->u.cval);
1626 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s",
1627 ins, pre, post, reg, ins->template_id, tops(ins->op));
1628 count = TRIPLE_SIZE(ins->sizes);
1629 for(i = 0; i < count; i++) {
1630 fprintf(fp, " %-10p", ins->param[i]);
1637 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1638 fprintf(fp, " %s,%s:%d.%d",
1647 struct triple_set *user;
1648 for(user = ptr->use; user; user = user->next) {
1649 fprintf(fp, "use: %p\n", user->member);
1656 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1658 /* Does the triple have no side effects.
1659 * I.e. Rexecuting the triple with the same arguments
1660 * gives the same value.
1663 valid_ins(state, ins);
1664 pure = PURE_BITS(table_ops[ins->op].flags);
1665 if ((pure != PURE) && (pure != IMPURE)) {
1666 internal_error(state, 0, "Purity of %s not known\n",
1669 return pure == PURE;
1672 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1674 /* This function is used to determine which triples need
1678 valid_ins(state, ins);
1679 is_branch = (table_ops[ins->op].targ != 0);
1683 static int triple_is_cond_branch(struct compile_state *state, struct triple *ins)
1685 /* A conditional branch has the condition argument as a single
1688 return triple_is_branch(state, ins) &&
1689 (TRIPLE_RHS(ins->sizes) == 1);
1692 static int triple_is_uncond_branch(struct compile_state *state, struct triple *ins)
1694 /* A unconditional branch has no RHS parameters.
1696 return triple_is_branch(state, ins) &&
1697 (TRIPLE_RHS(ins->sizes) == 0);
1700 static int triple_is_def(struct compile_state *state, struct triple *ins)
1702 /* This function is used to determine which triples need
1706 valid_ins(state, ins);
1707 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1711 static struct triple **triple_iter(struct compile_state *state,
1712 size_t count, struct triple **vector,
1713 struct triple *ins, struct triple **last)
1715 struct triple **ret;
1721 else if ((last >= vector) && (last < (vector + count - 1))) {
1729 static struct triple **triple_lhs(struct compile_state *state,
1730 struct triple *ins, struct triple **last)
1732 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1736 static struct triple **triple_rhs(struct compile_state *state,
1737 struct triple *ins, struct triple **last)
1739 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1743 static struct triple **triple_misc(struct compile_state *state,
1744 struct triple *ins, struct triple **last)
1746 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1750 static struct triple **triple_targ(struct compile_state *state,
1751 struct triple *ins, struct triple **last)
1754 struct triple **ret, **vector;
1756 count = TRIPLE_TARG(ins->sizes);
1757 vector = &TARG(ins, 0);
1762 else if ((last >= vector) && (last < (vector + count - 1))) {
1765 else if ((last == (vector + count - 1)) &&
1766 TRIPLE_RHS(ins->sizes)) {
1774 static void verify_use(struct compile_state *state,
1775 struct triple *user, struct triple *used)
1778 size = TRIPLE_SIZE(user->sizes);
1779 for(i = 0; i < size; i++) {
1780 if (user->param[i] == used) {
1784 if (triple_is_branch(state, user)) {
1785 if (user->next == used) {
1790 internal_error(state, user, "%s(%p) does not use %s(%p)",
1791 tops(user->op), user, tops(used->op), used);
1795 static int find_rhs_use(struct compile_state *state,
1796 struct triple *user, struct triple *used)
1798 struct triple **param;
1800 verify_use(state, user, used);
1801 size = TRIPLE_RHS(user->sizes);
1802 param = &RHS(user, 0);
1803 for(i = 0; i < size; i++) {
1804 if (param[i] == used) {
1811 static void free_triple(struct compile_state *state, struct triple *ptr)
1814 size = sizeof(*ptr) - sizeof(ptr->param) +
1815 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1816 ptr->prev->next = ptr->next;
1817 ptr->next->prev = ptr->prev;
1819 internal_error(state, ptr, "ptr->use != 0");
1821 put_occurance(ptr->occurance);
1822 memset(ptr, -1, size);
1826 static void release_triple(struct compile_state *state, struct triple *ptr)
1828 struct triple_set *set, *next;
1829 struct triple **expr;
1830 /* Remove ptr from use chains where it is the user */
1831 expr = triple_rhs(state, ptr, 0);
1832 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1834 unuse_triple(*expr, ptr);
1837 expr = triple_lhs(state, ptr, 0);
1838 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1840 unuse_triple(*expr, ptr);
1843 expr = triple_misc(state, ptr, 0);
1844 for(; expr; expr = triple_misc(state, ptr, expr)) {
1846 unuse_triple(*expr, ptr);
1849 expr = triple_targ(state, ptr, 0);
1850 for(; expr; expr = triple_targ(state, ptr, expr)) {
1852 unuse_triple(*expr, ptr);
1855 /* Reomve ptr from use chains where it is used */
1856 for(set = ptr->use; set; set = next) {
1858 expr = triple_rhs(state, set->member, 0);
1859 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1861 *expr = &zero_triple;
1864 expr = triple_lhs(state, set->member, 0);
1865 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1867 *expr = &zero_triple;
1870 expr = triple_misc(state, set->member, 0);
1871 for(; expr; expr = triple_misc(state, set->member, expr)) {
1873 *expr = &zero_triple;
1876 expr = triple_targ(state, set->member, 0);
1877 for(; expr; expr = triple_targ(state, set->member, expr)) {
1879 *expr = &zero_triple;
1882 unuse_triple(ptr, set->member);
1884 free_triple(state, ptr);
1887 static void print_triple(struct compile_state *state, struct triple *ptr);
1889 #define TOK_UNKNOWN 0
1892 #define TOK_LBRACE 3
1893 #define TOK_RBRACE 4
1897 #define TOK_LBRACKET 8
1898 #define TOK_RBRACKET 9
1899 #define TOK_LPAREN 10
1900 #define TOK_RPAREN 11
1905 #define TOK_TIMESEQ 16
1906 #define TOK_DIVEQ 17
1907 #define TOK_MODEQ 18
1908 #define TOK_PLUSEQ 19
1909 #define TOK_MINUSEQ 20
1912 #define TOK_ANDEQ 23
1913 #define TOK_XOREQ 24
1916 #define TOK_NOTEQ 27
1917 #define TOK_QUEST 28
1918 #define TOK_LOGOR 29
1919 #define TOK_LOGAND 30
1923 #define TOK_LESSEQ 34
1924 #define TOK_MOREEQ 35
1928 #define TOK_MINUS 39
1931 #define TOK_PLUSPLUS 42
1932 #define TOK_MINUSMINUS 43
1934 #define TOK_ARROW 45
1936 #define TOK_TILDE 47
1937 #define TOK_LIT_STRING 48
1938 #define TOK_LIT_CHAR 49
1939 #define TOK_LIT_INT 50
1940 #define TOK_LIT_FLOAT 51
1941 #define TOK_MACRO 52
1942 #define TOK_CONCATENATE 53
1944 #define TOK_IDENT 54
1945 #define TOK_STRUCT_NAME 55
1946 #define TOK_ENUM_CONST 56
1947 #define TOK_TYPE_NAME 57
1950 #define TOK_BREAK 59
1953 #define TOK_CONST 62
1954 #define TOK_CONTINUE 63
1955 #define TOK_DEFAULT 64
1957 #define TOK_DOUBLE 66
1960 #define TOK_EXTERN 69
1961 #define TOK_FLOAT 70
1965 #define TOK_INLINE 74
1968 #define TOK_REGISTER 77
1969 #define TOK_RESTRICT 78
1970 #define TOK_RETURN 79
1971 #define TOK_SHORT 80
1972 #define TOK_SIGNED 81
1973 #define TOK_SIZEOF 82
1974 #define TOK_STATIC 83
1975 #define TOK_STRUCT 84
1976 #define TOK_SWITCH 85
1977 #define TOK_TYPEDEF 86
1978 #define TOK_UNION 87
1979 #define TOK_UNSIGNED 88
1981 #define TOK_VOLATILE 90
1982 #define TOK_WHILE 91
1984 #define TOK_ATTRIBUTE 93
1985 #define TOK_ALIGNOF 94
1986 #define TOK_FIRST_KEYWORD TOK_AUTO
1987 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1989 #define TOK_DEFINE 100
1990 #define TOK_UNDEF 101
1991 #define TOK_INCLUDE 102
1992 #define TOK_LINE 103
1993 #define TOK_ERROR 104
1994 #define TOK_WARNING 105
1995 #define TOK_PRAGMA 106
1996 #define TOK_IFDEF 107
1997 #define TOK_IFNDEF 108
1998 #define TOK_ELIF 109
1999 #define TOK_ENDIF 110
2001 #define TOK_FIRST_MACRO TOK_DEFINE
2002 #define TOK_LAST_MACRO TOK_ENDIF
2006 static const char *tokens[] = {
2007 [TOK_UNKNOWN ] = "unknown",
2008 [TOK_SPACE ] = ":space:",
2010 [TOK_LBRACE ] = "{",
2011 [TOK_RBRACE ] = "}",
2015 [TOK_LBRACKET ] = "[",
2016 [TOK_RBRACKET ] = "]",
2017 [TOK_LPAREN ] = "(",
2018 [TOK_RPAREN ] = ")",
2020 [TOK_DOTS ] = "...",
2023 [TOK_TIMESEQ ] = "*=",
2024 [TOK_DIVEQ ] = "/=",
2025 [TOK_MODEQ ] = "%=",
2026 [TOK_PLUSEQ ] = "+=",
2027 [TOK_MINUSEQ ] = "-=",
2028 [TOK_SLEQ ] = "<<=",
2029 [TOK_SREQ ] = ">>=",
2030 [TOK_ANDEQ ] = "&=",
2031 [TOK_XOREQ ] = "^=",
2034 [TOK_NOTEQ ] = "!=",
2036 [TOK_LOGOR ] = "||",
2037 [TOK_LOGAND ] = "&&",
2041 [TOK_LESSEQ ] = "<=",
2042 [TOK_MOREEQ ] = ">=",
2049 [TOK_PLUSPLUS ] = "++",
2050 [TOK_MINUSMINUS ] = "--",
2052 [TOK_ARROW ] = "->",
2055 [TOK_LIT_STRING ] = ":string:",
2056 [TOK_IDENT ] = ":ident:",
2057 [TOK_TYPE_NAME ] = ":typename:",
2058 [TOK_LIT_CHAR ] = ":char:",
2059 [TOK_LIT_INT ] = ":integer:",
2060 [TOK_LIT_FLOAT ] = ":float:",
2062 [TOK_CONCATENATE ] = "##",
2064 [TOK_AUTO ] = "auto",
2065 [TOK_BREAK ] = "break",
2066 [TOK_CASE ] = "case",
2067 [TOK_CHAR ] = "char",
2068 [TOK_CONST ] = "const",
2069 [TOK_CONTINUE ] = "continue",
2070 [TOK_DEFAULT ] = "default",
2072 [TOK_DOUBLE ] = "double",
2073 [TOK_ELSE ] = "else",
2074 [TOK_ENUM ] = "enum",
2075 [TOK_EXTERN ] = "extern",
2076 [TOK_FLOAT ] = "float",
2078 [TOK_GOTO ] = "goto",
2080 [TOK_INLINE ] = "inline",
2082 [TOK_LONG ] = "long",
2083 [TOK_REGISTER ] = "register",
2084 [TOK_RESTRICT ] = "restrict",
2085 [TOK_RETURN ] = "return",
2086 [TOK_SHORT ] = "short",
2087 [TOK_SIGNED ] = "signed",
2088 [TOK_SIZEOF ] = "sizeof",
2089 [TOK_STATIC ] = "static",
2090 [TOK_STRUCT ] = "struct",
2091 [TOK_SWITCH ] = "switch",
2092 [TOK_TYPEDEF ] = "typedef",
2093 [TOK_UNION ] = "union",
2094 [TOK_UNSIGNED ] = "unsigned",
2095 [TOK_VOID ] = "void",
2096 [TOK_VOLATILE ] = "volatile",
2097 [TOK_WHILE ] = "while",
2099 [TOK_ATTRIBUTE ] = "__attribute__",
2100 [TOK_ALIGNOF ] = "__alignof__",
2102 [TOK_DEFINE ] = "define",
2103 [TOK_UNDEF ] = "undef",
2104 [TOK_INCLUDE ] = "include",
2105 [TOK_LINE ] = "line",
2106 [TOK_ERROR ] = "error",
2107 [TOK_WARNING ] = "warning",
2108 [TOK_PRAGMA ] = "pragma",
2109 [TOK_IFDEF ] = "ifdef",
2110 [TOK_IFNDEF ] = "ifndef",
2111 [TOK_ELIF ] = "elif",
2112 [TOK_ENDIF ] = "endif",
2117 static unsigned int hash(const char *str, int str_len)
2121 end = str + str_len;
2123 for(; str < end; str++) {
2124 hash = (hash *263) + *str;
2126 hash = hash & (HASH_TABLE_SIZE -1);
2130 static struct hash_entry *lookup(
2131 struct compile_state *state, const char *name, int name_len)
2133 struct hash_entry *entry;
2135 index = hash(name, name_len);
2136 entry = state->hash_table[index];
2138 ((entry->name_len != name_len) ||
2139 (memcmp(entry->name, name, name_len) != 0))) {
2140 entry = entry->next;
2144 /* Get a private copy of the name */
2145 new_name = xmalloc(name_len + 1, "hash_name");
2146 memcpy(new_name, name, name_len);
2147 new_name[name_len] = '\0';
2149 /* Create a new hash entry */
2150 entry = xcmalloc(sizeof(*entry), "hash_entry");
2151 entry->next = state->hash_table[index];
2152 entry->name = new_name;
2153 entry->name_len = name_len;
2155 /* Place the new entry in the hash table */
2156 state->hash_table[index] = entry;
2161 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2163 struct hash_entry *entry;
2165 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2166 (entry->tok == TOK_ENUM_CONST) ||
2167 ((entry->tok >= TOK_FIRST_KEYWORD) &&
2168 (entry->tok <= TOK_LAST_KEYWORD)))) {
2169 tk->tok = entry->tok;
2173 static void ident_to_macro(struct compile_state *state, struct token *tk)
2175 struct hash_entry *entry;
2178 (entry->tok >= TOK_FIRST_MACRO) &&
2179 (entry->tok <= TOK_LAST_MACRO)) {
2180 tk->tok = entry->tok;
2184 static void hash_keyword(
2185 struct compile_state *state, const char *keyword, int tok)
2187 struct hash_entry *entry;
2188 entry = lookup(state, keyword, strlen(keyword));
2189 if (entry && entry->tok != TOK_UNKNOWN) {
2190 die("keyword %s already hashed", keyword);
2196 struct compile_state *state, struct hash_entry *ident,
2197 struct symbol **chain, struct triple *def, struct type *type)
2200 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2201 error(state, 0, "%s already defined", ident->name);
2203 sym = xcmalloc(sizeof(*sym), "symbol");
2207 sym->scope_depth = state->scope_depth;
2212 static void label_symbol(struct compile_state *state,
2213 struct hash_entry *ident, struct triple *label)
2216 if (ident->sym_label) {
2217 error(state, 0, "label %s already defined", ident->name);
2219 sym = xcmalloc(sizeof(*sym), "label");
2222 sym->type = &void_type;
2223 sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2225 ident->sym_label = sym;
2228 static void start_scope(struct compile_state *state)
2230 state->scope_depth++;
2233 static void end_scope_syms(struct symbol **chain, int depth)
2235 struct symbol *sym, *next;
2237 while(sym && (sym->scope_depth == depth)) {
2245 static void end_scope(struct compile_state *state)
2249 /* Walk through the hash table and remove all symbols
2250 * in the current scope.
2252 depth = state->scope_depth;
2253 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2254 struct hash_entry *entry;
2255 entry = state->hash_table[i];
2257 end_scope_syms(&entry->sym_label, depth);
2258 end_scope_syms(&entry->sym_struct, depth);
2259 end_scope_syms(&entry->sym_ident, depth);
2260 entry = entry->next;
2263 state->scope_depth = depth - 1;
2266 static void register_keywords(struct compile_state *state)
2268 hash_keyword(state, "auto", TOK_AUTO);
2269 hash_keyword(state, "break", TOK_BREAK);
2270 hash_keyword(state, "case", TOK_CASE);
2271 hash_keyword(state, "char", TOK_CHAR);
2272 hash_keyword(state, "const", TOK_CONST);
2273 hash_keyword(state, "continue", TOK_CONTINUE);
2274 hash_keyword(state, "default", TOK_DEFAULT);
2275 hash_keyword(state, "do", TOK_DO);
2276 hash_keyword(state, "double", TOK_DOUBLE);
2277 hash_keyword(state, "else", TOK_ELSE);
2278 hash_keyword(state, "enum", TOK_ENUM);
2279 hash_keyword(state, "extern", TOK_EXTERN);
2280 hash_keyword(state, "float", TOK_FLOAT);
2281 hash_keyword(state, "for", TOK_FOR);
2282 hash_keyword(state, "goto", TOK_GOTO);
2283 hash_keyword(state, "if", TOK_IF);
2284 hash_keyword(state, "inline", TOK_INLINE);
2285 hash_keyword(state, "int", TOK_INT);
2286 hash_keyword(state, "long", TOK_LONG);
2287 hash_keyword(state, "register", TOK_REGISTER);
2288 hash_keyword(state, "restrict", TOK_RESTRICT);
2289 hash_keyword(state, "return", TOK_RETURN);
2290 hash_keyword(state, "short", TOK_SHORT);
2291 hash_keyword(state, "signed", TOK_SIGNED);
2292 hash_keyword(state, "sizeof", TOK_SIZEOF);
2293 hash_keyword(state, "static", TOK_STATIC);
2294 hash_keyword(state, "struct", TOK_STRUCT);
2295 hash_keyword(state, "switch", TOK_SWITCH);
2296 hash_keyword(state, "typedef", TOK_TYPEDEF);
2297 hash_keyword(state, "union", TOK_UNION);
2298 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2299 hash_keyword(state, "void", TOK_VOID);
2300 hash_keyword(state, "volatile", TOK_VOLATILE);
2301 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2302 hash_keyword(state, "while", TOK_WHILE);
2303 hash_keyword(state, "asm", TOK_ASM);
2304 hash_keyword(state, "__asm__", TOK_ASM);
2305 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2306 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2309 static void register_macro_keywords(struct compile_state *state)
2311 hash_keyword(state, "define", TOK_DEFINE);
2312 hash_keyword(state, "undef", TOK_UNDEF);
2313 hash_keyword(state, "include", TOK_INCLUDE);
2314 hash_keyword(state, "line", TOK_LINE);
2315 hash_keyword(state, "error", TOK_ERROR);
2316 hash_keyword(state, "warning", TOK_WARNING);
2317 hash_keyword(state, "pragma", TOK_PRAGMA);
2318 hash_keyword(state, "ifdef", TOK_IFDEF);
2319 hash_keyword(state, "ifndef", TOK_IFNDEF);
2320 hash_keyword(state, "elif", TOK_ELIF);
2321 hash_keyword(state, "endif", TOK_ENDIF);
2324 static int spacep(int c)
2340 static int digitp(int c)
2344 case '0': case '1': case '2': case '3': case '4':
2345 case '5': case '6': case '7': case '8': case '9':
2351 static int digval(int c)
2354 if ((c >= '0') && (c <= '9')) {
2360 static int hexdigitp(int c)
2364 case '0': case '1': case '2': case '3': case '4':
2365 case '5': case '6': case '7': case '8': case '9':
2366 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2367 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2373 static int hexdigval(int c)
2376 if ((c >= '0') && (c <= '9')) {
2379 else if ((c >= 'A') && (c <= 'F')) {
2380 val = 10 + (c - 'A');
2382 else if ((c >= 'a') && (c <= 'f')) {
2383 val = 10 + (c - 'a');
2388 static int octdigitp(int c)
2392 case '0': case '1': case '2': case '3':
2393 case '4': case '5': case '6': case '7':
2399 static int octdigval(int c)
2402 if ((c >= '0') && (c <= '7')) {
2408 static int letterp(int c)
2412 case 'a': case 'b': case 'c': case 'd': case 'e':
2413 case 'f': case 'g': case 'h': case 'i': case 'j':
2414 case 'k': case 'l': case 'm': case 'n': case 'o':
2415 case 'p': case 'q': case 'r': case 's': case 't':
2416 case 'u': case 'v': case 'w': case 'x': case 'y':
2418 case 'A': case 'B': case 'C': case 'D': case 'E':
2419 case 'F': case 'G': case 'H': case 'I': case 'J':
2420 case 'K': case 'L': case 'M': case 'N': case 'O':
2421 case 'P': case 'Q': case 'R': case 'S': case 'T':
2422 case 'U': case 'V': case 'W': case 'X': case 'Y':
2431 static int char_value(struct compile_state *state,
2432 const signed char **strp, const signed char *end)
2434 const signed char *str;
2438 if ((c == '\\') && (str < end)) {
2440 case 'n': c = '\n'; str++; break;
2441 case 't': c = '\t'; str++; break;
2442 case 'v': c = '\v'; str++; break;
2443 case 'b': c = '\b'; str++; break;
2444 case 'r': c = '\r'; str++; break;
2445 case 'f': c = '\f'; str++; break;
2446 case 'a': c = '\a'; str++; break;
2447 case '\\': c = '\\'; str++; break;
2448 case '?': c = '?'; str++; break;
2449 case '\'': c = '\''; str++; break;
2450 case '"': c = '"'; break;
2454 while((str < end) && hexdigitp(*str)) {
2456 c += hexdigval(*str);
2460 case '0': case '1': case '2': case '3':
2461 case '4': case '5': case '6': case '7':
2463 while((str < end) && octdigitp(*str)) {
2465 c += octdigval(*str);
2470 error(state, 0, "Invalid character constant");
2478 static char *after_digits(char *ptr, char *end)
2480 while((ptr < end) && digitp(*ptr)) {
2486 static char *after_octdigits(char *ptr, char *end)
2488 while((ptr < end) && octdigitp(*ptr)) {
2494 static char *after_hexdigits(char *ptr, char *end)
2496 while((ptr < end) && hexdigitp(*ptr)) {
2502 static void save_string(struct compile_state *state,
2503 struct token *tk, char *start, char *end, const char *id)
2507 /* Create a private copy of the string */
2508 str_len = end - start + 1;
2509 str = xmalloc(str_len + 1, id);
2510 memcpy(str, start, str_len);
2511 str[str_len] = '\0';
2513 /* Store the copy in the token */
2515 tk->str_len = str_len;
2517 static void next_token(struct compile_state *state, int index)
2519 struct file_state *file;
2527 tk = &state->token[index];
2530 token = tokp = file->pos;
2531 end = file->buf + file->size;
2538 if ((tokp + 1) < end) {
2542 if ((tokp + 2) < end) {
2546 if ((tokp + 3) < end) {
2554 else if (spacep(c)) {
2556 while ((tokp < end) && spacep(c)) {
2559 file->report_line++;
2560 file->line_start = tokp + 1;
2569 else if ((c == '/') && (c1 == '/')) {
2571 for(tokp += 2; tokp < end; tokp++) {
2575 file->report_line++;
2576 file->line_start = tokp +1;
2582 else if ((c == '/') && (c1 == '*')) {
2586 line_start = file->line_start;
2587 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2591 line_start = tokp +1;
2593 else if ((c == '*') && (tokp[1] == '/')) {
2599 if (tok == TOK_UNKNOWN) {
2600 error(state, 0, "unterminated comment");
2602 file->report_line += line - file->line;
2604 file->line_start = line_start;
2606 /* string constants */
2607 else if ((c == '"') ||
2608 ((c == 'L') && (c1 == '"'))) {
2613 line_start = file->line_start;
2619 for(tokp += 1; tokp < end; tokp++) {
2623 line_start = tokp + 1;
2625 else if ((c == '\\') && (tokp +1 < end)) {
2628 else if (c == '"') {
2629 tok = TOK_LIT_STRING;
2633 if (tok == TOK_UNKNOWN) {
2634 error(state, 0, "unterminated string constant");
2636 if (line != file->line) {
2637 warning(state, 0, "multiline string constant");
2639 file->report_line += line - file->line;
2641 file->line_start = line_start;
2643 /* Save the string value */
2644 save_string(state, tk, token, tokp, "literal string");
2646 /* character constants */
2647 else if ((c == '\'') ||
2648 ((c == 'L') && (c1 == '\''))) {
2653 line_start = file->line_start;
2659 for(tokp += 1; tokp < end; tokp++) {
2663 line_start = tokp + 1;
2665 else if ((c == '\\') && (tokp +1 < end)) {
2668 else if (c == '\'') {
2673 if (tok == TOK_UNKNOWN) {
2674 error(state, 0, "unterminated character constant");
2676 if (line != file->line) {
2677 warning(state, 0, "multiline character constant");
2679 file->report_line += line - file->line;
2681 file->line_start = line_start;
2683 /* Save the character value */
2684 save_string(state, tk, token, tokp, "literal character");
2686 /* integer and floating constants
2692 * Floating constants
2693 * {digits}.{digits}[Ee][+-]?{digits}
2695 * {digits}[Ee][+-]?{digits}
2696 * .{digits}[Ee][+-]?{digits}
2700 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2705 next = after_digits(tokp, end);
2710 if (next[0] == '.') {
2711 new = after_digits(next, end);
2712 is_float = (new != next);
2715 if ((next[0] == 'e') || (next[0] == 'E')) {
2716 if (((next + 1) < end) &&
2717 ((next[1] == '+') || (next[1] == '-'))) {
2720 new = after_digits(next, end);
2721 is_float = (new != next);
2725 tok = TOK_LIT_FLOAT;
2726 if ((next < end) && (
2735 if (!is_float && digitp(c)) {
2737 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2738 next = after_hexdigits(tokp + 2, end);
2740 else if (c == '0') {
2741 next = after_octdigits(tokp, end);
2744 next = after_digits(tokp, end);
2746 /* crazy integer suffixes */
2748 ((next[0] == 'u') || (next[0] == 'U'))) {
2751 ((next[0] == 'l') || (next[0] == 'L'))) {
2755 else if ((next < end) &&
2756 ((next[0] == 'l') || (next[0] == 'L'))) {
2759 ((next[0] == 'u') || (next[0] == 'U'))) {
2766 /* Save the integer/floating point value */
2767 save_string(state, tk, token, tokp, "literal number");
2770 else if (letterp(c)) {
2772 for(tokp += 1; tokp < end; tokp++) {
2774 if (!letterp(c) && !digitp(c)) {
2779 tk->ident = lookup(state, token, tokp +1 - token);
2781 /* C99 alternate macro characters */
2782 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2784 tok = TOK_CONCATENATE;
2786 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2787 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2788 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2789 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2790 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2791 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2792 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2793 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2794 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2795 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2796 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2797 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2798 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2799 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2800 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2801 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2802 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2803 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2804 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2805 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2806 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2807 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2808 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2809 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2810 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2811 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2812 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2813 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2814 else if (c == ';') { tok = TOK_SEMI; }
2815 else if (c == '{') { tok = TOK_LBRACE; }
2816 else if (c == '}') { tok = TOK_RBRACE; }
2817 else if (c == ',') { tok = TOK_COMMA; }
2818 else if (c == '=') { tok = TOK_EQ; }
2819 else if (c == ':') { tok = TOK_COLON; }
2820 else if (c == '[') { tok = TOK_LBRACKET; }
2821 else if (c == ']') { tok = TOK_RBRACKET; }
2822 else if (c == '(') { tok = TOK_LPAREN; }
2823 else if (c == ')') { tok = TOK_RPAREN; }
2824 else if (c == '*') { tok = TOK_STAR; }
2825 else if (c == '>') { tok = TOK_MORE; }
2826 else if (c == '<') { tok = TOK_LESS; }
2827 else if (c == '?') { tok = TOK_QUEST; }
2828 else if (c == '|') { tok = TOK_OR; }
2829 else if (c == '&') { tok = TOK_AND; }
2830 else if (c == '^') { tok = TOK_XOR; }
2831 else if (c == '+') { tok = TOK_PLUS; }
2832 else if (c == '-') { tok = TOK_MINUS; }
2833 else if (c == '/') { tok = TOK_DIV; }
2834 else if (c == '%') { tok = TOK_MOD; }
2835 else if (c == '!') { tok = TOK_BANG; }
2836 else if (c == '.') { tok = TOK_DOT; }
2837 else if (c == '~') { tok = TOK_TILDE; }
2838 else if (c == '#') { tok = TOK_MACRO; }
2839 if (tok == TOK_MACRO) {
2840 /* Only match preprocessor directives at the start of a line */
2842 for(ptr = file->line_start; spacep(*ptr); ptr++)
2848 if (tok == TOK_UNKNOWN) {
2849 error(state, 0, "unknown token");
2852 file->pos = tokp + 1;
2854 if (tok == TOK_IDENT) {
2855 ident_to_keyword(state, tk);
2857 /* Don't return space tokens. */
2858 if (tok == TOK_SPACE) {
2863 static void compile_macro(struct compile_state *state, struct token *tk)
2865 struct file_state *file;
2866 struct hash_entry *ident;
2868 file = xmalloc(sizeof(*file), "file_state");
2869 file->basename = xstrdup(tk->ident->name);
2870 file->dirname = xstrdup("");
2871 file->size = ident->sym_define->buf_len;
2872 file->buf = xmalloc(file->size +2, file->basename);
2873 memcpy(file->buf, ident->sym_define->buf, file->size);
2874 file->buf[file->size] = '\n';
2875 file->buf[file->size + 1] = '\0';
2876 file->pos = file->buf;
2877 file->line_start = file->pos;
2879 file->report_line = 1;
2880 file->report_name = file->basename;
2881 file->report_dir = file->dirname;
2882 file->prev = state->file;
2887 static int mpeek(struct compile_state *state, int index)
2891 tk = &state->token[index + 1];
2892 if (tk->tok == -1) {
2893 next_token(state, index + 1);
2897 if ((tk->tok == TOK_EOF) &&
2898 (state->file != state->macro_file) &&
2899 (state->file->prev)) {
2900 struct file_state *file = state->file;
2901 state->file = file->prev;
2902 /* file->basename is used keep it */
2903 if (file->report_dir != file->dirname) {
2904 xfree(file->report_dir);
2906 xfree(file->dirname);
2909 next_token(state, index + 1);
2912 else if (tk->ident && tk->ident->sym_define) {
2913 compile_macro(state, tk);
2914 next_token(state, index + 1);
2918 /* Don't show the token on the next line */
2919 if (state->macro_line < state->macro_file->line) {
2922 return state->token[index +1].tok;
2925 static void meat(struct compile_state *state, int index, int tok)
2929 next_tok = mpeek(state, index);
2930 if (next_tok != tok) {
2931 const char *name1, *name2;
2932 name1 = tokens[next_tok];
2934 if (next_tok == TOK_IDENT) {
2935 name2 = state->token[index + 1].ident->name;
2937 error(state, 0, "found %s %s expected %s",
2938 name1, name2, tokens[tok]);
2940 /* Free the old token value */
2941 if (state->token[index].str_len) {
2942 memset((void *)(state->token[index].val.str), -1,
2943 state->token[index].str_len);
2944 xfree(state->token[index].val.str);
2946 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2947 state->token[i] = state->token[i + 1];
2949 memset(&state->token[i], 0, sizeof(state->token[i]));
2950 state->token[i].tok = -1;
2953 static long_t mcexpr(struct compile_state *state, int index);
2955 static long_t mprimary_expr(struct compile_state *state, int index)
2959 tok = mpeek(state, index);
2960 while(state->token[index + 1].ident &&
2961 state->token[index + 1].ident->sym_define) {
2962 meat(state, index, tok);
2963 compile_macro(state, &state->token[index]);
2964 tok = mpeek(state, index);
2968 meat(state, index, TOK_LPAREN);
2969 val = mcexpr(state, index);
2970 meat(state, index, TOK_RPAREN);
2975 meat(state, index, TOK_LIT_INT);
2977 val = strtol(state->token[index].val.str, &end, 0);
2978 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2979 (errno == ERANGE)) {
2980 error(state, 0, "Integer constant to large");
2985 meat(state, index, TOK_LIT_INT);
2990 static long_t munary_expr(struct compile_state *state, int index)
2993 switch(mpeek(state, index)) {
2995 meat(state, index, TOK_PLUS);
2996 val = munary_expr(state, index);
3000 meat(state, index, TOK_MINUS);
3001 val = munary_expr(state, index);
3005 meat(state, index, TOK_BANG);
3006 val = munary_expr(state, index);
3010 meat(state, index, TOK_BANG);
3011 val = munary_expr(state, index);
3015 val = mprimary_expr(state, index);
3021 static long_t mmul_expr(struct compile_state *state, int index)
3025 val = munary_expr(state, index);
3029 switch(mpeek(state, index)) {
3031 meat(state, index, TOK_STAR);
3032 right = munary_expr(state, index);
3036 meat(state, index, TOK_DIV);
3037 right = munary_expr(state, index);
3041 meat(state, index, TOK_MOD);
3042 right = munary_expr(state, index);
3054 static long_t madd_expr(struct compile_state *state, int index)
3058 val = mmul_expr(state, index);
3062 switch(mpeek(state, index)) {
3064 meat(state, index, TOK_PLUS);
3065 right = mmul_expr(state, index);
3069 meat(state, index, TOK_MINUS);
3070 right = mmul_expr(state, index);
3082 static long_t mshift_expr(struct compile_state *state, int index)
3086 val = madd_expr(state, index);
3090 switch(mpeek(state, index)) {
3092 meat(state, index, TOK_SL);
3093 right = madd_expr(state, index);
3097 meat(state, index, TOK_SR);
3098 right = madd_expr(state, index);
3110 static long_t mrel_expr(struct compile_state *state, int index)
3114 val = mshift_expr(state, index);
3118 switch(mpeek(state, index)) {
3120 meat(state, index, TOK_LESS);
3121 right = mshift_expr(state, index);
3125 meat(state, index, TOK_MORE);
3126 right = mshift_expr(state, index);
3130 meat(state, index, TOK_LESSEQ);
3131 right = mshift_expr(state, index);
3135 meat(state, index, TOK_MOREEQ);
3136 right = mshift_expr(state, index);
3147 static long_t meq_expr(struct compile_state *state, int index)
3151 val = mrel_expr(state, index);
3155 switch(mpeek(state, index)) {
3157 meat(state, index, TOK_EQEQ);
3158 right = mrel_expr(state, index);
3162 meat(state, index, TOK_NOTEQ);
3163 right = mrel_expr(state, index);
3174 static long_t mand_expr(struct compile_state *state, int index)
3177 val = meq_expr(state, index);
3178 if (mpeek(state, index) == TOK_AND) {
3180 meat(state, index, TOK_AND);
3181 right = meq_expr(state, index);
3187 static long_t mxor_expr(struct compile_state *state, int index)
3190 val = mand_expr(state, index);
3191 if (mpeek(state, index) == TOK_XOR) {
3193 meat(state, index, TOK_XOR);
3194 right = mand_expr(state, index);
3200 static long_t mor_expr(struct compile_state *state, int index)
3203 val = mxor_expr(state, index);
3204 if (mpeek(state, index) == TOK_OR) {
3206 meat(state, index, TOK_OR);
3207 right = mxor_expr(state, index);
3213 static long_t mland_expr(struct compile_state *state, int index)
3216 val = mor_expr(state, index);
3217 if (mpeek(state, index) == TOK_LOGAND) {
3219 meat(state, index, TOK_LOGAND);
3220 right = mor_expr(state, index);
3225 static long_t mlor_expr(struct compile_state *state, int index)
3228 val = mland_expr(state, index);
3229 if (mpeek(state, index) == TOK_LOGOR) {
3231 meat(state, index, TOK_LOGOR);
3232 right = mland_expr(state, index);
3238 static long_t mcexpr(struct compile_state *state, int index)
3240 return mlor_expr(state, index);
3242 static void preprocess(struct compile_state *state, int index)
3244 /* Doing much more with the preprocessor would require
3245 * a parser and a major restructuring.
3246 * Postpone that for later.
3248 struct file_state *file;
3254 tk = &state->token[index];
3255 state->macro_line = line = file->line;
3256 state->macro_file = file;
3258 next_token(state, index);
3259 ident_to_macro(state, tk);
3260 if (tk->tok == TOK_IDENT) {
3261 error(state, 0, "undefined preprocessing directive `%s'",
3268 override_line = strtoul(tk->val.str, 0, 10);
3269 next_token(state, index);
3270 /* I have a cpp line marker parse it */
3271 if (tk->tok == TOK_LIT_STRING) {
3272 const char *token, *base;
3274 int name_len, dir_len;
3275 name = xmalloc(tk->str_len, "report_name");
3276 token = tk->val.str + 1;
3277 base = strrchr(token, '/');
3278 name_len = tk->str_len -2;
3280 dir_len = base - token;
3282 name_len -= base - token;
3287 memcpy(name, base, name_len);
3288 name[name_len] = '\0';
3289 dir = xmalloc(dir_len + 1, "report_dir");
3290 memcpy(dir, token, dir_len);
3291 dir[dir_len] = '\0';
3292 file->report_line = override_line - 1;
3293 file->report_name = name;
3294 file->report_dir = dir;
3299 meat(state, index, TOK_LINE);
3300 meat(state, index, TOK_LIT_INT);
3301 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3302 if (mpeek(state, index) == TOK_LIT_STRING) {
3303 const char *token, *base;
3305 int name_len, dir_len;
3306 meat(state, index, TOK_LIT_STRING);
3307 name = xmalloc(tk->str_len, "report_name");
3308 token = tk->val.str + 1;
3309 name_len = tk->str_len - 2;
3311 dir_len = base - token;
3313 name_len -= base - token;
3318 memcpy(name, base, name_len);
3319 name[name_len] = '\0';
3320 dir = xmalloc(dir_len + 1, "report_dir");
3321 memcpy(dir, token, dir_len);
3322 dir[dir_len] = '\0';
3323 file->report_name = name;
3324 file->report_dir = dir;
3329 if (state->if_value < 0) {
3332 warning(state, 0, "Ignoring preprocessor directive: %s",
3336 error(state, 0, "#elif not supported");
3337 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3338 if (state->if_depth == 0) {
3339 error(state, 0, "#elif without #if");
3341 /* If the #if was taken the #elif just disables the following code */
3342 if (state->if_value >= 0) {
3343 state->if_value = - state->if_value;
3345 /* If the previous #if was not taken see if the #elif enables the
3348 else if ((state->if_value < 0) &&
3349 (state->if_depth == - state->if_value))
3351 if (mcexpr(state, index) != 0) {
3352 state->if_value = state->if_depth;
3355 state->if_value = - state->if_depth;
3361 if (state->if_value < 0) {
3364 if (mcexpr(state, index) != 0) {
3365 state->if_value = state->if_depth;
3368 state->if_value = - state->if_depth;
3373 if (state->if_value < 0) {
3376 next_token(state, index);
3377 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3378 error(state, 0, "Invalid macro name");
3380 if (tk->ident->sym_define == 0) {
3381 state->if_value = state->if_depth;
3384 state->if_value = - state->if_depth;
3389 if (state->if_value < 0) {
3392 next_token(state, index);
3393 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3394 error(state, 0, "Invalid macro name");
3396 if (tk->ident->sym_define != 0) {
3397 state->if_value = state->if_depth;
3400 state->if_value = - state->if_depth;
3404 if (state->if_depth == 0) {
3405 error(state, 0, "#else without #if");
3407 if ((state->if_value >= 0) ||
3408 ((state->if_value < 0) &&
3409 (state->if_depth == -state->if_value)))
3411 state->if_value = - state->if_value;
3415 if (state->if_depth == 0) {
3416 error(state, 0, "#endif without #if");
3418 if ((state->if_value >= 0) ||
3419 ((state->if_value < 0) &&
3420 (state->if_depth == -state->if_value)))
3422 state->if_value = state->if_depth - 1;
3428 struct hash_entry *ident;
3429 struct macro *macro;
3432 if (state->if_value < 0) /* quit early when #if'd out */
3435 meat(state, index, TOK_IDENT);
3439 if (*file->pos == '(') {
3440 #warning "FIXME macros with arguments not supported"
3441 error(state, 0, "Macros with arguments not supported");
3444 /* Find the end of the line to get an estimate of
3445 * the macro's length.
3447 for(ptr = file->pos; *ptr != '\n'; ptr++)
3450 if (ident->sym_define != 0) {
3451 error(state, 0, "macro %s already defined\n", ident->name);
3453 macro = xmalloc(sizeof(*macro), "macro");
3454 macro->ident = ident;
3455 macro->buf_len = ptr - file->pos +1;
3456 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3458 memcpy(macro->buf, file->pos, macro->buf_len);
3459 macro->buf[macro->buf_len] = '\n';
3460 macro->buf[macro->buf_len +1] = '\0';
3462 ident->sym_define = macro;
3469 /* Find the end of the line */
3470 for(end = file->pos; *end != '\n'; end++)
3472 len = (end - file->pos);
3473 if (state->if_value >= 0) {
3474 error(state, 0, "%*.*s", len, len, file->pos);
3483 /* Find the end of the line */
3484 for(end = file->pos; *end != '\n'; end++)
3486 len = (end - file->pos);
3487 if (state->if_value >= 0) {
3488 warning(state, 0, "%*.*s", len, len, file->pos);
3500 next_token(state, index);
3501 if (tk->tok == TOK_LIT_STRING) {
3504 name = xmalloc(tk->str_len, "include");
3505 token = tk->val.str +1;
3506 name_len = tk->str_len -2;
3507 if (*token == '"') {
3511 memcpy(name, token, name_len);
3512 name[name_len] = '\0';
3515 else if (tk->tok == TOK_LESS) {
3518 for(end = start; *end != '\n'; end++) {
3524 error(state, 0, "Unterminated included directive");
3526 name = xmalloc(end - start + 1, "include");
3527 memcpy(name, start, end - start);
3528 name[end - start] = '\0';
3533 error(state, 0, "Invalid include directive");
3535 /* Error if there are any characters after the include */
3536 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3543 error(state, 0, "garbage after include directive");
3546 if (state->if_value >= 0) {
3547 compile_file(state, name, local);
3550 next_token(state, index);
3554 /* Ignore # without a following ident */
3555 if (tk->tok == TOK_IDENT) {
3556 error(state, 0, "Invalid preprocessor directive: %s",
3561 /* Consume the rest of the macro line */
3563 tok = mpeek(state, index);
3564 meat(state, index, tok);
3565 } while(tok != TOK_EOF);
3569 static void token(struct compile_state *state, int index)
3571 struct file_state *file;
3575 tk = &state->token[index];
3576 next_token(state, index);
3580 if (tk->tok == TOK_EOF && file->prev) {
3581 state->file = file->prev;
3582 /* file->basename is used keep it */
3583 xfree(file->dirname);
3586 next_token(state, index);
3589 else if (tk->tok == TOK_MACRO) {
3590 preprocess(state, index);
3593 else if (tk->ident && tk->ident->sym_define) {
3594 compile_macro(state, tk);
3595 next_token(state, index);
3598 else if (state->if_value < 0) {
3599 next_token(state, index);
3605 static int peek(struct compile_state *state)
3607 if (state->token[1].tok == -1) {
3610 return state->token[1].tok;
3613 static int peek2(struct compile_state *state)
3615 if (state->token[1].tok == -1) {
3618 if (state->token[2].tok == -1) {
3621 return state->token[2].tok;
3624 static void eat(struct compile_state *state, int tok)
3628 next_tok = peek(state);
3629 if (next_tok != tok) {
3630 const char *name1, *name2;
3631 name1 = tokens[next_tok];
3633 if (next_tok == TOK_IDENT) {
3634 name2 = state->token[1].ident->name;
3636 error(state, 0, "\tfound %s %s expected %s",
3637 name1, name2 ,tokens[tok]);
3639 /* Free the old token value */
3640 if (state->token[0].str_len) {
3641 xfree((void *)(state->token[0].val.str));
3643 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3644 state->token[i] = state->token[i + 1];
3646 memset(&state->token[i], 0, sizeof(state->token[i]));
3647 state->token[i].tok = -1;
3650 #warning "FIXME do not hardcode the include paths"
3651 static char *include_paths[] = {
3652 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3653 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3654 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3658 static void compile_file(struct compile_state *state, const char *filename, int local)
3661 const char *subdir, *base;
3663 struct file_state *file;
3665 file = xmalloc(sizeof(*file), "file_state");
3667 base = strrchr(filename, '/');
3670 subdir_len = base - filename;
3677 basename = xmalloc(strlen(base) +1, "basename");
3678 strcpy(basename, base);
3679 file->basename = basename;
3681 if (getcwd(cwd, sizeof(cwd)) == 0) {
3682 die("cwd buffer to small");
3685 if (subdir[0] == '/') {
3686 file->dirname = xmalloc(subdir_len + 1, "dirname");
3687 memcpy(file->dirname, subdir, subdir_len);
3688 file->dirname[subdir_len] = '\0';
3694 /* Find the appropriate directory... */
3696 if (!state->file && exists(cwd, filename)) {
3699 if (local && state->file && exists(state->file->dirname, filename)) {
3700 dir = state->file->dirname;
3702 for(path = include_paths; !dir && *path; path++) {
3703 if (exists(*path, filename)) {
3708 error(state, 0, "Cannot find `%s'\n", filename);
3710 dirlen = strlen(dir);
3711 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3712 memcpy(file->dirname, dir, dirlen);
3713 file->dirname[dirlen] = '/';
3714 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3715 file->dirname[dirlen + 1 + subdir_len] = '\0';
3717 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3720 file->pos = file->buf;
3721 file->line_start = file->pos;
3724 file->report_line = 1;
3725 file->report_name = file->basename;
3726 file->report_dir = file->dirname;
3728 file->prev = state->file;
3731 process_trigraphs(state);
3732 splice_lines(state);
3735 /* Type helper functions */
3737 static struct type *new_type(
3738 unsigned int type, struct type *left, struct type *right)
3740 struct type *result;
3741 result = xmalloc(sizeof(*result), "type");
3742 result->type = type;
3743 result->left = left;
3744 result->right = right;
3745 result->field_ident = 0;
3746 result->type_ident = 0;
3750 static struct type *clone_type(unsigned int specifiers, struct type *old)
3752 struct type *result;
3753 result = xmalloc(sizeof(*result), "type");
3754 memcpy(result, old, sizeof(*result));
3755 result->type &= TYPE_MASK;
3756 result->type |= specifiers;
3760 #define SIZEOF_SHORT 2
3761 #define SIZEOF_INT 4
3762 #define SIZEOF_LONG (sizeof(long_t))
3764 #define ALIGNOF_SHORT 2
3765 #define ALIGNOF_INT 4
3766 #define ALIGNOF_LONG (sizeof(long_t))
3768 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3769 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3770 static inline ulong_t mask_uint(ulong_t x)
3772 if (SIZEOF_INT < SIZEOF_LONG) {
3773 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3778 #define MASK_UINT(X) (mask_uint(X))
3779 #define MASK_ULONG(X) (X)
3781 static struct type void_type = { .type = TYPE_VOID };
3782 static struct type char_type = { .type = TYPE_CHAR };
3783 static struct type uchar_type = { .type = TYPE_UCHAR };
3784 static struct type short_type = { .type = TYPE_SHORT };
3785 static struct type ushort_type = { .type = TYPE_USHORT };
3786 static struct type int_type = { .type = TYPE_INT };
3787 static struct type uint_type = { .type = TYPE_UINT };
3788 static struct type long_type = { .type = TYPE_LONG };
3789 static struct type ulong_type = { .type = TYPE_ULONG };
3791 static struct triple *variable(struct compile_state *state, struct type *type)
3793 struct triple *result;
3794 if ((type->type & STOR_MASK) != STOR_PERM) {
3795 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3796 result = triple(state, OP_ADECL, type, 0, 0);
3799 struct triple **vector;
3801 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3802 vector = &result->param[0];
3806 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3807 vector[index] = variable(state, field->left);
3808 field = field->right;
3811 vector[index] = variable(state, field);
3815 result = triple(state, OP_SDECL, type, 0, 0);
3820 static void stor_of(FILE *fp, struct type *type)
3822 switch(type->type & STOR_MASK) {
3824 fprintf(fp, "auto ");
3827 fprintf(fp, "static ");
3830 fprintf(fp, "extern ");
3833 fprintf(fp, "register ");
3836 fprintf(fp, "typedef ");
3839 fprintf(fp, "inline ");
3843 static void qual_of(FILE *fp, struct type *type)
3845 if (type->type & QUAL_CONST) {
3846 fprintf(fp, " const");
3848 if (type->type & QUAL_VOLATILE) {
3849 fprintf(fp, " volatile");
3851 if (type->type & QUAL_RESTRICT) {
3852 fprintf(fp, " restrict");
3856 static void name_of(FILE *fp, struct type *type)
3859 switch(type->type & TYPE_MASK) {
3861 fprintf(fp, "void");
3865 fprintf(fp, "signed char");
3869 fprintf(fp, "unsigned char");
3873 fprintf(fp, "signed short");
3877 fprintf(fp, "unsigned short");
3881 fprintf(fp, "signed int");
3885 fprintf(fp, "unsigned int");
3889 fprintf(fp, "signed long");
3893 fprintf(fp, "unsigned long");
3897 name_of(fp, type->left);
3903 name_of(fp, type->left);
3905 name_of(fp, type->right);
3908 fprintf(fp, "enum %s", type->type_ident->name);
3912 fprintf(fp, "struct %s", type->type_ident->name);
3917 name_of(fp, type->left);
3918 fprintf(fp, " (*)(");
3919 name_of(fp, type->right);
3924 name_of(fp, type->left);
3925 fprintf(fp, " [%ld]", type->elements);
3928 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3933 static size_t align_of(struct compile_state *state, struct type *type)
3937 switch(type->type & TYPE_MASK) {
3947 align = ALIGNOF_SHORT;
3952 align = ALIGNOF_INT;
3957 align = ALIGNOF_LONG;
3962 size_t left_align, right_align;
3963 left_align = align_of(state, type->left);
3964 right_align = align_of(state, type->right);
3965 align = (left_align >= right_align) ? left_align : right_align;
3969 align = align_of(state, type->left);
3972 align = align_of(state, type->left);
3975 error(state, 0, "alignof not yet defined for type\n");
3981 static size_t needed_padding(size_t offset, size_t align)
3985 if (offset % align) {
3986 padding = align - (offset % align);
3990 static size_t size_of(struct compile_state *state, struct type *type)
3994 switch(type->type & TYPE_MASK) {
4004 size = SIZEOF_SHORT;
4020 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4021 align = align_of(state, type->left);
4022 pad = needed_padding(size, align);
4023 size = size + pad + size_of(state, type->left);
4026 align = align_of(state, type);
4027 pad = needed_padding(size, align);
4028 size = size + pad + sizeof(type);
4033 size_t size_left, size_right;
4034 size_left = size_of(state, type->left);
4035 size_right = size_of(state, type->right);
4036 size = (size_left >= size_right)? size_left : size_right;
4040 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4041 internal_error(state, 0, "Invalid array type");
4043 size = size_of(state, type->left) * type->elements;
4047 size = size_of(state, type->left);
4050 internal_error(state, 0, "sizeof not yet defined for type\n");
4056 static size_t field_offset(struct compile_state *state,
4057 struct type *type, struct hash_entry *field)
4059 struct type *member;
4061 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4062 internal_error(state, 0, "field_offset only works on structures");
4065 member = type->left;
4066 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4067 align = align_of(state, member->left);
4068 size += needed_padding(size, align);
4069 if (member->left->field_ident == field) {
4070 member = member->left;
4073 size += size_of(state, member->left);
4074 member = member->right;
4076 align = align_of(state, member);
4077 size += needed_padding(size, align);
4078 if (member->field_ident != field) {
4079 error(state, 0, "member %s not present", field->name);
4084 static struct type *field_type(struct compile_state *state,
4085 struct type *type, struct hash_entry *field)
4087 struct type *member;
4088 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4089 internal_error(state, 0, "field_type only works on structures");
4091 member = type->left;
4092 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4093 if (member->left->field_ident == field) {
4094 member = member->left;
4097 member = member->right;
4099 if (member->field_ident != field) {
4100 error(state, 0, "member %s not present", field->name);
4105 static struct type *next_field(struct compile_state *state,
4106 struct type *type, struct type *prev_member)
4108 struct type *member;
4109 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4110 internal_error(state, 0, "next_field only works on structures");
4112 member = type->left;
4113 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4115 member = member->left;
4118 if (member->left == prev_member) {
4121 member = member->right;
4123 if (member == prev_member) {
4127 internal_error(state, 0, "prev_member %s not present",
4128 prev_member->field_ident->name);
4133 static struct triple *struct_field(struct compile_state *state,
4134 struct triple *decl, struct hash_entry *field)
4136 struct triple **vector;
4140 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4143 if (decl->op != OP_VAL_VEC) {
4144 internal_error(state, 0, "Invalid struct variable");
4147 internal_error(state, 0, "Missing structure field");
4150 vector = &RHS(decl, 0);
4152 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4153 if (type->left->field_ident == field) {
4160 if (type->field_ident != field) {
4161 internal_error(state, 0, "field %s not found?", field->name);
4163 return vector[index];
4166 static void arrays_complete(struct compile_state *state, struct type *type)
4168 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4169 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4170 error(state, 0, "array size not specified");
4172 arrays_complete(state, type->left);
4176 static unsigned int do_integral_promotion(unsigned int type)
4179 if (TYPE_INTEGER(type) &&
4180 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4186 static unsigned int do_arithmetic_conversion(
4187 unsigned int left, unsigned int right)
4191 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4192 return TYPE_LDOUBLE;
4194 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4197 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4200 left = do_integral_promotion(left);
4201 right = do_integral_promotion(right);
4202 /* If both operands have the same size done */
4203 if (left == right) {
4206 /* If both operands have the same signedness pick the larger */
4207 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4208 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4210 /* If the signed type can hold everything use it */
4211 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4214 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4217 /* Convert to the unsigned type with the same rank as the signed type */
4218 else if (TYPE_SIGNED(left)) {
4219 return TYPE_MKUNSIGNED(left);
4222 return TYPE_MKUNSIGNED(right);
4226 /* see if two types are the same except for qualifiers */
4227 static int equiv_types(struct type *left, struct type *right)
4230 /* Error if the basic types do not match */
4231 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4234 type = left->type & TYPE_MASK;
4235 /* If the basic types match and it is a void type we are done */
4236 if (type == TYPE_VOID) {
4239 /* if the basic types match and it is an arithmetic type we are done */
4240 if (TYPE_ARITHMETIC(type)) {
4243 /* If it is a pointer type recurse and keep testing */
4244 if (type == TYPE_POINTER) {
4245 return equiv_types(left->left, right->left);
4247 else if (type == TYPE_ARRAY) {
4248 return (left->elements == right->elements) &&
4249 equiv_types(left->left, right->left);
4251 /* test for struct/union equality */
4252 else if (type == TYPE_STRUCT) {
4253 return left->type_ident == right->type_ident;
4255 /* Test for equivalent functions */
4256 else if (type == TYPE_FUNCTION) {
4257 return equiv_types(left->left, right->left) &&
4258 equiv_types(left->right, right->right);
4260 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4261 else if (type == TYPE_PRODUCT) {
4262 return equiv_types(left->left, right->left) &&
4263 equiv_types(left->right, right->right);
4265 /* We should see TYPE_OVERLAP */
4271 static int equiv_ptrs(struct type *left, struct type *right)
4273 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4274 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4277 return equiv_types(left->left, right->left);
4280 static struct type *compatible_types(struct type *left, struct type *right)
4282 struct type *result;
4283 unsigned int type, qual_type;
4284 /* Error if the basic types do not match */
4285 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4288 type = left->type & TYPE_MASK;
4289 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4291 /* if the basic types match and it is an arithmetic type we are done */
4292 if (TYPE_ARITHMETIC(type)) {
4293 result = new_type(qual_type, 0, 0);
4295 /* If it is a pointer type recurse and keep testing */
4296 else if (type == TYPE_POINTER) {
4297 result = compatible_types(left->left, right->left);
4299 result = new_type(qual_type, result, 0);
4302 /* test for struct/union equality */
4303 else if (type == TYPE_STRUCT) {
4304 if (left->type_ident == right->type_ident) {
4308 /* Test for equivalent functions */
4309 else if (type == TYPE_FUNCTION) {
4310 struct type *lf, *rf;
4311 lf = compatible_types(left->left, right->left);
4312 rf = compatible_types(left->right, right->right);
4314 result = new_type(qual_type, lf, rf);
4317 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4318 else if (type == TYPE_PRODUCT) {
4319 struct type *lf, *rf;
4320 lf = compatible_types(left->left, right->left);
4321 rf = compatible_types(left->right, right->right);
4323 result = new_type(qual_type, lf, rf);
4327 /* Nothing else is compatible */
4332 static struct type *compatible_ptrs(struct type *left, struct type *right)
4334 struct type *result;
4335 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4336 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4339 result = compatible_types(left->left, right->left);
4341 unsigned int qual_type;
4342 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4343 result = new_type(qual_type, result, 0);
4348 static struct triple *integral_promotion(
4349 struct compile_state *state, struct triple *def)
4353 /* As all operations are carried out in registers
4354 * the values are converted on load I just convert
4355 * logical type of the operand.
4357 if (TYPE_INTEGER(type->type)) {
4358 unsigned int int_type;
4359 int_type = type->type & ~TYPE_MASK;
4360 int_type |= do_integral_promotion(type->type);
4361 if (int_type != type->type) {
4362 def->type = new_type(int_type, 0, 0);
4369 static void arithmetic(struct compile_state *state, struct triple *def)
4371 if (!TYPE_ARITHMETIC(def->type->type)) {
4372 error(state, 0, "arithmetic type expexted");
4376 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4378 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4379 error(state, def, "pointer or arithmetic type expected");
4383 static int is_integral(struct triple *ins)
4385 return TYPE_INTEGER(ins->type->type);
4388 static void integral(struct compile_state *state, struct triple *def)
4390 if (!is_integral(def)) {
4391 error(state, 0, "integral type expected");
4396 static void bool(struct compile_state *state, struct triple *def)
4398 if (!TYPE_ARITHMETIC(def->type->type) &&
4399 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4400 error(state, 0, "arithmetic or pointer type expected");
4404 static int is_signed(struct type *type)
4406 return !!TYPE_SIGNED(type->type);
4409 /* Is this value located in a register otherwise it must be in memory */
4410 static int is_in_reg(struct compile_state *state, struct triple *def)
4413 if (def->op == OP_ADECL) {
4416 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4419 else if (def->op == OP_VAL_VEC) {
4420 in_reg = is_in_reg(state, RHS(def, 0));
4422 else if (def->op == OP_DOT) {
4423 in_reg = is_in_reg(state, RHS(def, 0));
4426 internal_error(state, 0, "unknown expr storage location");
4432 /* Is this a stable variable location otherwise it must be a temporary */
4433 static int is_stable(struct compile_state *state, struct triple *def)
4440 if ((def->op == OP_ADECL) ||
4441 (def->op == OP_SDECL) ||
4442 (def->op == OP_DEREF) ||
4443 (def->op == OP_BLOBCONST)) {
4446 else if (def->op == OP_DOT) {
4447 ret = is_stable(state, RHS(def, 0));
4449 else if (def->op == OP_VAL_VEC) {
4450 struct triple **vector;
4453 vector = &RHS(def, 0);
4454 for(i = 0; i < def->type->elements; i++) {
4455 if (!is_stable(state, vector[i])) {
4464 static int is_lvalue(struct compile_state *state, struct triple *def)
4471 if (!is_stable(state, def)) {
4474 if (def->op == OP_DOT) {
4475 ret = is_lvalue(state, RHS(def, 0));
4480 static void clvalue(struct compile_state *state, struct triple *def)
4483 internal_error(state, def, "nothing where lvalue expected?");
4485 if (!is_lvalue(state, def)) {
4486 error(state, def, "lvalue expected");
4489 static void lvalue(struct compile_state *state, struct triple *def)
4491 clvalue(state, def);
4492 if (def->type->type & QUAL_CONST) {
4493 error(state, def, "modifable lvalue expected");
4497 static int is_pointer(struct triple *def)
4499 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4502 static void pointer(struct compile_state *state, struct triple *def)
4504 if (!is_pointer(def)) {
4505 error(state, def, "pointer expected");
4509 static struct triple *int_const(
4510 struct compile_state *state, struct type *type, ulong_t value)
4512 struct triple *result;
4513 switch(type->type & TYPE_MASK) {
4515 case TYPE_INT: case TYPE_UINT:
4516 case TYPE_LONG: case TYPE_ULONG:
4519 internal_error(state, 0, "constant for unkown type");
4521 result = triple(state, OP_INTCONST, type, 0, 0);
4522 result->u.cval = value;
4527 static struct triple *do_mk_addr_expr(struct compile_state *state,
4528 struct triple *expr, struct type *type, ulong_t offset)
4530 struct triple *result;
4531 clvalue(state, expr);
4533 type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
4536 if (expr->op == OP_ADECL) {
4537 error(state, expr, "address of auto variables not supported");
4539 else if (expr->op == OP_SDECL) {
4540 result = triple(state, OP_ADDRCONST, type, 0, 0);
4541 MISC(result, 0) = expr;
4542 result->u.cval = offset;
4544 else if (expr->op == OP_DEREF) {
4545 result = triple(state, OP_ADD, type,
4547 int_const(state, &ulong_type, offset));
4552 static struct triple *mk_addr_expr(
4553 struct compile_state *state, struct triple *expr, ulong_t offset)
4555 return do_mk_addr_expr(state, expr, expr->type, offset);
4558 static struct triple *mk_deref_expr(
4559 struct compile_state *state, struct triple *expr)
4561 struct type *base_type;
4562 pointer(state, expr);
4563 base_type = expr->type->left;
4564 return triple(state, OP_DEREF, base_type, expr, 0);
4567 static struct triple *array_to_pointer(struct compile_state *state, struct triple *def)
4569 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4571 struct triple *addrconst;
4573 TYPE_POINTER | (def->type->type & QUAL_MASK),
4574 def->type->left, 0);
4575 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
4576 MISC(addrconst, 0) = def;
4582 static struct triple *deref_field(
4583 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4585 struct triple *result;
4586 struct type *type, *member;
4588 internal_error(state, 0, "No field passed to deref_field");
4592 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4593 error(state, 0, "request for member %s in something not a struct or union",
4596 member = field_type(state, type, field);
4597 if ((type->type & STOR_MASK) == STOR_PERM) {
4598 /* Do the pointer arithmetic to get a deref the field */
4600 offset = field_offset(state, type, field);
4601 result = do_mk_addr_expr(state, expr, member, offset);
4602 result = mk_deref_expr(state, result);
4605 /* Find the variable for the field I want. */
4606 result = triple(state, OP_DOT, member, expr, 0);
4607 result->u.field = field;
4612 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4618 if (!is_stable(state, def)) {
4621 /* Tranform an array to a pointer to the first element */
4623 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4624 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4625 return array_to_pointer(state, def);
4627 if (is_in_reg(state, def)) {
4632 return triple(state, op, def->type, def, 0);
4635 static void write_compatible(struct compile_state *state,
4636 struct type *dest, struct type *rval)
4639 /* Both operands have arithmetic type */
4640 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4643 /* One operand is a pointer and the other is a pointer to void */
4644 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4645 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4646 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4647 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4650 /* If both types are the same without qualifiers we are good */
4651 else if (equiv_ptrs(dest, rval)) {
4654 /* test for struct/union equality */
4655 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4656 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4657 (dest->type_ident == rval->type_ident)) {
4661 error(state, 0, "Incompatible types in assignment");
4665 static struct triple *write_expr(
4666 struct compile_state *state, struct triple *dest, struct triple *rval)
4673 internal_error(state, 0, "missing rval");
4676 if (rval->op == OP_LIST) {
4677 internal_error(state, 0, "expression of type OP_LIST?");
4679 if (!is_lvalue(state, dest)) {
4680 internal_error(state, 0, "writing to a non lvalue?");
4682 if (dest->type->type & QUAL_CONST) {
4683 internal_error(state, 0, "modifable lvalue expexted");
4686 write_compatible(state, dest->type, rval->type);
4688 /* Now figure out which assignment operator to use */
4690 if (is_in_reg(state, dest)) {
4695 def = triple(state, op, dest->type, dest, rval);
4699 static struct triple *init_expr(
4700 struct compile_state *state, struct triple *dest, struct triple *rval)
4706 internal_error(state, 0, "missing rval");
4708 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4709 rval = read_expr(state, rval);
4710 def = write_expr(state, dest, rval);
4713 /* Fill in the array size if necessary */
4714 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4715 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4716 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4717 dest->type->elements = rval->type->elements;
4720 if (!equiv_types(dest->type, rval->type)) {
4721 error(state, 0, "Incompatible types in inializer");
4723 MISC(dest, 0) = rval;
4724 insert_triple(state, dest, rval);
4725 rval->id |= TRIPLE_FLAG_FLATTENED;
4726 use_triple(MISC(dest, 0), dest);
4731 struct type *arithmetic_result(
4732 struct compile_state *state, struct triple *left, struct triple *right)
4735 /* Sanity checks to ensure I am working with arithmetic types */
4736 arithmetic(state, left);
4737 arithmetic(state, right);
4739 do_arithmetic_conversion(
4741 right->type->type), 0, 0);
4745 struct type *ptr_arithmetic_result(
4746 struct compile_state *state, struct triple *left, struct triple *right)
4749 /* Sanity checks to ensure I am working with the proper types */
4750 ptr_arithmetic(state, left);
4751 arithmetic(state, right);
4752 if (TYPE_ARITHMETIC(left->type->type) &&
4753 TYPE_ARITHMETIC(right->type->type)) {
4754 type = arithmetic_result(state, left, right);
4756 else if (TYPE_PTR(left->type->type)) {
4760 internal_error(state, 0, "huh?");
4767 /* boolean helper function */
4769 static struct triple *ltrue_expr(struct compile_state *state,
4770 struct triple *expr)
4773 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4774 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4775 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4776 /* If the expression is already boolean do nothing */
4779 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4785 static struct triple *lfalse_expr(struct compile_state *state,
4786 struct triple *expr)
4788 return triple(state, OP_LFALSE, &int_type, expr, 0);
4791 static struct triple *cond_expr(
4792 struct compile_state *state,
4793 struct triple *test, struct triple *left, struct triple *right)
4796 struct type *result_type;
4797 unsigned int left_type, right_type;
4799 left_type = left->type->type;
4800 right_type = right->type->type;
4802 /* Both operands have arithmetic type */
4803 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4804 result_type = arithmetic_result(state, left, right);
4806 /* Both operands have void type */
4807 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4808 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4809 result_type = &void_type;
4811 /* pointers to the same type... */
4812 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4815 /* Both operands are pointers and left is a pointer to void */
4816 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4817 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4818 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4819 result_type = right->type;
4821 /* Both operands are pointers and right is a pointer to void */
4822 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4823 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4824 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4825 result_type = left->type;
4828 error(state, 0, "Incompatible types in conditional expression");
4830 /* Cleanup and invert the test */
4831 test = lfalse_expr(state, read_expr(state, test));
4832 def = new_triple(state, OP_COND, result_type, 0, 3);
4833 def->param[0] = test;
4834 def->param[1] = left;
4835 def->param[2] = right;
4840 static int expr_depth(struct compile_state *state, struct triple *ins)
4844 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4847 else if (ins->op == OP_DEREF) {
4848 count = expr_depth(state, RHS(ins, 0)) - 1;
4850 else if (ins->op == OP_VAL) {
4851 count = expr_depth(state, RHS(ins, 0)) - 1;
4853 else if (ins->op == OP_COMMA) {
4855 ldepth = expr_depth(state, RHS(ins, 0));
4856 rdepth = expr_depth(state, RHS(ins, 1));
4857 count = (ldepth >= rdepth)? ldepth : rdepth;
4859 else if (ins->op == OP_CALL) {
4860 /* Don't figure the depth of a call just guess it is huge */
4864 struct triple **expr;
4865 expr = triple_rhs(state, ins, 0);
4866 for(;expr; expr = triple_rhs(state, ins, expr)) {
4869 depth = expr_depth(state, *expr);
4870 if (depth > count) {
4879 static struct triple *flatten(
4880 struct compile_state *state, struct triple *first, struct triple *ptr);
4882 static struct triple *flatten_generic(
4883 struct compile_state *state, struct triple *first, struct triple *ptr)
4887 struct triple **ins;
4890 /* Only operations with just a rhs should come here */
4891 rhs = TRIPLE_RHS(ptr->sizes);
4892 lhs = TRIPLE_LHS(ptr->sizes);
4893 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4894 internal_error(state, ptr, "unexpected args for: %d %s",
4895 ptr->op, tops(ptr->op));
4897 /* Find the depth of the rhs elements */
4898 for(i = 0; i < rhs; i++) {
4899 vector[i].ins = &RHS(ptr, i);
4900 vector[i].depth = expr_depth(state, *vector[i].ins);
4902 /* Selection sort the rhs */
4903 for(i = 0; i < rhs; i++) {
4905 for(j = i + 1; j < rhs; j++ ) {
4906 if (vector[j].depth > vector[max].depth) {
4911 struct rhs_vector tmp;
4913 vector[i] = vector[max];
4917 /* Now flatten the rhs elements */
4918 for(i = 0; i < rhs; i++) {
4919 *vector[i].ins = flatten(state, first, *vector[i].ins);
4920 use_triple(*vector[i].ins, ptr);
4923 /* Now flatten the lhs elements */
4924 for(i = 0; i < lhs; i++) {
4925 struct triple **ins = &LHS(ptr, i);
4926 *ins = flatten(state, first, *ins);
4927 use_triple(*ins, ptr);
4932 static struct triple *flatten_land(
4933 struct compile_state *state, struct triple *first, struct triple *ptr)
4935 struct triple *left, *right;
4936 struct triple *val, *test, *jmp, *label1, *end;
4938 /* Find the triples */
4940 right = RHS(ptr, 1);
4942 /* Generate the needed triples */
4945 /* Thread the triples together */
4946 val = flatten(state, first, variable(state, ptr->type));
4947 left = flatten(state, first, write_expr(state, val, left));
4948 test = flatten(state, first,
4949 lfalse_expr(state, read_expr(state, val)));
4950 jmp = flatten(state, first, branch(state, end, test));
4951 label1 = flatten(state, first, label(state));
4952 right = flatten(state, first, write_expr(state, val, right));
4953 TARG(jmp, 0) = flatten(state, first, end);
4955 /* Now give the caller something to chew on */
4956 return read_expr(state, val);
4959 static struct triple *flatten_lor(
4960 struct compile_state *state, struct triple *first, struct triple *ptr)
4962 struct triple *left, *right;
4963 struct triple *val, *jmp, *label1, *end;
4965 /* Find the triples */
4967 right = RHS(ptr, 1);
4969 /* Generate the needed triples */
4972 /* Thread the triples together */
4973 val = flatten(state, first, variable(state, ptr->type));
4974 left = flatten(state, first, write_expr(state, val, left));
4975 jmp = flatten(state, first, branch(state, end, left));
4976 label1 = flatten(state, first, label(state));
4977 right = flatten(state, first, write_expr(state, val, right));
4978 TARG(jmp, 0) = flatten(state, first, end);
4981 /* Now give the caller something to chew on */
4982 return read_expr(state, val);
4985 static struct triple *flatten_cond(
4986 struct compile_state *state, struct triple *first, struct triple *ptr)
4988 struct triple *test, *left, *right;
4989 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4991 /* Find the triples */
4994 right = RHS(ptr, 2);
4996 /* Generate the needed triples */
4998 middle = label(state);
5000 /* Thread the triples together */
5001 val = flatten(state, first, variable(state, ptr->type));
5002 test = flatten(state, first, test);
5003 jmp1 = flatten(state, first, branch(state, middle, test));
5004 label1 = flatten(state, first, label(state));
5005 left = flatten(state, first, left);
5006 mv1 = flatten(state, first, write_expr(state, val, left));
5007 jmp2 = flatten(state, first, branch(state, end, 0));
5008 TARG(jmp1, 0) = flatten(state, first, middle);
5009 right = flatten(state, first, right);
5010 mv2 = flatten(state, first, write_expr(state, val, right));
5011 TARG(jmp2, 0) = flatten(state, first, end);
5013 /* Now give the caller something to chew on */
5014 return read_expr(state, val);
5017 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
5018 struct occurance *base_occurance)
5020 struct triple *nfunc;
5021 struct triple *nfirst, *ofirst;
5022 struct triple *new, *old;
5025 fprintf(stdout, "\n");
5026 loc(stdout, state, 0);
5027 fprintf(stdout, "\n__________ copy_func _________\n");
5028 print_triple(state, ofunc);
5029 fprintf(stdout, "__________ copy_func _________ done\n\n");
5032 /* Make a new copy of the old function */
5033 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
5035 ofirst = old = RHS(ofunc, 0);
5038 struct occurance *occurance;
5039 int old_lhs, old_rhs;
5040 old_lhs = TRIPLE_LHS(old->sizes);
5041 old_rhs = TRIPLE_RHS(old->sizes);
5042 occurance = inline_occurance(state, base_occurance, old->occurance);
5043 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
5045 if (!triple_stores_block(state, new)) {
5046 memcpy(&new->u, &old->u, sizeof(new->u));
5049 RHS(nfunc, 0) = nfirst = new;
5052 insert_triple(state, nfirst, new);
5054 new->id |= TRIPLE_FLAG_FLATTENED;
5056 /* During the copy remember new as user of old */
5057 use_triple(old, new);
5059 /* Populate the return type if present */
5060 if (old == MISC(ofunc, 0)) {
5061 MISC(nfunc, 0) = new;
5064 } while(old != ofirst);
5066 /* Make a second pass to fix up any unresolved references */
5070 struct triple **oexpr, **nexpr;
5072 /* Lookup where the copy is, to join pointers */
5073 count = TRIPLE_SIZE(old->sizes);
5074 for(i = 0; i < count; i++) {
5075 oexpr = &old->param[i];
5076 nexpr = &new->param[i];
5077 if (!*nexpr && *oexpr && (*oexpr)->use) {
5078 *nexpr = (*oexpr)->use->member;
5079 if (*nexpr == old) {
5080 internal_error(state, 0, "new == old?");
5082 use_triple(*nexpr, new);
5084 if (!*nexpr && *oexpr) {
5085 internal_error(state, 0, "Could not copy %d\n", i);
5090 } while((old != ofirst) && (new != nfirst));
5092 /* Make a third pass to cleanup the extra useses */
5096 unuse_triple(old, new);
5099 } while ((old != ofirst) && (new != nfirst));
5103 static struct triple *flatten_call(
5104 struct compile_state *state, struct triple *first, struct triple *ptr)
5106 /* Inline the function call */
5108 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5109 struct triple *end, *nend;
5112 /* Find the triples */
5113 ofunc = MISC(ptr, 0);
5114 if (ofunc->op != OP_LIST) {
5115 internal_error(state, 0, "improper function");
5117 nfunc = copy_func(state, ofunc, ptr->occurance);
5118 nfirst = RHS(nfunc, 0)->next;
5119 /* Prepend the parameter reading into the new function list */
5120 ptype = nfunc->type->right;
5121 param = RHS(nfunc, 0)->next;
5122 pvals = TRIPLE_RHS(ptr->sizes);
5123 for(i = 0; i < pvals; i++) {
5127 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5128 atype = ptype->left;
5130 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5131 param = param->next;
5134 flatten(state, nfirst, write_expr(state, param, arg));
5135 ptype = ptype->right;
5136 param = param->next;
5139 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5140 result = read_expr(state, MISC(nfunc,0));
5143 fprintf(stdout, "\n");
5144 loc(stdout, state, 0);
5145 fprintf(stdout, "\n__________ flatten_call _________\n");
5146 print_triple(state, nfunc);
5147 fprintf(stdout, "__________ flatten_call _________ done\n\n");
5150 /* Get rid of the extra triples */
5151 nfirst = RHS(nfunc, 0)->next;
5152 free_triple(state, RHS(nfunc, 0));
5154 free_triple(state, nfunc);
5156 /* Append the new function list onto the return list */
5158 nend = nfirst->prev;
5167 static struct triple *flatten(
5168 struct compile_state *state, struct triple *first, struct triple *ptr)
5170 struct triple *orig_ptr;
5175 /* Only flatten triples once */
5176 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5181 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5185 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5186 return MISC(ptr, 0);
5189 ptr = flatten_land(state, first, ptr);
5192 ptr = flatten_lor(state, first, ptr);
5195 ptr = flatten_cond(state, first, ptr);
5198 ptr = flatten_call(state, first, ptr);
5202 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5203 use_triple(RHS(ptr, 0), ptr);
5206 use_triple(TARG(ptr, 0), ptr);
5207 if (TRIPLE_RHS(ptr->sizes)) {
5208 use_triple(RHS(ptr, 0), ptr);
5209 if (ptr->next != ptr) {
5210 use_triple(ptr->next, ptr);
5215 insert_triple(state, first, ptr);
5216 ptr->id |= TRIPLE_FLAG_FLATTENED;
5217 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5218 use_triple(MISC(ptr, 0), ptr);
5221 /* Since OP_DEREF is just a marker delete it when I flatten it */
5223 RHS(orig_ptr, 0) = 0;
5224 free_triple(state, orig_ptr);
5228 struct triple *base;
5230 if (base->op == OP_DEREF) {
5231 struct triple *left;
5233 offset = field_offset(state, base->type, ptr->u.field);
5234 left = RHS(base, 0);
5235 ptr = triple(state, OP_ADD, left->type,
5236 read_expr(state, left),
5237 int_const(state, &ulong_type, offset));
5238 free_triple(state, base);
5240 else if (base->op == OP_VAL_VEC) {
5241 base = flatten(state, first, base);
5242 ptr = struct_field(state, base, ptr->u.field);
5247 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5248 use_triple(MISC(ptr, 0), ptr);
5249 use_triple(ptr, MISC(ptr, 0));
5253 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5254 use_triple(MISC(ptr, 0), ptr);
5259 /* Flatten the easy cases we don't override */
5260 ptr = flatten_generic(state, first, ptr);
5263 } while(ptr && (ptr != orig_ptr));
5265 insert_triple(state, first, ptr);
5266 ptr->id |= TRIPLE_FLAG_FLATTENED;
5271 static void release_expr(struct compile_state *state, struct triple *expr)
5273 struct triple *head;
5274 head = label(state);
5275 flatten(state, head, expr);
5276 while(head->next != head) {
5277 release_triple(state, head->next);
5279 free_triple(state, head);
5282 static int replace_rhs_use(struct compile_state *state,
5283 struct triple *orig, struct triple *new, struct triple *use)
5285 struct triple **expr;
5288 expr = triple_rhs(state, use, 0);
5289 for(;expr; expr = triple_rhs(state, use, expr)) {
5290 if (*expr == orig) {
5296 unuse_triple(orig, use);
5297 use_triple(new, use);
5302 static int replace_lhs_use(struct compile_state *state,
5303 struct triple *orig, struct triple *new, struct triple *use)
5305 struct triple **expr;
5308 expr = triple_lhs(state, use, 0);
5309 for(;expr; expr = triple_lhs(state, use, expr)) {
5310 if (*expr == orig) {
5316 unuse_triple(orig, use);
5317 use_triple(new, use);
5322 static void propogate_use(struct compile_state *state,
5323 struct triple *orig, struct triple *new)
5325 struct triple_set *user, *next;
5326 for(user = orig->use; user; user = next) {
5332 found |= replace_rhs_use(state, orig, new, use);
5333 found |= replace_lhs_use(state, orig, new, use);
5335 internal_error(state, use, "use without use");
5339 internal_error(state, orig, "used after propogate_use");
5345 * ===========================
5348 static struct triple *mk_add_expr(
5349 struct compile_state *state, struct triple *left, struct triple *right)
5351 struct type *result_type;
5352 /* Put pointer operands on the left */
5353 if (is_pointer(right)) {
5359 left = read_expr(state, left);
5360 right = read_expr(state, right);
5361 result_type = ptr_arithmetic_result(state, left, right);
5362 if (is_pointer(left)) {
5363 right = triple(state,
5364 is_signed(right->type)? OP_SMUL : OP_UMUL,
5367 int_const(state, &ulong_type,
5368 size_of(state, left->type->left)));
5370 return triple(state, OP_ADD, result_type, left, right);
5373 static struct triple *mk_sub_expr(
5374 struct compile_state *state, struct triple *left, struct triple *right)
5376 struct type *result_type;
5377 result_type = ptr_arithmetic_result(state, left, right);
5378 left = read_expr(state, left);
5379 right = read_expr(state, right);
5380 if (is_pointer(left)) {
5381 right = triple(state,
5382 is_signed(right->type)? OP_SMUL : OP_UMUL,
5385 int_const(state, &ulong_type,
5386 size_of(state, left->type->left)));
5388 return triple(state, OP_SUB, result_type, left, right);
5391 static struct triple *mk_pre_inc_expr(
5392 struct compile_state *state, struct triple *def)
5396 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5397 return triple(state, OP_VAL, def->type,
5398 write_expr(state, def, val),
5402 static struct triple *mk_pre_dec_expr(
5403 struct compile_state *state, struct triple *def)
5407 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5408 return triple(state, OP_VAL, def->type,
5409 write_expr(state, def, val),
5413 static struct triple *mk_post_inc_expr(
5414 struct compile_state *state, struct triple *def)
5418 val = read_expr(state, def);
5419 return triple(state, OP_VAL, def->type,
5420 write_expr(state, def,
5421 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5425 static struct triple *mk_post_dec_expr(
5426 struct compile_state *state, struct triple *def)
5430 val = read_expr(state, def);
5431 return triple(state, OP_VAL, def->type,
5432 write_expr(state, def,
5433 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5437 static struct triple *mk_subscript_expr(
5438 struct compile_state *state, struct triple *left, struct triple *right)
5440 left = read_expr(state, left);
5441 right = read_expr(state, right);
5442 if (!is_pointer(left) && !is_pointer(right)) {
5443 error(state, left, "subscripted value is not a pointer");
5445 return mk_deref_expr(state, mk_add_expr(state, left, right));
5449 * Compile time evaluation
5450 * ===========================
5452 static int is_const(struct triple *ins)
5454 return IS_CONST_OP(ins->op);
5457 static int constants_equal(struct compile_state *state,
5458 struct triple *left, struct triple *right)
5461 if (!is_const(left) || !is_const(right)) {
5464 else if (left->op != right->op) {
5467 else if (!equiv_types(left->type, right->type)) {
5474 if (left->u.cval == right->u.cval) {
5480 size_t lsize, rsize;
5481 lsize = size_of(state, left->type);
5482 rsize = size_of(state, right->type);
5483 if (lsize != rsize) {
5486 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5492 if ((MISC(left, 0) == MISC(right, 0)) &&
5493 (left->u.cval == right->u.cval)) {
5498 internal_error(state, left, "uknown constant type");
5505 static int is_zero(struct triple *ins)
5507 return is_const(ins) && (ins->u.cval == 0);
5510 static int is_one(struct triple *ins)
5512 return is_const(ins) && (ins->u.cval == 1);
5515 static long_t bit_count(ulong_t value)
5520 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5531 static long_t bsr(ulong_t value)
5534 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5545 static long_t bsf(ulong_t value)
5548 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5559 static long_t log2(ulong_t value)
5564 static long_t tlog2(struct triple *ins)
5566 return log2(ins->u.cval);
5569 static int is_pow2(struct triple *ins)
5571 ulong_t value, mask;
5573 if (!is_const(ins)) {
5576 value = ins->u.cval;
5583 return ((value & mask) == value);
5586 static ulong_t read_const(struct compile_state *state,
5587 struct triple *ins, struct triple **expr)
5591 switch(rhs->type->type &TYPE_MASK) {
5603 internal_error(state, rhs, "bad type to read_const\n");
5609 static long_t read_sconst(struct triple *ins, struct triple **expr)
5613 return (long_t)(rhs->u.cval);
5616 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5618 struct triple **expr;
5619 expr = triple_rhs(state, ins, 0);
5620 for(;expr;expr = triple_rhs(state, ins, expr)) {
5622 unuse_triple(*expr, ins);
5628 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5630 struct triple **expr;
5631 expr = triple_lhs(state, ins, 0);
5632 for(;expr;expr = triple_lhs(state, ins, expr)) {
5633 unuse_triple(*expr, ins);
5638 static void check_lhs(struct compile_state *state, struct triple *ins)
5640 struct triple **expr;
5641 expr = triple_lhs(state, ins, 0);
5642 for(;expr;expr = triple_lhs(state, ins, expr)) {
5643 internal_error(state, ins, "unexpected lhs");
5647 static void check_targ(struct compile_state *state, struct triple *ins)
5649 struct triple **expr;
5650 expr = triple_targ(state, ins, 0);
5651 for(;expr;expr = triple_targ(state, ins, expr)) {
5652 internal_error(state, ins, "unexpected targ");
5656 static void wipe_ins(struct compile_state *state, struct triple *ins)
5658 /* Becareful which instructions you replace the wiped
5659 * instruction with, as there are not enough slots
5660 * in all instructions to hold all others.
5662 check_targ(state, ins);
5663 unuse_rhs(state, ins);
5664 unuse_lhs(state, ins);
5667 static void mkcopy(struct compile_state *state,
5668 struct triple *ins, struct triple *rhs)
5670 wipe_ins(state, ins);
5672 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5674 use_triple(RHS(ins, 0), ins);
5677 static void mkconst(struct compile_state *state,
5678 struct triple *ins, ulong_t value)
5680 if (!is_integral(ins) && !is_pointer(ins)) {
5681 internal_error(state, ins, "unknown type to make constant\n");
5683 wipe_ins(state, ins);
5684 ins->op = OP_INTCONST;
5685 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5686 ins->u.cval = value;
5689 static void mkaddr_const(struct compile_state *state,
5690 struct triple *ins, struct triple *sdecl, ulong_t value)
5692 wipe_ins(state, ins);
5693 ins->op = OP_ADDRCONST;
5694 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5695 MISC(ins, 0) = sdecl;
5696 ins->u.cval = value;
5697 use_triple(sdecl, ins);
5700 /* Transform multicomponent variables into simple register variables */
5701 static void flatten_structures(struct compile_state *state)
5703 struct triple *ins, *first;
5704 first = RHS(state->main_function, 0);
5706 /* Pass one expand structure values into valvecs.
5710 struct triple *next;
5712 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5713 if (ins->op == OP_VAL_VEC) {
5716 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5717 struct triple *def, **vector;
5724 get_occurance(ins->occurance);
5725 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5728 vector = &RHS(next, 0);
5729 tptr = next->type->left;
5730 for(i = 0; i < next->type->elements; i++) {
5731 struct triple *sfield;
5734 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5735 mtype = mtype->left;
5737 sfield = deref_field(state, def, mtype->field_ident);
5740 state, op, mtype, sfield, 0);
5741 put_occurance(vector[i]->occurance);
5742 get_occurance(next->occurance);
5743 vector[i]->occurance = next->occurance;
5746 propogate_use(state, ins, next);
5747 flatten(state, ins, next);
5748 free_triple(state, ins);
5750 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5751 struct triple *src, *dst, **vector;
5759 get_occurance(ins->occurance);
5760 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5763 vector = &RHS(next, 0);
5764 tptr = next->type->left;
5765 for(i = 0; i < ins->type->elements; i++) {
5766 struct triple *dfield, *sfield;
5769 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5770 mtype = mtype->left;
5772 sfield = deref_field(state, src, mtype->field_ident);
5773 dfield = deref_field(state, dst, mtype->field_ident);
5775 state, op, mtype, dfield, sfield);
5776 put_occurance(vector[i]->occurance);
5777 get_occurance(next->occurance);
5778 vector[i]->occurance = next->occurance;
5781 propogate_use(state, ins, next);
5782 flatten(state, ins, next);
5783 free_triple(state, ins);
5787 } while(ins != first);
5788 /* Pass two flatten the valvecs.
5792 struct triple *next;
5794 if (ins->op == OP_VAL_VEC) {
5795 release_triple(state, ins);
5798 } while(ins != first);
5799 /* Pass three verify the state and set ->id to 0.
5803 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5804 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5805 internal_error(state, ins, "STRUCT_TYPE remains?");
5807 if (ins->op == OP_DOT) {
5808 internal_error(state, ins, "OP_DOT remains?");
5810 if (ins->op == OP_VAL_VEC) {
5811 internal_error(state, ins, "OP_VAL_VEC remains?");
5814 } while(ins != first);
5817 /* For those operations that cannot be simplified */
5818 static void simplify_noop(struct compile_state *state, struct triple *ins)
5823 static void simplify_smul(struct compile_state *state, struct triple *ins)
5825 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5828 RHS(ins, 0) = RHS(ins, 1);
5831 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5833 left = read_sconst(ins, &RHS(ins, 0));
5834 right = read_sconst(ins, &RHS(ins, 1));
5835 mkconst(state, ins, left * right);
5837 else if (is_zero(RHS(ins, 1))) {
5838 mkconst(state, ins, 0);
5840 else if (is_one(RHS(ins, 1))) {
5841 mkcopy(state, ins, RHS(ins, 0));
5843 else if (is_pow2(RHS(ins, 1))) {
5845 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5847 insert_triple(state, ins, val);
5848 unuse_triple(RHS(ins, 1), ins);
5849 use_triple(val, ins);
5854 static void simplify_umul(struct compile_state *state, struct triple *ins)
5856 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5859 RHS(ins, 0) = RHS(ins, 1);
5862 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5863 ulong_t left, right;
5864 left = read_const(state, ins, &RHS(ins, 0));
5865 right = read_const(state, ins, &RHS(ins, 1));
5866 mkconst(state, ins, left * right);
5868 else if (is_zero(RHS(ins, 1))) {
5869 mkconst(state, ins, 0);
5871 else if (is_one(RHS(ins, 1))) {
5872 mkcopy(state, ins, RHS(ins, 0));
5874 else if (is_pow2(RHS(ins, 1))) {
5876 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5878 insert_triple(state, ins, val);
5879 unuse_triple(RHS(ins, 1), ins);
5880 use_triple(val, ins);
5885 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5887 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5889 left = read_sconst(ins, &RHS(ins, 0));
5890 right = read_sconst(ins, &RHS(ins, 1));
5891 mkconst(state, ins, left / right);
5893 else if (is_zero(RHS(ins, 0))) {
5894 mkconst(state, ins, 0);
5896 else if (is_zero(RHS(ins, 1))) {
5897 error(state, ins, "division by zero");
5899 else if (is_one(RHS(ins, 1))) {
5900 mkcopy(state, ins, RHS(ins, 0));
5902 else if (is_pow2(RHS(ins, 1))) {
5904 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5906 insert_triple(state, ins, val);
5907 unuse_triple(RHS(ins, 1), ins);
5908 use_triple(val, ins);
5913 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5915 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5916 ulong_t left, right;
5917 left = read_const(state, ins, &RHS(ins, 0));
5918 right = read_const(state, ins, &RHS(ins, 1));
5919 mkconst(state, ins, left / right);
5921 else if (is_zero(RHS(ins, 0))) {
5922 mkconst(state, ins, 0);
5924 else if (is_zero(RHS(ins, 1))) {
5925 error(state, ins, "division by zero");
5927 else if (is_one(RHS(ins, 1))) {
5928 mkcopy(state, ins, RHS(ins, 0));
5930 else if (is_pow2(RHS(ins, 1))) {
5932 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5934 insert_triple(state, ins, val);
5935 unuse_triple(RHS(ins, 1), ins);
5936 use_triple(val, ins);
5941 static void simplify_smod(struct compile_state *state, struct triple *ins)
5943 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5945 left = read_const(state, ins, &RHS(ins, 0));
5946 right = read_const(state, ins, &RHS(ins, 1));
5947 mkconst(state, ins, left % right);
5949 else if (is_zero(RHS(ins, 0))) {
5950 mkconst(state, ins, 0);
5952 else if (is_zero(RHS(ins, 1))) {
5953 error(state, ins, "division by zero");
5955 else if (is_one(RHS(ins, 1))) {
5956 mkconst(state, ins, 0);
5958 else if (is_pow2(RHS(ins, 1))) {
5960 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5962 insert_triple(state, ins, val);
5963 unuse_triple(RHS(ins, 1), ins);
5964 use_triple(val, ins);
5968 static void simplify_umod(struct compile_state *state, struct triple *ins)
5970 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5971 ulong_t left, right;
5972 left = read_const(state, ins, &RHS(ins, 0));
5973 right = read_const(state, ins, &RHS(ins, 1));
5974 mkconst(state, ins, left % right);
5976 else if (is_zero(RHS(ins, 0))) {
5977 mkconst(state, ins, 0);
5979 else if (is_zero(RHS(ins, 1))) {
5980 error(state, ins, "division by zero");
5982 else if (is_one(RHS(ins, 1))) {
5983 mkconst(state, ins, 0);
5985 else if (is_pow2(RHS(ins, 1))) {
5987 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5989 insert_triple(state, ins, val);
5990 unuse_triple(RHS(ins, 1), ins);
5991 use_triple(val, ins);
5996 static void simplify_add(struct compile_state *state, struct triple *ins)
5998 /* start with the pointer on the left */
5999 if (is_pointer(RHS(ins, 1))) {
6002 RHS(ins, 0) = RHS(ins, 1);
6005 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6006 if (RHS(ins, 0)->op == OP_INTCONST) {
6007 ulong_t left, right;
6008 left = read_const(state, ins, &RHS(ins, 0));
6009 right = read_const(state, ins, &RHS(ins, 1));
6010 mkconst(state, ins, left + right);
6012 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
6013 struct triple *sdecl;
6014 ulong_t left, right;
6015 sdecl = MISC(RHS(ins, 0), 0);
6016 left = RHS(ins, 0)->u.cval;
6017 right = RHS(ins, 1)->u.cval;
6018 mkaddr_const(state, ins, sdecl, left + right);
6021 internal_warning(state, ins, "Optimize me!");
6024 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
6027 RHS(ins, 1) = RHS(ins, 0);
6032 static void simplify_sub(struct compile_state *state, struct triple *ins)
6034 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6035 if (RHS(ins, 0)->op == OP_INTCONST) {
6036 ulong_t left, right;
6037 left = read_const(state, ins, &RHS(ins, 0));
6038 right = read_const(state, ins, &RHS(ins, 1));
6039 mkconst(state, ins, left - right);
6041 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
6042 struct triple *sdecl;
6043 ulong_t left, right;
6044 sdecl = MISC(RHS(ins, 0), 0);
6045 left = RHS(ins, 0)->u.cval;
6046 right = RHS(ins, 1)->u.cval;
6047 mkaddr_const(state, ins, sdecl, left - right);
6050 internal_warning(state, ins, "Optimize me!");
6055 static void simplify_sl(struct compile_state *state, struct triple *ins)
6057 if (is_const(RHS(ins, 1))) {
6059 right = read_const(state, ins, &RHS(ins, 1));
6060 if (right >= (size_of(state, ins->type)*8)) {
6061 warning(state, ins, "left shift count >= width of type");
6064 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6065 ulong_t left, right;
6066 left = read_const(state, ins, &RHS(ins, 0));
6067 right = read_const(state, ins, &RHS(ins, 1));
6068 mkconst(state, ins, left << right);
6072 static void simplify_usr(struct compile_state *state, struct triple *ins)
6074 if (is_const(RHS(ins, 1))) {
6076 right = read_const(state, ins, &RHS(ins, 1));
6077 if (right >= (size_of(state, ins->type)*8)) {
6078 warning(state, ins, "right shift count >= width of type");
6081 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6082 ulong_t left, right;
6083 left = read_const(state, ins, &RHS(ins, 0));
6084 right = read_const(state, ins, &RHS(ins, 1));
6085 mkconst(state, ins, left >> right);
6089 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6091 if (is_const(RHS(ins, 1))) {
6093 right = read_const(state, ins, &RHS(ins, 1));
6094 if (right >= (size_of(state, ins->type)*8)) {
6095 warning(state, ins, "right shift count >= width of type");
6098 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6100 left = read_sconst(ins, &RHS(ins, 0));
6101 right = read_sconst(ins, &RHS(ins, 1));
6102 mkconst(state, ins, left >> right);
6106 static void simplify_and(struct compile_state *state, struct triple *ins)
6108 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6109 ulong_t left, right;
6110 left = read_const(state, ins, &RHS(ins, 0));
6111 right = read_const(state, ins, &RHS(ins, 1));
6112 mkconst(state, ins, left & right);
6116 static void simplify_or(struct compile_state *state, struct triple *ins)
6118 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6119 ulong_t left, right;
6120 left = read_const(state, ins, &RHS(ins, 0));
6121 right = read_const(state, ins, &RHS(ins, 1));
6122 mkconst(state, ins, left | right);
6126 static void simplify_xor(struct compile_state *state, struct triple *ins)
6128 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6129 ulong_t left, right;
6130 left = read_const(state, ins, &RHS(ins, 0));
6131 right = read_const(state, ins, &RHS(ins, 1));
6132 mkconst(state, ins, left ^ right);
6136 static void simplify_pos(struct compile_state *state, struct triple *ins)
6138 if (is_const(RHS(ins, 0))) {
6139 mkconst(state, ins, RHS(ins, 0)->u.cval);
6142 mkcopy(state, ins, RHS(ins, 0));
6146 static void simplify_neg(struct compile_state *state, struct triple *ins)
6148 if (is_const(RHS(ins, 0))) {
6150 left = read_const(state, ins, &RHS(ins, 0));
6151 mkconst(state, ins, -left);
6153 else if (RHS(ins, 0)->op == OP_NEG) {
6154 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6158 static void simplify_invert(struct compile_state *state, struct triple *ins)
6160 if (is_const(RHS(ins, 0))) {
6162 left = read_const(state, ins, &RHS(ins, 0));
6163 mkconst(state, ins, ~left);
6167 static void simplify_eq(struct compile_state *state, struct triple *ins)
6169 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6170 ulong_t left, right;
6171 left = read_const(state, ins, &RHS(ins, 0));
6172 right = read_const(state, ins, &RHS(ins, 1));
6173 mkconst(state, ins, left == right);
6175 else if (RHS(ins, 0) == RHS(ins, 1)) {
6176 mkconst(state, ins, 1);
6180 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6182 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6183 ulong_t left, right;
6184 left = read_const(state, ins, &RHS(ins, 0));
6185 right = read_const(state, ins, &RHS(ins, 1));
6186 mkconst(state, ins, left != right);
6188 else if (RHS(ins, 0) == RHS(ins, 1)) {
6189 mkconst(state, ins, 0);
6193 static void simplify_sless(struct compile_state *state, struct triple *ins)
6195 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6197 left = read_sconst(ins, &RHS(ins, 0));
6198 right = read_sconst(ins, &RHS(ins, 1));
6199 mkconst(state, ins, left < right);
6201 else if (RHS(ins, 0) == RHS(ins, 1)) {
6202 mkconst(state, ins, 0);
6206 static void simplify_uless(struct compile_state *state, struct triple *ins)
6208 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6209 ulong_t left, right;
6210 left = read_const(state, ins, &RHS(ins, 0));
6211 right = read_const(state, ins, &RHS(ins, 1));
6212 mkconst(state, ins, left < right);
6214 else if (is_zero(RHS(ins, 0))) {
6215 mkconst(state, ins, 1);
6217 else if (RHS(ins, 0) == RHS(ins, 1)) {
6218 mkconst(state, ins, 0);
6222 static void simplify_smore(struct compile_state *state, struct triple *ins)
6224 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6226 left = read_sconst(ins, &RHS(ins, 0));
6227 right = read_sconst(ins, &RHS(ins, 1));
6228 mkconst(state, ins, left > right);
6230 else if (RHS(ins, 0) == RHS(ins, 1)) {
6231 mkconst(state, ins, 0);
6235 static void simplify_umore(struct compile_state *state, struct triple *ins)
6237 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6238 ulong_t left, right;
6239 left = read_const(state, ins, &RHS(ins, 0));
6240 right = read_const(state, ins, &RHS(ins, 1));
6241 mkconst(state, ins, left > right);
6243 else if (is_zero(RHS(ins, 1))) {
6244 mkconst(state, ins, 1);
6246 else if (RHS(ins, 0) == RHS(ins, 1)) {
6247 mkconst(state, ins, 0);
6252 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6254 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6256 left = read_sconst(ins, &RHS(ins, 0));
6257 right = read_sconst(ins, &RHS(ins, 1));
6258 mkconst(state, ins, left <= right);
6260 else if (RHS(ins, 0) == RHS(ins, 1)) {
6261 mkconst(state, ins, 1);
6265 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6267 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6268 ulong_t left, right;
6269 left = read_const(state, ins, &RHS(ins, 0));
6270 right = read_const(state, ins, &RHS(ins, 1));
6271 mkconst(state, ins, left <= right);
6273 else if (is_zero(RHS(ins, 0))) {
6274 mkconst(state, ins, 1);
6276 else if (RHS(ins, 0) == RHS(ins, 1)) {
6277 mkconst(state, ins, 1);
6281 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6283 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6285 left = read_sconst(ins, &RHS(ins, 0));
6286 right = read_sconst(ins, &RHS(ins, 1));
6287 mkconst(state, ins, left >= right);
6289 else if (RHS(ins, 0) == RHS(ins, 1)) {
6290 mkconst(state, ins, 1);
6294 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6296 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6297 ulong_t left, right;
6298 left = read_const(state, ins, &RHS(ins, 0));
6299 right = read_const(state, ins, &RHS(ins, 1));
6300 mkconst(state, ins, left >= right);
6302 else if (is_zero(RHS(ins, 1))) {
6303 mkconst(state, ins, 1);
6305 else if (RHS(ins, 0) == RHS(ins, 1)) {
6306 mkconst(state, ins, 1);
6310 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6312 if (is_const(RHS(ins, 0))) {
6314 left = read_const(state, ins, &RHS(ins, 0));
6315 mkconst(state, ins, left == 0);
6317 /* Otherwise if I am the only user... */
6318 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6320 /* Invert a boolean operation */
6321 switch(RHS(ins, 0)->op) {
6322 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
6323 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
6324 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
6325 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
6326 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
6327 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
6328 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
6329 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
6330 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
6331 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
6332 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
6333 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
6339 mkcopy(state, ins, RHS(ins, 0));
6344 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6346 if (is_const(RHS(ins, 0))) {
6348 left = read_const(state, ins, &RHS(ins, 0));
6349 mkconst(state, ins, left != 0);
6351 else switch(RHS(ins, 0)->op) {
6352 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
6353 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
6354 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6355 mkcopy(state, ins, RHS(ins, 0));
6360 static void simplify_copy(struct compile_state *state, struct triple *ins)
6362 if (is_const(RHS(ins, 0))) {
6363 switch(RHS(ins, 0)->op) {
6367 left = read_const(state, ins, &RHS(ins, 0));
6368 mkconst(state, ins, left);
6373 struct triple *sdecl;
6375 sdecl = MISC(RHS(ins, 0), 0);
6376 offset = RHS(ins, 0)->u.cval;
6377 mkaddr_const(state, ins, sdecl, offset);
6381 internal_error(state, ins, "uknown constant");
6387 static void simplify_branch(struct compile_state *state, struct triple *ins)
6389 struct block *block;
6390 if (ins->op != OP_BRANCH) {
6391 internal_error(state, ins, "not branch");
6393 if (ins->use != 0) {
6394 internal_error(state, ins, "branch use");
6396 #warning "FIXME implement simplify branch."
6397 /* The challenge here with simplify branch is that I need to
6398 * make modifications to the control flow graph as well
6399 * as to the branch instruction itself.
6401 block = ins->u.block;
6403 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6404 struct triple *targ;
6406 value = read_const(state, ins, &RHS(ins, 0));
6407 unuse_triple(RHS(ins, 0), ins);
6408 targ = TARG(ins, 0);
6409 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6411 unuse_triple(ins->next, ins);
6412 TARG(ins, 0) = targ;
6415 unuse_triple(targ, ins);
6416 TARG(ins, 0) = ins->next;
6418 #warning "FIXME handle the case of making a branch unconditional"
6420 if (TARG(ins, 0) == ins->next) {
6421 unuse_triple(ins->next, ins);
6422 if (TRIPLE_RHS(ins->sizes)) {
6423 unuse_triple(RHS(ins, 0), ins);
6424 unuse_triple(ins->next, ins);
6426 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6429 internal_error(state, ins, "noop use != 0");
6431 #warning "FIXME handle the case of killing a branch"
6435 int phi_present(struct block *block)
6443 if (ptr->op == OP_PHI) {
6447 } while(ptr != block->last);
6451 static void simplify_label(struct compile_state *state, struct triple *ins)
6453 #warning "FIXME enable simplify_label"
6454 struct triple *first, *last;
6455 first = RHS(state->main_function, 0);
6457 /* Ignore the first and last instructions */
6458 if ((ins == first) || (ins == last)) {
6461 if (ins->use == 0) {
6464 else if (ins->prev->op == OP_LABEL) {
6465 struct block *block;
6466 block = ins->prev->u.block;
6467 /* In general it is not safe to merge one label that
6468 * imediately follows another. The problem is that the empty
6469 * looking block may have phi functions that depend on it.
6472 (!phi_present(block->left) &&
6473 !phi_present(block->right)))
6475 struct triple_set *user, *next;
6477 for(user = ins->use; user; user = next) {
6481 if (TARG(use, 0) == ins) {
6482 TARG(use, 0) = ins->prev;
6483 unuse_triple(ins, use);
6484 use_triple(ins->prev, use);
6488 internal_error(state, ins, "noop use != 0");
6494 static void simplify_phi(struct compile_state *state, struct triple *ins)
6496 struct triple **expr;
6498 expr = triple_rhs(state, ins, 0);
6499 if (!*expr || !is_const(*expr)) {
6502 value = read_const(state, ins, expr);
6503 for(;expr;expr = triple_rhs(state, ins, expr)) {
6504 if (!*expr || !is_const(*expr)) {
6507 if (value != read_const(state, ins, expr)) {
6511 mkconst(state, ins, value);
6515 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6517 if (is_const(RHS(ins, 0))) {
6519 left = read_const(state, ins, &RHS(ins, 0));
6520 mkconst(state, ins, bsf(left));
6524 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6526 if (is_const(RHS(ins, 0))) {
6528 left = read_const(state, ins, &RHS(ins, 0));
6529 mkconst(state, ins, bsr(left));
6534 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6535 static const simplify_t table_simplify[] = {
6537 #define simplify_sdivt simplify_noop
6538 #define simplify_udivt simplify_noop
6541 #define simplify_smul simplify_noop
6542 #define simplify_umul simplify_noop
6543 #define simplify_sdiv simplify_noop
6544 #define simplify_udiv simplify_noop
6545 #define simplify_smod simplify_noop
6546 #define simplify_umod simplify_noop
6549 #define simplify_add simplify_noop
6550 #define simplify_sub simplify_noop
6553 #define simplify_sl simplify_noop
6554 #define simplify_usr simplify_noop
6555 #define simplify_ssr simplify_noop
6558 #define simplify_and simplify_noop
6559 #define simplify_xor simplify_noop
6560 #define simplify_or simplify_noop
6563 #define simplify_pos simplify_noop
6564 #define simplify_neg simplify_noop
6565 #define simplify_invert simplify_noop
6569 #define simplify_eq simplify_noop
6570 #define simplify_noteq simplify_noop
6573 #define simplify_sless simplify_noop
6574 #define simplify_uless simplify_noop
6575 #define simplify_smore simplify_noop
6576 #define simplify_umore simplify_noop
6579 #define simplify_slesseq simplify_noop
6580 #define simplify_ulesseq simplify_noop
6581 #define simplify_smoreeq simplify_noop
6582 #define simplify_umoreeq simplify_noop
6585 #define simplify_lfalse simplify_noop
6588 #define simplify_ltrue simplify_noop
6592 #define simplify_copy simplify_noop
6596 #define simplify_branch simplify_noop
6599 #define simplify_label simplify_noop
6603 #define simplify_phi simplify_noop
6607 #define simplify_bsf simplify_noop
6608 #define simplify_bsr simplify_noop
6611 [OP_SDIVT ] = simplify_sdivt,
6612 [OP_UDIVT ] = simplify_udivt,
6613 [OP_SMUL ] = simplify_smul,
6614 [OP_UMUL ] = simplify_umul,
6615 [OP_SDIV ] = simplify_sdiv,
6616 [OP_UDIV ] = simplify_udiv,
6617 [OP_SMOD ] = simplify_smod,
6618 [OP_UMOD ] = simplify_umod,
6619 [OP_ADD ] = simplify_add,
6620 [OP_SUB ] = simplify_sub,
6621 [OP_SL ] = simplify_sl,
6622 [OP_USR ] = simplify_usr,
6623 [OP_SSR ] = simplify_ssr,
6624 [OP_AND ] = simplify_and,
6625 [OP_XOR ] = simplify_xor,
6626 [OP_OR ] = simplify_or,
6627 [OP_POS ] = simplify_pos,
6628 [OP_NEG ] = simplify_neg,
6629 [OP_INVERT ] = simplify_invert,
6631 [OP_EQ ] = simplify_eq,
6632 [OP_NOTEQ ] = simplify_noteq,
6633 [OP_SLESS ] = simplify_sless,
6634 [OP_ULESS ] = simplify_uless,
6635 [OP_SMORE ] = simplify_smore,
6636 [OP_UMORE ] = simplify_umore,
6637 [OP_SLESSEQ ] = simplify_slesseq,
6638 [OP_ULESSEQ ] = simplify_ulesseq,
6639 [OP_SMOREEQ ] = simplify_smoreeq,
6640 [OP_UMOREEQ ] = simplify_umoreeq,
6641 [OP_LFALSE ] = simplify_lfalse,
6642 [OP_LTRUE ] = simplify_ltrue,
6644 [OP_LOAD ] = simplify_noop,
6645 [OP_STORE ] = simplify_noop,
6647 [OP_NOOP ] = simplify_noop,
6649 [OP_INTCONST ] = simplify_noop,
6650 [OP_BLOBCONST ] = simplify_noop,
6651 [OP_ADDRCONST ] = simplify_noop,
6653 [OP_WRITE ] = simplify_noop,
6654 [OP_READ ] = simplify_noop,
6655 [OP_COPY ] = simplify_copy,
6656 [OP_PIECE ] = simplify_noop,
6657 [OP_ASM ] = simplify_noop,
6659 [OP_DOT ] = simplify_noop,
6660 [OP_VAL_VEC ] = simplify_noop,
6662 [OP_LIST ] = simplify_noop,
6663 [OP_BRANCH ] = simplify_branch,
6664 [OP_LABEL ] = simplify_label,
6665 [OP_ADECL ] = simplify_noop,
6666 [OP_SDECL ] = simplify_noop,
6667 [OP_PHI ] = simplify_phi,
6669 [OP_INB ] = simplify_noop,
6670 [OP_INW ] = simplify_noop,
6671 [OP_INL ] = simplify_noop,
6672 [OP_OUTB ] = simplify_noop,
6673 [OP_OUTW ] = simplify_noop,
6674 [OP_OUTL ] = simplify_noop,
6675 [OP_BSF ] = simplify_bsf,
6676 [OP_BSR ] = simplify_bsr,
6677 [OP_RDMSR ] = simplify_noop,
6678 [OP_WRMSR ] = simplify_noop,
6679 [OP_HLT ] = simplify_noop,
6682 static void simplify(struct compile_state *state, struct triple *ins)
6685 simplify_t do_simplify;
6689 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6693 do_simplify = table_simplify[op];
6696 internal_error(state, ins, "cannot simplify op: %d %s\n",
6700 do_simplify(state, ins);
6701 } while(ins->op != op);
6704 static void simplify_all(struct compile_state *state)
6706 struct triple *ins, *first;
6707 first = RHS(state->main_function, 0);
6710 simplify(state, ins);
6712 }while(ins != first);
6717 * ============================
6720 static void register_builtin_function(struct compile_state *state,
6721 const char *name, int op, struct type *rtype, ...)
6723 struct type *ftype, *atype, *param, **next;
6724 struct triple *def, *arg, *result, *work, *last, *first;
6725 struct hash_entry *ident;
6726 struct file_state file;
6732 /* Dummy file state to get debug handling right */
6733 memset(&file, 0, sizeof(file));
6734 file.basename = "<built-in>";
6736 file.report_line = 1;
6737 file.report_name = file.basename;
6738 file.prev = state->file;
6739 state->file = &file;
6740 state->function = name;
6742 /* Find the Parameter count */
6743 valid_op(state, op);
6744 parameters = table_ops[op].rhs;
6745 if (parameters < 0 ) {
6746 internal_error(state, 0, "Invalid builtin parameter count");
6749 /* Find the function type */
6750 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6751 next = &ftype->right;
6752 va_start(args, rtype);
6753 for(i = 0; i < parameters; i++) {
6754 atype = va_arg(args, struct type *);
6758 *next = new_type(TYPE_PRODUCT, *next, atype);
6759 next = &((*next)->right);
6767 /* Generate the needed triples */
6768 def = triple(state, OP_LIST, ftype, 0, 0);
6769 first = label(state);
6770 RHS(def, 0) = first;
6772 /* Now string them together */
6773 param = ftype->right;
6774 for(i = 0; i < parameters; i++) {
6775 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6776 atype = param->left;
6780 arg = flatten(state, first, variable(state, atype));
6781 param = param->right;
6784 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6785 result = flatten(state, first, variable(state, rtype));
6787 MISC(def, 0) = result;
6788 work = new_triple(state, op, rtype, -1, parameters);
6789 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6790 RHS(work, i) = read_expr(state, arg);
6792 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6794 /* Populate the LHS with the target registers */
6795 work = flatten(state, first, work);
6796 work->type = &void_type;
6797 param = rtype->left;
6798 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6799 internal_error(state, 0, "Invalid result type");
6801 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6802 for(i = 0; i < rtype->elements; i++) {
6803 struct triple *piece;
6805 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6806 atype = param->left;
6808 if (!TYPE_ARITHMETIC(atype->type) &&
6809 !TYPE_PTR(atype->type)) {
6810 internal_error(state, 0, "Invalid lhs type");
6812 piece = triple(state, OP_PIECE, atype, work, 0);
6814 LHS(work, i) = piece;
6815 RHS(val, i) = piece;
6820 work = write_expr(state, result, work);
6822 work = flatten(state, first, work);
6823 last = flatten(state, first, label(state));
6824 name_len = strlen(name);
6825 ident = lookup(state, name, name_len);
6826 symbol(state, ident, &ident->sym_ident, def, ftype);
6828 state->file = file.prev;
6829 state->function = 0;
6831 fprintf(stdout, "\n");
6832 loc(stdout, state, 0);
6833 fprintf(stdout, "\n__________ builtin_function _________\n");
6834 print_triple(state, def);
6835 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6839 static struct type *partial_struct(struct compile_state *state,
6840 const char *field_name, struct type *type, struct type *rest)
6842 struct hash_entry *field_ident;
6843 struct type *result;
6846 field_name_len = strlen(field_name);
6847 field_ident = lookup(state, field_name, field_name_len);
6849 result = clone_type(0, type);
6850 result->field_ident = field_ident;
6853 result = new_type(TYPE_PRODUCT, result, rest);
6858 static struct type *register_builtin_type(struct compile_state *state,
6859 const char *name, struct type *type)
6861 struct hash_entry *ident;
6864 name_len = strlen(name);
6865 ident = lookup(state, name, name_len);
6867 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6868 ulong_t elements = 0;
6870 type = new_type(TYPE_STRUCT, type, 0);
6872 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6874 field = field->right;
6877 symbol(state, ident, &ident->sym_struct, 0, type);
6878 type->type_ident = ident;
6879 type->elements = elements;
6881 symbol(state, ident, &ident->sym_ident, 0, type);
6882 ident->tok = TOK_TYPE_NAME;
6887 static void register_builtins(struct compile_state *state)
6889 struct type *div_type, *ldiv_type;
6890 struct type *udiv_type, *uldiv_type;
6891 struct type *msr_type;
6893 div_type = register_builtin_type(state, "__builtin_div_t",
6894 partial_struct(state, "quot", &int_type,
6895 partial_struct(state, "rem", &int_type, 0)));
6896 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
6897 partial_struct(state, "quot", &long_type,
6898 partial_struct(state, "rem", &long_type, 0)));
6899 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
6900 partial_struct(state, "quot", &uint_type,
6901 partial_struct(state, "rem", &uint_type, 0)));
6902 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
6903 partial_struct(state, "quot", &ulong_type,
6904 partial_struct(state, "rem", &ulong_type, 0)));
6906 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
6907 &int_type, &int_type);
6908 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
6909 &long_type, &long_type);
6910 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
6911 &uint_type, &uint_type);
6912 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
6913 &ulong_type, &ulong_type);
6915 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6917 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6919 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6922 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6923 &uchar_type, &ushort_type);
6924 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6925 &ushort_type, &ushort_type);
6926 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6927 &uint_type, &ushort_type);
6929 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6931 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6934 msr_type = register_builtin_type(state, "__builtin_msr_t",
6935 partial_struct(state, "lo", &ulong_type,
6936 partial_struct(state, "hi", &ulong_type, 0)));
6938 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6940 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6941 &ulong_type, &ulong_type, &ulong_type);
6943 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6947 static struct type *declarator(
6948 struct compile_state *state, struct type *type,
6949 struct hash_entry **ident, int need_ident);
6950 static void decl(struct compile_state *state, struct triple *first);
6951 static struct type *specifier_qualifier_list(struct compile_state *state);
6952 static int isdecl_specifier(int tok);
6953 static struct type *decl_specifiers(struct compile_state *state);
6954 static int istype(int tok);
6955 static struct triple *expr(struct compile_state *state);
6956 static struct triple *assignment_expr(struct compile_state *state);
6957 static struct type *type_name(struct compile_state *state);
6958 static void statement(struct compile_state *state, struct triple *fist);
6960 static struct triple *call_expr(
6961 struct compile_state *state, struct triple *func)
6964 struct type *param, *type;
6965 ulong_t pvals, index;
6967 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6968 error(state, 0, "Called object is not a function");
6970 if (func->op != OP_LIST) {
6971 internal_error(state, 0, "improper function");
6973 eat(state, TOK_LPAREN);
6974 /* Find the return type without any specifiers */
6975 type = clone_type(0, func->type->left);
6976 def = new_triple(state, OP_CALL, func->type, -1, -1);
6979 pvals = TRIPLE_RHS(def->sizes);
6980 MISC(def, 0) = func;
6982 param = func->type->right;
6983 for(index = 0; index < pvals; index++) {
6985 struct type *arg_type;
6986 val = read_expr(state, assignment_expr(state));
6988 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6989 arg_type = param->left;
6991 write_compatible(state, arg_type, val->type);
6992 RHS(def, index) = val;
6993 if (index != (pvals - 1)) {
6994 eat(state, TOK_COMMA);
6995 param = param->right;
6998 eat(state, TOK_RPAREN);
7003 static struct triple *character_constant(struct compile_state *state)
7007 const signed char *str, *end;
7010 eat(state, TOK_LIT_CHAR);
7011 tk = &state->token[0];
7012 str = tk->val.str + 1;
7013 str_len = tk->str_len - 2;
7015 error(state, 0, "empty character constant");
7017 end = str + str_len;
7018 c = char_value(state, &str, end);
7020 error(state, 0, "multibyte character constant not supported");
7022 def = int_const(state, &char_type, (ulong_t)((long_t)c));
7026 static struct triple *string_constant(struct compile_state *state)
7031 const signed char *str, *end;
7032 signed char *buf, *ptr;
7036 type = new_type(TYPE_ARRAY, &char_type, 0);
7038 /* The while loop handles string concatenation */
7040 eat(state, TOK_LIT_STRING);
7041 tk = &state->token[0];
7042 str = tk->val.str + 1;
7043 str_len = tk->str_len - 2;
7045 error(state, 0, "negative string constant length");
7047 end = str + str_len;
7049 buf = xmalloc(type->elements + str_len + 1, "string_constant");
7050 memcpy(buf, ptr, type->elements);
7051 ptr = buf + type->elements;
7053 *ptr++ = char_value(state, &str, end);
7055 type->elements = ptr - buf;
7056 } while(peek(state) == TOK_LIT_STRING);
7058 type->elements += 1;
7059 def = triple(state, OP_BLOBCONST, type, 0, 0);
7065 static struct triple *integer_constant(struct compile_state *state)
7074 eat(state, TOK_LIT_INT);
7075 tk = &state->token[0];
7077 decimal = (tk->val.str[0] != '0');
7078 val = strtoul(tk->val.str, &end, 0);
7079 if ((val == ULONG_MAX) && (errno == ERANGE)) {
7080 error(state, 0, "Integer constant to large");
7083 if ((*end == 'u') || (*end == 'U')) {
7087 if ((*end == 'l') || (*end == 'L')) {
7091 if ((*end == 'u') || (*end == 'U')) {
7096 error(state, 0, "Junk at end of integer constant");
7103 if (!decimal && (val > LONG_MAX)) {
7109 if (val > UINT_MAX) {
7115 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
7118 else if (!decimal && (val > LONG_MAX)) {
7121 else if (val > INT_MAX) {
7125 def = int_const(state, type, val);
7129 static struct triple *primary_expr(struct compile_state *state)
7137 struct hash_entry *ident;
7138 /* Here ident is either:
7141 * an enumeration constant.
7143 eat(state, TOK_IDENT);
7144 ident = state->token[0].ident;
7145 if (!ident->sym_ident) {
7146 error(state, 0, "%s undeclared", ident->name);
7148 def = ident->sym_ident->def;
7151 case TOK_ENUM_CONST:
7152 /* Here ident is an enumeration constant */
7153 eat(state, TOK_ENUM_CONST);
7158 eat(state, TOK_LPAREN);
7160 eat(state, TOK_RPAREN);
7163 def = integer_constant(state);
7166 eat(state, TOK_LIT_FLOAT);
7167 error(state, 0, "Floating point constants not supported");
7172 def = character_constant(state);
7174 case TOK_LIT_STRING:
7175 def = string_constant(state);
7179 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7184 static struct triple *postfix_expr(struct compile_state *state)
7188 def = primary_expr(state);
7190 struct triple *left;
7194 switch((tok = peek(state))) {
7196 eat(state, TOK_LBRACKET);
7197 def = mk_subscript_expr(state, left, expr(state));
7198 eat(state, TOK_RBRACKET);
7201 def = call_expr(state, def);
7205 struct hash_entry *field;
7206 eat(state, TOK_DOT);
7207 eat(state, TOK_IDENT);
7208 field = state->token[0].ident;
7209 def = deref_field(state, def, field);
7214 struct hash_entry *field;
7215 eat(state, TOK_ARROW);
7216 eat(state, TOK_IDENT);
7217 field = state->token[0].ident;
7218 def = mk_deref_expr(state, read_expr(state, def));
7219 def = deref_field(state, def, field);
7223 eat(state, TOK_PLUSPLUS);
7224 def = mk_post_inc_expr(state, left);
7226 case TOK_MINUSMINUS:
7227 eat(state, TOK_MINUSMINUS);
7228 def = mk_post_dec_expr(state, left);
7238 static struct triple *cast_expr(struct compile_state *state);
7240 static struct triple *unary_expr(struct compile_state *state)
7242 struct triple *def, *right;
7244 switch((tok = peek(state))) {
7246 eat(state, TOK_PLUSPLUS);
7247 def = mk_pre_inc_expr(state, unary_expr(state));
7249 case TOK_MINUSMINUS:
7250 eat(state, TOK_MINUSMINUS);
7251 def = mk_pre_dec_expr(state, unary_expr(state));
7254 eat(state, TOK_AND);
7255 def = mk_addr_expr(state, cast_expr(state), 0);
7258 eat(state, TOK_STAR);
7259 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7262 eat(state, TOK_PLUS);
7263 right = read_expr(state, cast_expr(state));
7264 arithmetic(state, right);
7265 def = integral_promotion(state, right);
7268 eat(state, TOK_MINUS);
7269 right = read_expr(state, cast_expr(state));
7270 arithmetic(state, right);
7271 def = integral_promotion(state, right);
7272 def = triple(state, OP_NEG, def->type, def, 0);
7275 eat(state, TOK_TILDE);
7276 right = read_expr(state, cast_expr(state));
7277 integral(state, right);
7278 def = integral_promotion(state, right);
7279 def = triple(state, OP_INVERT, def->type, def, 0);
7282 eat(state, TOK_BANG);
7283 right = read_expr(state, cast_expr(state));
7285 def = lfalse_expr(state, right);
7291 eat(state, TOK_SIZEOF);
7293 tok2 = peek2(state);
7294 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7295 eat(state, TOK_LPAREN);
7296 type = type_name(state);
7297 eat(state, TOK_RPAREN);
7300 struct triple *expr;
7301 expr = unary_expr(state);
7303 release_expr(state, expr);
7305 def = int_const(state, &ulong_type, size_of(state, type));
7312 eat(state, TOK_ALIGNOF);
7314 tok2 = peek2(state);
7315 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7316 eat(state, TOK_LPAREN);
7317 type = type_name(state);
7318 eat(state, TOK_RPAREN);
7321 struct triple *expr;
7322 expr = unary_expr(state);
7324 release_expr(state, expr);
7326 def = int_const(state, &ulong_type, align_of(state, type));
7330 def = postfix_expr(state);
7336 static struct triple *cast_expr(struct compile_state *state)
7341 tok2 = peek2(state);
7342 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7344 eat(state, TOK_LPAREN);
7345 type = type_name(state);
7346 eat(state, TOK_RPAREN);
7347 def = read_expr(state, cast_expr(state));
7348 def = triple(state, OP_COPY, type, def, 0);
7351 def = unary_expr(state);
7356 static struct triple *mult_expr(struct compile_state *state)
7360 def = cast_expr(state);
7362 struct triple *left, *right;
7363 struct type *result_type;
7366 switch(tok = (peek(state))) {
7370 left = read_expr(state, def);
7371 arithmetic(state, left);
7375 right = read_expr(state, cast_expr(state));
7376 arithmetic(state, right);
7378 result_type = arithmetic_result(state, left, right);
7379 sign = is_signed(result_type);
7382 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7383 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
7384 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
7386 def = triple(state, op, result_type, left, right);
7396 static struct triple *add_expr(struct compile_state *state)
7400 def = mult_expr(state);
7403 switch( peek(state)) {
7405 eat(state, TOK_PLUS);
7406 def = mk_add_expr(state, def, mult_expr(state));
7409 eat(state, TOK_MINUS);
7410 def = mk_sub_expr(state, def, mult_expr(state));
7420 static struct triple *shift_expr(struct compile_state *state)
7424 def = add_expr(state);
7426 struct triple *left, *right;
7429 switch((tok = peek(state))) {
7432 left = read_expr(state, def);
7433 integral(state, left);
7434 left = integral_promotion(state, left);
7438 right = read_expr(state, add_expr(state));
7439 integral(state, right);
7440 right = integral_promotion(state, right);
7442 op = (tok == TOK_SL)? OP_SL :
7443 is_signed(left->type)? OP_SSR: OP_USR;
7445 def = triple(state, op, left->type, left, right);
7455 static struct triple *relational_expr(struct compile_state *state)
7457 #warning "Extend relational exprs to work on more than arithmetic types"
7460 def = shift_expr(state);
7462 struct triple *left, *right;
7463 struct type *arg_type;
7466 switch((tok = peek(state))) {
7471 left = read_expr(state, def);
7472 arithmetic(state, left);
7476 right = read_expr(state, shift_expr(state));
7477 arithmetic(state, right);
7479 arg_type = arithmetic_result(state, left, right);
7480 sign = is_signed(arg_type);
7483 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7484 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7485 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7486 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7488 def = triple(state, op, &int_type, left, right);
7498 static struct triple *equality_expr(struct compile_state *state)
7500 #warning "Extend equality exprs to work on more than arithmetic types"
7503 def = relational_expr(state);
7505 struct triple *left, *right;
7508 switch((tok = peek(state))) {
7511 left = read_expr(state, def);
7512 arithmetic(state, left);
7514 right = read_expr(state, relational_expr(state));
7515 arithmetic(state, right);
7516 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7517 def = triple(state, op, &int_type, left, right);
7527 static struct triple *and_expr(struct compile_state *state)
7530 def = equality_expr(state);
7531 while(peek(state) == TOK_AND) {
7532 struct triple *left, *right;
7533 struct type *result_type;
7534 left = read_expr(state, def);
7535 integral(state, left);
7536 eat(state, TOK_AND);
7537 right = read_expr(state, equality_expr(state));
7538 integral(state, right);
7539 result_type = arithmetic_result(state, left, right);
7540 def = triple(state, OP_AND, result_type, left, right);
7545 static struct triple *xor_expr(struct compile_state *state)
7548 def = and_expr(state);
7549 while(peek(state) == TOK_XOR) {
7550 struct triple *left, *right;
7551 struct type *result_type;
7552 left = read_expr(state, def);
7553 integral(state, left);
7554 eat(state, TOK_XOR);
7555 right = read_expr(state, and_expr(state));
7556 integral(state, right);
7557 result_type = arithmetic_result(state, left, right);
7558 def = triple(state, OP_XOR, result_type, left, right);
7563 static struct triple *or_expr(struct compile_state *state)
7566 def = xor_expr(state);
7567 while(peek(state) == TOK_OR) {
7568 struct triple *left, *right;
7569 struct type *result_type;
7570 left = read_expr(state, def);
7571 integral(state, left);
7573 right = read_expr(state, xor_expr(state));
7574 integral(state, right);
7575 result_type = arithmetic_result(state, left, right);
7576 def = triple(state, OP_OR, result_type, left, right);
7581 static struct triple *land_expr(struct compile_state *state)
7584 def = or_expr(state);
7585 while(peek(state) == TOK_LOGAND) {
7586 struct triple *left, *right;
7587 left = read_expr(state, def);
7589 eat(state, TOK_LOGAND);
7590 right = read_expr(state, or_expr(state));
7593 def = triple(state, OP_LAND, &int_type,
7594 ltrue_expr(state, left),
7595 ltrue_expr(state, right));
7600 static struct triple *lor_expr(struct compile_state *state)
7603 def = land_expr(state);
7604 while(peek(state) == TOK_LOGOR) {
7605 struct triple *left, *right;
7606 left = read_expr(state, def);
7608 eat(state, TOK_LOGOR);
7609 right = read_expr(state, land_expr(state));
7612 def = triple(state, OP_LOR, &int_type,
7613 ltrue_expr(state, left),
7614 ltrue_expr(state, right));
7619 static struct triple *conditional_expr(struct compile_state *state)
7622 def = lor_expr(state);
7623 if (peek(state) == TOK_QUEST) {
7624 struct triple *test, *left, *right;
7626 test = ltrue_expr(state, read_expr(state, def));
7627 eat(state, TOK_QUEST);
7628 left = read_expr(state, expr(state));
7629 eat(state, TOK_COLON);
7630 right = read_expr(state, conditional_expr(state));
7632 def = cond_expr(state, test, left, right);
7637 static struct triple *eval_const_expr(
7638 struct compile_state *state, struct triple *expr)
7641 if (is_const(expr)) {
7645 /* If we don't start out as a constant simplify into one */
7646 struct triple *head, *ptr;
7647 head = label(state); /* dummy initial triple */
7648 flatten(state, head, expr);
7649 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7650 simplify(state, ptr);
7652 /* Remove the constant value the tail of the list */
7654 def->prev->next = def->next;
7655 def->next->prev = def->prev;
7656 def->next = def->prev = def;
7657 if (!is_const(def)) {
7658 error(state, 0, "Not a constant expression");
7660 /* Free the intermediate expressions */
7661 while(head->next != head) {
7662 release_triple(state, head->next);
7664 free_triple(state, head);
7669 static struct triple *constant_expr(struct compile_state *state)
7671 return eval_const_expr(state, conditional_expr(state));
7674 static struct triple *assignment_expr(struct compile_state *state)
7676 struct triple *def, *left, *right;
7678 /* The C grammer in K&R shows assignment expressions
7679 * only taking unary expressions as input on their
7680 * left hand side. But specifies the precedence of
7681 * assignemnt as the lowest operator except for comma.
7683 * Allowing conditional expressions on the left hand side
7684 * of an assignement results in a grammar that accepts
7685 * a larger set of statements than standard C. As long
7686 * as the subset of the grammar that is standard C behaves
7687 * correctly this should cause no problems.
7689 * For the extra token strings accepted by the grammar
7690 * none of them should produce a valid lvalue, so they
7691 * should not produce functioning programs.
7693 * GCC has this bug as well, so surprises should be minimal.
7695 def = conditional_expr(state);
7697 switch((tok = peek(state))) {
7699 lvalue(state, left);
7701 def = write_expr(state, left,
7702 read_expr(state, assignment_expr(state)));
7707 lvalue(state, left);
7708 arithmetic(state, left);
7710 right = read_expr(state, assignment_expr(state));
7711 arithmetic(state, right);
7713 sign = is_signed(left->type);
7716 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7717 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7718 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7720 def = write_expr(state, left,
7721 triple(state, op, left->type,
7722 read_expr(state, left), right));
7725 lvalue(state, left);
7726 eat(state, TOK_PLUSEQ);
7727 def = write_expr(state, left,
7728 mk_add_expr(state, left, assignment_expr(state)));
7731 lvalue(state, left);
7732 eat(state, TOK_MINUSEQ);
7733 def = write_expr(state, left,
7734 mk_sub_expr(state, left, assignment_expr(state)));
7741 lvalue(state, left);
7742 integral(state, left);
7744 right = read_expr(state, assignment_expr(state));
7745 integral(state, right);
7746 right = integral_promotion(state, right);
7747 sign = is_signed(left->type);
7750 case TOK_SLEQ: op = OP_SL; break;
7751 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7752 case TOK_ANDEQ: op = OP_AND; break;
7753 case TOK_XOREQ: op = OP_XOR; break;
7754 case TOK_OREQ: op = OP_OR; break;
7756 def = write_expr(state, left,
7757 triple(state, op, left->type,
7758 read_expr(state, left), right));
7764 static struct triple *expr(struct compile_state *state)
7767 def = assignment_expr(state);
7768 while(peek(state) == TOK_COMMA) {
7769 struct triple *left, *right;
7771 eat(state, TOK_COMMA);
7772 right = assignment_expr(state);
7773 def = triple(state, OP_COMMA, right->type, left, right);
7778 static void expr_statement(struct compile_state *state, struct triple *first)
7780 if (peek(state) != TOK_SEMI) {
7781 flatten(state, first, expr(state));
7783 eat(state, TOK_SEMI);
7786 static void if_statement(struct compile_state *state, struct triple *first)
7788 struct triple *test, *jmp1, *jmp2, *middle, *end;
7790 jmp1 = jmp2 = middle = 0;
7792 eat(state, TOK_LPAREN);
7795 /* Cleanup and invert the test */
7796 test = lfalse_expr(state, read_expr(state, test));
7797 eat(state, TOK_RPAREN);
7798 /* Generate the needed pieces */
7799 middle = label(state);
7800 jmp1 = branch(state, middle, test);
7801 /* Thread the pieces together */
7802 flatten(state, first, test);
7803 flatten(state, first, jmp1);
7804 flatten(state, first, label(state));
7805 statement(state, first);
7806 if (peek(state) == TOK_ELSE) {
7807 eat(state, TOK_ELSE);
7808 /* Generate the rest of the pieces */
7810 jmp2 = branch(state, end, 0);
7811 /* Thread them together */
7812 flatten(state, first, jmp2);
7813 flatten(state, first, middle);
7814 statement(state, first);
7815 flatten(state, first, end);
7818 flatten(state, first, middle);
7822 static void for_statement(struct compile_state *state, struct triple *first)
7824 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7825 struct triple *label1, *label2, *label3;
7826 struct hash_entry *ident;
7828 eat(state, TOK_FOR);
7829 eat(state, TOK_LPAREN);
7830 head = test = tail = jmp1 = jmp2 = 0;
7831 if (peek(state) != TOK_SEMI) {
7834 eat(state, TOK_SEMI);
7835 if (peek(state) != TOK_SEMI) {
7838 test = ltrue_expr(state, read_expr(state, test));
7840 eat(state, TOK_SEMI);
7841 if (peek(state) != TOK_RPAREN) {
7844 eat(state, TOK_RPAREN);
7845 /* Generate the needed pieces */
7846 label1 = label(state);
7847 label2 = label(state);
7848 label3 = label(state);
7850 jmp1 = branch(state, label3, 0);
7851 jmp2 = branch(state, label1, test);
7854 jmp2 = branch(state, label1, 0);
7857 /* Remember where break and continue go */
7859 ident = state->i_break;
7860 symbol(state, ident, &ident->sym_ident, end, end->type);
7861 ident = state->i_continue;
7862 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7863 /* Now include the body */
7864 flatten(state, first, head);
7865 flatten(state, first, jmp1);
7866 flatten(state, first, label1);
7867 statement(state, first);
7868 flatten(state, first, label2);
7869 flatten(state, first, tail);
7870 flatten(state, first, label3);
7871 flatten(state, first, test);
7872 flatten(state, first, jmp2);
7873 flatten(state, first, end);
7874 /* Cleanup the break/continue scope */
7878 static void while_statement(struct compile_state *state, struct triple *first)
7880 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7881 struct hash_entry *ident;
7882 eat(state, TOK_WHILE);
7883 eat(state, TOK_LPAREN);
7886 test = ltrue_expr(state, read_expr(state, test));
7887 eat(state, TOK_RPAREN);
7888 /* Generate the needed pieces */
7889 label1 = label(state);
7890 label2 = label(state);
7891 jmp1 = branch(state, label2, 0);
7892 jmp2 = branch(state, label1, test);
7894 /* Remember where break and continue go */
7896 ident = state->i_break;
7897 symbol(state, ident, &ident->sym_ident, end, end->type);
7898 ident = state->i_continue;
7899 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7900 /* Thread them together */
7901 flatten(state, first, jmp1);
7902 flatten(state, first, label1);
7903 statement(state, first);
7904 flatten(state, first, label2);
7905 flatten(state, first, test);
7906 flatten(state, first, jmp2);
7907 flatten(state, first, end);
7908 /* Cleanup the break/continue scope */
7912 static void do_statement(struct compile_state *state, struct triple *first)
7914 struct triple *label1, *label2, *test, *end;
7915 struct hash_entry *ident;
7917 /* Generate the needed pieces */
7918 label1 = label(state);
7919 label2 = label(state);
7921 /* Remember where break and continue go */
7923 ident = state->i_break;
7924 symbol(state, ident, &ident->sym_ident, end, end->type);
7925 ident = state->i_continue;
7926 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7927 /* Now include the body */
7928 flatten(state, first, label1);
7929 statement(state, first);
7930 /* Cleanup the break/continue scope */
7932 /* Eat the rest of the loop */
7933 eat(state, TOK_WHILE);
7934 eat(state, TOK_LPAREN);
7935 test = read_expr(state, expr(state));
7937 eat(state, TOK_RPAREN);
7938 eat(state, TOK_SEMI);
7939 /* Thread the pieces together */
7940 test = ltrue_expr(state, test);
7941 flatten(state, first, label2);
7942 flatten(state, first, test);
7943 flatten(state, first, branch(state, label1, test));
7944 flatten(state, first, end);
7948 static void return_statement(struct compile_state *state, struct triple *first)
7950 struct triple *jmp, *mv, *dest, *var, *val;
7952 eat(state, TOK_RETURN);
7954 #warning "FIXME implement a more general excess branch elimination"
7956 /* If we have a return value do some more work */
7957 if (peek(state) != TOK_SEMI) {
7958 val = read_expr(state, expr(state));
7960 eat(state, TOK_SEMI);
7962 /* See if this last statement in a function */
7963 last = ((peek(state) == TOK_RBRACE) &&
7964 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7966 /* Find the return variable */
7967 var = MISC(state->main_function, 0);
7968 /* Find the return destination */
7969 dest = RHS(state->main_function, 0)->prev;
7971 /* If needed generate a jump instruction */
7973 jmp = branch(state, dest, 0);
7975 /* If needed generate an assignment instruction */
7977 mv = write_expr(state, var, val);
7979 /* Now put the code together */
7981 flatten(state, first, mv);
7982 flatten(state, first, jmp);
7985 flatten(state, first, jmp);
7989 static void break_statement(struct compile_state *state, struct triple *first)
7991 struct triple *dest;
7992 eat(state, TOK_BREAK);
7993 eat(state, TOK_SEMI);
7994 if (!state->i_break->sym_ident) {
7995 error(state, 0, "break statement not within loop or switch");
7997 dest = state->i_break->sym_ident->def;
7998 flatten(state, first, branch(state, dest, 0));
8001 static void continue_statement(struct compile_state *state, struct triple *first)
8003 struct triple *dest;
8004 eat(state, TOK_CONTINUE);
8005 eat(state, TOK_SEMI);
8006 if (!state->i_continue->sym_ident) {
8007 error(state, 0, "continue statement outside of a loop");
8009 dest = state->i_continue->sym_ident->def;
8010 flatten(state, first, branch(state, dest, 0));
8013 static void goto_statement(struct compile_state *state, struct triple *first)
8015 struct hash_entry *ident;
8016 eat(state, TOK_GOTO);
8017 eat(state, TOK_IDENT);
8018 ident = state->token[0].ident;
8019 if (!ident->sym_label) {
8020 /* If this is a forward branch allocate the label now,
8021 * it will be flattend in the appropriate location later.
8025 label_symbol(state, ident, ins);
8027 eat(state, TOK_SEMI);
8029 flatten(state, first, branch(state, ident->sym_label->def, 0));
8032 static void labeled_statement(struct compile_state *state, struct triple *first)
8035 struct hash_entry *ident;
8036 eat(state, TOK_IDENT);
8038 ident = state->token[0].ident;
8039 if (ident->sym_label && ident->sym_label->def) {
8040 ins = ident->sym_label->def;
8041 put_occurance(ins->occurance);
8042 ins->occurance = new_occurance(state);
8046 label_symbol(state, ident, ins);
8048 if (ins->id & TRIPLE_FLAG_FLATTENED) {
8049 error(state, 0, "label %s already defined", ident->name);
8051 flatten(state, first, ins);
8053 eat(state, TOK_COLON);
8054 statement(state, first);
8057 static void switch_statement(struct compile_state *state, struct triple *first)
8060 eat(state, TOK_SWITCH);
8061 eat(state, TOK_LPAREN);
8063 eat(state, TOK_RPAREN);
8064 statement(state, first);
8065 error(state, 0, "switch statements are not implemented");
8069 static void case_statement(struct compile_state *state, struct triple *first)
8072 eat(state, TOK_CASE);
8073 constant_expr(state);
8074 eat(state, TOK_COLON);
8075 statement(state, first);
8076 error(state, 0, "case statements are not implemented");
8080 static void default_statement(struct compile_state *state, struct triple *first)
8083 eat(state, TOK_DEFAULT);
8084 eat(state, TOK_COLON);
8085 statement(state, first);
8086 error(state, 0, "default statements are not implemented");
8090 static void asm_statement(struct compile_state *state, struct triple *first)
8092 struct asm_info *info;
8094 struct triple *constraint;
8095 struct triple *expr;
8096 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
8097 struct triple *def, *asm_str;
8098 int out, in, clobbers, more, colons, i;
8100 eat(state, TOK_ASM);
8101 /* For now ignore the qualifiers */
8102 switch(peek(state)) {
8104 eat(state, TOK_CONST);
8107 eat(state, TOK_VOLATILE);
8110 eat(state, TOK_LPAREN);
8111 asm_str = string_constant(state);
8114 out = in = clobbers = 0;
8116 if ((colons == 0) && (peek(state) == TOK_COLON)) {
8117 eat(state, TOK_COLON);
8119 more = (peek(state) == TOK_LIT_STRING);
8122 struct triple *constraint;
8125 if (out > MAX_LHS) {
8126 error(state, 0, "Maximum output count exceeded.");
8128 constraint = string_constant(state);
8129 str = constraint->u.blob;
8130 if (str[0] != '=') {
8131 error(state, 0, "Output constraint does not start with =");
8133 constraint->u.blob = str + 1;
8134 eat(state, TOK_LPAREN);
8135 var = conditional_expr(state);
8136 eat(state, TOK_RPAREN);
8139 out_param[out].constraint = constraint;
8140 out_param[out].expr = var;
8141 if (peek(state) == TOK_COMMA) {
8142 eat(state, TOK_COMMA);
8149 if ((colons == 1) && (peek(state) == TOK_COLON)) {
8150 eat(state, TOK_COLON);
8152 more = (peek(state) == TOK_LIT_STRING);
8155 struct triple *constraint;
8159 error(state, 0, "Maximum input count exceeded.");
8161 constraint = string_constant(state);
8162 str = constraint->u.blob;
8163 if (digitp(str[0] && str[1] == '\0')) {
8165 val = digval(str[0]);
8166 if ((val < 0) || (val >= out)) {
8167 error(state, 0, "Invalid input constraint %d", val);
8170 eat(state, TOK_LPAREN);
8171 val = conditional_expr(state);
8172 eat(state, TOK_RPAREN);
8174 in_param[in].constraint = constraint;
8175 in_param[in].expr = val;
8176 if (peek(state) == TOK_COMMA) {
8177 eat(state, TOK_COMMA);
8185 if ((colons == 2) && (peek(state) == TOK_COLON)) {
8186 eat(state, TOK_COLON);
8188 more = (peek(state) == TOK_LIT_STRING);
8190 struct triple *clobber;
8192 if ((clobbers + out) > MAX_LHS) {
8193 error(state, 0, "Maximum clobber limit exceeded.");
8195 clobber = string_constant(state);
8196 eat(state, TOK_RPAREN);
8198 clob_param[clobbers].constraint = clobber;
8199 if (peek(state) == TOK_COMMA) {
8200 eat(state, TOK_COMMA);
8206 eat(state, TOK_RPAREN);
8207 eat(state, TOK_SEMI);
8210 info = xcmalloc(sizeof(*info), "asm_info");
8211 info->str = asm_str->u.blob;
8212 free_triple(state, asm_str);
8214 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8215 def->u.ainfo = info;
8217 /* Find the register constraints */
8218 for(i = 0; i < out; i++) {
8219 struct triple *constraint;
8220 constraint = out_param[i].constraint;
8221 info->tmpl.lhs[i] = arch_reg_constraint(state,
8222 out_param[i].expr->type, constraint->u.blob);
8223 free_triple(state, constraint);
8225 for(; i - out < clobbers; i++) {
8226 struct triple *constraint;
8227 constraint = clob_param[i - out].constraint;
8228 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8229 free_triple(state, constraint);
8231 for(i = 0; i < in; i++) {
8232 struct triple *constraint;
8234 constraint = in_param[i].constraint;
8235 str = constraint->u.blob;
8236 if (digitp(str[0]) && str[1] == '\0') {
8237 struct reg_info cinfo;
8239 val = digval(str[0]);
8240 cinfo.reg = info->tmpl.lhs[val].reg;
8241 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8242 cinfo.regcm &= info->tmpl.lhs[val].regcm;
8243 if (cinfo.reg == REG_UNSET) {
8244 cinfo.reg = REG_VIRT0 + val;
8246 if (cinfo.regcm == 0) {
8247 error(state, 0, "No registers for %d", val);
8249 info->tmpl.lhs[val] = cinfo;
8250 info->tmpl.rhs[i] = cinfo;
8253 info->tmpl.rhs[i] = arch_reg_constraint(state,
8254 in_param[i].expr->type, str);
8256 free_triple(state, constraint);
8259 /* Now build the helper expressions */
8260 for(i = 0; i < in; i++) {
8261 RHS(def, i) = read_expr(state,in_param[i].expr);
8263 flatten(state, first, def);
8264 for(i = 0; i < out; i++) {
8265 struct triple *piece;
8266 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8268 LHS(def, i) = piece;
8269 flatten(state, first,
8270 write_expr(state, out_param[i].expr, piece));
8272 for(; i - out < clobbers; i++) {
8273 struct triple *piece;
8274 piece = triple(state, OP_PIECE, &void_type, def, 0);
8276 LHS(def, i) = piece;
8277 flatten(state, first, piece);
8282 static int isdecl(int tok)
8305 case TOK_TYPE_NAME: /* typedef name */
8312 static void compound_statement(struct compile_state *state, struct triple *first)
8314 eat(state, TOK_LBRACE);
8317 /* statement-list opt */
8318 while (peek(state) != TOK_RBRACE) {
8319 statement(state, first);
8322 eat(state, TOK_RBRACE);
8325 static void statement(struct compile_state *state, struct triple *first)
8329 if (tok == TOK_LBRACE) {
8330 compound_statement(state, first);
8332 else if (tok == TOK_IF) {
8333 if_statement(state, first);
8335 else if (tok == TOK_FOR) {
8336 for_statement(state, first);
8338 else if (tok == TOK_WHILE) {
8339 while_statement(state, first);
8341 else if (tok == TOK_DO) {
8342 do_statement(state, first);
8344 else if (tok == TOK_RETURN) {
8345 return_statement(state, first);
8347 else if (tok == TOK_BREAK) {
8348 break_statement(state, first);
8350 else if (tok == TOK_CONTINUE) {
8351 continue_statement(state, first);
8353 else if (tok == TOK_GOTO) {
8354 goto_statement(state, first);
8356 else if (tok == TOK_SWITCH) {
8357 switch_statement(state, first);
8359 else if (tok == TOK_ASM) {
8360 asm_statement(state, first);
8362 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8363 labeled_statement(state, first);
8365 else if (tok == TOK_CASE) {
8366 case_statement(state, first);
8368 else if (tok == TOK_DEFAULT) {
8369 default_statement(state, first);
8371 else if (isdecl(tok)) {
8372 /* This handles C99 intermixing of statements and decls */
8376 expr_statement(state, first);
8380 static struct type *param_decl(struct compile_state *state)
8383 struct hash_entry *ident;
8384 /* Cheat so the declarator will know we are not global */
8387 type = decl_specifiers(state);
8388 type = declarator(state, type, &ident, 0);
8389 type->field_ident = ident;
8394 static struct type *param_type_list(struct compile_state *state, struct type *type)
8396 struct type *ftype, **next;
8397 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8398 next = &ftype->right;
8399 while(peek(state) == TOK_COMMA) {
8400 eat(state, TOK_COMMA);
8401 if (peek(state) == TOK_DOTS) {
8402 eat(state, TOK_DOTS);
8403 error(state, 0, "variadic functions not supported");
8406 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8407 next = &((*next)->right);
8414 static struct type *type_name(struct compile_state *state)
8417 type = specifier_qualifier_list(state);
8418 /* abstract-declarator (may consume no tokens) */
8419 type = declarator(state, type, 0, 0);
8423 static struct type *direct_declarator(
8424 struct compile_state *state, struct type *type,
8425 struct hash_entry **ident, int need_ident)
8430 arrays_complete(state, type);
8431 switch(peek(state)) {
8433 eat(state, TOK_IDENT);
8435 error(state, 0, "Unexpected identifier found");
8437 /* The name of what we are declaring */
8438 *ident = state->token[0].ident;
8441 eat(state, TOK_LPAREN);
8442 outer = declarator(state, type, ident, need_ident);
8443 eat(state, TOK_RPAREN);
8447 error(state, 0, "Identifier expected");
8453 arrays_complete(state, type);
8454 switch(peek(state)) {
8456 eat(state, TOK_LPAREN);
8457 type = param_type_list(state, type);
8458 eat(state, TOK_RPAREN);
8462 unsigned int qualifiers;
8463 struct triple *value;
8465 eat(state, TOK_LBRACKET);
8466 if (peek(state) != TOK_RBRACKET) {
8467 value = constant_expr(state);
8468 integral(state, value);
8470 eat(state, TOK_RBRACKET);
8472 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8473 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8475 type->elements = value->u.cval;
8476 free_triple(state, value);
8478 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8490 arrays_complete(state, type);
8492 for(inner = outer; inner->left; inner = inner->left)
8500 static struct type *declarator(
8501 struct compile_state *state, struct type *type,
8502 struct hash_entry **ident, int need_ident)
8504 while(peek(state) == TOK_STAR) {
8505 eat(state, TOK_STAR);
8506 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8508 type = direct_declarator(state, type, ident, need_ident);
8513 static struct type *typedef_name(
8514 struct compile_state *state, unsigned int specifiers)
8516 struct hash_entry *ident;
8518 eat(state, TOK_TYPE_NAME);
8519 ident = state->token[0].ident;
8520 type = ident->sym_ident->type;
8521 specifiers |= type->type & QUAL_MASK;
8522 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8523 (type->type & (STOR_MASK | QUAL_MASK))) {
8524 type = clone_type(specifiers, type);
8529 static struct type *enum_specifier(
8530 struct compile_state *state, unsigned int specifiers)
8536 eat(state, TOK_ENUM);
8538 if (tok == TOK_IDENT) {
8539 eat(state, TOK_IDENT);
8541 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8542 eat(state, TOK_LBRACE);
8544 eat(state, TOK_IDENT);
8545 if (peek(state) == TOK_EQ) {
8547 constant_expr(state);
8549 if (peek(state) == TOK_COMMA) {
8550 eat(state, TOK_COMMA);
8552 } while(peek(state) != TOK_RBRACE);
8553 eat(state, TOK_RBRACE);
8559 static struct type *struct_declarator(
8560 struct compile_state *state, struct type *type, struct hash_entry **ident)
8564 if (tok != TOK_COLON) {
8565 type = declarator(state, type, ident, 1);
8567 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8568 struct triple *value;
8569 eat(state, TOK_COLON);
8570 value = constant_expr(state);
8571 #warning "FIXME implement bitfields to reduce register usage"
8572 error(state, 0, "bitfields not yet implemented");
8577 static struct type *struct_or_union_specifier(
8578 struct compile_state *state, unsigned int spec)
8580 struct type *struct_type;
8581 struct hash_entry *ident;
8582 unsigned int type_join;
8586 switch(peek(state)) {
8588 eat(state, TOK_STRUCT);
8589 type_join = TYPE_PRODUCT;
8592 eat(state, TOK_UNION);
8593 type_join = TYPE_OVERLAP;
8594 error(state, 0, "unions not yet supported\n");
8597 eat(state, TOK_STRUCT);
8598 type_join = TYPE_PRODUCT;
8602 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8604 ident = state->token[0].ident;
8606 if (!ident || (peek(state) == TOK_LBRACE)) {
8610 eat(state, TOK_LBRACE);
8611 next = &struct_type;
8613 struct type *base_type;
8615 base_type = specifier_qualifier_list(state);
8618 struct hash_entry *fident;
8620 type = struct_declarator(state, base_type, &fident);
8622 if (peek(state) == TOK_COMMA) {
8624 eat(state, TOK_COMMA);
8626 type = clone_type(0, type);
8627 type->field_ident = fident;
8629 *next = new_type(type_join, *next, type);
8630 next = &((*next)->right);
8635 eat(state, TOK_SEMI);
8636 } while(peek(state) != TOK_RBRACE);
8637 eat(state, TOK_RBRACE);
8638 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8639 struct_type->type_ident = ident;
8640 struct_type->elements = elements;
8641 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8643 if (ident && ident->sym_struct) {
8644 struct_type = clone_type(spec, ident->sym_struct->type);
8646 else if (ident && !ident->sym_struct) {
8647 error(state, 0, "struct %s undeclared", ident->name);
8652 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8654 unsigned int specifiers;
8655 switch(peek(state)) {
8657 eat(state, TOK_AUTO);
8658 specifiers = STOR_AUTO;
8661 eat(state, TOK_REGISTER);
8662 specifiers = STOR_REGISTER;
8665 eat(state, TOK_STATIC);
8666 specifiers = STOR_STATIC;
8669 eat(state, TOK_EXTERN);
8670 specifiers = STOR_EXTERN;
8673 eat(state, TOK_TYPEDEF);
8674 specifiers = STOR_TYPEDEF;
8677 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8678 specifiers = STOR_STATIC;
8681 specifiers = STOR_AUTO;
8687 static unsigned int function_specifier_opt(struct compile_state *state)
8689 /* Ignore the inline keyword */
8690 unsigned int specifiers;
8692 switch(peek(state)) {
8694 eat(state, TOK_INLINE);
8695 specifiers = STOR_INLINE;
8700 static unsigned int type_qualifiers(struct compile_state *state)
8702 unsigned int specifiers;
8705 specifiers = QUAL_NONE;
8707 switch(peek(state)) {
8709 eat(state, TOK_CONST);
8710 specifiers = QUAL_CONST;
8713 eat(state, TOK_VOLATILE);
8714 specifiers = QUAL_VOLATILE;
8717 eat(state, TOK_RESTRICT);
8718 specifiers = QUAL_RESTRICT;
8728 static struct type *type_specifier(
8729 struct compile_state *state, unsigned int spec)
8733 switch(peek(state)) {
8735 eat(state, TOK_VOID);
8736 type = new_type(TYPE_VOID | spec, 0, 0);
8739 eat(state, TOK_CHAR);
8740 type = new_type(TYPE_CHAR | spec, 0, 0);
8743 eat(state, TOK_SHORT);
8744 if (peek(state) == TOK_INT) {
8745 eat(state, TOK_INT);
8747 type = new_type(TYPE_SHORT | spec, 0, 0);
8750 eat(state, TOK_INT);
8751 type = new_type(TYPE_INT | spec, 0, 0);
8754 eat(state, TOK_LONG);
8755 switch(peek(state)) {
8757 eat(state, TOK_LONG);
8758 error(state, 0, "long long not supported");
8761 eat(state, TOK_DOUBLE);
8762 error(state, 0, "long double not supported");
8765 eat(state, TOK_INT);
8766 type = new_type(TYPE_LONG | spec, 0, 0);
8769 type = new_type(TYPE_LONG | spec, 0, 0);
8774 eat(state, TOK_FLOAT);
8775 error(state, 0, "type float not supported");
8778 eat(state, TOK_DOUBLE);
8779 error(state, 0, "type double not supported");
8782 eat(state, TOK_SIGNED);
8783 switch(peek(state)) {
8785 eat(state, TOK_LONG);
8786 switch(peek(state)) {
8788 eat(state, TOK_LONG);
8789 error(state, 0, "type long long not supported");
8792 eat(state, TOK_INT);
8793 type = new_type(TYPE_LONG | spec, 0, 0);
8796 type = new_type(TYPE_LONG | spec, 0, 0);
8801 eat(state, TOK_INT);
8802 type = new_type(TYPE_INT | spec, 0, 0);
8805 eat(state, TOK_SHORT);
8806 type = new_type(TYPE_SHORT | spec, 0, 0);
8809 eat(state, TOK_CHAR);
8810 type = new_type(TYPE_CHAR | spec, 0, 0);
8813 type = new_type(TYPE_INT | spec, 0, 0);
8818 eat(state, TOK_UNSIGNED);
8819 switch(peek(state)) {
8821 eat(state, TOK_LONG);
8822 switch(peek(state)) {
8824 eat(state, TOK_LONG);
8825 error(state, 0, "unsigned long long not supported");
8828 eat(state, TOK_INT);
8829 type = new_type(TYPE_ULONG | spec, 0, 0);
8832 type = new_type(TYPE_ULONG | spec, 0, 0);
8837 eat(state, TOK_INT);
8838 type = new_type(TYPE_UINT | spec, 0, 0);
8841 eat(state, TOK_SHORT);
8842 type = new_type(TYPE_USHORT | spec, 0, 0);
8845 eat(state, TOK_CHAR);
8846 type = new_type(TYPE_UCHAR | spec, 0, 0);
8849 type = new_type(TYPE_UINT | spec, 0, 0);
8853 /* struct or union specifier */
8856 type = struct_or_union_specifier(state, spec);
8858 /* enum-spefifier */
8860 type = enum_specifier(state, spec);
8864 type = typedef_name(state, spec);
8867 error(state, 0, "bad type specifier %s",
8868 tokens[peek(state)]);
8874 static int istype(int tok)
8900 static struct type *specifier_qualifier_list(struct compile_state *state)
8903 unsigned int specifiers = 0;
8905 /* type qualifiers */
8906 specifiers |= type_qualifiers(state);
8908 /* type specifier */
8909 type = type_specifier(state, specifiers);
8914 static int isdecl_specifier(int tok)
8917 /* storage class specifier */
8923 /* type qualifier */
8927 /* type specifiers */
8937 /* struct or union specifier */
8940 /* enum-spefifier */
8944 /* function specifiers */
8952 static struct type *decl_specifiers(struct compile_state *state)
8955 unsigned int specifiers;
8956 /* I am overly restrictive in the arragement of specifiers supported.
8957 * C is overly flexible in this department it makes interpreting
8958 * the parse tree difficult.
8962 /* storage class specifier */
8963 specifiers |= storage_class_specifier_opt(state);
8965 /* function-specifier */
8966 specifiers |= function_specifier_opt(state);
8968 /* type qualifier */
8969 specifiers |= type_qualifiers(state);
8971 /* type specifier */
8972 type = type_specifier(state, specifiers);
8981 static struct field_info designator(struct compile_state *state, struct type *type)
8984 struct field_info info;
8988 switch(peek(state)) {
8991 struct triple *value;
8992 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8993 error(state, 0, "Array designator not in array initializer");
8995 eat(state, TOK_LBRACKET);
8996 value = constant_expr(state);
8997 eat(state, TOK_RBRACKET);
8999 info.type = type->left;
9000 info.offset = value->u.cval * size_of(state, info.type);
9005 struct hash_entry *field;
9006 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
9007 error(state, 0, "Struct designator not in struct initializer");
9009 eat(state, TOK_DOT);
9010 eat(state, TOK_IDENT);
9011 field = state->token[0].ident;
9012 info.offset = field_offset(state, type, field);
9013 info.type = field_type(state, type, field);
9017 error(state, 0, "Invalid designator");
9020 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
9025 static struct triple *initializer(
9026 struct compile_state *state, struct type *type)
9028 struct triple *result;
9029 if (peek(state) != TOK_LBRACE) {
9030 result = assignment_expr(state);
9035 struct field_info info;
9037 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
9038 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
9039 internal_error(state, 0, "unknown initializer type");
9042 info.type = type->left;
9043 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
9044 info.type = next_field(state, type, 0);
9046 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
9049 max_offset = size_of(state, type);
9051 buf = xcmalloc(max_offset, "initializer");
9052 eat(state, TOK_LBRACE);
9054 struct triple *value;
9055 struct type *value_type;
9061 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
9062 info = designator(state, type);
9064 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
9065 (info.offset >= max_offset)) {
9066 error(state, 0, "element beyond bounds");
9068 value_type = info.type;
9069 value = eval_const_expr(state, initializer(state, value_type));
9070 value_size = size_of(state, value_type);
9071 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
9072 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
9073 (max_offset <= info.offset)) {
9077 old_size = max_offset;
9078 max_offset = info.offset + value_size;
9079 buf = xmalloc(max_offset, "initializer");
9080 memcpy(buf, old_buf, old_size);
9083 dest = ((char *)buf) + info.offset;
9084 if (value->op == OP_BLOBCONST) {
9085 memcpy(dest, value->u.blob, value_size);
9087 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
9088 *((uint8_t *)dest) = value->u.cval & 0xff;
9090 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
9091 *((uint16_t *)dest) = value->u.cval & 0xffff;
9093 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
9094 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
9097 internal_error(state, 0, "unhandled constant initializer");
9099 free_triple(state, value);
9100 if (peek(state) == TOK_COMMA) {
9101 eat(state, TOK_COMMA);
9104 info.offset += value_size;
9105 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
9106 info.type = next_field(state, type, info.type);
9107 info.offset = field_offset(state, type,
9108 info.type->field_ident);
9110 } while(comma && (peek(state) != TOK_RBRACE));
9111 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
9112 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
9113 type->elements = max_offset / size_of(state, type->left);
9115 eat(state, TOK_RBRACE);
9116 result = triple(state, OP_BLOBCONST, type, 0, 0);
9117 result->u.blob = buf;
9122 static void resolve_branches(struct compile_state *state)
9124 /* Make a second pass and finish anything outstanding
9125 * with respect to branches. The only outstanding item
9126 * is to see if there are goto to labels that have not
9127 * been defined and to error about them.
9130 for(i = 0; i < HASH_TABLE_SIZE; i++) {
9131 struct hash_entry *entry;
9132 for(entry = state->hash_table[i]; entry; entry = entry->next) {
9134 if (!entry->sym_label) {
9137 ins = entry->sym_label->def;
9138 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
9139 error(state, ins, "label `%s' used but not defined",
9146 static struct triple *function_definition(
9147 struct compile_state *state, struct type *type)
9149 struct triple *def, *tmp, *first, *end;
9150 struct hash_entry *ident;
9153 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
9154 error(state, 0, "Invalid function header");
9157 /* Verify the function type */
9158 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
9159 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
9160 (type->right->field_ident == 0)) {
9161 error(state, 0, "Invalid function parameters");
9163 param = type->right;
9165 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9167 if (!param->left->field_ident) {
9168 error(state, 0, "No identifier for parameter %d\n", i);
9170 param = param->right;
9173 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9174 error(state, 0, "No identifier for paramter %d\n", i);
9177 /* Get a list of statements for this function. */
9178 def = triple(state, OP_LIST, type, 0, 0);
9180 /* Start a new scope for the passed parameters */
9183 /* Put a label at the very start of a function */
9184 first = label(state);
9185 RHS(def, 0) = first;
9187 /* Put a label at the very end of a function */
9189 flatten(state, first, end);
9191 /* Walk through the parameters and create symbol table entries
9194 param = type->right;
9195 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9196 ident = param->left->field_ident;
9197 tmp = variable(state, param->left);
9198 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9199 flatten(state, end, tmp);
9200 param = param->right;
9202 if ((param->type & TYPE_MASK) != TYPE_VOID) {
9203 /* And don't forget the last parameter */
9204 ident = param->field_ident;
9205 tmp = variable(state, param);
9206 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9207 flatten(state, end, tmp);
9209 /* Add a variable for the return value */
9211 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9212 /* Remove all type qualifiers from the return type */
9213 tmp = variable(state, clone_type(0, type->left));
9214 flatten(state, end, tmp);
9215 /* Remember where the return value is */
9219 /* Remember which function I am compiling.
9220 * Also assume the last defined function is the main function.
9222 state->main_function = def;
9224 /* Now get the actual function definition */
9225 compound_statement(state, end);
9227 /* Finish anything unfinished with branches */
9228 resolve_branches(state);
9230 /* Remove the parameter scope */
9234 fprintf(stdout, "\n");
9235 loc(stdout, state, 0);
9236 fprintf(stdout, "\n__________ function_definition _________\n");
9237 print_triple(state, def);
9238 fprintf(stdout, "__________ function_definition _________ done\n\n");
9244 static struct triple *do_decl(struct compile_state *state,
9245 struct type *type, struct hash_entry *ident)
9249 /* Clean up the storage types used */
9250 switch (type->type & STOR_MASK) {
9253 /* These are the good types I am aiming for */
9256 type->type &= ~STOR_MASK;
9257 type->type |= STOR_AUTO;
9260 type->type &= ~STOR_MASK;
9261 type->type |= STOR_STATIC;
9265 error(state, 0, "typedef without name");
9267 symbol(state, ident, &ident->sym_ident, 0, type);
9268 ident->tok = TOK_TYPE_NAME;
9272 internal_error(state, 0, "Undefined storage class");
9274 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
9275 error(state, 0, "Function prototypes not supported");
9278 ((type->type & STOR_MASK) == STOR_STATIC) &&
9279 ((type->type & QUAL_CONST) == 0)) {
9280 error(state, 0, "non const static variables not supported");
9283 def = variable(state, type);
9284 symbol(state, ident, &ident->sym_ident, def, type);
9289 static void decl(struct compile_state *state, struct triple *first)
9291 struct type *base_type, *type;
9292 struct hash_entry *ident;
9295 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9296 base_type = decl_specifiers(state);
9298 type = declarator(state, base_type, &ident, 0);
9299 if (global && ident && (peek(state) == TOK_LBRACE)) {
9301 state->function = ident->name;
9302 def = function_definition(state, type);
9303 symbol(state, ident, &ident->sym_ident, def, type);
9304 state->function = 0;
9308 flatten(state, first, do_decl(state, type, ident));
9309 /* type or variable definition */
9312 if (peek(state) == TOK_EQ) {
9314 error(state, 0, "cannot assign to a type");
9317 flatten(state, first,
9319 ident->sym_ident->def,
9320 initializer(state, type)));
9322 arrays_complete(state, type);
9323 if (peek(state) == TOK_COMMA) {
9324 eat(state, TOK_COMMA);
9326 type = declarator(state, base_type, &ident, 0);
9327 flatten(state, first, do_decl(state, type, ident));
9331 eat(state, TOK_SEMI);
9335 static void decls(struct compile_state *state)
9337 struct triple *list;
9339 list = label(state);
9342 if (tok == TOK_EOF) {
9345 if (tok == TOK_SPACE) {
9346 eat(state, TOK_SPACE);
9349 if (list->next != list) {
9350 error(state, 0, "global variables not supported");
9356 * Data structurs for optimation.
9359 static void do_use_block(
9360 struct block *used, struct block_set **head, struct block *user,
9363 struct block_set **ptr, *new;
9370 if ((*ptr)->member == user) {
9373 ptr = &(*ptr)->next;
9375 new = xcmalloc(sizeof(*new), "block_set");
9386 static void do_unuse_block(
9387 struct block *used, struct block_set **head, struct block *unuser)
9389 struct block_set *use, **ptr;
9393 if (use->member == unuser) {
9395 memset(use, -1, sizeof(*use));
9404 static void use_block(struct block *used, struct block *user)
9406 /* Append new to the head of the list, print_block
9409 do_use_block(used, &used->use, user, 1);
9412 static void unuse_block(struct block *used, struct block *unuser)
9414 do_unuse_block(used, &used->use, unuser);
9418 static void idom_block(struct block *idom, struct block *user)
9420 do_use_block(idom, &idom->idominates, user, 0);
9423 static void unidom_block(struct block *idom, struct block *unuser)
9425 do_unuse_block(idom, &idom->idominates, unuser);
9428 static void domf_block(struct block *block, struct block *domf)
9430 do_use_block(block, &block->domfrontier, domf, 0);
9433 static void undomf_block(struct block *block, struct block *undomf)
9435 do_unuse_block(block, &block->domfrontier, undomf);
9438 static void ipdom_block(struct block *ipdom, struct block *user)
9440 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9443 static void unipdom_block(struct block *ipdom, struct block *unuser)
9445 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9448 static void ipdomf_block(struct block *block, struct block *ipdomf)
9450 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9453 static void unipdomf_block(struct block *block, struct block *unipdomf)
9455 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9460 static int do_walk_triple(struct compile_state *state,
9461 struct triple *ptr, int depth,
9462 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9465 result = cb(state, ptr, depth);
9466 if ((result == 0) && (ptr->op == OP_LIST)) {
9467 struct triple *list;
9471 result = do_walk_triple(state, ptr, depth + 1, cb);
9472 if (ptr->next->prev != ptr) {
9473 internal_error(state, ptr->next, "bad prev");
9477 } while((result == 0) && (ptr != RHS(list, 0)));
9482 static int walk_triple(
9483 struct compile_state *state,
9485 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9487 return do_walk_triple(state, ptr, 0, cb);
9490 static void do_print_prefix(int depth)
9493 for(i = 0; i < depth; i++) {
9498 #define PRINT_LIST 1
9499 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9503 if (op == OP_LIST) {
9508 if ((op == OP_LABEL) && (ins->use)) {
9509 printf("\n%p:\n", ins);
9511 do_print_prefix(depth);
9512 display_triple(stdout, ins);
9514 if ((ins->op == OP_BRANCH) && ins->use) {
9515 internal_error(state, ins, "branch used?");
9517 if (triple_is_branch(state, ins)) {
9523 static void print_triple(struct compile_state *state, struct triple *ins)
9525 walk_triple(state, ins, do_print_triple);
9528 static void print_triples(struct compile_state *state)
9530 print_triple(state, state->main_function);
9534 struct block *block;
9536 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9538 if (!block || (cf[block->vertex].block == block)) {
9541 cf[block->vertex].block = block;
9542 find_cf_blocks(cf, block->left);
9543 find_cf_blocks(cf, block->right);
9546 static void print_control_flow(struct compile_state *state)
9548 struct cf_block *cf;
9550 printf("\ncontrol flow\n");
9551 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9552 find_cf_blocks(cf, state->first_block);
9554 for(i = 1; i <= state->last_vertex; i++) {
9555 struct block *block;
9556 block = cf[i].block;
9559 printf("(%p) %d:", block, block->vertex);
9561 printf(" %d", block->left->vertex);
9563 if (block->right && (block->right != block->left)) {
9564 printf(" %d", block->right->vertex);
9573 static struct block *basic_block(struct compile_state *state,
9574 struct triple *first)
9576 struct block *block;
9579 if (first->op != OP_LABEL) {
9580 internal_error(state, 0, "block does not start with a label");
9582 /* See if this basic block has already been setup */
9583 if (first->u.block != 0) {
9584 return first->u.block;
9586 /* Allocate another basic block structure */
9587 state->last_vertex += 1;
9588 block = xcmalloc(sizeof(*block), "block");
9589 block->first = block->last = first;
9590 block->vertex = state->last_vertex;
9593 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9597 /* If ptr->u is not used remember where the baic block is */
9598 if (triple_stores_block(state, ptr)) {
9599 ptr->u.block = block;
9601 if (ptr->op == OP_BRANCH) {
9605 } while (ptr != RHS(state->main_function, 0));
9606 if (ptr == RHS(state->main_function, 0))
9609 if (op == OP_LABEL) {
9610 block->left = basic_block(state, ptr);
9612 use_block(block->left, block);
9614 else if (op == OP_BRANCH) {
9616 /* Trace the branch target */
9617 block->right = basic_block(state, TARG(ptr, 0));
9618 use_block(block->right, block);
9619 /* If there is a test trace the branch as well */
9620 if (TRIPLE_RHS(ptr->sizes)) {
9621 block->left = basic_block(state, ptr->next);
9622 use_block(block->left, block);
9626 internal_error(state, 0, "Bad basic block split");
9632 static void walk_blocks(struct compile_state *state,
9633 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9636 struct triple *ptr, *first;
9637 struct block *last_block;
9639 first = RHS(state->main_function, 0);
9642 struct block *block;
9643 if (triple_stores_block(state, ptr)) {
9644 block = ptr->u.block;
9645 if (block && (block != last_block)) {
9646 cb(state, block, arg);
9650 if (block && (block->last == ptr)) {
9654 } while(ptr != first);
9657 static void print_block(
9658 struct compile_state *state, struct block *block, void *arg)
9660 struct block_set *user;
9664 fprintf(fp, "\nblock: %p (%d) %p<-%p %p<-%p\n",
9668 block->left && block->left->use?block->left->use->member : 0,
9670 block->right && block->right->use?block->right->use->member : 0);
9671 if (block->first->op == OP_LABEL) {
9672 fprintf(fp, "%p:\n", block->first);
9674 for(ptr = block->first; ; ptr = ptr->next) {
9675 display_triple(fp, ptr);
9676 if (ptr == block->last)
9679 fprintf(fp, "users %d: ", block->users);
9680 for(user = block->use; user; user = user->next) {
9681 fprintf(fp, "%p (%d) ",
9683 user->member->vertex);
9689 static void print_blocks(struct compile_state *state, FILE *fp)
9691 fprintf(fp, "--------------- blocks ---------------\n");
9692 walk_blocks(state, print_block, fp);
9695 static void prune_nonblock_triples(struct compile_state *state)
9697 struct block *block;
9698 struct triple *first, *ins, *next;
9699 /* Delete the triples not in a basic block */
9700 first = RHS(state->main_function, 0);
9705 if (ins->op == OP_LABEL) {
9706 block = ins->u.block;
9709 release_triple(state, ins);
9711 if (block && block->last == ins) {
9715 } while(ins != first);
9718 static void setup_basic_blocks(struct compile_state *state)
9720 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9721 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9722 internal_error(state, 0, "ins will not store block?");
9724 /* Find the basic blocks */
9725 state->last_vertex = 0;
9726 state->first_block = basic_block(state, RHS(state->main_function,0));
9727 /* Delete the triples not in a basic block */
9728 prune_nonblock_triples(state);
9729 /* Find the last basic block */
9730 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9731 if (!state->last_block) {
9732 internal_error(state, 0, "end not used?");
9734 /* If we are debugging print what I have just done */
9735 if (state->debug & DEBUG_BASIC_BLOCKS) {
9736 print_blocks(state, stdout);
9737 print_control_flow(state);
9741 static void free_basic_block(struct compile_state *state, struct block *block)
9743 struct block_set *entry, *next;
9744 struct block *child;
9748 if (block->vertex == -1) {
9753 unuse_block(block->left, block);
9756 unuse_block(block->right, block);
9759 unidom_block(block->idom, block);
9763 unipdom_block(block->ipdom, block);
9766 for(entry = block->use; entry; entry = next) {
9768 child = entry->member;
9769 unuse_block(block, child);
9770 if (child->left == block) {
9773 if (child->right == block) {
9777 for(entry = block->idominates; entry; entry = next) {
9779 child = entry->member;
9780 unidom_block(block, child);
9783 for(entry = block->domfrontier; entry; entry = next) {
9785 child = entry->member;
9786 undomf_block(block, child);
9788 for(entry = block->ipdominates; entry; entry = next) {
9790 child = entry->member;
9791 unipdom_block(block, child);
9794 for(entry = block->ipdomfrontier; entry; entry = next) {
9796 child = entry->member;
9797 unipdomf_block(block, child);
9799 if (block->users != 0) {
9800 internal_error(state, 0, "block still has users");
9802 free_basic_block(state, block->left);
9804 free_basic_block(state, block->right);
9806 memset(block, -1, sizeof(*block));
9810 static void free_basic_blocks(struct compile_state *state)
9812 struct triple *first, *ins;
9813 free_basic_block(state, state->first_block);
9814 state->last_vertex = 0;
9815 state->first_block = state->last_block = 0;
9816 first = RHS(state->main_function, 0);
9819 if (triple_stores_block(state, ins)) {
9823 } while(ins != first);
9828 struct block *block;
9829 struct sdom_block *sdominates;
9830 struct sdom_block *sdom_next;
9831 struct sdom_block *sdom;
9832 struct sdom_block *label;
9833 struct sdom_block *parent;
9834 struct sdom_block *ancestor;
9839 static void unsdom_block(struct sdom_block *block)
9841 struct sdom_block **ptr;
9842 if (!block->sdom_next) {
9845 ptr = &block->sdom->sdominates;
9847 if ((*ptr) == block) {
9848 *ptr = block->sdom_next;
9851 ptr = &(*ptr)->sdom_next;
9855 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9857 unsdom_block(block);
9859 block->sdom_next = sdom->sdominates;
9860 sdom->sdominates = block;
9865 static int initialize_sdblock(struct sdom_block *sd,
9866 struct block *parent, struct block *block, int vertex)
9868 if (!block || (sd[block->vertex].block == block)) {
9872 /* Renumber the blocks in a convinient fashion */
9873 block->vertex = vertex;
9874 sd[vertex].block = block;
9875 sd[vertex].sdom = &sd[vertex];
9876 sd[vertex].label = &sd[vertex];
9877 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9878 sd[vertex].ancestor = 0;
9879 sd[vertex].vertex = vertex;
9880 vertex = initialize_sdblock(sd, block, block->left, vertex);
9881 vertex = initialize_sdblock(sd, block, block->right, vertex);
9885 static int initialize_sdpblock(
9886 struct compile_state *state, struct sdom_block *sd,
9887 struct block *parent, struct block *block, int vertex)
9889 struct block_set *user;
9890 if (!block || (sd[block->vertex].block == block)) {
9894 /* Renumber the blocks in a convinient fashion */
9895 block->vertex = vertex;
9896 sd[vertex].block = block;
9897 sd[vertex].sdom = &sd[vertex];
9898 sd[vertex].label = &sd[vertex];
9899 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9900 sd[vertex].ancestor = 0;
9901 sd[vertex].vertex = vertex;
9902 for(user = block->use; user; user = user->next) {
9903 vertex = initialize_sdpblock(state, sd, block, user->member, vertex);
9908 static int setup_sdpblocks(struct compile_state *state, struct sdom_block *sd)
9910 struct block *block;
9912 /* Setup as many sdpblocks as possible without using fake edges */
9913 vertex = initialize_sdpblock(state, sd, 0, state->last_block, 0);
9915 /* Walk through the graph and find unconnected blocks. If
9916 * we can, add a fake edge from the unconnected blocks to the
9919 block = state->first_block->last->next->u.block;
9920 for(; block && block != state->first_block; block = block->last->next->u.block) {
9921 if (sd[block->vertex].block == block) {
9924 if (block->left != 0) {
9928 #if DEBUG_SDP_BLOCKS
9929 fprintf(stderr, "Adding %d\n", vertex +1);
9932 block->left = state->last_block;
9933 use_block(block->left, block);
9934 vertex = initialize_sdpblock(state, sd, state->last_block, block, vertex);
9939 static void compress_ancestors(struct sdom_block *v)
9941 /* This procedure assumes ancestor(v) != 0 */
9942 /* if (ancestor(ancestor(v)) != 0) {
9943 * compress(ancestor(ancestor(v)));
9944 * if (semi(label(ancestor(v))) < semi(label(v))) {
9945 * label(v) = label(ancestor(v));
9947 * ancestor(v) = ancestor(ancestor(v));
9953 if (v->ancestor->ancestor) {
9954 compress_ancestors(v->ancestor->ancestor);
9955 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9956 v->label = v->ancestor->label;
9958 v->ancestor = v->ancestor->ancestor;
9962 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9966 * for each v <= pred(w) {
9968 * if (semi[u] < semi[w] {
9969 * semi[w] = semi[u];
9972 * add w to bucket(vertex(semi[w]));
9973 * LINK(parent(w), w);
9976 * for each v <= bucket(parent(w)) {
9977 * delete v from bucket(parent(w));
9979 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9982 for(i = state->last_vertex; i >= 2; i--) {
9983 struct sdom_block *v, *parent, *next;
9984 struct block_set *user;
9985 struct block *block;
9986 block = sd[i].block;
9987 parent = sd[i].parent;
9989 for(user = block->use; user; user = user->next) {
9990 struct sdom_block *v, *u;
9991 v = &sd[user->member->vertex];
9992 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9993 if (u->sdom->vertex < sd[i].sdom->vertex) {
9994 sd[i].sdom = u->sdom;
9997 sdom_block(sd[i].sdom, &sd[i]);
9998 sd[i].ancestor = parent;
10000 for(v = parent->sdominates; v; v = next) {
10001 struct sdom_block *u;
10002 next = v->sdom_next;
10004 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
10005 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
10006 u->block : parent->block;
10011 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
10015 * for each v <= pred(w) {
10017 * if (semi[u] < semi[w] {
10018 * semi[w] = semi[u];
10021 * add w to bucket(vertex(semi[w]));
10022 * LINK(parent(w), w);
10025 * for each v <= bucket(parent(w)) {
10026 * delete v from bucket(parent(w));
10028 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
10031 for(i = state->last_vertex; i >= 2; i--) {
10032 struct sdom_block *u, *v, *parent, *next;
10033 struct block *block;
10034 block = sd[i].block;
10035 parent = sd[i].parent;
10038 v = &sd[block->left->vertex];
10039 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10040 if (u->sdom->vertex < sd[i].sdom->vertex) {
10041 sd[i].sdom = u->sdom;
10044 if (block->right && (block->right != block->left)) {
10045 v = &sd[block->right->vertex];
10046 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10047 if (u->sdom->vertex < sd[i].sdom->vertex) {
10048 sd[i].sdom = u->sdom;
10051 sdom_block(sd[i].sdom, &sd[i]);
10052 sd[i].ancestor = parent;
10054 for(v = parent->sdominates; v; v = next) {
10055 struct sdom_block *u;
10056 next = v->sdom_next;
10058 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
10059 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
10060 u->block : parent->block;
10065 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
10068 for(i = 2; i <= state->last_vertex; i++) {
10069 struct block *block;
10070 block = sd[i].block;
10071 if (block->idom->vertex != sd[i].sdom->vertex) {
10072 block->idom = block->idom->idom;
10074 idom_block(block->idom, block);
10076 sd[1].block->idom = 0;
10079 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
10082 for(i = 2; i <= state->last_vertex; i++) {
10083 struct block *block;
10084 block = sd[i].block;
10085 if (block->ipdom->vertex != sd[i].sdom->vertex) {
10086 block->ipdom = block->ipdom->ipdom;
10088 ipdom_block(block->ipdom, block);
10090 sd[1].block->ipdom = 0;
10094 * Every vertex of a flowgraph G = (V, E, r) except r has
10095 * a unique immediate dominator.
10096 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
10097 * rooted at r, called the dominator tree of G, such that
10098 * v dominates w if and only if v is a proper ancestor of w in
10099 * the dominator tree.
10102 * If v and w are vertices of G such that v <= w,
10103 * than any path from v to w must contain a common ancestor
10106 /* Lemma 2: For any vertex w != r, idom(w) -> w */
10107 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
10108 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
10110 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
10111 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
10114 * Let w != r and let u be a vertex for which sdom(u) is
10115 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
10116 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
10118 /* Lemma 5: Let vertices v,w satisfy v -> w.
10119 * Then v -> idom(w) or idom(w) -> idom(v)
10122 static void find_immediate_dominators(struct compile_state *state)
10124 struct sdom_block *sd;
10125 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
10126 * vi > w for (1 <= i <= k - 1}
10129 * For any vertex w != r.
10131 * {v|(v,w) <= E and v < w } U
10132 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
10135 * Let w != r and let u be a vertex for which sdom(u) is
10136 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
10138 * { sdom(w) if sdom(w) = sdom(u),
10140 * { idom(u) otherwise
10142 /* The algorithm consists of the following 4 steps.
10143 * Step 1. Carry out a depth-first search of the problem graph.
10144 * Number the vertices from 1 to N as they are reached during
10145 * the search. Initialize the variables used in succeeding steps.
10146 * Step 2. Compute the semidominators of all vertices by applying
10147 * theorem 4. Carry out the computation vertex by vertex in
10148 * decreasing order by number.
10149 * Step 3. Implicitly define the immediate dominator of each vertex
10150 * by applying Corollary 1.
10151 * Step 4. Explicitly define the immediate dominator of each vertex,
10152 * carrying out the computation vertex by vertex in increasing order
10155 /* Step 1 initialize the basic block information */
10156 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10157 initialize_sdblock(sd, 0, state->first_block, 0);
10163 /* Step 2 compute the semidominators */
10164 /* Step 3 implicitly define the immediate dominator of each vertex */
10165 compute_sdom(state, sd);
10166 /* Step 4 explicitly define the immediate dominator of each vertex */
10167 compute_idom(state, sd);
10171 static void find_post_dominators(struct compile_state *state)
10173 struct sdom_block *sd;
10175 /* Step 1 initialize the basic block information */
10176 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10178 vertex = setup_sdpblocks(state, sd);
10179 if (vertex != state->last_vertex) {
10180 internal_error(state, 0, "missing %d blocks\n",
10181 state->last_vertex - vertex);
10184 /* Step 2 compute the semidominators */
10185 /* Step 3 implicitly define the immediate dominator of each vertex */
10186 compute_spdom(state, sd);
10187 /* Step 4 explicitly define the immediate dominator of each vertex */
10188 compute_ipdom(state, sd);
10194 static void find_block_domf(struct compile_state *state, struct block *block)
10196 struct block *child;
10197 struct block_set *user;
10198 if (block->domfrontier != 0) {
10199 internal_error(state, block->first, "domfrontier present?");
10201 for(user = block->idominates; user; user = user->next) {
10202 child = user->member;
10203 if (child->idom != block) {
10204 internal_error(state, block->first, "bad idom");
10206 find_block_domf(state, child);
10208 if (block->left && block->left->idom != block) {
10209 domf_block(block, block->left);
10211 if (block->right && block->right->idom != block) {
10212 domf_block(block, block->right);
10214 for(user = block->idominates; user; user = user->next) {
10215 struct block_set *frontier;
10216 child = user->member;
10217 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10218 if (frontier->member->idom != block) {
10219 domf_block(block, frontier->member);
10225 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10227 struct block *child;
10228 struct block_set *user;
10229 if (block->ipdomfrontier != 0) {
10230 internal_error(state, block->first, "ipdomfrontier present?");
10232 for(user = block->ipdominates; user; user = user->next) {
10233 child = user->member;
10234 if (child->ipdom != block) {
10235 internal_error(state, block->first, "bad ipdom");
10237 find_block_ipdomf(state, child);
10239 if (block->left && block->left->ipdom != block) {
10240 ipdomf_block(block, block->left);
10242 if (block->right && block->right->ipdom != block) {
10243 ipdomf_block(block, block->right);
10245 for(user = block->idominates; user; user = user->next) {
10246 struct block_set *frontier;
10247 child = user->member;
10248 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10249 if (frontier->member->ipdom != block) {
10250 ipdomf_block(block, frontier->member);
10256 static void print_dominated(
10257 struct compile_state *state, struct block *block, void *arg)
10259 struct block_set *user;
10262 fprintf(fp, "%d:", block->vertex);
10263 for(user = block->idominates; user; user = user->next) {
10264 fprintf(fp, " %d", user->member->vertex);
10265 if (user->member->idom != block) {
10266 internal_error(state, user->member->first, "bad idom");
10272 static void print_dominators(struct compile_state *state, FILE *fp)
10274 fprintf(fp, "\ndominates\n");
10275 walk_blocks(state, print_dominated, fp);
10279 static int print_frontiers(
10280 struct compile_state *state, struct block *block, int vertex)
10282 struct block_set *user;
10284 if (!block || (block->vertex != vertex + 1)) {
10289 printf("%d:", block->vertex);
10290 for(user = block->domfrontier; user; user = user->next) {
10291 printf(" %d", user->member->vertex);
10295 vertex = print_frontiers(state, block->left, vertex);
10296 vertex = print_frontiers(state, block->right, vertex);
10299 static void print_dominance_frontiers(struct compile_state *state)
10301 printf("\ndominance frontiers\n");
10302 print_frontiers(state, state->first_block, 0);
10306 static void analyze_idominators(struct compile_state *state)
10308 /* Find the immediate dominators */
10309 find_immediate_dominators(state);
10310 /* Find the dominance frontiers */
10311 find_block_domf(state, state->first_block);
10312 /* If debuging print the print what I have just found */
10313 if (state->debug & DEBUG_FDOMINATORS) {
10314 print_dominators(state, stdout);
10315 print_dominance_frontiers(state);
10316 print_control_flow(state);
10322 static void print_ipdominated(
10323 struct compile_state *state, struct block *block, void *arg)
10325 struct block_set *user;
10328 fprintf(fp, "%d:", block->vertex);
10329 for(user = block->ipdominates; user; user = user->next) {
10330 fprintf(fp, " %d", user->member->vertex);
10331 if (user->member->ipdom != block) {
10332 internal_error(state, user->member->first, "bad ipdom");
10338 static void print_ipdominators(struct compile_state *state, FILE *fp)
10340 fprintf(fp, "\nipdominates\n");
10341 walk_blocks(state, print_ipdominated, fp);
10344 static int print_pfrontiers(
10345 struct compile_state *state, struct block *block, int vertex)
10347 struct block_set *user;
10349 if (!block || (block->vertex != vertex + 1)) {
10354 printf("%d:", block->vertex);
10355 for(user = block->ipdomfrontier; user; user = user->next) {
10356 printf(" %d", user->member->vertex);
10359 for(user = block->use; user; user = user->next) {
10360 vertex = print_pfrontiers(state, user->member, vertex);
10364 static void print_ipdominance_frontiers(struct compile_state *state)
10366 printf("\nipdominance frontiers\n");
10367 print_pfrontiers(state, state->last_block, 0);
10371 static void analyze_ipdominators(struct compile_state *state)
10373 /* Find the post dominators */
10374 find_post_dominators(state);
10375 /* Find the control dependencies (post dominance frontiers) */
10376 find_block_ipdomf(state, state->last_block);
10377 /* If debuging print the print what I have just found */
10378 if (state->debug & DEBUG_RDOMINATORS) {
10379 print_ipdominators(state, stdout);
10380 print_ipdominance_frontiers(state);
10381 print_control_flow(state);
10385 static int bdominates(struct compile_state *state,
10386 struct block *dom, struct block *sub)
10388 while(sub && (sub != dom)) {
10394 static int tdominates(struct compile_state *state,
10395 struct triple *dom, struct triple *sub)
10397 struct block *bdom, *bsub;
10399 bdom = block_of_triple(state, dom);
10400 bsub = block_of_triple(state, sub);
10401 if (bdom != bsub) {
10402 result = bdominates(state, bdom, bsub);
10405 struct triple *ins;
10407 while((ins != bsub->first) && (ins != dom)) {
10410 result = (ins == dom);
10415 static void insert_phi_operations(struct compile_state *state)
10418 struct triple *first;
10419 int *has_already, *work;
10420 struct block *work_list, **work_list_tail;
10422 struct triple *var, *vnext;
10424 size = sizeof(int) * (state->last_vertex + 1);
10425 has_already = xcmalloc(size, "has_already");
10426 work = xcmalloc(size, "work");
10429 first = RHS(state->main_function, 0);
10430 for(var = first->next; var != first ; var = vnext) {
10431 struct block *block;
10432 struct triple_set *user, *unext;
10434 if ((var->op != OP_ADECL) || !var->use) {
10439 work_list_tail = &work_list;
10440 for(user = var->use; user; user = unext) {
10441 unext = user->next;
10442 if (user->member->op == OP_READ) {
10445 if (user->member->op != OP_WRITE) {
10446 internal_error(state, user->member,
10447 "bad variable access");
10449 block = user->member->u.block;
10451 warning(state, user->member, "dead code");
10452 release_triple(state, user->member);
10455 if (work[block->vertex] >= iter) {
10458 work[block->vertex] = iter;
10459 *work_list_tail = block;
10460 block->work_next = 0;
10461 work_list_tail = &block->work_next;
10463 for(block = work_list; block; block = block->work_next) {
10464 struct block_set *df;
10465 for(df = block->domfrontier; df; df = df->next) {
10466 struct triple *phi;
10467 struct block *front;
10469 front = df->member;
10471 if (has_already[front->vertex] >= iter) {
10474 /* Count how many edges flow into this block */
10475 in_edges = front->users;
10476 /* Insert a phi function for this variable */
10477 get_occurance(front->first->occurance);
10478 phi = alloc_triple(
10479 state, OP_PHI, var->type, -1, in_edges,
10480 front->first->occurance);
10481 phi->u.block = front;
10482 MISC(phi, 0) = var;
10483 use_triple(var, phi);
10484 /* Insert the phi functions immediately after the label */
10485 insert_triple(state, front->first->next, phi);
10486 if (front->first == front->last) {
10487 front->last = front->first->next;
10489 has_already[front->vertex] = iter;
10491 /* If necessary plan to visit the basic block */
10492 if (work[front->vertex] >= iter) {
10495 work[front->vertex] = iter;
10496 *work_list_tail = front;
10497 front->work_next = 0;
10498 work_list_tail = &front->work_next;
10502 xfree(has_already);
10510 static void fixup_block_phi_variables(
10511 struct compile_state *state, struct block *parent, struct block *block)
10513 struct block_set *set;
10514 struct triple *ptr;
10516 if (!parent || !block)
10518 /* Find the edge I am coming in on */
10520 for(set = block->use; set; set = set->next, edge++) {
10521 if (set->member == parent) {
10526 internal_error(state, 0, "phi input is not on a control predecessor");
10528 for(ptr = block->first; ; ptr = ptr->next) {
10529 if (ptr->op == OP_PHI) {
10530 struct triple *var, *val, **slot;
10531 var = MISC(ptr, 0);
10533 internal_error(state, ptr, "no var???");
10535 /* Find the current value of the variable */
10536 val = var->use->member;
10537 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10538 internal_error(state, val, "bad value in phi");
10540 if (edge >= TRIPLE_RHS(ptr->sizes)) {
10541 internal_error(state, ptr, "edges > phi rhs");
10543 slot = &RHS(ptr, edge);
10544 if ((*slot != 0) && (*slot != val)) {
10545 internal_error(state, ptr, "phi already bound on this edge");
10548 use_triple(val, ptr);
10550 if (ptr == block->last) {
10557 static void rename_block_variables(
10558 struct compile_state *state, struct block *block)
10560 struct block_set *user;
10561 struct triple *ptr, *next, *last;
10565 last = block->first;
10567 for(ptr = block->first; !done; ptr = next) {
10569 if (ptr == block->last) {
10573 if (ptr->op == OP_READ) {
10574 struct triple *var, *val;
10576 unuse_triple(var, ptr);
10578 error(state, ptr, "variable used without being set");
10580 /* Find the current value of the variable */
10581 val = var->use->member;
10582 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10583 internal_error(state, val, "bad value in read");
10585 propogate_use(state, ptr, val);
10586 release_triple(state, ptr);
10590 if (ptr->op == OP_WRITE) {
10591 struct triple *var, *val, *tval;
10593 tval = val = RHS(ptr, 1);
10594 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10595 internal_error(state, ptr, "bad value in write");
10597 /* Insert a copy if the types differ */
10598 if (!equiv_types(ptr->type, val->type)) {
10599 if (val->op == OP_INTCONST) {
10600 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
10601 tval->u.cval = val->u.cval;
10604 tval = pre_triple(state, ptr, OP_COPY, ptr->type, val, 0);
10605 use_triple(val, tval);
10607 unuse_triple(val, ptr);
10608 RHS(ptr, 1) = tval;
10609 use_triple(tval, ptr);
10611 propogate_use(state, ptr, tval);
10612 unuse_triple(var, ptr);
10613 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10614 push_triple(var, tval);
10616 if (ptr->op == OP_PHI) {
10617 struct triple *var;
10618 var = MISC(ptr, 0);
10619 /* Push OP_PHI onto a stack of variable uses */
10620 push_triple(var, ptr);
10624 block->last = last;
10626 /* Fixup PHI functions in the cf successors */
10627 fixup_block_phi_variables(state, block, block->left);
10628 fixup_block_phi_variables(state, block, block->right);
10629 /* rename variables in the dominated nodes */
10630 for(user = block->idominates; user; user = user->next) {
10631 rename_block_variables(state, user->member);
10633 /* pop the renamed variable stack */
10634 last = block->first;
10636 for(ptr = block->first; !done ; ptr = next) {
10638 if (ptr == block->last) {
10641 if (ptr->op == OP_WRITE) {
10642 struct triple *var;
10644 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10645 pop_triple(var, RHS(ptr, 1));
10646 release_triple(state, ptr);
10649 if (ptr->op == OP_PHI) {
10650 struct triple *var;
10651 var = MISC(ptr, 0);
10652 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10653 pop_triple(var, ptr);
10657 block->last = last;
10660 static void prune_block_variables(struct compile_state *state,
10661 struct block *block)
10663 struct block_set *user;
10664 struct triple *next, *last, *ptr;
10666 last = block->first;
10668 for(ptr = block->first; !done; ptr = next) {
10670 if (ptr == block->last) {
10673 if (ptr->op == OP_ADECL) {
10674 struct triple_set *user, *next;
10675 for(user = ptr->use; user; user = next) {
10676 struct triple *use;
10678 use = user->member;
10679 if (use->op != OP_PHI) {
10680 internal_error(state, use, "decl still used");
10682 if (MISC(use, 0) != ptr) {
10683 internal_error(state, use, "bad phi use of decl");
10685 unuse_triple(ptr, use);
10688 release_triple(state, ptr);
10693 block->last = last;
10694 for(user = block->idominates; user; user = user->next) {
10695 prune_block_variables(state, user->member);
10699 static void transform_to_ssa_form(struct compile_state *state)
10701 insert_phi_operations(state);
10703 printf("@%s:%d\n", __FILE__, __LINE__);
10704 print_blocks(state, stdout);
10706 rename_block_variables(state, state->first_block);
10707 prune_block_variables(state, state->first_block);
10711 static void clear_vertex(
10712 struct compile_state *state, struct block *block, void *arg)
10717 static void mark_live_block(
10718 struct compile_state *state, struct block *block, int *next_vertex)
10720 /* See if this is a block that has not been marked */
10721 if (block->vertex != 0) {
10724 block->vertex = *next_vertex;
10726 if (triple_is_branch(state, block->last)) {
10727 struct triple **targ;
10728 targ = triple_targ(state, block->last, 0);
10729 for(; targ; targ = triple_targ(state, block->last, targ)) {
10733 if (!triple_stores_block(state, *targ)) {
10734 internal_error(state, 0, "bad targ");
10736 mark_live_block(state, (*targ)->u.block, next_vertex);
10739 else if (block->last->next != RHS(state->main_function, 0)) {
10740 struct triple *ins;
10741 ins = block->last->next;
10742 if (!triple_stores_block(state, ins)) {
10743 internal_error(state, 0, "bad block start");
10745 mark_live_block(state, ins->u.block, next_vertex);
10749 static void transform_from_ssa_form(struct compile_state *state)
10751 /* To get out of ssa form we insert moves on the incoming
10752 * edges to blocks containting phi functions.
10754 struct triple *first;
10755 struct triple *phi, *next;
10758 /* Walk the control flow to see which blocks remain alive */
10759 walk_blocks(state, clear_vertex, 0);
10761 mark_live_block(state, state->first_block, &next_vertex);
10763 /* Walk all of the operations to find the phi functions */
10764 first = RHS(state->main_function, 0);
10765 for(phi = first->next; phi != first ; phi = next) {
10766 struct block_set *set;
10767 struct block *block;
10768 struct triple **slot;
10769 struct triple *var, *read;
10770 struct triple_set *use, *use_next;
10773 if (phi->op != OP_PHI) {
10776 block = phi->u.block;
10777 slot = &RHS(phi, 0);
10779 /* Forget uses from code in dead blocks */
10780 for(use = phi->use; use; use = use_next) {
10781 struct block *ublock;
10782 struct triple **expr;
10783 use_next = use->next;
10784 ublock = block_of_triple(state, use->member);
10785 if ((use->member == phi) || (ublock->vertex != 0)) {
10788 expr = triple_rhs(state, use->member, 0);
10789 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10790 if (*expr == phi) {
10794 unuse_triple(phi, use->member);
10797 #warning "CHECK_ME does the OP_ADECL need to be placed somewhere that dominates all of the incoming phi edges?"
10798 /* A variable to replace the phi function */
10799 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10800 /* A read of the single value that is set into the variable */
10801 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10802 use_triple(var, read);
10804 /* Replaces uses of the phi with variable reads */
10805 propogate_use(state, phi, read);
10807 /* Walk all of the incoming edges/blocks and insert moves.
10809 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10810 struct block *eblock;
10811 struct triple *move;
10812 struct triple *val, *base;
10813 eblock = set->member;
10816 unuse_triple(val, phi);
10818 if (!val || (val == &zero_triple) ||
10819 (block->vertex == 0) || (eblock->vertex == 0) ||
10820 (val == phi) || (val == read)) {
10824 /* Make certain the write is placed in the edge block... */
10825 base = eblock->first;
10826 if (block_of_triple(state, val) == eblock) {
10829 move = post_triple(state, base, OP_WRITE, phi->type, var, val);
10830 use_triple(val, move);
10831 use_triple(var, move);
10833 /* See if there are any writers of var */
10835 for(use = var->use; use; use = use->next) {
10836 if ((use->member->op == OP_WRITE) &&
10837 (RHS(use->member, 0) == var)) {
10841 /* If var is not used free it */
10843 unuse_triple(var, read);
10844 free_triple(state, read);
10845 free_triple(state, var);
10848 /* Release the phi function */
10849 release_triple(state, phi);
10856 * Register conflict resolution
10857 * =========================================================
10860 static struct reg_info find_def_color(
10861 struct compile_state *state, struct triple *def)
10863 struct triple_set *set;
10864 struct reg_info info;
10865 info.reg = REG_UNSET;
10867 if (!triple_is_def(state, def)) {
10870 info = arch_reg_lhs(state, def, 0);
10871 if (info.reg >= MAX_REGISTERS) {
10872 info.reg = REG_UNSET;
10874 for(set = def->use; set; set = set->next) {
10875 struct reg_info tinfo;
10877 i = find_rhs_use(state, set->member, def);
10881 tinfo = arch_reg_rhs(state, set->member, i);
10882 if (tinfo.reg >= MAX_REGISTERS) {
10883 tinfo.reg = REG_UNSET;
10885 if ((tinfo.reg != REG_UNSET) &&
10886 (info.reg != REG_UNSET) &&
10887 (tinfo.reg != info.reg)) {
10888 internal_error(state, def, "register conflict");
10890 if ((info.regcm & tinfo.regcm) == 0) {
10891 internal_error(state, def, "regcm conflict %x & %x == 0",
10892 info.regcm, tinfo.regcm);
10894 if (info.reg == REG_UNSET) {
10895 info.reg = tinfo.reg;
10897 info.regcm &= tinfo.regcm;
10899 if (info.reg >= MAX_REGISTERS) {
10900 internal_error(state, def, "register out of range");
10905 static struct reg_info find_lhs_pre_color(
10906 struct compile_state *state, struct triple *ins, int index)
10908 struct reg_info info;
10910 zrhs = TRIPLE_RHS(ins->sizes);
10911 zlhs = TRIPLE_LHS(ins->sizes);
10912 if (!zlhs && triple_is_def(state, ins)) {
10915 if (index >= zlhs) {
10916 internal_error(state, ins, "Bad lhs %d", index);
10918 info = arch_reg_lhs(state, ins, index);
10919 for(i = 0; i < zrhs; i++) {
10920 struct reg_info rinfo;
10921 rinfo = arch_reg_rhs(state, ins, i);
10922 if ((info.reg == rinfo.reg) &&
10923 (rinfo.reg >= MAX_REGISTERS)) {
10924 struct reg_info tinfo;
10925 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10926 info.reg = tinfo.reg;
10927 info.regcm &= tinfo.regcm;
10931 if (info.reg >= MAX_REGISTERS) {
10932 info.reg = REG_UNSET;
10937 static struct reg_info find_rhs_post_color(
10938 struct compile_state *state, struct triple *ins, int index);
10940 static struct reg_info find_lhs_post_color(
10941 struct compile_state *state, struct triple *ins, int index)
10943 struct triple_set *set;
10944 struct reg_info info;
10945 struct triple *lhs;
10946 #if DEBUG_TRIPLE_COLOR
10947 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10950 if ((index == 0) && triple_is_def(state, ins)) {
10953 else if (index < TRIPLE_LHS(ins->sizes)) {
10954 lhs = LHS(ins, index);
10957 internal_error(state, ins, "Bad lhs %d", index);
10960 info = arch_reg_lhs(state, ins, index);
10961 if (info.reg >= MAX_REGISTERS) {
10962 info.reg = REG_UNSET;
10964 for(set = lhs->use; set; set = set->next) {
10965 struct reg_info rinfo;
10966 struct triple *user;
10968 user = set->member;
10969 zrhs = TRIPLE_RHS(user->sizes);
10970 for(i = 0; i < zrhs; i++) {
10971 if (RHS(user, i) != lhs) {
10974 rinfo = find_rhs_post_color(state, user, i);
10975 if ((info.reg != REG_UNSET) &&
10976 (rinfo.reg != REG_UNSET) &&
10977 (info.reg != rinfo.reg)) {
10978 internal_error(state, ins, "register conflict");
10980 if ((info.regcm & rinfo.regcm) == 0) {
10981 internal_error(state, ins, "regcm conflict %x & %x == 0",
10982 info.regcm, rinfo.regcm);
10984 if (info.reg == REG_UNSET) {
10985 info.reg = rinfo.reg;
10987 info.regcm &= rinfo.regcm;
10990 #if DEBUG_TRIPLE_COLOR
10991 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10992 ins, index, info.reg, info.regcm);
10997 static struct reg_info find_rhs_post_color(
10998 struct compile_state *state, struct triple *ins, int index)
11000 struct reg_info info, rinfo;
11002 #if DEBUG_TRIPLE_COLOR
11003 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
11006 rinfo = arch_reg_rhs(state, ins, index);
11007 zlhs = TRIPLE_LHS(ins->sizes);
11008 if (!zlhs && triple_is_def(state, ins)) {
11012 if (info.reg >= MAX_REGISTERS) {
11013 info.reg = REG_UNSET;
11015 for(i = 0; i < zlhs; i++) {
11016 struct reg_info linfo;
11017 linfo = arch_reg_lhs(state, ins, i);
11018 if ((linfo.reg == rinfo.reg) &&
11019 (linfo.reg >= MAX_REGISTERS)) {
11020 struct reg_info tinfo;
11021 tinfo = find_lhs_post_color(state, ins, i);
11022 if (tinfo.reg >= MAX_REGISTERS) {
11023 tinfo.reg = REG_UNSET;
11025 info.regcm &= linfo.regcm;
11026 info.regcm &= tinfo.regcm;
11027 if (info.reg != REG_UNSET) {
11028 internal_error(state, ins, "register conflict");
11030 if (info.regcm == 0) {
11031 internal_error(state, ins, "regcm conflict");
11033 info.reg = tinfo.reg;
11036 #if DEBUG_TRIPLE_COLOR
11037 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
11038 ins, index, info.reg, info.regcm);
11043 static struct reg_info find_lhs_color(
11044 struct compile_state *state, struct triple *ins, int index)
11046 struct reg_info pre, post, info;
11047 #if DEBUG_TRIPLE_COLOR
11048 fprintf(stderr, "find_lhs_color(%p, %d)\n",
11051 pre = find_lhs_pre_color(state, ins, index);
11052 post = find_lhs_post_color(state, ins, index);
11053 if ((pre.reg != post.reg) &&
11054 (pre.reg != REG_UNSET) &&
11055 (post.reg != REG_UNSET)) {
11056 internal_error(state, ins, "register conflict");
11058 info.regcm = pre.regcm & post.regcm;
11059 info.reg = pre.reg;
11060 if (info.reg == REG_UNSET) {
11061 info.reg = post.reg;
11063 #if DEBUG_TRIPLE_COLOR
11064 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
11065 ins, index, info.reg, info.regcm,
11066 pre.reg, pre.regcm, post.reg, post.regcm);
11071 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
11073 struct triple_set *entry, *next;
11074 struct triple *out;
11075 struct reg_info info, rinfo;
11077 info = arch_reg_lhs(state, ins, 0);
11078 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
11079 use_triple(RHS(out, 0), out);
11080 /* Get the users of ins to use out instead */
11081 for(entry = ins->use; entry; entry = next) {
11083 next = entry->next;
11084 if (entry->member == out) {
11087 i = find_rhs_use(state, entry->member, ins);
11091 rinfo = arch_reg_rhs(state, entry->member, i);
11092 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
11095 replace_rhs_use(state, ins, out, entry->member);
11097 transform_to_arch_instruction(state, out);
11101 static struct triple *typed_pre_copy(
11102 struct compile_state *state, struct type *type, struct triple *ins, int index)
11104 /* Carefully insert enough operations so that I can
11105 * enter any operation with a GPR32.
11108 struct triple **expr;
11110 struct reg_info info;
11111 if (ins->op == OP_PHI) {
11112 internal_error(state, ins, "pre_copy on a phi?");
11114 classes = arch_type_to_regcm(state, type);
11115 info = arch_reg_rhs(state, ins, index);
11116 expr = &RHS(ins, index);
11117 if ((info.regcm & classes) == 0) {
11118 internal_error(state, ins, "pre_copy with no register classes");
11120 in = pre_triple(state, ins, OP_COPY, type, *expr, 0);
11121 unuse_triple(*expr, ins);
11123 use_triple(RHS(in, 0), in);
11124 use_triple(in, ins);
11125 transform_to_arch_instruction(state, in);
11129 static struct triple *pre_copy(
11130 struct compile_state *state, struct triple *ins, int index)
11132 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
11136 static void insert_copies_to_phi(struct compile_state *state)
11138 /* To get out of ssa form we insert moves on the incoming
11139 * edges to blocks containting phi functions.
11141 struct triple *first;
11142 struct triple *phi;
11144 /* Walk all of the operations to find the phi functions */
11145 first = RHS(state->main_function, 0);
11146 for(phi = first->next; phi != first ; phi = phi->next) {
11147 struct block_set *set;
11148 struct block *block;
11149 struct triple **slot, *copy;
11151 if (phi->op != OP_PHI) {
11154 phi->id |= TRIPLE_FLAG_POST_SPLIT;
11155 block = phi->u.block;
11156 slot = &RHS(phi, 0);
11157 /* Phi's that feed into mandatory live range joins
11158 * cause nasty complications. Insert a copy of
11159 * the phi value so I never have to deal with
11160 * that in the rest of the code.
11162 copy = post_copy(state, phi);
11163 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
11164 /* Walk all of the incoming edges/blocks and insert moves.
11166 for(edge = 0, set = block->use; set; set = set->next, edge++) {
11167 struct block *eblock;
11168 struct triple *move;
11169 struct triple *val;
11170 struct triple *ptr;
11171 eblock = set->member;
11178 get_occurance(val->occurance);
11179 move = build_triple(state, OP_COPY, phi->type, val, 0,
11181 move->u.block = eblock;
11182 move->id |= TRIPLE_FLAG_PRE_SPLIT;
11183 use_triple(val, move);
11186 unuse_triple(val, phi);
11187 use_triple(move, phi);
11189 /* Walk through the block backwards to find
11190 * an appropriate location for the OP_COPY.
11192 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
11193 struct triple **expr;
11194 if ((ptr == phi) || (ptr == val)) {
11197 expr = triple_rhs(state, ptr, 0);
11198 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11199 if ((*expr) == phi) {
11205 if (triple_is_branch(state, ptr)) {
11206 internal_error(state, ptr,
11207 "Could not insert write to phi");
11209 insert_triple(state, ptr->next, move);
11210 if (eblock->last == ptr) {
11211 eblock->last = move;
11213 transform_to_arch_instruction(state, move);
11218 struct triple_reg_set {
11219 struct triple_reg_set *next;
11220 struct triple *member;
11221 struct triple *new;
11225 struct block *block;
11226 struct triple_reg_set *in;
11227 struct triple_reg_set *out;
11231 static int do_triple_set(struct triple_reg_set **head,
11232 struct triple *member, struct triple *new_member)
11234 struct triple_reg_set **ptr, *new;
11239 if ((*ptr)->member == member) {
11242 ptr = &(*ptr)->next;
11244 new = xcmalloc(sizeof(*new), "triple_set");
11245 new->member = member;
11246 new->new = new_member;
11252 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11254 struct triple_reg_set *entry, **ptr;
11258 if (entry->member == member) {
11259 *ptr = entry->next;
11264 ptr = &entry->next;
11269 static int in_triple(struct reg_block *rb, struct triple *in)
11271 return do_triple_set(&rb->in, in, 0);
11273 static void unin_triple(struct reg_block *rb, struct triple *unin)
11275 do_triple_unset(&rb->in, unin);
11278 static int out_triple(struct reg_block *rb, struct triple *out)
11280 return do_triple_set(&rb->out, out, 0);
11282 static void unout_triple(struct reg_block *rb, struct triple *unout)
11284 do_triple_unset(&rb->out, unout);
11287 static int initialize_regblock(struct reg_block *blocks,
11288 struct block *block, int vertex)
11290 struct block_set *user;
11291 if (!block || (blocks[block->vertex].block == block)) {
11295 /* Renumber the blocks in a convinient fashion */
11296 block->vertex = vertex;
11297 blocks[vertex].block = block;
11298 blocks[vertex].vertex = vertex;
11299 for(user = block->use; user; user = user->next) {
11300 vertex = initialize_regblock(blocks, user->member, vertex);
11305 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11306 struct reg_block *rb, struct block *suc)
11308 /* Read the conditional input set of a successor block
11309 * (i.e. the input to the phi nodes) and place it in the
11310 * current blocks output set.
11312 struct block_set *set;
11313 struct triple *ptr;
11317 /* Find the edge I am coming in on */
11318 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11319 if (set->member == rb->block) {
11324 internal_error(state, 0, "Not coming on a control edge?");
11326 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11327 struct triple **slot, *expr, *ptr2;
11328 int out_change, done2;
11329 done = (ptr == suc->last);
11330 if (ptr->op != OP_PHI) {
11333 slot = &RHS(ptr, 0);
11335 out_change = out_triple(rb, expr);
11339 /* If we don't define the variable also plast it
11340 * in the current blocks input set.
11342 ptr2 = rb->block->first;
11343 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11344 if (ptr2 == expr) {
11347 done2 = (ptr2 == rb->block->last);
11352 change |= in_triple(rb, expr);
11357 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11358 struct reg_block *rb, struct block *suc)
11360 struct triple_reg_set *in_set;
11363 /* Read the input set of a successor block
11364 * and place it in the current blocks output set.
11366 in_set = blocks[suc->vertex].in;
11367 for(; in_set; in_set = in_set->next) {
11368 int out_change, done;
11369 struct triple *first, *last, *ptr;
11370 out_change = out_triple(rb, in_set->member);
11374 /* If we don't define the variable also place it
11375 * in the current blocks input set.
11377 first = rb->block->first;
11378 last = rb->block->last;
11380 for(ptr = first; !done; ptr = ptr->next) {
11381 if (ptr == in_set->member) {
11384 done = (ptr == last);
11389 change |= in_triple(rb, in_set->member);
11391 change |= phi_in(state, blocks, rb, suc);
11396 static int use_in(struct compile_state *state, struct reg_block *rb)
11398 /* Find the variables we use but don't define and add
11399 * it to the current blocks input set.
11401 #warning "FIXME is this O(N^2) algorithm bad?"
11402 struct block *block;
11403 struct triple *ptr;
11408 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11409 struct triple **expr;
11410 done = (ptr == block->first);
11411 /* The variable a phi function uses depends on the
11412 * control flow, and is handled in phi_in, not
11415 if (ptr->op == OP_PHI) {
11418 expr = triple_rhs(state, ptr, 0);
11419 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11420 struct triple *rhs, *test;
11426 /* See if rhs is defined in this block */
11427 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11428 tdone = (test == block->first);
11434 /* If I still have a valid rhs add it to in */
11435 change |= in_triple(rb, rhs);
11441 static struct reg_block *compute_variable_lifetimes(
11442 struct compile_state *state)
11444 struct reg_block *blocks;
11447 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11448 initialize_regblock(blocks, state->last_block, 0);
11452 for(i = 1; i <= state->last_vertex; i++) {
11453 struct reg_block *rb;
11455 /* Add the left successor's input set to in */
11456 if (rb->block->left) {
11457 change |= reg_in(state, blocks, rb, rb->block->left);
11459 /* Add the right successor's input set to in */
11460 if ((rb->block->right) &&
11461 (rb->block->right != rb->block->left)) {
11462 change |= reg_in(state, blocks, rb, rb->block->right);
11464 /* Add use to in... */
11465 change |= use_in(state, rb);
11471 static void free_variable_lifetimes(
11472 struct compile_state *state, struct reg_block *blocks)
11475 /* free in_set && out_set on each block */
11476 for(i = 1; i <= state->last_vertex; i++) {
11477 struct triple_reg_set *entry, *next;
11478 struct reg_block *rb;
11480 for(entry = rb->in; entry ; entry = next) {
11481 next = entry->next;
11482 do_triple_unset(&rb->in, entry->member);
11484 for(entry = rb->out; entry; entry = next) {
11485 next = entry->next;
11486 do_triple_unset(&rb->out, entry->member);
11493 typedef void (*wvl_cb_t)(
11494 struct compile_state *state,
11495 struct reg_block *blocks, struct triple_reg_set *live,
11496 struct reg_block *rb, struct triple *ins, void *arg);
11498 static void walk_variable_lifetimes(struct compile_state *state,
11499 struct reg_block *blocks, wvl_cb_t cb, void *arg)
11503 for(i = 1; i <= state->last_vertex; i++) {
11504 struct triple_reg_set *live;
11505 struct triple_reg_set *entry, *next;
11506 struct triple *ptr, *prev;
11507 struct reg_block *rb;
11508 struct block *block;
11511 /* Get the blocks */
11515 /* Copy out into live */
11517 for(entry = rb->out; entry; entry = next) {
11518 next = entry->next;
11519 do_triple_set(&live, entry->member, entry->new);
11521 /* Walk through the basic block calculating live */
11522 for(done = 0, ptr = block->last; !done; ptr = prev) {
11523 struct triple **expr;
11526 done = (ptr == block->first);
11528 /* Ensure the current definition is in live */
11529 if (triple_is_def(state, ptr)) {
11530 do_triple_set(&live, ptr, 0);
11533 /* Inform the callback function of what is
11536 cb(state, blocks, live, rb, ptr, arg);
11538 /* Remove the current definition from live */
11539 do_triple_unset(&live, ptr);
11541 /* Add the current uses to live.
11543 * It is safe to skip phi functions because they do
11544 * not have any block local uses, and the block
11545 * output sets already properly account for what
11546 * control flow depedent uses phi functions do have.
11548 if (ptr->op == OP_PHI) {
11551 expr = triple_rhs(state, ptr, 0);
11552 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11553 /* If the triple is not a definition skip it. */
11554 if (!*expr || !triple_is_def(state, *expr)) {
11557 do_triple_set(&live, *expr, 0);
11561 for(entry = live; entry; entry = next) {
11562 next = entry->next;
11563 do_triple_unset(&live, entry->member);
11568 static int count_triples(struct compile_state *state)
11570 struct triple *first, *ins;
11572 first = RHS(state->main_function, 0);
11577 } while (ins != first);
11580 struct dead_triple {
11581 struct triple *triple;
11582 struct dead_triple *work_next;
11583 struct block *block;
11586 #define TRIPLE_FLAG_ALIVE 1
11590 static void awaken(
11591 struct compile_state *state,
11592 struct dead_triple *dtriple, struct triple **expr,
11593 struct dead_triple ***work_list_tail)
11595 struct triple *triple;
11596 struct dead_triple *dt;
11604 if (triple->id <= 0) {
11605 internal_error(state, triple, "bad triple id: %d",
11608 if (triple->op == OP_NOOP) {
11609 internal_warning(state, triple, "awakening noop?");
11612 dt = &dtriple[triple->id];
11613 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11614 dt->flags |= TRIPLE_FLAG_ALIVE;
11615 if (!dt->work_next) {
11616 **work_list_tail = dt;
11617 *work_list_tail = &dt->work_next;
11622 static void eliminate_inefectual_code(struct compile_state *state)
11624 struct block *block;
11625 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11627 struct triple *first, *ins;
11629 /* Setup the work list */
11631 work_list_tail = &work_list;
11633 first = RHS(state->main_function, 0);
11635 /* Count how many triples I have */
11636 triples = count_triples(state);
11638 /* Now put then in an array and mark all of the triples dead */
11639 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11645 if (ins->op == OP_LABEL) {
11646 block = ins->u.block;
11648 dtriple[i].triple = ins;
11649 dtriple[i].block = block;
11650 dtriple[i].flags = 0;
11651 dtriple[i].color = ins->id;
11653 /* See if it is an operation we always keep */
11654 #warning "FIXME handle the case of killing a branch instruction"
11655 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11656 awaken(state, dtriple, &ins, &work_list_tail);
11659 /* Unconditionally keep the very last instruction */
11660 else if (ins->next == first) {
11661 awaken(state, dtriple, &ins, &work_list_tail);
11666 } while(ins != first);
11668 struct dead_triple *dt;
11669 struct block_set *user;
11670 struct triple **expr;
11672 work_list = dt->work_next;
11674 work_list_tail = &work_list;
11676 /* Wake up the data depencencies of this triple */
11679 expr = triple_rhs(state, dt->triple, expr);
11680 awaken(state, dtriple, expr, &work_list_tail);
11683 expr = triple_lhs(state, dt->triple, expr);
11684 awaken(state, dtriple, expr, &work_list_tail);
11687 expr = triple_misc(state, dt->triple, expr);
11688 awaken(state, dtriple, expr, &work_list_tail);
11690 /* Wake up the forward control dependencies */
11692 expr = triple_targ(state, dt->triple, expr);
11693 awaken(state, dtriple, expr, &work_list_tail);
11695 /* Wake up the reverse control dependencies of this triple */
11696 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11697 awaken(state, dtriple, &user->member->last, &work_list_tail);
11700 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11701 if ((dt->triple->op == OP_NOOP) &&
11702 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11703 internal_error(state, dt->triple, "noop effective?");
11705 dt->triple->id = dt->color; /* Restore the color */
11706 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11707 #warning "FIXME handle the case of killing a basic block"
11708 if (dt->block->first == dt->triple) {
11711 if (dt->block->last == dt->triple) {
11712 dt->block->last = dt->triple->prev;
11714 release_triple(state, dt->triple);
11721 static void insert_mandatory_copies(struct compile_state *state)
11723 struct triple *ins, *first;
11725 /* The object is with a minimum of inserted copies,
11726 * to resolve in fundamental register conflicts between
11727 * register value producers and consumers.
11728 * Theoretically we may be greater than minimal when we
11729 * are inserting copies before instructions but that
11730 * case should be rare.
11732 first = RHS(state->main_function, 0);
11735 struct triple_set *entry, *next;
11736 struct triple *tmp;
11737 struct reg_info info;
11738 unsigned reg, regcm;
11739 int do_post_copy, do_pre_copy;
11741 if (!triple_is_def(state, ins)) {
11744 /* Find the architecture specific color information */
11745 info = arch_reg_lhs(state, ins, 0);
11746 if (info.reg >= MAX_REGISTERS) {
11747 info.reg = REG_UNSET;
11751 regcm = arch_type_to_regcm(state, ins->type);
11752 do_post_copy = do_pre_copy = 0;
11754 /* Walk through the uses of ins and check for conflicts */
11755 for(entry = ins->use; entry; entry = next) {
11756 struct reg_info rinfo;
11758 next = entry->next;
11759 i = find_rhs_use(state, entry->member, ins);
11764 /* Find the users color requirements */
11765 rinfo = arch_reg_rhs(state, entry->member, i);
11766 if (rinfo.reg >= MAX_REGISTERS) {
11767 rinfo.reg = REG_UNSET;
11770 /* See if I need a pre_copy */
11771 if (rinfo.reg != REG_UNSET) {
11772 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11777 regcm &= rinfo.regcm;
11778 regcm = arch_regcm_normalize(state, regcm);
11782 /* Always use pre_copies for constants.
11783 * They do not take up any registers until a
11784 * copy places them in one.
11786 if ((info.reg == REG_UNNEEDED) &&
11787 (rinfo.reg != REG_UNNEEDED)) {
11793 (((info.reg != REG_UNSET) &&
11794 (reg != REG_UNSET) &&
11795 (info.reg != reg)) ||
11796 ((info.regcm & regcm) == 0));
11799 regcm = info.regcm;
11800 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
11801 for(entry = ins->use; entry; entry = next) {
11802 struct reg_info rinfo;
11804 next = entry->next;
11805 i = find_rhs_use(state, entry->member, ins);
11810 /* Find the users color requirements */
11811 rinfo = arch_reg_rhs(state, entry->member, i);
11812 if (rinfo.reg >= MAX_REGISTERS) {
11813 rinfo.reg = REG_UNSET;
11816 /* Now see if it is time to do the pre_copy */
11817 if (rinfo.reg != REG_UNSET) {
11818 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11819 ((regcm & rinfo.regcm) == 0) ||
11820 /* Don't let a mandatory coalesce sneak
11821 * into a operation that is marked to prevent
11824 ((reg != REG_UNNEEDED) &&
11825 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11826 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11829 struct triple *user;
11830 user = entry->member;
11831 if (RHS(user, i) != ins) {
11832 internal_error(state, user, "bad rhs");
11834 tmp = pre_copy(state, user, i);
11835 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11843 if ((regcm & rinfo.regcm) == 0) {
11845 struct triple *user;
11846 user = entry->member;
11847 if (RHS(user, i) != ins) {
11848 internal_error(state, user, "bad rhs");
11850 tmp = pre_copy(state, user, i);
11851 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11857 regcm &= rinfo.regcm;
11860 if (do_post_copy) {
11861 struct reg_info pre, post;
11862 tmp = post_copy(state, ins);
11863 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11864 pre = arch_reg_lhs(state, ins, 0);
11865 post = arch_reg_lhs(state, tmp, 0);
11866 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11867 internal_error(state, tmp, "useless copy");
11872 } while(ins != first);
11876 struct live_range_edge;
11877 struct live_range_def;
11878 struct live_range {
11879 struct live_range_edge *edges;
11880 struct live_range_def *defs;
11881 /* Note. The list pointed to by defs is kept in order.
11882 * That is baring splits in the flow control
11883 * defs dominates defs->next wich dominates defs->next->next
11890 struct live_range *group_next, **group_prev;
11893 struct live_range_edge {
11894 struct live_range_edge *next;
11895 struct live_range *node;
11898 struct live_range_def {
11899 struct live_range_def *next;
11900 struct live_range_def *prev;
11901 struct live_range *lr;
11902 struct triple *def;
11906 #define LRE_HASH_SIZE 2048
11908 struct lre_hash *next;
11909 struct live_range *left;
11910 struct live_range *right;
11915 struct lre_hash *hash[LRE_HASH_SIZE];
11916 struct reg_block *blocks;
11917 struct live_range_def *lrd;
11918 struct live_range *lr;
11919 struct live_range *low, **low_tail;
11920 struct live_range *high, **high_tail;
11923 int passes, max_passes;
11924 #define MAX_ALLOCATION_PASSES 100
11929 struct print_interference_block_info {
11930 struct reg_state *rstate;
11934 static void print_interference_block(
11935 struct compile_state *state, struct block *block, void *arg)
11938 struct print_interference_block_info *info = arg;
11939 struct reg_state *rstate = info->rstate;
11940 FILE *fp = info->fp;
11941 struct reg_block *rb;
11942 struct triple *ptr;
11945 rb = &rstate->blocks[block->vertex];
11947 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
11951 block->left && block->left->use?block->left->use->member : 0,
11953 block->right && block->right->use?block->right->use->member : 0);
11955 struct triple_reg_set *in_set;
11956 fprintf(fp, " in:");
11957 for(in_set = rb->in; in_set; in_set = in_set->next) {
11958 fprintf(fp, " %-10p", in_set->member);
11963 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11964 done = (ptr == block->last);
11965 if (ptr->op == OP_PHI) {
11972 for(edge = 0; edge < block->users; edge++) {
11973 fprintf(fp, " in(%d):", edge);
11974 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11975 struct triple **slot;
11976 done = (ptr == block->last);
11977 if (ptr->op != OP_PHI) {
11980 slot = &RHS(ptr, 0);
11981 fprintf(fp, " %-10p", slot[edge]);
11986 if (block->first->op == OP_LABEL) {
11987 fprintf(fp, "%p:\n", block->first);
11989 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11990 struct live_range *lr;
11994 done = (ptr == block->last);
11995 lr = rstate->lrd[ptr->id].lr;
11998 ptr->id = rstate->lrd[id].orig_id;
11999 SET_REG(ptr->id, lr->color);
12000 display_triple(fp, ptr);
12003 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
12004 internal_error(state, ptr, "lr has no defs!");
12006 if (info->need_edges) {
12008 struct live_range_def *lrd;
12009 fprintf(fp, " range:");
12012 fprintf(fp, " %-10p", lrd->def);
12014 } while(lrd != lr->defs);
12017 if (lr->edges > 0) {
12018 struct live_range_edge *edge;
12019 fprintf(fp, " edges:");
12020 for(edge = lr->edges; edge; edge = edge->next) {
12021 struct live_range_def *lrd;
12022 lrd = edge->node->defs;
12024 fprintf(fp, " %-10p", lrd->def);
12026 } while(lrd != edge->node->defs);
12032 /* Do a bunch of sanity checks */
12033 valid_ins(state, ptr);
12034 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
12035 internal_error(state, ptr, "Invalid triple id: %d",
12040 struct triple_reg_set *out_set;
12041 fprintf(fp, " out:");
12042 for(out_set = rb->out; out_set; out_set = out_set->next) {
12043 fprintf(fp, " %-10p", out_set->member);
12050 static void print_interference_blocks(
12051 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
12053 struct print_interference_block_info info;
12054 info.rstate = rstate;
12056 info.need_edges = need_edges;
12057 fprintf(fp, "\nlive variables by block\n");
12058 walk_blocks(state, print_interference_block, &info);
12062 static unsigned regc_max_size(struct compile_state *state, int classes)
12067 for(i = 0; i < MAX_REGC; i++) {
12068 if (classes & (1 << i)) {
12070 size = arch_regc_size(state, i);
12071 if (size > max_size) {
12079 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
12081 unsigned equivs[MAX_REG_EQUIVS];
12083 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
12084 internal_error(state, 0, "invalid register");
12086 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
12087 internal_error(state, 0, "invalid register");
12089 arch_reg_equivs(state, equivs, reg1);
12090 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12091 if (equivs[i] == reg2) {
12098 static void reg_fill_used(struct compile_state *state, char *used, int reg)
12100 unsigned equivs[MAX_REG_EQUIVS];
12102 if (reg == REG_UNNEEDED) {
12105 arch_reg_equivs(state, equivs, reg);
12106 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12107 used[equivs[i]] = 1;
12112 static void reg_inc_used(struct compile_state *state, char *used, int reg)
12114 unsigned equivs[MAX_REG_EQUIVS];
12116 if (reg == REG_UNNEEDED) {
12119 arch_reg_equivs(state, equivs, reg);
12120 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12121 used[equivs[i]] += 1;
12126 static unsigned int hash_live_edge(
12127 struct live_range *left, struct live_range *right)
12129 unsigned int hash, val;
12130 unsigned long lval, rval;
12131 lval = ((unsigned long)left)/sizeof(struct live_range);
12132 rval = ((unsigned long)right)/sizeof(struct live_range);
12137 hash = (hash *263) + val;
12142 hash = (hash *263) + val;
12144 hash = hash & (LRE_HASH_SIZE - 1);
12148 static struct lre_hash **lre_probe(struct reg_state *rstate,
12149 struct live_range *left, struct live_range *right)
12151 struct lre_hash **ptr;
12152 unsigned int index;
12153 /* Ensure left <= right */
12154 if (left > right) {
12155 struct live_range *tmp;
12160 index = hash_live_edge(left, right);
12162 ptr = &rstate->hash[index];
12164 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
12167 ptr = &(*ptr)->next;
12172 static int interfere(struct reg_state *rstate,
12173 struct live_range *left, struct live_range *right)
12175 struct lre_hash **ptr;
12176 ptr = lre_probe(rstate, left, right);
12177 return ptr && *ptr;
12180 static void add_live_edge(struct reg_state *rstate,
12181 struct live_range *left, struct live_range *right)
12183 /* FIXME the memory allocation overhead is noticeable here... */
12184 struct lre_hash **ptr, *new_hash;
12185 struct live_range_edge *edge;
12187 if (left == right) {
12190 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
12193 /* Ensure left <= right */
12194 if (left > right) {
12195 struct live_range *tmp;
12200 ptr = lre_probe(rstate, left, right);
12205 fprintf(stderr, "new_live_edge(%p, %p)\n",
12208 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
12209 new_hash->next = *ptr;
12210 new_hash->left = left;
12211 new_hash->right = right;
12214 edge = xmalloc(sizeof(*edge), "live_range_edge");
12215 edge->next = left->edges;
12216 edge->node = right;
12217 left->edges = edge;
12220 edge = xmalloc(sizeof(*edge), "live_range_edge");
12221 edge->next = right->edges;
12223 right->edges = edge;
12224 right->degree += 1;
12227 static void remove_live_edge(struct reg_state *rstate,
12228 struct live_range *left, struct live_range *right)
12230 struct live_range_edge *edge, **ptr;
12231 struct lre_hash **hptr, *entry;
12232 hptr = lre_probe(rstate, left, right);
12233 if (!hptr || !*hptr) {
12237 *hptr = entry->next;
12240 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
12242 if (edge->node == right) {
12244 memset(edge, 0, sizeof(*edge));
12250 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
12252 if (edge->node == left) {
12254 memset(edge, 0, sizeof(*edge));
12262 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
12264 struct live_range_edge *edge, *next;
12265 for(edge = range->edges; edge; edge = next) {
12267 remove_live_edge(rstate, range, edge->node);
12271 static void transfer_live_edges(struct reg_state *rstate,
12272 struct live_range *dest, struct live_range *src)
12274 struct live_range_edge *edge, *next;
12275 for(edge = src->edges; edge; edge = next) {
12276 struct live_range *other;
12278 other = edge->node;
12279 remove_live_edge(rstate, src, other);
12280 add_live_edge(rstate, dest, other);
12285 /* Interference graph...
12287 * new(n) --- Return a graph with n nodes but no edges.
12288 * add(g,x,y) --- Return a graph including g with an between x and y
12289 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
12290 * x and y in the graph g
12291 * degree(g, x) --- Return the degree of the node x in the graph g
12292 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
12294 * Implement with a hash table && a set of adjcency vectors.
12295 * The hash table supports constant time implementations of add and interfere.
12296 * The adjacency vectors support an efficient implementation of neighbors.
12300 * +---------------------------------------------------+
12301 * | +--------------+ |
12303 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
12305 * -- In simplify implment optimistic coloring... (No backtracking)
12306 * -- Implement Rematerialization it is the only form of spilling we can perform
12307 * Essentially this means dropping a constant from a register because
12308 * we can regenerate it later.
12310 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
12311 * coalesce at phi points...
12312 * --- Bias coloring if at all possible do the coalesing a compile time.
12317 static void different_colored(
12318 struct compile_state *state, struct reg_state *rstate,
12319 struct triple *parent, struct triple *ins)
12321 struct live_range *lr;
12322 struct triple **expr;
12323 lr = rstate->lrd[ins->id].lr;
12324 expr = triple_rhs(state, ins, 0);
12325 for(;expr; expr = triple_rhs(state, ins, expr)) {
12326 struct live_range *lr2;
12327 if (!*expr || (*expr == parent) || (*expr == ins)) {
12330 lr2 = rstate->lrd[(*expr)->id].lr;
12331 if (lr->color == lr2->color) {
12332 internal_error(state, ins, "live range too big");
12338 static struct live_range *coalesce_ranges(
12339 struct compile_state *state, struct reg_state *rstate,
12340 struct live_range *lr1, struct live_range *lr2)
12342 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
12348 if (!lr1->defs || !lr2->defs) {
12349 internal_error(state, 0,
12350 "cannot coalese dead live ranges");
12352 if ((lr1->color == REG_UNNEEDED) ||
12353 (lr2->color == REG_UNNEEDED)) {
12354 internal_error(state, 0,
12355 "cannot coalesce live ranges without a possible color");
12357 if ((lr1->color != lr2->color) &&
12358 (lr1->color != REG_UNSET) &&
12359 (lr2->color != REG_UNSET)) {
12360 internal_error(state, lr1->defs->def,
12361 "cannot coalesce live ranges of different colors");
12363 color = lr1->color;
12364 if (color == REG_UNSET) {
12365 color = lr2->color;
12367 classes = lr1->classes & lr2->classes;
12369 internal_error(state, lr1->defs->def,
12370 "cannot coalesce live ranges with dissimilar register classes");
12372 #if DEBUG_COALESCING
12373 fprintf(stderr, "coalescing:");
12376 fprintf(stderr, " %p", lrd->def);
12378 } while(lrd != lr1->defs);
12379 fprintf(stderr, " |");
12382 fprintf(stderr, " %p", lrd->def);
12384 } while(lrd != lr2->defs);
12385 fprintf(stderr, "\n");
12387 /* If there is a clear dominate live range put it in lr1,
12388 * For purposes of this test phi functions are
12389 * considered dominated by the definitions that feed into
12392 if ((lr1->defs->prev->def->op == OP_PHI) ||
12393 ((lr2->defs->prev->def->op != OP_PHI) &&
12394 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12395 struct live_range *tmp;
12401 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12402 fprintf(stderr, "lr1 post\n");
12404 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12405 fprintf(stderr, "lr1 pre\n");
12407 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12408 fprintf(stderr, "lr2 post\n");
12410 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12411 fprintf(stderr, "lr2 pre\n");
12415 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12422 /* Append lr2 onto lr1 */
12423 #warning "FIXME should this be a merge instead of a splice?"
12424 /* This FIXME item applies to the correctness of live_range_end
12425 * and to the necessity of making multiple passes of coalesce_live_ranges.
12426 * A failure to find some coalesce opportunities in coaleace_live_ranges
12427 * does not impact the correct of the compiler just the efficiency with
12428 * which registers are allocated.
12431 mid1 = lr1->defs->prev;
12433 end = lr2->defs->prev;
12441 /* Fixup the live range in the added live range defs */
12446 } while(lrd != head);
12448 /* Mark lr2 as free. */
12450 lr2->color = REG_UNNEEDED;
12454 internal_error(state, 0, "lr1->defs == 0 ?");
12457 lr1->color = color;
12458 lr1->classes = classes;
12460 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12461 transfer_live_edges(rstate, lr1, lr2);
12466 static struct live_range_def *live_range_head(
12467 struct compile_state *state, struct live_range *lr,
12468 struct live_range_def *last)
12470 struct live_range_def *result;
12475 else if (!tdominates(state, lr->defs->def, last->next->def)) {
12476 result = last->next;
12481 static struct live_range_def *live_range_end(
12482 struct compile_state *state, struct live_range *lr,
12483 struct live_range_def *last)
12485 struct live_range_def *result;
12488 result = lr->defs->prev;
12490 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12491 result = last->prev;
12497 static void initialize_live_ranges(
12498 struct compile_state *state, struct reg_state *rstate)
12500 struct triple *ins, *first;
12501 size_t count, size;
12504 first = RHS(state->main_function, 0);
12505 /* First count how many instructions I have.
12507 count = count_triples(state);
12508 /* Potentially I need one live range definitions for each
12511 rstate->defs = count;
12512 /* Potentially I need one live range for each instruction
12513 * plus an extra for the dummy live range.
12515 rstate->ranges = count + 1;
12516 size = sizeof(rstate->lrd[0]) * rstate->defs;
12517 rstate->lrd = xcmalloc(size, "live_range_def");
12518 size = sizeof(rstate->lr[0]) * rstate->ranges;
12519 rstate->lr = xcmalloc(size, "live_range");
12521 /* Setup the dummy live range */
12522 rstate->lr[0].classes = 0;
12523 rstate->lr[0].color = REG_UNSET;
12524 rstate->lr[0].defs = 0;
12528 /* If the triple is a variable give it a live range */
12529 if (triple_is_def(state, ins)) {
12530 struct reg_info info;
12531 /* Find the architecture specific color information */
12532 info = find_def_color(state, ins);
12534 rstate->lr[i].defs = &rstate->lrd[j];
12535 rstate->lr[i].color = info.reg;
12536 rstate->lr[i].classes = info.regcm;
12537 rstate->lr[i].degree = 0;
12538 rstate->lrd[j].lr = &rstate->lr[i];
12540 /* Otherwise give the triple the dummy live range. */
12542 rstate->lrd[j].lr = &rstate->lr[0];
12545 /* Initalize the live_range_def */
12546 rstate->lrd[j].next = &rstate->lrd[j];
12547 rstate->lrd[j].prev = &rstate->lrd[j];
12548 rstate->lrd[j].def = ins;
12549 rstate->lrd[j].orig_id = ins->id;
12554 } while(ins != first);
12555 rstate->ranges = i;
12557 /* Make a second pass to handle achitecture specific register
12562 int zlhs, zrhs, i, j;
12563 if (ins->id > rstate->defs) {
12564 internal_error(state, ins, "bad id");
12567 /* Walk through the template of ins and coalesce live ranges */
12568 zlhs = TRIPLE_LHS(ins->sizes);
12569 if ((zlhs == 0) && triple_is_def(state, ins)) {
12572 zrhs = TRIPLE_RHS(ins->sizes);
12574 #if DEBUG_COALESCING > 1
12575 fprintf(stderr, "mandatory coalesce: %p %d %d\n",
12578 for(i = 0; i < zlhs; i++) {
12579 struct reg_info linfo;
12580 struct live_range_def *lhs;
12581 linfo = arch_reg_lhs(state, ins, i);
12582 if (linfo.reg < MAX_REGISTERS) {
12585 if (triple_is_def(state, ins)) {
12586 lhs = &rstate->lrd[ins->id];
12588 lhs = &rstate->lrd[LHS(ins, i)->id];
12590 #if DEBUG_COALESCING > 1
12591 fprintf(stderr, "coalesce lhs(%d): %p %d\n",
12592 i, lhs, linfo.reg);
12595 for(j = 0; j < zrhs; j++) {
12596 struct reg_info rinfo;
12597 struct live_range_def *rhs;
12598 rinfo = arch_reg_rhs(state, ins, j);
12599 if (rinfo.reg < MAX_REGISTERS) {
12602 rhs = &rstate->lrd[RHS(ins, j)->id];
12603 #if DEBUG_COALESCING > 1
12604 fprintf(stderr, "coalesce rhs(%d): %p %d\n",
12605 j, rhs, rinfo.reg);
12608 if (rinfo.reg == linfo.reg) {
12609 coalesce_ranges(state, rstate,
12615 } while(ins != first);
12618 static void graph_ins(
12619 struct compile_state *state,
12620 struct reg_block *blocks, struct triple_reg_set *live,
12621 struct reg_block *rb, struct triple *ins, void *arg)
12623 struct reg_state *rstate = arg;
12624 struct live_range *def;
12625 struct triple_reg_set *entry;
12627 /* If the triple is not a definition
12628 * we do not have a definition to add to
12629 * the interference graph.
12631 if (!triple_is_def(state, ins)) {
12634 def = rstate->lrd[ins->id].lr;
12636 /* Create an edge between ins and everything that is
12637 * alive, unless the live_range cannot share
12638 * a physical register with ins.
12640 for(entry = live; entry; entry = entry->next) {
12641 struct live_range *lr;
12642 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12643 internal_error(state, 0, "bad entry?");
12645 lr = rstate->lrd[entry->member->id].lr;
12649 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12652 add_live_edge(rstate, def, lr);
12657 static struct live_range *get_verify_live_range(
12658 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12660 struct live_range *lr;
12661 struct live_range_def *lrd;
12663 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12664 internal_error(state, ins, "bad ins?");
12666 lr = rstate->lrd[ins->id].lr;
12670 if (lrd->def == ins) {
12674 } while(lrd != lr->defs);
12676 internal_error(state, ins, "ins not in live range");
12681 static void verify_graph_ins(
12682 struct compile_state *state,
12683 struct reg_block *blocks, struct triple_reg_set *live,
12684 struct reg_block *rb, struct triple *ins, void *arg)
12686 struct reg_state *rstate = arg;
12687 struct triple_reg_set *entry1, *entry2;
12690 /* Compare live against edges and make certain the code is working */
12691 for(entry1 = live; entry1; entry1 = entry1->next) {
12692 struct live_range *lr1;
12693 lr1 = get_verify_live_range(state, rstate, entry1->member);
12694 for(entry2 = live; entry2; entry2 = entry2->next) {
12695 struct live_range *lr2;
12696 struct live_range_edge *edge2;
12699 if (entry2 == entry1) {
12702 lr2 = get_verify_live_range(state, rstate, entry2->member);
12704 internal_error(state, entry2->member,
12705 "live range with 2 values simultaneously alive");
12707 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12710 if (!interfere(rstate, lr1, lr2)) {
12711 internal_error(state, entry2->member,
12712 "edges don't interfere?");
12717 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12719 if (edge2->node == lr1) {
12723 if (lr2_degree != lr2->degree) {
12724 internal_error(state, entry2->member,
12725 "computed degree: %d does not match reported degree: %d\n",
12726 lr2_degree, lr2->degree);
12729 internal_error(state, entry2->member, "missing edge");
12737 static void print_interference_ins(
12738 struct compile_state *state,
12739 struct reg_block *blocks, struct triple_reg_set *live,
12740 struct reg_block *rb, struct triple *ins, void *arg)
12742 struct reg_state *rstate = arg;
12743 struct live_range *lr;
12746 lr = rstate->lrd[ins->id].lr;
12748 ins->id = rstate->lrd[id].orig_id;
12749 SET_REG(ins->id, lr->color);
12750 display_triple(stdout, ins);
12754 struct live_range_def *lrd;
12758 printf(" %-10p", lrd->def);
12760 } while(lrd != lr->defs);
12764 struct triple_reg_set *entry;
12766 for(entry = live; entry; entry = entry->next) {
12767 printf(" %-10p", entry->member);
12772 struct live_range_edge *entry;
12774 for(entry = lr->edges; entry; entry = entry->next) {
12775 struct live_range_def *lrd;
12776 lrd = entry->node->defs;
12778 printf(" %-10p", lrd->def);
12780 } while(lrd != entry->node->defs);
12785 if (triple_is_branch(state, ins)) {
12791 static int coalesce_live_ranges(
12792 struct compile_state *state, struct reg_state *rstate)
12794 /* At the point where a value is moved from one
12795 * register to another that value requires two
12796 * registers, thus increasing register pressure.
12797 * Live range coaleescing reduces the register
12798 * pressure by keeping a value in one register
12801 * In the case of a phi function all paths leading
12802 * into it must be allocated to the same register
12803 * otherwise the phi function may not be removed.
12805 * Forcing a value to stay in a single register
12806 * for an extended period of time does have
12807 * limitations when applied to non homogenous
12810 * The two cases I have identified are:
12811 * 1) Two forced register assignments may
12813 * 2) Registers may go unused because they
12814 * are only good for storing the value
12815 * and not manipulating it.
12817 * Because of this I need to split live ranges,
12818 * even outside of the context of coalesced live
12819 * ranges. The need to split live ranges does
12820 * impose some constraints on live range coalescing.
12822 * - Live ranges may not be coalesced across phi
12823 * functions. This creates a 2 headed live
12824 * range that cannot be sanely split.
12826 * - phi functions (coalesced in initialize_live_ranges)
12827 * are handled as pre split live ranges so we will
12828 * never attempt to split them.
12834 for(i = 0; i <= rstate->ranges; i++) {
12835 struct live_range *lr1;
12836 struct live_range_def *lrd1;
12837 lr1 = &rstate->lr[i];
12841 lrd1 = live_range_end(state, lr1, 0);
12842 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12843 struct triple_set *set;
12844 if (lrd1->def->op != OP_COPY) {
12847 /* Skip copies that are the result of a live range split. */
12848 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12851 for(set = lrd1->def->use; set; set = set->next) {
12852 struct live_range_def *lrd2;
12853 struct live_range *lr2, *res;
12855 lrd2 = &rstate->lrd[set->member->id];
12857 /* Don't coalesce with instructions
12858 * that are the result of a live range
12861 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12864 lr2 = rstate->lrd[set->member->id].lr;
12868 if ((lr1->color != lr2->color) &&
12869 (lr1->color != REG_UNSET) &&
12870 (lr2->color != REG_UNSET)) {
12873 if ((lr1->classes & lr2->classes) == 0) {
12877 if (interfere(rstate, lr1, lr2)) {
12881 res = coalesce_ranges(state, rstate, lr1, lr2);
12895 static void fix_coalesce_conflicts(struct compile_state *state,
12896 struct reg_block *blocks, struct triple_reg_set *live,
12897 struct reg_block *rb, struct triple *ins, void *arg)
12899 int *conflicts = arg;
12900 int zlhs, zrhs, i, j;
12902 /* See if we have a mandatory coalesce operation between
12903 * a lhs and a rhs value. If so and the rhs value is also
12904 * alive then this triple needs to be pre copied. Otherwise
12905 * we would have two definitions in the same live range simultaneously
12908 zlhs = TRIPLE_LHS(ins->sizes);
12909 if ((zlhs == 0) && triple_is_def(state, ins)) {
12912 zrhs = TRIPLE_RHS(ins->sizes);
12913 for(i = 0; i < zlhs; i++) {
12914 struct reg_info linfo;
12915 linfo = arch_reg_lhs(state, ins, i);
12916 if (linfo.reg < MAX_REGISTERS) {
12919 for(j = 0; j < zrhs; j++) {
12920 struct reg_info rinfo;
12921 struct triple *rhs;
12922 struct triple_reg_set *set;
12925 rinfo = arch_reg_rhs(state, ins, j);
12926 if (rinfo.reg != linfo.reg) {
12930 for(set = live; set && !found; set = set->next) {
12931 if (set->member == rhs) {
12936 struct triple *copy;
12937 copy = pre_copy(state, ins, j);
12938 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12946 static int correct_coalesce_conflicts(
12947 struct compile_state *state, struct reg_block *blocks)
12951 walk_variable_lifetimes(state, blocks, fix_coalesce_conflicts, &conflicts);
12955 static void replace_set_use(struct compile_state *state,
12956 struct triple_reg_set *head, struct triple *orig, struct triple *new)
12958 struct triple_reg_set *set;
12959 for(set = head; set; set = set->next) {
12960 if (set->member == orig) {
12966 static void replace_block_use(struct compile_state *state,
12967 struct reg_block *blocks, struct triple *orig, struct triple *new)
12970 #warning "WISHLIST visit just those blocks that need it *"
12971 for(i = 1; i <= state->last_vertex; i++) {
12972 struct reg_block *rb;
12974 replace_set_use(state, rb->in, orig, new);
12975 replace_set_use(state, rb->out, orig, new);
12979 static void color_instructions(struct compile_state *state)
12981 struct triple *ins, *first;
12982 first = RHS(state->main_function, 0);
12985 if (triple_is_def(state, ins)) {
12986 struct reg_info info;
12987 info = find_lhs_color(state, ins, 0);
12988 if (info.reg >= MAX_REGISTERS) {
12989 info.reg = REG_UNSET;
12991 SET_INFO(ins->id, info);
12994 } while(ins != first);
12997 static struct reg_info read_lhs_color(
12998 struct compile_state *state, struct triple *ins, int index)
13000 struct reg_info info;
13001 if ((index == 0) && triple_is_def(state, ins)) {
13002 info.reg = ID_REG(ins->id);
13003 info.regcm = ID_REGCM(ins->id);
13005 else if (index < TRIPLE_LHS(ins->sizes)) {
13006 info = read_lhs_color(state, LHS(ins, index), 0);
13009 internal_error(state, ins, "Bad lhs %d", index);
13010 info.reg = REG_UNSET;
13016 static struct triple *resolve_tangle(
13017 struct compile_state *state, struct triple *tangle)
13019 struct reg_info info, uinfo;
13020 struct triple_set *set, *next;
13021 struct triple *copy;
13023 #warning "WISHLIST recalculate all affected instructions colors"
13024 info = find_lhs_color(state, tangle, 0);
13025 for(set = tangle->use; set; set = next) {
13026 struct triple *user;
13029 user = set->member;
13030 zrhs = TRIPLE_RHS(user->sizes);
13031 for(i = 0; i < zrhs; i++) {
13032 if (RHS(user, i) != tangle) {
13035 uinfo = find_rhs_post_color(state, user, i);
13036 if (uinfo.reg == info.reg) {
13037 copy = pre_copy(state, user, i);
13038 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13039 SET_INFO(copy->id, uinfo);
13044 uinfo = find_lhs_pre_color(state, tangle, 0);
13045 if (uinfo.reg == info.reg) {
13046 struct reg_info linfo;
13047 copy = post_copy(state, tangle);
13048 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13049 linfo = find_lhs_color(state, copy, 0);
13050 SET_INFO(copy->id, linfo);
13052 info = find_lhs_color(state, tangle, 0);
13053 SET_INFO(tangle->id, info);
13059 static void fix_tangles(struct compile_state *state,
13060 struct reg_block *blocks, struct triple_reg_set *live,
13061 struct reg_block *rb, struct triple *ins, void *arg)
13063 int *tangles = arg;
13064 struct triple *tangle;
13066 char used[MAX_REGISTERS];
13067 struct triple_reg_set *set;
13070 /* Find out which registers have multiple uses at this point */
13071 memset(used, 0, sizeof(used));
13072 for(set = live; set; set = set->next) {
13073 struct reg_info info;
13074 info = read_lhs_color(state, set->member, 0);
13075 if (info.reg == REG_UNSET) {
13078 reg_inc_used(state, used, info.reg);
13081 /* Now find the least dominated definition of a register in
13082 * conflict I have seen so far.
13084 for(set = live; set; set = set->next) {
13085 struct reg_info info;
13086 info = read_lhs_color(state, set->member, 0);
13087 if (used[info.reg] < 2) {
13090 /* Changing copies that feed into phi functions
13093 if (set->member->use &&
13094 (set->member->use->member->op == OP_PHI)) {
13097 if (!tangle || tdominates(state, set->member, tangle)) {
13098 tangle = set->member;
13101 /* If I have found a tangle resolve it */
13103 struct triple *post_copy;
13105 post_copy = resolve_tangle(state, tangle);
13107 replace_block_use(state, blocks, tangle, post_copy);
13109 if (post_copy && (tangle != ins)) {
13110 replace_set_use(state, live, tangle, post_copy);
13117 static int correct_tangles(
13118 struct compile_state *state, struct reg_block *blocks)
13122 color_instructions(state);
13123 walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
13128 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
13129 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
13131 struct triple *find_constrained_def(
13132 struct compile_state *state, struct live_range *range, struct triple *constrained)
13134 struct live_range_def *lrd;
13137 struct reg_info info;
13139 int is_constrained;
13140 regcm = arch_type_to_regcm(state, lrd->def->type);
13141 info = find_lhs_color(state, lrd->def, 0);
13142 regcm = arch_regcm_reg_normalize(state, regcm);
13143 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
13144 /* If the 2 register class masks are not equal the
13145 * the current register class is constrained.
13147 is_constrained = regcm != info.regcm;
13149 /* Of the constrained live ranges deal with the
13150 * least dominated one first.
13152 if (is_constrained) {
13153 #if DEBUG_RANGE_CONFLICTS
13154 fprintf(stderr, "canidate: %p %-8s regcm: %x %x\n",
13155 lrd->def, tops(lrd->def->op), regcm, info.regcm);
13157 if (!constrained ||
13158 tdominates(state, lrd->def, constrained))
13160 constrained = lrd->def;
13164 } while(lrd != range->defs);
13165 return constrained;
13168 static int split_constrained_ranges(
13169 struct compile_state *state, struct reg_state *rstate,
13170 struct live_range *range)
13172 /* Walk through the edges in conflict and our current live
13173 * range, and find definitions that are more severly constrained
13174 * than they type of data they contain require.
13176 * Then pick one of those ranges and relax the constraints.
13178 struct live_range_edge *edge;
13179 struct triple *constrained;
13182 for(edge = range->edges; edge; edge = edge->next) {
13183 constrained = find_constrained_def(state, edge->node, constrained);
13185 if (!constrained) {
13186 constrained = find_constrained_def(state, range, constrained);
13188 #if DEBUG_RANGE_CONFLICTS
13189 fprintf(stderr, "constrained: %p %-8s\n",
13190 constrained, tops(constrained->op));
13193 ids_from_rstate(state, rstate);
13194 cleanup_rstate(state, rstate);
13195 resolve_tangle(state, constrained);
13197 return !!constrained;
13200 static int split_ranges(
13201 struct compile_state *state, struct reg_state *rstate,
13202 char *used, struct live_range *range)
13205 #if DEBUG_RANGE_CONFLICTS
13206 fprintf(stderr, "split_ranges %d %s %p\n",
13207 rstate->passes, tops(range->defs->def->op), range->defs->def);
13209 if ((range->color == REG_UNNEEDED) ||
13210 (rstate->passes >= rstate->max_passes)) {
13213 split = split_constrained_ranges(state, rstate, range);
13215 /* Ideally I would split the live range that will not be used
13216 * for the longest period of time in hopes that this will
13217 * (a) allow me to spill a register or
13218 * (b) allow me to place a value in another register.
13220 * So far I don't have a test case for this, the resolving
13221 * of mandatory constraints has solved all of my
13222 * know issues. So I have choosen not to write any
13223 * code until I cat get a better feel for cases where
13224 * it would be useful to have.
13227 #warning "WISHLIST implement live range splitting..."
13228 if ((DEBUG_RANGE_CONFLICTS > 1) &&
13229 (!split || (DEBUG_RANGE_CONFLICTS > 2))) {
13230 print_interference_blocks(state, rstate, stderr, 0);
13231 print_dominators(state, stderr);
13236 #if DEBUG_COLOR_GRAPH > 1
13237 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13238 #define cgdebug_flush() fflush(stdout)
13239 #define cgdebug_loc(STATE, TRIPLE) loc(stdout, STATE, TRIPLE)
13240 #elif DEBUG_COLOR_GRAPH == 1
13241 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13242 #define cgdebug_flush() fflush(stderr)
13243 #define cgdebug_loc(STATE, TRIPLE) loc(stderr, STATE, TRIPLE)
13245 #define cgdebug_printf(...)
13246 #define cgdebug_flush()
13247 #define cgdebug_loc(STATE, TRIPLE)
13251 static int select_free_color(struct compile_state *state,
13252 struct reg_state *rstate, struct live_range *range)
13254 struct triple_set *entry;
13255 struct live_range_def *lrd;
13256 struct live_range_def *phi;
13257 struct live_range_edge *edge;
13258 char used[MAX_REGISTERS];
13259 struct triple **expr;
13261 /* Instead of doing just the trivial color select here I try
13262 * a few extra things because a good color selection will help reduce
13266 /* Find the registers currently in use */
13267 memset(used, 0, sizeof(used));
13268 for(edge = range->edges; edge; edge = edge->next) {
13269 if (edge->node->color == REG_UNSET) {
13272 reg_fill_used(state, used, edge->node->color);
13274 #if DEBUG_COLOR_GRAPH > 1
13278 for(edge = range->edges; edge; edge = edge->next) {
13281 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
13282 tops(range->def->op), i,
13283 range->def->filename, range->def->line, range->def->col);
13284 for(i = 0; i < MAX_REGISTERS; i++) {
13286 cgdebug_printf("used: %s\n",
13293 /* If a color is already assigned see if it will work */
13294 if (range->color != REG_UNSET) {
13295 struct live_range_def *lrd;
13296 if (!used[range->color]) {
13299 for(edge = range->edges; edge; edge = edge->next) {
13300 if (edge->node->color != range->color) {
13303 warning(state, edge->node->defs->def, "edge: ");
13304 lrd = edge->node->defs;
13306 warning(state, lrd->def, " %p %s",
13307 lrd->def, tops(lrd->def->op));
13309 } while(lrd != edge->node->defs);
13312 warning(state, range->defs->def, "def: ");
13314 warning(state, lrd->def, " %p %s",
13315 lrd->def, tops(lrd->def->op));
13317 } while(lrd != range->defs);
13318 internal_error(state, range->defs->def,
13319 "live range with already used color %s",
13320 arch_reg_str(range->color));
13323 /* If I feed into an expression reuse it's color.
13324 * This should help remove copies in the case of 2 register instructions
13325 * and phi functions.
13328 lrd = live_range_end(state, range, 0);
13329 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13330 entry = lrd->def->use;
13331 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13332 struct live_range_def *insd;
13334 insd = &rstate->lrd[entry->member->id];
13335 if (insd->lr->defs == 0) {
13338 if (!phi && (insd->def->op == OP_PHI) &&
13339 !interfere(rstate, range, insd->lr)) {
13342 if (insd->lr->color == REG_UNSET) {
13345 regcm = insd->lr->classes;
13346 if (((regcm & range->classes) == 0) ||
13347 (used[insd->lr->color])) {
13350 if (interfere(rstate, range, insd->lr)) {
13353 range->color = insd->lr->color;
13356 /* If I feed into a phi function reuse it's color or the color
13357 * of something else that feeds into the phi function.
13360 if (phi->lr->color != REG_UNSET) {
13361 if (used[phi->lr->color]) {
13362 range->color = phi->lr->color;
13366 expr = triple_rhs(state, phi->def, 0);
13367 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13368 struct live_range *lr;
13373 lr = rstate->lrd[(*expr)->id].lr;
13374 if (lr->color == REG_UNSET) {
13377 regcm = lr->classes;
13378 if (((regcm & range->classes) == 0) ||
13379 (used[lr->color])) {
13382 if (interfere(rstate, range, lr)) {
13385 range->color = lr->color;
13389 /* If I don't interfere with a rhs node reuse it's color */
13390 lrd = live_range_head(state, range, 0);
13391 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13392 expr = triple_rhs(state, lrd->def, 0);
13393 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13394 struct live_range *lr;
13399 lr = rstate->lrd[(*expr)->id].lr;
13400 if (lr->color == REG_UNSET) {
13403 regcm = lr->classes;
13404 if (((regcm & range->classes) == 0) ||
13405 (used[lr->color])) {
13408 if (interfere(rstate, range, lr)) {
13411 range->color = lr->color;
13415 /* If I have not opportunitically picked a useful color
13416 * pick the first color that is free.
13418 if (range->color == REG_UNSET) {
13420 arch_select_free_register(state, used, range->classes);
13422 if (range->color == REG_UNSET) {
13423 struct live_range_def *lrd;
13425 if (split_ranges(state, rstate, used, range)) {
13428 for(edge = range->edges; edge; edge = edge->next) {
13429 warning(state, edge->node->defs->def, "edge reg %s",
13430 arch_reg_str(edge->node->color));
13431 lrd = edge->node->defs;
13433 warning(state, lrd->def, " %s %p",
13434 tops(lrd->def->op), lrd->def);
13436 } while(lrd != edge->node->defs);
13438 warning(state, range->defs->def, "range: ");
13441 warning(state, lrd->def, " %s %p",
13442 tops(lrd->def->op), lrd->def);
13444 } while(lrd != range->defs);
13446 warning(state, range->defs->def, "classes: %x",
13448 for(i = 0; i < MAX_REGISTERS; i++) {
13450 warning(state, range->defs->def, "used: %s",
13454 #if DEBUG_COLOR_GRAPH < 2
13455 error(state, range->defs->def, "too few registers");
13457 internal_error(state, range->defs->def, "too few registers");
13460 range->classes &= arch_reg_regcm(state, range->color);
13461 if ((range->color == REG_UNSET) || (range->classes == 0)) {
13462 internal_error(state, range->defs->def, "select_free_color did not?");
13467 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13470 struct live_range_edge *edge;
13471 struct live_range *range;
13473 cgdebug_printf("Lo: ");
13474 range = rstate->low;
13475 if (*range->group_prev != range) {
13476 internal_error(state, 0, "lo: *prev != range?");
13478 *range->group_prev = range->group_next;
13479 if (range->group_next) {
13480 range->group_next->group_prev = range->group_prev;
13482 if (&range->group_next == rstate->low_tail) {
13483 rstate->low_tail = range->group_prev;
13485 if (rstate->low == range) {
13486 internal_error(state, 0, "low: next != prev?");
13489 else if (rstate->high) {
13490 cgdebug_printf("Hi: ");
13491 range = rstate->high;
13492 if (*range->group_prev != range) {
13493 internal_error(state, 0, "hi: *prev != range?");
13495 *range->group_prev = range->group_next;
13496 if (range->group_next) {
13497 range->group_next->group_prev = range->group_prev;
13499 if (&range->group_next == rstate->high_tail) {
13500 rstate->high_tail = range->group_prev;
13502 if (rstate->high == range) {
13503 internal_error(state, 0, "high: next != prev?");
13509 cgdebug_printf(" %d\n", range - rstate->lr);
13510 range->group_prev = 0;
13511 for(edge = range->edges; edge; edge = edge->next) {
13512 struct live_range *node;
13514 /* Move nodes from the high to the low list */
13515 if (node->group_prev && (node->color == REG_UNSET) &&
13516 (node->degree == regc_max_size(state, node->classes))) {
13517 if (*node->group_prev != node) {
13518 internal_error(state, 0, "move: *prev != node?");
13520 *node->group_prev = node->group_next;
13521 if (node->group_next) {
13522 node->group_next->group_prev = node->group_prev;
13524 if (&node->group_next == rstate->high_tail) {
13525 rstate->high_tail = node->group_prev;
13527 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13528 node->group_prev = rstate->low_tail;
13529 node->group_next = 0;
13530 *rstate->low_tail = node;
13531 rstate->low_tail = &node->group_next;
13532 if (*node->group_prev != node) {
13533 internal_error(state, 0, "move2: *prev != node?");
13538 colored = color_graph(state, rstate);
13540 cgdebug_printf("Coloring %d @", range - rstate->lr);
13541 cgdebug_loc(state, range->defs->def);
13543 colored = select_free_color(state, rstate, range);
13544 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13549 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13551 struct live_range *lr;
13552 struct live_range_edge *edge;
13553 struct triple *ins, *first;
13554 char used[MAX_REGISTERS];
13555 first = RHS(state->main_function, 0);
13558 if (triple_is_def(state, ins)) {
13559 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13560 internal_error(state, ins,
13561 "triple without a live range def");
13563 lr = rstate->lrd[ins->id].lr;
13564 if (lr->color == REG_UNSET) {
13565 internal_error(state, ins,
13566 "triple without a color");
13568 /* Find the registers used by the edges */
13569 memset(used, 0, sizeof(used));
13570 for(edge = lr->edges; edge; edge = edge->next) {
13571 if (edge->node->color == REG_UNSET) {
13572 internal_error(state, 0,
13573 "live range without a color");
13575 reg_fill_used(state, used, edge->node->color);
13577 if (used[lr->color]) {
13578 internal_error(state, ins,
13579 "triple with already used color");
13583 } while(ins != first);
13586 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13588 struct live_range *lr;
13589 struct triple *first, *ins;
13590 first = RHS(state->main_function, 0);
13593 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13594 internal_error(state, ins,
13595 "triple without a live range");
13597 lr = rstate->lrd[ins->id].lr;
13598 SET_REG(ins->id, lr->color);
13600 } while (ins != first);
13603 static struct live_range *merge_sort_lr(
13604 struct live_range *first, struct live_range *last)
13606 struct live_range *mid, *join, **join_tail, *pick;
13608 size = (last - first) + 1;
13610 mid = first + size/2;
13611 first = merge_sort_lr(first, mid -1);
13612 mid = merge_sort_lr(mid, last);
13616 /* merge the two lists */
13617 while(first && mid) {
13618 if ((first->degree < mid->degree) ||
13619 ((first->degree == mid->degree) &&
13620 (first->length < mid->length))) {
13622 first = first->group_next;
13624 first->group_prev = 0;
13629 mid = mid->group_next;
13631 mid->group_prev = 0;
13634 pick->group_next = 0;
13635 pick->group_prev = join_tail;
13637 join_tail = &pick->group_next;
13639 /* Splice the remaining list */
13640 pick = (first)? first : mid;
13643 pick->group_prev = join_tail;
13647 if (!first->defs) {
13655 static void ids_from_rstate(struct compile_state *state,
13656 struct reg_state *rstate)
13658 struct triple *ins, *first;
13659 if (!rstate->defs) {
13662 /* Display the graph if desired */
13663 if (state->debug & DEBUG_INTERFERENCE) {
13664 print_blocks(state, stdout);
13665 print_control_flow(state);
13667 first = RHS(state->main_function, 0);
13671 struct live_range_def *lrd;
13672 lrd = &rstate->lrd[ins->id];
13673 ins->id = lrd->orig_id;
13676 } while(ins != first);
13679 static void cleanup_live_edges(struct reg_state *rstate)
13682 /* Free the edges on each node */
13683 for(i = 1; i <= rstate->ranges; i++) {
13684 remove_live_edges(rstate, &rstate->lr[i]);
13688 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13690 cleanup_live_edges(rstate);
13691 xfree(rstate->lrd);
13694 /* Free the variable lifetime information */
13695 if (rstate->blocks) {
13696 free_variable_lifetimes(state, rstate->blocks);
13699 rstate->ranges = 0;
13702 rstate->blocks = 0;
13705 static void verify_consistency(struct compile_state *state);
13706 static void allocate_registers(struct compile_state *state)
13708 struct reg_state rstate;
13711 /* Clear out the reg_state */
13712 memset(&rstate, 0, sizeof(rstate));
13713 rstate.max_passes = MAX_ALLOCATION_PASSES;
13716 struct live_range **point, **next;
13721 #if DEBUG_RANGE_CONFLICTS
13722 fprintf(stderr, "pass: %d\n", rstate.passes);
13726 ids_from_rstate(state, &rstate);
13728 /* Cleanup the temporary data structures */
13729 cleanup_rstate(state, &rstate);
13731 /* Compute the variable lifetimes */
13732 rstate.blocks = compute_variable_lifetimes(state);
13734 /* Fix invalid mandatory live range coalesce conflicts */
13735 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
13737 /* Fix two simultaneous uses of the same register.
13738 * In a few pathlogical cases a partial untangle moves
13739 * the tangle to a part of the graph we won't revisit.
13740 * So we keep looping until we have no more tangle fixes
13744 tangles = correct_tangles(state, rstate.blocks);
13747 if (state->debug & DEBUG_INSERTED_COPIES) {
13748 printf("After resolve_tangles\n");
13749 print_blocks(state, stdout);
13750 print_control_flow(state);
13752 verify_consistency(state);
13754 /* Allocate and initialize the live ranges */
13755 initialize_live_ranges(state, &rstate);
13757 /* Note current doing coalescing in a loop appears to
13758 * buys me nothing. The code is left this way in case
13759 * there is some value in it. Or if a future bugfix
13760 * yields some benefit.
13763 #if DEBUG_COALESCING
13764 fprintf(stderr, "coalescing\n");
13766 /* Remove any previous live edge calculations */
13767 cleanup_live_edges(&rstate);
13769 /* Compute the interference graph */
13770 walk_variable_lifetimes(
13771 state, rstate.blocks, graph_ins, &rstate);
13773 /* Display the interference graph if desired */
13774 if (state->debug & DEBUG_INTERFERENCE) {
13775 print_interference_blocks(state, &rstate, stdout, 1);
13776 printf("\nlive variables by instruction\n");
13777 walk_variable_lifetimes(
13778 state, rstate.blocks,
13779 print_interference_ins, &rstate);
13782 coalesced = coalesce_live_ranges(state, &rstate);
13784 #if DEBUG_COALESCING
13785 fprintf(stderr, "coalesced: %d\n", coalesced);
13787 } while(coalesced);
13789 #if DEBUG_CONSISTENCY > 1
13791 fprintf(stderr, "verify_graph_ins...\n");
13793 /* Verify the interference graph */
13794 walk_variable_lifetimes(
13795 state, rstate.blocks, verify_graph_ins, &rstate);
13797 fprintf(stderr, "verify_graph_ins done\n");
13801 /* Build the groups low and high. But with the nodes
13802 * first sorted by degree order.
13804 rstate.low_tail = &rstate.low;
13805 rstate.high_tail = &rstate.high;
13806 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13808 rstate.high->group_prev = &rstate.high;
13810 for(point = &rstate.high; *point; point = &(*point)->group_next)
13812 rstate.high_tail = point;
13813 /* Walk through the high list and move everything that needs
13816 for(point = &rstate.high; *point; point = next) {
13817 struct live_range *range;
13818 next = &(*point)->group_next;
13821 /* If it has a low degree or it already has a color
13822 * place the node in low.
13824 if ((range->degree < regc_max_size(state, range->classes)) ||
13825 (range->color != REG_UNSET)) {
13826 cgdebug_printf("Lo: %5d degree %5d%s\n",
13827 range - rstate.lr, range->degree,
13828 (range->color != REG_UNSET) ? " (colored)": "");
13829 *range->group_prev = range->group_next;
13830 if (range->group_next) {
13831 range->group_next->group_prev = range->group_prev;
13833 if (&range->group_next == rstate.high_tail) {
13834 rstate.high_tail = range->group_prev;
13836 range->group_prev = rstate.low_tail;
13837 range->group_next = 0;
13838 *rstate.low_tail = range;
13839 rstate.low_tail = &range->group_next;
13843 cgdebug_printf("hi: %5d degree %5d%s\n",
13844 range - rstate.lr, range->degree,
13845 (range->color != REG_UNSET) ? " (colored)": "");
13848 /* Color the live_ranges */
13849 colored = color_graph(state, &rstate);
13851 } while (!colored);
13853 /* Verify the graph was properly colored */
13854 verify_colors(state, &rstate);
13856 /* Move the colors from the graph to the triples */
13857 color_triples(state, &rstate);
13859 /* Cleanup the temporary data structures */
13860 cleanup_rstate(state, &rstate);
13863 /* Sparce Conditional Constant Propogation
13864 * =========================================
13868 struct lattice_node {
13870 struct triple *def;
13871 struct ssa_edge *out;
13872 struct flow_block *fblock;
13873 struct triple *val;
13874 /* lattice high val && !is_const(val)
13875 * lattice const is_const(val)
13876 * lattice low val == 0
13880 struct lattice_node *src;
13881 struct lattice_node *dst;
13882 struct ssa_edge *work_next;
13883 struct ssa_edge *work_prev;
13884 struct ssa_edge *out_next;
13887 struct flow_block *src;
13888 struct flow_block *dst;
13889 struct flow_edge *work_next;
13890 struct flow_edge *work_prev;
13891 struct flow_edge *in_next;
13892 struct flow_edge *out_next;
13895 struct flow_block {
13896 struct block *block;
13897 struct flow_edge *in;
13898 struct flow_edge *out;
13899 struct flow_edge left, right;
13904 struct lattice_node *lattice;
13905 struct ssa_edge *ssa_edges;
13906 struct flow_block *flow_blocks;
13907 struct flow_edge *flow_work_list;
13908 struct ssa_edge *ssa_work_list;
13912 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13913 struct flow_edge *fedge)
13915 if (!scc->flow_work_list) {
13916 scc->flow_work_list = fedge;
13917 fedge->work_next = fedge->work_prev = fedge;
13920 struct flow_edge *ftail;
13921 ftail = scc->flow_work_list->work_prev;
13922 fedge->work_next = ftail->work_next;
13923 fedge->work_prev = ftail;
13924 fedge->work_next->work_prev = fedge;
13925 fedge->work_prev->work_next = fedge;
13929 static struct flow_edge *scc_next_fedge(
13930 struct compile_state *state, struct scc_state *scc)
13932 struct flow_edge *fedge;
13933 fedge = scc->flow_work_list;
13935 fedge->work_next->work_prev = fedge->work_prev;
13936 fedge->work_prev->work_next = fedge->work_next;
13937 if (fedge->work_next != fedge) {
13938 scc->flow_work_list = fedge->work_next;
13940 scc->flow_work_list = 0;
13946 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13947 struct ssa_edge *sedge)
13949 if (!scc->ssa_work_list) {
13950 scc->ssa_work_list = sedge;
13951 sedge->work_next = sedge->work_prev = sedge;
13954 struct ssa_edge *stail;
13955 stail = scc->ssa_work_list->work_prev;
13956 sedge->work_next = stail->work_next;
13957 sedge->work_prev = stail;
13958 sedge->work_next->work_prev = sedge;
13959 sedge->work_prev->work_next = sedge;
13963 static struct ssa_edge *scc_next_sedge(
13964 struct compile_state *state, struct scc_state *scc)
13966 struct ssa_edge *sedge;
13967 sedge = scc->ssa_work_list;
13969 sedge->work_next->work_prev = sedge->work_prev;
13970 sedge->work_prev->work_next = sedge->work_next;
13971 if (sedge->work_next != sedge) {
13972 scc->ssa_work_list = sedge->work_next;
13974 scc->ssa_work_list = 0;
13980 static void initialize_scc_state(
13981 struct compile_state *state, struct scc_state *scc)
13983 int ins_count, ssa_edge_count;
13984 int ins_index, ssa_edge_index, fblock_index;
13985 struct triple *first, *ins;
13986 struct block *block;
13987 struct flow_block *fblock;
13989 memset(scc, 0, sizeof(*scc));
13991 /* Inialize pass zero find out how much memory we need */
13992 first = RHS(state->main_function, 0);
13994 ins_count = ssa_edge_count = 0;
13996 struct triple_set *edge;
13998 for(edge = ins->use; edge; edge = edge->next) {
14002 } while(ins != first);
14004 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
14005 ins_count, ssa_edge_count, state->last_vertex);
14007 scc->ins_count = ins_count;
14009 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
14011 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
14013 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
14016 /* Initialize pass one collect up the nodes */
14019 ins_index = ssa_edge_index = fblock_index = 0;
14022 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14023 block = ins->u.block;
14025 internal_error(state, ins, "label without block");
14028 block->vertex = fblock_index;
14029 fblock = &scc->flow_blocks[fblock_index];
14030 fblock->block = block;
14033 struct lattice_node *lnode;
14035 lnode = &scc->lattice[ins_index];
14038 lnode->fblock = fblock;
14039 lnode->val = ins; /* LATTICE HIGH */
14040 lnode->old_id = ins->id;
14041 ins->id = ins_index;
14044 } while(ins != first);
14045 /* Initialize pass two collect up the edges */
14050 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14051 struct flow_edge *fedge, **ftail;
14052 struct block_set *bedge;
14053 block = ins->u.block;
14054 fblock = &scc->flow_blocks[block->vertex];
14057 ftail = &fblock->out;
14059 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
14060 if (fblock->left.dst->block != block->left) {
14061 internal_error(state, 0, "block mismatch");
14063 fblock->left.out_next = 0;
14064 *ftail = &fblock->left;
14065 ftail = &fblock->left.out_next;
14067 if (block->right) {
14068 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
14069 if (fblock->right.dst->block != block->right) {
14070 internal_error(state, 0, "block mismatch");
14072 fblock->right.out_next = 0;
14073 *ftail = &fblock->right;
14074 ftail = &fblock->right.out_next;
14076 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
14077 fedge->src = fblock;
14078 fedge->work_next = fedge->work_prev = fedge;
14079 fedge->executable = 0;
14081 ftail = &fblock->in;
14082 for(bedge = block->use; bedge; bedge = bedge->next) {
14083 struct block *src_block;
14084 struct flow_block *sfblock;
14085 struct flow_edge *sfedge;
14086 src_block = bedge->member;
14087 sfblock = &scc->flow_blocks[src_block->vertex];
14089 if (src_block->left == block) {
14090 sfedge = &sfblock->left;
14092 sfedge = &sfblock->right;
14095 ftail = &sfedge->in_next;
14096 sfedge->in_next = 0;
14100 struct triple_set *edge;
14101 struct ssa_edge **stail;
14102 struct lattice_node *lnode;
14103 lnode = &scc->lattice[ins->id];
14105 stail = &lnode->out;
14106 for(edge = ins->use; edge; edge = edge->next) {
14107 struct ssa_edge *sedge;
14108 ssa_edge_index += 1;
14109 sedge = &scc->ssa_edges[ssa_edge_index];
14111 stail = &sedge->out_next;
14112 sedge->src = lnode;
14113 sedge->dst = &scc->lattice[edge->member->id];
14114 sedge->work_next = sedge->work_prev = sedge;
14115 sedge->out_next = 0;
14119 } while(ins != first);
14120 /* Setup a dummy block 0 as a node above the start node */
14122 struct flow_block *fblock, *dst;
14123 struct flow_edge *fedge;
14124 fblock = &scc->flow_blocks[0];
14127 fblock->out = &fblock->left;
14128 dst = &scc->flow_blocks[state->first_block->vertex];
14129 fedge = &fblock->left;
14130 fedge->src = fblock;
14132 fedge->work_next = fedge;
14133 fedge->work_prev = fedge;
14134 fedge->in_next = fedge->dst->in;
14135 fedge->out_next = 0;
14136 fedge->executable = 0;
14137 fedge->dst->in = fedge;
14139 /* Initialize the work lists */
14140 scc->flow_work_list = 0;
14141 scc->ssa_work_list = 0;
14142 scc_add_fedge(state, scc, fedge);
14145 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14146 ins_index, ssa_edge_index, fblock_index);
14151 static void free_scc_state(
14152 struct compile_state *state, struct scc_state *scc)
14154 xfree(scc->flow_blocks);
14155 xfree(scc->ssa_edges);
14156 xfree(scc->lattice);
14160 static struct lattice_node *triple_to_lattice(
14161 struct compile_state *state, struct scc_state *scc, struct triple *ins)
14163 if (ins->id <= 0) {
14164 internal_error(state, ins, "bad id");
14166 return &scc->lattice[ins->id];
14169 static struct triple *preserve_lval(
14170 struct compile_state *state, struct lattice_node *lnode)
14172 struct triple *old;
14173 /* Preserve the original value */
14175 old = dup_triple(state, lnode->val);
14176 if (lnode->val != lnode->def) {
14186 static int lval_changed(struct compile_state *state,
14187 struct triple *old, struct lattice_node *lnode)
14190 /* See if the lattice value has changed */
14192 if (!old && !lnode->val) {
14195 if (changed && lnode->val && !is_const(lnode->val)) {
14199 lnode->val && old &&
14200 (memcmp(lnode->val->param, old->param,
14201 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14202 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14212 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
14213 struct lattice_node *lnode)
14215 struct lattice_node *tmp;
14216 struct triple **slot, *old;
14217 struct flow_edge *fedge;
14219 if (lnode->def->op != OP_PHI) {
14220 internal_error(state, lnode->def, "not phi");
14222 /* Store the original value */
14223 old = preserve_lval(state, lnode);
14225 /* default to lattice high */
14226 lnode->val = lnode->def;
14227 slot = &RHS(lnode->def, 0);
14229 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14230 if (!fedge->executable) {
14233 if (!slot[index]) {
14234 internal_error(state, lnode->def, "no phi value");
14236 tmp = triple_to_lattice(state, scc, slot[index]);
14237 /* meet(X, lattice low) = lattice low */
14241 /* meet(X, lattice high) = X */
14242 else if (!tmp->val) {
14243 lnode->val = lnode->val;
14245 /* meet(lattice high, X) = X */
14246 else if (!is_const(lnode->val)) {
14247 lnode->val = dup_triple(state, tmp->val);
14248 lnode->val->type = lnode->def->type;
14250 /* meet(const, const) = const or lattice low */
14251 else if (!constants_equal(state, lnode->val, tmp->val)) {
14259 fprintf(stderr, "phi: %d -> %s\n",
14261 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14263 /* If the lattice value has changed update the work lists. */
14264 if (lval_changed(state, old, lnode)) {
14265 struct ssa_edge *sedge;
14266 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14267 scc_add_sedge(state, scc, sedge);
14272 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14273 struct lattice_node *lnode)
14276 struct triple *old, *scratch;
14277 struct triple **dexpr, **vexpr;
14280 /* Store the original value */
14281 old = preserve_lval(state, lnode);
14283 /* Reinitialize the value */
14284 lnode->val = scratch = dup_triple(state, lnode->def);
14285 scratch->id = lnode->old_id;
14286 scratch->next = scratch;
14287 scratch->prev = scratch;
14290 count = TRIPLE_SIZE(scratch->sizes);
14291 for(i = 0; i < count; i++) {
14292 dexpr = &lnode->def->param[i];
14293 vexpr = &scratch->param[i];
14295 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14296 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14298 struct lattice_node *tmp;
14299 tmp = triple_to_lattice(state, scc, *dexpr);
14300 *vexpr = (tmp->val)? tmp->val : tmp->def;
14303 if (scratch->op == OP_BRANCH) {
14304 scratch->next = lnode->def->next;
14306 /* Recompute the value */
14307 #warning "FIXME see if simplify does anything bad"
14308 /* So far it looks like only the strength reduction
14309 * optimization are things I need to worry about.
14311 simplify(state, scratch);
14312 /* Cleanup my value */
14313 if (scratch->use) {
14314 internal_error(state, lnode->def, "scratch used?");
14316 if ((scratch->prev != scratch) ||
14317 ((scratch->next != scratch) &&
14318 ((lnode->def->op != OP_BRANCH) ||
14319 (scratch->next != lnode->def->next)))) {
14320 internal_error(state, lnode->def, "scratch in list?");
14322 /* undo any uses... */
14323 count = TRIPLE_SIZE(scratch->sizes);
14324 for(i = 0; i < count; i++) {
14325 vexpr = &scratch->param[i];
14327 unuse_triple(*vexpr, scratch);
14330 if (!is_const(scratch)) {
14331 for(i = 0; i < count; i++) {
14332 dexpr = &lnode->def->param[i];
14333 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14334 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14336 struct lattice_node *tmp;
14337 tmp = triple_to_lattice(state, scc, *dexpr);
14345 (lnode->val->op == lnode->def->op) &&
14346 (memcmp(lnode->val->param, lnode->def->param,
14347 count * sizeof(lnode->val->param[0])) == 0) &&
14348 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14349 lnode->val = lnode->def;
14351 /* Find the cases that are always lattice lo */
14353 triple_is_def(state, lnode->val) &&
14354 !triple_is_pure(state, lnode->val)) {
14358 (lnode->val->op == OP_SDECL) &&
14359 (lnode->val != lnode->def)) {
14360 internal_error(state, lnode->def, "bad sdecl");
14362 /* See if the lattice value has changed */
14363 changed = lval_changed(state, old, lnode);
14364 if (lnode->val != scratch) {
14370 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14371 struct lattice_node *lnode)
14373 struct lattice_node *cond;
14376 struct flow_edge *fedge;
14377 fprintf(stderr, "branch: %d (",
14380 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14381 fprintf(stderr, " %d", fedge->dst->block->vertex);
14383 fprintf(stderr, " )");
14384 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14385 fprintf(stderr, " <- %d",
14386 RHS(lnode->def, 0)->id);
14388 fprintf(stderr, "\n");
14391 if (lnode->def->op != OP_BRANCH) {
14392 internal_error(state, lnode->def, "not branch");
14394 /* This only applies to conditional branches */
14395 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14398 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14399 if (cond->val && !is_const(cond->val)) {
14400 #warning "FIXME do I need to do something here?"
14401 warning(state, cond->def, "condition not constant?");
14404 if (cond->val == 0) {
14405 scc_add_fedge(state, scc, cond->fblock->out);
14406 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14408 else if (cond->val->u.cval) {
14409 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14412 scc_add_fedge(state, scc, cond->fblock->out);
14417 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14418 struct lattice_node *lnode)
14422 changed = compute_lnode_val(state, scc, lnode);
14425 struct triple **expr;
14426 fprintf(stderr, "expr: %3d %10s (",
14427 lnode->def->id, tops(lnode->def->op));
14428 expr = triple_rhs(state, lnode->def, 0);
14429 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14431 fprintf(stderr, " %d", (*expr)->id);
14434 fprintf(stderr, " ) -> %s\n",
14435 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14438 if (lnode->def->op == OP_BRANCH) {
14439 scc_visit_branch(state, scc, lnode);
14442 else if (changed) {
14443 struct ssa_edge *sedge;
14444 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14445 scc_add_sedge(state, scc, sedge);
14450 static void scc_writeback_values(
14451 struct compile_state *state, struct scc_state *scc)
14453 struct triple *first, *ins;
14454 first = RHS(state->main_function, 0);
14457 struct lattice_node *lnode;
14458 lnode = triple_to_lattice(state, scc, ins);
14460 ins->id = lnode->old_id;
14462 if (lnode->val && !is_const(lnode->val)) {
14463 warning(state, lnode->def,
14464 "lattice node still high?");
14467 if (lnode->val && (lnode->val != ins)) {
14468 /* See if it something I know how to write back */
14469 switch(lnode->val->op) {
14471 mkconst(state, ins, lnode->val->u.cval);
14474 mkaddr_const(state, ins,
14475 MISC(lnode->val, 0), lnode->val->u.cval);
14478 /* By default don't copy the changes,
14479 * recompute them in place instead.
14481 simplify(state, ins);
14484 if (is_const(lnode->val) &&
14485 !constants_equal(state, lnode->val, ins)) {
14486 internal_error(state, 0, "constants not equal");
14488 /* Free the lattice nodes */
14493 } while(ins != first);
14496 static void scc_transform(struct compile_state *state)
14498 struct scc_state scc;
14500 initialize_scc_state(state, &scc);
14502 while(scc.flow_work_list || scc.ssa_work_list) {
14503 struct flow_edge *fedge;
14504 struct ssa_edge *sedge;
14505 struct flow_edge *fptr;
14506 while((fedge = scc_next_fedge(state, &scc))) {
14507 struct block *block;
14508 struct triple *ptr;
14509 struct flow_block *fblock;
14512 if (fedge->executable) {
14516 internal_error(state, 0, "fedge without dst");
14519 internal_error(state, 0, "fedge without src");
14521 fedge->executable = 1;
14522 fblock = fedge->dst;
14523 block = fblock->block;
14525 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14526 if (fptr->executable) {
14531 fprintf(stderr, "vertex: %d time: %d\n",
14532 block->vertex, time);
14536 for(ptr = block->first; !done; ptr = ptr->next) {
14537 struct lattice_node *lnode;
14538 done = (ptr == block->last);
14539 lnode = &scc.lattice[ptr->id];
14540 if (ptr->op == OP_PHI) {
14541 scc_visit_phi(state, &scc, lnode);
14543 else if (time == 1) {
14544 scc_visit_expr(state, &scc, lnode);
14547 if (fblock->out && !fblock->out->out_next) {
14548 scc_add_fedge(state, &scc, fblock->out);
14551 while((sedge = scc_next_sedge(state, &scc))) {
14552 struct lattice_node *lnode;
14553 struct flow_block *fblock;
14554 lnode = sedge->dst;
14555 fblock = lnode->fblock;
14557 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14558 sedge - scc.ssa_edges,
14559 sedge->src->def->id,
14560 sedge->dst->def->id);
14562 if (lnode->def->op == OP_PHI) {
14563 scc_visit_phi(state, &scc, lnode);
14566 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14567 if (fptr->executable) {
14572 scc_visit_expr(state, &scc, lnode);
14578 scc_writeback_values(state, &scc);
14579 free_scc_state(state, &scc);
14583 static void transform_to_arch_instructions(struct compile_state *state)
14585 struct triple *ins, *first;
14586 first = RHS(state->main_function, 0);
14589 ins = transform_to_arch_instruction(state, ins);
14590 } while(ins != first);
14593 #if DEBUG_CONSISTENCY
14594 static void verify_uses(struct compile_state *state)
14596 struct triple *first, *ins;
14597 struct triple_set *set;
14598 first = RHS(state->main_function, 0);
14601 struct triple **expr;
14602 expr = triple_rhs(state, ins, 0);
14603 for(; expr; expr = triple_rhs(state, ins, expr)) {
14604 struct triple *rhs;
14606 for(set = rhs?rhs->use:0; set; set = set->next) {
14607 if (set->member == ins) {
14612 internal_error(state, ins, "rhs not used");
14615 expr = triple_lhs(state, ins, 0);
14616 for(; expr; expr = triple_lhs(state, ins, expr)) {
14617 struct triple *lhs;
14619 for(set = lhs?lhs->use:0; set; set = set->next) {
14620 if (set->member == ins) {
14625 internal_error(state, ins, "lhs not used");
14629 } while(ins != first);
14632 static void verify_blocks_present(struct compile_state *state)
14634 struct triple *first, *ins;
14635 if (!state->first_block) {
14638 first = RHS(state->main_function, 0);
14641 valid_ins(state, ins);
14642 if (triple_stores_block(state, ins)) {
14643 if (!ins->u.block) {
14644 internal_error(state, ins,
14645 "%p not in a block?\n", ins);
14649 } while(ins != first);
14653 static void verify_blocks(struct compile_state *state)
14655 struct triple *ins;
14656 struct block *block;
14658 block = state->first_block;
14665 struct block_set *user;
14667 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14668 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
14669 internal_error(state, ins, "inconsitent block specified");
14671 valid_ins(state, ins);
14674 for(user = block->use; user; user = user->next) {
14676 if ((block == state->last_block) &&
14677 (user->member == state->first_block)) {
14680 if ((user->member->left != block) &&
14681 (user->member->right != block)) {
14682 internal_error(state, user->member->first,
14683 "user does not use block");
14686 if (triple_is_branch(state, block->last) &&
14687 (block->right != block_of_triple(state, TARG(block->last, 0))))
14689 internal_error(state, block->last, "block->right != TARG(0)");
14691 if (!triple_is_uncond_branch(state, block->last) &&
14692 (block != state->last_block) &&
14693 (block->left != block_of_triple(state, block->last->next)))
14695 internal_error(state, block->last, "block->left != block->last->next");
14698 for(user = block->left->use; user; user = user->next) {
14699 if (user->member == block) {
14703 if (!user || user->member != block) {
14704 internal_error(state, block->first,
14705 "block does not use left");
14708 if (block->right) {
14709 for(user = block->right->use; user; user = user->next) {
14710 if (user->member == block) {
14714 if (!user || user->member != block) {
14715 internal_error(state, block->first,
14716 "block does not use right");
14719 if (block->users != users) {
14720 internal_error(state, block->first,
14721 "computed users %d != stored users %d\n",
14722 users, block->users);
14724 if (!triple_stores_block(state, block->last->next)) {
14725 internal_error(state, block->last->next,
14726 "cannot find next block");
14728 block = block->last->next->u.block;
14730 internal_error(state, block->last->next,
14733 } while(block != state->first_block);
14734 if (blocks != state->last_vertex) {
14735 internal_error(state, 0, "computed blocks != stored blocks %d\n",
14736 blocks, state->last_vertex);
14740 static void verify_domination(struct compile_state *state)
14742 struct triple *first, *ins;
14743 struct triple_set *set;
14744 if (!state->first_block) {
14748 first = RHS(state->main_function, 0);
14751 for(set = ins->use; set; set = set->next) {
14752 struct triple **expr;
14753 if (set->member->op == OP_PHI) {
14756 /* See if the use is on the righ hand side */
14757 expr = triple_rhs(state, set->member, 0);
14758 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14759 if (*expr == ins) {
14764 !tdominates(state, ins, set->member)) {
14765 internal_error(state, set->member,
14766 "non dominated rhs use?");
14770 } while(ins != first);
14773 static void verify_piece(struct compile_state *state)
14775 struct triple *first, *ins;
14776 first = RHS(state->main_function, 0);
14779 struct triple *ptr;
14781 lhs = TRIPLE_LHS(ins->sizes);
14782 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14783 if (ptr != LHS(ins, i)) {
14784 internal_error(state, ins, "malformed lhs on %s",
14787 if (ptr->op != OP_PIECE) {
14788 internal_error(state, ins, "bad lhs op %s at %d on %s",
14789 tops(ptr->op), i, tops(ins->op));
14791 if (ptr->u.cval != i) {
14792 internal_error(state, ins, "bad u.cval of %d %d expected",
14797 } while(ins != first);
14799 static void verify_ins_colors(struct compile_state *state)
14801 struct triple *first, *ins;
14803 first = RHS(state->main_function, 0);
14807 } while(ins != first);
14809 static void verify_consistency(struct compile_state *state)
14811 verify_uses(state);
14812 verify_blocks_present(state);
14813 verify_blocks(state);
14814 verify_domination(state);
14815 verify_piece(state);
14816 verify_ins_colors(state);
14819 static void verify_consistency(struct compile_state *state) {}
14820 #endif /* DEBUG_USES */
14822 static void optimize(struct compile_state *state)
14824 if (state->debug & DEBUG_TRIPLES) {
14825 print_triples(state);
14827 /* Replace structures with simpler data types */
14828 flatten_structures(state);
14829 if (state->debug & DEBUG_TRIPLES) {
14830 print_triples(state);
14832 verify_consistency(state);
14833 /* Analize the intermediate code */
14834 setup_basic_blocks(state);
14835 analyze_idominators(state);
14836 analyze_ipdominators(state);
14838 /* Transform the code to ssa form. */
14840 * The transformation to ssa form puts a phi function
14841 * on each of edge of a dominance frontier where that
14842 * phi function might be needed. At -O2 if we don't
14843 * eleminate the excess phi functions we can get an
14844 * exponential code size growth. So I kill the extra
14845 * phi functions early and I kill them often.
14847 transform_to_ssa_form(state);
14848 eliminate_inefectual_code(state);
14850 verify_consistency(state);
14851 if (state->debug & DEBUG_CODE_ELIMINATION) {
14852 fprintf(stdout, "After transform_to_ssa_form\n");
14853 print_blocks(state, stdout);
14855 /* Do strength reduction and simple constant optimizations */
14856 if (state->optimize >= 1) {
14857 simplify_all(state);
14858 transform_from_ssa_form(state);
14859 free_basic_blocks(state);
14860 setup_basic_blocks(state);
14861 analyze_idominators(state);
14862 analyze_ipdominators(state);
14863 transform_to_ssa_form(state);
14864 eliminate_inefectual_code(state);
14866 if (state->debug & DEBUG_CODE_ELIMINATION) {
14867 fprintf(stdout, "After simplify_all\n");
14868 print_blocks(state, stdout);
14870 verify_consistency(state);
14871 /* Propogate constants throughout the code */
14872 if (state->optimize >= 2) {
14873 scc_transform(state);
14874 transform_from_ssa_form(state);
14875 free_basic_blocks(state);
14876 setup_basic_blocks(state);
14877 analyze_idominators(state);
14878 analyze_ipdominators(state);
14879 transform_to_ssa_form(state);
14880 eliminate_inefectual_code(state);
14882 verify_consistency(state);
14883 #warning "WISHLIST implement single use constants (least possible register pressure)"
14884 #warning "WISHLIST implement induction variable elimination"
14885 /* Select architecture instructions and an initial partial
14886 * coloring based on architecture constraints.
14888 transform_to_arch_instructions(state);
14889 verify_consistency(state);
14890 if (state->debug & DEBUG_ARCH_CODE) {
14891 printf("After transform_to_arch_instructions\n");
14892 print_blocks(state, stdout);
14893 print_control_flow(state);
14895 eliminate_inefectual_code(state);
14896 verify_consistency(state);
14897 if (state->debug & DEBUG_CODE_ELIMINATION) {
14898 printf("After eliminate_inefectual_code\n");
14899 print_blocks(state, stdout);
14900 print_control_flow(state);
14902 verify_consistency(state);
14903 /* Color all of the variables to see if they will fit in registers */
14904 insert_copies_to_phi(state);
14905 if (state->debug & DEBUG_INSERTED_COPIES) {
14906 printf("After insert_copies_to_phi\n");
14907 print_blocks(state, stdout);
14908 print_control_flow(state);
14910 verify_consistency(state);
14911 insert_mandatory_copies(state);
14912 if (state->debug & DEBUG_INSERTED_COPIES) {
14913 printf("After insert_mandatory_copies\n");
14914 print_blocks(state, stdout);
14915 print_control_flow(state);
14917 verify_consistency(state);
14918 allocate_registers(state);
14919 verify_consistency(state);
14920 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14921 print_blocks(state, stdout);
14923 if (state->debug & DEBUG_CONTROL_FLOW) {
14924 print_control_flow(state);
14926 /* Remove the optimization information.
14927 * This is more to check for memory consistency than to free memory.
14929 free_basic_blocks(state);
14932 static void print_op_asm(struct compile_state *state,
14933 struct triple *ins, FILE *fp)
14935 struct asm_info *info;
14937 unsigned lhs, rhs, i;
14938 info = ins->u.ainfo;
14939 lhs = TRIPLE_LHS(ins->sizes);
14940 rhs = TRIPLE_RHS(ins->sizes);
14941 /* Don't count the clobbers in lhs */
14942 for(i = 0; i < lhs; i++) {
14943 if (LHS(ins, i)->type == &void_type) {
14948 fprintf(fp, "#ASM\n");
14950 for(ptr = info->str; *ptr; ptr++) {
14952 unsigned long param;
14953 struct triple *piece;
14963 param = strtoul(ptr, &next, 10);
14965 error(state, ins, "Invalid asm template");
14967 if (param >= (lhs + rhs)) {
14968 error(state, ins, "Invalid param %%%u in asm template",
14971 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14973 arch_reg_str(ID_REG(piece->id)));
14976 fprintf(fp, "\n#NOT ASM\n");
14980 /* Only use the low x86 byte registers. This allows me
14981 * allocate the entire register when a byte register is used.
14983 #define X86_4_8BIT_GPRS 1
14985 /* Recognized x86 cpu variants */
14993 #define CPU_DEFAULT CPU_I386
14995 /* The x86 register classes */
14996 #define REGC_FLAGS 0
14997 #define REGC_GPR8 1
14998 #define REGC_GPR16 2
14999 #define REGC_GPR32 3
15000 #define REGC_DIVIDEND64 4
15001 #define REGC_DIVIDEND32 5
15004 #define REGC_GPR32_8 8
15005 #define REGC_GPR16_8 9
15006 #define REGC_GPR8_LO 10
15007 #define REGC_IMM32 11
15008 #define REGC_IMM16 12
15009 #define REGC_IMM8 13
15010 #define LAST_REGC REGC_IMM8
15011 #if LAST_REGC >= MAX_REGC
15012 #error "MAX_REGC is to low"
15015 /* Register class masks */
15016 #define REGCM_FLAGS (1 << REGC_FLAGS)
15017 #define REGCM_GPR8 (1 << REGC_GPR8)
15018 #define REGCM_GPR16 (1 << REGC_GPR16)
15019 #define REGCM_GPR32 (1 << REGC_GPR32)
15020 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
15021 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
15022 #define REGCM_MMX (1 << REGC_MMX)
15023 #define REGCM_XMM (1 << REGC_XMM)
15024 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
15025 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
15026 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
15027 #define REGCM_IMM32 (1 << REGC_IMM32)
15028 #define REGCM_IMM16 (1 << REGC_IMM16)
15029 #define REGCM_IMM8 (1 << REGC_IMM8)
15030 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
15032 /* The x86 registers */
15033 #define REG_EFLAGS 2
15034 #define REGC_FLAGS_FIRST REG_EFLAGS
15035 #define REGC_FLAGS_LAST REG_EFLAGS
15044 #define REGC_GPR8_LO_FIRST REG_AL
15045 #define REGC_GPR8_LO_LAST REG_DL
15046 #define REGC_GPR8_FIRST REG_AL
15047 #define REGC_GPR8_LAST REG_DH
15056 #define REGC_GPR16_FIRST REG_AX
15057 #define REGC_GPR16_LAST REG_SP
15066 #define REGC_GPR32_FIRST REG_EAX
15067 #define REGC_GPR32_LAST REG_ESP
15068 #define REG_EDXEAX 27
15069 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
15070 #define REGC_DIVIDEND64_LAST REG_EDXEAX
15071 #define REG_DXAX 28
15072 #define REGC_DIVIDEND32_FIRST REG_DXAX
15073 #define REGC_DIVIDEND32_LAST REG_DXAX
15074 #define REG_MMX0 29
15075 #define REG_MMX1 30
15076 #define REG_MMX2 31
15077 #define REG_MMX3 32
15078 #define REG_MMX4 33
15079 #define REG_MMX5 34
15080 #define REG_MMX6 35
15081 #define REG_MMX7 36
15082 #define REGC_MMX_FIRST REG_MMX0
15083 #define REGC_MMX_LAST REG_MMX7
15084 #define REG_XMM0 37
15085 #define REG_XMM1 38
15086 #define REG_XMM2 39
15087 #define REG_XMM3 40
15088 #define REG_XMM4 41
15089 #define REG_XMM5 42
15090 #define REG_XMM6 43
15091 #define REG_XMM7 44
15092 #define REGC_XMM_FIRST REG_XMM0
15093 #define REGC_XMM_LAST REG_XMM7
15094 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
15095 #define LAST_REG REG_XMM7
15097 #define REGC_GPR32_8_FIRST REG_EAX
15098 #define REGC_GPR32_8_LAST REG_EDX
15099 #define REGC_GPR16_8_FIRST REG_AX
15100 #define REGC_GPR16_8_LAST REG_DX
15102 #define REGC_IMM8_FIRST -1
15103 #define REGC_IMM8_LAST -1
15104 #define REGC_IMM16_FIRST -2
15105 #define REGC_IMM16_LAST -1
15106 #define REGC_IMM32_FIRST -4
15107 #define REGC_IMM32_LAST -1
15109 #if LAST_REG >= MAX_REGISTERS
15110 #error "MAX_REGISTERS to low"
15114 static unsigned regc_size[LAST_REGC +1] = {
15115 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
15116 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
15117 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
15118 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
15119 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
15120 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
15121 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
15122 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
15123 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
15124 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
15125 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
15131 static const struct {
15133 } regcm_bound[LAST_REGC + 1] = {
15134 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
15135 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
15136 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
15137 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
15138 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
15139 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
15140 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
15141 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
15142 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
15143 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
15144 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
15145 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
15146 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
15147 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
15150 static int arch_encode_cpu(const char *cpu)
15156 { "i386", CPU_I386 },
15164 for(ptr = cpus; ptr->name; ptr++) {
15165 if (strcmp(ptr->name, cpu) == 0) {
15172 static unsigned arch_regc_size(struct compile_state *state, int class)
15174 if ((class < 0) || (class > LAST_REGC)) {
15177 return regc_size[class];
15180 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
15182 /* See if two register classes may have overlapping registers */
15183 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
15184 REGCM_GPR32_8 | REGCM_GPR32 |
15185 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
15187 /* Special case for the immediates */
15188 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15189 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
15190 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15191 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
15194 return (regcm1 & regcm2) ||
15195 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
15198 static void arch_reg_equivs(
15199 struct compile_state *state, unsigned *equiv, int reg)
15201 if ((reg < 0) || (reg > LAST_REG)) {
15202 internal_error(state, 0, "invalid register");
15207 #if X86_4_8BIT_GPRS
15211 *equiv++ = REG_EAX;
15212 *equiv++ = REG_DXAX;
15213 *equiv++ = REG_EDXEAX;
15216 #if X86_4_8BIT_GPRS
15220 *equiv++ = REG_EAX;
15221 *equiv++ = REG_DXAX;
15222 *equiv++ = REG_EDXEAX;
15225 #if X86_4_8BIT_GPRS
15229 *equiv++ = REG_EBX;
15233 #if X86_4_8BIT_GPRS
15237 *equiv++ = REG_EBX;
15240 #if X86_4_8BIT_GPRS
15244 *equiv++ = REG_ECX;
15248 #if X86_4_8BIT_GPRS
15252 *equiv++ = REG_ECX;
15255 #if X86_4_8BIT_GPRS
15259 *equiv++ = REG_EDX;
15260 *equiv++ = REG_DXAX;
15261 *equiv++ = REG_EDXEAX;
15264 #if X86_4_8BIT_GPRS
15268 *equiv++ = REG_EDX;
15269 *equiv++ = REG_DXAX;
15270 *equiv++ = REG_EDXEAX;
15275 *equiv++ = REG_EAX;
15276 *equiv++ = REG_DXAX;
15277 *equiv++ = REG_EDXEAX;
15282 *equiv++ = REG_EBX;
15287 *equiv++ = REG_ECX;
15292 *equiv++ = REG_EDX;
15293 *equiv++ = REG_DXAX;
15294 *equiv++ = REG_EDXEAX;
15297 *equiv++ = REG_ESI;
15300 *equiv++ = REG_EDI;
15303 *equiv++ = REG_EBP;
15306 *equiv++ = REG_ESP;
15312 *equiv++ = REG_DXAX;
15313 *equiv++ = REG_EDXEAX;
15329 *equiv++ = REG_DXAX;
15330 *equiv++ = REG_EDXEAX;
15351 *equiv++ = REG_EAX;
15352 *equiv++ = REG_EDX;
15353 *equiv++ = REG_EDXEAX;
15362 *equiv++ = REG_EAX;
15363 *equiv++ = REG_EDX;
15364 *equiv++ = REG_DXAX;
15367 *equiv++ = REG_UNSET;
15370 static unsigned arch_avail_mask(struct compile_state *state)
15372 unsigned avail_mask;
15373 /* REGCM_GPR8 is not available */
15374 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
15375 REGCM_GPR32 | REGCM_GPR32_8 |
15376 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15377 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15378 switch(state->cpu) {
15381 avail_mask |= REGCM_MMX;
15385 avail_mask |= REGCM_MMX | REGCM_XMM;
15391 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15393 unsigned mask, result;
15397 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15398 if ((result & mask) == 0) {
15401 if (class > LAST_REGC) {
15404 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15405 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15406 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15407 result |= (1 << class2);
15411 result &= arch_avail_mask(state);
15415 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
15417 /* Like arch_regcm_normalize except immediate register classes are excluded */
15418 regcm = arch_regcm_normalize(state, regcm);
15419 /* Remove the immediate register classes */
15420 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15425 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15430 for(class = 0; class <= LAST_REGC; class++) {
15431 if ((reg >= regcm_bound[class].first) &&
15432 (reg <= regcm_bound[class].last)) {
15433 mask |= (1 << class);
15437 internal_error(state, 0, "reg %d not in any class", reg);
15442 static struct reg_info arch_reg_constraint(
15443 struct compile_state *state, struct type *type, const char *constraint)
15445 static const struct {
15449 } constraints[] = {
15450 { 'r', REGCM_GPR32, REG_UNSET },
15451 { 'g', REGCM_GPR32, REG_UNSET },
15452 { 'p', REGCM_GPR32, REG_UNSET },
15453 { 'q', REGCM_GPR8_LO, REG_UNSET },
15454 { 'Q', REGCM_GPR32_8, REG_UNSET },
15455 { 'x', REGCM_XMM, REG_UNSET },
15456 { 'y', REGCM_MMX, REG_UNSET },
15457 { 'a', REGCM_GPR32, REG_EAX },
15458 { 'b', REGCM_GPR32, REG_EBX },
15459 { 'c', REGCM_GPR32, REG_ECX },
15460 { 'd', REGCM_GPR32, REG_EDX },
15461 { 'D', REGCM_GPR32, REG_EDI },
15462 { 'S', REGCM_GPR32, REG_ESI },
15463 { '\0', 0, REG_UNSET },
15465 unsigned int regcm;
15466 unsigned int mask, reg;
15467 struct reg_info result;
15469 regcm = arch_type_to_regcm(state, type);
15472 for(ptr = constraint; *ptr; ptr++) {
15477 for(i = 0; constraints[i].class != '\0'; i++) {
15478 if (constraints[i].class == *ptr) {
15482 if (constraints[i].class == '\0') {
15483 error(state, 0, "invalid register constraint ``%c''", *ptr);
15486 if ((constraints[i].mask & regcm) == 0) {
15487 error(state, 0, "invalid register class %c specified",
15490 mask |= constraints[i].mask;
15491 if (constraints[i].reg != REG_UNSET) {
15492 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15493 error(state, 0, "Only one register may be specified");
15495 reg = constraints[i].reg;
15499 result.regcm = mask;
15503 static struct reg_info arch_reg_clobber(
15504 struct compile_state *state, const char *clobber)
15506 struct reg_info result;
15507 if (strcmp(clobber, "memory") == 0) {
15508 result.reg = REG_UNSET;
15511 else if (strcmp(clobber, "%eax") == 0) {
15512 result.reg = REG_EAX;
15513 result.regcm = REGCM_GPR32;
15515 else if (strcmp(clobber, "%ebx") == 0) {
15516 result.reg = REG_EBX;
15517 result.regcm = REGCM_GPR32;
15519 else if (strcmp(clobber, "%ecx") == 0) {
15520 result.reg = REG_ECX;
15521 result.regcm = REGCM_GPR32;
15523 else if (strcmp(clobber, "%edx") == 0) {
15524 result.reg = REG_EDX;
15525 result.regcm = REGCM_GPR32;
15527 else if (strcmp(clobber, "%esi") == 0) {
15528 result.reg = REG_ESI;
15529 result.regcm = REGCM_GPR32;
15531 else if (strcmp(clobber, "%edi") == 0) {
15532 result.reg = REG_EDI;
15533 result.regcm = REGCM_GPR32;
15535 else if (strcmp(clobber, "%ebp") == 0) {
15536 result.reg = REG_EBP;
15537 result.regcm = REGCM_GPR32;
15539 else if (strcmp(clobber, "%esp") == 0) {
15540 result.reg = REG_ESP;
15541 result.regcm = REGCM_GPR32;
15543 else if (strcmp(clobber, "cc") == 0) {
15544 result.reg = REG_EFLAGS;
15545 result.regcm = REGCM_FLAGS;
15547 else if ((strncmp(clobber, "xmm", 3) == 0) &&
15548 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15549 result.reg = REG_XMM0 + octdigval(clobber[3]);
15550 result.regcm = REGCM_XMM;
15552 else if ((strncmp(clobber, "mmx", 3) == 0) &&
15553 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15554 result.reg = REG_MMX0 + octdigval(clobber[3]);
15555 result.regcm = REGCM_MMX;
15558 error(state, 0, "Invalid register clobber");
15559 result.reg = REG_UNSET;
15565 static int do_select_reg(struct compile_state *state,
15566 char *used, int reg, unsigned classes)
15572 mask = arch_reg_regcm(state, reg);
15573 return (classes & mask) ? reg : REG_UNSET;
15576 static int arch_select_free_register(
15577 struct compile_state *state, char *used, int classes)
15579 /* Live ranges with the most neighbors are colored first.
15581 * Generally it does not matter which colors are given
15582 * as the register allocator attempts to color live ranges
15583 * in an order where you are guaranteed not to run out of colors.
15585 * Occasionally the register allocator cannot find an order
15586 * of register selection that will find a free color. To
15587 * increase the odds the register allocator will work when
15588 * it guesses first give out registers from register classes
15589 * least likely to run out of registers.
15594 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15595 reg = do_select_reg(state, used, i, classes);
15597 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15598 reg = do_select_reg(state, used, i, classes);
15600 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
15601 reg = do_select_reg(state, used, i, classes);
15603 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15604 reg = do_select_reg(state, used, i, classes);
15606 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15607 reg = do_select_reg(state, used, i, classes);
15609 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
15610 reg = do_select_reg(state, used, i, classes);
15612 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
15613 reg = do_select_reg(state, used, i, classes);
15615 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
15616 reg = do_select_reg(state, used, i, classes);
15618 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15619 reg = do_select_reg(state, used, i, classes);
15625 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
15627 #warning "FIXME force types smaller (if legal) before I get here"
15630 switch(type->type & TYPE_MASK) {
15637 mask = REGCM_GPR8 | REGCM_GPR8_LO |
15638 REGCM_GPR16 | REGCM_GPR16_8 |
15639 REGCM_GPR32 | REGCM_GPR32_8 |
15640 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15641 REGCM_MMX | REGCM_XMM |
15642 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15646 mask = REGCM_GPR16 | REGCM_GPR16_8 |
15647 REGCM_GPR32 | REGCM_GPR32_8 |
15648 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15649 REGCM_MMX | REGCM_XMM |
15650 REGCM_IMM32 | REGCM_IMM16;
15657 mask = REGCM_GPR32 | REGCM_GPR32_8 |
15658 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15659 REGCM_MMX | REGCM_XMM |
15663 internal_error(state, 0, "no register class for type");
15666 mask = arch_regcm_normalize(state, mask);
15670 static int is_imm32(struct triple *imm)
15672 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15673 (imm->op == OP_ADDRCONST);
15676 static int is_imm16(struct triple *imm)
15678 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15680 static int is_imm8(struct triple *imm)
15682 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15685 static int get_imm32(struct triple *ins, struct triple **expr)
15687 struct triple *imm;
15689 while(imm->op == OP_COPY) {
15692 if (!is_imm32(imm)) {
15695 unuse_triple(*expr, ins);
15696 use_triple(imm, ins);
15701 static int get_imm8(struct triple *ins, struct triple **expr)
15703 struct triple *imm;
15705 while(imm->op == OP_COPY) {
15708 if (!is_imm8(imm)) {
15711 unuse_triple(*expr, ins);
15712 use_triple(imm, ins);
15717 #define TEMPLATE_NOP 0
15718 #define TEMPLATE_INTCONST8 1
15719 #define TEMPLATE_INTCONST32 2
15720 #define TEMPLATE_COPY8_REG 3
15721 #define TEMPLATE_COPY16_REG 4
15722 #define TEMPLATE_COPY32_REG 5
15723 #define TEMPLATE_COPY_IMM8 6
15724 #define TEMPLATE_COPY_IMM16 7
15725 #define TEMPLATE_COPY_IMM32 8
15726 #define TEMPLATE_PHI8 9
15727 #define TEMPLATE_PHI16 10
15728 #define TEMPLATE_PHI32 11
15729 #define TEMPLATE_STORE8 12
15730 #define TEMPLATE_STORE16 13
15731 #define TEMPLATE_STORE32 14
15732 #define TEMPLATE_LOAD8 15
15733 #define TEMPLATE_LOAD16 16
15734 #define TEMPLATE_LOAD32 17
15735 #define TEMPLATE_BINARY8_REG 18
15736 #define TEMPLATE_BINARY16_REG 19
15737 #define TEMPLATE_BINARY32_REG 20
15738 #define TEMPLATE_BINARY8_IMM 21
15739 #define TEMPLATE_BINARY16_IMM 22
15740 #define TEMPLATE_BINARY32_IMM 23
15741 #define TEMPLATE_SL8_CL 24
15742 #define TEMPLATE_SL16_CL 25
15743 #define TEMPLATE_SL32_CL 26
15744 #define TEMPLATE_SL8_IMM 27
15745 #define TEMPLATE_SL16_IMM 28
15746 #define TEMPLATE_SL32_IMM 29
15747 #define TEMPLATE_UNARY8 30
15748 #define TEMPLATE_UNARY16 31
15749 #define TEMPLATE_UNARY32 32
15750 #define TEMPLATE_CMP8_REG 33
15751 #define TEMPLATE_CMP16_REG 34
15752 #define TEMPLATE_CMP32_REG 35
15753 #define TEMPLATE_CMP8_IMM 36
15754 #define TEMPLATE_CMP16_IMM 37
15755 #define TEMPLATE_CMP32_IMM 38
15756 #define TEMPLATE_TEST8 39
15757 #define TEMPLATE_TEST16 40
15758 #define TEMPLATE_TEST32 41
15759 #define TEMPLATE_SET 42
15760 #define TEMPLATE_JMP 43
15761 #define TEMPLATE_INB_DX 44
15762 #define TEMPLATE_INB_IMM 45
15763 #define TEMPLATE_INW_DX 46
15764 #define TEMPLATE_INW_IMM 47
15765 #define TEMPLATE_INL_DX 48
15766 #define TEMPLATE_INL_IMM 49
15767 #define TEMPLATE_OUTB_DX 50
15768 #define TEMPLATE_OUTB_IMM 51
15769 #define TEMPLATE_OUTW_DX 52
15770 #define TEMPLATE_OUTW_IMM 53
15771 #define TEMPLATE_OUTL_DX 54
15772 #define TEMPLATE_OUTL_IMM 55
15773 #define TEMPLATE_BSF 56
15774 #define TEMPLATE_RDMSR 57
15775 #define TEMPLATE_WRMSR 58
15776 #define TEMPLATE_UMUL8 59
15777 #define TEMPLATE_UMUL16 60
15778 #define TEMPLATE_UMUL32 61
15779 #define TEMPLATE_DIV8 62
15780 #define TEMPLATE_DIV16 63
15781 #define TEMPLATE_DIV32 64
15782 #define LAST_TEMPLATE TEMPLATE_DIV32
15783 #if LAST_TEMPLATE >= MAX_TEMPLATES
15784 #error "MAX_TEMPLATES to low"
15787 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
15788 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
15789 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15792 static struct ins_template templates[] = {
15793 [TEMPLATE_NOP] = {},
15794 [TEMPLATE_INTCONST8] = {
15795 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15797 [TEMPLATE_INTCONST32] = {
15798 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15800 [TEMPLATE_COPY8_REG] = {
15801 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15802 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15804 [TEMPLATE_COPY16_REG] = {
15805 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15806 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15808 [TEMPLATE_COPY32_REG] = {
15809 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15810 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15812 [TEMPLATE_COPY_IMM8] = {
15813 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15814 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15816 [TEMPLATE_COPY_IMM16] = {
15817 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15818 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
15820 [TEMPLATE_COPY_IMM32] = {
15821 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15822 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
15824 [TEMPLATE_PHI8] = {
15825 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
15827 [ 0] = { REG_VIRT0, COPY8_REGCM },
15828 [ 1] = { REG_VIRT0, COPY8_REGCM },
15829 [ 2] = { REG_VIRT0, COPY8_REGCM },
15830 [ 3] = { REG_VIRT0, COPY8_REGCM },
15831 [ 4] = { REG_VIRT0, COPY8_REGCM },
15832 [ 5] = { REG_VIRT0, COPY8_REGCM },
15833 [ 6] = { REG_VIRT0, COPY8_REGCM },
15834 [ 7] = { REG_VIRT0, COPY8_REGCM },
15835 [ 8] = { REG_VIRT0, COPY8_REGCM },
15836 [ 9] = { REG_VIRT0, COPY8_REGCM },
15837 [10] = { REG_VIRT0, COPY8_REGCM },
15838 [11] = { REG_VIRT0, COPY8_REGCM },
15839 [12] = { REG_VIRT0, COPY8_REGCM },
15840 [13] = { REG_VIRT0, COPY8_REGCM },
15841 [14] = { REG_VIRT0, COPY8_REGCM },
15842 [15] = { REG_VIRT0, COPY8_REGCM },
15844 [TEMPLATE_PHI16] = {
15845 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
15847 [ 0] = { REG_VIRT0, COPY16_REGCM },
15848 [ 1] = { REG_VIRT0, COPY16_REGCM },
15849 [ 2] = { REG_VIRT0, COPY16_REGCM },
15850 [ 3] = { REG_VIRT0, COPY16_REGCM },
15851 [ 4] = { REG_VIRT0, COPY16_REGCM },
15852 [ 5] = { REG_VIRT0, COPY16_REGCM },
15853 [ 6] = { REG_VIRT0, COPY16_REGCM },
15854 [ 7] = { REG_VIRT0, COPY16_REGCM },
15855 [ 8] = { REG_VIRT0, COPY16_REGCM },
15856 [ 9] = { REG_VIRT0, COPY16_REGCM },
15857 [10] = { REG_VIRT0, COPY16_REGCM },
15858 [11] = { REG_VIRT0, COPY16_REGCM },
15859 [12] = { REG_VIRT0, COPY16_REGCM },
15860 [13] = { REG_VIRT0, COPY16_REGCM },
15861 [14] = { REG_VIRT0, COPY16_REGCM },
15862 [15] = { REG_VIRT0, COPY16_REGCM },
15864 [TEMPLATE_PHI32] = {
15865 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
15867 [ 0] = { REG_VIRT0, COPY32_REGCM },
15868 [ 1] = { REG_VIRT0, COPY32_REGCM },
15869 [ 2] = { REG_VIRT0, COPY32_REGCM },
15870 [ 3] = { REG_VIRT0, COPY32_REGCM },
15871 [ 4] = { REG_VIRT0, COPY32_REGCM },
15872 [ 5] = { REG_VIRT0, COPY32_REGCM },
15873 [ 6] = { REG_VIRT0, COPY32_REGCM },
15874 [ 7] = { REG_VIRT0, COPY32_REGCM },
15875 [ 8] = { REG_VIRT0, COPY32_REGCM },
15876 [ 9] = { REG_VIRT0, COPY32_REGCM },
15877 [10] = { REG_VIRT0, COPY32_REGCM },
15878 [11] = { REG_VIRT0, COPY32_REGCM },
15879 [12] = { REG_VIRT0, COPY32_REGCM },
15880 [13] = { REG_VIRT0, COPY32_REGCM },
15881 [14] = { REG_VIRT0, COPY32_REGCM },
15882 [15] = { REG_VIRT0, COPY32_REGCM },
15884 [TEMPLATE_STORE8] = {
15886 [0] = { REG_UNSET, REGCM_GPR32 },
15887 [1] = { REG_UNSET, REGCM_GPR8_LO },
15890 [TEMPLATE_STORE16] = {
15892 [0] = { REG_UNSET, REGCM_GPR32 },
15893 [1] = { REG_UNSET, REGCM_GPR16 },
15896 [TEMPLATE_STORE32] = {
15898 [0] = { REG_UNSET, REGCM_GPR32 },
15899 [1] = { REG_UNSET, REGCM_GPR32 },
15902 [TEMPLATE_LOAD8] = {
15903 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
15904 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15906 [TEMPLATE_LOAD16] = {
15907 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15908 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15910 [TEMPLATE_LOAD32] = {
15911 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15912 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15914 [TEMPLATE_BINARY8_REG] = {
15915 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15917 [0] = { REG_VIRT0, REGCM_GPR8_LO },
15918 [1] = { REG_UNSET, REGCM_GPR8_LO },
15921 [TEMPLATE_BINARY16_REG] = {
15922 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15924 [0] = { REG_VIRT0, REGCM_GPR16 },
15925 [1] = { REG_UNSET, REGCM_GPR16 },
15928 [TEMPLATE_BINARY32_REG] = {
15929 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15931 [0] = { REG_VIRT0, REGCM_GPR32 },
15932 [1] = { REG_UNSET, REGCM_GPR32 },
15935 [TEMPLATE_BINARY8_IMM] = {
15936 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15938 [0] = { REG_VIRT0, REGCM_GPR8_LO },
15939 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15942 [TEMPLATE_BINARY16_IMM] = {
15943 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15945 [0] = { REG_VIRT0, REGCM_GPR16 },
15946 [1] = { REG_UNNEEDED, REGCM_IMM16 },
15949 [TEMPLATE_BINARY32_IMM] = {
15950 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15952 [0] = { REG_VIRT0, REGCM_GPR32 },
15953 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15956 [TEMPLATE_SL8_CL] = {
15957 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15959 [0] = { REG_VIRT0, REGCM_GPR8_LO },
15960 [1] = { REG_CL, REGCM_GPR8_LO },
15963 [TEMPLATE_SL16_CL] = {
15964 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15966 [0] = { REG_VIRT0, REGCM_GPR16 },
15967 [1] = { REG_CL, REGCM_GPR8_LO },
15970 [TEMPLATE_SL32_CL] = {
15971 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15973 [0] = { REG_VIRT0, REGCM_GPR32 },
15974 [1] = { REG_CL, REGCM_GPR8_LO },
15977 [TEMPLATE_SL8_IMM] = {
15978 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15980 [0] = { REG_VIRT0, REGCM_GPR8_LO },
15981 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15984 [TEMPLATE_SL16_IMM] = {
15985 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15987 [0] = { REG_VIRT0, REGCM_GPR16 },
15988 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15991 [TEMPLATE_SL32_IMM] = {
15992 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15994 [0] = { REG_VIRT0, REGCM_GPR32 },
15995 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15998 [TEMPLATE_UNARY8] = {
15999 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16000 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16002 [TEMPLATE_UNARY16] = {
16003 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16004 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16006 [TEMPLATE_UNARY32] = {
16007 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16008 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16010 [TEMPLATE_CMP8_REG] = {
16011 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16013 [0] = { REG_UNSET, REGCM_GPR8_LO },
16014 [1] = { REG_UNSET, REGCM_GPR8_LO },
16017 [TEMPLATE_CMP16_REG] = {
16018 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16020 [0] = { REG_UNSET, REGCM_GPR16 },
16021 [1] = { REG_UNSET, REGCM_GPR16 },
16024 [TEMPLATE_CMP32_REG] = {
16025 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16027 [0] = { REG_UNSET, REGCM_GPR32 },
16028 [1] = { REG_UNSET, REGCM_GPR32 },
16031 [TEMPLATE_CMP8_IMM] = {
16032 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16034 [0] = { REG_UNSET, REGCM_GPR8_LO },
16035 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16038 [TEMPLATE_CMP16_IMM] = {
16039 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16041 [0] = { REG_UNSET, REGCM_GPR16 },
16042 [1] = { REG_UNNEEDED, REGCM_IMM16 },
16045 [TEMPLATE_CMP32_IMM] = {
16046 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16048 [0] = { REG_UNSET, REGCM_GPR32 },
16049 [1] = { REG_UNNEEDED, REGCM_IMM32 },
16052 [TEMPLATE_TEST8] = {
16053 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16054 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16056 [TEMPLATE_TEST16] = {
16057 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16058 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
16060 [TEMPLATE_TEST32] = {
16061 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16062 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16065 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16066 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16069 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16071 [TEMPLATE_INB_DX] = {
16072 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
16073 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16075 [TEMPLATE_INB_IMM] = {
16076 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
16077 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16079 [TEMPLATE_INW_DX] = {
16080 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16081 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16083 [TEMPLATE_INW_IMM] = {
16084 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16085 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16087 [TEMPLATE_INL_DX] = {
16088 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
16089 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16091 [TEMPLATE_INL_IMM] = {
16092 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
16093 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16095 [TEMPLATE_OUTB_DX] = {
16097 [0] = { REG_AL, REGCM_GPR8_LO },
16098 [1] = { REG_DX, REGCM_GPR16 },
16101 [TEMPLATE_OUTB_IMM] = {
16103 [0] = { REG_AL, REGCM_GPR8_LO },
16104 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16107 [TEMPLATE_OUTW_DX] = {
16109 [0] = { REG_AX, REGCM_GPR16 },
16110 [1] = { REG_DX, REGCM_GPR16 },
16113 [TEMPLATE_OUTW_IMM] = {
16115 [0] = { REG_AX, REGCM_GPR16 },
16116 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16119 [TEMPLATE_OUTL_DX] = {
16121 [0] = { REG_EAX, REGCM_GPR32 },
16122 [1] = { REG_DX, REGCM_GPR16 },
16125 [TEMPLATE_OUTL_IMM] = {
16127 [0] = { REG_EAX, REGCM_GPR32 },
16128 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16132 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16133 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16135 [TEMPLATE_RDMSR] = {
16137 [0] = { REG_EAX, REGCM_GPR32 },
16138 [1] = { REG_EDX, REGCM_GPR32 },
16140 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
16142 [TEMPLATE_WRMSR] = {
16144 [0] = { REG_ECX, REGCM_GPR32 },
16145 [1] = { REG_EAX, REGCM_GPR32 },
16146 [2] = { REG_EDX, REGCM_GPR32 },
16149 [TEMPLATE_UMUL8] = {
16150 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16152 [0] = { REG_AL, REGCM_GPR8_LO },
16153 [1] = { REG_UNSET, REGCM_GPR8_LO },
16156 [TEMPLATE_UMUL16] = {
16157 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
16159 [0] = { REG_AX, REGCM_GPR16 },
16160 [1] = { REG_UNSET, REGCM_GPR16 },
16163 [TEMPLATE_UMUL32] = {
16164 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
16166 [0] = { REG_EAX, REGCM_GPR32 },
16167 [1] = { REG_UNSET, REGCM_GPR32 },
16170 [TEMPLATE_DIV8] = {
16172 [0] = { REG_AL, REGCM_GPR8_LO },
16173 [1] = { REG_AH, REGCM_GPR8 },
16176 [0] = { REG_AX, REGCM_GPR16 },
16177 [1] = { REG_UNSET, REGCM_GPR8_LO },
16180 [TEMPLATE_DIV16] = {
16182 [0] = { REG_AX, REGCM_GPR16 },
16183 [1] = { REG_DX, REGCM_GPR16 },
16186 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
16187 [1] = { REG_UNSET, REGCM_GPR16 },
16190 [TEMPLATE_DIV32] = {
16192 [0] = { REG_EAX, REGCM_GPR32 },
16193 [1] = { REG_EDX, REGCM_GPR32 },
16196 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
16197 [1] = { REG_UNSET, REGCM_GPR32 },
16202 static void fixup_branches(struct compile_state *state,
16203 struct triple *cmp, struct triple *use, int jmp_op)
16205 struct triple_set *entry, *next;
16206 for(entry = use->use; entry; entry = next) {
16207 next = entry->next;
16208 if (entry->member->op == OP_COPY) {
16209 fixup_branches(state, cmp, entry->member, jmp_op);
16211 else if (entry->member->op == OP_BRANCH) {
16212 struct triple *branch, *test;
16213 struct triple *left, *right;
16215 left = RHS(cmp, 0);
16216 if (TRIPLE_RHS(cmp->sizes) > 1) {
16217 right = RHS(cmp, 1);
16219 branch = entry->member;
16220 test = pre_triple(state, branch,
16221 cmp->op, cmp->type, left, right);
16222 test->template_id = TEMPLATE_TEST32;
16223 if (cmp->op == OP_CMP) {
16224 test->template_id = TEMPLATE_CMP32_REG;
16225 if (get_imm32(test, &RHS(test, 1))) {
16226 test->template_id = TEMPLATE_CMP32_IMM;
16229 use_triple(RHS(test, 0), test);
16230 use_triple(RHS(test, 1), test);
16231 unuse_triple(RHS(branch, 0), branch);
16232 RHS(branch, 0) = test;
16233 branch->op = jmp_op;
16234 branch->template_id = TEMPLATE_JMP;
16235 use_triple(RHS(branch, 0), branch);
16240 static void bool_cmp(struct compile_state *state,
16241 struct triple *ins, int cmp_op, int jmp_op, int set_op)
16243 struct triple_set *entry, *next;
16244 struct triple *set;
16246 /* Put a barrier up before the cmp which preceeds the
16247 * copy instruction. If a set actually occurs this gives
16248 * us a chance to move variables in registers out of the way.
16251 /* Modify the comparison operator */
16253 ins->template_id = TEMPLATE_TEST32;
16254 if (cmp_op == OP_CMP) {
16255 ins->template_id = TEMPLATE_CMP32_REG;
16256 if (get_imm32(ins, &RHS(ins, 1))) {
16257 ins->template_id = TEMPLATE_CMP32_IMM;
16260 /* Generate the instruction sequence that will transform the
16261 * result of the comparison into a logical value.
16263 set = post_triple(state, ins, set_op, &char_type, ins, 0);
16264 use_triple(ins, set);
16265 set->template_id = TEMPLATE_SET;
16267 for(entry = ins->use; entry; entry = next) {
16268 next = entry->next;
16269 if (entry->member == set) {
16272 replace_rhs_use(state, ins, set, entry->member);
16274 fixup_branches(state, ins, set, jmp_op);
16277 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
16279 struct triple *next;
16281 lhs = TRIPLE_LHS(ins->sizes);
16282 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
16283 if (next != LHS(ins, i)) {
16284 internal_error(state, ins, "malformed lhs on %s",
16287 if (next->op != OP_PIECE) {
16288 internal_error(state, ins, "bad lhs op %s at %d on %s",
16289 tops(next->op), i, tops(ins->op));
16291 if (next->u.cval != i) {
16292 internal_error(state, ins, "bad u.cval of %d %d expected",
16299 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
16301 struct ins_template *template;
16302 struct reg_info result;
16304 if (ins->op == OP_PIECE) {
16305 index = ins->u.cval;
16306 ins = MISC(ins, 0);
16308 zlhs = TRIPLE_LHS(ins->sizes);
16309 if (triple_is_def(state, ins)) {
16312 if (index >= zlhs) {
16313 internal_error(state, ins, "index %d out of range for %s\n",
16314 index, tops(ins->op));
16318 template = &ins->u.ainfo->tmpl;
16321 if (ins->template_id > LAST_TEMPLATE) {
16322 internal_error(state, ins, "bad template number %d",
16325 template = &templates[ins->template_id];
16328 result = template->lhs[index];
16329 result.regcm = arch_regcm_normalize(state, result.regcm);
16330 if (result.reg != REG_UNNEEDED) {
16331 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
16333 if (result.regcm == 0) {
16334 internal_error(state, ins, "lhs %d regcm == 0", index);
16339 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
16341 struct reg_info result;
16342 struct ins_template *template;
16343 if ((index > TRIPLE_RHS(ins->sizes)) ||
16344 (ins->op == OP_PIECE)) {
16345 internal_error(state, ins, "index %d out of range for %s\n",
16346 index, tops(ins->op));
16350 template = &ins->u.ainfo->tmpl;
16353 if (ins->template_id > LAST_TEMPLATE) {
16354 internal_error(state, ins, "bad template number %d",
16357 template = &templates[ins->template_id];
16360 result = template->rhs[index];
16361 result.regcm = arch_regcm_normalize(state, result.regcm);
16362 if (result.regcm == 0) {
16363 internal_error(state, ins, "rhs %d regcm == 0", index);
16368 static struct triple *mod_div(struct compile_state *state,
16369 struct triple *ins, int div_op, int index)
16371 struct triple *div, *piece0, *piece1;
16373 /* Generate a piece to hold the remainder */
16374 piece1 = post_triple(state, ins, OP_PIECE, ins->type, 0, 0);
16375 piece1->u.cval = 1;
16377 /* Generate a piece to hold the quotient */
16378 piece0 = post_triple(state, ins, OP_PIECE, ins->type, 0, 0);
16379 piece0->u.cval = 0;
16381 /* Generate the appropriate division instruction */
16382 div = post_triple(state, ins, div_op, ins->type, 0, 0);
16383 RHS(div, 0) = RHS(ins, 0);
16384 RHS(div, 1) = RHS(ins, 1);
16385 LHS(div, 0) = piece0;
16386 LHS(div, 1) = piece1;
16387 div->template_id = TEMPLATE_DIV32;
16388 use_triple(RHS(div, 0), div);
16389 use_triple(RHS(div, 1), div);
16390 use_triple(LHS(div, 0), div);
16391 use_triple(LHS(div, 1), div);
16393 /* Hook on piece0 */
16394 MISC(piece0, 0) = div;
16395 use_triple(div, piece0);
16397 /* Hook on piece1 */
16398 MISC(piece1, 0) = div;
16399 use_triple(div, piece1);
16401 /* Replate uses of ins with the appropriate piece of the div */
16402 propogate_use(state, ins, LHS(div, index));
16403 release_triple(state, ins);
16405 /* Return the address of the next instruction */
16406 return piece1->next;
16409 static struct triple *transform_to_arch_instruction(
16410 struct compile_state *state, struct triple *ins)
16412 /* Transform from generic 3 address instructions
16413 * to archtecture specific instructions.
16414 * And apply architecture specific constraints to instructions.
16415 * Copies are inserted to preserve the register flexibility
16416 * of 3 address instructions.
16418 struct triple *next;
16423 ins->template_id = TEMPLATE_INTCONST32;
16424 if (ins->u.cval < 256) {
16425 ins->template_id = TEMPLATE_INTCONST8;
16429 ins->template_id = TEMPLATE_INTCONST32;
16435 ins->template_id = TEMPLATE_NOP;
16438 size = size_of(state, ins->type);
16439 if (is_imm8(RHS(ins, 0)) && (size <= 1)) {
16440 ins->template_id = TEMPLATE_COPY_IMM8;
16442 else if (is_imm16(RHS(ins, 0)) && (size <= 2)) {
16443 ins->template_id = TEMPLATE_COPY_IMM16;
16445 else if (is_imm32(RHS(ins, 0)) && (size <= 4)) {
16446 ins->template_id = TEMPLATE_COPY_IMM32;
16448 else if (is_const(RHS(ins, 0))) {
16449 internal_error(state, ins, "bad constant passed to copy");
16451 else if (size <= 1) {
16452 ins->template_id = TEMPLATE_COPY8_REG;
16454 else if (size <= 2) {
16455 ins->template_id = TEMPLATE_COPY16_REG;
16457 else if (size <= 4) {
16458 ins->template_id = TEMPLATE_COPY32_REG;
16461 internal_error(state, ins, "bad type passed to copy");
16465 size = size_of(state, ins->type);
16467 ins->template_id = TEMPLATE_PHI8;
16469 else if (size <= 2) {
16470 ins->template_id = TEMPLATE_PHI16;
16472 else if (size <= 4) {
16473 ins->template_id = TEMPLATE_PHI32;
16476 internal_error(state, ins, "bad type passed to phi");
16480 switch(ins->type->type & TYPE_MASK) {
16481 case TYPE_CHAR: case TYPE_UCHAR:
16482 ins->template_id = TEMPLATE_STORE8;
16484 case TYPE_SHORT: case TYPE_USHORT:
16485 ins->template_id = TEMPLATE_STORE16;
16487 case TYPE_INT: case TYPE_UINT:
16488 case TYPE_LONG: case TYPE_ULONG:
16490 ins->template_id = TEMPLATE_STORE32;
16493 internal_error(state, ins, "unknown type in store");
16498 switch(ins->type->type & TYPE_MASK) {
16499 case TYPE_CHAR: case TYPE_UCHAR:
16500 ins->template_id = TEMPLATE_LOAD8;
16504 ins->template_id = TEMPLATE_LOAD16;
16511 ins->template_id = TEMPLATE_LOAD32;
16514 internal_error(state, ins, "unknown type in load");
16524 ins->template_id = TEMPLATE_BINARY32_REG;
16525 if (get_imm32(ins, &RHS(ins, 1))) {
16526 ins->template_id = TEMPLATE_BINARY32_IMM;
16531 ins->template_id = TEMPLATE_DIV32;
16532 next = after_lhs(state, ins);
16534 /* FIXME UMUL does not work yet.. */
16536 ins->template_id = TEMPLATE_UMUL32;
16539 next = mod_div(state, ins, OP_UDIVT, 0);
16542 next = mod_div(state, ins, OP_SDIVT, 0);
16545 next = mod_div(state, ins, OP_UDIVT, 1);
16548 next = mod_div(state, ins, OP_SDIVT, 1);
16553 ins->template_id = TEMPLATE_SL32_CL;
16554 if (get_imm8(ins, &RHS(ins, 1))) {
16555 ins->template_id = TEMPLATE_SL32_IMM;
16556 } else if (size_of(state, RHS(ins, 1)->type) > 1) {
16557 typed_pre_copy(state, &char_type, ins, 1);
16562 ins->template_id = TEMPLATE_UNARY32;
16565 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
16568 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16571 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16574 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16577 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16580 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16583 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16586 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16589 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16592 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16595 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16598 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16601 if (TRIPLE_RHS(ins->sizes) > 0) {
16602 internal_error(state, ins, "bad branch test");
16605 ins->template_id = TEMPLATE_NOP;
16611 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16612 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16613 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16615 if (get_imm8(ins, &RHS(ins, 0))) {
16616 ins->template_id += 1;
16623 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16624 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16625 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16627 if (get_imm8(ins, &RHS(ins, 1))) {
16628 ins->template_id += 1;
16633 ins->template_id = TEMPLATE_BSF;
16636 ins->template_id = TEMPLATE_RDMSR;
16637 next = after_lhs(state, ins);
16640 ins->template_id = TEMPLATE_WRMSR;
16643 ins->template_id = TEMPLATE_NOP;
16646 ins->template_id = TEMPLATE_NOP;
16647 next = after_lhs(state, ins);
16649 /* Already transformed instructions */
16651 ins->template_id = TEMPLATE_TEST32;
16654 ins->template_id = TEMPLATE_CMP32_REG;
16655 if (get_imm32(ins, &RHS(ins, 1))) {
16656 ins->template_id = TEMPLATE_CMP32_IMM;
16659 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16660 case OP_JMP_SLESS: case OP_JMP_ULESS:
16661 case OP_JMP_SMORE: case OP_JMP_UMORE:
16662 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16663 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16664 ins->template_id = TEMPLATE_JMP;
16666 case OP_SET_EQ: case OP_SET_NOTEQ:
16667 case OP_SET_SLESS: case OP_SET_ULESS:
16668 case OP_SET_SMORE: case OP_SET_UMORE:
16669 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16670 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16671 ins->template_id = TEMPLATE_SET;
16673 /* Unhandled instructions */
16676 internal_error(state, ins, "unhandled ins: %d %s\n",
16677 ins->op, tops(ins->op));
16683 static long next_label(struct compile_state *state)
16685 static long label_counter = 0;
16686 return ++label_counter;
16688 static void generate_local_labels(struct compile_state *state)
16690 struct triple *first, *label;
16691 first = RHS(state->main_function, 0);
16694 if ((label->op == OP_LABEL) ||
16695 (label->op == OP_SDECL)) {
16697 label->u.cval = next_label(state);
16703 label = label->next;
16704 } while(label != first);
16707 static int check_reg(struct compile_state *state,
16708 struct triple *triple, int classes)
16712 reg = ID_REG(triple->id);
16713 if (reg == REG_UNSET) {
16714 internal_error(state, triple, "register not set");
16716 mask = arch_reg_regcm(state, reg);
16717 if (!(classes & mask)) {
16718 internal_error(state, triple, "reg %d in wrong class",
16724 static const char *arch_reg_str(int reg)
16727 #error "Registers have renumberd fix arch_reg_str"
16729 static const char *regs[] = {
16733 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16734 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16735 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16738 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16739 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
16740 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16742 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16749 static const char *reg(struct compile_state *state, struct triple *triple,
16753 reg = check_reg(state, triple, classes);
16754 return arch_reg_str(reg);
16757 const char *type_suffix(struct compile_state *state, struct type *type)
16759 const char *suffix;
16760 switch(size_of(state, type)) {
16761 case 1: suffix = "b"; break;
16762 case 2: suffix = "w"; break;
16763 case 4: suffix = "l"; break;
16765 internal_error(state, 0, "unknown suffix");
16772 static void print_const_val(
16773 struct compile_state *state, struct triple *ins, FILE *fp)
16777 fprintf(fp, " $%ld ",
16778 (long_t)(ins->u.cval));
16781 fprintf(fp, " $L%s%lu+%lu ",
16782 state->label_prefix,
16783 MISC(ins, 0)->u.cval,
16787 internal_error(state, ins, "unknown constant type");
16792 static void print_const(struct compile_state *state,
16793 struct triple *ins, FILE *fp)
16797 switch(ins->type->type & TYPE_MASK) {
16800 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16804 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16810 fprintf(fp, ".int %lu\n", ins->u.cval);
16813 internal_error(state, ins, "Unknown constant type");
16817 fprintf(fp, " .int L%s%lu+%lu ",
16818 state->label_prefix,
16819 MISC(ins, 0)->u.cval,
16824 unsigned char *blob;
16826 size = size_of(state, ins->type);
16827 blob = ins->u.blob;
16828 for(i = 0; i < size; i++) {
16829 fprintf(fp, ".byte 0x%02x\n",
16835 internal_error(state, ins, "Unknown constant type");
16840 #define TEXT_SECTION ".rom.text"
16841 #define DATA_SECTION ".rom.data"
16843 static long get_const_pool_ref(
16844 struct compile_state *state, struct triple *ins, FILE *fp)
16847 ref = next_label(state);
16848 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16849 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16850 fprintf(fp, "L%s%lu:\n", state->label_prefix, ref);
16851 print_const(state, ins, fp);
16852 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16856 static void print_binary_op(struct compile_state *state,
16857 const char *op, struct triple *ins, FILE *fp)
16860 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16861 if (RHS(ins, 0)->id != ins->id) {
16862 internal_error(state, ins, "invalid register assignment");
16864 if (is_const(RHS(ins, 1))) {
16865 fprintf(fp, "\t%s ", op);
16866 print_const_val(state, RHS(ins, 1), fp);
16867 fprintf(fp, ", %s\n",
16868 reg(state, RHS(ins, 0), mask));
16871 unsigned lmask, rmask;
16873 lreg = check_reg(state, RHS(ins, 0), mask);
16874 rreg = check_reg(state, RHS(ins, 1), mask);
16875 lmask = arch_reg_regcm(state, lreg);
16876 rmask = arch_reg_regcm(state, rreg);
16877 mask = lmask & rmask;
16878 fprintf(fp, "\t%s %s, %s\n",
16880 reg(state, RHS(ins, 1), mask),
16881 reg(state, RHS(ins, 0), mask));
16884 static void print_unary_op(struct compile_state *state,
16885 const char *op, struct triple *ins, FILE *fp)
16888 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16889 fprintf(fp, "\t%s %s\n",
16891 reg(state, RHS(ins, 0), mask));
16894 static void print_op_shift(struct compile_state *state,
16895 const char *op, struct triple *ins, FILE *fp)
16898 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16899 if (RHS(ins, 0)->id != ins->id) {
16900 internal_error(state, ins, "invalid register assignment");
16902 if (is_const(RHS(ins, 1))) {
16903 fprintf(fp, "\t%s ", op);
16904 print_const_val(state, RHS(ins, 1), fp);
16905 fprintf(fp, ", %s\n",
16906 reg(state, RHS(ins, 0), mask));
16909 fprintf(fp, "\t%s %s, %s\n",
16911 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
16912 reg(state, RHS(ins, 0), mask));
16916 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16923 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
16924 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16925 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16927 internal_error(state, ins, "not an in operation");
16931 dreg = check_reg(state, ins, mask);
16932 if (!reg_is_reg(state, dreg, REG_EAX)) {
16933 internal_error(state, ins, "dst != %%eax");
16935 if (is_const(RHS(ins, 0))) {
16936 fprintf(fp, "\t%s ", op);
16937 print_const_val(state, RHS(ins, 0), fp);
16938 fprintf(fp, ", %s\n",
16939 reg(state, ins, mask));
16943 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16944 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16945 internal_error(state, ins, "src != %%dx");
16947 fprintf(fp, "\t%s %s, %s\n",
16949 reg(state, RHS(ins, 0), REGCM_GPR16),
16950 reg(state, ins, mask));
16954 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16961 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
16962 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16963 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16965 internal_error(state, ins, "not an out operation");
16969 lreg = check_reg(state, RHS(ins, 0), mask);
16970 if (!reg_is_reg(state, lreg, REG_EAX)) {
16971 internal_error(state, ins, "src != %%eax");
16973 if (is_const(RHS(ins, 1))) {
16974 fprintf(fp, "\t%s %s,",
16975 op, reg(state, RHS(ins, 0), mask));
16976 print_const_val(state, RHS(ins, 1), fp);
16981 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16982 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16983 internal_error(state, ins, "dst != %%dx");
16985 fprintf(fp, "\t%s %s, %s\n",
16987 reg(state, RHS(ins, 0), mask),
16988 reg(state, RHS(ins, 1), REGCM_GPR16));
16992 static void print_op_move(struct compile_state *state,
16993 struct triple *ins, FILE *fp)
16995 /* op_move is complex because there are many types
16996 * of registers we can move between.
16997 * Because OP_COPY will be introduced in arbitrary locations
16998 * OP_COPY must not affect flags.
17000 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
17001 struct triple *dst, *src;
17002 if (ins->op == OP_COPY) {
17007 internal_error(state, ins, "unknown move operation");
17010 if (!is_const(src)) {
17011 int src_reg, dst_reg;
17012 int src_regcm, dst_regcm;
17013 src_reg = ID_REG(src->id);
17014 dst_reg = ID_REG(dst->id);
17015 src_regcm = arch_reg_regcm(state, src_reg);
17016 dst_regcm = arch_reg_regcm(state, dst_reg);
17017 /* If the class is the same just move the register */
17018 if (src_regcm & dst_regcm &
17019 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
17020 if ((src_reg != dst_reg) || !omit_copy) {
17021 fprintf(fp, "\tmov %s, %s\n",
17022 reg(state, src, src_regcm),
17023 reg(state, dst, dst_regcm));
17026 /* Move 32bit to 16bit */
17027 else if ((src_regcm & REGCM_GPR32) &&
17028 (dst_regcm & REGCM_GPR16)) {
17029 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
17030 if ((src_reg != dst_reg) || !omit_copy) {
17031 fprintf(fp, "\tmovw %s, %s\n",
17032 arch_reg_str(src_reg),
17033 arch_reg_str(dst_reg));
17036 /* Move from 32bit gprs to 16bit gprs */
17037 else if ((src_regcm & REGCM_GPR32) &&
17038 (dst_regcm & REGCM_GPR16)) {
17039 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17040 if ((src_reg != dst_reg) || !omit_copy) {
17041 fprintf(fp, "\tmov %s, %s\n",
17042 arch_reg_str(src_reg),
17043 arch_reg_str(dst_reg));
17046 /* Move 32bit to 8bit */
17047 else if ((src_regcm & REGCM_GPR32_8) &&
17048 (dst_regcm & REGCM_GPR8_LO))
17050 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
17051 if ((src_reg != dst_reg) || !omit_copy) {
17052 fprintf(fp, "\tmovb %s, %s\n",
17053 arch_reg_str(src_reg),
17054 arch_reg_str(dst_reg));
17057 /* Move 16bit to 8bit */
17058 else if ((src_regcm & REGCM_GPR16_8) &&
17059 (dst_regcm & REGCM_GPR8_LO))
17061 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
17062 if ((src_reg != dst_reg) || !omit_copy) {
17063 fprintf(fp, "\tmovb %s, %s\n",
17064 arch_reg_str(src_reg),
17065 arch_reg_str(dst_reg));
17068 /* Move 8/16bit to 16/32bit */
17069 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
17070 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
17072 op = is_signed(src->type)? "movsx": "movzx";
17073 fprintf(fp, "\t%s %s, %s\n",
17075 reg(state, src, src_regcm),
17076 reg(state, dst, dst_regcm));
17078 /* Move between sse registers */
17079 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
17080 if ((src_reg != dst_reg) || !omit_copy) {
17081 fprintf(fp, "\tmovdqa %s, %s\n",
17082 reg(state, src, src_regcm),
17083 reg(state, dst, dst_regcm));
17086 /* Move between mmx registers */
17087 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
17088 if ((src_reg != dst_reg) || !omit_copy) {
17089 fprintf(fp, "\tmovq %s, %s\n",
17090 reg(state, src, src_regcm),
17091 reg(state, dst, dst_regcm));
17094 /* Move from sse to mmx registers */
17095 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
17096 fprintf(fp, "\tmovdq2q %s, %s\n",
17097 reg(state, src, src_regcm),
17098 reg(state, dst, dst_regcm));
17100 /* Move from mmx to sse registers */
17101 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
17102 fprintf(fp, "\tmovq2dq %s, %s\n",
17103 reg(state, src, src_regcm),
17104 reg(state, dst, dst_regcm));
17106 /* Move between 32bit gprs & mmx/sse registers */
17107 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
17108 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
17109 fprintf(fp, "\tmovd %s, %s\n",
17110 reg(state, src, src_regcm),
17111 reg(state, dst, dst_regcm));
17113 /* Move from 16bit gprs & mmx/sse registers */
17114 else if ((src_regcm & REGCM_GPR16) &&
17115 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
17118 op = is_signed(src->type)? "movsx":"movzx";
17119 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17120 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
17122 arch_reg_str(src_reg),
17123 arch_reg_str(mid_reg),
17124 arch_reg_str(mid_reg),
17125 arch_reg_str(dst_reg));
17127 /* Move from mmx/sse registers to 16bit gprs */
17128 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17129 (dst_regcm & REGCM_GPR16)) {
17130 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17131 fprintf(fp, "\tmovd %s, %s\n",
17132 arch_reg_str(src_reg),
17133 arch_reg_str(dst_reg));
17135 /* Move from gpr to 64bit dividend */
17136 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
17137 (dst_regcm & REGCM_DIVIDEND64)) {
17138 const char *extend;
17139 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
17140 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
17141 arch_reg_str(src_reg),
17144 /* Move from 64bit gpr to gpr */
17145 else if ((src_regcm & REGCM_DIVIDEND64) &&
17146 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
17147 if (dst_regcm & REGCM_GPR32) {
17150 else if (dst_regcm & REGCM_GPR16) {
17153 else if (dst_regcm & REGCM_GPR8_LO) {
17156 fprintf(fp, "\tmov %s, %s\n",
17157 arch_reg_str(src_reg),
17158 arch_reg_str(dst_reg));
17160 /* Move from mmx/sse registers to 64bit gpr */
17161 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17162 (dst_regcm & REGCM_DIVIDEND64)) {
17163 const char *extend;
17164 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
17165 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
17166 arch_reg_str(src_reg),
17169 /* Move from 64bit gpr to mmx/sse register */
17170 else if ((src_regcm & REGCM_DIVIDEND64) &&
17171 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
17172 fprintf(fp, "\tmovd %%eax, %s\n",
17173 arch_reg_str(dst_reg));
17175 #if X86_4_8BIT_GPRS
17176 /* Move from 8bit gprs to mmx/sse registers */
17177 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
17178 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
17181 op = is_signed(src->type)? "movsx":"movzx";
17182 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17183 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
17185 reg(state, src, src_regcm),
17186 arch_reg_str(mid_reg),
17187 arch_reg_str(mid_reg),
17188 reg(state, dst, dst_regcm));
17190 /* Move from mmx/sse registers and 8bit gprs */
17191 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17192 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
17194 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17195 fprintf(fp, "\tmovd %s, %s\n",
17196 reg(state, src, src_regcm),
17197 arch_reg_str(mid_reg));
17199 /* Move from 32bit gprs to 8bit gprs */
17200 else if ((src_regcm & REGCM_GPR32) &&
17201 (dst_regcm & REGCM_GPR8_LO)) {
17202 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17203 if ((src_reg != dst_reg) || !omit_copy) {
17204 fprintf(fp, "\tmov %s, %s\n",
17205 arch_reg_str(src_reg),
17206 arch_reg_str(dst_reg));
17209 /* Move from 16bit gprs to 8bit gprs */
17210 else if ((src_regcm & REGCM_GPR16) &&
17211 (dst_regcm & REGCM_GPR8_LO)) {
17212 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
17213 if ((src_reg != dst_reg) || !omit_copy) {
17214 fprintf(fp, "\tmov %s, %s\n",
17215 arch_reg_str(src_reg),
17216 arch_reg_str(dst_reg));
17219 #endif /* X86_4_8BIT_GPRS */
17221 internal_error(state, ins, "unknown copy type");
17227 dst_reg = ID_REG(dst->id);
17228 dst_regcm = arch_reg_regcm(state, dst_reg);
17229 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
17230 fprintf(fp, "\tmov ");
17231 print_const_val(state, src, fp);
17232 fprintf(fp, ", %s\n",
17233 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
17235 else if (dst_regcm & REGCM_DIVIDEND64) {
17236 if (size_of(state, dst->type) > 4) {
17237 internal_error(state, ins, "64bit constant...");
17239 fprintf(fp, "\tmov $0, %%edx\n");
17240 fprintf(fp, "\tmov ");
17241 print_const_val(state, src, fp);
17242 fprintf(fp, ", %%eax\n");
17244 else if (dst_regcm & REGCM_DIVIDEND32) {
17245 if (size_of(state, dst->type) > 2) {
17246 internal_error(state, ins, "32bit constant...");
17248 fprintf(fp, "\tmov $0, %%dx\n");
17249 fprintf(fp, "\tmov ");
17250 print_const_val(state, src, fp);
17251 fprintf(fp, ", %%ax");
17253 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
17255 ref = get_const_pool_ref(state, src, fp);
17256 fprintf(fp, "\tmovq L%s%lu, %s\n",
17257 state->label_prefix, ref,
17258 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
17261 internal_error(state, ins, "unknown copy immediate type");
17266 static void print_op_load(struct compile_state *state,
17267 struct triple *ins, FILE *fp)
17269 struct triple *dst, *src;
17272 if (is_const(src) || is_const(dst)) {
17273 internal_error(state, ins, "unknown load operation");
17275 fprintf(fp, "\tmov (%s), %s\n",
17276 reg(state, src, REGCM_GPR32),
17277 reg(state, dst, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32));
17281 static void print_op_store(struct compile_state *state,
17282 struct triple *ins, FILE *fp)
17284 struct triple *dst, *src;
17287 if (is_const(src) && (src->op == OP_INTCONST)) {
17289 value = (long_t)(src->u.cval);
17290 fprintf(fp, "\tmov%s $%ld, (%s)\n",
17291 type_suffix(state, src->type),
17293 reg(state, dst, REGCM_GPR32));
17295 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
17296 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
17297 type_suffix(state, src->type),
17298 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
17302 if (is_const(src) || is_const(dst)) {
17303 internal_error(state, ins, "unknown store operation");
17305 fprintf(fp, "\tmov%s %s, (%s)\n",
17306 type_suffix(state, src->type),
17307 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
17308 reg(state, dst, REGCM_GPR32));
17314 static void print_op_smul(struct compile_state *state,
17315 struct triple *ins, FILE *fp)
17317 if (!is_const(RHS(ins, 1))) {
17318 fprintf(fp, "\timul %s, %s\n",
17319 reg(state, RHS(ins, 1), REGCM_GPR32),
17320 reg(state, RHS(ins, 0), REGCM_GPR32));
17323 fprintf(fp, "\timul ");
17324 print_const_val(state, RHS(ins, 1), fp);
17325 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
17329 static void print_op_cmp(struct compile_state *state,
17330 struct triple *ins, FILE *fp)
17334 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17335 dreg = check_reg(state, ins, REGCM_FLAGS);
17336 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
17337 internal_error(state, ins, "bad dest register for cmp");
17339 if (is_const(RHS(ins, 1))) {
17340 fprintf(fp, "\tcmp ");
17341 print_const_val(state, RHS(ins, 1), fp);
17342 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
17345 unsigned lmask, rmask;
17347 lreg = check_reg(state, RHS(ins, 0), mask);
17348 rreg = check_reg(state, RHS(ins, 1), mask);
17349 lmask = arch_reg_regcm(state, lreg);
17350 rmask = arch_reg_regcm(state, rreg);
17351 mask = lmask & rmask;
17352 fprintf(fp, "\tcmp %s, %s\n",
17353 reg(state, RHS(ins, 1), mask),
17354 reg(state, RHS(ins, 0), mask));
17358 static void print_op_test(struct compile_state *state,
17359 struct triple *ins, FILE *fp)
17362 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17363 fprintf(fp, "\ttest %s, %s\n",
17364 reg(state, RHS(ins, 0), mask),
17365 reg(state, RHS(ins, 0), mask));
17368 static void print_op_branch(struct compile_state *state,
17369 struct triple *branch, FILE *fp)
17371 const char *bop = "j";
17372 if (branch->op == OP_JMP) {
17373 if (TRIPLE_RHS(branch->sizes) != 0) {
17374 internal_error(state, branch, "jmp with condition?");
17379 struct triple *ptr;
17380 if (TRIPLE_RHS(branch->sizes) != 1) {
17381 internal_error(state, branch, "jmpcc without condition?");
17383 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
17384 if ((RHS(branch, 0)->op != OP_CMP) &&
17385 (RHS(branch, 0)->op != OP_TEST)) {
17386 internal_error(state, branch, "bad branch test");
17388 #warning "FIXME I have observed instructions between the test and branch instructions"
17389 ptr = RHS(branch, 0);
17390 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
17391 if (ptr->op != OP_COPY) {
17392 internal_error(state, branch, "branch does not follow test");
17395 switch(branch->op) {
17396 case OP_JMP_EQ: bop = "jz"; break;
17397 case OP_JMP_NOTEQ: bop = "jnz"; break;
17398 case OP_JMP_SLESS: bop = "jl"; break;
17399 case OP_JMP_ULESS: bop = "jb"; break;
17400 case OP_JMP_SMORE: bop = "jg"; break;
17401 case OP_JMP_UMORE: bop = "ja"; break;
17402 case OP_JMP_SLESSEQ: bop = "jle"; break;
17403 case OP_JMP_ULESSEQ: bop = "jbe"; break;
17404 case OP_JMP_SMOREEQ: bop = "jge"; break;
17405 case OP_JMP_UMOREEQ: bop = "jae"; break;
17407 internal_error(state, branch, "Invalid branch op");
17412 fprintf(fp, "\t%s L%s%lu\n",
17414 state->label_prefix,
17415 TARG(branch, 0)->u.cval);
17418 static void print_op_set(struct compile_state *state,
17419 struct triple *set, FILE *fp)
17421 const char *sop = "set";
17422 if (TRIPLE_RHS(set->sizes) != 1) {
17423 internal_error(state, set, "setcc without condition?");
17425 check_reg(state, RHS(set, 0), REGCM_FLAGS);
17426 if ((RHS(set, 0)->op != OP_CMP) &&
17427 (RHS(set, 0)->op != OP_TEST)) {
17428 internal_error(state, set, "bad set test");
17430 if (RHS(set, 0)->next != set) {
17431 internal_error(state, set, "set does not follow test");
17434 case OP_SET_EQ: sop = "setz"; break;
17435 case OP_SET_NOTEQ: sop = "setnz"; break;
17436 case OP_SET_SLESS: sop = "setl"; break;
17437 case OP_SET_ULESS: sop = "setb"; break;
17438 case OP_SET_SMORE: sop = "setg"; break;
17439 case OP_SET_UMORE: sop = "seta"; break;
17440 case OP_SET_SLESSEQ: sop = "setle"; break;
17441 case OP_SET_ULESSEQ: sop = "setbe"; break;
17442 case OP_SET_SMOREEQ: sop = "setge"; break;
17443 case OP_SET_UMOREEQ: sop = "setae"; break;
17445 internal_error(state, set, "Invalid set op");
17448 fprintf(fp, "\t%s %s\n",
17449 sop, reg(state, set, REGCM_GPR8_LO));
17452 static void print_op_bit_scan(struct compile_state *state,
17453 struct triple *ins, FILE *fp)
17457 case OP_BSF: op = "bsf"; break;
17458 case OP_BSR: op = "bsr"; break;
17460 internal_error(state, ins, "unknown bit scan");
17470 reg(state, RHS(ins, 0), REGCM_GPR32),
17471 reg(state, ins, REGCM_GPR32),
17472 reg(state, ins, REGCM_GPR32));
17476 static void print_sdecl(struct compile_state *state,
17477 struct triple *ins, FILE *fp)
17479 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
17480 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
17481 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17482 print_const(state, MISC(ins, 0), fp);
17483 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17487 static void print_instruction(struct compile_state *state,
17488 struct triple *ins, FILE *fp)
17490 /* Assumption: after I have exted the register allocator
17491 * everything is in a valid register.
17495 print_op_asm(state, ins, fp);
17497 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
17498 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
17499 case OP_AND: print_binary_op(state, "and", ins, fp); break;
17500 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
17501 case OP_OR: print_binary_op(state, "or", ins, fp); break;
17502 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
17503 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
17504 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
17505 case OP_POS: break;
17506 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
17507 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
17511 /* Don't generate anything here for constants */
17513 /* Don't generate anything for variable declarations. */
17516 print_sdecl(state, ins, fp);
17519 print_op_move(state, ins, fp);
17522 print_op_load(state, ins, fp);
17525 print_op_store(state, ins, fp);
17528 print_op_smul(state, ins, fp);
17530 case OP_CMP: print_op_cmp(state, ins, fp); break;
17531 case OP_TEST: print_op_test(state, ins, fp); break;
17533 case OP_JMP_EQ: case OP_JMP_NOTEQ:
17534 case OP_JMP_SLESS: case OP_JMP_ULESS:
17535 case OP_JMP_SMORE: case OP_JMP_UMORE:
17536 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
17537 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
17538 print_op_branch(state, ins, fp);
17540 case OP_SET_EQ: case OP_SET_NOTEQ:
17541 case OP_SET_SLESS: case OP_SET_ULESS:
17542 case OP_SET_SMORE: case OP_SET_UMORE:
17543 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
17544 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
17545 print_op_set(state, ins, fp);
17547 case OP_INB: case OP_INW: case OP_INL:
17548 print_op_in(state, ins, fp);
17550 case OP_OUTB: case OP_OUTW: case OP_OUTL:
17551 print_op_out(state, ins, fp);
17555 print_op_bit_scan(state, ins, fp);
17558 after_lhs(state, ins);
17559 fprintf(fp, "\trdmsr\n");
17562 fprintf(fp, "\twrmsr\n");
17565 fprintf(fp, "\thlt\n");
17568 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17571 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17574 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17580 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17582 /* Ignore OP_PIECE */
17585 /* Operations that should never get here */
17586 case OP_SDIV: case OP_UDIV:
17587 case OP_SMOD: case OP_UMOD:
17588 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
17589 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
17590 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
17592 internal_error(state, ins, "unknown op: %d %s",
17593 ins->op, tops(ins->op));
17598 static void print_instructions(struct compile_state *state)
17600 struct triple *first, *ins;
17601 int print_location;
17602 struct occurance *last_occurance;
17604 int max_inline_depth;
17605 max_inline_depth = 0;
17606 print_location = 1;
17607 last_occurance = 0;
17608 fp = state->output;
17609 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17610 first = RHS(state->main_function, 0);
17613 if (print_location &&
17614 last_occurance != ins->occurance) {
17615 if (!ins->occurance->parent) {
17616 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17617 ins->occurance->function,
17618 ins->occurance->filename,
17619 ins->occurance->line,
17620 ins->occurance->col);
17623 struct occurance *ptr;
17625 fprintf(fp, "\t/*\n");
17627 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17629 fprintf(fp, "\t * %s,%s:%d.%d\n",
17635 fprintf(fp, "\t */\n");
17636 if (inline_depth > max_inline_depth) {
17637 max_inline_depth = inline_depth;
17640 if (last_occurance) {
17641 put_occurance(last_occurance);
17643 get_occurance(ins->occurance);
17644 last_occurance = ins->occurance;
17647 print_instruction(state, ins, fp);
17649 } while(ins != first);
17650 if (print_location) {
17651 fprintf(fp, "/* max inline depth %d */\n",
17656 static void generate_code(struct compile_state *state)
17658 generate_local_labels(state);
17659 print_instructions(state);
17663 static void print_tokens(struct compile_state *state)
17666 tk = &state->token[0];
17671 next_token(state, 0);
17673 loc(stdout, state, 0);
17674 printf("%s <- `%s'\n",
17676 tk->ident ? tk->ident->name :
17677 tk->str_len ? tk->val.str : "");
17679 } while(tk->tok != TOK_EOF);
17682 static void compile(const char *filename, const char *ofilename,
17683 int cpu, int debug, int opt, const char *label_prefix)
17686 struct compile_state state;
17687 memset(&state, 0, sizeof(state));
17689 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17690 memset(&state.token[i], 0, sizeof(state.token[i]));
17691 state.token[i].tok = -1;
17693 /* Remember the debug settings */
17695 state.debug = debug;
17696 state.optimize = opt;
17697 /* Remember the output filename */
17698 state.ofilename = ofilename;
17699 state.output = fopen(state.ofilename, "w");
17700 if (!state.output) {
17701 error(&state, 0, "Cannot open output file %s\n",
17704 /* Remember the label prefix */
17705 state.label_prefix = label_prefix;
17706 /* Prep the preprocessor */
17707 state.if_depth = 0;
17708 state.if_value = 0;
17709 /* register the C keywords */
17710 register_keywords(&state);
17711 /* register the keywords the macro preprocessor knows */
17712 register_macro_keywords(&state);
17713 /* Memorize where some special keywords are. */
17714 state.i_continue = lookup(&state, "continue", 8);
17715 state.i_break = lookup(&state, "break", 5);
17716 /* Enter the globl definition scope */
17717 start_scope(&state);
17718 register_builtins(&state);
17719 compile_file(&state, filename, 1);
17721 print_tokens(&state);
17724 /* Exit the global definition scope */
17727 /* Now that basic compilation has happened
17728 * optimize the intermediate code
17732 generate_code(&state);
17734 fprintf(stderr, "done\n");
17738 static void version(void)
17740 printf("romcc " VERSION " released " RELEASE_DATE "\n");
17743 static void usage(void)
17747 "Usage: romcc <source>.c\n"
17748 "Compile a C source file without using ram\n"
17752 static void arg_error(char *fmt, ...)
17755 va_start(args, fmt);
17756 vfprintf(stderr, fmt, args);
17762 int main(int argc, char **argv)
17764 const char *filename;
17765 const char *ofilename;
17766 const char *label_prefix;
17773 ofilename = "auto.inc";
17777 while((argc > 1) && (argc != last_argc)) {
17779 if (strncmp(argv[1], "--debug=", 8) == 0) {
17780 debug = atoi(argv[1] + 8);
17784 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17785 label_prefix= argv[1] + 15;
17789 else if ((strcmp(argv[1],"-O") == 0) ||
17790 (strcmp(argv[1], "-O1") == 0)) {
17795 else if (strcmp(argv[1],"-O2") == 0) {
17800 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17801 ofilename = argv[2];
17805 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17806 cpu = arch_encode_cpu(argv[1] + 6);
17807 if (cpu == BAD_CPU) {
17808 arg_error("Invalid cpu specified: %s\n",
17816 arg_error("Wrong argument count %d\n", argc);
17818 filename = argv[1];
17819 compile(filename, ofilename, cpu, debug, optimize, label_prefix);