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) & 0x0f)
672 #define TRIPLE_MISC(SIZES) (((SIZES) >> 8) & 0x0f)
673 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
674 #define TRIPLE_SIZE(SIZES) \
675 ((((SIZES) >> 0) & 0x0f) + \
676 (((SIZES) >> 4) & 0x0f) + \
677 (((SIZES) >> 8) & 0x0f) + \
678 (((SIZES) >> 12) & 0x0f))
679 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
680 ((((LHS) & 0x0f) << 0) | \
681 (((RHS) & 0x0f) << 4) | \
682 (((MISC) & 0x0f) << 8) | \
683 (((TARG) & 0x0f) << 12))
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)
1341 int lhs, rhs, misc, targ;
1342 valid_op(state, op);
1343 lhs = table_ops[op].lhs;
1344 rhs = table_ops[op].rhs;
1345 misc = table_ops[op].misc;
1346 targ = table_ops[op].targ;
1349 if (op == OP_CALL) {
1352 param = type->right;
1353 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1355 param = param->right;
1357 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1361 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1362 lhs = type->left->elements;
1365 else if (op == OP_VAL_VEC) {
1366 rhs = type->elements;
1368 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1371 else if (op == OP_ASM) {
1375 if ((rhs < 0) || (rhs > MAX_RHS)) {
1376 internal_error(state, 0, "bad rhs");
1378 if ((lhs < 0) || (lhs > MAX_LHS)) {
1379 internal_error(state, 0, "bad lhs");
1381 if ((misc < 0) || (misc > MAX_MISC)) {
1382 internal_error(state, 0, "bad misc");
1384 if ((targ < 0) || (targ > MAX_TARG)) {
1385 internal_error(state, 0, "bad targs");
1387 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1390 static struct triple *alloc_triple(struct compile_state *state,
1391 int op, struct type *type, int lhs, int rhs,
1392 struct occurance *occurance)
1394 size_t size, sizes, extra_count, min_count;
1396 sizes = triple_sizes(state, op, type, lhs, rhs);
1398 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1399 extra_count = TRIPLE_SIZE(sizes);
1400 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1402 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1403 ret = xcmalloc(size, "tripple");
1409 ret->occurance = occurance;
1413 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1416 int src_lhs, src_rhs, src_size;
1417 src_lhs = TRIPLE_LHS(src->sizes);
1418 src_rhs = TRIPLE_RHS(src->sizes);
1419 src_size = TRIPLE_SIZE(src->sizes);
1420 get_occurance(src->occurance);
1421 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1423 memcpy(dup, src, sizeof(*src));
1424 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1428 static struct triple *new_triple(struct compile_state *state,
1429 int op, struct type *type, int lhs, int rhs)
1432 struct occurance *occurance;
1433 occurance = new_occurance(state);
1434 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1438 static struct triple *build_triple(struct compile_state *state,
1439 int op, struct type *type, struct triple *left, struct triple *right,
1440 struct occurance *occurance)
1444 ret = alloc_triple(state, op, type, -1, -1, occurance);
1445 count = TRIPLE_SIZE(ret->sizes);
1447 ret->param[0] = left;
1450 ret->param[1] = right;
1455 static struct triple *triple(struct compile_state *state,
1456 int op, struct type *type, struct triple *left, struct triple *right)
1460 ret = new_triple(state, op, type, -1, -1);
1461 count = TRIPLE_SIZE(ret->sizes);
1463 ret->param[0] = left;
1466 ret->param[1] = right;
1471 static struct triple *branch(struct compile_state *state,
1472 struct triple *targ, struct triple *test)
1475 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1479 TARG(ret, 0) = targ;
1480 /* record the branch target was used */
1481 if (!targ || (targ->op != OP_LABEL)) {
1482 internal_error(state, 0, "branch not to label");
1483 use_triple(targ, ret);
1489 static void insert_triple(struct compile_state *state,
1490 struct triple *first, struct triple *ptr)
1493 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1494 internal_error(state, ptr, "expression already used");
1497 ptr->prev = first->prev;
1498 ptr->prev->next = ptr;
1499 ptr->next->prev = ptr;
1500 if ((ptr->prev->op == OP_BRANCH) &&
1501 TRIPLE_RHS(ptr->prev->sizes)) {
1502 unuse_triple(first, ptr->prev);
1503 use_triple(ptr, ptr->prev);
1508 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1510 /* This function is used to determine if u.block
1511 * is utilized to store the current block number.
1514 valid_ins(state, ins);
1515 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1516 return stores_block;
1519 static struct block *block_of_triple(struct compile_state *state,
1522 struct triple *first;
1523 first = RHS(state->main_function, 0);
1524 while(ins != first && !triple_stores_block(state, ins)) {
1525 if (ins == ins->prev) {
1526 internal_error(state, 0, "ins == ins->prev?");
1530 if (!triple_stores_block(state, ins)) {
1531 internal_error(state, ins, "Cannot find block");
1533 return ins->u.block;
1536 static struct triple *pre_triple(struct compile_state *state,
1537 struct triple *base,
1538 int op, struct type *type, struct triple *left, struct triple *right)
1540 struct block *block;
1542 /* If I am an OP_PIECE jump to the real instruction */
1543 if (base->op == OP_PIECE) {
1544 base = MISC(base, 0);
1546 block = block_of_triple(state, base);
1547 get_occurance(base->occurance);
1548 ret = build_triple(state, op, type, left, right, base->occurance);
1549 if (triple_stores_block(state, ret)) {
1550 ret->u.block = block;
1552 insert_triple(state, base, ret);
1553 if (block->first == base) {
1559 static struct triple *post_triple(struct compile_state *state,
1560 struct triple *base,
1561 int op, struct type *type, struct triple *left, struct triple *right)
1563 struct block *block;
1566 /* If I am an OP_PIECE jump to the real instruction */
1567 if (base->op == OP_PIECE) {
1568 base = MISC(base, 0);
1570 /* If I have a left hand side skip over it */
1571 zlhs = TRIPLE_LHS(base->sizes);
1573 base = LHS(base, zlhs - 1);
1576 block = block_of_triple(state, base);
1577 get_occurance(base->occurance);
1578 ret = build_triple(state, op, type, left, right, base->occurance);
1579 if (triple_stores_block(state, ret)) {
1580 ret->u.block = block;
1582 insert_triple(state, base->next, ret);
1583 if (block->last == base) {
1589 static struct triple *label(struct compile_state *state)
1591 /* Labels don't get a type */
1592 struct triple *result;
1593 result = triple(state, OP_LABEL, &void_type, 0, 0);
1597 static void display_triple(FILE *fp, struct triple *ins)
1599 struct occurance *ptr;
1603 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1606 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1609 reg = arch_reg_str(ID_REG(ins->id));
1610 if (ins->op == OP_INTCONST) {
1611 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx> ",
1612 ins, pre, post, reg, ins->template_id, tops(ins->op),
1615 else if (ins->op == OP_ADDRCONST) {
1616 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1617 ins, pre, post, reg, ins->template_id, tops(ins->op),
1618 MISC(ins, 0), ins->u.cval);
1622 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s",
1623 ins, pre, post, reg, ins->template_id, tops(ins->op));
1624 count = TRIPLE_SIZE(ins->sizes);
1625 for(i = 0; i < count; i++) {
1626 fprintf(fp, " %-10p", ins->param[i]);
1633 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1634 fprintf(fp, " %s,%s:%d.%d",
1643 struct triple_set *user;
1644 for(user = ptr->use; user; user = user->next) {
1645 fprintf(fp, "use: %p\n", user->member);
1652 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1654 /* Does the triple have no side effects.
1655 * I.e. Rexecuting the triple with the same arguments
1656 * gives the same value.
1659 valid_ins(state, ins);
1660 pure = PURE_BITS(table_ops[ins->op].flags);
1661 if ((pure != PURE) && (pure != IMPURE)) {
1662 internal_error(state, 0, "Purity of %s not known\n",
1665 return pure == PURE;
1668 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1670 /* This function is used to determine which triples need
1674 valid_ins(state, ins);
1675 is_branch = (table_ops[ins->op].targ != 0);
1679 static int triple_is_cond_branch(struct compile_state *state, struct triple *ins)
1681 /* A conditional branch has the condition argument as a single
1684 return triple_is_branch(state, ins) &&
1685 (TRIPLE_RHS(ins->sizes) == 1);
1688 static int triple_is_uncond_branch(struct compile_state *state, struct triple *ins)
1690 /* A unconditional branch has no RHS parameters.
1692 return triple_is_branch(state, ins) &&
1693 (TRIPLE_RHS(ins->sizes) == 0);
1696 static int triple_is_def(struct compile_state *state, struct triple *ins)
1698 /* This function is used to determine which triples need
1702 valid_ins(state, ins);
1703 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1707 static struct triple **triple_iter(struct compile_state *state,
1708 size_t count, struct triple **vector,
1709 struct triple *ins, struct triple **last)
1711 struct triple **ret;
1717 else if ((last >= vector) && (last < (vector + count - 1))) {
1725 static struct triple **triple_lhs(struct compile_state *state,
1726 struct triple *ins, struct triple **last)
1728 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1732 static struct triple **triple_rhs(struct compile_state *state,
1733 struct triple *ins, struct triple **last)
1735 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1739 static struct triple **triple_misc(struct compile_state *state,
1740 struct triple *ins, struct triple **last)
1742 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1746 static struct triple **triple_targ(struct compile_state *state,
1747 struct triple *ins, struct triple **last)
1750 struct triple **ret, **vector;
1752 count = TRIPLE_TARG(ins->sizes);
1753 vector = &TARG(ins, 0);
1758 else if ((last >= vector) && (last < (vector + count - 1))) {
1761 else if ((last == (vector + count - 1)) &&
1762 TRIPLE_RHS(ins->sizes)) {
1770 static void verify_use(struct compile_state *state,
1771 struct triple *user, struct triple *used)
1774 size = TRIPLE_SIZE(user->sizes);
1775 for(i = 0; i < size; i++) {
1776 if (user->param[i] == used) {
1780 if (triple_is_branch(state, user)) {
1781 if (user->next == used) {
1786 internal_error(state, user, "%s(%p) does not use %s(%p)",
1787 tops(user->op), user, tops(used->op), used);
1791 static int find_rhs_use(struct compile_state *state,
1792 struct triple *user, struct triple *used)
1794 struct triple **param;
1796 verify_use(state, user, used);
1797 size = TRIPLE_RHS(user->sizes);
1798 param = &RHS(user, 0);
1799 for(i = 0; i < size; i++) {
1800 if (param[i] == used) {
1807 static void free_triple(struct compile_state *state, struct triple *ptr)
1810 size = sizeof(*ptr) - sizeof(ptr->param) +
1811 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1812 ptr->prev->next = ptr->next;
1813 ptr->next->prev = ptr->prev;
1815 internal_error(state, ptr, "ptr->use != 0");
1817 put_occurance(ptr->occurance);
1818 memset(ptr, -1, size);
1822 static void release_triple(struct compile_state *state, struct triple *ptr)
1824 struct triple_set *set, *next;
1825 struct triple **expr;
1826 /* Remove ptr from use chains where it is the user */
1827 expr = triple_rhs(state, ptr, 0);
1828 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1830 unuse_triple(*expr, ptr);
1833 expr = triple_lhs(state, ptr, 0);
1834 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1836 unuse_triple(*expr, ptr);
1839 expr = triple_misc(state, ptr, 0);
1840 for(; expr; expr = triple_misc(state, ptr, expr)) {
1842 unuse_triple(*expr, ptr);
1845 expr = triple_targ(state, ptr, 0);
1846 for(; expr; expr = triple_targ(state, ptr, expr)) {
1848 unuse_triple(*expr, ptr);
1851 /* Reomve ptr from use chains where it is used */
1852 for(set = ptr->use; set; set = next) {
1854 expr = triple_rhs(state, set->member, 0);
1855 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1857 *expr = &zero_triple;
1860 expr = triple_lhs(state, set->member, 0);
1861 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1863 *expr = &zero_triple;
1866 expr = triple_misc(state, set->member, 0);
1867 for(; expr; expr = triple_misc(state, set->member, expr)) {
1869 *expr = &zero_triple;
1872 expr = triple_targ(state, set->member, 0);
1873 for(; expr; expr = triple_targ(state, set->member, expr)) {
1875 *expr = &zero_triple;
1878 unuse_triple(ptr, set->member);
1880 free_triple(state, ptr);
1883 static void print_triple(struct compile_state *state, struct triple *ptr);
1885 #define TOK_UNKNOWN 0
1888 #define TOK_LBRACE 3
1889 #define TOK_RBRACE 4
1893 #define TOK_LBRACKET 8
1894 #define TOK_RBRACKET 9
1895 #define TOK_LPAREN 10
1896 #define TOK_RPAREN 11
1901 #define TOK_TIMESEQ 16
1902 #define TOK_DIVEQ 17
1903 #define TOK_MODEQ 18
1904 #define TOK_PLUSEQ 19
1905 #define TOK_MINUSEQ 20
1908 #define TOK_ANDEQ 23
1909 #define TOK_XOREQ 24
1912 #define TOK_NOTEQ 27
1913 #define TOK_QUEST 28
1914 #define TOK_LOGOR 29
1915 #define TOK_LOGAND 30
1919 #define TOK_LESSEQ 34
1920 #define TOK_MOREEQ 35
1924 #define TOK_MINUS 39
1927 #define TOK_PLUSPLUS 42
1928 #define TOK_MINUSMINUS 43
1930 #define TOK_ARROW 45
1932 #define TOK_TILDE 47
1933 #define TOK_LIT_STRING 48
1934 #define TOK_LIT_CHAR 49
1935 #define TOK_LIT_INT 50
1936 #define TOK_LIT_FLOAT 51
1937 #define TOK_MACRO 52
1938 #define TOK_CONCATENATE 53
1940 #define TOK_IDENT 54
1941 #define TOK_STRUCT_NAME 55
1942 #define TOK_ENUM_CONST 56
1943 #define TOK_TYPE_NAME 57
1946 #define TOK_BREAK 59
1949 #define TOK_CONST 62
1950 #define TOK_CONTINUE 63
1951 #define TOK_DEFAULT 64
1953 #define TOK_DOUBLE 66
1956 #define TOK_EXTERN 69
1957 #define TOK_FLOAT 70
1961 #define TOK_INLINE 74
1964 #define TOK_REGISTER 77
1965 #define TOK_RESTRICT 78
1966 #define TOK_RETURN 79
1967 #define TOK_SHORT 80
1968 #define TOK_SIGNED 81
1969 #define TOK_SIZEOF 82
1970 #define TOK_STATIC 83
1971 #define TOK_STRUCT 84
1972 #define TOK_SWITCH 85
1973 #define TOK_TYPEDEF 86
1974 #define TOK_UNION 87
1975 #define TOK_UNSIGNED 88
1977 #define TOK_VOLATILE 90
1978 #define TOK_WHILE 91
1980 #define TOK_ATTRIBUTE 93
1981 #define TOK_ALIGNOF 94
1982 #define TOK_FIRST_KEYWORD TOK_AUTO
1983 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1985 #define TOK_DEFINE 100
1986 #define TOK_UNDEF 101
1987 #define TOK_INCLUDE 102
1988 #define TOK_LINE 103
1989 #define TOK_ERROR 104
1990 #define TOK_WARNING 105
1991 #define TOK_PRAGMA 106
1992 #define TOK_IFDEF 107
1993 #define TOK_IFNDEF 108
1994 #define TOK_ELIF 109
1995 #define TOK_ENDIF 110
1997 #define TOK_FIRST_MACRO TOK_DEFINE
1998 #define TOK_LAST_MACRO TOK_ENDIF
2002 static const char *tokens[] = {
2003 [TOK_UNKNOWN ] = "unknown",
2004 [TOK_SPACE ] = ":space:",
2006 [TOK_LBRACE ] = "{",
2007 [TOK_RBRACE ] = "}",
2011 [TOK_LBRACKET ] = "[",
2012 [TOK_RBRACKET ] = "]",
2013 [TOK_LPAREN ] = "(",
2014 [TOK_RPAREN ] = ")",
2016 [TOK_DOTS ] = "...",
2019 [TOK_TIMESEQ ] = "*=",
2020 [TOK_DIVEQ ] = "/=",
2021 [TOK_MODEQ ] = "%=",
2022 [TOK_PLUSEQ ] = "+=",
2023 [TOK_MINUSEQ ] = "-=",
2024 [TOK_SLEQ ] = "<<=",
2025 [TOK_SREQ ] = ">>=",
2026 [TOK_ANDEQ ] = "&=",
2027 [TOK_XOREQ ] = "^=",
2030 [TOK_NOTEQ ] = "!=",
2032 [TOK_LOGOR ] = "||",
2033 [TOK_LOGAND ] = "&&",
2037 [TOK_LESSEQ ] = "<=",
2038 [TOK_MOREEQ ] = ">=",
2045 [TOK_PLUSPLUS ] = "++",
2046 [TOK_MINUSMINUS ] = "--",
2048 [TOK_ARROW ] = "->",
2051 [TOK_LIT_STRING ] = ":string:",
2052 [TOK_IDENT ] = ":ident:",
2053 [TOK_TYPE_NAME ] = ":typename:",
2054 [TOK_LIT_CHAR ] = ":char:",
2055 [TOK_LIT_INT ] = ":integer:",
2056 [TOK_LIT_FLOAT ] = ":float:",
2058 [TOK_CONCATENATE ] = "##",
2060 [TOK_AUTO ] = "auto",
2061 [TOK_BREAK ] = "break",
2062 [TOK_CASE ] = "case",
2063 [TOK_CHAR ] = "char",
2064 [TOK_CONST ] = "const",
2065 [TOK_CONTINUE ] = "continue",
2066 [TOK_DEFAULT ] = "default",
2068 [TOK_DOUBLE ] = "double",
2069 [TOK_ELSE ] = "else",
2070 [TOK_ENUM ] = "enum",
2071 [TOK_EXTERN ] = "extern",
2072 [TOK_FLOAT ] = "float",
2074 [TOK_GOTO ] = "goto",
2076 [TOK_INLINE ] = "inline",
2078 [TOK_LONG ] = "long",
2079 [TOK_REGISTER ] = "register",
2080 [TOK_RESTRICT ] = "restrict",
2081 [TOK_RETURN ] = "return",
2082 [TOK_SHORT ] = "short",
2083 [TOK_SIGNED ] = "signed",
2084 [TOK_SIZEOF ] = "sizeof",
2085 [TOK_STATIC ] = "static",
2086 [TOK_STRUCT ] = "struct",
2087 [TOK_SWITCH ] = "switch",
2088 [TOK_TYPEDEF ] = "typedef",
2089 [TOK_UNION ] = "union",
2090 [TOK_UNSIGNED ] = "unsigned",
2091 [TOK_VOID ] = "void",
2092 [TOK_VOLATILE ] = "volatile",
2093 [TOK_WHILE ] = "while",
2095 [TOK_ATTRIBUTE ] = "__attribute__",
2096 [TOK_ALIGNOF ] = "__alignof__",
2098 [TOK_DEFINE ] = "define",
2099 [TOK_UNDEF ] = "undef",
2100 [TOK_INCLUDE ] = "include",
2101 [TOK_LINE ] = "line",
2102 [TOK_ERROR ] = "error",
2103 [TOK_WARNING ] = "warning",
2104 [TOK_PRAGMA ] = "pragma",
2105 [TOK_IFDEF ] = "ifdef",
2106 [TOK_IFNDEF ] = "ifndef",
2107 [TOK_ELIF ] = "elif",
2108 [TOK_ENDIF ] = "endif",
2113 static unsigned int hash(const char *str, int str_len)
2117 end = str + str_len;
2119 for(; str < end; str++) {
2120 hash = (hash *263) + *str;
2122 hash = hash & (HASH_TABLE_SIZE -1);
2126 static struct hash_entry *lookup(
2127 struct compile_state *state, const char *name, int name_len)
2129 struct hash_entry *entry;
2131 index = hash(name, name_len);
2132 entry = state->hash_table[index];
2134 ((entry->name_len != name_len) ||
2135 (memcmp(entry->name, name, name_len) != 0))) {
2136 entry = entry->next;
2140 /* Get a private copy of the name */
2141 new_name = xmalloc(name_len + 1, "hash_name");
2142 memcpy(new_name, name, name_len);
2143 new_name[name_len] = '\0';
2145 /* Create a new hash entry */
2146 entry = xcmalloc(sizeof(*entry), "hash_entry");
2147 entry->next = state->hash_table[index];
2148 entry->name = new_name;
2149 entry->name_len = name_len;
2151 /* Place the new entry in the hash table */
2152 state->hash_table[index] = entry;
2157 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2159 struct hash_entry *entry;
2161 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2162 (entry->tok == TOK_ENUM_CONST) ||
2163 ((entry->tok >= TOK_FIRST_KEYWORD) &&
2164 (entry->tok <= TOK_LAST_KEYWORD)))) {
2165 tk->tok = entry->tok;
2169 static void ident_to_macro(struct compile_state *state, struct token *tk)
2171 struct hash_entry *entry;
2174 (entry->tok >= TOK_FIRST_MACRO) &&
2175 (entry->tok <= TOK_LAST_MACRO)) {
2176 tk->tok = entry->tok;
2180 static void hash_keyword(
2181 struct compile_state *state, const char *keyword, int tok)
2183 struct hash_entry *entry;
2184 entry = lookup(state, keyword, strlen(keyword));
2185 if (entry && entry->tok != TOK_UNKNOWN) {
2186 die("keyword %s already hashed", keyword);
2192 struct compile_state *state, struct hash_entry *ident,
2193 struct symbol **chain, struct triple *def, struct type *type)
2196 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2197 error(state, 0, "%s already defined", ident->name);
2199 sym = xcmalloc(sizeof(*sym), "symbol");
2203 sym->scope_depth = state->scope_depth;
2208 static void label_symbol(struct compile_state *state,
2209 struct hash_entry *ident, struct triple *label)
2212 if (ident->sym_label) {
2213 error(state, 0, "label %s already defined", ident->name);
2215 sym = xcmalloc(sizeof(*sym), "label");
2218 sym->type = &void_type;
2219 sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2221 ident->sym_label = sym;
2224 static void start_scope(struct compile_state *state)
2226 state->scope_depth++;
2229 static void end_scope_syms(struct symbol **chain, int depth)
2231 struct symbol *sym, *next;
2233 while(sym && (sym->scope_depth == depth)) {
2241 static void end_scope(struct compile_state *state)
2245 /* Walk through the hash table and remove all symbols
2246 * in the current scope.
2248 depth = state->scope_depth;
2249 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2250 struct hash_entry *entry;
2251 entry = state->hash_table[i];
2253 end_scope_syms(&entry->sym_label, depth);
2254 end_scope_syms(&entry->sym_struct, depth);
2255 end_scope_syms(&entry->sym_ident, depth);
2256 entry = entry->next;
2259 state->scope_depth = depth - 1;
2262 static void register_keywords(struct compile_state *state)
2264 hash_keyword(state, "auto", TOK_AUTO);
2265 hash_keyword(state, "break", TOK_BREAK);
2266 hash_keyword(state, "case", TOK_CASE);
2267 hash_keyword(state, "char", TOK_CHAR);
2268 hash_keyword(state, "const", TOK_CONST);
2269 hash_keyword(state, "continue", TOK_CONTINUE);
2270 hash_keyword(state, "default", TOK_DEFAULT);
2271 hash_keyword(state, "do", TOK_DO);
2272 hash_keyword(state, "double", TOK_DOUBLE);
2273 hash_keyword(state, "else", TOK_ELSE);
2274 hash_keyword(state, "enum", TOK_ENUM);
2275 hash_keyword(state, "extern", TOK_EXTERN);
2276 hash_keyword(state, "float", TOK_FLOAT);
2277 hash_keyword(state, "for", TOK_FOR);
2278 hash_keyword(state, "goto", TOK_GOTO);
2279 hash_keyword(state, "if", TOK_IF);
2280 hash_keyword(state, "inline", TOK_INLINE);
2281 hash_keyword(state, "int", TOK_INT);
2282 hash_keyword(state, "long", TOK_LONG);
2283 hash_keyword(state, "register", TOK_REGISTER);
2284 hash_keyword(state, "restrict", TOK_RESTRICT);
2285 hash_keyword(state, "return", TOK_RETURN);
2286 hash_keyword(state, "short", TOK_SHORT);
2287 hash_keyword(state, "signed", TOK_SIGNED);
2288 hash_keyword(state, "sizeof", TOK_SIZEOF);
2289 hash_keyword(state, "static", TOK_STATIC);
2290 hash_keyword(state, "struct", TOK_STRUCT);
2291 hash_keyword(state, "switch", TOK_SWITCH);
2292 hash_keyword(state, "typedef", TOK_TYPEDEF);
2293 hash_keyword(state, "union", TOK_UNION);
2294 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2295 hash_keyword(state, "void", TOK_VOID);
2296 hash_keyword(state, "volatile", TOK_VOLATILE);
2297 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2298 hash_keyword(state, "while", TOK_WHILE);
2299 hash_keyword(state, "asm", TOK_ASM);
2300 hash_keyword(state, "__asm__", TOK_ASM);
2301 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2302 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2305 static void register_macro_keywords(struct compile_state *state)
2307 hash_keyword(state, "define", TOK_DEFINE);
2308 hash_keyword(state, "undef", TOK_UNDEF);
2309 hash_keyword(state, "include", TOK_INCLUDE);
2310 hash_keyword(state, "line", TOK_LINE);
2311 hash_keyword(state, "error", TOK_ERROR);
2312 hash_keyword(state, "warning", TOK_WARNING);
2313 hash_keyword(state, "pragma", TOK_PRAGMA);
2314 hash_keyword(state, "ifdef", TOK_IFDEF);
2315 hash_keyword(state, "ifndef", TOK_IFNDEF);
2316 hash_keyword(state, "elif", TOK_ELIF);
2317 hash_keyword(state, "endif", TOK_ENDIF);
2320 static int spacep(int c)
2336 static int digitp(int c)
2340 case '0': case '1': case '2': case '3': case '4':
2341 case '5': case '6': case '7': case '8': case '9':
2347 static int digval(int c)
2350 if ((c >= '0') && (c <= '9')) {
2356 static int hexdigitp(int c)
2360 case '0': case '1': case '2': case '3': case '4':
2361 case '5': case '6': case '7': case '8': case '9':
2362 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2363 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2369 static int hexdigval(int c)
2372 if ((c >= '0') && (c <= '9')) {
2375 else if ((c >= 'A') && (c <= 'F')) {
2376 val = 10 + (c - 'A');
2378 else if ((c >= 'a') && (c <= 'f')) {
2379 val = 10 + (c - 'a');
2384 static int octdigitp(int c)
2388 case '0': case '1': case '2': case '3':
2389 case '4': case '5': case '6': case '7':
2395 static int octdigval(int c)
2398 if ((c >= '0') && (c <= '7')) {
2404 static int letterp(int c)
2408 case 'a': case 'b': case 'c': case 'd': case 'e':
2409 case 'f': case 'g': case 'h': case 'i': case 'j':
2410 case 'k': case 'l': case 'm': case 'n': case 'o':
2411 case 'p': case 'q': case 'r': case 's': case 't':
2412 case 'u': case 'v': case 'w': case 'x': case 'y':
2414 case 'A': case 'B': case 'C': case 'D': case 'E':
2415 case 'F': case 'G': case 'H': case 'I': case 'J':
2416 case 'K': case 'L': case 'M': case 'N': case 'O':
2417 case 'P': case 'Q': case 'R': case 'S': case 'T':
2418 case 'U': case 'V': case 'W': case 'X': case 'Y':
2427 static int char_value(struct compile_state *state,
2428 const signed char **strp, const signed char *end)
2430 const signed char *str;
2434 if ((c == '\\') && (str < end)) {
2436 case 'n': c = '\n'; str++; break;
2437 case 't': c = '\t'; str++; break;
2438 case 'v': c = '\v'; str++; break;
2439 case 'b': c = '\b'; str++; break;
2440 case 'r': c = '\r'; str++; break;
2441 case 'f': c = '\f'; str++; break;
2442 case 'a': c = '\a'; str++; break;
2443 case '\\': c = '\\'; str++; break;
2444 case '?': c = '?'; str++; break;
2445 case '\'': c = '\''; str++; break;
2446 case '"': c = '"'; break;
2450 while((str < end) && hexdigitp(*str)) {
2452 c += hexdigval(*str);
2456 case '0': case '1': case '2': case '3':
2457 case '4': case '5': case '6': case '7':
2459 while((str < end) && octdigitp(*str)) {
2461 c += octdigval(*str);
2466 error(state, 0, "Invalid character constant");
2474 static char *after_digits(char *ptr, char *end)
2476 while((ptr < end) && digitp(*ptr)) {
2482 static char *after_octdigits(char *ptr, char *end)
2484 while((ptr < end) && octdigitp(*ptr)) {
2490 static char *after_hexdigits(char *ptr, char *end)
2492 while((ptr < end) && hexdigitp(*ptr)) {
2498 static void save_string(struct compile_state *state,
2499 struct token *tk, char *start, char *end, const char *id)
2503 /* Create a private copy of the string */
2504 str_len = end - start + 1;
2505 str = xmalloc(str_len + 1, id);
2506 memcpy(str, start, str_len);
2507 str[str_len] = '\0';
2509 /* Store the copy in the token */
2511 tk->str_len = str_len;
2513 static void next_token(struct compile_state *state, int index)
2515 struct file_state *file;
2523 tk = &state->token[index];
2526 token = tokp = file->pos;
2527 end = file->buf + file->size;
2534 if ((tokp + 1) < end) {
2538 if ((tokp + 2) < end) {
2542 if ((tokp + 3) < end) {
2550 else if (spacep(c)) {
2552 while ((tokp < end) && spacep(c)) {
2555 file->report_line++;
2556 file->line_start = tokp + 1;
2565 else if ((c == '/') && (c1 == '/')) {
2567 for(tokp += 2; tokp < end; tokp++) {
2571 file->report_line++;
2572 file->line_start = tokp +1;
2578 else if ((c == '/') && (c1 == '*')) {
2582 line_start = file->line_start;
2583 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2587 line_start = tokp +1;
2589 else if ((c == '*') && (tokp[1] == '/')) {
2595 if (tok == TOK_UNKNOWN) {
2596 error(state, 0, "unterminated comment");
2598 file->report_line += line - file->line;
2600 file->line_start = line_start;
2602 /* string constants */
2603 else if ((c == '"') ||
2604 ((c == 'L') && (c1 == '"'))) {
2609 line_start = file->line_start;
2615 for(tokp += 1; tokp < end; tokp++) {
2619 line_start = tokp + 1;
2621 else if ((c == '\\') && (tokp +1 < end)) {
2624 else if (c == '"') {
2625 tok = TOK_LIT_STRING;
2629 if (tok == TOK_UNKNOWN) {
2630 error(state, 0, "unterminated string constant");
2632 if (line != file->line) {
2633 warning(state, 0, "multiline string constant");
2635 file->report_line += line - file->line;
2637 file->line_start = line_start;
2639 /* Save the string value */
2640 save_string(state, tk, token, tokp, "literal string");
2642 /* character constants */
2643 else if ((c == '\'') ||
2644 ((c == 'L') && (c1 == '\''))) {
2649 line_start = file->line_start;
2655 for(tokp += 1; tokp < end; tokp++) {
2659 line_start = tokp + 1;
2661 else if ((c == '\\') && (tokp +1 < end)) {
2664 else if (c == '\'') {
2669 if (tok == TOK_UNKNOWN) {
2670 error(state, 0, "unterminated character constant");
2672 if (line != file->line) {
2673 warning(state, 0, "multiline character constant");
2675 file->report_line += line - file->line;
2677 file->line_start = line_start;
2679 /* Save the character value */
2680 save_string(state, tk, token, tokp, "literal character");
2682 /* integer and floating constants
2688 * Floating constants
2689 * {digits}.{digits}[Ee][+-]?{digits}
2691 * {digits}[Ee][+-]?{digits}
2692 * .{digits}[Ee][+-]?{digits}
2696 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2701 next = after_digits(tokp, end);
2706 if (next[0] == '.') {
2707 new = after_digits(next, end);
2708 is_float = (new != next);
2711 if ((next[0] == 'e') || (next[0] == 'E')) {
2712 if (((next + 1) < end) &&
2713 ((next[1] == '+') || (next[1] == '-'))) {
2716 new = after_digits(next, end);
2717 is_float = (new != next);
2721 tok = TOK_LIT_FLOAT;
2722 if ((next < end) && (
2731 if (!is_float && digitp(c)) {
2733 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2734 next = after_hexdigits(tokp + 2, end);
2736 else if (c == '0') {
2737 next = after_octdigits(tokp, end);
2740 next = after_digits(tokp, end);
2742 /* crazy integer suffixes */
2744 ((next[0] == 'u') || (next[0] == 'U'))) {
2747 ((next[0] == 'l') || (next[0] == 'L'))) {
2751 else if ((next < end) &&
2752 ((next[0] == 'l') || (next[0] == 'L'))) {
2755 ((next[0] == 'u') || (next[0] == 'U'))) {
2762 /* Save the integer/floating point value */
2763 save_string(state, tk, token, tokp, "literal number");
2766 else if (letterp(c)) {
2768 for(tokp += 1; tokp < end; tokp++) {
2770 if (!letterp(c) && !digitp(c)) {
2775 tk->ident = lookup(state, token, tokp +1 - token);
2777 /* C99 alternate macro characters */
2778 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2780 tok = TOK_CONCATENATE;
2782 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2783 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2784 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2785 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2786 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2787 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2788 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2789 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2790 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2791 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2792 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2793 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2794 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2795 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2796 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2797 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2798 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2799 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2800 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2801 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2802 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2803 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2804 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2805 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2806 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2807 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2808 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2809 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2810 else if (c == ';') { tok = TOK_SEMI; }
2811 else if (c == '{') { tok = TOK_LBRACE; }
2812 else if (c == '}') { tok = TOK_RBRACE; }
2813 else if (c == ',') { tok = TOK_COMMA; }
2814 else if (c == '=') { tok = TOK_EQ; }
2815 else if (c == ':') { tok = TOK_COLON; }
2816 else if (c == '[') { tok = TOK_LBRACKET; }
2817 else if (c == ']') { tok = TOK_RBRACKET; }
2818 else if (c == '(') { tok = TOK_LPAREN; }
2819 else if (c == ')') { tok = TOK_RPAREN; }
2820 else if (c == '*') { tok = TOK_STAR; }
2821 else if (c == '>') { tok = TOK_MORE; }
2822 else if (c == '<') { tok = TOK_LESS; }
2823 else if (c == '?') { tok = TOK_QUEST; }
2824 else if (c == '|') { tok = TOK_OR; }
2825 else if (c == '&') { tok = TOK_AND; }
2826 else if (c == '^') { tok = TOK_XOR; }
2827 else if (c == '+') { tok = TOK_PLUS; }
2828 else if (c == '-') { tok = TOK_MINUS; }
2829 else if (c == '/') { tok = TOK_DIV; }
2830 else if (c == '%') { tok = TOK_MOD; }
2831 else if (c == '!') { tok = TOK_BANG; }
2832 else if (c == '.') { tok = TOK_DOT; }
2833 else if (c == '~') { tok = TOK_TILDE; }
2834 else if (c == '#') { tok = TOK_MACRO; }
2835 if (tok == TOK_MACRO) {
2836 /* Only match preprocessor directives at the start of a line */
2838 for(ptr = file->line_start; spacep(*ptr); ptr++)
2844 if (tok == TOK_UNKNOWN) {
2845 error(state, 0, "unknown token");
2848 file->pos = tokp + 1;
2850 if (tok == TOK_IDENT) {
2851 ident_to_keyword(state, tk);
2853 /* Don't return space tokens. */
2854 if (tok == TOK_SPACE) {
2859 static void compile_macro(struct compile_state *state, struct token *tk)
2861 struct file_state *file;
2862 struct hash_entry *ident;
2864 file = xmalloc(sizeof(*file), "file_state");
2865 file->basename = xstrdup(tk->ident->name);
2866 file->dirname = xstrdup("");
2867 file->size = ident->sym_define->buf_len;
2868 file->buf = xmalloc(file->size +2, file->basename);
2869 memcpy(file->buf, ident->sym_define->buf, file->size);
2870 file->buf[file->size] = '\n';
2871 file->buf[file->size + 1] = '\0';
2872 file->pos = file->buf;
2873 file->line_start = file->pos;
2875 file->report_line = 1;
2876 file->report_name = file->basename;
2877 file->report_dir = file->dirname;
2878 file->prev = state->file;
2883 static int mpeek(struct compile_state *state, int index)
2887 tk = &state->token[index + 1];
2888 if (tk->tok == -1) {
2889 next_token(state, index + 1);
2893 if ((tk->tok == TOK_EOF) &&
2894 (state->file != state->macro_file) &&
2895 (state->file->prev)) {
2896 struct file_state *file = state->file;
2897 state->file = file->prev;
2898 /* file->basename is used keep it */
2899 if (file->report_dir != file->dirname) {
2900 xfree(file->report_dir);
2902 xfree(file->dirname);
2905 next_token(state, index + 1);
2908 else if (tk->ident && tk->ident->sym_define) {
2909 compile_macro(state, tk);
2910 next_token(state, index + 1);
2914 /* Don't show the token on the next line */
2915 if (state->macro_line < state->macro_file->line) {
2918 return state->token[index +1].tok;
2921 static void meat(struct compile_state *state, int index, int tok)
2925 next_tok = mpeek(state, index);
2926 if (next_tok != tok) {
2927 const char *name1, *name2;
2928 name1 = tokens[next_tok];
2930 if (next_tok == TOK_IDENT) {
2931 name2 = state->token[index + 1].ident->name;
2933 error(state, 0, "found %s %s expected %s",
2934 name1, name2, tokens[tok]);
2936 /* Free the old token value */
2937 if (state->token[index].str_len) {
2938 memset((void *)(state->token[index].val.str), -1,
2939 state->token[index].str_len);
2940 xfree(state->token[index].val.str);
2942 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2943 state->token[i] = state->token[i + 1];
2945 memset(&state->token[i], 0, sizeof(state->token[i]));
2946 state->token[i].tok = -1;
2949 static long_t mcexpr(struct compile_state *state, int index);
2951 static long_t mprimary_expr(struct compile_state *state, int index)
2955 tok = mpeek(state, index);
2956 while(state->token[index + 1].ident &&
2957 state->token[index + 1].ident->sym_define) {
2958 meat(state, index, tok);
2959 compile_macro(state, &state->token[index]);
2960 tok = mpeek(state, index);
2964 meat(state, index, TOK_LPAREN);
2965 val = mcexpr(state, index);
2966 meat(state, index, TOK_RPAREN);
2971 meat(state, index, TOK_LIT_INT);
2973 val = strtol(state->token[index].val.str, &end, 0);
2974 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2975 (errno == ERANGE)) {
2976 error(state, 0, "Integer constant to large");
2981 meat(state, index, TOK_LIT_INT);
2986 static long_t munary_expr(struct compile_state *state, int index)
2989 switch(mpeek(state, index)) {
2991 meat(state, index, TOK_PLUS);
2992 val = munary_expr(state, index);
2996 meat(state, index, TOK_MINUS);
2997 val = munary_expr(state, index);
3001 meat(state, index, TOK_BANG);
3002 val = munary_expr(state, index);
3006 meat(state, index, TOK_BANG);
3007 val = munary_expr(state, index);
3011 val = mprimary_expr(state, index);
3017 static long_t mmul_expr(struct compile_state *state, int index)
3021 val = munary_expr(state, index);
3025 switch(mpeek(state, index)) {
3027 meat(state, index, TOK_STAR);
3028 right = munary_expr(state, index);
3032 meat(state, index, TOK_DIV);
3033 right = munary_expr(state, index);
3037 meat(state, index, TOK_MOD);
3038 right = munary_expr(state, index);
3050 static long_t madd_expr(struct compile_state *state, int index)
3054 val = mmul_expr(state, index);
3058 switch(mpeek(state, index)) {
3060 meat(state, index, TOK_PLUS);
3061 right = mmul_expr(state, index);
3065 meat(state, index, TOK_MINUS);
3066 right = mmul_expr(state, index);
3078 static long_t mshift_expr(struct compile_state *state, int index)
3082 val = madd_expr(state, index);
3086 switch(mpeek(state, index)) {
3088 meat(state, index, TOK_SL);
3089 right = madd_expr(state, index);
3093 meat(state, index, TOK_SR);
3094 right = madd_expr(state, index);
3106 static long_t mrel_expr(struct compile_state *state, int index)
3110 val = mshift_expr(state, index);
3114 switch(mpeek(state, index)) {
3116 meat(state, index, TOK_LESS);
3117 right = mshift_expr(state, index);
3121 meat(state, index, TOK_MORE);
3122 right = mshift_expr(state, index);
3126 meat(state, index, TOK_LESSEQ);
3127 right = mshift_expr(state, index);
3131 meat(state, index, TOK_MOREEQ);
3132 right = mshift_expr(state, index);
3143 static long_t meq_expr(struct compile_state *state, int index)
3147 val = mrel_expr(state, index);
3151 switch(mpeek(state, index)) {
3153 meat(state, index, TOK_EQEQ);
3154 right = mrel_expr(state, index);
3158 meat(state, index, TOK_NOTEQ);
3159 right = mrel_expr(state, index);
3170 static long_t mand_expr(struct compile_state *state, int index)
3173 val = meq_expr(state, index);
3174 if (mpeek(state, index) == TOK_AND) {
3176 meat(state, index, TOK_AND);
3177 right = meq_expr(state, index);
3183 static long_t mxor_expr(struct compile_state *state, int index)
3186 val = mand_expr(state, index);
3187 if (mpeek(state, index) == TOK_XOR) {
3189 meat(state, index, TOK_XOR);
3190 right = mand_expr(state, index);
3196 static long_t mor_expr(struct compile_state *state, int index)
3199 val = mxor_expr(state, index);
3200 if (mpeek(state, index) == TOK_OR) {
3202 meat(state, index, TOK_OR);
3203 right = mxor_expr(state, index);
3209 static long_t mland_expr(struct compile_state *state, int index)
3212 val = mor_expr(state, index);
3213 if (mpeek(state, index) == TOK_LOGAND) {
3215 meat(state, index, TOK_LOGAND);
3216 right = mor_expr(state, index);
3221 static long_t mlor_expr(struct compile_state *state, int index)
3224 val = mland_expr(state, index);
3225 if (mpeek(state, index) == TOK_LOGOR) {
3227 meat(state, index, TOK_LOGOR);
3228 right = mland_expr(state, index);
3234 static long_t mcexpr(struct compile_state *state, int index)
3236 return mlor_expr(state, index);
3238 static void preprocess(struct compile_state *state, int index)
3240 /* Doing much more with the preprocessor would require
3241 * a parser and a major restructuring.
3242 * Postpone that for later.
3244 struct file_state *file;
3250 tk = &state->token[index];
3251 state->macro_line = line = file->line;
3252 state->macro_file = file;
3254 next_token(state, index);
3255 ident_to_macro(state, tk);
3256 if (tk->tok == TOK_IDENT) {
3257 error(state, 0, "undefined preprocessing directive `%s'",
3264 override_line = strtoul(tk->val.str, 0, 10);
3265 next_token(state, index);
3266 /* I have a cpp line marker parse it */
3267 if (tk->tok == TOK_LIT_STRING) {
3268 const char *token, *base;
3270 int name_len, dir_len;
3271 name = xmalloc(tk->str_len, "report_name");
3272 token = tk->val.str + 1;
3273 base = strrchr(token, '/');
3274 name_len = tk->str_len -2;
3276 dir_len = base - token;
3278 name_len -= base - token;
3283 memcpy(name, base, name_len);
3284 name[name_len] = '\0';
3285 dir = xmalloc(dir_len + 1, "report_dir");
3286 memcpy(dir, token, dir_len);
3287 dir[dir_len] = '\0';
3288 file->report_line = override_line - 1;
3289 file->report_name = name;
3290 file->report_dir = dir;
3295 meat(state, index, TOK_LINE);
3296 meat(state, index, TOK_LIT_INT);
3297 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3298 if (mpeek(state, index) == TOK_LIT_STRING) {
3299 const char *token, *base;
3301 int name_len, dir_len;
3302 meat(state, index, TOK_LIT_STRING);
3303 name = xmalloc(tk->str_len, "report_name");
3304 token = tk->val.str + 1;
3305 name_len = tk->str_len - 2;
3307 dir_len = base - token;
3309 name_len -= base - token;
3314 memcpy(name, base, name_len);
3315 name[name_len] = '\0';
3316 dir = xmalloc(dir_len + 1, "report_dir");
3317 memcpy(dir, token, dir_len);
3318 dir[dir_len] = '\0';
3319 file->report_name = name;
3320 file->report_dir = dir;
3325 if (state->if_value < 0) {
3328 warning(state, 0, "Ignoring preprocessor directive: %s",
3332 error(state, 0, "#elif not supported");
3333 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3334 if (state->if_depth == 0) {
3335 error(state, 0, "#elif without #if");
3337 /* If the #if was taken the #elif just disables the following code */
3338 if (state->if_value >= 0) {
3339 state->if_value = - state->if_value;
3341 /* If the previous #if was not taken see if the #elif enables the
3344 else if ((state->if_value < 0) &&
3345 (state->if_depth == - state->if_value))
3347 if (mcexpr(state, index) != 0) {
3348 state->if_value = state->if_depth;
3351 state->if_value = - state->if_depth;
3357 if (state->if_value < 0) {
3360 if (mcexpr(state, index) != 0) {
3361 state->if_value = state->if_depth;
3364 state->if_value = - state->if_depth;
3369 if (state->if_value < 0) {
3372 next_token(state, index);
3373 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3374 error(state, 0, "Invalid macro name");
3376 if (tk->ident->sym_define == 0) {
3377 state->if_value = state->if_depth;
3380 state->if_value = - state->if_depth;
3385 if (state->if_value < 0) {
3388 next_token(state, index);
3389 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3390 error(state, 0, "Invalid macro name");
3392 if (tk->ident->sym_define != 0) {
3393 state->if_value = state->if_depth;
3396 state->if_value = - state->if_depth;
3400 if (state->if_depth == 0) {
3401 error(state, 0, "#else without #if");
3403 if ((state->if_value >= 0) ||
3404 ((state->if_value < 0) &&
3405 (state->if_depth == -state->if_value)))
3407 state->if_value = - state->if_value;
3411 if (state->if_depth == 0) {
3412 error(state, 0, "#endif without #if");
3414 if ((state->if_value >= 0) ||
3415 ((state->if_value < 0) &&
3416 (state->if_depth == -state->if_value)))
3418 state->if_value = state->if_depth - 1;
3424 struct hash_entry *ident;
3425 struct macro *macro;
3428 if (state->if_value < 0) /* quit early when #if'd out */
3431 meat(state, index, TOK_IDENT);
3435 if (*file->pos == '(') {
3436 #warning "FIXME macros with arguments not supported"
3437 error(state, 0, "Macros with arguments not supported");
3440 /* Find the end of the line to get an estimate of
3441 * the macro's length.
3443 for(ptr = file->pos; *ptr != '\n'; ptr++)
3446 if (ident->sym_define != 0) {
3447 error(state, 0, "macro %s already defined\n", ident->name);
3449 macro = xmalloc(sizeof(*macro), "macro");
3450 macro->ident = ident;
3451 macro->buf_len = ptr - file->pos +1;
3452 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3454 memcpy(macro->buf, file->pos, macro->buf_len);
3455 macro->buf[macro->buf_len] = '\n';
3456 macro->buf[macro->buf_len +1] = '\0';
3458 ident->sym_define = macro;
3465 /* Find the end of the line */
3466 for(end = file->pos; *end != '\n'; end++)
3468 len = (end - file->pos);
3469 if (state->if_value >= 0) {
3470 error(state, 0, "%*.*s", len, len, file->pos);
3479 /* Find the end of the line */
3480 for(end = file->pos; *end != '\n'; end++)
3482 len = (end - file->pos);
3483 if (state->if_value >= 0) {
3484 warning(state, 0, "%*.*s", len, len, file->pos);
3496 next_token(state, index);
3497 if (tk->tok == TOK_LIT_STRING) {
3500 name = xmalloc(tk->str_len, "include");
3501 token = tk->val.str +1;
3502 name_len = tk->str_len -2;
3503 if (*token == '"') {
3507 memcpy(name, token, name_len);
3508 name[name_len] = '\0';
3511 else if (tk->tok == TOK_LESS) {
3514 for(end = start; *end != '\n'; end++) {
3520 error(state, 0, "Unterminated included directive");
3522 name = xmalloc(end - start + 1, "include");
3523 memcpy(name, start, end - start);
3524 name[end - start] = '\0';
3529 error(state, 0, "Invalid include directive");
3531 /* Error if there are any characters after the include */
3532 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3539 error(state, 0, "garbage after include directive");
3542 if (state->if_value >= 0) {
3543 compile_file(state, name, local);
3546 next_token(state, index);
3550 /* Ignore # without a following ident */
3551 if (tk->tok == TOK_IDENT) {
3552 error(state, 0, "Invalid preprocessor directive: %s",
3557 /* Consume the rest of the macro line */
3559 tok = mpeek(state, index);
3560 meat(state, index, tok);
3561 } while(tok != TOK_EOF);
3565 static void token(struct compile_state *state, int index)
3567 struct file_state *file;
3571 tk = &state->token[index];
3572 next_token(state, index);
3576 if (tk->tok == TOK_EOF && file->prev) {
3577 state->file = file->prev;
3578 /* file->basename is used keep it */
3579 xfree(file->dirname);
3582 next_token(state, index);
3585 else if (tk->tok == TOK_MACRO) {
3586 preprocess(state, index);
3589 else if (tk->ident && tk->ident->sym_define) {
3590 compile_macro(state, tk);
3591 next_token(state, index);
3594 else if (state->if_value < 0) {
3595 next_token(state, index);
3601 static int peek(struct compile_state *state)
3603 if (state->token[1].tok == -1) {
3606 return state->token[1].tok;
3609 static int peek2(struct compile_state *state)
3611 if (state->token[1].tok == -1) {
3614 if (state->token[2].tok == -1) {
3617 return state->token[2].tok;
3620 static void eat(struct compile_state *state, int tok)
3624 next_tok = peek(state);
3625 if (next_tok != tok) {
3626 const char *name1, *name2;
3627 name1 = tokens[next_tok];
3629 if (next_tok == TOK_IDENT) {
3630 name2 = state->token[1].ident->name;
3632 error(state, 0, "\tfound %s %s expected %s",
3633 name1, name2 ,tokens[tok]);
3635 /* Free the old token value */
3636 if (state->token[0].str_len) {
3637 xfree((void *)(state->token[0].val.str));
3639 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3640 state->token[i] = state->token[i + 1];
3642 memset(&state->token[i], 0, sizeof(state->token[i]));
3643 state->token[i].tok = -1;
3646 #warning "FIXME do not hardcode the include paths"
3647 static char *include_paths[] = {
3648 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3649 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3650 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3654 static void compile_file(struct compile_state *state, const char *filename, int local)
3657 const char *subdir, *base;
3659 struct file_state *file;
3661 file = xmalloc(sizeof(*file), "file_state");
3663 base = strrchr(filename, '/');
3666 subdir_len = base - filename;
3673 basename = xmalloc(strlen(base) +1, "basename");
3674 strcpy(basename, base);
3675 file->basename = basename;
3677 if (getcwd(cwd, sizeof(cwd)) == 0) {
3678 die("cwd buffer to small");
3681 if (subdir[0] == '/') {
3682 file->dirname = xmalloc(subdir_len + 1, "dirname");
3683 memcpy(file->dirname, subdir, subdir_len);
3684 file->dirname[subdir_len] = '\0';
3690 /* Find the appropriate directory... */
3692 if (!state->file && exists(cwd, filename)) {
3695 if (local && state->file && exists(state->file->dirname, filename)) {
3696 dir = state->file->dirname;
3698 for(path = include_paths; !dir && *path; path++) {
3699 if (exists(*path, filename)) {
3704 error(state, 0, "Cannot find `%s'\n", filename);
3706 dirlen = strlen(dir);
3707 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3708 memcpy(file->dirname, dir, dirlen);
3709 file->dirname[dirlen] = '/';
3710 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3711 file->dirname[dirlen + 1 + subdir_len] = '\0';
3713 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3716 file->pos = file->buf;
3717 file->line_start = file->pos;
3720 file->report_line = 1;
3721 file->report_name = file->basename;
3722 file->report_dir = file->dirname;
3724 file->prev = state->file;
3727 process_trigraphs(state);
3728 splice_lines(state);
3731 /* Type helper functions */
3733 static struct type *new_type(
3734 unsigned int type, struct type *left, struct type *right)
3736 struct type *result;
3737 result = xmalloc(sizeof(*result), "type");
3738 result->type = type;
3739 result->left = left;
3740 result->right = right;
3741 result->field_ident = 0;
3742 result->type_ident = 0;
3746 static struct type *clone_type(unsigned int specifiers, struct type *old)
3748 struct type *result;
3749 result = xmalloc(sizeof(*result), "type");
3750 memcpy(result, old, sizeof(*result));
3751 result->type &= TYPE_MASK;
3752 result->type |= specifiers;
3756 #define SIZEOF_SHORT 2
3757 #define SIZEOF_INT 4
3758 #define SIZEOF_LONG (sizeof(long_t))
3760 #define ALIGNOF_SHORT 2
3761 #define ALIGNOF_INT 4
3762 #define ALIGNOF_LONG (sizeof(long_t))
3764 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3765 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3766 static inline ulong_t mask_uint(ulong_t x)
3768 if (SIZEOF_INT < SIZEOF_LONG) {
3769 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3774 #define MASK_UINT(X) (mask_uint(X))
3775 #define MASK_ULONG(X) (X)
3777 static struct type void_type = { .type = TYPE_VOID };
3778 static struct type char_type = { .type = TYPE_CHAR };
3779 static struct type uchar_type = { .type = TYPE_UCHAR };
3780 static struct type short_type = { .type = TYPE_SHORT };
3781 static struct type ushort_type = { .type = TYPE_USHORT };
3782 static struct type int_type = { .type = TYPE_INT };
3783 static struct type uint_type = { .type = TYPE_UINT };
3784 static struct type long_type = { .type = TYPE_LONG };
3785 static struct type ulong_type = { .type = TYPE_ULONG };
3787 static struct triple *variable(struct compile_state *state, struct type *type)
3789 struct triple *result;
3790 if ((type->type & STOR_MASK) != STOR_PERM) {
3791 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3792 result = triple(state, OP_ADECL, type, 0, 0);
3795 struct triple **vector;
3797 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3798 vector = &result->param[0];
3802 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3803 vector[index] = variable(state, field->left);
3804 field = field->right;
3807 vector[index] = variable(state, field);
3811 result = triple(state, OP_SDECL, type, 0, 0);
3816 static void stor_of(FILE *fp, struct type *type)
3818 switch(type->type & STOR_MASK) {
3820 fprintf(fp, "auto ");
3823 fprintf(fp, "static ");
3826 fprintf(fp, "extern ");
3829 fprintf(fp, "register ");
3832 fprintf(fp, "typedef ");
3835 fprintf(fp, "inline ");
3839 static void qual_of(FILE *fp, struct type *type)
3841 if (type->type & QUAL_CONST) {
3842 fprintf(fp, " const");
3844 if (type->type & QUAL_VOLATILE) {
3845 fprintf(fp, " volatile");
3847 if (type->type & QUAL_RESTRICT) {
3848 fprintf(fp, " restrict");
3852 static void name_of(FILE *fp, struct type *type)
3855 switch(type->type & TYPE_MASK) {
3857 fprintf(fp, "void");
3861 fprintf(fp, "signed char");
3865 fprintf(fp, "unsigned char");
3869 fprintf(fp, "signed short");
3873 fprintf(fp, "unsigned short");
3877 fprintf(fp, "signed int");
3881 fprintf(fp, "unsigned int");
3885 fprintf(fp, "signed long");
3889 fprintf(fp, "unsigned long");
3893 name_of(fp, type->left);
3899 name_of(fp, type->left);
3901 name_of(fp, type->right);
3904 fprintf(fp, "enum %s", type->type_ident->name);
3908 fprintf(fp, "struct %s", type->type_ident->name);
3913 name_of(fp, type->left);
3914 fprintf(fp, " (*)(");
3915 name_of(fp, type->right);
3920 name_of(fp, type->left);
3921 fprintf(fp, " [%ld]", type->elements);
3924 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3929 static size_t align_of(struct compile_state *state, struct type *type)
3933 switch(type->type & TYPE_MASK) {
3943 align = ALIGNOF_SHORT;
3948 align = ALIGNOF_INT;
3953 align = ALIGNOF_LONG;
3958 size_t left_align, right_align;
3959 left_align = align_of(state, type->left);
3960 right_align = align_of(state, type->right);
3961 align = (left_align >= right_align) ? left_align : right_align;
3965 align = align_of(state, type->left);
3968 align = align_of(state, type->left);
3971 error(state, 0, "alignof not yet defined for type\n");
3977 static size_t needed_padding(size_t offset, size_t align)
3981 if (offset % align) {
3982 padding = align - (offset % align);
3986 static size_t size_of(struct compile_state *state, struct type *type)
3990 switch(type->type & TYPE_MASK) {
4000 size = SIZEOF_SHORT;
4016 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4017 align = align_of(state, type->left);
4018 pad = needed_padding(size, align);
4019 size = size + pad + size_of(state, type->left);
4022 align = align_of(state, type);
4023 pad = needed_padding(size, align);
4024 size = size + pad + sizeof(type);
4029 size_t size_left, size_right;
4030 size_left = size_of(state, type->left);
4031 size_right = size_of(state, type->right);
4032 size = (size_left >= size_right)? size_left : size_right;
4036 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4037 internal_error(state, 0, "Invalid array type");
4039 size = size_of(state, type->left) * type->elements;
4043 size = size_of(state, type->left);
4046 internal_error(state, 0, "sizeof not yet defined for type\n");
4052 static size_t field_offset(struct compile_state *state,
4053 struct type *type, struct hash_entry *field)
4055 struct type *member;
4057 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4058 internal_error(state, 0, "field_offset only works on structures");
4061 member = type->left;
4062 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4063 align = align_of(state, member->left);
4064 size += needed_padding(size, align);
4065 if (member->left->field_ident == field) {
4066 member = member->left;
4069 size += size_of(state, member->left);
4070 member = member->right;
4072 align = align_of(state, member);
4073 size += needed_padding(size, align);
4074 if (member->field_ident != field) {
4075 error(state, 0, "member %s not present", field->name);
4080 static struct type *field_type(struct compile_state *state,
4081 struct type *type, struct hash_entry *field)
4083 struct type *member;
4084 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4085 internal_error(state, 0, "field_type only works on structures");
4087 member = type->left;
4088 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4089 if (member->left->field_ident == field) {
4090 member = member->left;
4093 member = member->right;
4095 if (member->field_ident != field) {
4096 error(state, 0, "member %s not present", field->name);
4101 static struct type *next_field(struct compile_state *state,
4102 struct type *type, struct type *prev_member)
4104 struct type *member;
4105 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4106 internal_error(state, 0, "next_field only works on structures");
4108 member = type->left;
4109 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4111 member = member->left;
4114 if (member->left == prev_member) {
4117 member = member->right;
4119 if (member == prev_member) {
4123 internal_error(state, 0, "prev_member %s not present",
4124 prev_member->field_ident->name);
4129 static struct triple *struct_field(struct compile_state *state,
4130 struct triple *decl, struct hash_entry *field)
4132 struct triple **vector;
4136 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4139 if (decl->op != OP_VAL_VEC) {
4140 internal_error(state, 0, "Invalid struct variable");
4143 internal_error(state, 0, "Missing structure field");
4146 vector = &RHS(decl, 0);
4148 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4149 if (type->left->field_ident == field) {
4156 if (type->field_ident != field) {
4157 internal_error(state, 0, "field %s not found?", field->name);
4159 return vector[index];
4162 static void arrays_complete(struct compile_state *state, struct type *type)
4164 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4165 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4166 error(state, 0, "array size not specified");
4168 arrays_complete(state, type->left);
4172 static unsigned int do_integral_promotion(unsigned int type)
4175 if (TYPE_INTEGER(type) &&
4176 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4182 static unsigned int do_arithmetic_conversion(
4183 unsigned int left, unsigned int right)
4187 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4188 return TYPE_LDOUBLE;
4190 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4193 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4196 left = do_integral_promotion(left);
4197 right = do_integral_promotion(right);
4198 /* If both operands have the same size done */
4199 if (left == right) {
4202 /* If both operands have the same signedness pick the larger */
4203 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4204 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4206 /* If the signed type can hold everything use it */
4207 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4210 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4213 /* Convert to the unsigned type with the same rank as the signed type */
4214 else if (TYPE_SIGNED(left)) {
4215 return TYPE_MKUNSIGNED(left);
4218 return TYPE_MKUNSIGNED(right);
4222 /* see if two types are the same except for qualifiers */
4223 static int equiv_types(struct type *left, struct type *right)
4226 /* Error if the basic types do not match */
4227 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4230 type = left->type & TYPE_MASK;
4231 /* If the basic types match and it is a void type we are done */
4232 if (type == TYPE_VOID) {
4235 /* if the basic types match and it is an arithmetic type we are done */
4236 if (TYPE_ARITHMETIC(type)) {
4239 /* If it is a pointer type recurse and keep testing */
4240 if (type == TYPE_POINTER) {
4241 return equiv_types(left->left, right->left);
4243 else if (type == TYPE_ARRAY) {
4244 return (left->elements == right->elements) &&
4245 equiv_types(left->left, right->left);
4247 /* test for struct/union equality */
4248 else if (type == TYPE_STRUCT) {
4249 return left->type_ident == right->type_ident;
4251 /* Test for equivalent functions */
4252 else if (type == TYPE_FUNCTION) {
4253 return equiv_types(left->left, right->left) &&
4254 equiv_types(left->right, right->right);
4256 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4257 else if (type == TYPE_PRODUCT) {
4258 return equiv_types(left->left, right->left) &&
4259 equiv_types(left->right, right->right);
4261 /* We should see TYPE_OVERLAP */
4267 static int equiv_ptrs(struct type *left, struct type *right)
4269 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4270 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4273 return equiv_types(left->left, right->left);
4276 static struct type *compatible_types(struct type *left, struct type *right)
4278 struct type *result;
4279 unsigned int type, qual_type;
4280 /* Error if the basic types do not match */
4281 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4284 type = left->type & TYPE_MASK;
4285 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4287 /* if the basic types match and it is an arithmetic type we are done */
4288 if (TYPE_ARITHMETIC(type)) {
4289 result = new_type(qual_type, 0, 0);
4291 /* If it is a pointer type recurse and keep testing */
4292 else if (type == TYPE_POINTER) {
4293 result = compatible_types(left->left, right->left);
4295 result = new_type(qual_type, result, 0);
4298 /* test for struct/union equality */
4299 else if (type == TYPE_STRUCT) {
4300 if (left->type_ident == right->type_ident) {
4304 /* Test for equivalent functions */
4305 else if (type == TYPE_FUNCTION) {
4306 struct type *lf, *rf;
4307 lf = compatible_types(left->left, right->left);
4308 rf = compatible_types(left->right, right->right);
4310 result = new_type(qual_type, lf, rf);
4313 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4314 else if (type == TYPE_PRODUCT) {
4315 struct type *lf, *rf;
4316 lf = compatible_types(left->left, right->left);
4317 rf = compatible_types(left->right, right->right);
4319 result = new_type(qual_type, lf, rf);
4323 /* Nothing else is compatible */
4328 static struct type *compatible_ptrs(struct type *left, struct type *right)
4330 struct type *result;
4331 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4332 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4335 result = compatible_types(left->left, right->left);
4337 unsigned int qual_type;
4338 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4339 result = new_type(qual_type, result, 0);
4344 static struct triple *integral_promotion(
4345 struct compile_state *state, struct triple *def)
4349 /* As all operations are carried out in registers
4350 * the values are converted on load I just convert
4351 * logical type of the operand.
4353 if (TYPE_INTEGER(type->type)) {
4354 unsigned int int_type;
4355 int_type = type->type & ~TYPE_MASK;
4356 int_type |= do_integral_promotion(type->type);
4357 if (int_type != type->type) {
4358 def->type = new_type(int_type, 0, 0);
4365 static void arithmetic(struct compile_state *state, struct triple *def)
4367 if (!TYPE_ARITHMETIC(def->type->type)) {
4368 error(state, 0, "arithmetic type expexted");
4372 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4374 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4375 error(state, def, "pointer or arithmetic type expected");
4379 static int is_integral(struct triple *ins)
4381 return TYPE_INTEGER(ins->type->type);
4384 static void integral(struct compile_state *state, struct triple *def)
4386 if (!is_integral(def)) {
4387 error(state, 0, "integral type expected");
4392 static void bool(struct compile_state *state, struct triple *def)
4394 if (!TYPE_ARITHMETIC(def->type->type) &&
4395 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4396 error(state, 0, "arithmetic or pointer type expected");
4400 static int is_signed(struct type *type)
4402 return !!TYPE_SIGNED(type->type);
4405 /* Is this value located in a register otherwise it must be in memory */
4406 static int is_in_reg(struct compile_state *state, struct triple *def)
4409 if (def->op == OP_ADECL) {
4412 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4415 else if (def->op == OP_VAL_VEC) {
4416 in_reg = is_in_reg(state, RHS(def, 0));
4418 else if (def->op == OP_DOT) {
4419 in_reg = is_in_reg(state, RHS(def, 0));
4422 internal_error(state, 0, "unknown expr storage location");
4428 /* Is this a stable variable location otherwise it must be a temporary */
4429 static int is_stable(struct compile_state *state, struct triple *def)
4436 if ((def->op == OP_ADECL) ||
4437 (def->op == OP_SDECL) ||
4438 (def->op == OP_DEREF) ||
4439 (def->op == OP_BLOBCONST)) {
4442 else if (def->op == OP_DOT) {
4443 ret = is_stable(state, RHS(def, 0));
4445 else if (def->op == OP_VAL_VEC) {
4446 struct triple **vector;
4449 vector = &RHS(def, 0);
4450 for(i = 0; i < def->type->elements; i++) {
4451 if (!is_stable(state, vector[i])) {
4460 static int is_lvalue(struct compile_state *state, struct triple *def)
4467 if (!is_stable(state, def)) {
4470 if (def->op == OP_DOT) {
4471 ret = is_lvalue(state, RHS(def, 0));
4476 static void clvalue(struct compile_state *state, struct triple *def)
4479 internal_error(state, def, "nothing where lvalue expected?");
4481 if (!is_lvalue(state, def)) {
4482 error(state, def, "lvalue expected");
4485 static void lvalue(struct compile_state *state, struct triple *def)
4487 clvalue(state, def);
4488 if (def->type->type & QUAL_CONST) {
4489 error(state, def, "modifable lvalue expected");
4493 static int is_pointer(struct triple *def)
4495 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4498 static void pointer(struct compile_state *state, struct triple *def)
4500 if (!is_pointer(def)) {
4501 error(state, def, "pointer expected");
4505 static struct triple *int_const(
4506 struct compile_state *state, struct type *type, ulong_t value)
4508 struct triple *result;
4509 switch(type->type & TYPE_MASK) {
4511 case TYPE_INT: case TYPE_UINT:
4512 case TYPE_LONG: case TYPE_ULONG:
4515 internal_error(state, 0, "constant for unkown type");
4517 result = triple(state, OP_INTCONST, type, 0, 0);
4518 result->u.cval = value;
4523 static struct triple *do_mk_addr_expr(struct compile_state *state,
4524 struct triple *expr, struct type *type, ulong_t offset)
4526 struct triple *result;
4527 clvalue(state, expr);
4529 type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
4532 if (expr->op == OP_ADECL) {
4533 error(state, expr, "address of auto variables not supported");
4535 else if (expr->op == OP_SDECL) {
4536 result = triple(state, OP_ADDRCONST, type, 0, 0);
4537 MISC(result, 0) = expr;
4538 result->u.cval = offset;
4540 else if (expr->op == OP_DEREF) {
4541 result = triple(state, OP_ADD, type,
4543 int_const(state, &ulong_type, offset));
4548 static struct triple *mk_addr_expr(
4549 struct compile_state *state, struct triple *expr, ulong_t offset)
4551 return do_mk_addr_expr(state, expr, expr->type, offset);
4554 static struct triple *mk_deref_expr(
4555 struct compile_state *state, struct triple *expr)
4557 struct type *base_type;
4558 pointer(state, expr);
4559 base_type = expr->type->left;
4560 return triple(state, OP_DEREF, base_type, expr, 0);
4563 static struct triple *array_to_pointer(struct compile_state *state, struct triple *def)
4565 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4567 struct triple *addrconst;
4569 TYPE_POINTER | (def->type->type & QUAL_MASK),
4570 def->type->left, 0);
4571 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
4572 MISC(addrconst, 0) = def;
4578 static struct triple *deref_field(
4579 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4581 struct triple *result;
4582 struct type *type, *member;
4584 internal_error(state, 0, "No field passed to deref_field");
4588 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4589 error(state, 0, "request for member %s in something not a struct or union",
4592 member = field_type(state, type, field);
4593 if ((type->type & STOR_MASK) == STOR_PERM) {
4594 /* Do the pointer arithmetic to get a deref the field */
4596 offset = field_offset(state, type, field);
4597 result = do_mk_addr_expr(state, expr, member, offset);
4598 result = mk_deref_expr(state, result);
4601 /* Find the variable for the field I want. */
4602 result = triple(state, OP_DOT, member, expr, 0);
4603 result->u.field = field;
4608 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4614 if (!is_stable(state, def)) {
4617 /* Tranform an array to a pointer to the first element */
4619 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4620 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4621 return array_to_pointer(state, def);
4623 if (is_in_reg(state, def)) {
4628 return triple(state, op, def->type, def, 0);
4631 static void write_compatible(struct compile_state *state,
4632 struct type *dest, struct type *rval)
4635 /* Both operands have arithmetic type */
4636 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4639 /* One operand is a pointer and the other is a pointer to void */
4640 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4641 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4642 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4643 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4646 /* If both types are the same without qualifiers we are good */
4647 else if (equiv_ptrs(dest, rval)) {
4650 /* test for struct/union equality */
4651 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4652 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4653 (dest->type_ident == rval->type_ident)) {
4657 error(state, 0, "Incompatible types in assignment");
4661 static struct triple *write_expr(
4662 struct compile_state *state, struct triple *dest, struct triple *rval)
4669 internal_error(state, 0, "missing rval");
4672 if (rval->op == OP_LIST) {
4673 internal_error(state, 0, "expression of type OP_LIST?");
4675 if (!is_lvalue(state, dest)) {
4676 internal_error(state, 0, "writing to a non lvalue?");
4678 if (dest->type->type & QUAL_CONST) {
4679 internal_error(state, 0, "modifable lvalue expexted");
4682 write_compatible(state, dest->type, rval->type);
4684 /* Now figure out which assignment operator to use */
4686 if (is_in_reg(state, dest)) {
4691 def = triple(state, op, dest->type, dest, rval);
4695 static struct triple *init_expr(
4696 struct compile_state *state, struct triple *dest, struct triple *rval)
4702 internal_error(state, 0, "missing rval");
4704 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4705 rval = read_expr(state, rval);
4706 def = write_expr(state, dest, rval);
4709 /* Fill in the array size if necessary */
4710 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4711 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4712 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4713 dest->type->elements = rval->type->elements;
4716 if (!equiv_types(dest->type, rval->type)) {
4717 error(state, 0, "Incompatible types in inializer");
4719 MISC(dest, 0) = rval;
4720 insert_triple(state, dest, rval);
4721 rval->id |= TRIPLE_FLAG_FLATTENED;
4722 use_triple(MISC(dest, 0), dest);
4727 struct type *arithmetic_result(
4728 struct compile_state *state, struct triple *left, struct triple *right)
4731 /* Sanity checks to ensure I am working with arithmetic types */
4732 arithmetic(state, left);
4733 arithmetic(state, right);
4735 do_arithmetic_conversion(
4737 right->type->type), 0, 0);
4741 struct type *ptr_arithmetic_result(
4742 struct compile_state *state, struct triple *left, struct triple *right)
4745 /* Sanity checks to ensure I am working with the proper types */
4746 ptr_arithmetic(state, left);
4747 arithmetic(state, right);
4748 if (TYPE_ARITHMETIC(left->type->type) &&
4749 TYPE_ARITHMETIC(right->type->type)) {
4750 type = arithmetic_result(state, left, right);
4752 else if (TYPE_PTR(left->type->type)) {
4756 internal_error(state, 0, "huh?");
4763 /* boolean helper function */
4765 static struct triple *ltrue_expr(struct compile_state *state,
4766 struct triple *expr)
4769 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4770 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4771 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4772 /* If the expression is already boolean do nothing */
4775 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4781 static struct triple *lfalse_expr(struct compile_state *state,
4782 struct triple *expr)
4784 return triple(state, OP_LFALSE, &int_type, expr, 0);
4787 static struct triple *cond_expr(
4788 struct compile_state *state,
4789 struct triple *test, struct triple *left, struct triple *right)
4792 struct type *result_type;
4793 unsigned int left_type, right_type;
4795 left_type = left->type->type;
4796 right_type = right->type->type;
4798 /* Both operands have arithmetic type */
4799 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4800 result_type = arithmetic_result(state, left, right);
4802 /* Both operands have void type */
4803 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4804 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4805 result_type = &void_type;
4807 /* pointers to the same type... */
4808 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4811 /* Both operands are pointers and left is a pointer to void */
4812 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4813 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4814 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4815 result_type = right->type;
4817 /* Both operands are pointers and right is a pointer to void */
4818 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4819 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4820 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4821 result_type = left->type;
4824 error(state, 0, "Incompatible types in conditional expression");
4826 /* Cleanup and invert the test */
4827 test = lfalse_expr(state, read_expr(state, test));
4828 def = new_triple(state, OP_COND, result_type, 0, 3);
4829 def->param[0] = test;
4830 def->param[1] = left;
4831 def->param[2] = right;
4836 static int expr_depth(struct compile_state *state, struct triple *ins)
4840 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4843 else if (ins->op == OP_DEREF) {
4844 count = expr_depth(state, RHS(ins, 0)) - 1;
4846 else if (ins->op == OP_VAL) {
4847 count = expr_depth(state, RHS(ins, 0)) - 1;
4849 else if (ins->op == OP_COMMA) {
4851 ldepth = expr_depth(state, RHS(ins, 0));
4852 rdepth = expr_depth(state, RHS(ins, 1));
4853 count = (ldepth >= rdepth)? ldepth : rdepth;
4855 else if (ins->op == OP_CALL) {
4856 /* Don't figure the depth of a call just guess it is huge */
4860 struct triple **expr;
4861 expr = triple_rhs(state, ins, 0);
4862 for(;expr; expr = triple_rhs(state, ins, expr)) {
4865 depth = expr_depth(state, *expr);
4866 if (depth > count) {
4875 static struct triple *flatten(
4876 struct compile_state *state, struct triple *first, struct triple *ptr);
4878 static struct triple *flatten_generic(
4879 struct compile_state *state, struct triple *first, struct triple *ptr)
4883 struct triple **ins;
4886 /* Only operations with just a rhs should come here */
4887 rhs = TRIPLE_RHS(ptr->sizes);
4888 lhs = TRIPLE_LHS(ptr->sizes);
4889 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4890 internal_error(state, ptr, "unexpected args for: %d %s",
4891 ptr->op, tops(ptr->op));
4893 /* Find the depth of the rhs elements */
4894 for(i = 0; i < rhs; i++) {
4895 vector[i].ins = &RHS(ptr, i);
4896 vector[i].depth = expr_depth(state, *vector[i].ins);
4898 /* Selection sort the rhs */
4899 for(i = 0; i < rhs; i++) {
4901 for(j = i + 1; j < rhs; j++ ) {
4902 if (vector[j].depth > vector[max].depth) {
4907 struct rhs_vector tmp;
4909 vector[i] = vector[max];
4913 /* Now flatten the rhs elements */
4914 for(i = 0; i < rhs; i++) {
4915 *vector[i].ins = flatten(state, first, *vector[i].ins);
4916 use_triple(*vector[i].ins, ptr);
4919 /* Now flatten the lhs elements */
4920 for(i = 0; i < lhs; i++) {
4921 struct triple **ins = &LHS(ptr, i);
4922 *ins = flatten(state, first, *ins);
4923 use_triple(*ins, ptr);
4928 static struct triple *flatten_land(
4929 struct compile_state *state, struct triple *first, struct triple *ptr)
4931 struct triple *left, *right;
4932 struct triple *val, *test, *jmp, *label1, *end;
4934 /* Find the triples */
4936 right = RHS(ptr, 1);
4938 /* Generate the needed triples */
4941 /* Thread the triples together */
4942 val = flatten(state, first, variable(state, ptr->type));
4943 left = flatten(state, first, write_expr(state, val, left));
4944 test = flatten(state, first,
4945 lfalse_expr(state, read_expr(state, val)));
4946 jmp = flatten(state, first, branch(state, end, test));
4947 label1 = flatten(state, first, label(state));
4948 right = flatten(state, first, write_expr(state, val, right));
4949 TARG(jmp, 0) = flatten(state, first, end);
4951 /* Now give the caller something to chew on */
4952 return read_expr(state, val);
4955 static struct triple *flatten_lor(
4956 struct compile_state *state, struct triple *first, struct triple *ptr)
4958 struct triple *left, *right;
4959 struct triple *val, *jmp, *label1, *end;
4961 /* Find the triples */
4963 right = RHS(ptr, 1);
4965 /* Generate the needed triples */
4968 /* Thread the triples together */
4969 val = flatten(state, first, variable(state, ptr->type));
4970 left = flatten(state, first, write_expr(state, val, left));
4971 jmp = flatten(state, first, branch(state, end, left));
4972 label1 = flatten(state, first, label(state));
4973 right = flatten(state, first, write_expr(state, val, right));
4974 TARG(jmp, 0) = flatten(state, first, end);
4977 /* Now give the caller something to chew on */
4978 return read_expr(state, val);
4981 static struct triple *flatten_cond(
4982 struct compile_state *state, struct triple *first, struct triple *ptr)
4984 struct triple *test, *left, *right;
4985 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4987 /* Find the triples */
4990 right = RHS(ptr, 2);
4992 /* Generate the needed triples */
4994 middle = label(state);
4996 /* Thread the triples together */
4997 val = flatten(state, first, variable(state, ptr->type));
4998 test = flatten(state, first, test);
4999 jmp1 = flatten(state, first, branch(state, middle, test));
5000 label1 = flatten(state, first, label(state));
5001 left = flatten(state, first, left);
5002 mv1 = flatten(state, first, write_expr(state, val, left));
5003 jmp2 = flatten(state, first, branch(state, end, 0));
5004 TARG(jmp1, 0) = flatten(state, first, middle);
5005 right = flatten(state, first, right);
5006 mv2 = flatten(state, first, write_expr(state, val, right));
5007 TARG(jmp2, 0) = flatten(state, first, end);
5009 /* Now give the caller something to chew on */
5010 return read_expr(state, val);
5013 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
5014 struct occurance *base_occurance)
5016 struct triple *nfunc;
5017 struct triple *nfirst, *ofirst;
5018 struct triple *new, *old;
5021 fprintf(stdout, "\n");
5022 loc(stdout, state, 0);
5023 fprintf(stdout, "\n__________ copy_func _________\n");
5024 print_triple(state, ofunc);
5025 fprintf(stdout, "__________ copy_func _________ done\n\n");
5028 /* Make a new copy of the old function */
5029 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
5031 ofirst = old = RHS(ofunc, 0);
5034 struct occurance *occurance;
5035 int old_lhs, old_rhs;
5036 old_lhs = TRIPLE_LHS(old->sizes);
5037 old_rhs = TRIPLE_RHS(old->sizes);
5038 occurance = inline_occurance(state, base_occurance, old->occurance);
5039 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
5041 if (!triple_stores_block(state, new)) {
5042 memcpy(&new->u, &old->u, sizeof(new->u));
5045 RHS(nfunc, 0) = nfirst = new;
5048 insert_triple(state, nfirst, new);
5050 new->id |= TRIPLE_FLAG_FLATTENED;
5052 /* During the copy remember new as user of old */
5053 use_triple(old, new);
5055 /* Populate the return type if present */
5056 if (old == MISC(ofunc, 0)) {
5057 MISC(nfunc, 0) = new;
5060 } while(old != ofirst);
5062 /* Make a second pass to fix up any unresolved references */
5066 struct triple **oexpr, **nexpr;
5068 /* Lookup where the copy is, to join pointers */
5069 count = TRIPLE_SIZE(old->sizes);
5070 for(i = 0; i < count; i++) {
5071 oexpr = &old->param[i];
5072 nexpr = &new->param[i];
5073 if (!*nexpr && *oexpr && (*oexpr)->use) {
5074 *nexpr = (*oexpr)->use->member;
5075 if (*nexpr == old) {
5076 internal_error(state, 0, "new == old?");
5078 use_triple(*nexpr, new);
5080 if (!*nexpr && *oexpr) {
5081 internal_error(state, 0, "Could not copy %d\n", i);
5086 } while((old != ofirst) && (new != nfirst));
5088 /* Make a third pass to cleanup the extra useses */
5092 unuse_triple(old, new);
5095 } while ((old != ofirst) && (new != nfirst));
5099 static struct triple *flatten_call(
5100 struct compile_state *state, struct triple *first, struct triple *ptr)
5102 /* Inline the function call */
5104 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5105 struct triple *end, *nend;
5108 /* Find the triples */
5109 ofunc = MISC(ptr, 0);
5110 if (ofunc->op != OP_LIST) {
5111 internal_error(state, 0, "improper function");
5113 nfunc = copy_func(state, ofunc, ptr->occurance);
5114 nfirst = RHS(nfunc, 0)->next;
5115 /* Prepend the parameter reading into the new function list */
5116 ptype = nfunc->type->right;
5117 param = RHS(nfunc, 0)->next;
5118 pvals = TRIPLE_RHS(ptr->sizes);
5119 for(i = 0; i < pvals; i++) {
5123 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5124 atype = ptype->left;
5126 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5127 param = param->next;
5130 flatten(state, nfirst, write_expr(state, param, arg));
5131 ptype = ptype->right;
5132 param = param->next;
5135 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5136 result = read_expr(state, MISC(nfunc,0));
5139 fprintf(stdout, "\n");
5140 loc(stdout, state, 0);
5141 fprintf(stdout, "\n__________ flatten_call _________\n");
5142 print_triple(state, nfunc);
5143 fprintf(stdout, "__________ flatten_call _________ done\n\n");
5146 /* Get rid of the extra triples */
5147 nfirst = RHS(nfunc, 0)->next;
5148 free_triple(state, RHS(nfunc, 0));
5150 free_triple(state, nfunc);
5152 /* Append the new function list onto the return list */
5154 nend = nfirst->prev;
5163 static struct triple *flatten(
5164 struct compile_state *state, struct triple *first, struct triple *ptr)
5166 struct triple *orig_ptr;
5171 /* Only flatten triples once */
5172 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5177 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5181 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5182 return MISC(ptr, 0);
5185 ptr = flatten_land(state, first, ptr);
5188 ptr = flatten_lor(state, first, ptr);
5191 ptr = flatten_cond(state, first, ptr);
5194 ptr = flatten_call(state, first, ptr);
5198 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5199 use_triple(RHS(ptr, 0), ptr);
5202 use_triple(TARG(ptr, 0), ptr);
5203 if (TRIPLE_RHS(ptr->sizes)) {
5204 use_triple(RHS(ptr, 0), ptr);
5205 if (ptr->next != ptr) {
5206 use_triple(ptr->next, ptr);
5211 insert_triple(state, first, ptr);
5212 ptr->id |= TRIPLE_FLAG_FLATTENED;
5213 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5214 use_triple(MISC(ptr, 0), ptr);
5217 /* Since OP_DEREF is just a marker delete it when I flatten it */
5219 RHS(orig_ptr, 0) = 0;
5220 free_triple(state, orig_ptr);
5224 struct triple *base;
5226 if (base->op == OP_DEREF) {
5227 struct triple *left;
5229 offset = field_offset(state, base->type, ptr->u.field);
5230 left = RHS(base, 0);
5231 ptr = triple(state, OP_ADD, left->type,
5232 read_expr(state, left),
5233 int_const(state, &ulong_type, offset));
5234 free_triple(state, base);
5236 else if (base->op == OP_VAL_VEC) {
5237 base = flatten(state, first, base);
5238 ptr = struct_field(state, base, ptr->u.field);
5243 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5244 use_triple(MISC(ptr, 0), ptr);
5245 use_triple(ptr, MISC(ptr, 0));
5249 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5250 use_triple(MISC(ptr, 0), ptr);
5255 /* Flatten the easy cases we don't override */
5256 ptr = flatten_generic(state, first, ptr);
5259 } while(ptr && (ptr != orig_ptr));
5261 insert_triple(state, first, ptr);
5262 ptr->id |= TRIPLE_FLAG_FLATTENED;
5267 static void release_expr(struct compile_state *state, struct triple *expr)
5269 struct triple *head;
5270 head = label(state);
5271 flatten(state, head, expr);
5272 while(head->next != head) {
5273 release_triple(state, head->next);
5275 free_triple(state, head);
5278 static int replace_rhs_use(struct compile_state *state,
5279 struct triple *orig, struct triple *new, struct triple *use)
5281 struct triple **expr;
5284 expr = triple_rhs(state, use, 0);
5285 for(;expr; expr = triple_rhs(state, use, expr)) {
5286 if (*expr == orig) {
5292 unuse_triple(orig, use);
5293 use_triple(new, use);
5298 static int replace_lhs_use(struct compile_state *state,
5299 struct triple *orig, struct triple *new, struct triple *use)
5301 struct triple **expr;
5304 expr = triple_lhs(state, use, 0);
5305 for(;expr; expr = triple_lhs(state, use, expr)) {
5306 if (*expr == orig) {
5312 unuse_triple(orig, use);
5313 use_triple(new, use);
5318 static void propogate_use(struct compile_state *state,
5319 struct triple *orig, struct triple *new)
5321 struct triple_set *user, *next;
5322 for(user = orig->use; user; user = next) {
5328 found |= replace_rhs_use(state, orig, new, use);
5329 found |= replace_lhs_use(state, orig, new, use);
5331 internal_error(state, use, "use without use");
5335 internal_error(state, orig, "used after propogate_use");
5341 * ===========================
5344 static struct triple *mk_add_expr(
5345 struct compile_state *state, struct triple *left, struct triple *right)
5347 struct type *result_type;
5348 /* Put pointer operands on the left */
5349 if (is_pointer(right)) {
5355 left = read_expr(state, left);
5356 right = read_expr(state, right);
5357 result_type = ptr_arithmetic_result(state, left, right);
5358 if (is_pointer(left)) {
5359 right = triple(state,
5360 is_signed(right->type)? OP_SMUL : OP_UMUL,
5363 int_const(state, &ulong_type,
5364 size_of(state, left->type->left)));
5366 return triple(state, OP_ADD, result_type, left, right);
5369 static struct triple *mk_sub_expr(
5370 struct compile_state *state, struct triple *left, struct triple *right)
5372 struct type *result_type;
5373 result_type = ptr_arithmetic_result(state, left, right);
5374 left = read_expr(state, left);
5375 right = read_expr(state, right);
5376 if (is_pointer(left)) {
5377 right = triple(state,
5378 is_signed(right->type)? OP_SMUL : OP_UMUL,
5381 int_const(state, &ulong_type,
5382 size_of(state, left->type->left)));
5384 return triple(state, OP_SUB, result_type, left, right);
5387 static struct triple *mk_pre_inc_expr(
5388 struct compile_state *state, struct triple *def)
5392 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5393 return triple(state, OP_VAL, def->type,
5394 write_expr(state, def, val),
5398 static struct triple *mk_pre_dec_expr(
5399 struct compile_state *state, struct triple *def)
5403 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5404 return triple(state, OP_VAL, def->type,
5405 write_expr(state, def, val),
5409 static struct triple *mk_post_inc_expr(
5410 struct compile_state *state, struct triple *def)
5414 val = read_expr(state, def);
5415 return triple(state, OP_VAL, def->type,
5416 write_expr(state, def,
5417 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5421 static struct triple *mk_post_dec_expr(
5422 struct compile_state *state, struct triple *def)
5426 val = read_expr(state, def);
5427 return triple(state, OP_VAL, def->type,
5428 write_expr(state, def,
5429 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5433 static struct triple *mk_subscript_expr(
5434 struct compile_state *state, struct triple *left, struct triple *right)
5436 left = read_expr(state, left);
5437 right = read_expr(state, right);
5438 if (!is_pointer(left) && !is_pointer(right)) {
5439 error(state, left, "subscripted value is not a pointer");
5441 return mk_deref_expr(state, mk_add_expr(state, left, right));
5445 * Compile time evaluation
5446 * ===========================
5448 static int is_const(struct triple *ins)
5450 return IS_CONST_OP(ins->op);
5453 static int constants_equal(struct compile_state *state,
5454 struct triple *left, struct triple *right)
5457 if (!is_const(left) || !is_const(right)) {
5460 else if (left->op != right->op) {
5463 else if (!equiv_types(left->type, right->type)) {
5470 if (left->u.cval == right->u.cval) {
5476 size_t lsize, rsize;
5477 lsize = size_of(state, left->type);
5478 rsize = size_of(state, right->type);
5479 if (lsize != rsize) {
5482 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5488 if ((MISC(left, 0) == MISC(right, 0)) &&
5489 (left->u.cval == right->u.cval)) {
5494 internal_error(state, left, "uknown constant type");
5501 static int is_zero(struct triple *ins)
5503 return is_const(ins) && (ins->u.cval == 0);
5506 static int is_one(struct triple *ins)
5508 return is_const(ins) && (ins->u.cval == 1);
5511 static long_t bit_count(ulong_t value)
5516 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5527 static long_t bsr(ulong_t value)
5530 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5541 static long_t bsf(ulong_t value)
5544 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5555 static long_t log2(ulong_t value)
5560 static long_t tlog2(struct triple *ins)
5562 return log2(ins->u.cval);
5565 static int is_pow2(struct triple *ins)
5567 ulong_t value, mask;
5569 if (!is_const(ins)) {
5572 value = ins->u.cval;
5579 return ((value & mask) == value);
5582 static ulong_t read_const(struct compile_state *state,
5583 struct triple *ins, struct triple **expr)
5587 switch(rhs->type->type &TYPE_MASK) {
5599 internal_error(state, rhs, "bad type to read_const\n");
5605 static long_t read_sconst(struct triple *ins, struct triple **expr)
5609 return (long_t)(rhs->u.cval);
5612 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5614 struct triple **expr;
5615 expr = triple_rhs(state, ins, 0);
5616 for(;expr;expr = triple_rhs(state, ins, expr)) {
5618 unuse_triple(*expr, ins);
5624 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5626 struct triple **expr;
5627 expr = triple_lhs(state, ins, 0);
5628 for(;expr;expr = triple_lhs(state, ins, expr)) {
5629 unuse_triple(*expr, ins);
5634 static void check_lhs(struct compile_state *state, struct triple *ins)
5636 struct triple **expr;
5637 expr = triple_lhs(state, ins, 0);
5638 for(;expr;expr = triple_lhs(state, ins, expr)) {
5639 internal_error(state, ins, "unexpected lhs");
5643 static void check_targ(struct compile_state *state, struct triple *ins)
5645 struct triple **expr;
5646 expr = triple_targ(state, ins, 0);
5647 for(;expr;expr = triple_targ(state, ins, expr)) {
5648 internal_error(state, ins, "unexpected targ");
5652 static void wipe_ins(struct compile_state *state, struct triple *ins)
5654 /* Becareful which instructions you replace the wiped
5655 * instruction with, as there are not enough slots
5656 * in all instructions to hold all others.
5658 check_targ(state, ins);
5659 unuse_rhs(state, ins);
5660 unuse_lhs(state, ins);
5663 static void mkcopy(struct compile_state *state,
5664 struct triple *ins, struct triple *rhs)
5666 wipe_ins(state, ins);
5668 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5670 use_triple(RHS(ins, 0), ins);
5673 static void mkconst(struct compile_state *state,
5674 struct triple *ins, ulong_t value)
5676 if (!is_integral(ins) && !is_pointer(ins)) {
5677 internal_error(state, ins, "unknown type to make constant\n");
5679 wipe_ins(state, ins);
5680 ins->op = OP_INTCONST;
5681 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5682 ins->u.cval = value;
5685 static void mkaddr_const(struct compile_state *state,
5686 struct triple *ins, struct triple *sdecl, ulong_t value)
5688 wipe_ins(state, ins);
5689 ins->op = OP_ADDRCONST;
5690 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5691 MISC(ins, 0) = sdecl;
5692 ins->u.cval = value;
5693 use_triple(sdecl, ins);
5696 /* Transform multicomponent variables into simple register variables */
5697 static void flatten_structures(struct compile_state *state)
5699 struct triple *ins, *first;
5700 first = RHS(state->main_function, 0);
5702 /* Pass one expand structure values into valvecs.
5706 struct triple *next;
5708 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5709 if (ins->op == OP_VAL_VEC) {
5712 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5713 struct triple *def, **vector;
5720 get_occurance(ins->occurance);
5721 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5724 vector = &RHS(next, 0);
5725 tptr = next->type->left;
5726 for(i = 0; i < next->type->elements; i++) {
5727 struct triple *sfield;
5730 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5731 mtype = mtype->left;
5733 sfield = deref_field(state, def, mtype->field_ident);
5736 state, op, mtype, sfield, 0);
5737 put_occurance(vector[i]->occurance);
5738 get_occurance(next->occurance);
5739 vector[i]->occurance = next->occurance;
5742 propogate_use(state, ins, next);
5743 flatten(state, ins, next);
5744 free_triple(state, ins);
5746 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5747 struct triple *src, *dst, **vector;
5755 get_occurance(ins->occurance);
5756 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5759 vector = &RHS(next, 0);
5760 tptr = next->type->left;
5761 for(i = 0; i < ins->type->elements; i++) {
5762 struct triple *dfield, *sfield;
5765 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5766 mtype = mtype->left;
5768 sfield = deref_field(state, src, mtype->field_ident);
5769 dfield = deref_field(state, dst, mtype->field_ident);
5771 state, op, mtype, dfield, sfield);
5772 put_occurance(vector[i]->occurance);
5773 get_occurance(next->occurance);
5774 vector[i]->occurance = next->occurance;
5777 propogate_use(state, ins, next);
5778 flatten(state, ins, next);
5779 free_triple(state, ins);
5783 } while(ins != first);
5784 /* Pass two flatten the valvecs.
5788 struct triple *next;
5790 if (ins->op == OP_VAL_VEC) {
5791 release_triple(state, ins);
5794 } while(ins != first);
5795 /* Pass three verify the state and set ->id to 0.
5799 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5800 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5801 internal_error(state, ins, "STRUCT_TYPE remains?");
5803 if (ins->op == OP_DOT) {
5804 internal_error(state, ins, "OP_DOT remains?");
5806 if (ins->op == OP_VAL_VEC) {
5807 internal_error(state, ins, "OP_VAL_VEC remains?");
5810 } while(ins != first);
5813 /* For those operations that cannot be simplified */
5814 static void simplify_noop(struct compile_state *state, struct triple *ins)
5819 static void simplify_smul(struct compile_state *state, struct triple *ins)
5821 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5824 RHS(ins, 0) = RHS(ins, 1);
5827 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5829 left = read_sconst(ins, &RHS(ins, 0));
5830 right = read_sconst(ins, &RHS(ins, 1));
5831 mkconst(state, ins, left * right);
5833 else if (is_zero(RHS(ins, 1))) {
5834 mkconst(state, ins, 0);
5836 else if (is_one(RHS(ins, 1))) {
5837 mkcopy(state, ins, RHS(ins, 0));
5839 else if (is_pow2(RHS(ins, 1))) {
5841 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5843 insert_triple(state, ins, val);
5844 unuse_triple(RHS(ins, 1), ins);
5845 use_triple(val, ins);
5850 static void simplify_umul(struct compile_state *state, struct triple *ins)
5852 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5855 RHS(ins, 0) = RHS(ins, 1);
5858 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5859 ulong_t left, right;
5860 left = read_const(state, ins, &RHS(ins, 0));
5861 right = read_const(state, ins, &RHS(ins, 1));
5862 mkconst(state, ins, left * right);
5864 else if (is_zero(RHS(ins, 1))) {
5865 mkconst(state, ins, 0);
5867 else if (is_one(RHS(ins, 1))) {
5868 mkcopy(state, ins, RHS(ins, 0));
5870 else if (is_pow2(RHS(ins, 1))) {
5872 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5874 insert_triple(state, ins, val);
5875 unuse_triple(RHS(ins, 1), ins);
5876 use_triple(val, ins);
5881 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5883 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5885 left = read_sconst(ins, &RHS(ins, 0));
5886 right = read_sconst(ins, &RHS(ins, 1));
5887 mkconst(state, ins, left / right);
5889 else if (is_zero(RHS(ins, 0))) {
5890 mkconst(state, ins, 0);
5892 else if (is_zero(RHS(ins, 1))) {
5893 error(state, ins, "division by zero");
5895 else if (is_one(RHS(ins, 1))) {
5896 mkcopy(state, ins, RHS(ins, 0));
5898 else if (is_pow2(RHS(ins, 1))) {
5900 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5902 insert_triple(state, ins, val);
5903 unuse_triple(RHS(ins, 1), ins);
5904 use_triple(val, ins);
5909 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5911 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5912 ulong_t left, right;
5913 left = read_const(state, ins, &RHS(ins, 0));
5914 right = read_const(state, ins, &RHS(ins, 1));
5915 mkconst(state, ins, left / right);
5917 else if (is_zero(RHS(ins, 0))) {
5918 mkconst(state, ins, 0);
5920 else if (is_zero(RHS(ins, 1))) {
5921 error(state, ins, "division by zero");
5923 else if (is_one(RHS(ins, 1))) {
5924 mkcopy(state, ins, RHS(ins, 0));
5926 else if (is_pow2(RHS(ins, 1))) {
5928 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5930 insert_triple(state, ins, val);
5931 unuse_triple(RHS(ins, 1), ins);
5932 use_triple(val, ins);
5937 static void simplify_smod(struct compile_state *state, struct triple *ins)
5939 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5941 left = read_const(state, ins, &RHS(ins, 0));
5942 right = read_const(state, ins, &RHS(ins, 1));
5943 mkconst(state, ins, left % right);
5945 else if (is_zero(RHS(ins, 0))) {
5946 mkconst(state, ins, 0);
5948 else if (is_zero(RHS(ins, 1))) {
5949 error(state, ins, "division by zero");
5951 else if (is_one(RHS(ins, 1))) {
5952 mkconst(state, ins, 0);
5954 else if (is_pow2(RHS(ins, 1))) {
5956 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5958 insert_triple(state, ins, val);
5959 unuse_triple(RHS(ins, 1), ins);
5960 use_triple(val, ins);
5964 static void simplify_umod(struct compile_state *state, struct triple *ins)
5966 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5967 ulong_t left, right;
5968 left = read_const(state, ins, &RHS(ins, 0));
5969 right = read_const(state, ins, &RHS(ins, 1));
5970 mkconst(state, ins, left % right);
5972 else if (is_zero(RHS(ins, 0))) {
5973 mkconst(state, ins, 0);
5975 else if (is_zero(RHS(ins, 1))) {
5976 error(state, ins, "division by zero");
5978 else if (is_one(RHS(ins, 1))) {
5979 mkconst(state, ins, 0);
5981 else if (is_pow2(RHS(ins, 1))) {
5983 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5985 insert_triple(state, ins, val);
5986 unuse_triple(RHS(ins, 1), ins);
5987 use_triple(val, ins);
5992 static void simplify_add(struct compile_state *state, struct triple *ins)
5994 /* start with the pointer on the left */
5995 if (is_pointer(RHS(ins, 1))) {
5998 RHS(ins, 0) = RHS(ins, 1);
6001 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6002 if (RHS(ins, 0)->op == OP_INTCONST) {
6003 ulong_t left, right;
6004 left = read_const(state, ins, &RHS(ins, 0));
6005 right = read_const(state, ins, &RHS(ins, 1));
6006 mkconst(state, ins, left + right);
6008 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
6009 struct triple *sdecl;
6010 ulong_t left, right;
6011 sdecl = MISC(RHS(ins, 0), 0);
6012 left = RHS(ins, 0)->u.cval;
6013 right = RHS(ins, 1)->u.cval;
6014 mkaddr_const(state, ins, sdecl, left + right);
6017 internal_warning(state, ins, "Optimize me!");
6020 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
6023 RHS(ins, 1) = RHS(ins, 0);
6028 static void simplify_sub(struct compile_state *state, struct triple *ins)
6030 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6031 if (RHS(ins, 0)->op == OP_INTCONST) {
6032 ulong_t left, right;
6033 left = read_const(state, ins, &RHS(ins, 0));
6034 right = read_const(state, ins, &RHS(ins, 1));
6035 mkconst(state, ins, left - right);
6037 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
6038 struct triple *sdecl;
6039 ulong_t left, right;
6040 sdecl = MISC(RHS(ins, 0), 0);
6041 left = RHS(ins, 0)->u.cval;
6042 right = RHS(ins, 1)->u.cval;
6043 mkaddr_const(state, ins, sdecl, left - right);
6046 internal_warning(state, ins, "Optimize me!");
6051 static void simplify_sl(struct compile_state *state, struct triple *ins)
6053 if (is_const(RHS(ins, 1))) {
6055 right = read_const(state, ins, &RHS(ins, 1));
6056 if (right >= (size_of(state, ins->type)*8)) {
6057 warning(state, ins, "left shift count >= width of type");
6060 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6061 ulong_t left, right;
6062 left = read_const(state, ins, &RHS(ins, 0));
6063 right = read_const(state, ins, &RHS(ins, 1));
6064 mkconst(state, ins, left << right);
6068 static void simplify_usr(struct compile_state *state, struct triple *ins)
6070 if (is_const(RHS(ins, 1))) {
6072 right = read_const(state, ins, &RHS(ins, 1));
6073 if (right >= (size_of(state, ins->type)*8)) {
6074 warning(state, ins, "right shift count >= width of type");
6077 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6078 ulong_t left, right;
6079 left = read_const(state, ins, &RHS(ins, 0));
6080 right = read_const(state, ins, &RHS(ins, 1));
6081 mkconst(state, ins, left >> right);
6085 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6087 if (is_const(RHS(ins, 1))) {
6089 right = read_const(state, ins, &RHS(ins, 1));
6090 if (right >= (size_of(state, ins->type)*8)) {
6091 warning(state, ins, "right shift count >= width of type");
6094 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6096 left = read_sconst(ins, &RHS(ins, 0));
6097 right = read_sconst(ins, &RHS(ins, 1));
6098 mkconst(state, ins, left >> right);
6102 static void simplify_and(struct compile_state *state, struct triple *ins)
6104 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6105 ulong_t left, right;
6106 left = read_const(state, ins, &RHS(ins, 0));
6107 right = read_const(state, ins, &RHS(ins, 1));
6108 mkconst(state, ins, left & right);
6112 static void simplify_or(struct compile_state *state, struct triple *ins)
6114 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6115 ulong_t left, right;
6116 left = read_const(state, ins, &RHS(ins, 0));
6117 right = read_const(state, ins, &RHS(ins, 1));
6118 mkconst(state, ins, left | right);
6122 static void simplify_xor(struct compile_state *state, struct triple *ins)
6124 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6125 ulong_t left, right;
6126 left = read_const(state, ins, &RHS(ins, 0));
6127 right = read_const(state, ins, &RHS(ins, 1));
6128 mkconst(state, ins, left ^ right);
6132 static void simplify_pos(struct compile_state *state, struct triple *ins)
6134 if (is_const(RHS(ins, 0))) {
6135 mkconst(state, ins, RHS(ins, 0)->u.cval);
6138 mkcopy(state, ins, RHS(ins, 0));
6142 static void simplify_neg(struct compile_state *state, struct triple *ins)
6144 if (is_const(RHS(ins, 0))) {
6146 left = read_const(state, ins, &RHS(ins, 0));
6147 mkconst(state, ins, -left);
6149 else if (RHS(ins, 0)->op == OP_NEG) {
6150 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6154 static void simplify_invert(struct compile_state *state, struct triple *ins)
6156 if (is_const(RHS(ins, 0))) {
6158 left = read_const(state, ins, &RHS(ins, 0));
6159 mkconst(state, ins, ~left);
6163 static void simplify_eq(struct compile_state *state, struct triple *ins)
6165 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6166 ulong_t left, right;
6167 left = read_const(state, ins, &RHS(ins, 0));
6168 right = read_const(state, ins, &RHS(ins, 1));
6169 mkconst(state, ins, left == right);
6171 else if (RHS(ins, 0) == RHS(ins, 1)) {
6172 mkconst(state, ins, 1);
6176 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6178 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6179 ulong_t left, right;
6180 left = read_const(state, ins, &RHS(ins, 0));
6181 right = read_const(state, ins, &RHS(ins, 1));
6182 mkconst(state, ins, left != right);
6184 else if (RHS(ins, 0) == RHS(ins, 1)) {
6185 mkconst(state, ins, 0);
6189 static void simplify_sless(struct compile_state *state, struct triple *ins)
6191 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6193 left = read_sconst(ins, &RHS(ins, 0));
6194 right = read_sconst(ins, &RHS(ins, 1));
6195 mkconst(state, ins, left < right);
6197 else if (RHS(ins, 0) == RHS(ins, 1)) {
6198 mkconst(state, ins, 0);
6202 static void simplify_uless(struct compile_state *state, struct triple *ins)
6204 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6205 ulong_t left, right;
6206 left = read_const(state, ins, &RHS(ins, 0));
6207 right = read_const(state, ins, &RHS(ins, 1));
6208 mkconst(state, ins, left < right);
6210 else if (is_zero(RHS(ins, 0))) {
6211 mkconst(state, ins, 1);
6213 else if (RHS(ins, 0) == RHS(ins, 1)) {
6214 mkconst(state, ins, 0);
6218 static void simplify_smore(struct compile_state *state, struct triple *ins)
6220 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6222 left = read_sconst(ins, &RHS(ins, 0));
6223 right = read_sconst(ins, &RHS(ins, 1));
6224 mkconst(state, ins, left > right);
6226 else if (RHS(ins, 0) == RHS(ins, 1)) {
6227 mkconst(state, ins, 0);
6231 static void simplify_umore(struct compile_state *state, struct triple *ins)
6233 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6234 ulong_t left, right;
6235 left = read_const(state, ins, &RHS(ins, 0));
6236 right = read_const(state, ins, &RHS(ins, 1));
6237 mkconst(state, ins, left > right);
6239 else if (is_zero(RHS(ins, 1))) {
6240 mkconst(state, ins, 1);
6242 else if (RHS(ins, 0) == RHS(ins, 1)) {
6243 mkconst(state, ins, 0);
6248 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6250 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6252 left = read_sconst(ins, &RHS(ins, 0));
6253 right = read_sconst(ins, &RHS(ins, 1));
6254 mkconst(state, ins, left <= right);
6256 else if (RHS(ins, 0) == RHS(ins, 1)) {
6257 mkconst(state, ins, 1);
6261 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6263 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6264 ulong_t left, right;
6265 left = read_const(state, ins, &RHS(ins, 0));
6266 right = read_const(state, ins, &RHS(ins, 1));
6267 mkconst(state, ins, left <= right);
6269 else if (is_zero(RHS(ins, 0))) {
6270 mkconst(state, ins, 1);
6272 else if (RHS(ins, 0) == RHS(ins, 1)) {
6273 mkconst(state, ins, 1);
6277 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6279 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6281 left = read_sconst(ins, &RHS(ins, 0));
6282 right = read_sconst(ins, &RHS(ins, 1));
6283 mkconst(state, ins, left >= right);
6285 else if (RHS(ins, 0) == RHS(ins, 1)) {
6286 mkconst(state, ins, 1);
6290 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6292 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6293 ulong_t left, right;
6294 left = read_const(state, ins, &RHS(ins, 0));
6295 right = read_const(state, ins, &RHS(ins, 1));
6296 mkconst(state, ins, left >= right);
6298 else if (is_zero(RHS(ins, 1))) {
6299 mkconst(state, ins, 1);
6301 else if (RHS(ins, 0) == RHS(ins, 1)) {
6302 mkconst(state, ins, 1);
6306 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6308 if (is_const(RHS(ins, 0))) {
6310 left = read_const(state, ins, &RHS(ins, 0));
6311 mkconst(state, ins, left == 0);
6313 /* Otherwise if I am the only user... */
6314 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6316 /* Invert a boolean operation */
6317 switch(RHS(ins, 0)->op) {
6318 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
6319 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
6320 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
6321 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
6322 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
6323 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
6324 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
6325 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
6326 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
6327 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
6328 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
6329 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
6335 mkcopy(state, ins, RHS(ins, 0));
6340 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6342 if (is_const(RHS(ins, 0))) {
6344 left = read_const(state, ins, &RHS(ins, 0));
6345 mkconst(state, ins, left != 0);
6347 else switch(RHS(ins, 0)->op) {
6348 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
6349 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
6350 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6351 mkcopy(state, ins, RHS(ins, 0));
6356 static void simplify_copy(struct compile_state *state, struct triple *ins)
6358 if (is_const(RHS(ins, 0))) {
6359 switch(RHS(ins, 0)->op) {
6363 left = read_const(state, ins, &RHS(ins, 0));
6364 mkconst(state, ins, left);
6369 struct triple *sdecl;
6371 sdecl = MISC(RHS(ins, 0), 0);
6372 offset = RHS(ins, 0)->u.cval;
6373 mkaddr_const(state, ins, sdecl, offset);
6377 internal_error(state, ins, "uknown constant");
6383 static void simplify_branch(struct compile_state *state, struct triple *ins)
6385 struct block *block;
6386 if (ins->op != OP_BRANCH) {
6387 internal_error(state, ins, "not branch");
6389 if (ins->use != 0) {
6390 internal_error(state, ins, "branch use");
6392 #warning "FIXME implement simplify branch."
6393 /* The challenge here with simplify branch is that I need to
6394 * make modifications to the control flow graph as well
6395 * as to the branch instruction itself.
6397 block = ins->u.block;
6399 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6400 struct triple *targ;
6402 value = read_const(state, ins, &RHS(ins, 0));
6403 unuse_triple(RHS(ins, 0), ins);
6404 targ = TARG(ins, 0);
6405 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6407 unuse_triple(ins->next, ins);
6408 TARG(ins, 0) = targ;
6411 unuse_triple(targ, ins);
6412 TARG(ins, 0) = ins->next;
6414 #warning "FIXME handle the case of making a branch unconditional"
6416 if (TARG(ins, 0) == ins->next) {
6417 unuse_triple(ins->next, ins);
6418 if (TRIPLE_RHS(ins->sizes)) {
6419 unuse_triple(RHS(ins, 0), ins);
6420 unuse_triple(ins->next, ins);
6422 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6425 internal_error(state, ins, "noop use != 0");
6427 #warning "FIXME handle the case of killing a branch"
6431 int phi_present(struct block *block)
6439 if (ptr->op == OP_PHI) {
6443 } while(ptr != block->last);
6447 static void simplify_label(struct compile_state *state, struct triple *ins)
6449 #warning "FIXME enable simplify_label"
6450 struct triple *first, *last;
6451 first = RHS(state->main_function, 0);
6453 /* Ignore the first and last instructions */
6454 if ((ins == first) || (ins == last)) {
6457 if (ins->use == 0) {
6460 else if (ins->prev->op == OP_LABEL) {
6461 struct block *block;
6462 block = ins->prev->u.block;
6463 /* In general it is not safe to merge one label that
6464 * imediately follows another. The problem is that the empty
6465 * looking block may have phi functions that depend on it.
6468 (!phi_present(block->left) &&
6469 !phi_present(block->right)))
6471 struct triple_set *user, *next;
6473 for(user = ins->use; user; user = next) {
6477 if (TARG(use, 0) == ins) {
6478 TARG(use, 0) = ins->prev;
6479 unuse_triple(ins, use);
6480 use_triple(ins->prev, use);
6484 internal_error(state, ins, "noop use != 0");
6490 static void simplify_phi(struct compile_state *state, struct triple *ins)
6492 struct triple **expr;
6494 expr = triple_rhs(state, ins, 0);
6495 if (!*expr || !is_const(*expr)) {
6498 value = read_const(state, ins, expr);
6499 for(;expr;expr = triple_rhs(state, ins, expr)) {
6500 if (!*expr || !is_const(*expr)) {
6503 if (value != read_const(state, ins, expr)) {
6507 mkconst(state, ins, value);
6511 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6513 if (is_const(RHS(ins, 0))) {
6515 left = read_const(state, ins, &RHS(ins, 0));
6516 mkconst(state, ins, bsf(left));
6520 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6522 if (is_const(RHS(ins, 0))) {
6524 left = read_const(state, ins, &RHS(ins, 0));
6525 mkconst(state, ins, bsr(left));
6530 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6531 static const simplify_t table_simplify[] = {
6533 #define simplify_sdivt simplify_noop
6534 #define simplify_udivt simplify_noop
6537 #define simplify_smul simplify_noop
6538 #define simplify_umul simplify_noop
6539 #define simplify_sdiv simplify_noop
6540 #define simplify_udiv simplify_noop
6541 #define simplify_smod simplify_noop
6542 #define simplify_umod simplify_noop
6545 #define simplify_add simplify_noop
6546 #define simplify_sub simplify_noop
6549 #define simplify_sl simplify_noop
6550 #define simplify_usr simplify_noop
6551 #define simplify_ssr simplify_noop
6554 #define simplify_and simplify_noop
6555 #define simplify_xor simplify_noop
6556 #define simplify_or simplify_noop
6559 #define simplify_pos simplify_noop
6560 #define simplify_neg simplify_noop
6561 #define simplify_invert simplify_noop
6565 #define simplify_eq simplify_noop
6566 #define simplify_noteq simplify_noop
6569 #define simplify_sless simplify_noop
6570 #define simplify_uless simplify_noop
6571 #define simplify_smore simplify_noop
6572 #define simplify_umore simplify_noop
6575 #define simplify_slesseq simplify_noop
6576 #define simplify_ulesseq simplify_noop
6577 #define simplify_smoreeq simplify_noop
6578 #define simplify_umoreeq simplify_noop
6581 #define simplify_lfalse simplify_noop
6584 #define simplify_ltrue simplify_noop
6588 #define simplify_copy simplify_noop
6592 #define simplify_branch simplify_noop
6595 #define simplify_label simplify_noop
6599 #define simplify_phi simplify_noop
6603 #define simplify_bsf simplify_noop
6604 #define simplify_bsr simplify_noop
6607 [OP_SDIVT ] = simplify_sdivt,
6608 [OP_UDIVT ] = simplify_udivt,
6609 [OP_SMUL ] = simplify_smul,
6610 [OP_UMUL ] = simplify_umul,
6611 [OP_SDIV ] = simplify_sdiv,
6612 [OP_UDIV ] = simplify_udiv,
6613 [OP_SMOD ] = simplify_smod,
6614 [OP_UMOD ] = simplify_umod,
6615 [OP_ADD ] = simplify_add,
6616 [OP_SUB ] = simplify_sub,
6617 [OP_SL ] = simplify_sl,
6618 [OP_USR ] = simplify_usr,
6619 [OP_SSR ] = simplify_ssr,
6620 [OP_AND ] = simplify_and,
6621 [OP_XOR ] = simplify_xor,
6622 [OP_OR ] = simplify_or,
6623 [OP_POS ] = simplify_pos,
6624 [OP_NEG ] = simplify_neg,
6625 [OP_INVERT ] = simplify_invert,
6627 [OP_EQ ] = simplify_eq,
6628 [OP_NOTEQ ] = simplify_noteq,
6629 [OP_SLESS ] = simplify_sless,
6630 [OP_ULESS ] = simplify_uless,
6631 [OP_SMORE ] = simplify_smore,
6632 [OP_UMORE ] = simplify_umore,
6633 [OP_SLESSEQ ] = simplify_slesseq,
6634 [OP_ULESSEQ ] = simplify_ulesseq,
6635 [OP_SMOREEQ ] = simplify_smoreeq,
6636 [OP_UMOREEQ ] = simplify_umoreeq,
6637 [OP_LFALSE ] = simplify_lfalse,
6638 [OP_LTRUE ] = simplify_ltrue,
6640 [OP_LOAD ] = simplify_noop,
6641 [OP_STORE ] = simplify_noop,
6643 [OP_NOOP ] = simplify_noop,
6645 [OP_INTCONST ] = simplify_noop,
6646 [OP_BLOBCONST ] = simplify_noop,
6647 [OP_ADDRCONST ] = simplify_noop,
6649 [OP_WRITE ] = simplify_noop,
6650 [OP_READ ] = simplify_noop,
6651 [OP_COPY ] = simplify_copy,
6652 [OP_PIECE ] = simplify_noop,
6653 [OP_ASM ] = simplify_noop,
6655 [OP_DOT ] = simplify_noop,
6656 [OP_VAL_VEC ] = simplify_noop,
6658 [OP_LIST ] = simplify_noop,
6659 [OP_BRANCH ] = simplify_branch,
6660 [OP_LABEL ] = simplify_label,
6661 [OP_ADECL ] = simplify_noop,
6662 [OP_SDECL ] = simplify_noop,
6663 [OP_PHI ] = simplify_phi,
6665 [OP_INB ] = simplify_noop,
6666 [OP_INW ] = simplify_noop,
6667 [OP_INL ] = simplify_noop,
6668 [OP_OUTB ] = simplify_noop,
6669 [OP_OUTW ] = simplify_noop,
6670 [OP_OUTL ] = simplify_noop,
6671 [OP_BSF ] = simplify_bsf,
6672 [OP_BSR ] = simplify_bsr,
6673 [OP_RDMSR ] = simplify_noop,
6674 [OP_WRMSR ] = simplify_noop,
6675 [OP_HLT ] = simplify_noop,
6678 static void simplify(struct compile_state *state, struct triple *ins)
6681 simplify_t do_simplify;
6685 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6689 do_simplify = table_simplify[op];
6692 internal_error(state, ins, "cannot simplify op: %d %s\n",
6696 do_simplify(state, ins);
6697 } while(ins->op != op);
6700 static void simplify_all(struct compile_state *state)
6702 struct triple *ins, *first;
6703 first = RHS(state->main_function, 0);
6706 simplify(state, ins);
6708 }while(ins != first);
6713 * ============================
6716 static void register_builtin_function(struct compile_state *state,
6717 const char *name, int op, struct type *rtype, ...)
6719 struct type *ftype, *atype, *param, **next;
6720 struct triple *def, *arg, *result, *work, *last, *first;
6721 struct hash_entry *ident;
6722 struct file_state file;
6728 /* Dummy file state to get debug handling right */
6729 memset(&file, 0, sizeof(file));
6730 file.basename = "<built-in>";
6732 file.report_line = 1;
6733 file.report_name = file.basename;
6734 file.prev = state->file;
6735 state->file = &file;
6736 state->function = name;
6738 /* Find the Parameter count */
6739 valid_op(state, op);
6740 parameters = table_ops[op].rhs;
6741 if (parameters < 0 ) {
6742 internal_error(state, 0, "Invalid builtin parameter count");
6745 /* Find the function type */
6746 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6747 next = &ftype->right;
6748 va_start(args, rtype);
6749 for(i = 0; i < parameters; i++) {
6750 atype = va_arg(args, struct type *);
6754 *next = new_type(TYPE_PRODUCT, *next, atype);
6755 next = &((*next)->right);
6763 /* Generate the needed triples */
6764 def = triple(state, OP_LIST, ftype, 0, 0);
6765 first = label(state);
6766 RHS(def, 0) = first;
6768 /* Now string them together */
6769 param = ftype->right;
6770 for(i = 0; i < parameters; i++) {
6771 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6772 atype = param->left;
6776 arg = flatten(state, first, variable(state, atype));
6777 param = param->right;
6780 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6781 result = flatten(state, first, variable(state, rtype));
6783 MISC(def, 0) = result;
6784 work = new_triple(state, op, rtype, -1, parameters);
6785 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6786 RHS(work, i) = read_expr(state, arg);
6788 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6790 /* Populate the LHS with the target registers */
6791 work = flatten(state, first, work);
6792 work->type = &void_type;
6793 param = rtype->left;
6794 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6795 internal_error(state, 0, "Invalid result type");
6797 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6798 for(i = 0; i < rtype->elements; i++) {
6799 struct triple *piece;
6801 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6802 atype = param->left;
6804 if (!TYPE_ARITHMETIC(atype->type) &&
6805 !TYPE_PTR(atype->type)) {
6806 internal_error(state, 0, "Invalid lhs type");
6808 piece = triple(state, OP_PIECE, atype, work, 0);
6810 LHS(work, i) = piece;
6811 RHS(val, i) = piece;
6816 work = write_expr(state, result, work);
6818 work = flatten(state, first, work);
6819 last = flatten(state, first, label(state));
6820 name_len = strlen(name);
6821 ident = lookup(state, name, name_len);
6822 symbol(state, ident, &ident->sym_ident, def, ftype);
6824 state->file = file.prev;
6825 state->function = 0;
6827 fprintf(stdout, "\n");
6828 loc(stdout, state, 0);
6829 fprintf(stdout, "\n__________ builtin_function _________\n");
6830 print_triple(state, def);
6831 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6835 static struct type *partial_struct(struct compile_state *state,
6836 const char *field_name, struct type *type, struct type *rest)
6838 struct hash_entry *field_ident;
6839 struct type *result;
6842 field_name_len = strlen(field_name);
6843 field_ident = lookup(state, field_name, field_name_len);
6845 result = clone_type(0, type);
6846 result->field_ident = field_ident;
6849 result = new_type(TYPE_PRODUCT, result, rest);
6854 static struct type *register_builtin_type(struct compile_state *state,
6855 const char *name, struct type *type)
6857 struct hash_entry *ident;
6860 name_len = strlen(name);
6861 ident = lookup(state, name, name_len);
6863 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6864 ulong_t elements = 0;
6866 type = new_type(TYPE_STRUCT, type, 0);
6868 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6870 field = field->right;
6873 symbol(state, ident, &ident->sym_struct, 0, type);
6874 type->type_ident = ident;
6875 type->elements = elements;
6877 symbol(state, ident, &ident->sym_ident, 0, type);
6878 ident->tok = TOK_TYPE_NAME;
6883 static void register_builtins(struct compile_state *state)
6885 struct type *div_type, *ldiv_type;
6886 struct type *udiv_type, *uldiv_type;
6887 struct type *msr_type;
6889 div_type = register_builtin_type(state, "__builtin_div_t",
6890 partial_struct(state, "quot", &int_type,
6891 partial_struct(state, "rem", &int_type, 0)));
6892 ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
6893 partial_struct(state, "quot", &long_type,
6894 partial_struct(state, "rem", &long_type, 0)));
6895 udiv_type = register_builtin_type(state, "__builtin_udiv_t",
6896 partial_struct(state, "quot", &uint_type,
6897 partial_struct(state, "rem", &uint_type, 0)));
6898 uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
6899 partial_struct(state, "quot", &ulong_type,
6900 partial_struct(state, "rem", &ulong_type, 0)));
6902 register_builtin_function(state, "__builtin_div", OP_SDIVT, div_type,
6903 &int_type, &int_type);
6904 register_builtin_function(state, "__builtin_ldiv", OP_SDIVT, ldiv_type,
6905 &long_type, &long_type);
6906 register_builtin_function(state, "__builtin_udiv", OP_UDIVT, udiv_type,
6907 &uint_type, &uint_type);
6908 register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
6909 &ulong_type, &ulong_type);
6911 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6913 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6915 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6918 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6919 &uchar_type, &ushort_type);
6920 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6921 &ushort_type, &ushort_type);
6922 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6923 &uint_type, &ushort_type);
6925 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6927 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6930 msr_type = register_builtin_type(state, "__builtin_msr_t",
6931 partial_struct(state, "lo", &ulong_type,
6932 partial_struct(state, "hi", &ulong_type, 0)));
6934 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6936 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6937 &ulong_type, &ulong_type, &ulong_type);
6939 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6943 static struct type *declarator(
6944 struct compile_state *state, struct type *type,
6945 struct hash_entry **ident, int need_ident);
6946 static void decl(struct compile_state *state, struct triple *first);
6947 static struct type *specifier_qualifier_list(struct compile_state *state);
6948 static int isdecl_specifier(int tok);
6949 static struct type *decl_specifiers(struct compile_state *state);
6950 static int istype(int tok);
6951 static struct triple *expr(struct compile_state *state);
6952 static struct triple *assignment_expr(struct compile_state *state);
6953 static struct type *type_name(struct compile_state *state);
6954 static void statement(struct compile_state *state, struct triple *fist);
6956 static struct triple *call_expr(
6957 struct compile_state *state, struct triple *func)
6960 struct type *param, *type;
6961 ulong_t pvals, index;
6963 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6964 error(state, 0, "Called object is not a function");
6966 if (func->op != OP_LIST) {
6967 internal_error(state, 0, "improper function");
6969 eat(state, TOK_LPAREN);
6970 /* Find the return type without any specifiers */
6971 type = clone_type(0, func->type->left);
6972 def = new_triple(state, OP_CALL, func->type, -1, -1);
6975 pvals = TRIPLE_RHS(def->sizes);
6976 MISC(def, 0) = func;
6978 param = func->type->right;
6979 for(index = 0; index < pvals; index++) {
6981 struct type *arg_type;
6982 val = read_expr(state, assignment_expr(state));
6984 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6985 arg_type = param->left;
6987 write_compatible(state, arg_type, val->type);
6988 RHS(def, index) = val;
6989 if (index != (pvals - 1)) {
6990 eat(state, TOK_COMMA);
6991 param = param->right;
6994 eat(state, TOK_RPAREN);
6999 static struct triple *character_constant(struct compile_state *state)
7003 const signed char *str, *end;
7006 eat(state, TOK_LIT_CHAR);
7007 tk = &state->token[0];
7008 str = tk->val.str + 1;
7009 str_len = tk->str_len - 2;
7011 error(state, 0, "empty character constant");
7013 end = str + str_len;
7014 c = char_value(state, &str, end);
7016 error(state, 0, "multibyte character constant not supported");
7018 def = int_const(state, &char_type, (ulong_t)((long_t)c));
7022 static struct triple *string_constant(struct compile_state *state)
7027 const signed char *str, *end;
7028 signed char *buf, *ptr;
7032 type = new_type(TYPE_ARRAY, &char_type, 0);
7034 /* The while loop handles string concatenation */
7036 eat(state, TOK_LIT_STRING);
7037 tk = &state->token[0];
7038 str = tk->val.str + 1;
7039 str_len = tk->str_len - 2;
7041 error(state, 0, "negative string constant length");
7043 end = str + str_len;
7045 buf = xmalloc(type->elements + str_len + 1, "string_constant");
7046 memcpy(buf, ptr, type->elements);
7047 ptr = buf + type->elements;
7049 *ptr++ = char_value(state, &str, end);
7051 type->elements = ptr - buf;
7052 } while(peek(state) == TOK_LIT_STRING);
7054 type->elements += 1;
7055 def = triple(state, OP_BLOBCONST, type, 0, 0);
7061 static struct triple *integer_constant(struct compile_state *state)
7070 eat(state, TOK_LIT_INT);
7071 tk = &state->token[0];
7073 decimal = (tk->val.str[0] != '0');
7074 val = strtoul(tk->val.str, &end, 0);
7075 if ((val == ULONG_MAX) && (errno == ERANGE)) {
7076 error(state, 0, "Integer constant to large");
7079 if ((*end == 'u') || (*end == 'U')) {
7083 if ((*end == 'l') || (*end == 'L')) {
7087 if ((*end == 'u') || (*end == 'U')) {
7092 error(state, 0, "Junk at end of integer constant");
7099 if (!decimal && (val > LONG_MAX)) {
7105 if (val > UINT_MAX) {
7111 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
7114 else if (!decimal && (val > LONG_MAX)) {
7117 else if (val > INT_MAX) {
7121 def = int_const(state, type, val);
7125 static struct triple *primary_expr(struct compile_state *state)
7133 struct hash_entry *ident;
7134 /* Here ident is either:
7137 * an enumeration constant.
7139 eat(state, TOK_IDENT);
7140 ident = state->token[0].ident;
7141 if (!ident->sym_ident) {
7142 error(state, 0, "%s undeclared", ident->name);
7144 def = ident->sym_ident->def;
7147 case TOK_ENUM_CONST:
7148 /* Here ident is an enumeration constant */
7149 eat(state, TOK_ENUM_CONST);
7154 eat(state, TOK_LPAREN);
7156 eat(state, TOK_RPAREN);
7159 def = integer_constant(state);
7162 eat(state, TOK_LIT_FLOAT);
7163 error(state, 0, "Floating point constants not supported");
7168 def = character_constant(state);
7170 case TOK_LIT_STRING:
7171 def = string_constant(state);
7175 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7180 static struct triple *postfix_expr(struct compile_state *state)
7184 def = primary_expr(state);
7186 struct triple *left;
7190 switch((tok = peek(state))) {
7192 eat(state, TOK_LBRACKET);
7193 def = mk_subscript_expr(state, left, expr(state));
7194 eat(state, TOK_RBRACKET);
7197 def = call_expr(state, def);
7201 struct hash_entry *field;
7202 eat(state, TOK_DOT);
7203 eat(state, TOK_IDENT);
7204 field = state->token[0].ident;
7205 def = deref_field(state, def, field);
7210 struct hash_entry *field;
7211 eat(state, TOK_ARROW);
7212 eat(state, TOK_IDENT);
7213 field = state->token[0].ident;
7214 def = mk_deref_expr(state, read_expr(state, def));
7215 def = deref_field(state, def, field);
7219 eat(state, TOK_PLUSPLUS);
7220 def = mk_post_inc_expr(state, left);
7222 case TOK_MINUSMINUS:
7223 eat(state, TOK_MINUSMINUS);
7224 def = mk_post_dec_expr(state, left);
7234 static struct triple *cast_expr(struct compile_state *state);
7236 static struct triple *unary_expr(struct compile_state *state)
7238 struct triple *def, *right;
7240 switch((tok = peek(state))) {
7242 eat(state, TOK_PLUSPLUS);
7243 def = mk_pre_inc_expr(state, unary_expr(state));
7245 case TOK_MINUSMINUS:
7246 eat(state, TOK_MINUSMINUS);
7247 def = mk_pre_dec_expr(state, unary_expr(state));
7250 eat(state, TOK_AND);
7251 def = mk_addr_expr(state, cast_expr(state), 0);
7254 eat(state, TOK_STAR);
7255 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7258 eat(state, TOK_PLUS);
7259 right = read_expr(state, cast_expr(state));
7260 arithmetic(state, right);
7261 def = integral_promotion(state, right);
7264 eat(state, TOK_MINUS);
7265 right = read_expr(state, cast_expr(state));
7266 arithmetic(state, right);
7267 def = integral_promotion(state, right);
7268 def = triple(state, OP_NEG, def->type, def, 0);
7271 eat(state, TOK_TILDE);
7272 right = read_expr(state, cast_expr(state));
7273 integral(state, right);
7274 def = integral_promotion(state, right);
7275 def = triple(state, OP_INVERT, def->type, def, 0);
7278 eat(state, TOK_BANG);
7279 right = read_expr(state, cast_expr(state));
7281 def = lfalse_expr(state, right);
7287 eat(state, TOK_SIZEOF);
7289 tok2 = peek2(state);
7290 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7291 eat(state, TOK_LPAREN);
7292 type = type_name(state);
7293 eat(state, TOK_RPAREN);
7296 struct triple *expr;
7297 expr = unary_expr(state);
7299 release_expr(state, expr);
7301 def = int_const(state, &ulong_type, size_of(state, type));
7308 eat(state, TOK_ALIGNOF);
7310 tok2 = peek2(state);
7311 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7312 eat(state, TOK_LPAREN);
7313 type = type_name(state);
7314 eat(state, TOK_RPAREN);
7317 struct triple *expr;
7318 expr = unary_expr(state);
7320 release_expr(state, expr);
7322 def = int_const(state, &ulong_type, align_of(state, type));
7326 def = postfix_expr(state);
7332 static struct triple *cast_expr(struct compile_state *state)
7337 tok2 = peek2(state);
7338 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7340 eat(state, TOK_LPAREN);
7341 type = type_name(state);
7342 eat(state, TOK_RPAREN);
7343 def = read_expr(state, cast_expr(state));
7344 def = triple(state, OP_COPY, type, def, 0);
7347 def = unary_expr(state);
7352 static struct triple *mult_expr(struct compile_state *state)
7356 def = cast_expr(state);
7358 struct triple *left, *right;
7359 struct type *result_type;
7362 switch(tok = (peek(state))) {
7366 left = read_expr(state, def);
7367 arithmetic(state, left);
7371 right = read_expr(state, cast_expr(state));
7372 arithmetic(state, right);
7374 result_type = arithmetic_result(state, left, right);
7375 sign = is_signed(result_type);
7378 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7379 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
7380 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
7382 def = triple(state, op, result_type, left, right);
7392 static struct triple *add_expr(struct compile_state *state)
7396 def = mult_expr(state);
7399 switch( peek(state)) {
7401 eat(state, TOK_PLUS);
7402 def = mk_add_expr(state, def, mult_expr(state));
7405 eat(state, TOK_MINUS);
7406 def = mk_sub_expr(state, def, mult_expr(state));
7416 static struct triple *shift_expr(struct compile_state *state)
7420 def = add_expr(state);
7422 struct triple *left, *right;
7425 switch((tok = peek(state))) {
7428 left = read_expr(state, def);
7429 integral(state, left);
7430 left = integral_promotion(state, left);
7434 right = read_expr(state, add_expr(state));
7435 integral(state, right);
7436 right = integral_promotion(state, right);
7438 op = (tok == TOK_SL)? OP_SL :
7439 is_signed(left->type)? OP_SSR: OP_USR;
7441 def = triple(state, op, left->type, left, right);
7451 static struct triple *relational_expr(struct compile_state *state)
7453 #warning "Extend relational exprs to work on more than arithmetic types"
7456 def = shift_expr(state);
7458 struct triple *left, *right;
7459 struct type *arg_type;
7462 switch((tok = peek(state))) {
7467 left = read_expr(state, def);
7468 arithmetic(state, left);
7472 right = read_expr(state, shift_expr(state));
7473 arithmetic(state, right);
7475 arg_type = arithmetic_result(state, left, right);
7476 sign = is_signed(arg_type);
7479 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7480 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7481 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7482 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7484 def = triple(state, op, &int_type, left, right);
7494 static struct triple *equality_expr(struct compile_state *state)
7496 #warning "Extend equality exprs to work on more than arithmetic types"
7499 def = relational_expr(state);
7501 struct triple *left, *right;
7504 switch((tok = peek(state))) {
7507 left = read_expr(state, def);
7508 arithmetic(state, left);
7510 right = read_expr(state, relational_expr(state));
7511 arithmetic(state, right);
7512 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7513 def = triple(state, op, &int_type, left, right);
7523 static struct triple *and_expr(struct compile_state *state)
7526 def = equality_expr(state);
7527 while(peek(state) == TOK_AND) {
7528 struct triple *left, *right;
7529 struct type *result_type;
7530 left = read_expr(state, def);
7531 integral(state, left);
7532 eat(state, TOK_AND);
7533 right = read_expr(state, equality_expr(state));
7534 integral(state, right);
7535 result_type = arithmetic_result(state, left, right);
7536 def = triple(state, OP_AND, result_type, left, right);
7541 static struct triple *xor_expr(struct compile_state *state)
7544 def = and_expr(state);
7545 while(peek(state) == TOK_XOR) {
7546 struct triple *left, *right;
7547 struct type *result_type;
7548 left = read_expr(state, def);
7549 integral(state, left);
7550 eat(state, TOK_XOR);
7551 right = read_expr(state, and_expr(state));
7552 integral(state, right);
7553 result_type = arithmetic_result(state, left, right);
7554 def = triple(state, OP_XOR, result_type, left, right);
7559 static struct triple *or_expr(struct compile_state *state)
7562 def = xor_expr(state);
7563 while(peek(state) == TOK_OR) {
7564 struct triple *left, *right;
7565 struct type *result_type;
7566 left = read_expr(state, def);
7567 integral(state, left);
7569 right = read_expr(state, xor_expr(state));
7570 integral(state, right);
7571 result_type = arithmetic_result(state, left, right);
7572 def = triple(state, OP_OR, result_type, left, right);
7577 static struct triple *land_expr(struct compile_state *state)
7580 def = or_expr(state);
7581 while(peek(state) == TOK_LOGAND) {
7582 struct triple *left, *right;
7583 left = read_expr(state, def);
7585 eat(state, TOK_LOGAND);
7586 right = read_expr(state, or_expr(state));
7589 def = triple(state, OP_LAND, &int_type,
7590 ltrue_expr(state, left),
7591 ltrue_expr(state, right));
7596 static struct triple *lor_expr(struct compile_state *state)
7599 def = land_expr(state);
7600 while(peek(state) == TOK_LOGOR) {
7601 struct triple *left, *right;
7602 left = read_expr(state, def);
7604 eat(state, TOK_LOGOR);
7605 right = read_expr(state, land_expr(state));
7608 def = triple(state, OP_LOR, &int_type,
7609 ltrue_expr(state, left),
7610 ltrue_expr(state, right));
7615 static struct triple *conditional_expr(struct compile_state *state)
7618 def = lor_expr(state);
7619 if (peek(state) == TOK_QUEST) {
7620 struct triple *test, *left, *right;
7622 test = ltrue_expr(state, read_expr(state, def));
7623 eat(state, TOK_QUEST);
7624 left = read_expr(state, expr(state));
7625 eat(state, TOK_COLON);
7626 right = read_expr(state, conditional_expr(state));
7628 def = cond_expr(state, test, left, right);
7633 static struct triple *eval_const_expr(
7634 struct compile_state *state, struct triple *expr)
7637 if (is_const(expr)) {
7641 /* If we don't start out as a constant simplify into one */
7642 struct triple *head, *ptr;
7643 head = label(state); /* dummy initial triple */
7644 flatten(state, head, expr);
7645 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7646 simplify(state, ptr);
7648 /* Remove the constant value the tail of the list */
7650 def->prev->next = def->next;
7651 def->next->prev = def->prev;
7652 def->next = def->prev = def;
7653 if (!is_const(def)) {
7654 error(state, 0, "Not a constant expression");
7656 /* Free the intermediate expressions */
7657 while(head->next != head) {
7658 release_triple(state, head->next);
7660 free_triple(state, head);
7665 static struct triple *constant_expr(struct compile_state *state)
7667 return eval_const_expr(state, conditional_expr(state));
7670 static struct triple *assignment_expr(struct compile_state *state)
7672 struct triple *def, *left, *right;
7674 /* The C grammer in K&R shows assignment expressions
7675 * only taking unary expressions as input on their
7676 * left hand side. But specifies the precedence of
7677 * assignemnt as the lowest operator except for comma.
7679 * Allowing conditional expressions on the left hand side
7680 * of an assignement results in a grammar that accepts
7681 * a larger set of statements than standard C. As long
7682 * as the subset of the grammar that is standard C behaves
7683 * correctly this should cause no problems.
7685 * For the extra token strings accepted by the grammar
7686 * none of them should produce a valid lvalue, so they
7687 * should not produce functioning programs.
7689 * GCC has this bug as well, so surprises should be minimal.
7691 def = conditional_expr(state);
7693 switch((tok = peek(state))) {
7695 lvalue(state, left);
7697 def = write_expr(state, left,
7698 read_expr(state, assignment_expr(state)));
7703 lvalue(state, left);
7704 arithmetic(state, left);
7706 right = read_expr(state, assignment_expr(state));
7707 arithmetic(state, right);
7709 sign = is_signed(left->type);
7712 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7713 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7714 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7716 def = write_expr(state, left,
7717 triple(state, op, left->type,
7718 read_expr(state, left), right));
7721 lvalue(state, left);
7722 eat(state, TOK_PLUSEQ);
7723 def = write_expr(state, left,
7724 mk_add_expr(state, left, assignment_expr(state)));
7727 lvalue(state, left);
7728 eat(state, TOK_MINUSEQ);
7729 def = write_expr(state, left,
7730 mk_sub_expr(state, left, assignment_expr(state)));
7737 lvalue(state, left);
7738 integral(state, left);
7740 right = read_expr(state, assignment_expr(state));
7741 integral(state, right);
7742 right = integral_promotion(state, right);
7743 sign = is_signed(left->type);
7746 case TOK_SLEQ: op = OP_SL; break;
7747 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7748 case TOK_ANDEQ: op = OP_AND; break;
7749 case TOK_XOREQ: op = OP_XOR; break;
7750 case TOK_OREQ: op = OP_OR; break;
7752 def = write_expr(state, left,
7753 triple(state, op, left->type,
7754 read_expr(state, left), right));
7760 static struct triple *expr(struct compile_state *state)
7763 def = assignment_expr(state);
7764 while(peek(state) == TOK_COMMA) {
7765 struct triple *left, *right;
7767 eat(state, TOK_COMMA);
7768 right = assignment_expr(state);
7769 def = triple(state, OP_COMMA, right->type, left, right);
7774 static void expr_statement(struct compile_state *state, struct triple *first)
7776 if (peek(state) != TOK_SEMI) {
7777 flatten(state, first, expr(state));
7779 eat(state, TOK_SEMI);
7782 static void if_statement(struct compile_state *state, struct triple *first)
7784 struct triple *test, *jmp1, *jmp2, *middle, *end;
7786 jmp1 = jmp2 = middle = 0;
7788 eat(state, TOK_LPAREN);
7791 /* Cleanup and invert the test */
7792 test = lfalse_expr(state, read_expr(state, test));
7793 eat(state, TOK_RPAREN);
7794 /* Generate the needed pieces */
7795 middle = label(state);
7796 jmp1 = branch(state, middle, test);
7797 /* Thread the pieces together */
7798 flatten(state, first, test);
7799 flatten(state, first, jmp1);
7800 flatten(state, first, label(state));
7801 statement(state, first);
7802 if (peek(state) == TOK_ELSE) {
7803 eat(state, TOK_ELSE);
7804 /* Generate the rest of the pieces */
7806 jmp2 = branch(state, end, 0);
7807 /* Thread them together */
7808 flatten(state, first, jmp2);
7809 flatten(state, first, middle);
7810 statement(state, first);
7811 flatten(state, first, end);
7814 flatten(state, first, middle);
7818 static void for_statement(struct compile_state *state, struct triple *first)
7820 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7821 struct triple *label1, *label2, *label3;
7822 struct hash_entry *ident;
7824 eat(state, TOK_FOR);
7825 eat(state, TOK_LPAREN);
7826 head = test = tail = jmp1 = jmp2 = 0;
7827 if (peek(state) != TOK_SEMI) {
7830 eat(state, TOK_SEMI);
7831 if (peek(state) != TOK_SEMI) {
7834 test = ltrue_expr(state, read_expr(state, test));
7836 eat(state, TOK_SEMI);
7837 if (peek(state) != TOK_RPAREN) {
7840 eat(state, TOK_RPAREN);
7841 /* Generate the needed pieces */
7842 label1 = label(state);
7843 label2 = label(state);
7844 label3 = label(state);
7846 jmp1 = branch(state, label3, 0);
7847 jmp2 = branch(state, label1, test);
7850 jmp2 = branch(state, label1, 0);
7853 /* Remember where break and continue go */
7855 ident = state->i_break;
7856 symbol(state, ident, &ident->sym_ident, end, end->type);
7857 ident = state->i_continue;
7858 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7859 /* Now include the body */
7860 flatten(state, first, head);
7861 flatten(state, first, jmp1);
7862 flatten(state, first, label1);
7863 statement(state, first);
7864 flatten(state, first, label2);
7865 flatten(state, first, tail);
7866 flatten(state, first, label3);
7867 flatten(state, first, test);
7868 flatten(state, first, jmp2);
7869 flatten(state, first, end);
7870 /* Cleanup the break/continue scope */
7874 static void while_statement(struct compile_state *state, struct triple *first)
7876 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7877 struct hash_entry *ident;
7878 eat(state, TOK_WHILE);
7879 eat(state, TOK_LPAREN);
7882 test = ltrue_expr(state, read_expr(state, test));
7883 eat(state, TOK_RPAREN);
7884 /* Generate the needed pieces */
7885 label1 = label(state);
7886 label2 = label(state);
7887 jmp1 = branch(state, label2, 0);
7888 jmp2 = branch(state, label1, test);
7890 /* Remember where break and continue go */
7892 ident = state->i_break;
7893 symbol(state, ident, &ident->sym_ident, end, end->type);
7894 ident = state->i_continue;
7895 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7896 /* Thread them together */
7897 flatten(state, first, jmp1);
7898 flatten(state, first, label1);
7899 statement(state, first);
7900 flatten(state, first, label2);
7901 flatten(state, first, test);
7902 flatten(state, first, jmp2);
7903 flatten(state, first, end);
7904 /* Cleanup the break/continue scope */
7908 static void do_statement(struct compile_state *state, struct triple *first)
7910 struct triple *label1, *label2, *test, *end;
7911 struct hash_entry *ident;
7913 /* Generate the needed pieces */
7914 label1 = label(state);
7915 label2 = label(state);
7917 /* Remember where break and continue go */
7919 ident = state->i_break;
7920 symbol(state, ident, &ident->sym_ident, end, end->type);
7921 ident = state->i_continue;
7922 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7923 /* Now include the body */
7924 flatten(state, first, label1);
7925 statement(state, first);
7926 /* Cleanup the break/continue scope */
7928 /* Eat the rest of the loop */
7929 eat(state, TOK_WHILE);
7930 eat(state, TOK_LPAREN);
7931 test = read_expr(state, expr(state));
7933 eat(state, TOK_RPAREN);
7934 eat(state, TOK_SEMI);
7935 /* Thread the pieces together */
7936 test = ltrue_expr(state, test);
7937 flatten(state, first, label2);
7938 flatten(state, first, test);
7939 flatten(state, first, branch(state, label1, test));
7940 flatten(state, first, end);
7944 static void return_statement(struct compile_state *state, struct triple *first)
7946 struct triple *jmp, *mv, *dest, *var, *val;
7948 eat(state, TOK_RETURN);
7950 #warning "FIXME implement a more general excess branch elimination"
7952 /* If we have a return value do some more work */
7953 if (peek(state) != TOK_SEMI) {
7954 val = read_expr(state, expr(state));
7956 eat(state, TOK_SEMI);
7958 /* See if this last statement in a function */
7959 last = ((peek(state) == TOK_RBRACE) &&
7960 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7962 /* Find the return variable */
7963 var = MISC(state->main_function, 0);
7964 /* Find the return destination */
7965 dest = RHS(state->main_function, 0)->prev;
7967 /* If needed generate a jump instruction */
7969 jmp = branch(state, dest, 0);
7971 /* If needed generate an assignment instruction */
7973 mv = write_expr(state, var, val);
7975 /* Now put the code together */
7977 flatten(state, first, mv);
7978 flatten(state, first, jmp);
7981 flatten(state, first, jmp);
7985 static void break_statement(struct compile_state *state, struct triple *first)
7987 struct triple *dest;
7988 eat(state, TOK_BREAK);
7989 eat(state, TOK_SEMI);
7990 if (!state->i_break->sym_ident) {
7991 error(state, 0, "break statement not within loop or switch");
7993 dest = state->i_break->sym_ident->def;
7994 flatten(state, first, branch(state, dest, 0));
7997 static void continue_statement(struct compile_state *state, struct triple *first)
7999 struct triple *dest;
8000 eat(state, TOK_CONTINUE);
8001 eat(state, TOK_SEMI);
8002 if (!state->i_continue->sym_ident) {
8003 error(state, 0, "continue statement outside of a loop");
8005 dest = state->i_continue->sym_ident->def;
8006 flatten(state, first, branch(state, dest, 0));
8009 static void goto_statement(struct compile_state *state, struct triple *first)
8011 struct hash_entry *ident;
8012 eat(state, TOK_GOTO);
8013 eat(state, TOK_IDENT);
8014 ident = state->token[0].ident;
8015 if (!ident->sym_label) {
8016 /* If this is a forward branch allocate the label now,
8017 * it will be flattend in the appropriate location later.
8021 label_symbol(state, ident, ins);
8023 eat(state, TOK_SEMI);
8025 flatten(state, first, branch(state, ident->sym_label->def, 0));
8028 static void labeled_statement(struct compile_state *state, struct triple *first)
8031 struct hash_entry *ident;
8032 eat(state, TOK_IDENT);
8034 ident = state->token[0].ident;
8035 if (ident->sym_label && ident->sym_label->def) {
8036 ins = ident->sym_label->def;
8037 put_occurance(ins->occurance);
8038 ins->occurance = new_occurance(state);
8042 label_symbol(state, ident, ins);
8044 if (ins->id & TRIPLE_FLAG_FLATTENED) {
8045 error(state, 0, "label %s already defined", ident->name);
8047 flatten(state, first, ins);
8049 eat(state, TOK_COLON);
8050 statement(state, first);
8053 static void switch_statement(struct compile_state *state, struct triple *first)
8056 eat(state, TOK_SWITCH);
8057 eat(state, TOK_LPAREN);
8059 eat(state, TOK_RPAREN);
8060 statement(state, first);
8061 error(state, 0, "switch statements are not implemented");
8065 static void case_statement(struct compile_state *state, struct triple *first)
8068 eat(state, TOK_CASE);
8069 constant_expr(state);
8070 eat(state, TOK_COLON);
8071 statement(state, first);
8072 error(state, 0, "case statements are not implemented");
8076 static void default_statement(struct compile_state *state, struct triple *first)
8079 eat(state, TOK_DEFAULT);
8080 eat(state, TOK_COLON);
8081 statement(state, first);
8082 error(state, 0, "default statements are not implemented");
8086 static void asm_statement(struct compile_state *state, struct triple *first)
8088 struct asm_info *info;
8090 struct triple *constraint;
8091 struct triple *expr;
8092 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
8093 struct triple *def, *asm_str;
8094 int out, in, clobbers, more, colons, i;
8096 eat(state, TOK_ASM);
8097 /* For now ignore the qualifiers */
8098 switch(peek(state)) {
8100 eat(state, TOK_CONST);
8103 eat(state, TOK_VOLATILE);
8106 eat(state, TOK_LPAREN);
8107 asm_str = string_constant(state);
8110 out = in = clobbers = 0;
8112 if ((colons == 0) && (peek(state) == TOK_COLON)) {
8113 eat(state, TOK_COLON);
8115 more = (peek(state) == TOK_LIT_STRING);
8118 struct triple *constraint;
8121 if (out > MAX_LHS) {
8122 error(state, 0, "Maximum output count exceeded.");
8124 constraint = string_constant(state);
8125 str = constraint->u.blob;
8126 if (str[0] != '=') {
8127 error(state, 0, "Output constraint does not start with =");
8129 constraint->u.blob = str + 1;
8130 eat(state, TOK_LPAREN);
8131 var = conditional_expr(state);
8132 eat(state, TOK_RPAREN);
8135 out_param[out].constraint = constraint;
8136 out_param[out].expr = var;
8137 if (peek(state) == TOK_COMMA) {
8138 eat(state, TOK_COMMA);
8145 if ((colons == 1) && (peek(state) == TOK_COLON)) {
8146 eat(state, TOK_COLON);
8148 more = (peek(state) == TOK_LIT_STRING);
8151 struct triple *constraint;
8155 error(state, 0, "Maximum input count exceeded.");
8157 constraint = string_constant(state);
8158 str = constraint->u.blob;
8159 if (digitp(str[0] && str[1] == '\0')) {
8161 val = digval(str[0]);
8162 if ((val < 0) || (val >= out)) {
8163 error(state, 0, "Invalid input constraint %d", val);
8166 eat(state, TOK_LPAREN);
8167 val = conditional_expr(state);
8168 eat(state, TOK_RPAREN);
8170 in_param[in].constraint = constraint;
8171 in_param[in].expr = val;
8172 if (peek(state) == TOK_COMMA) {
8173 eat(state, TOK_COMMA);
8181 if ((colons == 2) && (peek(state) == TOK_COLON)) {
8182 eat(state, TOK_COLON);
8184 more = (peek(state) == TOK_LIT_STRING);
8186 struct triple *clobber;
8188 if ((clobbers + out) > MAX_LHS) {
8189 error(state, 0, "Maximum clobber limit exceeded.");
8191 clobber = string_constant(state);
8192 eat(state, TOK_RPAREN);
8194 clob_param[clobbers].constraint = clobber;
8195 if (peek(state) == TOK_COMMA) {
8196 eat(state, TOK_COMMA);
8202 eat(state, TOK_RPAREN);
8203 eat(state, TOK_SEMI);
8206 info = xcmalloc(sizeof(*info), "asm_info");
8207 info->str = asm_str->u.blob;
8208 free_triple(state, asm_str);
8210 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8211 def->u.ainfo = info;
8213 /* Find the register constraints */
8214 for(i = 0; i < out; i++) {
8215 struct triple *constraint;
8216 constraint = out_param[i].constraint;
8217 info->tmpl.lhs[i] = arch_reg_constraint(state,
8218 out_param[i].expr->type, constraint->u.blob);
8219 free_triple(state, constraint);
8221 for(; i - out < clobbers; i++) {
8222 struct triple *constraint;
8223 constraint = clob_param[i - out].constraint;
8224 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8225 free_triple(state, constraint);
8227 for(i = 0; i < in; i++) {
8228 struct triple *constraint;
8230 constraint = in_param[i].constraint;
8231 str = constraint->u.blob;
8232 if (digitp(str[0]) && str[1] == '\0') {
8233 struct reg_info cinfo;
8235 val = digval(str[0]);
8236 cinfo.reg = info->tmpl.lhs[val].reg;
8237 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8238 cinfo.regcm &= info->tmpl.lhs[val].regcm;
8239 if (cinfo.reg == REG_UNSET) {
8240 cinfo.reg = REG_VIRT0 + val;
8242 if (cinfo.regcm == 0) {
8243 error(state, 0, "No registers for %d", val);
8245 info->tmpl.lhs[val] = cinfo;
8246 info->tmpl.rhs[i] = cinfo;
8249 info->tmpl.rhs[i] = arch_reg_constraint(state,
8250 in_param[i].expr->type, str);
8252 free_triple(state, constraint);
8255 /* Now build the helper expressions */
8256 for(i = 0; i < in; i++) {
8257 RHS(def, i) = read_expr(state,in_param[i].expr);
8259 flatten(state, first, def);
8260 for(i = 0; i < out; i++) {
8261 struct triple *piece;
8262 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8264 LHS(def, i) = piece;
8265 flatten(state, first,
8266 write_expr(state, out_param[i].expr, piece));
8268 for(; i - out < clobbers; i++) {
8269 struct triple *piece;
8270 piece = triple(state, OP_PIECE, &void_type, def, 0);
8272 LHS(def, i) = piece;
8273 flatten(state, first, piece);
8278 static int isdecl(int tok)
8301 case TOK_TYPE_NAME: /* typedef name */
8308 static void compound_statement(struct compile_state *state, struct triple *first)
8310 eat(state, TOK_LBRACE);
8313 /* statement-list opt */
8314 while (peek(state) != TOK_RBRACE) {
8315 statement(state, first);
8318 eat(state, TOK_RBRACE);
8321 static void statement(struct compile_state *state, struct triple *first)
8325 if (tok == TOK_LBRACE) {
8326 compound_statement(state, first);
8328 else if (tok == TOK_IF) {
8329 if_statement(state, first);
8331 else if (tok == TOK_FOR) {
8332 for_statement(state, first);
8334 else if (tok == TOK_WHILE) {
8335 while_statement(state, first);
8337 else if (tok == TOK_DO) {
8338 do_statement(state, first);
8340 else if (tok == TOK_RETURN) {
8341 return_statement(state, first);
8343 else if (tok == TOK_BREAK) {
8344 break_statement(state, first);
8346 else if (tok == TOK_CONTINUE) {
8347 continue_statement(state, first);
8349 else if (tok == TOK_GOTO) {
8350 goto_statement(state, first);
8352 else if (tok == TOK_SWITCH) {
8353 switch_statement(state, first);
8355 else if (tok == TOK_ASM) {
8356 asm_statement(state, first);
8358 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8359 labeled_statement(state, first);
8361 else if (tok == TOK_CASE) {
8362 case_statement(state, first);
8364 else if (tok == TOK_DEFAULT) {
8365 default_statement(state, first);
8367 else if (isdecl(tok)) {
8368 /* This handles C99 intermixing of statements and decls */
8372 expr_statement(state, first);
8376 static struct type *param_decl(struct compile_state *state)
8379 struct hash_entry *ident;
8380 /* Cheat so the declarator will know we are not global */
8383 type = decl_specifiers(state);
8384 type = declarator(state, type, &ident, 0);
8385 type->field_ident = ident;
8390 static struct type *param_type_list(struct compile_state *state, struct type *type)
8392 struct type *ftype, **next;
8393 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8394 next = &ftype->right;
8395 while(peek(state) == TOK_COMMA) {
8396 eat(state, TOK_COMMA);
8397 if (peek(state) == TOK_DOTS) {
8398 eat(state, TOK_DOTS);
8399 error(state, 0, "variadic functions not supported");
8402 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8403 next = &((*next)->right);
8410 static struct type *type_name(struct compile_state *state)
8413 type = specifier_qualifier_list(state);
8414 /* abstract-declarator (may consume no tokens) */
8415 type = declarator(state, type, 0, 0);
8419 static struct type *direct_declarator(
8420 struct compile_state *state, struct type *type,
8421 struct hash_entry **ident, int need_ident)
8426 arrays_complete(state, type);
8427 switch(peek(state)) {
8429 eat(state, TOK_IDENT);
8431 error(state, 0, "Unexpected identifier found");
8433 /* The name of what we are declaring */
8434 *ident = state->token[0].ident;
8437 eat(state, TOK_LPAREN);
8438 outer = declarator(state, type, ident, need_ident);
8439 eat(state, TOK_RPAREN);
8443 error(state, 0, "Identifier expected");
8449 arrays_complete(state, type);
8450 switch(peek(state)) {
8452 eat(state, TOK_LPAREN);
8453 type = param_type_list(state, type);
8454 eat(state, TOK_RPAREN);
8458 unsigned int qualifiers;
8459 struct triple *value;
8461 eat(state, TOK_LBRACKET);
8462 if (peek(state) != TOK_RBRACKET) {
8463 value = constant_expr(state);
8464 integral(state, value);
8466 eat(state, TOK_RBRACKET);
8468 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8469 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8471 type->elements = value->u.cval;
8472 free_triple(state, value);
8474 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8486 arrays_complete(state, type);
8488 for(inner = outer; inner->left; inner = inner->left)
8496 static struct type *declarator(
8497 struct compile_state *state, struct type *type,
8498 struct hash_entry **ident, int need_ident)
8500 while(peek(state) == TOK_STAR) {
8501 eat(state, TOK_STAR);
8502 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8504 type = direct_declarator(state, type, ident, need_ident);
8509 static struct type *typedef_name(
8510 struct compile_state *state, unsigned int specifiers)
8512 struct hash_entry *ident;
8514 eat(state, TOK_TYPE_NAME);
8515 ident = state->token[0].ident;
8516 type = ident->sym_ident->type;
8517 specifiers |= type->type & QUAL_MASK;
8518 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8519 (type->type & (STOR_MASK | QUAL_MASK))) {
8520 type = clone_type(specifiers, type);
8525 static struct type *enum_specifier(
8526 struct compile_state *state, unsigned int specifiers)
8532 eat(state, TOK_ENUM);
8534 if (tok == TOK_IDENT) {
8535 eat(state, TOK_IDENT);
8537 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8538 eat(state, TOK_LBRACE);
8540 eat(state, TOK_IDENT);
8541 if (peek(state) == TOK_EQ) {
8543 constant_expr(state);
8545 if (peek(state) == TOK_COMMA) {
8546 eat(state, TOK_COMMA);
8548 } while(peek(state) != TOK_RBRACE);
8549 eat(state, TOK_RBRACE);
8555 static struct type *struct_declarator(
8556 struct compile_state *state, struct type *type, struct hash_entry **ident)
8560 if (tok != TOK_COLON) {
8561 type = declarator(state, type, ident, 1);
8563 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8564 struct triple *value;
8565 eat(state, TOK_COLON);
8566 value = constant_expr(state);
8567 #warning "FIXME implement bitfields to reduce register usage"
8568 error(state, 0, "bitfields not yet implemented");
8573 static struct type *struct_or_union_specifier(
8574 struct compile_state *state, unsigned int spec)
8576 struct type *struct_type;
8577 struct hash_entry *ident;
8578 unsigned int type_join;
8582 switch(peek(state)) {
8584 eat(state, TOK_STRUCT);
8585 type_join = TYPE_PRODUCT;
8588 eat(state, TOK_UNION);
8589 type_join = TYPE_OVERLAP;
8590 error(state, 0, "unions not yet supported\n");
8593 eat(state, TOK_STRUCT);
8594 type_join = TYPE_PRODUCT;
8598 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8600 ident = state->token[0].ident;
8602 if (!ident || (peek(state) == TOK_LBRACE)) {
8606 eat(state, TOK_LBRACE);
8607 next = &struct_type;
8609 struct type *base_type;
8611 base_type = specifier_qualifier_list(state);
8614 struct hash_entry *fident;
8616 type = struct_declarator(state, base_type, &fident);
8618 if (peek(state) == TOK_COMMA) {
8620 eat(state, TOK_COMMA);
8622 type = clone_type(0, type);
8623 type->field_ident = fident;
8625 *next = new_type(type_join, *next, type);
8626 next = &((*next)->right);
8631 eat(state, TOK_SEMI);
8632 } while(peek(state) != TOK_RBRACE);
8633 eat(state, TOK_RBRACE);
8634 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8635 struct_type->type_ident = ident;
8636 struct_type->elements = elements;
8637 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8639 if (ident && ident->sym_struct) {
8640 struct_type = clone_type(spec, ident->sym_struct->type);
8642 else if (ident && !ident->sym_struct) {
8643 error(state, 0, "struct %s undeclared", ident->name);
8648 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8650 unsigned int specifiers;
8651 switch(peek(state)) {
8653 eat(state, TOK_AUTO);
8654 specifiers = STOR_AUTO;
8657 eat(state, TOK_REGISTER);
8658 specifiers = STOR_REGISTER;
8661 eat(state, TOK_STATIC);
8662 specifiers = STOR_STATIC;
8665 eat(state, TOK_EXTERN);
8666 specifiers = STOR_EXTERN;
8669 eat(state, TOK_TYPEDEF);
8670 specifiers = STOR_TYPEDEF;
8673 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8674 specifiers = STOR_STATIC;
8677 specifiers = STOR_AUTO;
8683 static unsigned int function_specifier_opt(struct compile_state *state)
8685 /* Ignore the inline keyword */
8686 unsigned int specifiers;
8688 switch(peek(state)) {
8690 eat(state, TOK_INLINE);
8691 specifiers = STOR_INLINE;
8696 static unsigned int type_qualifiers(struct compile_state *state)
8698 unsigned int specifiers;
8701 specifiers = QUAL_NONE;
8703 switch(peek(state)) {
8705 eat(state, TOK_CONST);
8706 specifiers = QUAL_CONST;
8709 eat(state, TOK_VOLATILE);
8710 specifiers = QUAL_VOLATILE;
8713 eat(state, TOK_RESTRICT);
8714 specifiers = QUAL_RESTRICT;
8724 static struct type *type_specifier(
8725 struct compile_state *state, unsigned int spec)
8729 switch(peek(state)) {
8731 eat(state, TOK_VOID);
8732 type = new_type(TYPE_VOID | spec, 0, 0);
8735 eat(state, TOK_CHAR);
8736 type = new_type(TYPE_CHAR | spec, 0, 0);
8739 eat(state, TOK_SHORT);
8740 if (peek(state) == TOK_INT) {
8741 eat(state, TOK_INT);
8743 type = new_type(TYPE_SHORT | spec, 0, 0);
8746 eat(state, TOK_INT);
8747 type = new_type(TYPE_INT | spec, 0, 0);
8750 eat(state, TOK_LONG);
8751 switch(peek(state)) {
8753 eat(state, TOK_LONG);
8754 error(state, 0, "long long not supported");
8757 eat(state, TOK_DOUBLE);
8758 error(state, 0, "long double not supported");
8761 eat(state, TOK_INT);
8762 type = new_type(TYPE_LONG | spec, 0, 0);
8765 type = new_type(TYPE_LONG | spec, 0, 0);
8770 eat(state, TOK_FLOAT);
8771 error(state, 0, "type float not supported");
8774 eat(state, TOK_DOUBLE);
8775 error(state, 0, "type double not supported");
8778 eat(state, TOK_SIGNED);
8779 switch(peek(state)) {
8781 eat(state, TOK_LONG);
8782 switch(peek(state)) {
8784 eat(state, TOK_LONG);
8785 error(state, 0, "type long long not supported");
8788 eat(state, TOK_INT);
8789 type = new_type(TYPE_LONG | spec, 0, 0);
8792 type = new_type(TYPE_LONG | spec, 0, 0);
8797 eat(state, TOK_INT);
8798 type = new_type(TYPE_INT | spec, 0, 0);
8801 eat(state, TOK_SHORT);
8802 type = new_type(TYPE_SHORT | spec, 0, 0);
8805 eat(state, TOK_CHAR);
8806 type = new_type(TYPE_CHAR | spec, 0, 0);
8809 type = new_type(TYPE_INT | spec, 0, 0);
8814 eat(state, TOK_UNSIGNED);
8815 switch(peek(state)) {
8817 eat(state, TOK_LONG);
8818 switch(peek(state)) {
8820 eat(state, TOK_LONG);
8821 error(state, 0, "unsigned long long not supported");
8824 eat(state, TOK_INT);
8825 type = new_type(TYPE_ULONG | spec, 0, 0);
8828 type = new_type(TYPE_ULONG | spec, 0, 0);
8833 eat(state, TOK_INT);
8834 type = new_type(TYPE_UINT | spec, 0, 0);
8837 eat(state, TOK_SHORT);
8838 type = new_type(TYPE_USHORT | spec, 0, 0);
8841 eat(state, TOK_CHAR);
8842 type = new_type(TYPE_UCHAR | spec, 0, 0);
8845 type = new_type(TYPE_UINT | spec, 0, 0);
8849 /* struct or union specifier */
8852 type = struct_or_union_specifier(state, spec);
8854 /* enum-spefifier */
8856 type = enum_specifier(state, spec);
8860 type = typedef_name(state, spec);
8863 error(state, 0, "bad type specifier %s",
8864 tokens[peek(state)]);
8870 static int istype(int tok)
8896 static struct type *specifier_qualifier_list(struct compile_state *state)
8899 unsigned int specifiers = 0;
8901 /* type qualifiers */
8902 specifiers |= type_qualifiers(state);
8904 /* type specifier */
8905 type = type_specifier(state, specifiers);
8910 static int isdecl_specifier(int tok)
8913 /* storage class specifier */
8919 /* type qualifier */
8923 /* type specifiers */
8933 /* struct or union specifier */
8936 /* enum-spefifier */
8940 /* function specifiers */
8948 static struct type *decl_specifiers(struct compile_state *state)
8951 unsigned int specifiers;
8952 /* I am overly restrictive in the arragement of specifiers supported.
8953 * C is overly flexible in this department it makes interpreting
8954 * the parse tree difficult.
8958 /* storage class specifier */
8959 specifiers |= storage_class_specifier_opt(state);
8961 /* function-specifier */
8962 specifiers |= function_specifier_opt(state);
8964 /* type qualifier */
8965 specifiers |= type_qualifiers(state);
8967 /* type specifier */
8968 type = type_specifier(state, specifiers);
8977 static struct field_info designator(struct compile_state *state, struct type *type)
8980 struct field_info info;
8984 switch(peek(state)) {
8987 struct triple *value;
8988 if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8989 error(state, 0, "Array designator not in array initializer");
8991 eat(state, TOK_LBRACKET);
8992 value = constant_expr(state);
8993 eat(state, TOK_RBRACKET);
8995 info.type = type->left;
8996 info.offset = value->u.cval * size_of(state, info.type);
9001 struct hash_entry *field;
9002 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
9003 error(state, 0, "Struct designator not in struct initializer");
9005 eat(state, TOK_DOT);
9006 eat(state, TOK_IDENT);
9007 field = state->token[0].ident;
9008 info.offset = field_offset(state, type, field);
9009 info.type = field_type(state, type, field);
9013 error(state, 0, "Invalid designator");
9016 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
9021 static struct triple *initializer(
9022 struct compile_state *state, struct type *type)
9024 struct triple *result;
9025 if (peek(state) != TOK_LBRACE) {
9026 result = assignment_expr(state);
9031 struct field_info info;
9033 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
9034 ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
9035 internal_error(state, 0, "unknown initializer type");
9038 info.type = type->left;
9039 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
9040 info.type = next_field(state, type, 0);
9042 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
9045 max_offset = size_of(state, type);
9047 buf = xcmalloc(max_offset, "initializer");
9048 eat(state, TOK_LBRACE);
9050 struct triple *value;
9051 struct type *value_type;
9057 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
9058 info = designator(state, type);
9060 if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
9061 (info.offset >= max_offset)) {
9062 error(state, 0, "element beyond bounds");
9064 value_type = info.type;
9065 value = eval_const_expr(state, initializer(state, value_type));
9066 value_size = size_of(state, value_type);
9067 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
9068 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
9069 (max_offset <= info.offset)) {
9073 old_size = max_offset;
9074 max_offset = info.offset + value_size;
9075 buf = xmalloc(max_offset, "initializer");
9076 memcpy(buf, old_buf, old_size);
9079 dest = ((char *)buf) + info.offset;
9080 if (value->op == OP_BLOBCONST) {
9081 memcpy(dest, value->u.blob, value_size);
9083 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
9084 *((uint8_t *)dest) = value->u.cval & 0xff;
9086 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
9087 *((uint16_t *)dest) = value->u.cval & 0xffff;
9089 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
9090 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
9093 internal_error(state, 0, "unhandled constant initializer");
9095 free_triple(state, value);
9096 if (peek(state) == TOK_COMMA) {
9097 eat(state, TOK_COMMA);
9100 info.offset += value_size;
9101 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
9102 info.type = next_field(state, type, info.type);
9103 info.offset = field_offset(state, type,
9104 info.type->field_ident);
9106 } while(comma && (peek(state) != TOK_RBRACE));
9107 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
9108 ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
9109 type->elements = max_offset / size_of(state, type->left);
9111 eat(state, TOK_RBRACE);
9112 result = triple(state, OP_BLOBCONST, type, 0, 0);
9113 result->u.blob = buf;
9118 static void resolve_branches(struct compile_state *state)
9120 /* Make a second pass and finish anything outstanding
9121 * with respect to branches. The only outstanding item
9122 * is to see if there are goto to labels that have not
9123 * been defined and to error about them.
9126 for(i = 0; i < HASH_TABLE_SIZE; i++) {
9127 struct hash_entry *entry;
9128 for(entry = state->hash_table[i]; entry; entry = entry->next) {
9130 if (!entry->sym_label) {
9133 ins = entry->sym_label->def;
9134 if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
9135 error(state, ins, "label `%s' used but not defined",
9142 static struct triple *function_definition(
9143 struct compile_state *state, struct type *type)
9145 struct triple *def, *tmp, *first, *end;
9146 struct hash_entry *ident;
9149 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
9150 error(state, 0, "Invalid function header");
9153 /* Verify the function type */
9154 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
9155 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
9156 (type->right->field_ident == 0)) {
9157 error(state, 0, "Invalid function parameters");
9159 param = type->right;
9161 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9163 if (!param->left->field_ident) {
9164 error(state, 0, "No identifier for parameter %d\n", i);
9166 param = param->right;
9169 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9170 error(state, 0, "No identifier for paramter %d\n", i);
9173 /* Get a list of statements for this function. */
9174 def = triple(state, OP_LIST, type, 0, 0);
9176 /* Start a new scope for the passed parameters */
9179 /* Put a label at the very start of a function */
9180 first = label(state);
9181 RHS(def, 0) = first;
9183 /* Put a label at the very end of a function */
9185 flatten(state, first, end);
9187 /* Walk through the parameters and create symbol table entries
9190 param = type->right;
9191 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9192 ident = param->left->field_ident;
9193 tmp = variable(state, param->left);
9194 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9195 flatten(state, end, tmp);
9196 param = param->right;
9198 if ((param->type & TYPE_MASK) != TYPE_VOID) {
9199 /* And don't forget the last parameter */
9200 ident = param->field_ident;
9201 tmp = variable(state, param);
9202 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9203 flatten(state, end, tmp);
9205 /* Add a variable for the return value */
9207 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9208 /* Remove all type qualifiers from the return type */
9209 tmp = variable(state, clone_type(0, type->left));
9210 flatten(state, end, tmp);
9211 /* Remember where the return value is */
9215 /* Remember which function I am compiling.
9216 * Also assume the last defined function is the main function.
9218 state->main_function = def;
9220 /* Now get the actual function definition */
9221 compound_statement(state, end);
9223 /* Finish anything unfinished with branches */
9224 resolve_branches(state);
9226 /* Remove the parameter scope */
9230 fprintf(stdout, "\n");
9231 loc(stdout, state, 0);
9232 fprintf(stdout, "\n__________ function_definition _________\n");
9233 print_triple(state, def);
9234 fprintf(stdout, "__________ function_definition _________ done\n\n");
9240 static struct triple *do_decl(struct compile_state *state,
9241 struct type *type, struct hash_entry *ident)
9245 /* Clean up the storage types used */
9246 switch (type->type & STOR_MASK) {
9249 /* These are the good types I am aiming for */
9252 type->type &= ~STOR_MASK;
9253 type->type |= STOR_AUTO;
9256 type->type &= ~STOR_MASK;
9257 type->type |= STOR_STATIC;
9261 error(state, 0, "typedef without name");
9263 symbol(state, ident, &ident->sym_ident, 0, type);
9264 ident->tok = TOK_TYPE_NAME;
9268 internal_error(state, 0, "Undefined storage class");
9270 if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
9271 error(state, 0, "Function prototypes not supported");
9274 ((type->type & STOR_MASK) == STOR_STATIC) &&
9275 ((type->type & QUAL_CONST) == 0)) {
9276 error(state, 0, "non const static variables not supported");
9279 def = variable(state, type);
9280 symbol(state, ident, &ident->sym_ident, def, type);
9285 static void decl(struct compile_state *state, struct triple *first)
9287 struct type *base_type, *type;
9288 struct hash_entry *ident;
9291 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9292 base_type = decl_specifiers(state);
9294 type = declarator(state, base_type, &ident, 0);
9295 if (global && ident && (peek(state) == TOK_LBRACE)) {
9297 state->function = ident->name;
9298 def = function_definition(state, type);
9299 symbol(state, ident, &ident->sym_ident, def, type);
9300 state->function = 0;
9304 flatten(state, first, do_decl(state, type, ident));
9305 /* type or variable definition */
9308 if (peek(state) == TOK_EQ) {
9310 error(state, 0, "cannot assign to a type");
9313 flatten(state, first,
9315 ident->sym_ident->def,
9316 initializer(state, type)));
9318 arrays_complete(state, type);
9319 if (peek(state) == TOK_COMMA) {
9320 eat(state, TOK_COMMA);
9322 type = declarator(state, base_type, &ident, 0);
9323 flatten(state, first, do_decl(state, type, ident));
9327 eat(state, TOK_SEMI);
9331 static void decls(struct compile_state *state)
9333 struct triple *list;
9335 list = label(state);
9338 if (tok == TOK_EOF) {
9341 if (tok == TOK_SPACE) {
9342 eat(state, TOK_SPACE);
9345 if (list->next != list) {
9346 error(state, 0, "global variables not supported");
9352 * Data structurs for optimation.
9355 static void do_use_block(
9356 struct block *used, struct block_set **head, struct block *user,
9359 struct block_set **ptr, *new;
9366 if ((*ptr)->member == user) {
9369 ptr = &(*ptr)->next;
9371 new = xcmalloc(sizeof(*new), "block_set");
9382 static void do_unuse_block(
9383 struct block *used, struct block_set **head, struct block *unuser)
9385 struct block_set *use, **ptr;
9389 if (use->member == unuser) {
9391 memset(use, -1, sizeof(*use));
9400 static void use_block(struct block *used, struct block *user)
9402 /* Append new to the head of the list, print_block
9405 do_use_block(used, &used->use, user, 1);
9408 static void unuse_block(struct block *used, struct block *unuser)
9410 do_unuse_block(used, &used->use, unuser);
9414 static void idom_block(struct block *idom, struct block *user)
9416 do_use_block(idom, &idom->idominates, user, 0);
9419 static void unidom_block(struct block *idom, struct block *unuser)
9421 do_unuse_block(idom, &idom->idominates, unuser);
9424 static void domf_block(struct block *block, struct block *domf)
9426 do_use_block(block, &block->domfrontier, domf, 0);
9429 static void undomf_block(struct block *block, struct block *undomf)
9431 do_unuse_block(block, &block->domfrontier, undomf);
9434 static void ipdom_block(struct block *ipdom, struct block *user)
9436 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9439 static void unipdom_block(struct block *ipdom, struct block *unuser)
9441 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9444 static void ipdomf_block(struct block *block, struct block *ipdomf)
9446 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9449 static void unipdomf_block(struct block *block, struct block *unipdomf)
9451 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9456 static int do_walk_triple(struct compile_state *state,
9457 struct triple *ptr, int depth,
9458 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9461 result = cb(state, ptr, depth);
9462 if ((result == 0) && (ptr->op == OP_LIST)) {
9463 struct triple *list;
9467 result = do_walk_triple(state, ptr, depth + 1, cb);
9468 if (ptr->next->prev != ptr) {
9469 internal_error(state, ptr->next, "bad prev");
9473 } while((result == 0) && (ptr != RHS(list, 0)));
9478 static int walk_triple(
9479 struct compile_state *state,
9481 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9483 return do_walk_triple(state, ptr, 0, cb);
9486 static void do_print_prefix(int depth)
9489 for(i = 0; i < depth; i++) {
9494 #define PRINT_LIST 1
9495 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9499 if (op == OP_LIST) {
9504 if ((op == OP_LABEL) && (ins->use)) {
9505 printf("\n%p:\n", ins);
9507 do_print_prefix(depth);
9508 display_triple(stdout, ins);
9510 if ((ins->op == OP_BRANCH) && ins->use) {
9511 internal_error(state, ins, "branch used?");
9513 if (triple_is_branch(state, ins)) {
9519 static void print_triple(struct compile_state *state, struct triple *ins)
9521 walk_triple(state, ins, do_print_triple);
9524 static void print_triples(struct compile_state *state)
9526 print_triple(state, state->main_function);
9530 struct block *block;
9532 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9534 if (!block || (cf[block->vertex].block == block)) {
9537 cf[block->vertex].block = block;
9538 find_cf_blocks(cf, block->left);
9539 find_cf_blocks(cf, block->right);
9542 static void print_control_flow(struct compile_state *state)
9544 struct cf_block *cf;
9546 printf("\ncontrol flow\n");
9547 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9548 find_cf_blocks(cf, state->first_block);
9550 for(i = 1; i <= state->last_vertex; i++) {
9551 struct block *block;
9552 block = cf[i].block;
9555 printf("(%p) %d:", block, block->vertex);
9557 printf(" %d", block->left->vertex);
9559 if (block->right && (block->right != block->left)) {
9560 printf(" %d", block->right->vertex);
9569 static struct block *basic_block(struct compile_state *state,
9570 struct triple *first)
9572 struct block *block;
9575 if (first->op != OP_LABEL) {
9576 internal_error(state, 0, "block does not start with a label");
9578 /* See if this basic block has already been setup */
9579 if (first->u.block != 0) {
9580 return first->u.block;
9582 /* Allocate another basic block structure */
9583 state->last_vertex += 1;
9584 block = xcmalloc(sizeof(*block), "block");
9585 block->first = block->last = first;
9586 block->vertex = state->last_vertex;
9589 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9593 /* If ptr->u is not used remember where the baic block is */
9594 if (triple_stores_block(state, ptr)) {
9595 ptr->u.block = block;
9597 if (ptr->op == OP_BRANCH) {
9601 } while (ptr != RHS(state->main_function, 0));
9602 if (ptr == RHS(state->main_function, 0))
9605 if (op == OP_LABEL) {
9606 block->left = basic_block(state, ptr);
9608 use_block(block->left, block);
9610 else if (op == OP_BRANCH) {
9612 /* Trace the branch target */
9613 block->right = basic_block(state, TARG(ptr, 0));
9614 use_block(block->right, block);
9615 /* If there is a test trace the branch as well */
9616 if (TRIPLE_RHS(ptr->sizes)) {
9617 block->left = basic_block(state, ptr->next);
9618 use_block(block->left, block);
9622 internal_error(state, 0, "Bad basic block split");
9628 static void walk_blocks(struct compile_state *state,
9629 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9632 struct triple *ptr, *first;
9633 struct block *last_block;
9635 first = RHS(state->main_function, 0);
9638 struct block *block;
9639 if (triple_stores_block(state, ptr)) {
9640 block = ptr->u.block;
9641 if (block && (block != last_block)) {
9642 cb(state, block, arg);
9646 if (block && (block->last == ptr)) {
9650 } while(ptr != first);
9653 static void print_block(
9654 struct compile_state *state, struct block *block, void *arg)
9656 struct block_set *user;
9660 fprintf(fp, "\nblock: %p (%d) %p<-%p %p<-%p\n",
9664 block->left && block->left->use?block->left->use->member : 0,
9666 block->right && block->right->use?block->right->use->member : 0);
9667 if (block->first->op == OP_LABEL) {
9668 fprintf(fp, "%p:\n", block->first);
9670 for(ptr = block->first; ; ptr = ptr->next) {
9671 display_triple(fp, ptr);
9672 if (ptr == block->last)
9675 fprintf(fp, "users %d: ", block->users);
9676 for(user = block->use; user; user = user->next) {
9677 fprintf(fp, "%p (%d) ",
9679 user->member->vertex);
9685 static void print_blocks(struct compile_state *state, FILE *fp)
9687 fprintf(fp, "--------------- blocks ---------------\n");
9688 walk_blocks(state, print_block, fp);
9691 static void prune_nonblock_triples(struct compile_state *state)
9693 struct block *block;
9694 struct triple *first, *ins, *next;
9695 /* Delete the triples not in a basic block */
9696 first = RHS(state->main_function, 0);
9701 if (ins->op == OP_LABEL) {
9702 block = ins->u.block;
9705 release_triple(state, ins);
9707 if (block && block->last == ins) {
9711 } while(ins != first);
9714 static void setup_basic_blocks(struct compile_state *state)
9716 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9717 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9718 internal_error(state, 0, "ins will not store block?");
9720 /* Find the basic blocks */
9721 state->last_vertex = 0;
9722 state->first_block = basic_block(state, RHS(state->main_function,0));
9723 /* Delete the triples not in a basic block */
9724 prune_nonblock_triples(state);
9725 /* Find the last basic block */
9726 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9727 if (!state->last_block) {
9728 internal_error(state, 0, "end not used?");
9730 /* If we are debugging print what I have just done */
9731 if (state->debug & DEBUG_BASIC_BLOCKS) {
9732 print_blocks(state, stdout);
9733 print_control_flow(state);
9737 static void free_basic_block(struct compile_state *state, struct block *block)
9739 struct block_set *entry, *next;
9740 struct block *child;
9744 if (block->vertex == -1) {
9749 unuse_block(block->left, block);
9752 unuse_block(block->right, block);
9755 unidom_block(block->idom, block);
9759 unipdom_block(block->ipdom, block);
9762 for(entry = block->use; entry; entry = next) {
9764 child = entry->member;
9765 unuse_block(block, child);
9766 if (child->left == block) {
9769 if (child->right == block) {
9773 for(entry = block->idominates; entry; entry = next) {
9775 child = entry->member;
9776 unidom_block(block, child);
9779 for(entry = block->domfrontier; entry; entry = next) {
9781 child = entry->member;
9782 undomf_block(block, child);
9784 for(entry = block->ipdominates; entry; entry = next) {
9786 child = entry->member;
9787 unipdom_block(block, child);
9790 for(entry = block->ipdomfrontier; entry; entry = next) {
9792 child = entry->member;
9793 unipdomf_block(block, child);
9795 if (block->users != 0) {
9796 internal_error(state, 0, "block still has users");
9798 free_basic_block(state, block->left);
9800 free_basic_block(state, block->right);
9802 memset(block, -1, sizeof(*block));
9806 static void free_basic_blocks(struct compile_state *state)
9808 struct triple *first, *ins;
9809 free_basic_block(state, state->first_block);
9810 state->last_vertex = 0;
9811 state->first_block = state->last_block = 0;
9812 first = RHS(state->main_function, 0);
9815 if (triple_stores_block(state, ins)) {
9819 } while(ins != first);
9824 struct block *block;
9825 struct sdom_block *sdominates;
9826 struct sdom_block *sdom_next;
9827 struct sdom_block *sdom;
9828 struct sdom_block *label;
9829 struct sdom_block *parent;
9830 struct sdom_block *ancestor;
9835 static void unsdom_block(struct sdom_block *block)
9837 struct sdom_block **ptr;
9838 if (!block->sdom_next) {
9841 ptr = &block->sdom->sdominates;
9843 if ((*ptr) == block) {
9844 *ptr = block->sdom_next;
9847 ptr = &(*ptr)->sdom_next;
9851 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9853 unsdom_block(block);
9855 block->sdom_next = sdom->sdominates;
9856 sdom->sdominates = block;
9861 static int initialize_sdblock(struct sdom_block *sd,
9862 struct block *parent, struct block *block, int vertex)
9864 if (!block || (sd[block->vertex].block == block)) {
9868 /* Renumber the blocks in a convinient fashion */
9869 block->vertex = vertex;
9870 sd[vertex].block = block;
9871 sd[vertex].sdom = &sd[vertex];
9872 sd[vertex].label = &sd[vertex];
9873 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9874 sd[vertex].ancestor = 0;
9875 sd[vertex].vertex = vertex;
9876 vertex = initialize_sdblock(sd, block, block->left, vertex);
9877 vertex = initialize_sdblock(sd, block, block->right, vertex);
9881 static int initialize_sdpblock(
9882 struct compile_state *state, struct sdom_block *sd,
9883 struct block *parent, struct block *block, int vertex)
9885 struct block_set *user;
9886 if (!block || (sd[block->vertex].block == block)) {
9890 /* Renumber the blocks in a convinient fashion */
9891 block->vertex = vertex;
9892 sd[vertex].block = block;
9893 sd[vertex].sdom = &sd[vertex];
9894 sd[vertex].label = &sd[vertex];
9895 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9896 sd[vertex].ancestor = 0;
9897 sd[vertex].vertex = vertex;
9898 for(user = block->use; user; user = user->next) {
9899 vertex = initialize_sdpblock(state, sd, block, user->member, vertex);
9904 static int setup_sdpblocks(struct compile_state *state, struct sdom_block *sd)
9906 struct block *block;
9908 /* Setup as many sdpblocks as possible without using fake edges */
9909 vertex = initialize_sdpblock(state, sd, 0, state->last_block, 0);
9911 /* Walk through the graph and find unconnected blocks. If
9912 * we can, add a fake edge from the unconnected blocks to the
9915 block = state->first_block->last->next->u.block;
9916 for(; block && block != state->first_block; block = block->last->next->u.block) {
9917 if (sd[block->vertex].block == block) {
9920 if (block->left != 0) {
9924 #if DEBUG_SDP_BLOCKS
9925 fprintf(stderr, "Adding %d\n", vertex +1);
9928 block->left = state->last_block;
9929 use_block(block->left, block);
9930 vertex = initialize_sdpblock(state, sd, state->last_block, block, vertex);
9935 static void compress_ancestors(struct sdom_block *v)
9937 /* This procedure assumes ancestor(v) != 0 */
9938 /* if (ancestor(ancestor(v)) != 0) {
9939 * compress(ancestor(ancestor(v)));
9940 * if (semi(label(ancestor(v))) < semi(label(v))) {
9941 * label(v) = label(ancestor(v));
9943 * ancestor(v) = ancestor(ancestor(v));
9949 if (v->ancestor->ancestor) {
9950 compress_ancestors(v->ancestor->ancestor);
9951 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9952 v->label = v->ancestor->label;
9954 v->ancestor = v->ancestor->ancestor;
9958 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9962 * for each v <= pred(w) {
9964 * if (semi[u] < semi[w] {
9965 * semi[w] = semi[u];
9968 * add w to bucket(vertex(semi[w]));
9969 * LINK(parent(w), w);
9972 * for each v <= bucket(parent(w)) {
9973 * delete v from bucket(parent(w));
9975 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9978 for(i = state->last_vertex; i >= 2; i--) {
9979 struct sdom_block *v, *parent, *next;
9980 struct block_set *user;
9981 struct block *block;
9982 block = sd[i].block;
9983 parent = sd[i].parent;
9985 for(user = block->use; user; user = user->next) {
9986 struct sdom_block *v, *u;
9987 v = &sd[user->member->vertex];
9988 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9989 if (u->sdom->vertex < sd[i].sdom->vertex) {
9990 sd[i].sdom = u->sdom;
9993 sdom_block(sd[i].sdom, &sd[i]);
9994 sd[i].ancestor = parent;
9996 for(v = parent->sdominates; v; v = next) {
9997 struct sdom_block *u;
9998 next = v->sdom_next;
10000 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
10001 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
10002 u->block : parent->block;
10007 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
10011 * for each v <= pred(w) {
10013 * if (semi[u] < semi[w] {
10014 * semi[w] = semi[u];
10017 * add w to bucket(vertex(semi[w]));
10018 * LINK(parent(w), w);
10021 * for each v <= bucket(parent(w)) {
10022 * delete v from bucket(parent(w));
10024 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
10027 for(i = state->last_vertex; i >= 2; i--) {
10028 struct sdom_block *u, *v, *parent, *next;
10029 struct block *block;
10030 block = sd[i].block;
10031 parent = sd[i].parent;
10034 v = &sd[block->left->vertex];
10035 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10036 if (u->sdom->vertex < sd[i].sdom->vertex) {
10037 sd[i].sdom = u->sdom;
10040 if (block->right && (block->right != block->left)) {
10041 v = &sd[block->right->vertex];
10042 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10043 if (u->sdom->vertex < sd[i].sdom->vertex) {
10044 sd[i].sdom = u->sdom;
10047 sdom_block(sd[i].sdom, &sd[i]);
10048 sd[i].ancestor = parent;
10050 for(v = parent->sdominates; v; v = next) {
10051 struct sdom_block *u;
10052 next = v->sdom_next;
10054 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
10055 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
10056 u->block : parent->block;
10061 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
10064 for(i = 2; i <= state->last_vertex; i++) {
10065 struct block *block;
10066 block = sd[i].block;
10067 if (block->idom->vertex != sd[i].sdom->vertex) {
10068 block->idom = block->idom->idom;
10070 idom_block(block->idom, block);
10072 sd[1].block->idom = 0;
10075 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
10078 for(i = 2; i <= state->last_vertex; i++) {
10079 struct block *block;
10080 block = sd[i].block;
10081 if (block->ipdom->vertex != sd[i].sdom->vertex) {
10082 block->ipdom = block->ipdom->ipdom;
10084 ipdom_block(block->ipdom, block);
10086 sd[1].block->ipdom = 0;
10090 * Every vertex of a flowgraph G = (V, E, r) except r has
10091 * a unique immediate dominator.
10092 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
10093 * rooted at r, called the dominator tree of G, such that
10094 * v dominates w if and only if v is a proper ancestor of w in
10095 * the dominator tree.
10098 * If v and w are vertices of G such that v <= w,
10099 * than any path from v to w must contain a common ancestor
10102 /* Lemma 2: For any vertex w != r, idom(w) -> w */
10103 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
10104 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
10106 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
10107 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
10110 * Let w != r and let u be a vertex for which sdom(u) is
10111 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
10112 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
10114 /* Lemma 5: Let vertices v,w satisfy v -> w.
10115 * Then v -> idom(w) or idom(w) -> idom(v)
10118 static void find_immediate_dominators(struct compile_state *state)
10120 struct sdom_block *sd;
10121 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
10122 * vi > w for (1 <= i <= k - 1}
10125 * For any vertex w != r.
10127 * {v|(v,w) <= E and v < w } U
10128 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
10131 * Let w != r and let u be a vertex for which sdom(u) is
10132 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
10134 * { sdom(w) if sdom(w) = sdom(u),
10136 * { idom(u) otherwise
10138 /* The algorithm consists of the following 4 steps.
10139 * Step 1. Carry out a depth-first search of the problem graph.
10140 * Number the vertices from 1 to N as they are reached during
10141 * the search. Initialize the variables used in succeeding steps.
10142 * Step 2. Compute the semidominators of all vertices by applying
10143 * theorem 4. Carry out the computation vertex by vertex in
10144 * decreasing order by number.
10145 * Step 3. Implicitly define the immediate dominator of each vertex
10146 * by applying Corollary 1.
10147 * Step 4. Explicitly define the immediate dominator of each vertex,
10148 * carrying out the computation vertex by vertex in increasing order
10151 /* Step 1 initialize the basic block information */
10152 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10153 initialize_sdblock(sd, 0, state->first_block, 0);
10159 /* Step 2 compute the semidominators */
10160 /* Step 3 implicitly define the immediate dominator of each vertex */
10161 compute_sdom(state, sd);
10162 /* Step 4 explicitly define the immediate dominator of each vertex */
10163 compute_idom(state, sd);
10167 static void find_post_dominators(struct compile_state *state)
10169 struct sdom_block *sd;
10171 /* Step 1 initialize the basic block information */
10172 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10174 vertex = setup_sdpblocks(state, sd);
10175 if (vertex != state->last_vertex) {
10176 internal_error(state, 0, "missing %d blocks\n",
10177 state->last_vertex - vertex);
10180 /* Step 2 compute the semidominators */
10181 /* Step 3 implicitly define the immediate dominator of each vertex */
10182 compute_spdom(state, sd);
10183 /* Step 4 explicitly define the immediate dominator of each vertex */
10184 compute_ipdom(state, sd);
10190 static void find_block_domf(struct compile_state *state, struct block *block)
10192 struct block *child;
10193 struct block_set *user;
10194 if (block->domfrontier != 0) {
10195 internal_error(state, block->first, "domfrontier present?");
10197 for(user = block->idominates; user; user = user->next) {
10198 child = user->member;
10199 if (child->idom != block) {
10200 internal_error(state, block->first, "bad idom");
10202 find_block_domf(state, child);
10204 if (block->left && block->left->idom != block) {
10205 domf_block(block, block->left);
10207 if (block->right && block->right->idom != block) {
10208 domf_block(block, block->right);
10210 for(user = block->idominates; user; user = user->next) {
10211 struct block_set *frontier;
10212 child = user->member;
10213 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10214 if (frontier->member->idom != block) {
10215 domf_block(block, frontier->member);
10221 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10223 struct block *child;
10224 struct block_set *user;
10225 if (block->ipdomfrontier != 0) {
10226 internal_error(state, block->first, "ipdomfrontier present?");
10228 for(user = block->ipdominates; user; user = user->next) {
10229 child = user->member;
10230 if (child->ipdom != block) {
10231 internal_error(state, block->first, "bad ipdom");
10233 find_block_ipdomf(state, child);
10235 if (block->left && block->left->ipdom != block) {
10236 ipdomf_block(block, block->left);
10238 if (block->right && block->right->ipdom != block) {
10239 ipdomf_block(block, block->right);
10241 for(user = block->idominates; user; user = user->next) {
10242 struct block_set *frontier;
10243 child = user->member;
10244 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10245 if (frontier->member->ipdom != block) {
10246 ipdomf_block(block, frontier->member);
10252 static void print_dominated(
10253 struct compile_state *state, struct block *block, void *arg)
10255 struct block_set *user;
10258 fprintf(fp, "%d:", block->vertex);
10259 for(user = block->idominates; user; user = user->next) {
10260 fprintf(fp, " %d", user->member->vertex);
10261 if (user->member->idom != block) {
10262 internal_error(state, user->member->first, "bad idom");
10268 static void print_dominators(struct compile_state *state, FILE *fp)
10270 fprintf(fp, "\ndominates\n");
10271 walk_blocks(state, print_dominated, fp);
10275 static int print_frontiers(
10276 struct compile_state *state, struct block *block, int vertex)
10278 struct block_set *user;
10280 if (!block || (block->vertex != vertex + 1)) {
10285 printf("%d:", block->vertex);
10286 for(user = block->domfrontier; user; user = user->next) {
10287 printf(" %d", user->member->vertex);
10291 vertex = print_frontiers(state, block->left, vertex);
10292 vertex = print_frontiers(state, block->right, vertex);
10295 static void print_dominance_frontiers(struct compile_state *state)
10297 printf("\ndominance frontiers\n");
10298 print_frontiers(state, state->first_block, 0);
10302 static void analyze_idominators(struct compile_state *state)
10304 /* Find the immediate dominators */
10305 find_immediate_dominators(state);
10306 /* Find the dominance frontiers */
10307 find_block_domf(state, state->first_block);
10308 /* If debuging print the print what I have just found */
10309 if (state->debug & DEBUG_FDOMINATORS) {
10310 print_dominators(state, stdout);
10311 print_dominance_frontiers(state);
10312 print_control_flow(state);
10318 static void print_ipdominated(
10319 struct compile_state *state, struct block *block, void *arg)
10321 struct block_set *user;
10324 fprintf(fp, "%d:", block->vertex);
10325 for(user = block->ipdominates; user; user = user->next) {
10326 fprintf(fp, " %d", user->member->vertex);
10327 if (user->member->ipdom != block) {
10328 internal_error(state, user->member->first, "bad ipdom");
10334 static void print_ipdominators(struct compile_state *state, FILE *fp)
10336 fprintf(fp, "\nipdominates\n");
10337 walk_blocks(state, print_ipdominated, fp);
10340 static int print_pfrontiers(
10341 struct compile_state *state, struct block *block, int vertex)
10343 struct block_set *user;
10345 if (!block || (block->vertex != vertex + 1)) {
10350 printf("%d:", block->vertex);
10351 for(user = block->ipdomfrontier; user; user = user->next) {
10352 printf(" %d", user->member->vertex);
10355 for(user = block->use; user; user = user->next) {
10356 vertex = print_pfrontiers(state, user->member, vertex);
10360 static void print_ipdominance_frontiers(struct compile_state *state)
10362 printf("\nipdominance frontiers\n");
10363 print_pfrontiers(state, state->last_block, 0);
10367 static void analyze_ipdominators(struct compile_state *state)
10369 /* Find the post dominators */
10370 find_post_dominators(state);
10371 /* Find the control dependencies (post dominance frontiers) */
10372 find_block_ipdomf(state, state->last_block);
10373 /* If debuging print the print what I have just found */
10374 if (state->debug & DEBUG_RDOMINATORS) {
10375 print_ipdominators(state, stdout);
10376 print_ipdominance_frontiers(state);
10377 print_control_flow(state);
10381 static int bdominates(struct compile_state *state,
10382 struct block *dom, struct block *sub)
10384 while(sub && (sub != dom)) {
10390 static int tdominates(struct compile_state *state,
10391 struct triple *dom, struct triple *sub)
10393 struct block *bdom, *bsub;
10395 bdom = block_of_triple(state, dom);
10396 bsub = block_of_triple(state, sub);
10397 if (bdom != bsub) {
10398 result = bdominates(state, bdom, bsub);
10401 struct triple *ins;
10403 while((ins != bsub->first) && (ins != dom)) {
10406 result = (ins == dom);
10411 static void insert_phi_operations(struct compile_state *state)
10414 struct triple *first;
10415 int *has_already, *work;
10416 struct block *work_list, **work_list_tail;
10418 struct triple *var, *vnext;
10420 size = sizeof(int) * (state->last_vertex + 1);
10421 has_already = xcmalloc(size, "has_already");
10422 work = xcmalloc(size, "work");
10425 first = RHS(state->main_function, 0);
10426 for(var = first->next; var != first ; var = vnext) {
10427 struct block *block;
10428 struct triple_set *user, *unext;
10430 if ((var->op != OP_ADECL) || !var->use) {
10435 work_list_tail = &work_list;
10436 for(user = var->use; user; user = unext) {
10437 unext = user->next;
10438 if (user->member->op == OP_READ) {
10441 if (user->member->op != OP_WRITE) {
10442 internal_error(state, user->member,
10443 "bad variable access");
10445 block = user->member->u.block;
10447 warning(state, user->member, "dead code");
10448 release_triple(state, user->member);
10451 if (work[block->vertex] >= iter) {
10454 work[block->vertex] = iter;
10455 *work_list_tail = block;
10456 block->work_next = 0;
10457 work_list_tail = &block->work_next;
10459 for(block = work_list; block; block = block->work_next) {
10460 struct block_set *df;
10461 for(df = block->domfrontier; df; df = df->next) {
10462 struct triple *phi;
10463 struct block *front;
10465 front = df->member;
10467 if (has_already[front->vertex] >= iter) {
10470 /* Count how many edges flow into this block */
10471 in_edges = front->users;
10472 /* Insert a phi function for this variable */
10473 get_occurance(front->first->occurance);
10474 phi = alloc_triple(
10475 state, OP_PHI, var->type, -1, in_edges,
10476 front->first->occurance);
10477 phi->u.block = front;
10478 MISC(phi, 0) = var;
10479 use_triple(var, phi);
10480 /* Insert the phi functions immediately after the label */
10481 insert_triple(state, front->first->next, phi);
10482 if (front->first == front->last) {
10483 front->last = front->first->next;
10485 has_already[front->vertex] = iter;
10487 /* If necessary plan to visit the basic block */
10488 if (work[front->vertex] >= iter) {
10491 work[front->vertex] = iter;
10492 *work_list_tail = front;
10493 front->work_next = 0;
10494 work_list_tail = &front->work_next;
10498 xfree(has_already);
10506 static void fixup_block_phi_variables(
10507 struct compile_state *state, struct block *parent, struct block *block)
10509 struct block_set *set;
10510 struct triple *ptr;
10512 if (!parent || !block)
10514 /* Find the edge I am coming in on */
10516 for(set = block->use; set; set = set->next, edge++) {
10517 if (set->member == parent) {
10522 internal_error(state, 0, "phi input is not on a control predecessor");
10524 for(ptr = block->first; ; ptr = ptr->next) {
10525 if (ptr->op == OP_PHI) {
10526 struct triple *var, *val, **slot;
10527 var = MISC(ptr, 0);
10529 internal_error(state, ptr, "no var???");
10531 /* Find the current value of the variable */
10532 val = var->use->member;
10533 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10534 internal_error(state, val, "bad value in phi");
10536 if (edge >= TRIPLE_RHS(ptr->sizes)) {
10537 internal_error(state, ptr, "edges > phi rhs");
10539 slot = &RHS(ptr, edge);
10540 if ((*slot != 0) && (*slot != val)) {
10541 internal_error(state, ptr, "phi already bound on this edge");
10544 use_triple(val, ptr);
10546 if (ptr == block->last) {
10553 static void rename_block_variables(
10554 struct compile_state *state, struct block *block)
10556 struct block_set *user;
10557 struct triple *ptr, *next, *last;
10561 last = block->first;
10563 for(ptr = block->first; !done; ptr = next) {
10565 if (ptr == block->last) {
10569 if (ptr->op == OP_READ) {
10570 struct triple *var, *val;
10572 unuse_triple(var, ptr);
10574 error(state, ptr, "variable used without being set");
10576 /* Find the current value of the variable */
10577 val = var->use->member;
10578 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10579 internal_error(state, val, "bad value in read");
10581 propogate_use(state, ptr, val);
10582 release_triple(state, ptr);
10586 if (ptr->op == OP_WRITE) {
10587 struct triple *var, *val, *tval;
10589 tval = val = RHS(ptr, 1);
10590 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10591 internal_error(state, val, "bad value in write");
10593 /* Insert a copy if the types differ */
10594 if (!equiv_types(ptr->type, val->type)) {
10595 if (val->op == OP_INTCONST) {
10596 tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
10597 tval->u.cval = val->u.cval;
10600 tval = pre_triple(state, ptr, OP_COPY, ptr->type, val, 0);
10601 use_triple(val, tval);
10603 unuse_triple(val, ptr);
10604 RHS(ptr, 1) = tval;
10605 use_triple(tval, ptr);
10607 propogate_use(state, ptr, tval);
10608 unuse_triple(var, ptr);
10609 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10610 push_triple(var, tval);
10612 if (ptr->op == OP_PHI) {
10613 struct triple *var;
10614 var = MISC(ptr, 0);
10615 /* Push OP_PHI onto a stack of variable uses */
10616 push_triple(var, ptr);
10620 block->last = last;
10622 /* Fixup PHI functions in the cf successors */
10623 fixup_block_phi_variables(state, block, block->left);
10624 fixup_block_phi_variables(state, block, block->right);
10625 /* rename variables in the dominated nodes */
10626 for(user = block->idominates; user; user = user->next) {
10627 rename_block_variables(state, user->member);
10629 /* pop the renamed variable stack */
10630 last = block->first;
10632 for(ptr = block->first; !done ; ptr = next) {
10634 if (ptr == block->last) {
10637 if (ptr->op == OP_WRITE) {
10638 struct triple *var;
10640 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10641 pop_triple(var, RHS(ptr, 1));
10642 release_triple(state, ptr);
10645 if (ptr->op == OP_PHI) {
10646 struct triple *var;
10647 var = MISC(ptr, 0);
10648 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10649 pop_triple(var, ptr);
10653 block->last = last;
10656 static void prune_block_variables(struct compile_state *state,
10657 struct block *block)
10659 struct block_set *user;
10660 struct triple *next, *last, *ptr;
10662 last = block->first;
10664 for(ptr = block->first; !done; ptr = next) {
10666 if (ptr == block->last) {
10669 if (ptr->op == OP_ADECL) {
10670 struct triple_set *user, *next;
10671 for(user = ptr->use; user; user = next) {
10672 struct triple *use;
10674 use = user->member;
10675 if (use->op != OP_PHI) {
10676 internal_error(state, use, "decl still used");
10678 if (MISC(use, 0) != ptr) {
10679 internal_error(state, use, "bad phi use of decl");
10681 unuse_triple(ptr, use);
10684 release_triple(state, ptr);
10689 block->last = last;
10690 for(user = block->idominates; user; user = user->next) {
10691 prune_block_variables(state, user->member);
10695 static void transform_to_ssa_form(struct compile_state *state)
10697 insert_phi_operations(state);
10699 printf("@%s:%d\n", __FILE__, __LINE__);
10700 print_blocks(state, stdout);
10702 rename_block_variables(state, state->first_block);
10703 prune_block_variables(state, state->first_block);
10707 static void clear_vertex(
10708 struct compile_state *state, struct block *block, void *arg)
10713 static void mark_live_block(
10714 struct compile_state *state, struct block *block, int *next_vertex)
10716 /* See if this is a block that has not been marked */
10717 if (block->vertex != 0) {
10720 block->vertex = *next_vertex;
10722 if (triple_is_branch(state, block->last)) {
10723 struct triple **targ;
10724 targ = triple_targ(state, block->last, 0);
10725 for(; targ; targ = triple_targ(state, block->last, targ)) {
10729 if (!triple_stores_block(state, *targ)) {
10730 internal_error(state, 0, "bad targ");
10732 mark_live_block(state, (*targ)->u.block, next_vertex);
10735 else if (block->last->next != RHS(state->main_function, 0)) {
10736 struct triple *ins;
10737 ins = block->last->next;
10738 if (!triple_stores_block(state, ins)) {
10739 internal_error(state, 0, "bad block start");
10741 mark_live_block(state, ins->u.block, next_vertex);
10745 static void transform_from_ssa_form(struct compile_state *state)
10747 /* To get out of ssa form we insert moves on the incoming
10748 * edges to blocks containting phi functions.
10750 struct triple *first;
10751 struct triple *phi, *next;
10754 /* Walk the control flow to see which blocks remain alive */
10755 walk_blocks(state, clear_vertex, 0);
10757 mark_live_block(state, state->first_block, &next_vertex);
10759 /* Walk all of the operations to find the phi functions */
10760 first = RHS(state->main_function, 0);
10761 for(phi = first->next; phi != first ; phi = next) {
10762 struct block_set *set;
10763 struct block *block;
10764 struct triple **slot;
10765 struct triple *var, *read;
10766 struct triple_set *use, *use_next;
10769 if (phi->op != OP_PHI) {
10772 block = phi->u.block;
10773 slot = &RHS(phi, 0);
10775 /* Forget uses from code in dead blocks */
10776 for(use = phi->use; use; use = use_next) {
10777 struct block *ublock;
10778 struct triple **expr;
10779 use_next = use->next;
10780 ublock = block_of_triple(state, use->member);
10781 if ((use->member == phi) || (ublock->vertex != 0)) {
10784 expr = triple_rhs(state, use->member, 0);
10785 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10786 if (*expr == phi) {
10790 unuse_triple(phi, use->member);
10793 #warning "CHECK_ME does the OP_ADECL need to be placed somewhere that dominates all of the incoming phi edges?"
10794 /* A variable to replace the phi function */
10795 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10796 /* A read of the single value that is set into the variable */
10797 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10798 use_triple(var, read);
10800 /* Replaces uses of the phi with variable reads */
10801 propogate_use(state, phi, read);
10803 /* Walk all of the incoming edges/blocks and insert moves.
10805 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10806 struct block *eblock;
10807 struct triple *move;
10808 struct triple *val, *base;
10809 eblock = set->member;
10812 unuse_triple(val, phi);
10814 if (!val || (val == &zero_triple) ||
10815 (block->vertex == 0) || (eblock->vertex == 0) ||
10816 (val == phi) || (val == read)) {
10820 /* Make certain the write is placed in the edge block... */
10821 base = eblock->first;
10822 if (block_of_triple(state, val) == eblock) {
10825 move = post_triple(state, base, OP_WRITE, phi->type, var, val);
10826 use_triple(val, move);
10827 use_triple(var, move);
10829 /* See if there are any writers of var */
10831 for(use = var->use; use; use = use->next) {
10832 if ((use->member->op == OP_WRITE) &&
10833 (RHS(use->member, 0) == var)) {
10837 /* If var is not used free it */
10839 unuse_triple(var, read);
10840 free_triple(state, read);
10841 free_triple(state, var);
10844 /* Release the phi function */
10845 release_triple(state, phi);
10852 * Register conflict resolution
10853 * =========================================================
10856 static struct reg_info find_def_color(
10857 struct compile_state *state, struct triple *def)
10859 struct triple_set *set;
10860 struct reg_info info;
10861 info.reg = REG_UNSET;
10863 if (!triple_is_def(state, def)) {
10866 info = arch_reg_lhs(state, def, 0);
10867 if (info.reg >= MAX_REGISTERS) {
10868 info.reg = REG_UNSET;
10870 for(set = def->use; set; set = set->next) {
10871 struct reg_info tinfo;
10873 i = find_rhs_use(state, set->member, def);
10877 tinfo = arch_reg_rhs(state, set->member, i);
10878 if (tinfo.reg >= MAX_REGISTERS) {
10879 tinfo.reg = REG_UNSET;
10881 if ((tinfo.reg != REG_UNSET) &&
10882 (info.reg != REG_UNSET) &&
10883 (tinfo.reg != info.reg)) {
10884 internal_error(state, def, "register conflict");
10886 if ((info.regcm & tinfo.regcm) == 0) {
10887 internal_error(state, def, "regcm conflict %x & %x == 0",
10888 info.regcm, tinfo.regcm);
10890 if (info.reg == REG_UNSET) {
10891 info.reg = tinfo.reg;
10893 info.regcm &= tinfo.regcm;
10895 if (info.reg >= MAX_REGISTERS) {
10896 internal_error(state, def, "register out of range");
10901 static struct reg_info find_lhs_pre_color(
10902 struct compile_state *state, struct triple *ins, int index)
10904 struct reg_info info;
10906 zrhs = TRIPLE_RHS(ins->sizes);
10907 zlhs = TRIPLE_LHS(ins->sizes);
10908 if (!zlhs && triple_is_def(state, ins)) {
10911 if (index >= zlhs) {
10912 internal_error(state, ins, "Bad lhs %d", index);
10914 info = arch_reg_lhs(state, ins, index);
10915 for(i = 0; i < zrhs; i++) {
10916 struct reg_info rinfo;
10917 rinfo = arch_reg_rhs(state, ins, i);
10918 if ((info.reg == rinfo.reg) &&
10919 (rinfo.reg >= MAX_REGISTERS)) {
10920 struct reg_info tinfo;
10921 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10922 info.reg = tinfo.reg;
10923 info.regcm &= tinfo.regcm;
10927 if (info.reg >= MAX_REGISTERS) {
10928 info.reg = REG_UNSET;
10933 static struct reg_info find_rhs_post_color(
10934 struct compile_state *state, struct triple *ins, int index);
10936 static struct reg_info find_lhs_post_color(
10937 struct compile_state *state, struct triple *ins, int index)
10939 struct triple_set *set;
10940 struct reg_info info;
10941 struct triple *lhs;
10942 #if DEBUG_TRIPLE_COLOR
10943 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10946 if ((index == 0) && triple_is_def(state, ins)) {
10949 else if (index < TRIPLE_LHS(ins->sizes)) {
10950 lhs = LHS(ins, index);
10953 internal_error(state, ins, "Bad lhs %d", index);
10956 info = arch_reg_lhs(state, ins, index);
10957 if (info.reg >= MAX_REGISTERS) {
10958 info.reg = REG_UNSET;
10960 for(set = lhs->use; set; set = set->next) {
10961 struct reg_info rinfo;
10962 struct triple *user;
10964 user = set->member;
10965 zrhs = TRIPLE_RHS(user->sizes);
10966 for(i = 0; i < zrhs; i++) {
10967 if (RHS(user, i) != lhs) {
10970 rinfo = find_rhs_post_color(state, user, i);
10971 if ((info.reg != REG_UNSET) &&
10972 (rinfo.reg != REG_UNSET) &&
10973 (info.reg != rinfo.reg)) {
10974 internal_error(state, ins, "register conflict");
10976 if ((info.regcm & rinfo.regcm) == 0) {
10977 internal_error(state, ins, "regcm conflict %x & %x == 0",
10978 info.regcm, rinfo.regcm);
10980 if (info.reg == REG_UNSET) {
10981 info.reg = rinfo.reg;
10983 info.regcm &= rinfo.regcm;
10986 #if DEBUG_TRIPLE_COLOR
10987 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10988 ins, index, info.reg, info.regcm);
10993 static struct reg_info find_rhs_post_color(
10994 struct compile_state *state, struct triple *ins, int index)
10996 struct reg_info info, rinfo;
10998 #if DEBUG_TRIPLE_COLOR
10999 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
11002 rinfo = arch_reg_rhs(state, ins, index);
11003 zlhs = TRIPLE_LHS(ins->sizes);
11004 if (!zlhs && triple_is_def(state, ins)) {
11008 if (info.reg >= MAX_REGISTERS) {
11009 info.reg = REG_UNSET;
11011 for(i = 0; i < zlhs; i++) {
11012 struct reg_info linfo;
11013 linfo = arch_reg_lhs(state, ins, i);
11014 if ((linfo.reg == rinfo.reg) &&
11015 (linfo.reg >= MAX_REGISTERS)) {
11016 struct reg_info tinfo;
11017 tinfo = find_lhs_post_color(state, ins, i);
11018 if (tinfo.reg >= MAX_REGISTERS) {
11019 tinfo.reg = REG_UNSET;
11021 info.regcm &= linfo.regcm;
11022 info.regcm &= tinfo.regcm;
11023 if (info.reg != REG_UNSET) {
11024 internal_error(state, ins, "register conflict");
11026 if (info.regcm == 0) {
11027 internal_error(state, ins, "regcm conflict");
11029 info.reg = tinfo.reg;
11032 #if DEBUG_TRIPLE_COLOR
11033 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
11034 ins, index, info.reg, info.regcm);
11039 static struct reg_info find_lhs_color(
11040 struct compile_state *state, struct triple *ins, int index)
11042 struct reg_info pre, post, info;
11043 #if DEBUG_TRIPLE_COLOR
11044 fprintf(stderr, "find_lhs_color(%p, %d)\n",
11047 pre = find_lhs_pre_color(state, ins, index);
11048 post = find_lhs_post_color(state, ins, index);
11049 if ((pre.reg != post.reg) &&
11050 (pre.reg != REG_UNSET) &&
11051 (post.reg != REG_UNSET)) {
11052 internal_error(state, ins, "register conflict");
11054 info.regcm = pre.regcm & post.regcm;
11055 info.reg = pre.reg;
11056 if (info.reg == REG_UNSET) {
11057 info.reg = post.reg;
11059 #if DEBUG_TRIPLE_COLOR
11060 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
11061 ins, index, info.reg, info.regcm,
11062 pre.reg, pre.regcm, post.reg, post.regcm);
11067 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
11069 struct triple_set *entry, *next;
11070 struct triple *out;
11071 struct reg_info info, rinfo;
11073 info = arch_reg_lhs(state, ins, 0);
11074 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
11075 use_triple(RHS(out, 0), out);
11076 /* Get the users of ins to use out instead */
11077 for(entry = ins->use; entry; entry = next) {
11079 next = entry->next;
11080 if (entry->member == out) {
11083 i = find_rhs_use(state, entry->member, ins);
11087 rinfo = arch_reg_rhs(state, entry->member, i);
11088 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
11091 replace_rhs_use(state, ins, out, entry->member);
11093 transform_to_arch_instruction(state, out);
11097 static struct triple *typed_pre_copy(
11098 struct compile_state *state, struct type *type, struct triple *ins, int index)
11100 /* Carefully insert enough operations so that I can
11101 * enter any operation with a GPR32.
11104 struct triple **expr;
11106 struct reg_info info;
11107 if (ins->op == OP_PHI) {
11108 internal_error(state, ins, "pre_copy on a phi?");
11110 classes = arch_type_to_regcm(state, type);
11111 info = arch_reg_rhs(state, ins, index);
11112 expr = &RHS(ins, index);
11113 if ((info.regcm & classes) == 0) {
11114 internal_error(state, ins, "pre_copy with no register classes");
11116 in = pre_triple(state, ins, OP_COPY, type, *expr, 0);
11117 unuse_triple(*expr, ins);
11119 use_triple(RHS(in, 0), in);
11120 use_triple(in, ins);
11121 transform_to_arch_instruction(state, in);
11125 static struct triple *pre_copy(
11126 struct compile_state *state, struct triple *ins, int index)
11128 return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
11132 static void insert_copies_to_phi(struct compile_state *state)
11134 /* To get out of ssa form we insert moves on the incoming
11135 * edges to blocks containting phi functions.
11137 struct triple *first;
11138 struct triple *phi;
11140 /* Walk all of the operations to find the phi functions */
11141 first = RHS(state->main_function, 0);
11142 for(phi = first->next; phi != first ; phi = phi->next) {
11143 struct block_set *set;
11144 struct block *block;
11145 struct triple **slot, *copy;
11147 if (phi->op != OP_PHI) {
11150 phi->id |= TRIPLE_FLAG_POST_SPLIT;
11151 block = phi->u.block;
11152 slot = &RHS(phi, 0);
11153 /* Phi's that feed into mandatory live range joins
11154 * cause nasty complications. Insert a copy of
11155 * the phi value so I never have to deal with
11156 * that in the rest of the code.
11158 copy = post_copy(state, phi);
11159 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
11160 /* Walk all of the incoming edges/blocks and insert moves.
11162 for(edge = 0, set = block->use; set; set = set->next, edge++) {
11163 struct block *eblock;
11164 struct triple *move;
11165 struct triple *val;
11166 struct triple *ptr;
11167 eblock = set->member;
11174 get_occurance(val->occurance);
11175 move = build_triple(state, OP_COPY, phi->type, val, 0,
11177 move->u.block = eblock;
11178 move->id |= TRIPLE_FLAG_PRE_SPLIT;
11179 use_triple(val, move);
11182 unuse_triple(val, phi);
11183 use_triple(move, phi);
11185 /* Walk through the block backwards to find
11186 * an appropriate location for the OP_COPY.
11188 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
11189 struct triple **expr;
11190 if ((ptr == phi) || (ptr == val)) {
11193 expr = triple_rhs(state, ptr, 0);
11194 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11195 if ((*expr) == phi) {
11201 if (triple_is_branch(state, ptr)) {
11202 internal_error(state, ptr,
11203 "Could not insert write to phi");
11205 insert_triple(state, ptr->next, move);
11206 if (eblock->last == ptr) {
11207 eblock->last = move;
11209 transform_to_arch_instruction(state, move);
11214 struct triple_reg_set {
11215 struct triple_reg_set *next;
11216 struct triple *member;
11217 struct triple *new;
11221 struct block *block;
11222 struct triple_reg_set *in;
11223 struct triple_reg_set *out;
11227 static int do_triple_set(struct triple_reg_set **head,
11228 struct triple *member, struct triple *new_member)
11230 struct triple_reg_set **ptr, *new;
11235 if ((*ptr)->member == member) {
11238 ptr = &(*ptr)->next;
11240 new = xcmalloc(sizeof(*new), "triple_set");
11241 new->member = member;
11242 new->new = new_member;
11248 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11250 struct triple_reg_set *entry, **ptr;
11254 if (entry->member == member) {
11255 *ptr = entry->next;
11260 ptr = &entry->next;
11265 static int in_triple(struct reg_block *rb, struct triple *in)
11267 return do_triple_set(&rb->in, in, 0);
11269 static void unin_triple(struct reg_block *rb, struct triple *unin)
11271 do_triple_unset(&rb->in, unin);
11274 static int out_triple(struct reg_block *rb, struct triple *out)
11276 return do_triple_set(&rb->out, out, 0);
11278 static void unout_triple(struct reg_block *rb, struct triple *unout)
11280 do_triple_unset(&rb->out, unout);
11283 static int initialize_regblock(struct reg_block *blocks,
11284 struct block *block, int vertex)
11286 struct block_set *user;
11287 if (!block || (blocks[block->vertex].block == block)) {
11291 /* Renumber the blocks in a convinient fashion */
11292 block->vertex = vertex;
11293 blocks[vertex].block = block;
11294 blocks[vertex].vertex = vertex;
11295 for(user = block->use; user; user = user->next) {
11296 vertex = initialize_regblock(blocks, user->member, vertex);
11301 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11302 struct reg_block *rb, struct block *suc)
11304 /* Read the conditional input set of a successor block
11305 * (i.e. the input to the phi nodes) and place it in the
11306 * current blocks output set.
11308 struct block_set *set;
11309 struct triple *ptr;
11313 /* Find the edge I am coming in on */
11314 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11315 if (set->member == rb->block) {
11320 internal_error(state, 0, "Not coming on a control edge?");
11322 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11323 struct triple **slot, *expr, *ptr2;
11324 int out_change, done2;
11325 done = (ptr == suc->last);
11326 if (ptr->op != OP_PHI) {
11329 slot = &RHS(ptr, 0);
11331 out_change = out_triple(rb, expr);
11335 /* If we don't define the variable also plast it
11336 * in the current blocks input set.
11338 ptr2 = rb->block->first;
11339 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11340 if (ptr2 == expr) {
11343 done2 = (ptr2 == rb->block->last);
11348 change |= in_triple(rb, expr);
11353 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11354 struct reg_block *rb, struct block *suc)
11356 struct triple_reg_set *in_set;
11359 /* Read the input set of a successor block
11360 * and place it in the current blocks output set.
11362 in_set = blocks[suc->vertex].in;
11363 for(; in_set; in_set = in_set->next) {
11364 int out_change, done;
11365 struct triple *first, *last, *ptr;
11366 out_change = out_triple(rb, in_set->member);
11370 /* If we don't define the variable also place it
11371 * in the current blocks input set.
11373 first = rb->block->first;
11374 last = rb->block->last;
11376 for(ptr = first; !done; ptr = ptr->next) {
11377 if (ptr == in_set->member) {
11380 done = (ptr == last);
11385 change |= in_triple(rb, in_set->member);
11387 change |= phi_in(state, blocks, rb, suc);
11392 static int use_in(struct compile_state *state, struct reg_block *rb)
11394 /* Find the variables we use but don't define and add
11395 * it to the current blocks input set.
11397 #warning "FIXME is this O(N^2) algorithm bad?"
11398 struct block *block;
11399 struct triple *ptr;
11404 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11405 struct triple **expr;
11406 done = (ptr == block->first);
11407 /* The variable a phi function uses depends on the
11408 * control flow, and is handled in phi_in, not
11411 if (ptr->op == OP_PHI) {
11414 expr = triple_rhs(state, ptr, 0);
11415 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11416 struct triple *rhs, *test;
11422 /* See if rhs is defined in this block */
11423 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11424 tdone = (test == block->first);
11430 /* If I still have a valid rhs add it to in */
11431 change |= in_triple(rb, rhs);
11437 static struct reg_block *compute_variable_lifetimes(
11438 struct compile_state *state)
11440 struct reg_block *blocks;
11443 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11444 initialize_regblock(blocks, state->last_block, 0);
11448 for(i = 1; i <= state->last_vertex; i++) {
11449 struct reg_block *rb;
11451 /* Add the left successor's input set to in */
11452 if (rb->block->left) {
11453 change |= reg_in(state, blocks, rb, rb->block->left);
11455 /* Add the right successor's input set to in */
11456 if ((rb->block->right) &&
11457 (rb->block->right != rb->block->left)) {
11458 change |= reg_in(state, blocks, rb, rb->block->right);
11460 /* Add use to in... */
11461 change |= use_in(state, rb);
11467 static void free_variable_lifetimes(
11468 struct compile_state *state, struct reg_block *blocks)
11471 /* free in_set && out_set on each block */
11472 for(i = 1; i <= state->last_vertex; i++) {
11473 struct triple_reg_set *entry, *next;
11474 struct reg_block *rb;
11476 for(entry = rb->in; entry ; entry = next) {
11477 next = entry->next;
11478 do_triple_unset(&rb->in, entry->member);
11480 for(entry = rb->out; entry; entry = next) {
11481 next = entry->next;
11482 do_triple_unset(&rb->out, entry->member);
11489 typedef void (*wvl_cb_t)(
11490 struct compile_state *state,
11491 struct reg_block *blocks, struct triple_reg_set *live,
11492 struct reg_block *rb, struct triple *ins, void *arg);
11494 static void walk_variable_lifetimes(struct compile_state *state,
11495 struct reg_block *blocks, wvl_cb_t cb, void *arg)
11499 for(i = 1; i <= state->last_vertex; i++) {
11500 struct triple_reg_set *live;
11501 struct triple_reg_set *entry, *next;
11502 struct triple *ptr, *prev;
11503 struct reg_block *rb;
11504 struct block *block;
11507 /* Get the blocks */
11511 /* Copy out into live */
11513 for(entry = rb->out; entry; entry = next) {
11514 next = entry->next;
11515 do_triple_set(&live, entry->member, entry->new);
11517 /* Walk through the basic block calculating live */
11518 for(done = 0, ptr = block->last; !done; ptr = prev) {
11519 struct triple **expr;
11522 done = (ptr == block->first);
11524 /* Ensure the current definition is in live */
11525 if (triple_is_def(state, ptr)) {
11526 do_triple_set(&live, ptr, 0);
11529 /* Inform the callback function of what is
11532 cb(state, blocks, live, rb, ptr, arg);
11534 /* Remove the current definition from live */
11535 do_triple_unset(&live, ptr);
11537 /* Add the current uses to live.
11539 * It is safe to skip phi functions because they do
11540 * not have any block local uses, and the block
11541 * output sets already properly account for what
11542 * control flow depedent uses phi functions do have.
11544 if (ptr->op == OP_PHI) {
11547 expr = triple_rhs(state, ptr, 0);
11548 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11549 /* If the triple is not a definition skip it. */
11550 if (!*expr || !triple_is_def(state, *expr)) {
11553 do_triple_set(&live, *expr, 0);
11557 for(entry = live; entry; entry = next) {
11558 next = entry->next;
11559 do_triple_unset(&live, entry->member);
11564 static int count_triples(struct compile_state *state)
11566 struct triple *first, *ins;
11568 first = RHS(state->main_function, 0);
11573 } while (ins != first);
11576 struct dead_triple {
11577 struct triple *triple;
11578 struct dead_triple *work_next;
11579 struct block *block;
11582 #define TRIPLE_FLAG_ALIVE 1
11586 static void awaken(
11587 struct compile_state *state,
11588 struct dead_triple *dtriple, struct triple **expr,
11589 struct dead_triple ***work_list_tail)
11591 struct triple *triple;
11592 struct dead_triple *dt;
11600 if (triple->id <= 0) {
11601 internal_error(state, triple, "bad triple id: %d",
11604 if (triple->op == OP_NOOP) {
11605 internal_warning(state, triple, "awakening noop?");
11608 dt = &dtriple[triple->id];
11609 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11610 dt->flags |= TRIPLE_FLAG_ALIVE;
11611 if (!dt->work_next) {
11612 **work_list_tail = dt;
11613 *work_list_tail = &dt->work_next;
11618 static void eliminate_inefectual_code(struct compile_state *state)
11620 struct block *block;
11621 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11623 struct triple *first, *ins;
11625 /* Setup the work list */
11627 work_list_tail = &work_list;
11629 first = RHS(state->main_function, 0);
11631 /* Count how many triples I have */
11632 triples = count_triples(state);
11634 /* Now put then in an array and mark all of the triples dead */
11635 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11641 if (ins->op == OP_LABEL) {
11642 block = ins->u.block;
11644 dtriple[i].triple = ins;
11645 dtriple[i].block = block;
11646 dtriple[i].flags = 0;
11647 dtriple[i].color = ins->id;
11649 /* See if it is an operation we always keep */
11650 #warning "FIXME handle the case of killing a branch instruction"
11651 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11652 awaken(state, dtriple, &ins, &work_list_tail);
11655 /* Unconditionally keep the very last instruction */
11656 else if (ins->next == first) {
11657 awaken(state, dtriple, &ins, &work_list_tail);
11662 } while(ins != first);
11664 struct dead_triple *dt;
11665 struct block_set *user;
11666 struct triple **expr;
11668 work_list = dt->work_next;
11670 work_list_tail = &work_list;
11672 /* Wake up the data depencencies of this triple */
11675 expr = triple_rhs(state, dt->triple, expr);
11676 awaken(state, dtriple, expr, &work_list_tail);
11679 expr = triple_lhs(state, dt->triple, expr);
11680 awaken(state, dtriple, expr, &work_list_tail);
11683 expr = triple_misc(state, dt->triple, expr);
11684 awaken(state, dtriple, expr, &work_list_tail);
11686 /* Wake up the forward control dependencies */
11688 expr = triple_targ(state, dt->triple, expr);
11689 awaken(state, dtriple, expr, &work_list_tail);
11691 /* Wake up the reverse control dependencies of this triple */
11692 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11693 awaken(state, dtriple, &user->member->last, &work_list_tail);
11696 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11697 if ((dt->triple->op == OP_NOOP) &&
11698 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11699 internal_error(state, dt->triple, "noop effective?");
11701 dt->triple->id = dt->color; /* Restore the color */
11702 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11703 #warning "FIXME handle the case of killing a basic block"
11704 if (dt->block->first == dt->triple) {
11707 if (dt->block->last == dt->triple) {
11708 dt->block->last = dt->triple->prev;
11710 release_triple(state, dt->triple);
11717 static void insert_mandatory_copies(struct compile_state *state)
11719 struct triple *ins, *first;
11721 /* The object is with a minimum of inserted copies,
11722 * to resolve in fundamental register conflicts between
11723 * register value producers and consumers.
11724 * Theoretically we may be greater than minimal when we
11725 * are inserting copies before instructions but that
11726 * case should be rare.
11728 first = RHS(state->main_function, 0);
11731 struct triple_set *entry, *next;
11732 struct triple *tmp;
11733 struct reg_info info;
11734 unsigned reg, regcm;
11735 int do_post_copy, do_pre_copy;
11737 if (!triple_is_def(state, ins)) {
11740 /* Find the architecture specific color information */
11741 info = arch_reg_lhs(state, ins, 0);
11742 if (info.reg >= MAX_REGISTERS) {
11743 info.reg = REG_UNSET;
11747 regcm = arch_type_to_regcm(state, ins->type);
11748 do_post_copy = do_pre_copy = 0;
11750 /* Walk through the uses of ins and check for conflicts */
11751 for(entry = ins->use; entry; entry = next) {
11752 struct reg_info rinfo;
11754 next = entry->next;
11755 i = find_rhs_use(state, entry->member, ins);
11760 /* Find the users color requirements */
11761 rinfo = arch_reg_rhs(state, entry->member, i);
11762 if (rinfo.reg >= MAX_REGISTERS) {
11763 rinfo.reg = REG_UNSET;
11766 /* See if I need a pre_copy */
11767 if (rinfo.reg != REG_UNSET) {
11768 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11773 regcm &= rinfo.regcm;
11774 regcm = arch_regcm_normalize(state, regcm);
11778 /* Always use pre_copies for constants.
11779 * They do not take up any registers until a
11780 * copy places them in one.
11782 if ((info.reg == REG_UNNEEDED) &&
11783 (rinfo.reg != REG_UNNEEDED)) {
11789 (((info.reg != REG_UNSET) &&
11790 (reg != REG_UNSET) &&
11791 (info.reg != reg)) ||
11792 ((info.regcm & regcm) == 0));
11795 regcm = info.regcm;
11796 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
11797 for(entry = ins->use; entry; entry = next) {
11798 struct reg_info rinfo;
11800 next = entry->next;
11801 i = find_rhs_use(state, entry->member, ins);
11806 /* Find the users color requirements */
11807 rinfo = arch_reg_rhs(state, entry->member, i);
11808 if (rinfo.reg >= MAX_REGISTERS) {
11809 rinfo.reg = REG_UNSET;
11812 /* Now see if it is time to do the pre_copy */
11813 if (rinfo.reg != REG_UNSET) {
11814 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11815 ((regcm & rinfo.regcm) == 0) ||
11816 /* Don't let a mandatory coalesce sneak
11817 * into a operation that is marked to prevent
11820 ((reg != REG_UNNEEDED) &&
11821 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11822 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11825 struct triple *user;
11826 user = entry->member;
11827 if (RHS(user, i) != ins) {
11828 internal_error(state, user, "bad rhs");
11830 tmp = pre_copy(state, user, i);
11831 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11839 if ((regcm & rinfo.regcm) == 0) {
11841 struct triple *user;
11842 user = entry->member;
11843 if (RHS(user, i) != ins) {
11844 internal_error(state, user, "bad rhs");
11846 tmp = pre_copy(state, user, i);
11847 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11853 regcm &= rinfo.regcm;
11856 if (do_post_copy) {
11857 struct reg_info pre, post;
11858 tmp = post_copy(state, ins);
11859 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11860 pre = arch_reg_lhs(state, ins, 0);
11861 post = arch_reg_lhs(state, tmp, 0);
11862 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11863 internal_error(state, tmp, "useless copy");
11868 } while(ins != first);
11872 struct live_range_edge;
11873 struct live_range_def;
11874 struct live_range {
11875 struct live_range_edge *edges;
11876 struct live_range_def *defs;
11877 /* Note. The list pointed to by defs is kept in order.
11878 * That is baring splits in the flow control
11879 * defs dominates defs->next wich dominates defs->next->next
11886 struct live_range *group_next, **group_prev;
11889 struct live_range_edge {
11890 struct live_range_edge *next;
11891 struct live_range *node;
11894 struct live_range_def {
11895 struct live_range_def *next;
11896 struct live_range_def *prev;
11897 struct live_range *lr;
11898 struct triple *def;
11902 #define LRE_HASH_SIZE 2048
11904 struct lre_hash *next;
11905 struct live_range *left;
11906 struct live_range *right;
11911 struct lre_hash *hash[LRE_HASH_SIZE];
11912 struct reg_block *blocks;
11913 struct live_range_def *lrd;
11914 struct live_range *lr;
11915 struct live_range *low, **low_tail;
11916 struct live_range *high, **high_tail;
11919 int passes, max_passes;
11920 #define MAX_ALLOCATION_PASSES 100
11925 struct print_interference_block_info {
11926 struct reg_state *rstate;
11930 static void print_interference_block(
11931 struct compile_state *state, struct block *block, void *arg)
11934 struct print_interference_block_info *info = arg;
11935 struct reg_state *rstate = info->rstate;
11936 FILE *fp = info->fp;
11937 struct reg_block *rb;
11938 struct triple *ptr;
11941 rb = &rstate->blocks[block->vertex];
11943 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
11947 block->left && block->left->use?block->left->use->member : 0,
11949 block->right && block->right->use?block->right->use->member : 0);
11951 struct triple_reg_set *in_set;
11952 fprintf(fp, " in:");
11953 for(in_set = rb->in; in_set; in_set = in_set->next) {
11954 fprintf(fp, " %-10p", in_set->member);
11959 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11960 done = (ptr == block->last);
11961 if (ptr->op == OP_PHI) {
11968 for(edge = 0; edge < block->users; edge++) {
11969 fprintf(fp, " in(%d):", edge);
11970 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11971 struct triple **slot;
11972 done = (ptr == block->last);
11973 if (ptr->op != OP_PHI) {
11976 slot = &RHS(ptr, 0);
11977 fprintf(fp, " %-10p", slot[edge]);
11982 if (block->first->op == OP_LABEL) {
11983 fprintf(fp, "%p:\n", block->first);
11985 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11986 struct live_range *lr;
11990 done = (ptr == block->last);
11991 lr = rstate->lrd[ptr->id].lr;
11994 ptr->id = rstate->lrd[id].orig_id;
11995 SET_REG(ptr->id, lr->color);
11996 display_triple(fp, ptr);
11999 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
12000 internal_error(state, ptr, "lr has no defs!");
12002 if (info->need_edges) {
12004 struct live_range_def *lrd;
12005 fprintf(fp, " range:");
12008 fprintf(fp, " %-10p", lrd->def);
12010 } while(lrd != lr->defs);
12013 if (lr->edges > 0) {
12014 struct live_range_edge *edge;
12015 fprintf(fp, " edges:");
12016 for(edge = lr->edges; edge; edge = edge->next) {
12017 struct live_range_def *lrd;
12018 lrd = edge->node->defs;
12020 fprintf(fp, " %-10p", lrd->def);
12022 } while(lrd != edge->node->defs);
12028 /* Do a bunch of sanity checks */
12029 valid_ins(state, ptr);
12030 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
12031 internal_error(state, ptr, "Invalid triple id: %d",
12036 struct triple_reg_set *out_set;
12037 fprintf(fp, " out:");
12038 for(out_set = rb->out; out_set; out_set = out_set->next) {
12039 fprintf(fp, " %-10p", out_set->member);
12046 static void print_interference_blocks(
12047 struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
12049 struct print_interference_block_info info;
12050 info.rstate = rstate;
12052 info.need_edges = need_edges;
12053 fprintf(fp, "\nlive variables by block\n");
12054 walk_blocks(state, print_interference_block, &info);
12058 static unsigned regc_max_size(struct compile_state *state, int classes)
12063 for(i = 0; i < MAX_REGC; i++) {
12064 if (classes & (1 << i)) {
12066 size = arch_regc_size(state, i);
12067 if (size > max_size) {
12075 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
12077 unsigned equivs[MAX_REG_EQUIVS];
12079 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
12080 internal_error(state, 0, "invalid register");
12082 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
12083 internal_error(state, 0, "invalid register");
12085 arch_reg_equivs(state, equivs, reg1);
12086 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12087 if (equivs[i] == reg2) {
12094 static void reg_fill_used(struct compile_state *state, char *used, int reg)
12096 unsigned equivs[MAX_REG_EQUIVS];
12098 if (reg == REG_UNNEEDED) {
12101 arch_reg_equivs(state, equivs, reg);
12102 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12103 used[equivs[i]] = 1;
12108 static void reg_inc_used(struct compile_state *state, char *used, int reg)
12110 unsigned equivs[MAX_REG_EQUIVS];
12112 if (reg == REG_UNNEEDED) {
12115 arch_reg_equivs(state, equivs, reg);
12116 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12117 used[equivs[i]] += 1;
12122 static unsigned int hash_live_edge(
12123 struct live_range *left, struct live_range *right)
12125 unsigned int hash, val;
12126 unsigned long lval, rval;
12127 lval = ((unsigned long)left)/sizeof(struct live_range);
12128 rval = ((unsigned long)right)/sizeof(struct live_range);
12133 hash = (hash *263) + val;
12138 hash = (hash *263) + val;
12140 hash = hash & (LRE_HASH_SIZE - 1);
12144 static struct lre_hash **lre_probe(struct reg_state *rstate,
12145 struct live_range *left, struct live_range *right)
12147 struct lre_hash **ptr;
12148 unsigned int index;
12149 /* Ensure left <= right */
12150 if (left > right) {
12151 struct live_range *tmp;
12156 index = hash_live_edge(left, right);
12158 ptr = &rstate->hash[index];
12160 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
12163 ptr = &(*ptr)->next;
12168 static int interfere(struct reg_state *rstate,
12169 struct live_range *left, struct live_range *right)
12171 struct lre_hash **ptr;
12172 ptr = lre_probe(rstate, left, right);
12173 return ptr && *ptr;
12176 static void add_live_edge(struct reg_state *rstate,
12177 struct live_range *left, struct live_range *right)
12179 /* FIXME the memory allocation overhead is noticeable here... */
12180 struct lre_hash **ptr, *new_hash;
12181 struct live_range_edge *edge;
12183 if (left == right) {
12186 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
12189 /* Ensure left <= right */
12190 if (left > right) {
12191 struct live_range *tmp;
12196 ptr = lre_probe(rstate, left, right);
12201 fprintf(stderr, "new_live_edge(%p, %p)\n",
12204 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
12205 new_hash->next = *ptr;
12206 new_hash->left = left;
12207 new_hash->right = right;
12210 edge = xmalloc(sizeof(*edge), "live_range_edge");
12211 edge->next = left->edges;
12212 edge->node = right;
12213 left->edges = edge;
12216 edge = xmalloc(sizeof(*edge), "live_range_edge");
12217 edge->next = right->edges;
12219 right->edges = edge;
12220 right->degree += 1;
12223 static void remove_live_edge(struct reg_state *rstate,
12224 struct live_range *left, struct live_range *right)
12226 struct live_range_edge *edge, **ptr;
12227 struct lre_hash **hptr, *entry;
12228 hptr = lre_probe(rstate, left, right);
12229 if (!hptr || !*hptr) {
12233 *hptr = entry->next;
12236 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
12238 if (edge->node == right) {
12240 memset(edge, 0, sizeof(*edge));
12246 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
12248 if (edge->node == left) {
12250 memset(edge, 0, sizeof(*edge));
12258 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
12260 struct live_range_edge *edge, *next;
12261 for(edge = range->edges; edge; edge = next) {
12263 remove_live_edge(rstate, range, edge->node);
12267 static void transfer_live_edges(struct reg_state *rstate,
12268 struct live_range *dest, struct live_range *src)
12270 struct live_range_edge *edge, *next;
12271 for(edge = src->edges; edge; edge = next) {
12272 struct live_range *other;
12274 other = edge->node;
12275 remove_live_edge(rstate, src, other);
12276 add_live_edge(rstate, dest, other);
12281 /* Interference graph...
12283 * new(n) --- Return a graph with n nodes but no edges.
12284 * add(g,x,y) --- Return a graph including g with an between x and y
12285 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
12286 * x and y in the graph g
12287 * degree(g, x) --- Return the degree of the node x in the graph g
12288 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
12290 * Implement with a hash table && a set of adjcency vectors.
12291 * The hash table supports constant time implementations of add and interfere.
12292 * The adjacency vectors support an efficient implementation of neighbors.
12296 * +---------------------------------------------------+
12297 * | +--------------+ |
12299 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
12301 * -- In simplify implment optimistic coloring... (No backtracking)
12302 * -- Implement Rematerialization it is the only form of spilling we can perform
12303 * Essentially this means dropping a constant from a register because
12304 * we can regenerate it later.
12306 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
12307 * coalesce at phi points...
12308 * --- Bias coloring if at all possible do the coalesing a compile time.
12313 static void different_colored(
12314 struct compile_state *state, struct reg_state *rstate,
12315 struct triple *parent, struct triple *ins)
12317 struct live_range *lr;
12318 struct triple **expr;
12319 lr = rstate->lrd[ins->id].lr;
12320 expr = triple_rhs(state, ins, 0);
12321 for(;expr; expr = triple_rhs(state, ins, expr)) {
12322 struct live_range *lr2;
12323 if (!*expr || (*expr == parent) || (*expr == ins)) {
12326 lr2 = rstate->lrd[(*expr)->id].lr;
12327 if (lr->color == lr2->color) {
12328 internal_error(state, ins, "live range too big");
12334 static struct live_range *coalesce_ranges(
12335 struct compile_state *state, struct reg_state *rstate,
12336 struct live_range *lr1, struct live_range *lr2)
12338 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
12344 if (!lr1->defs || !lr2->defs) {
12345 internal_error(state, 0,
12346 "cannot coalese dead live ranges");
12348 if ((lr1->color == REG_UNNEEDED) ||
12349 (lr2->color == REG_UNNEEDED)) {
12350 internal_error(state, 0,
12351 "cannot coalesce live ranges without a possible color");
12353 if ((lr1->color != lr2->color) &&
12354 (lr1->color != REG_UNSET) &&
12355 (lr2->color != REG_UNSET)) {
12356 internal_error(state, lr1->defs->def,
12357 "cannot coalesce live ranges of different colors");
12359 color = lr1->color;
12360 if (color == REG_UNSET) {
12361 color = lr2->color;
12363 classes = lr1->classes & lr2->classes;
12365 internal_error(state, lr1->defs->def,
12366 "cannot coalesce live ranges with dissimilar register classes");
12368 #if DEBUG_COALESCING
12369 fprintf(stderr, "coalescing:");
12372 fprintf(stderr, " %p", lrd->def);
12374 } while(lrd != lr1->defs);
12375 fprintf(stderr, " |");
12378 fprintf(stderr, " %p", lrd->def);
12380 } while(lrd != lr2->defs);
12381 fprintf(stderr, "\n");
12383 /* If there is a clear dominate live range put it in lr1,
12384 * For purposes of this test phi functions are
12385 * considered dominated by the definitions that feed into
12388 if ((lr1->defs->prev->def->op == OP_PHI) ||
12389 ((lr2->defs->prev->def->op != OP_PHI) &&
12390 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12391 struct live_range *tmp;
12397 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12398 fprintf(stderr, "lr1 post\n");
12400 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12401 fprintf(stderr, "lr1 pre\n");
12403 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12404 fprintf(stderr, "lr2 post\n");
12406 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12407 fprintf(stderr, "lr2 pre\n");
12411 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12418 /* Append lr2 onto lr1 */
12419 #warning "FIXME should this be a merge instead of a splice?"
12420 /* This FIXME item applies to the correctness of live_range_end
12421 * and to the necessity of making multiple passes of coalesce_live_ranges.
12422 * A failure to find some coalesce opportunities in coaleace_live_ranges
12423 * does not impact the correct of the compiler just the efficiency with
12424 * which registers are allocated.
12427 mid1 = lr1->defs->prev;
12429 end = lr2->defs->prev;
12437 /* Fixup the live range in the added live range defs */
12442 } while(lrd != head);
12444 /* Mark lr2 as free. */
12446 lr2->color = REG_UNNEEDED;
12450 internal_error(state, 0, "lr1->defs == 0 ?");
12453 lr1->color = color;
12454 lr1->classes = classes;
12456 /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12457 transfer_live_edges(rstate, lr1, lr2);
12462 static struct live_range_def *live_range_head(
12463 struct compile_state *state, struct live_range *lr,
12464 struct live_range_def *last)
12466 struct live_range_def *result;
12471 else if (!tdominates(state, lr->defs->def, last->next->def)) {
12472 result = last->next;
12477 static struct live_range_def *live_range_end(
12478 struct compile_state *state, struct live_range *lr,
12479 struct live_range_def *last)
12481 struct live_range_def *result;
12484 result = lr->defs->prev;
12486 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12487 result = last->prev;
12493 static void initialize_live_ranges(
12494 struct compile_state *state, struct reg_state *rstate)
12496 struct triple *ins, *first;
12497 size_t count, size;
12500 first = RHS(state->main_function, 0);
12501 /* First count how many instructions I have.
12503 count = count_triples(state);
12504 /* Potentially I need one live range definitions for each
12507 rstate->defs = count;
12508 /* Potentially I need one live range for each instruction
12509 * plus an extra for the dummy live range.
12511 rstate->ranges = count + 1;
12512 size = sizeof(rstate->lrd[0]) * rstate->defs;
12513 rstate->lrd = xcmalloc(size, "live_range_def");
12514 size = sizeof(rstate->lr[0]) * rstate->ranges;
12515 rstate->lr = xcmalloc(size, "live_range");
12517 /* Setup the dummy live range */
12518 rstate->lr[0].classes = 0;
12519 rstate->lr[0].color = REG_UNSET;
12520 rstate->lr[0].defs = 0;
12524 /* If the triple is a variable give it a live range */
12525 if (triple_is_def(state, ins)) {
12526 struct reg_info info;
12527 /* Find the architecture specific color information */
12528 info = find_def_color(state, ins);
12530 rstate->lr[i].defs = &rstate->lrd[j];
12531 rstate->lr[i].color = info.reg;
12532 rstate->lr[i].classes = info.regcm;
12533 rstate->lr[i].degree = 0;
12534 rstate->lrd[j].lr = &rstate->lr[i];
12536 /* Otherwise give the triple the dummy live range. */
12538 rstate->lrd[j].lr = &rstate->lr[0];
12541 /* Initalize the live_range_def */
12542 rstate->lrd[j].next = &rstate->lrd[j];
12543 rstate->lrd[j].prev = &rstate->lrd[j];
12544 rstate->lrd[j].def = ins;
12545 rstate->lrd[j].orig_id = ins->id;
12550 } while(ins != first);
12551 rstate->ranges = i;
12553 /* Make a second pass to handle achitecture specific register
12558 int zlhs, zrhs, i, j;
12559 if (ins->id > rstate->defs) {
12560 internal_error(state, ins, "bad id");
12563 /* Walk through the template of ins and coalesce live ranges */
12564 zlhs = TRIPLE_LHS(ins->sizes);
12565 if ((zlhs == 0) && triple_is_def(state, ins)) {
12568 zrhs = TRIPLE_RHS(ins->sizes);
12570 #if DEBUG_COALESCING > 1
12571 fprintf(stderr, "mandatory coalesce: %p %d %d\n",
12574 for(i = 0; i < zlhs; i++) {
12575 struct reg_info linfo;
12576 struct live_range_def *lhs;
12577 linfo = arch_reg_lhs(state, ins, i);
12578 if (linfo.reg < MAX_REGISTERS) {
12581 if (triple_is_def(state, ins)) {
12582 lhs = &rstate->lrd[ins->id];
12584 lhs = &rstate->lrd[LHS(ins, i)->id];
12586 #if DEBUG_COALESCING > 1
12587 fprintf(stderr, "coalesce lhs(%d): %p %d\n",
12588 i, lhs, linfo.reg);
12591 for(j = 0; j < zrhs; j++) {
12592 struct reg_info rinfo;
12593 struct live_range_def *rhs;
12594 rinfo = arch_reg_rhs(state, ins, j);
12595 if (rinfo.reg < MAX_REGISTERS) {
12598 rhs = &rstate->lrd[RHS(ins, j)->id];
12599 #if DEBUG_COALESCING > 1
12600 fprintf(stderr, "coalesce rhs(%d): %p %d\n",
12601 j, rhs, rinfo.reg);
12604 if (rinfo.reg == linfo.reg) {
12605 coalesce_ranges(state, rstate,
12611 } while(ins != first);
12614 static void graph_ins(
12615 struct compile_state *state,
12616 struct reg_block *blocks, struct triple_reg_set *live,
12617 struct reg_block *rb, struct triple *ins, void *arg)
12619 struct reg_state *rstate = arg;
12620 struct live_range *def;
12621 struct triple_reg_set *entry;
12623 /* If the triple is not a definition
12624 * we do not have a definition to add to
12625 * the interference graph.
12627 if (!triple_is_def(state, ins)) {
12630 def = rstate->lrd[ins->id].lr;
12632 /* Create an edge between ins and everything that is
12633 * alive, unless the live_range cannot share
12634 * a physical register with ins.
12636 for(entry = live; entry; entry = entry->next) {
12637 struct live_range *lr;
12638 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12639 internal_error(state, 0, "bad entry?");
12641 lr = rstate->lrd[entry->member->id].lr;
12645 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12648 add_live_edge(rstate, def, lr);
12653 static struct live_range *get_verify_live_range(
12654 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12656 struct live_range *lr;
12657 struct live_range_def *lrd;
12659 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12660 internal_error(state, ins, "bad ins?");
12662 lr = rstate->lrd[ins->id].lr;
12666 if (lrd->def == ins) {
12670 } while(lrd != lr->defs);
12672 internal_error(state, ins, "ins not in live range");
12677 static void verify_graph_ins(
12678 struct compile_state *state,
12679 struct reg_block *blocks, struct triple_reg_set *live,
12680 struct reg_block *rb, struct triple *ins, void *arg)
12682 struct reg_state *rstate = arg;
12683 struct triple_reg_set *entry1, *entry2;
12686 /* Compare live against edges and make certain the code is working */
12687 for(entry1 = live; entry1; entry1 = entry1->next) {
12688 struct live_range *lr1;
12689 lr1 = get_verify_live_range(state, rstate, entry1->member);
12690 for(entry2 = live; entry2; entry2 = entry2->next) {
12691 struct live_range *lr2;
12692 struct live_range_edge *edge2;
12695 if (entry2 == entry1) {
12698 lr2 = get_verify_live_range(state, rstate, entry2->member);
12700 internal_error(state, entry2->member,
12701 "live range with 2 values simultaneously alive");
12703 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12706 if (!interfere(rstate, lr1, lr2)) {
12707 internal_error(state, entry2->member,
12708 "edges don't interfere?");
12713 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12715 if (edge2->node == lr1) {
12719 if (lr2_degree != lr2->degree) {
12720 internal_error(state, entry2->member,
12721 "computed degree: %d does not match reported degree: %d\n",
12722 lr2_degree, lr2->degree);
12725 internal_error(state, entry2->member, "missing edge");
12733 static void print_interference_ins(
12734 struct compile_state *state,
12735 struct reg_block *blocks, struct triple_reg_set *live,
12736 struct reg_block *rb, struct triple *ins, void *arg)
12738 struct reg_state *rstate = arg;
12739 struct live_range *lr;
12742 lr = rstate->lrd[ins->id].lr;
12744 ins->id = rstate->lrd[id].orig_id;
12745 SET_REG(ins->id, lr->color);
12746 display_triple(stdout, ins);
12750 struct live_range_def *lrd;
12754 printf(" %-10p", lrd->def);
12756 } while(lrd != lr->defs);
12760 struct triple_reg_set *entry;
12762 for(entry = live; entry; entry = entry->next) {
12763 printf(" %-10p", entry->member);
12768 struct live_range_edge *entry;
12770 for(entry = lr->edges; entry; entry = entry->next) {
12771 struct live_range_def *lrd;
12772 lrd = entry->node->defs;
12774 printf(" %-10p", lrd->def);
12776 } while(lrd != entry->node->defs);
12781 if (triple_is_branch(state, ins)) {
12787 static int coalesce_live_ranges(
12788 struct compile_state *state, struct reg_state *rstate)
12790 /* At the point where a value is moved from one
12791 * register to another that value requires two
12792 * registers, thus increasing register pressure.
12793 * Live range coaleescing reduces the register
12794 * pressure by keeping a value in one register
12797 * In the case of a phi function all paths leading
12798 * into it must be allocated to the same register
12799 * otherwise the phi function may not be removed.
12801 * Forcing a value to stay in a single register
12802 * for an extended period of time does have
12803 * limitations when applied to non homogenous
12806 * The two cases I have identified are:
12807 * 1) Two forced register assignments may
12809 * 2) Registers may go unused because they
12810 * are only good for storing the value
12811 * and not manipulating it.
12813 * Because of this I need to split live ranges,
12814 * even outside of the context of coalesced live
12815 * ranges. The need to split live ranges does
12816 * impose some constraints on live range coalescing.
12818 * - Live ranges may not be coalesced across phi
12819 * functions. This creates a 2 headed live
12820 * range that cannot be sanely split.
12822 * - phi functions (coalesced in initialize_live_ranges)
12823 * are handled as pre split live ranges so we will
12824 * never attempt to split them.
12830 for(i = 0; i <= rstate->ranges; i++) {
12831 struct live_range *lr1;
12832 struct live_range_def *lrd1;
12833 lr1 = &rstate->lr[i];
12837 lrd1 = live_range_end(state, lr1, 0);
12838 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12839 struct triple_set *set;
12840 if (lrd1->def->op != OP_COPY) {
12843 /* Skip copies that are the result of a live range split. */
12844 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12847 for(set = lrd1->def->use; set; set = set->next) {
12848 struct live_range_def *lrd2;
12849 struct live_range *lr2, *res;
12851 lrd2 = &rstate->lrd[set->member->id];
12853 /* Don't coalesce with instructions
12854 * that are the result of a live range
12857 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12860 lr2 = rstate->lrd[set->member->id].lr;
12864 if ((lr1->color != lr2->color) &&
12865 (lr1->color != REG_UNSET) &&
12866 (lr2->color != REG_UNSET)) {
12869 if ((lr1->classes & lr2->classes) == 0) {
12873 if (interfere(rstate, lr1, lr2)) {
12877 res = coalesce_ranges(state, rstate, lr1, lr2);
12891 static void fix_coalesce_conflicts(struct compile_state *state,
12892 struct reg_block *blocks, struct triple_reg_set *live,
12893 struct reg_block *rb, struct triple *ins, void *arg)
12895 int *conflicts = arg;
12896 int zlhs, zrhs, i, j;
12898 /* See if we have a mandatory coalesce operation between
12899 * a lhs and a rhs value. If so and the rhs value is also
12900 * alive then this triple needs to be pre copied. Otherwise
12901 * we would have two definitions in the same live range simultaneously
12904 zlhs = TRIPLE_LHS(ins->sizes);
12905 if ((zlhs == 0) && triple_is_def(state, ins)) {
12908 zrhs = TRIPLE_RHS(ins->sizes);
12909 for(i = 0; i < zlhs; i++) {
12910 struct reg_info linfo;
12911 linfo = arch_reg_lhs(state, ins, i);
12912 if (linfo.reg < MAX_REGISTERS) {
12915 for(j = 0; j < zrhs; j++) {
12916 struct reg_info rinfo;
12917 struct triple *rhs;
12918 struct triple_reg_set *set;
12921 rinfo = arch_reg_rhs(state, ins, j);
12922 if (rinfo.reg != linfo.reg) {
12926 for(set = live; set && !found; set = set->next) {
12927 if (set->member == rhs) {
12932 struct triple *copy;
12933 copy = pre_copy(state, ins, j);
12934 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12942 static int correct_coalesce_conflicts(
12943 struct compile_state *state, struct reg_block *blocks)
12947 walk_variable_lifetimes(state, blocks, fix_coalesce_conflicts, &conflicts);
12951 static void replace_set_use(struct compile_state *state,
12952 struct triple_reg_set *head, struct triple *orig, struct triple *new)
12954 struct triple_reg_set *set;
12955 for(set = head; set; set = set->next) {
12956 if (set->member == orig) {
12962 static void replace_block_use(struct compile_state *state,
12963 struct reg_block *blocks, struct triple *orig, struct triple *new)
12966 #warning "WISHLIST visit just those blocks that need it *"
12967 for(i = 1; i <= state->last_vertex; i++) {
12968 struct reg_block *rb;
12970 replace_set_use(state, rb->in, orig, new);
12971 replace_set_use(state, rb->out, orig, new);
12975 static void color_instructions(struct compile_state *state)
12977 struct triple *ins, *first;
12978 first = RHS(state->main_function, 0);
12981 if (triple_is_def(state, ins)) {
12982 struct reg_info info;
12983 info = find_lhs_color(state, ins, 0);
12984 if (info.reg >= MAX_REGISTERS) {
12985 info.reg = REG_UNSET;
12987 SET_INFO(ins->id, info);
12990 } while(ins != first);
12993 static struct reg_info read_lhs_color(
12994 struct compile_state *state, struct triple *ins, int index)
12996 struct reg_info info;
12997 if ((index == 0) && triple_is_def(state, ins)) {
12998 info.reg = ID_REG(ins->id);
12999 info.regcm = ID_REGCM(ins->id);
13001 else if (index < TRIPLE_LHS(ins->sizes)) {
13002 info = read_lhs_color(state, LHS(ins, index), 0);
13005 internal_error(state, ins, "Bad lhs %d", index);
13006 info.reg = REG_UNSET;
13012 static struct triple *resolve_tangle(
13013 struct compile_state *state, struct triple *tangle)
13015 struct reg_info info, uinfo;
13016 struct triple_set *set, *next;
13017 struct triple *copy;
13019 #warning "WISHLIST recalculate all affected instructions colors"
13020 info = find_lhs_color(state, tangle, 0);
13021 for(set = tangle->use; set; set = next) {
13022 struct triple *user;
13025 user = set->member;
13026 zrhs = TRIPLE_RHS(user->sizes);
13027 for(i = 0; i < zrhs; i++) {
13028 if (RHS(user, i) != tangle) {
13031 uinfo = find_rhs_post_color(state, user, i);
13032 if (uinfo.reg == info.reg) {
13033 copy = pre_copy(state, user, i);
13034 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13035 SET_INFO(copy->id, uinfo);
13040 uinfo = find_lhs_pre_color(state, tangle, 0);
13041 if (uinfo.reg == info.reg) {
13042 struct reg_info linfo;
13043 copy = post_copy(state, tangle);
13044 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13045 linfo = find_lhs_color(state, copy, 0);
13046 SET_INFO(copy->id, linfo);
13048 info = find_lhs_color(state, tangle, 0);
13049 SET_INFO(tangle->id, info);
13055 static void fix_tangles(struct compile_state *state,
13056 struct reg_block *blocks, struct triple_reg_set *live,
13057 struct reg_block *rb, struct triple *ins, void *arg)
13059 int *tangles = arg;
13060 struct triple *tangle;
13062 char used[MAX_REGISTERS];
13063 struct triple_reg_set *set;
13066 /* Find out which registers have multiple uses at this point */
13067 memset(used, 0, sizeof(used));
13068 for(set = live; set; set = set->next) {
13069 struct reg_info info;
13070 info = read_lhs_color(state, set->member, 0);
13071 if (info.reg == REG_UNSET) {
13074 reg_inc_used(state, used, info.reg);
13077 /* Now find the least dominated definition of a register in
13078 * conflict I have seen so far.
13080 for(set = live; set; set = set->next) {
13081 struct reg_info info;
13082 info = read_lhs_color(state, set->member, 0);
13083 if (used[info.reg] < 2) {
13086 /* Changing copies that feed into phi functions
13089 if (set->member->use &&
13090 (set->member->use->member->op == OP_PHI)) {
13093 if (!tangle || tdominates(state, set->member, tangle)) {
13094 tangle = set->member;
13097 /* If I have found a tangle resolve it */
13099 struct triple *post_copy;
13101 post_copy = resolve_tangle(state, tangle);
13103 replace_block_use(state, blocks, tangle, post_copy);
13105 if (post_copy && (tangle != ins)) {
13106 replace_set_use(state, live, tangle, post_copy);
13113 static int correct_tangles(
13114 struct compile_state *state, struct reg_block *blocks)
13118 color_instructions(state);
13119 walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
13124 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
13125 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
13127 struct triple *find_constrained_def(
13128 struct compile_state *state, struct live_range *range, struct triple *constrained)
13130 struct live_range_def *lrd;
13133 struct reg_info info;
13135 int is_constrained;
13136 regcm = arch_type_to_regcm(state, lrd->def->type);
13137 info = find_lhs_color(state, lrd->def, 0);
13138 regcm = arch_regcm_reg_normalize(state, regcm);
13139 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
13140 /* If the 2 register class masks are not equal the
13141 * the current register class is constrained.
13143 is_constrained = regcm != info.regcm;
13145 /* Of the constrained live ranges deal with the
13146 * least dominated one first.
13148 if (is_constrained) {
13149 #if DEBUG_RANGE_CONFLICTS
13150 fprintf(stderr, "canidate: %p %-8s regcm: %x %x\n",
13151 lrd->def, tops(lrd->def->op), regcm, info.regcm);
13153 if (!constrained ||
13154 tdominates(state, lrd->def, constrained))
13156 constrained = lrd->def;
13160 } while(lrd != range->defs);
13161 return constrained;
13164 static int split_constrained_ranges(
13165 struct compile_state *state, struct reg_state *rstate,
13166 struct live_range *range)
13168 /* Walk through the edges in conflict and our current live
13169 * range, and find definitions that are more severly constrained
13170 * than they type of data they contain require.
13172 * Then pick one of those ranges and relax the constraints.
13174 struct live_range_edge *edge;
13175 struct triple *constrained;
13178 for(edge = range->edges; edge; edge = edge->next) {
13179 constrained = find_constrained_def(state, edge->node, constrained);
13181 if (!constrained) {
13182 constrained = find_constrained_def(state, range, constrained);
13184 #if DEBUG_RANGE_CONFLICTS
13185 fprintf(stderr, "constrained: %p %-8s\n",
13186 constrained, tops(constrained->op));
13189 ids_from_rstate(state, rstate);
13190 cleanup_rstate(state, rstate);
13191 resolve_tangle(state, constrained);
13193 return !!constrained;
13196 static int split_ranges(
13197 struct compile_state *state, struct reg_state *rstate,
13198 char *used, struct live_range *range)
13201 #if DEBUG_RANGE_CONFLICTS
13202 fprintf(stderr, "split_ranges %d %s %p\n",
13203 rstate->passes, tops(range->defs->def->op), range->defs->def);
13205 if ((range->color == REG_UNNEEDED) ||
13206 (rstate->passes >= rstate->max_passes)) {
13209 split = split_constrained_ranges(state, rstate, range);
13211 /* Ideally I would split the live range that will not be used
13212 * for the longest period of time in hopes that this will
13213 * (a) allow me to spill a register or
13214 * (b) allow me to place a value in another register.
13216 * So far I don't have a test case for this, the resolving
13217 * of mandatory constraints has solved all of my
13218 * know issues. So I have choosen not to write any
13219 * code until I cat get a better feel for cases where
13220 * it would be useful to have.
13223 #warning "WISHLIST implement live range splitting..."
13224 if ((DEBUG_RANGE_CONFLICTS > 1) &&
13225 (!split || (DEBUG_RANGE_CONFLICTS > 2))) {
13226 print_interference_blocks(state, rstate, stderr, 0);
13227 print_dominators(state, stderr);
13232 #if DEBUG_COLOR_GRAPH > 1
13233 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13234 #define cgdebug_flush() fflush(stdout)
13235 #define cgdebug_loc(STATE, TRIPLE) loc(stdout, STATE, TRIPLE)
13236 #elif DEBUG_COLOR_GRAPH == 1
13237 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13238 #define cgdebug_flush() fflush(stderr)
13239 #define cgdebug_loc(STATE, TRIPLE) loc(stderr, STATE, TRIPLE)
13241 #define cgdebug_printf(...)
13242 #define cgdebug_flush()
13243 #define cgdebug_loc(STATE, TRIPLE)
13247 static int select_free_color(struct compile_state *state,
13248 struct reg_state *rstate, struct live_range *range)
13250 struct triple_set *entry;
13251 struct live_range_def *lrd;
13252 struct live_range_def *phi;
13253 struct live_range_edge *edge;
13254 char used[MAX_REGISTERS];
13255 struct triple **expr;
13257 /* Instead of doing just the trivial color select here I try
13258 * a few extra things because a good color selection will help reduce
13262 /* Find the registers currently in use */
13263 memset(used, 0, sizeof(used));
13264 for(edge = range->edges; edge; edge = edge->next) {
13265 if (edge->node->color == REG_UNSET) {
13268 reg_fill_used(state, used, edge->node->color);
13270 #if DEBUG_COLOR_GRAPH > 1
13274 for(edge = range->edges; edge; edge = edge->next) {
13277 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
13278 tops(range->def->op), i,
13279 range->def->filename, range->def->line, range->def->col);
13280 for(i = 0; i < MAX_REGISTERS; i++) {
13282 cgdebug_printf("used: %s\n",
13289 /* If a color is already assigned see if it will work */
13290 if (range->color != REG_UNSET) {
13291 struct live_range_def *lrd;
13292 if (!used[range->color]) {
13295 for(edge = range->edges; edge; edge = edge->next) {
13296 if (edge->node->color != range->color) {
13299 warning(state, edge->node->defs->def, "edge: ");
13300 lrd = edge->node->defs;
13302 warning(state, lrd->def, " %p %s",
13303 lrd->def, tops(lrd->def->op));
13305 } while(lrd != edge->node->defs);
13308 warning(state, range->defs->def, "def: ");
13310 warning(state, lrd->def, " %p %s",
13311 lrd->def, tops(lrd->def->op));
13313 } while(lrd != range->defs);
13314 internal_error(state, range->defs->def,
13315 "live range with already used color %s",
13316 arch_reg_str(range->color));
13319 /* If I feed into an expression reuse it's color.
13320 * This should help remove copies in the case of 2 register instructions
13321 * and phi functions.
13324 lrd = live_range_end(state, range, 0);
13325 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13326 entry = lrd->def->use;
13327 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13328 struct live_range_def *insd;
13330 insd = &rstate->lrd[entry->member->id];
13331 if (insd->lr->defs == 0) {
13334 if (!phi && (insd->def->op == OP_PHI) &&
13335 !interfere(rstate, range, insd->lr)) {
13338 if (insd->lr->color == REG_UNSET) {
13341 regcm = insd->lr->classes;
13342 if (((regcm & range->classes) == 0) ||
13343 (used[insd->lr->color])) {
13346 if (interfere(rstate, range, insd->lr)) {
13349 range->color = insd->lr->color;
13352 /* If I feed into a phi function reuse it's color or the color
13353 * of something else that feeds into the phi function.
13356 if (phi->lr->color != REG_UNSET) {
13357 if (used[phi->lr->color]) {
13358 range->color = phi->lr->color;
13362 expr = triple_rhs(state, phi->def, 0);
13363 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13364 struct live_range *lr;
13369 lr = rstate->lrd[(*expr)->id].lr;
13370 if (lr->color == REG_UNSET) {
13373 regcm = lr->classes;
13374 if (((regcm & range->classes) == 0) ||
13375 (used[lr->color])) {
13378 if (interfere(rstate, range, lr)) {
13381 range->color = lr->color;
13385 /* If I don't interfere with a rhs node reuse it's color */
13386 lrd = live_range_head(state, range, 0);
13387 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13388 expr = triple_rhs(state, lrd->def, 0);
13389 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13390 struct live_range *lr;
13395 lr = rstate->lrd[(*expr)->id].lr;
13396 if (lr->color == REG_UNSET) {
13399 regcm = lr->classes;
13400 if (((regcm & range->classes) == 0) ||
13401 (used[lr->color])) {
13404 if (interfere(rstate, range, lr)) {
13407 range->color = lr->color;
13411 /* If I have not opportunitically picked a useful color
13412 * pick the first color that is free.
13414 if (range->color == REG_UNSET) {
13416 arch_select_free_register(state, used, range->classes);
13418 if (range->color == REG_UNSET) {
13419 struct live_range_def *lrd;
13421 if (split_ranges(state, rstate, used, range)) {
13424 for(edge = range->edges; edge; edge = edge->next) {
13425 warning(state, edge->node->defs->def, "edge reg %s",
13426 arch_reg_str(edge->node->color));
13427 lrd = edge->node->defs;
13429 warning(state, lrd->def, " %s %p",
13430 tops(lrd->def->op), lrd->def);
13432 } while(lrd != edge->node->defs);
13434 warning(state, range->defs->def, "range: ");
13437 warning(state, lrd->def, " %s %p",
13438 tops(lrd->def->op), lrd->def);
13440 } while(lrd != range->defs);
13442 warning(state, range->defs->def, "classes: %x",
13444 for(i = 0; i < MAX_REGISTERS; i++) {
13446 warning(state, range->defs->def, "used: %s",
13450 #if DEBUG_COLOR_GRAPH < 2
13451 error(state, range->defs->def, "too few registers");
13453 internal_error(state, range->defs->def, "too few registers");
13456 range->classes &= arch_reg_regcm(state, range->color);
13457 if ((range->color == REG_UNSET) || (range->classes == 0)) {
13458 internal_error(state, range->defs->def, "select_free_color did not?");
13463 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13466 struct live_range_edge *edge;
13467 struct live_range *range;
13469 cgdebug_printf("Lo: ");
13470 range = rstate->low;
13471 if (*range->group_prev != range) {
13472 internal_error(state, 0, "lo: *prev != range?");
13474 *range->group_prev = range->group_next;
13475 if (range->group_next) {
13476 range->group_next->group_prev = range->group_prev;
13478 if (&range->group_next == rstate->low_tail) {
13479 rstate->low_tail = range->group_prev;
13481 if (rstate->low == range) {
13482 internal_error(state, 0, "low: next != prev?");
13485 else if (rstate->high) {
13486 cgdebug_printf("Hi: ");
13487 range = rstate->high;
13488 if (*range->group_prev != range) {
13489 internal_error(state, 0, "hi: *prev != range?");
13491 *range->group_prev = range->group_next;
13492 if (range->group_next) {
13493 range->group_next->group_prev = range->group_prev;
13495 if (&range->group_next == rstate->high_tail) {
13496 rstate->high_tail = range->group_prev;
13498 if (rstate->high == range) {
13499 internal_error(state, 0, "high: next != prev?");
13505 cgdebug_printf(" %d\n", range - rstate->lr);
13506 range->group_prev = 0;
13507 for(edge = range->edges; edge; edge = edge->next) {
13508 struct live_range *node;
13510 /* Move nodes from the high to the low list */
13511 if (node->group_prev && (node->color == REG_UNSET) &&
13512 (node->degree == regc_max_size(state, node->classes))) {
13513 if (*node->group_prev != node) {
13514 internal_error(state, 0, "move: *prev != node?");
13516 *node->group_prev = node->group_next;
13517 if (node->group_next) {
13518 node->group_next->group_prev = node->group_prev;
13520 if (&node->group_next == rstate->high_tail) {
13521 rstate->high_tail = node->group_prev;
13523 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13524 node->group_prev = rstate->low_tail;
13525 node->group_next = 0;
13526 *rstate->low_tail = node;
13527 rstate->low_tail = &node->group_next;
13528 if (*node->group_prev != node) {
13529 internal_error(state, 0, "move2: *prev != node?");
13534 colored = color_graph(state, rstate);
13536 cgdebug_printf("Coloring %d @", range - rstate->lr);
13537 cgdebug_loc(state, range->defs->def);
13539 colored = select_free_color(state, rstate, range);
13540 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13545 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13547 struct live_range *lr;
13548 struct live_range_edge *edge;
13549 struct triple *ins, *first;
13550 char used[MAX_REGISTERS];
13551 first = RHS(state->main_function, 0);
13554 if (triple_is_def(state, ins)) {
13555 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13556 internal_error(state, ins,
13557 "triple without a live range def");
13559 lr = rstate->lrd[ins->id].lr;
13560 if (lr->color == REG_UNSET) {
13561 internal_error(state, ins,
13562 "triple without a color");
13564 /* Find the registers used by the edges */
13565 memset(used, 0, sizeof(used));
13566 for(edge = lr->edges; edge; edge = edge->next) {
13567 if (edge->node->color == REG_UNSET) {
13568 internal_error(state, 0,
13569 "live range without a color");
13571 reg_fill_used(state, used, edge->node->color);
13573 if (used[lr->color]) {
13574 internal_error(state, ins,
13575 "triple with already used color");
13579 } while(ins != first);
13582 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13584 struct live_range *lr;
13585 struct triple *first, *ins;
13586 first = RHS(state->main_function, 0);
13589 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13590 internal_error(state, ins,
13591 "triple without a live range");
13593 lr = rstate->lrd[ins->id].lr;
13594 SET_REG(ins->id, lr->color);
13596 } while (ins != first);
13599 static struct live_range *merge_sort_lr(
13600 struct live_range *first, struct live_range *last)
13602 struct live_range *mid, *join, **join_tail, *pick;
13604 size = (last - first) + 1;
13606 mid = first + size/2;
13607 first = merge_sort_lr(first, mid -1);
13608 mid = merge_sort_lr(mid, last);
13612 /* merge the two lists */
13613 while(first && mid) {
13614 if ((first->degree < mid->degree) ||
13615 ((first->degree == mid->degree) &&
13616 (first->length < mid->length))) {
13618 first = first->group_next;
13620 first->group_prev = 0;
13625 mid = mid->group_next;
13627 mid->group_prev = 0;
13630 pick->group_next = 0;
13631 pick->group_prev = join_tail;
13633 join_tail = &pick->group_next;
13635 /* Splice the remaining list */
13636 pick = (first)? first : mid;
13639 pick->group_prev = join_tail;
13643 if (!first->defs) {
13651 static void ids_from_rstate(struct compile_state *state,
13652 struct reg_state *rstate)
13654 struct triple *ins, *first;
13655 if (!rstate->defs) {
13658 /* Display the graph if desired */
13659 if (state->debug & DEBUG_INTERFERENCE) {
13660 print_blocks(state, stdout);
13661 print_control_flow(state);
13663 first = RHS(state->main_function, 0);
13667 struct live_range_def *lrd;
13668 lrd = &rstate->lrd[ins->id];
13669 ins->id = lrd->orig_id;
13672 } while(ins != first);
13675 static void cleanup_live_edges(struct reg_state *rstate)
13678 /* Free the edges on each node */
13679 for(i = 1; i <= rstate->ranges; i++) {
13680 remove_live_edges(rstate, &rstate->lr[i]);
13684 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13686 cleanup_live_edges(rstate);
13687 xfree(rstate->lrd);
13690 /* Free the variable lifetime information */
13691 if (rstate->blocks) {
13692 free_variable_lifetimes(state, rstate->blocks);
13695 rstate->ranges = 0;
13698 rstate->blocks = 0;
13701 static void verify_consistency(struct compile_state *state);
13702 static void allocate_registers(struct compile_state *state)
13704 struct reg_state rstate;
13707 /* Clear out the reg_state */
13708 memset(&rstate, 0, sizeof(rstate));
13709 rstate.max_passes = MAX_ALLOCATION_PASSES;
13712 struct live_range **point, **next;
13717 #if DEBUG_RANGE_CONFLICTS
13718 fprintf(stderr, "pass: %d\n", rstate.passes);
13722 ids_from_rstate(state, &rstate);
13724 /* Cleanup the temporary data structures */
13725 cleanup_rstate(state, &rstate);
13727 /* Compute the variable lifetimes */
13728 rstate.blocks = compute_variable_lifetimes(state);
13730 /* Fix invalid mandatory live range coalesce conflicts */
13731 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
13733 /* Fix two simultaneous uses of the same register.
13734 * In a few pathlogical cases a partial untangle moves
13735 * the tangle to a part of the graph we won't revisit.
13736 * So we keep looping until we have no more tangle fixes
13740 tangles = correct_tangles(state, rstate.blocks);
13743 if (state->debug & DEBUG_INSERTED_COPIES) {
13744 printf("After resolve_tangles\n");
13745 print_blocks(state, stdout);
13746 print_control_flow(state);
13748 verify_consistency(state);
13750 /* Allocate and initialize the live ranges */
13751 initialize_live_ranges(state, &rstate);
13753 /* Note current doing coalescing in a loop appears to
13754 * buys me nothing. The code is left this way in case
13755 * there is some value in it. Or if a future bugfix
13756 * yields some benefit.
13759 #if DEBUG_COALESCING
13760 fprintf(stderr, "coalescing\n");
13762 /* Remove any previous live edge calculations */
13763 cleanup_live_edges(&rstate);
13765 /* Compute the interference graph */
13766 walk_variable_lifetimes(
13767 state, rstate.blocks, graph_ins, &rstate);
13769 /* Display the interference graph if desired */
13770 if (state->debug & DEBUG_INTERFERENCE) {
13771 print_interference_blocks(state, &rstate, stdout, 1);
13772 printf("\nlive variables by instruction\n");
13773 walk_variable_lifetimes(
13774 state, rstate.blocks,
13775 print_interference_ins, &rstate);
13778 coalesced = coalesce_live_ranges(state, &rstate);
13780 #if DEBUG_COALESCING
13781 fprintf(stderr, "coalesced: %d\n", coalesced);
13783 } while(coalesced);
13785 #if DEBUG_CONSISTENCY > 1
13787 fprintf(stderr, "verify_graph_ins...\n");
13789 /* Verify the interference graph */
13790 walk_variable_lifetimes(
13791 state, rstate.blocks, verify_graph_ins, &rstate);
13793 fprintf(stderr, "verify_graph_ins done\n");
13797 /* Build the groups low and high. But with the nodes
13798 * first sorted by degree order.
13800 rstate.low_tail = &rstate.low;
13801 rstate.high_tail = &rstate.high;
13802 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13804 rstate.high->group_prev = &rstate.high;
13806 for(point = &rstate.high; *point; point = &(*point)->group_next)
13808 rstate.high_tail = point;
13809 /* Walk through the high list and move everything that needs
13812 for(point = &rstate.high; *point; point = next) {
13813 struct live_range *range;
13814 next = &(*point)->group_next;
13817 /* If it has a low degree or it already has a color
13818 * place the node in low.
13820 if ((range->degree < regc_max_size(state, range->classes)) ||
13821 (range->color != REG_UNSET)) {
13822 cgdebug_printf("Lo: %5d degree %5d%s\n",
13823 range - rstate.lr, range->degree,
13824 (range->color != REG_UNSET) ? " (colored)": "");
13825 *range->group_prev = range->group_next;
13826 if (range->group_next) {
13827 range->group_next->group_prev = range->group_prev;
13829 if (&range->group_next == rstate.high_tail) {
13830 rstate.high_tail = range->group_prev;
13832 range->group_prev = rstate.low_tail;
13833 range->group_next = 0;
13834 *rstate.low_tail = range;
13835 rstate.low_tail = &range->group_next;
13839 cgdebug_printf("hi: %5d degree %5d%s\n",
13840 range - rstate.lr, range->degree,
13841 (range->color != REG_UNSET) ? " (colored)": "");
13844 /* Color the live_ranges */
13845 colored = color_graph(state, &rstate);
13847 } while (!colored);
13849 /* Verify the graph was properly colored */
13850 verify_colors(state, &rstate);
13852 /* Move the colors from the graph to the triples */
13853 color_triples(state, &rstate);
13855 /* Cleanup the temporary data structures */
13856 cleanup_rstate(state, &rstate);
13859 /* Sparce Conditional Constant Propogation
13860 * =========================================
13864 struct lattice_node {
13866 struct triple *def;
13867 struct ssa_edge *out;
13868 struct flow_block *fblock;
13869 struct triple *val;
13870 /* lattice high val && !is_const(val)
13871 * lattice const is_const(val)
13872 * lattice low val == 0
13876 struct lattice_node *src;
13877 struct lattice_node *dst;
13878 struct ssa_edge *work_next;
13879 struct ssa_edge *work_prev;
13880 struct ssa_edge *out_next;
13883 struct flow_block *src;
13884 struct flow_block *dst;
13885 struct flow_edge *work_next;
13886 struct flow_edge *work_prev;
13887 struct flow_edge *in_next;
13888 struct flow_edge *out_next;
13891 struct flow_block {
13892 struct block *block;
13893 struct flow_edge *in;
13894 struct flow_edge *out;
13895 struct flow_edge left, right;
13900 struct lattice_node *lattice;
13901 struct ssa_edge *ssa_edges;
13902 struct flow_block *flow_blocks;
13903 struct flow_edge *flow_work_list;
13904 struct ssa_edge *ssa_work_list;
13908 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13909 struct flow_edge *fedge)
13911 if (!scc->flow_work_list) {
13912 scc->flow_work_list = fedge;
13913 fedge->work_next = fedge->work_prev = fedge;
13916 struct flow_edge *ftail;
13917 ftail = scc->flow_work_list->work_prev;
13918 fedge->work_next = ftail->work_next;
13919 fedge->work_prev = ftail;
13920 fedge->work_next->work_prev = fedge;
13921 fedge->work_prev->work_next = fedge;
13925 static struct flow_edge *scc_next_fedge(
13926 struct compile_state *state, struct scc_state *scc)
13928 struct flow_edge *fedge;
13929 fedge = scc->flow_work_list;
13931 fedge->work_next->work_prev = fedge->work_prev;
13932 fedge->work_prev->work_next = fedge->work_next;
13933 if (fedge->work_next != fedge) {
13934 scc->flow_work_list = fedge->work_next;
13936 scc->flow_work_list = 0;
13942 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13943 struct ssa_edge *sedge)
13945 if (!scc->ssa_work_list) {
13946 scc->ssa_work_list = sedge;
13947 sedge->work_next = sedge->work_prev = sedge;
13950 struct ssa_edge *stail;
13951 stail = scc->ssa_work_list->work_prev;
13952 sedge->work_next = stail->work_next;
13953 sedge->work_prev = stail;
13954 sedge->work_next->work_prev = sedge;
13955 sedge->work_prev->work_next = sedge;
13959 static struct ssa_edge *scc_next_sedge(
13960 struct compile_state *state, struct scc_state *scc)
13962 struct ssa_edge *sedge;
13963 sedge = scc->ssa_work_list;
13965 sedge->work_next->work_prev = sedge->work_prev;
13966 sedge->work_prev->work_next = sedge->work_next;
13967 if (sedge->work_next != sedge) {
13968 scc->ssa_work_list = sedge->work_next;
13970 scc->ssa_work_list = 0;
13976 static void initialize_scc_state(
13977 struct compile_state *state, struct scc_state *scc)
13979 int ins_count, ssa_edge_count;
13980 int ins_index, ssa_edge_index, fblock_index;
13981 struct triple *first, *ins;
13982 struct block *block;
13983 struct flow_block *fblock;
13985 memset(scc, 0, sizeof(*scc));
13987 /* Inialize pass zero find out how much memory we need */
13988 first = RHS(state->main_function, 0);
13990 ins_count = ssa_edge_count = 0;
13992 struct triple_set *edge;
13994 for(edge = ins->use; edge; edge = edge->next) {
13998 } while(ins != first);
14000 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
14001 ins_count, ssa_edge_count, state->last_vertex);
14003 scc->ins_count = ins_count;
14005 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
14007 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
14009 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
14012 /* Initialize pass one collect up the nodes */
14015 ins_index = ssa_edge_index = fblock_index = 0;
14018 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14019 block = ins->u.block;
14021 internal_error(state, ins, "label without block");
14024 block->vertex = fblock_index;
14025 fblock = &scc->flow_blocks[fblock_index];
14026 fblock->block = block;
14029 struct lattice_node *lnode;
14031 lnode = &scc->lattice[ins_index];
14034 lnode->fblock = fblock;
14035 lnode->val = ins; /* LATTICE HIGH */
14036 lnode->old_id = ins->id;
14037 ins->id = ins_index;
14040 } while(ins != first);
14041 /* Initialize pass two collect up the edges */
14046 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14047 struct flow_edge *fedge, **ftail;
14048 struct block_set *bedge;
14049 block = ins->u.block;
14050 fblock = &scc->flow_blocks[block->vertex];
14053 ftail = &fblock->out;
14055 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
14056 if (fblock->left.dst->block != block->left) {
14057 internal_error(state, 0, "block mismatch");
14059 fblock->left.out_next = 0;
14060 *ftail = &fblock->left;
14061 ftail = &fblock->left.out_next;
14063 if (block->right) {
14064 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
14065 if (fblock->right.dst->block != block->right) {
14066 internal_error(state, 0, "block mismatch");
14068 fblock->right.out_next = 0;
14069 *ftail = &fblock->right;
14070 ftail = &fblock->right.out_next;
14072 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
14073 fedge->src = fblock;
14074 fedge->work_next = fedge->work_prev = fedge;
14075 fedge->executable = 0;
14077 ftail = &fblock->in;
14078 for(bedge = block->use; bedge; bedge = bedge->next) {
14079 struct block *src_block;
14080 struct flow_block *sfblock;
14081 struct flow_edge *sfedge;
14082 src_block = bedge->member;
14083 sfblock = &scc->flow_blocks[src_block->vertex];
14085 if (src_block->left == block) {
14086 sfedge = &sfblock->left;
14088 sfedge = &sfblock->right;
14091 ftail = &sfedge->in_next;
14092 sfedge->in_next = 0;
14096 struct triple_set *edge;
14097 struct ssa_edge **stail;
14098 struct lattice_node *lnode;
14099 lnode = &scc->lattice[ins->id];
14101 stail = &lnode->out;
14102 for(edge = ins->use; edge; edge = edge->next) {
14103 struct ssa_edge *sedge;
14104 ssa_edge_index += 1;
14105 sedge = &scc->ssa_edges[ssa_edge_index];
14107 stail = &sedge->out_next;
14108 sedge->src = lnode;
14109 sedge->dst = &scc->lattice[edge->member->id];
14110 sedge->work_next = sedge->work_prev = sedge;
14111 sedge->out_next = 0;
14115 } while(ins != first);
14116 /* Setup a dummy block 0 as a node above the start node */
14118 struct flow_block *fblock, *dst;
14119 struct flow_edge *fedge;
14120 fblock = &scc->flow_blocks[0];
14123 fblock->out = &fblock->left;
14124 dst = &scc->flow_blocks[state->first_block->vertex];
14125 fedge = &fblock->left;
14126 fedge->src = fblock;
14128 fedge->work_next = fedge;
14129 fedge->work_prev = fedge;
14130 fedge->in_next = fedge->dst->in;
14131 fedge->out_next = 0;
14132 fedge->executable = 0;
14133 fedge->dst->in = fedge;
14135 /* Initialize the work lists */
14136 scc->flow_work_list = 0;
14137 scc->ssa_work_list = 0;
14138 scc_add_fedge(state, scc, fedge);
14141 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14142 ins_index, ssa_edge_index, fblock_index);
14147 static void free_scc_state(
14148 struct compile_state *state, struct scc_state *scc)
14150 xfree(scc->flow_blocks);
14151 xfree(scc->ssa_edges);
14152 xfree(scc->lattice);
14156 static struct lattice_node *triple_to_lattice(
14157 struct compile_state *state, struct scc_state *scc, struct triple *ins)
14159 if (ins->id <= 0) {
14160 internal_error(state, ins, "bad id");
14162 return &scc->lattice[ins->id];
14165 static struct triple *preserve_lval(
14166 struct compile_state *state, struct lattice_node *lnode)
14168 struct triple *old;
14169 /* Preserve the original value */
14171 old = dup_triple(state, lnode->val);
14172 if (lnode->val != lnode->def) {
14182 static int lval_changed(struct compile_state *state,
14183 struct triple *old, struct lattice_node *lnode)
14186 /* See if the lattice value has changed */
14188 if (!old && !lnode->val) {
14191 if (changed && lnode->val && !is_const(lnode->val)) {
14195 lnode->val && old &&
14196 (memcmp(lnode->val->param, old->param,
14197 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14198 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14208 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
14209 struct lattice_node *lnode)
14211 struct lattice_node *tmp;
14212 struct triple **slot, *old;
14213 struct flow_edge *fedge;
14215 if (lnode->def->op != OP_PHI) {
14216 internal_error(state, lnode->def, "not phi");
14218 /* Store the original value */
14219 old = preserve_lval(state, lnode);
14221 /* default to lattice high */
14222 lnode->val = lnode->def;
14223 slot = &RHS(lnode->def, 0);
14225 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14226 if (!fedge->executable) {
14229 if (!slot[index]) {
14230 internal_error(state, lnode->def, "no phi value");
14232 tmp = triple_to_lattice(state, scc, slot[index]);
14233 /* meet(X, lattice low) = lattice low */
14237 /* meet(X, lattice high) = X */
14238 else if (!tmp->val) {
14239 lnode->val = lnode->val;
14241 /* meet(lattice high, X) = X */
14242 else if (!is_const(lnode->val)) {
14243 lnode->val = dup_triple(state, tmp->val);
14244 lnode->val->type = lnode->def->type;
14246 /* meet(const, const) = const or lattice low */
14247 else if (!constants_equal(state, lnode->val, tmp->val)) {
14255 fprintf(stderr, "phi: %d -> %s\n",
14257 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14259 /* If the lattice value has changed update the work lists. */
14260 if (lval_changed(state, old, lnode)) {
14261 struct ssa_edge *sedge;
14262 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14263 scc_add_sedge(state, scc, sedge);
14268 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14269 struct lattice_node *lnode)
14272 struct triple *old, *scratch;
14273 struct triple **dexpr, **vexpr;
14276 /* Store the original value */
14277 old = preserve_lval(state, lnode);
14279 /* Reinitialize the value */
14280 lnode->val = scratch = dup_triple(state, lnode->def);
14281 scratch->id = lnode->old_id;
14282 scratch->next = scratch;
14283 scratch->prev = scratch;
14286 count = TRIPLE_SIZE(scratch->sizes);
14287 for(i = 0; i < count; i++) {
14288 dexpr = &lnode->def->param[i];
14289 vexpr = &scratch->param[i];
14291 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14292 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14294 struct lattice_node *tmp;
14295 tmp = triple_to_lattice(state, scc, *dexpr);
14296 *vexpr = (tmp->val)? tmp->val : tmp->def;
14299 if (scratch->op == OP_BRANCH) {
14300 scratch->next = lnode->def->next;
14302 /* Recompute the value */
14303 #warning "FIXME see if simplify does anything bad"
14304 /* So far it looks like only the strength reduction
14305 * optimization are things I need to worry about.
14307 simplify(state, scratch);
14308 /* Cleanup my value */
14309 if (scratch->use) {
14310 internal_error(state, lnode->def, "scratch used?");
14312 if ((scratch->prev != scratch) ||
14313 ((scratch->next != scratch) &&
14314 ((lnode->def->op != OP_BRANCH) ||
14315 (scratch->next != lnode->def->next)))) {
14316 internal_error(state, lnode->def, "scratch in list?");
14318 /* undo any uses... */
14319 count = TRIPLE_SIZE(scratch->sizes);
14320 for(i = 0; i < count; i++) {
14321 vexpr = &scratch->param[i];
14323 unuse_triple(*vexpr, scratch);
14326 if (!is_const(scratch)) {
14327 for(i = 0; i < count; i++) {
14328 dexpr = &lnode->def->param[i];
14329 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14330 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14332 struct lattice_node *tmp;
14333 tmp = triple_to_lattice(state, scc, *dexpr);
14341 (lnode->val->op == lnode->def->op) &&
14342 (memcmp(lnode->val->param, lnode->def->param,
14343 count * sizeof(lnode->val->param[0])) == 0) &&
14344 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14345 lnode->val = lnode->def;
14347 /* Find the cases that are always lattice lo */
14349 triple_is_def(state, lnode->val) &&
14350 !triple_is_pure(state, lnode->val)) {
14354 (lnode->val->op == OP_SDECL) &&
14355 (lnode->val != lnode->def)) {
14356 internal_error(state, lnode->def, "bad sdecl");
14358 /* See if the lattice value has changed */
14359 changed = lval_changed(state, old, lnode);
14360 if (lnode->val != scratch) {
14366 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14367 struct lattice_node *lnode)
14369 struct lattice_node *cond;
14372 struct flow_edge *fedge;
14373 fprintf(stderr, "branch: %d (",
14376 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14377 fprintf(stderr, " %d", fedge->dst->block->vertex);
14379 fprintf(stderr, " )");
14380 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14381 fprintf(stderr, " <- %d",
14382 RHS(lnode->def, 0)->id);
14384 fprintf(stderr, "\n");
14387 if (lnode->def->op != OP_BRANCH) {
14388 internal_error(state, lnode->def, "not branch");
14390 /* This only applies to conditional branches */
14391 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14394 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14395 if (cond->val && !is_const(cond->val)) {
14396 #warning "FIXME do I need to do something here?"
14397 warning(state, cond->def, "condition not constant?");
14400 if (cond->val == 0) {
14401 scc_add_fedge(state, scc, cond->fblock->out);
14402 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14404 else if (cond->val->u.cval) {
14405 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14408 scc_add_fedge(state, scc, cond->fblock->out);
14413 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14414 struct lattice_node *lnode)
14418 changed = compute_lnode_val(state, scc, lnode);
14421 struct triple **expr;
14422 fprintf(stderr, "expr: %3d %10s (",
14423 lnode->def->id, tops(lnode->def->op));
14424 expr = triple_rhs(state, lnode->def, 0);
14425 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14427 fprintf(stderr, " %d", (*expr)->id);
14430 fprintf(stderr, " ) -> %s\n",
14431 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14434 if (lnode->def->op == OP_BRANCH) {
14435 scc_visit_branch(state, scc, lnode);
14438 else if (changed) {
14439 struct ssa_edge *sedge;
14440 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14441 scc_add_sedge(state, scc, sedge);
14446 static void scc_writeback_values(
14447 struct compile_state *state, struct scc_state *scc)
14449 struct triple *first, *ins;
14450 first = RHS(state->main_function, 0);
14453 struct lattice_node *lnode;
14454 lnode = triple_to_lattice(state, scc, ins);
14456 ins->id = lnode->old_id;
14458 if (lnode->val && !is_const(lnode->val)) {
14459 warning(state, lnode->def,
14460 "lattice node still high?");
14463 if (lnode->val && (lnode->val != ins)) {
14464 /* See if it something I know how to write back */
14465 switch(lnode->val->op) {
14467 mkconst(state, ins, lnode->val->u.cval);
14470 mkaddr_const(state, ins,
14471 MISC(lnode->val, 0), lnode->val->u.cval);
14474 /* By default don't copy the changes,
14475 * recompute them in place instead.
14477 simplify(state, ins);
14480 if (is_const(lnode->val) &&
14481 !constants_equal(state, lnode->val, ins)) {
14482 internal_error(state, 0, "constants not equal");
14484 /* Free the lattice nodes */
14489 } while(ins != first);
14492 static void scc_transform(struct compile_state *state)
14494 struct scc_state scc;
14496 initialize_scc_state(state, &scc);
14498 while(scc.flow_work_list || scc.ssa_work_list) {
14499 struct flow_edge *fedge;
14500 struct ssa_edge *sedge;
14501 struct flow_edge *fptr;
14502 while((fedge = scc_next_fedge(state, &scc))) {
14503 struct block *block;
14504 struct triple *ptr;
14505 struct flow_block *fblock;
14508 if (fedge->executable) {
14512 internal_error(state, 0, "fedge without dst");
14515 internal_error(state, 0, "fedge without src");
14517 fedge->executable = 1;
14518 fblock = fedge->dst;
14519 block = fblock->block;
14521 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14522 if (fptr->executable) {
14527 fprintf(stderr, "vertex: %d time: %d\n",
14528 block->vertex, time);
14532 for(ptr = block->first; !done; ptr = ptr->next) {
14533 struct lattice_node *lnode;
14534 done = (ptr == block->last);
14535 lnode = &scc.lattice[ptr->id];
14536 if (ptr->op == OP_PHI) {
14537 scc_visit_phi(state, &scc, lnode);
14539 else if (time == 1) {
14540 scc_visit_expr(state, &scc, lnode);
14543 if (fblock->out && !fblock->out->out_next) {
14544 scc_add_fedge(state, &scc, fblock->out);
14547 while((sedge = scc_next_sedge(state, &scc))) {
14548 struct lattice_node *lnode;
14549 struct flow_block *fblock;
14550 lnode = sedge->dst;
14551 fblock = lnode->fblock;
14553 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14554 sedge - scc.ssa_edges,
14555 sedge->src->def->id,
14556 sedge->dst->def->id);
14558 if (lnode->def->op == OP_PHI) {
14559 scc_visit_phi(state, &scc, lnode);
14562 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14563 if (fptr->executable) {
14568 scc_visit_expr(state, &scc, lnode);
14574 scc_writeback_values(state, &scc);
14575 free_scc_state(state, &scc);
14579 static void transform_to_arch_instructions(struct compile_state *state)
14581 struct triple *ins, *first;
14582 first = RHS(state->main_function, 0);
14585 ins = transform_to_arch_instruction(state, ins);
14586 } while(ins != first);
14589 #if DEBUG_CONSISTENCY
14590 static void verify_uses(struct compile_state *state)
14592 struct triple *first, *ins;
14593 struct triple_set *set;
14594 first = RHS(state->main_function, 0);
14597 struct triple **expr;
14598 expr = triple_rhs(state, ins, 0);
14599 for(; expr; expr = triple_rhs(state, ins, expr)) {
14600 struct triple *rhs;
14602 for(set = rhs?rhs->use:0; set; set = set->next) {
14603 if (set->member == ins) {
14608 internal_error(state, ins, "rhs not used");
14611 expr = triple_lhs(state, ins, 0);
14612 for(; expr; expr = triple_lhs(state, ins, expr)) {
14613 struct triple *lhs;
14615 for(set = lhs?lhs->use:0; set; set = set->next) {
14616 if (set->member == ins) {
14621 internal_error(state, ins, "lhs not used");
14625 } while(ins != first);
14628 static void verify_blocks_present(struct compile_state *state)
14630 struct triple *first, *ins;
14631 if (!state->first_block) {
14634 first = RHS(state->main_function, 0);
14637 valid_ins(state, ins);
14638 if (triple_stores_block(state, ins)) {
14639 if (!ins->u.block) {
14640 internal_error(state, ins,
14641 "%p not in a block?\n", ins);
14645 } while(ins != first);
14649 static void verify_blocks(struct compile_state *state)
14651 struct triple *ins;
14652 struct block *block;
14654 block = state->first_block;
14661 struct block_set *user;
14663 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14664 if (triple_stores_block(state, ins) && (ins->u.block != block)) {
14665 internal_error(state, ins, "inconsitent block specified");
14667 valid_ins(state, ins);
14670 for(user = block->use; user; user = user->next) {
14672 if ((block == state->last_block) &&
14673 (user->member == state->first_block)) {
14676 if ((user->member->left != block) &&
14677 (user->member->right != block)) {
14678 internal_error(state, user->member->first,
14679 "user does not use block");
14682 if (triple_is_branch(state, block->last) &&
14683 (block->right != block_of_triple(state, TARG(block->last, 0))))
14685 internal_error(state, block->last, "block->right != TARG(0)");
14687 if (!triple_is_uncond_branch(state, block->last) &&
14688 (block != state->last_block) &&
14689 (block->left != block_of_triple(state, block->last->next)))
14691 internal_error(state, block->last, "block->left != block->last->next");
14694 for(user = block->left->use; user; user = user->next) {
14695 if (user->member == block) {
14699 if (!user || user->member != block) {
14700 internal_error(state, block->first,
14701 "block does not use left");
14704 if (block->right) {
14705 for(user = block->right->use; user; user = user->next) {
14706 if (user->member == block) {
14710 if (!user || user->member != block) {
14711 internal_error(state, block->first,
14712 "block does not use right");
14715 if (block->users != users) {
14716 internal_error(state, block->first,
14717 "computed users %d != stored users %d\n",
14718 users, block->users);
14720 if (!triple_stores_block(state, block->last->next)) {
14721 internal_error(state, block->last->next,
14722 "cannot find next block");
14724 block = block->last->next->u.block;
14726 internal_error(state, block->last->next,
14729 } while(block != state->first_block);
14730 if (blocks != state->last_vertex) {
14731 internal_error(state, 0, "computed blocks != stored blocks %d\n",
14732 blocks, state->last_vertex);
14736 static void verify_domination(struct compile_state *state)
14738 struct triple *first, *ins;
14739 struct triple_set *set;
14740 if (!state->first_block) {
14744 first = RHS(state->main_function, 0);
14747 for(set = ins->use; set; set = set->next) {
14748 struct triple **expr;
14749 if (set->member->op == OP_PHI) {
14752 /* See if the use is on the righ hand side */
14753 expr = triple_rhs(state, set->member, 0);
14754 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14755 if (*expr == ins) {
14760 !tdominates(state, ins, set->member)) {
14761 internal_error(state, set->member,
14762 "non dominated rhs use?");
14766 } while(ins != first);
14769 static void verify_piece(struct compile_state *state)
14771 struct triple *first, *ins;
14772 first = RHS(state->main_function, 0);
14775 struct triple *ptr;
14777 lhs = TRIPLE_LHS(ins->sizes);
14778 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14779 if (ptr != LHS(ins, i)) {
14780 internal_error(state, ins, "malformed lhs on %s",
14783 if (ptr->op != OP_PIECE) {
14784 internal_error(state, ins, "bad lhs op %s at %d on %s",
14785 tops(ptr->op), i, tops(ins->op));
14787 if (ptr->u.cval != i) {
14788 internal_error(state, ins, "bad u.cval of %d %d expected",
14793 } while(ins != first);
14795 static void verify_ins_colors(struct compile_state *state)
14797 struct triple *first, *ins;
14799 first = RHS(state->main_function, 0);
14803 } while(ins != first);
14805 static void verify_consistency(struct compile_state *state)
14807 verify_uses(state);
14808 verify_blocks_present(state);
14809 verify_blocks(state);
14810 verify_domination(state);
14811 verify_piece(state);
14812 verify_ins_colors(state);
14815 static void verify_consistency(struct compile_state *state) {}
14816 #endif /* DEBUG_USES */
14818 static void optimize(struct compile_state *state)
14820 if (state->debug & DEBUG_TRIPLES) {
14821 print_triples(state);
14823 /* Replace structures with simpler data types */
14824 flatten_structures(state);
14825 if (state->debug & DEBUG_TRIPLES) {
14826 print_triples(state);
14828 verify_consistency(state);
14829 /* Analize the intermediate code */
14830 setup_basic_blocks(state);
14831 analyze_idominators(state);
14832 analyze_ipdominators(state);
14834 /* Transform the code to ssa form. */
14836 * The transformation to ssa form puts a phi function
14837 * on each of edge of a dominance frontier where that
14838 * phi function might be needed. At -O2 if we don't
14839 * eleminate the excess phi functions we can get an
14840 * exponential code size growth. So I kill the extra
14841 * phi functions early and I kill them often.
14843 transform_to_ssa_form(state);
14844 eliminate_inefectual_code(state);
14846 verify_consistency(state);
14847 if (state->debug & DEBUG_CODE_ELIMINATION) {
14848 fprintf(stdout, "After transform_to_ssa_form\n");
14849 print_blocks(state, stdout);
14851 /* Do strength reduction and simple constant optimizations */
14852 if (state->optimize >= 1) {
14853 simplify_all(state);
14854 transform_from_ssa_form(state);
14855 free_basic_blocks(state);
14856 setup_basic_blocks(state);
14857 analyze_idominators(state);
14858 analyze_ipdominators(state);
14859 transform_to_ssa_form(state);
14860 eliminate_inefectual_code(state);
14862 if (state->debug & DEBUG_CODE_ELIMINATION) {
14863 fprintf(stdout, "After simplify_all\n");
14864 print_blocks(state, stdout);
14866 verify_consistency(state);
14867 /* Propogate constants throughout the code */
14868 if (state->optimize >= 2) {
14869 scc_transform(state);
14870 transform_from_ssa_form(state);
14871 free_basic_blocks(state);
14872 setup_basic_blocks(state);
14873 analyze_idominators(state);
14874 analyze_ipdominators(state);
14875 transform_to_ssa_form(state);
14876 eliminate_inefectual_code(state);
14878 verify_consistency(state);
14879 #warning "WISHLIST implement single use constants (least possible register pressure)"
14880 #warning "WISHLIST implement induction variable elimination"
14881 /* Select architecture instructions and an initial partial
14882 * coloring based on architecture constraints.
14884 transform_to_arch_instructions(state);
14885 verify_consistency(state);
14886 if (state->debug & DEBUG_ARCH_CODE) {
14887 printf("After transform_to_arch_instructions\n");
14888 print_blocks(state, stdout);
14889 print_control_flow(state);
14891 eliminate_inefectual_code(state);
14892 verify_consistency(state);
14893 if (state->debug & DEBUG_CODE_ELIMINATION) {
14894 printf("After eliminate_inefectual_code\n");
14895 print_blocks(state, stdout);
14896 print_control_flow(state);
14898 verify_consistency(state);
14899 /* Color all of the variables to see if they will fit in registers */
14900 insert_copies_to_phi(state);
14901 if (state->debug & DEBUG_INSERTED_COPIES) {
14902 printf("After insert_copies_to_phi\n");
14903 print_blocks(state, stdout);
14904 print_control_flow(state);
14906 verify_consistency(state);
14907 insert_mandatory_copies(state);
14908 if (state->debug & DEBUG_INSERTED_COPIES) {
14909 printf("After insert_mandatory_copies\n");
14910 print_blocks(state, stdout);
14911 print_control_flow(state);
14913 verify_consistency(state);
14914 allocate_registers(state);
14915 verify_consistency(state);
14916 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14917 print_blocks(state, stdout);
14919 if (state->debug & DEBUG_CONTROL_FLOW) {
14920 print_control_flow(state);
14922 /* Remove the optimization information.
14923 * This is more to check for memory consistency than to free memory.
14925 free_basic_blocks(state);
14928 static void print_op_asm(struct compile_state *state,
14929 struct triple *ins, FILE *fp)
14931 struct asm_info *info;
14933 unsigned lhs, rhs, i;
14934 info = ins->u.ainfo;
14935 lhs = TRIPLE_LHS(ins->sizes);
14936 rhs = TRIPLE_RHS(ins->sizes);
14937 /* Don't count the clobbers in lhs */
14938 for(i = 0; i < lhs; i++) {
14939 if (LHS(ins, i)->type == &void_type) {
14944 fprintf(fp, "#ASM\n");
14946 for(ptr = info->str; *ptr; ptr++) {
14948 unsigned long param;
14949 struct triple *piece;
14959 param = strtoul(ptr, &next, 10);
14961 error(state, ins, "Invalid asm template");
14963 if (param >= (lhs + rhs)) {
14964 error(state, ins, "Invalid param %%%u in asm template",
14967 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14969 arch_reg_str(ID_REG(piece->id)));
14972 fprintf(fp, "\n#NOT ASM\n");
14976 /* Only use the low x86 byte registers. This allows me
14977 * allocate the entire register when a byte register is used.
14979 #define X86_4_8BIT_GPRS 1
14981 /* Recognized x86 cpu variants */
14989 #define CPU_DEFAULT CPU_I386
14991 /* The x86 register classes */
14992 #define REGC_FLAGS 0
14993 #define REGC_GPR8 1
14994 #define REGC_GPR16 2
14995 #define REGC_GPR32 3
14996 #define REGC_DIVIDEND64 4
14997 #define REGC_DIVIDEND32 5
15000 #define REGC_GPR32_8 8
15001 #define REGC_GPR16_8 9
15002 #define REGC_GPR8_LO 10
15003 #define REGC_IMM32 11
15004 #define REGC_IMM16 12
15005 #define REGC_IMM8 13
15006 #define LAST_REGC REGC_IMM8
15007 #if LAST_REGC >= MAX_REGC
15008 #error "MAX_REGC is to low"
15011 /* Register class masks */
15012 #define REGCM_FLAGS (1 << REGC_FLAGS)
15013 #define REGCM_GPR8 (1 << REGC_GPR8)
15014 #define REGCM_GPR16 (1 << REGC_GPR16)
15015 #define REGCM_GPR32 (1 << REGC_GPR32)
15016 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
15017 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
15018 #define REGCM_MMX (1 << REGC_MMX)
15019 #define REGCM_XMM (1 << REGC_XMM)
15020 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
15021 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
15022 #define REGCM_GPR8_LO (1 << REGC_GPR8_LO)
15023 #define REGCM_IMM32 (1 << REGC_IMM32)
15024 #define REGCM_IMM16 (1 << REGC_IMM16)
15025 #define REGCM_IMM8 (1 << REGC_IMM8)
15026 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
15028 /* The x86 registers */
15029 #define REG_EFLAGS 2
15030 #define REGC_FLAGS_FIRST REG_EFLAGS
15031 #define REGC_FLAGS_LAST REG_EFLAGS
15040 #define REGC_GPR8_LO_FIRST REG_AL
15041 #define REGC_GPR8_LO_LAST REG_DL
15042 #define REGC_GPR8_FIRST REG_AL
15043 #define REGC_GPR8_LAST REG_DH
15052 #define REGC_GPR16_FIRST REG_AX
15053 #define REGC_GPR16_LAST REG_SP
15062 #define REGC_GPR32_FIRST REG_EAX
15063 #define REGC_GPR32_LAST REG_ESP
15064 #define REG_EDXEAX 27
15065 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
15066 #define REGC_DIVIDEND64_LAST REG_EDXEAX
15067 #define REG_DXAX 28
15068 #define REGC_DIVIDEND32_FIRST REG_DXAX
15069 #define REGC_DIVIDEND32_LAST REG_DXAX
15070 #define REG_MMX0 29
15071 #define REG_MMX1 30
15072 #define REG_MMX2 31
15073 #define REG_MMX3 32
15074 #define REG_MMX4 33
15075 #define REG_MMX5 34
15076 #define REG_MMX6 35
15077 #define REG_MMX7 36
15078 #define REGC_MMX_FIRST REG_MMX0
15079 #define REGC_MMX_LAST REG_MMX7
15080 #define REG_XMM0 37
15081 #define REG_XMM1 38
15082 #define REG_XMM2 39
15083 #define REG_XMM3 40
15084 #define REG_XMM4 41
15085 #define REG_XMM5 42
15086 #define REG_XMM6 43
15087 #define REG_XMM7 44
15088 #define REGC_XMM_FIRST REG_XMM0
15089 #define REGC_XMM_LAST REG_XMM7
15090 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
15091 #define LAST_REG REG_XMM7
15093 #define REGC_GPR32_8_FIRST REG_EAX
15094 #define REGC_GPR32_8_LAST REG_EDX
15095 #define REGC_GPR16_8_FIRST REG_AX
15096 #define REGC_GPR16_8_LAST REG_DX
15098 #define REGC_IMM8_FIRST -1
15099 #define REGC_IMM8_LAST -1
15100 #define REGC_IMM16_FIRST -2
15101 #define REGC_IMM16_LAST -1
15102 #define REGC_IMM32_FIRST -4
15103 #define REGC_IMM32_LAST -1
15105 #if LAST_REG >= MAX_REGISTERS
15106 #error "MAX_REGISTERS to low"
15110 static unsigned regc_size[LAST_REGC +1] = {
15111 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
15112 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
15113 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
15114 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
15115 [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
15116 [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
15117 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
15118 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
15119 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
15120 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
15121 [REGC_GPR8_LO] = REGC_GPR8_LO_LAST - REGC_GPR8_LO_FIRST + 1,
15127 static const struct {
15129 } regcm_bound[LAST_REGC + 1] = {
15130 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
15131 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
15132 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
15133 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
15134 [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
15135 [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
15136 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
15137 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
15138 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
15139 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
15140 [REGC_GPR8_LO] = { REGC_GPR8_LO_FIRST, REGC_GPR8_LO_LAST },
15141 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
15142 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
15143 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
15146 static int arch_encode_cpu(const char *cpu)
15152 { "i386", CPU_I386 },
15160 for(ptr = cpus; ptr->name; ptr++) {
15161 if (strcmp(ptr->name, cpu) == 0) {
15168 static unsigned arch_regc_size(struct compile_state *state, int class)
15170 if ((class < 0) || (class > LAST_REGC)) {
15173 return regc_size[class];
15176 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
15178 /* See if two register classes may have overlapping registers */
15179 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
15180 REGCM_GPR32_8 | REGCM_GPR32 |
15181 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
15183 /* Special case for the immediates */
15184 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15185 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
15186 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15187 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
15190 return (regcm1 & regcm2) ||
15191 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
15194 static void arch_reg_equivs(
15195 struct compile_state *state, unsigned *equiv, int reg)
15197 if ((reg < 0) || (reg > LAST_REG)) {
15198 internal_error(state, 0, "invalid register");
15203 #if X86_4_8BIT_GPRS
15207 *equiv++ = REG_EAX;
15208 *equiv++ = REG_DXAX;
15209 *equiv++ = REG_EDXEAX;
15212 #if X86_4_8BIT_GPRS
15216 *equiv++ = REG_EAX;
15217 *equiv++ = REG_DXAX;
15218 *equiv++ = REG_EDXEAX;
15221 #if X86_4_8BIT_GPRS
15225 *equiv++ = REG_EBX;
15229 #if X86_4_8BIT_GPRS
15233 *equiv++ = REG_EBX;
15236 #if X86_4_8BIT_GPRS
15240 *equiv++ = REG_ECX;
15244 #if X86_4_8BIT_GPRS
15248 *equiv++ = REG_ECX;
15251 #if X86_4_8BIT_GPRS
15255 *equiv++ = REG_EDX;
15256 *equiv++ = REG_DXAX;
15257 *equiv++ = REG_EDXEAX;
15260 #if X86_4_8BIT_GPRS
15264 *equiv++ = REG_EDX;
15265 *equiv++ = REG_DXAX;
15266 *equiv++ = REG_EDXEAX;
15271 *equiv++ = REG_EAX;
15272 *equiv++ = REG_DXAX;
15273 *equiv++ = REG_EDXEAX;
15278 *equiv++ = REG_EBX;
15283 *equiv++ = REG_ECX;
15288 *equiv++ = REG_EDX;
15289 *equiv++ = REG_DXAX;
15290 *equiv++ = REG_EDXEAX;
15293 *equiv++ = REG_ESI;
15296 *equiv++ = REG_EDI;
15299 *equiv++ = REG_EBP;
15302 *equiv++ = REG_ESP;
15308 *equiv++ = REG_DXAX;
15309 *equiv++ = REG_EDXEAX;
15325 *equiv++ = REG_DXAX;
15326 *equiv++ = REG_EDXEAX;
15347 *equiv++ = REG_EAX;
15348 *equiv++ = REG_EDX;
15349 *equiv++ = REG_EDXEAX;
15358 *equiv++ = REG_EAX;
15359 *equiv++ = REG_EDX;
15360 *equiv++ = REG_DXAX;
15363 *equiv++ = REG_UNSET;
15366 static unsigned arch_avail_mask(struct compile_state *state)
15368 unsigned avail_mask;
15369 /* REGCM_GPR8 is not available */
15370 avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
15371 REGCM_GPR32 | REGCM_GPR32_8 |
15372 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15373 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15374 switch(state->cpu) {
15377 avail_mask |= REGCM_MMX;
15381 avail_mask |= REGCM_MMX | REGCM_XMM;
15387 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15389 unsigned mask, result;
15393 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15394 if ((result & mask) == 0) {
15397 if (class > LAST_REGC) {
15400 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15401 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15402 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15403 result |= (1 << class2);
15407 result &= arch_avail_mask(state);
15411 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
15413 /* Like arch_regcm_normalize except immediate register classes are excluded */
15414 regcm = arch_regcm_normalize(state, regcm);
15415 /* Remove the immediate register classes */
15416 regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15421 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15426 for(class = 0; class <= LAST_REGC; class++) {
15427 if ((reg >= regcm_bound[class].first) &&
15428 (reg <= regcm_bound[class].last)) {
15429 mask |= (1 << class);
15433 internal_error(state, 0, "reg %d not in any class", reg);
15438 static struct reg_info arch_reg_constraint(
15439 struct compile_state *state, struct type *type, const char *constraint)
15441 static const struct {
15445 } constraints[] = {
15446 { 'r', REGCM_GPR32, REG_UNSET },
15447 { 'g', REGCM_GPR32, REG_UNSET },
15448 { 'p', REGCM_GPR32, REG_UNSET },
15449 { 'q', REGCM_GPR8_LO, REG_UNSET },
15450 { 'Q', REGCM_GPR32_8, REG_UNSET },
15451 { 'x', REGCM_XMM, REG_UNSET },
15452 { 'y', REGCM_MMX, REG_UNSET },
15453 { 'a', REGCM_GPR32, REG_EAX },
15454 { 'b', REGCM_GPR32, REG_EBX },
15455 { 'c', REGCM_GPR32, REG_ECX },
15456 { 'd', REGCM_GPR32, REG_EDX },
15457 { 'D', REGCM_GPR32, REG_EDI },
15458 { 'S', REGCM_GPR32, REG_ESI },
15459 { '\0', 0, REG_UNSET },
15461 unsigned int regcm;
15462 unsigned int mask, reg;
15463 struct reg_info result;
15465 regcm = arch_type_to_regcm(state, type);
15468 for(ptr = constraint; *ptr; ptr++) {
15473 for(i = 0; constraints[i].class != '\0'; i++) {
15474 if (constraints[i].class == *ptr) {
15478 if (constraints[i].class == '\0') {
15479 error(state, 0, "invalid register constraint ``%c''", *ptr);
15482 if ((constraints[i].mask & regcm) == 0) {
15483 error(state, 0, "invalid register class %c specified",
15486 mask |= constraints[i].mask;
15487 if (constraints[i].reg != REG_UNSET) {
15488 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15489 error(state, 0, "Only one register may be specified");
15491 reg = constraints[i].reg;
15495 result.regcm = mask;
15499 static struct reg_info arch_reg_clobber(
15500 struct compile_state *state, const char *clobber)
15502 struct reg_info result;
15503 if (strcmp(clobber, "memory") == 0) {
15504 result.reg = REG_UNSET;
15507 else if (strcmp(clobber, "%eax") == 0) {
15508 result.reg = REG_EAX;
15509 result.regcm = REGCM_GPR32;
15511 else if (strcmp(clobber, "%ebx") == 0) {
15512 result.reg = REG_EBX;
15513 result.regcm = REGCM_GPR32;
15515 else if (strcmp(clobber, "%ecx") == 0) {
15516 result.reg = REG_ECX;
15517 result.regcm = REGCM_GPR32;
15519 else if (strcmp(clobber, "%edx") == 0) {
15520 result.reg = REG_EDX;
15521 result.regcm = REGCM_GPR32;
15523 else if (strcmp(clobber, "%esi") == 0) {
15524 result.reg = REG_ESI;
15525 result.regcm = REGCM_GPR32;
15527 else if (strcmp(clobber, "%edi") == 0) {
15528 result.reg = REG_EDI;
15529 result.regcm = REGCM_GPR32;
15531 else if (strcmp(clobber, "%ebp") == 0) {
15532 result.reg = REG_EBP;
15533 result.regcm = REGCM_GPR32;
15535 else if (strcmp(clobber, "%esp") == 0) {
15536 result.reg = REG_ESP;
15537 result.regcm = REGCM_GPR32;
15539 else if (strcmp(clobber, "cc") == 0) {
15540 result.reg = REG_EFLAGS;
15541 result.regcm = REGCM_FLAGS;
15543 else if ((strncmp(clobber, "xmm", 3) == 0) &&
15544 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15545 result.reg = REG_XMM0 + octdigval(clobber[3]);
15546 result.regcm = REGCM_XMM;
15548 else if ((strncmp(clobber, "mmx", 3) == 0) &&
15549 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15550 result.reg = REG_MMX0 + octdigval(clobber[3]);
15551 result.regcm = REGCM_MMX;
15554 error(state, 0, "Invalid register clobber");
15555 result.reg = REG_UNSET;
15561 static int do_select_reg(struct compile_state *state,
15562 char *used, int reg, unsigned classes)
15568 mask = arch_reg_regcm(state, reg);
15569 return (classes & mask) ? reg : REG_UNSET;
15572 static int arch_select_free_register(
15573 struct compile_state *state, char *used, int classes)
15575 /* Live ranges with the most neighbors are colored first.
15577 * Generally it does not matter which colors are given
15578 * as the register allocator attempts to color live ranges
15579 * in an order where you are guaranteed not to run out of colors.
15581 * Occasionally the register allocator cannot find an order
15582 * of register selection that will find a free color. To
15583 * increase the odds the register allocator will work when
15584 * it guesses first give out registers from register classes
15585 * least likely to run out of registers.
15590 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15591 reg = do_select_reg(state, used, i, classes);
15593 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15594 reg = do_select_reg(state, used, i, classes);
15596 for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
15597 reg = do_select_reg(state, used, i, classes);
15599 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15600 reg = do_select_reg(state, used, i, classes);
15602 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15603 reg = do_select_reg(state, used, i, classes);
15605 for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
15606 reg = do_select_reg(state, used, i, classes);
15608 for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
15609 reg = do_select_reg(state, used, i, classes);
15611 for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
15612 reg = do_select_reg(state, used, i, classes);
15614 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15615 reg = do_select_reg(state, used, i, classes);
15621 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
15623 #warning "FIXME force types smaller (if legal) before I get here"
15626 switch(type->type & TYPE_MASK) {
15633 mask = REGCM_GPR8 | REGCM_GPR8_LO |
15634 REGCM_GPR16 | REGCM_GPR16_8 |
15635 REGCM_GPR32 | REGCM_GPR32_8 |
15636 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15637 REGCM_MMX | REGCM_XMM |
15638 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15642 mask = REGCM_GPR16 | REGCM_GPR16_8 |
15643 REGCM_GPR32 | REGCM_GPR32_8 |
15644 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15645 REGCM_MMX | REGCM_XMM |
15646 REGCM_IMM32 | REGCM_IMM16;
15653 mask = REGCM_GPR32 | REGCM_GPR32_8 |
15654 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15655 REGCM_MMX | REGCM_XMM |
15659 internal_error(state, 0, "no register class for type");
15662 mask = arch_regcm_normalize(state, mask);
15666 static int is_imm32(struct triple *imm)
15668 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15669 (imm->op == OP_ADDRCONST);
15672 static int is_imm16(struct triple *imm)
15674 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15676 static int is_imm8(struct triple *imm)
15678 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15681 static int get_imm32(struct triple *ins, struct triple **expr)
15683 struct triple *imm;
15685 while(imm->op == OP_COPY) {
15688 if (!is_imm32(imm)) {
15691 unuse_triple(*expr, ins);
15692 use_triple(imm, ins);
15697 static int get_imm8(struct triple *ins, struct triple **expr)
15699 struct triple *imm;
15701 while(imm->op == OP_COPY) {
15704 if (!is_imm8(imm)) {
15707 unuse_triple(*expr, ins);
15708 use_triple(imm, ins);
15713 #define TEMPLATE_NOP 0
15714 #define TEMPLATE_INTCONST8 1
15715 #define TEMPLATE_INTCONST32 2
15716 #define TEMPLATE_COPY8_REG 3
15717 #define TEMPLATE_COPY16_REG 4
15718 #define TEMPLATE_COPY32_REG 5
15719 #define TEMPLATE_COPY_IMM8 6
15720 #define TEMPLATE_COPY_IMM16 7
15721 #define TEMPLATE_COPY_IMM32 8
15722 #define TEMPLATE_PHI8 9
15723 #define TEMPLATE_PHI16 10
15724 #define TEMPLATE_PHI32 11
15725 #define TEMPLATE_STORE8 12
15726 #define TEMPLATE_STORE16 13
15727 #define TEMPLATE_STORE32 14
15728 #define TEMPLATE_LOAD8 15
15729 #define TEMPLATE_LOAD16 16
15730 #define TEMPLATE_LOAD32 17
15731 #define TEMPLATE_BINARY8_REG 18
15732 #define TEMPLATE_BINARY16_REG 19
15733 #define TEMPLATE_BINARY32_REG 20
15734 #define TEMPLATE_BINARY8_IMM 21
15735 #define TEMPLATE_BINARY16_IMM 22
15736 #define TEMPLATE_BINARY32_IMM 23
15737 #define TEMPLATE_SL8_CL 24
15738 #define TEMPLATE_SL16_CL 25
15739 #define TEMPLATE_SL32_CL 26
15740 #define TEMPLATE_SL8_IMM 27
15741 #define TEMPLATE_SL16_IMM 28
15742 #define TEMPLATE_SL32_IMM 29
15743 #define TEMPLATE_UNARY8 30
15744 #define TEMPLATE_UNARY16 31
15745 #define TEMPLATE_UNARY32 32
15746 #define TEMPLATE_CMP8_REG 33
15747 #define TEMPLATE_CMP16_REG 34
15748 #define TEMPLATE_CMP32_REG 35
15749 #define TEMPLATE_CMP8_IMM 36
15750 #define TEMPLATE_CMP16_IMM 37
15751 #define TEMPLATE_CMP32_IMM 38
15752 #define TEMPLATE_TEST8 39
15753 #define TEMPLATE_TEST16 40
15754 #define TEMPLATE_TEST32 41
15755 #define TEMPLATE_SET 42
15756 #define TEMPLATE_JMP 43
15757 #define TEMPLATE_INB_DX 44
15758 #define TEMPLATE_INB_IMM 45
15759 #define TEMPLATE_INW_DX 46
15760 #define TEMPLATE_INW_IMM 47
15761 #define TEMPLATE_INL_DX 48
15762 #define TEMPLATE_INL_IMM 49
15763 #define TEMPLATE_OUTB_DX 50
15764 #define TEMPLATE_OUTB_IMM 51
15765 #define TEMPLATE_OUTW_DX 52
15766 #define TEMPLATE_OUTW_IMM 53
15767 #define TEMPLATE_OUTL_DX 54
15768 #define TEMPLATE_OUTL_IMM 55
15769 #define TEMPLATE_BSF 56
15770 #define TEMPLATE_RDMSR 57
15771 #define TEMPLATE_WRMSR 58
15772 #define TEMPLATE_UMUL8 59
15773 #define TEMPLATE_UMUL16 60
15774 #define TEMPLATE_UMUL32 61
15775 #define TEMPLATE_DIV8 62
15776 #define TEMPLATE_DIV16 63
15777 #define TEMPLATE_DIV32 64
15778 #define LAST_TEMPLATE TEMPLATE_DIV32
15779 #if LAST_TEMPLATE >= MAX_TEMPLATES
15780 #error "MAX_TEMPLATES to low"
15783 #define COPY8_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
15784 #define COPY16_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
15785 #define COPY32_REGCM (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15788 static struct ins_template templates[] = {
15789 [TEMPLATE_NOP] = {},
15790 [TEMPLATE_INTCONST8] = {
15791 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15793 [TEMPLATE_INTCONST32] = {
15794 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15796 [TEMPLATE_COPY8_REG] = {
15797 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15798 .rhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15800 [TEMPLATE_COPY16_REG] = {
15801 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15802 .rhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15804 [TEMPLATE_COPY32_REG] = {
15805 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15806 .rhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15808 [TEMPLATE_COPY_IMM8] = {
15809 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15810 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15812 [TEMPLATE_COPY_IMM16] = {
15813 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15814 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
15816 [TEMPLATE_COPY_IMM32] = {
15817 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15818 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
15820 [TEMPLATE_PHI8] = {
15821 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
15823 [ 0] = { REG_VIRT0, COPY8_REGCM },
15824 [ 1] = { REG_VIRT0, COPY8_REGCM },
15825 [ 2] = { REG_VIRT0, COPY8_REGCM },
15826 [ 3] = { REG_VIRT0, COPY8_REGCM },
15827 [ 4] = { REG_VIRT0, COPY8_REGCM },
15828 [ 5] = { REG_VIRT0, COPY8_REGCM },
15829 [ 6] = { REG_VIRT0, COPY8_REGCM },
15830 [ 7] = { REG_VIRT0, COPY8_REGCM },
15831 [ 8] = { REG_VIRT0, COPY8_REGCM },
15832 [ 9] = { REG_VIRT0, COPY8_REGCM },
15833 [10] = { REG_VIRT0, COPY8_REGCM },
15834 [11] = { REG_VIRT0, COPY8_REGCM },
15835 [12] = { REG_VIRT0, COPY8_REGCM },
15836 [13] = { REG_VIRT0, COPY8_REGCM },
15837 [14] = { REG_VIRT0, COPY8_REGCM },
15838 [15] = { REG_VIRT0, COPY8_REGCM },
15840 [TEMPLATE_PHI16] = {
15841 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
15843 [ 0] = { REG_VIRT0, COPY16_REGCM },
15844 [ 1] = { REG_VIRT0, COPY16_REGCM },
15845 [ 2] = { REG_VIRT0, COPY16_REGCM },
15846 [ 3] = { REG_VIRT0, COPY16_REGCM },
15847 [ 4] = { REG_VIRT0, COPY16_REGCM },
15848 [ 5] = { REG_VIRT0, COPY16_REGCM },
15849 [ 6] = { REG_VIRT0, COPY16_REGCM },
15850 [ 7] = { REG_VIRT0, COPY16_REGCM },
15851 [ 8] = { REG_VIRT0, COPY16_REGCM },
15852 [ 9] = { REG_VIRT0, COPY16_REGCM },
15853 [10] = { REG_VIRT0, COPY16_REGCM },
15854 [11] = { REG_VIRT0, COPY16_REGCM },
15855 [12] = { REG_VIRT0, COPY16_REGCM },
15856 [13] = { REG_VIRT0, COPY16_REGCM },
15857 [14] = { REG_VIRT0, COPY16_REGCM },
15858 [15] = { REG_VIRT0, COPY16_REGCM },
15860 [TEMPLATE_PHI32] = {
15861 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
15863 [ 0] = { REG_VIRT0, COPY32_REGCM },
15864 [ 1] = { REG_VIRT0, COPY32_REGCM },
15865 [ 2] = { REG_VIRT0, COPY32_REGCM },
15866 [ 3] = { REG_VIRT0, COPY32_REGCM },
15867 [ 4] = { REG_VIRT0, COPY32_REGCM },
15868 [ 5] = { REG_VIRT0, COPY32_REGCM },
15869 [ 6] = { REG_VIRT0, COPY32_REGCM },
15870 [ 7] = { REG_VIRT0, COPY32_REGCM },
15871 [ 8] = { REG_VIRT0, COPY32_REGCM },
15872 [ 9] = { REG_VIRT0, COPY32_REGCM },
15873 [10] = { REG_VIRT0, COPY32_REGCM },
15874 [11] = { REG_VIRT0, COPY32_REGCM },
15875 [12] = { REG_VIRT0, COPY32_REGCM },
15876 [13] = { REG_VIRT0, COPY32_REGCM },
15877 [14] = { REG_VIRT0, COPY32_REGCM },
15878 [15] = { REG_VIRT0, COPY32_REGCM },
15880 [TEMPLATE_STORE8] = {
15882 [0] = { REG_UNSET, REGCM_GPR32 },
15883 [1] = { REG_UNSET, REGCM_GPR8_LO },
15886 [TEMPLATE_STORE16] = {
15888 [0] = { REG_UNSET, REGCM_GPR32 },
15889 [1] = { REG_UNSET, REGCM_GPR16 },
15892 [TEMPLATE_STORE32] = {
15894 [0] = { REG_UNSET, REGCM_GPR32 },
15895 [1] = { REG_UNSET, REGCM_GPR32 },
15898 [TEMPLATE_LOAD8] = {
15899 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
15900 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15902 [TEMPLATE_LOAD16] = {
15903 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15904 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15906 [TEMPLATE_LOAD32] = {
15907 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15908 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15910 [TEMPLATE_BINARY8_REG] = {
15911 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15913 [0] = { REG_VIRT0, REGCM_GPR8_LO },
15914 [1] = { REG_UNSET, REGCM_GPR8_LO },
15917 [TEMPLATE_BINARY16_REG] = {
15918 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15920 [0] = { REG_VIRT0, REGCM_GPR16 },
15921 [1] = { REG_UNSET, REGCM_GPR16 },
15924 [TEMPLATE_BINARY32_REG] = {
15925 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15927 [0] = { REG_VIRT0, REGCM_GPR32 },
15928 [1] = { REG_UNSET, REGCM_GPR32 },
15931 [TEMPLATE_BINARY8_IMM] = {
15932 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15934 [0] = { REG_VIRT0, REGCM_GPR8_LO },
15935 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15938 [TEMPLATE_BINARY16_IMM] = {
15939 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15941 [0] = { REG_VIRT0, REGCM_GPR16 },
15942 [1] = { REG_UNNEEDED, REGCM_IMM16 },
15945 [TEMPLATE_BINARY32_IMM] = {
15946 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15948 [0] = { REG_VIRT0, REGCM_GPR32 },
15949 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15952 [TEMPLATE_SL8_CL] = {
15953 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15955 [0] = { REG_VIRT0, REGCM_GPR8_LO },
15956 [1] = { REG_CL, REGCM_GPR8_LO },
15959 [TEMPLATE_SL16_CL] = {
15960 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15962 [0] = { REG_VIRT0, REGCM_GPR16 },
15963 [1] = { REG_CL, REGCM_GPR8_LO },
15966 [TEMPLATE_SL32_CL] = {
15967 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15969 [0] = { REG_VIRT0, REGCM_GPR32 },
15970 [1] = { REG_CL, REGCM_GPR8_LO },
15973 [TEMPLATE_SL8_IMM] = {
15974 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15976 [0] = { REG_VIRT0, REGCM_GPR8_LO },
15977 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15980 [TEMPLATE_SL16_IMM] = {
15981 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15983 [0] = { REG_VIRT0, REGCM_GPR16 },
15984 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15987 [TEMPLATE_SL32_IMM] = {
15988 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15990 [0] = { REG_VIRT0, REGCM_GPR32 },
15991 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15994 [TEMPLATE_UNARY8] = {
15995 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15996 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15998 [TEMPLATE_UNARY16] = {
15999 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16000 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16002 [TEMPLATE_UNARY32] = {
16003 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16004 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16006 [TEMPLATE_CMP8_REG] = {
16007 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16009 [0] = { REG_UNSET, REGCM_GPR8_LO },
16010 [1] = { REG_UNSET, REGCM_GPR8_LO },
16013 [TEMPLATE_CMP16_REG] = {
16014 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16016 [0] = { REG_UNSET, REGCM_GPR16 },
16017 [1] = { REG_UNSET, REGCM_GPR16 },
16020 [TEMPLATE_CMP32_REG] = {
16021 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16023 [0] = { REG_UNSET, REGCM_GPR32 },
16024 [1] = { REG_UNSET, REGCM_GPR32 },
16027 [TEMPLATE_CMP8_IMM] = {
16028 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16030 [0] = { REG_UNSET, REGCM_GPR8_LO },
16031 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16034 [TEMPLATE_CMP16_IMM] = {
16035 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16037 [0] = { REG_UNSET, REGCM_GPR16 },
16038 [1] = { REG_UNNEEDED, REGCM_IMM16 },
16041 [TEMPLATE_CMP32_IMM] = {
16042 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16044 [0] = { REG_UNSET, REGCM_GPR32 },
16045 [1] = { REG_UNNEEDED, REGCM_IMM32 },
16048 [TEMPLATE_TEST8] = {
16049 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16050 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16052 [TEMPLATE_TEST16] = {
16053 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16054 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
16056 [TEMPLATE_TEST32] = {
16057 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16058 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16061 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16062 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16065 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16067 [TEMPLATE_INB_DX] = {
16068 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
16069 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16071 [TEMPLATE_INB_IMM] = {
16072 .lhs = { [0] = { REG_AL, REGCM_GPR8_LO } },
16073 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16075 [TEMPLATE_INW_DX] = {
16076 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16077 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16079 [TEMPLATE_INW_IMM] = {
16080 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16081 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16083 [TEMPLATE_INL_DX] = {
16084 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
16085 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16087 [TEMPLATE_INL_IMM] = {
16088 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
16089 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16091 [TEMPLATE_OUTB_DX] = {
16093 [0] = { REG_AL, REGCM_GPR8_LO },
16094 [1] = { REG_DX, REGCM_GPR16 },
16097 [TEMPLATE_OUTB_IMM] = {
16099 [0] = { REG_AL, REGCM_GPR8_LO },
16100 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16103 [TEMPLATE_OUTW_DX] = {
16105 [0] = { REG_AX, REGCM_GPR16 },
16106 [1] = { REG_DX, REGCM_GPR16 },
16109 [TEMPLATE_OUTW_IMM] = {
16111 [0] = { REG_AX, REGCM_GPR16 },
16112 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16115 [TEMPLATE_OUTL_DX] = {
16117 [0] = { REG_EAX, REGCM_GPR32 },
16118 [1] = { REG_DX, REGCM_GPR16 },
16121 [TEMPLATE_OUTL_IMM] = {
16123 [0] = { REG_EAX, REGCM_GPR32 },
16124 [1] = { REG_UNNEEDED, REGCM_IMM8 },
16128 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16129 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16131 [TEMPLATE_RDMSR] = {
16133 [0] = { REG_EAX, REGCM_GPR32 },
16134 [1] = { REG_EDX, REGCM_GPR32 },
16136 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
16138 [TEMPLATE_WRMSR] = {
16140 [0] = { REG_ECX, REGCM_GPR32 },
16141 [1] = { REG_EAX, REGCM_GPR32 },
16142 [2] = { REG_EDX, REGCM_GPR32 },
16145 [TEMPLATE_UMUL8] = {
16146 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16148 [0] = { REG_AL, REGCM_GPR8_LO },
16149 [1] = { REG_UNSET, REGCM_GPR8_LO },
16152 [TEMPLATE_UMUL16] = {
16153 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
16155 [0] = { REG_AX, REGCM_GPR16 },
16156 [1] = { REG_UNSET, REGCM_GPR16 },
16159 [TEMPLATE_UMUL32] = {
16160 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
16162 [0] = { REG_EAX, REGCM_GPR32 },
16163 [1] = { REG_UNSET, REGCM_GPR32 },
16166 [TEMPLATE_DIV8] = {
16168 [0] = { REG_AL, REGCM_GPR8_LO },
16169 [1] = { REG_AH, REGCM_GPR8 },
16172 [0] = { REG_AX, REGCM_GPR16 },
16173 [1] = { REG_UNSET, REGCM_GPR8_LO },
16176 [TEMPLATE_DIV16] = {
16178 [0] = { REG_AX, REGCM_GPR16 },
16179 [1] = { REG_DX, REGCM_GPR16 },
16182 [0] = { REG_DXAX, REGCM_DIVIDEND32 },
16183 [1] = { REG_UNSET, REGCM_GPR16 },
16186 [TEMPLATE_DIV32] = {
16188 [0] = { REG_EAX, REGCM_GPR32 },
16189 [1] = { REG_EDX, REGCM_GPR32 },
16192 [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
16193 [1] = { REG_UNSET, REGCM_GPR32 },
16198 static void fixup_branches(struct compile_state *state,
16199 struct triple *cmp, struct triple *use, int jmp_op)
16201 struct triple_set *entry, *next;
16202 for(entry = use->use; entry; entry = next) {
16203 next = entry->next;
16204 if (entry->member->op == OP_COPY) {
16205 fixup_branches(state, cmp, entry->member, jmp_op);
16207 else if (entry->member->op == OP_BRANCH) {
16208 struct triple *branch, *test;
16209 struct triple *left, *right;
16211 left = RHS(cmp, 0);
16212 if (TRIPLE_RHS(cmp->sizes) > 1) {
16213 right = RHS(cmp, 1);
16215 branch = entry->member;
16216 test = pre_triple(state, branch,
16217 cmp->op, cmp->type, left, right);
16218 test->template_id = TEMPLATE_TEST32;
16219 if (cmp->op == OP_CMP) {
16220 test->template_id = TEMPLATE_CMP32_REG;
16221 if (get_imm32(test, &RHS(test, 1))) {
16222 test->template_id = TEMPLATE_CMP32_IMM;
16225 use_triple(RHS(test, 0), test);
16226 use_triple(RHS(test, 1), test);
16227 unuse_triple(RHS(branch, 0), branch);
16228 RHS(branch, 0) = test;
16229 branch->op = jmp_op;
16230 branch->template_id = TEMPLATE_JMP;
16231 use_triple(RHS(branch, 0), branch);
16236 static void bool_cmp(struct compile_state *state,
16237 struct triple *ins, int cmp_op, int jmp_op, int set_op)
16239 struct triple_set *entry, *next;
16240 struct triple *set;
16242 /* Put a barrier up before the cmp which preceeds the
16243 * copy instruction. If a set actually occurs this gives
16244 * us a chance to move variables in registers out of the way.
16247 /* Modify the comparison operator */
16249 ins->template_id = TEMPLATE_TEST32;
16250 if (cmp_op == OP_CMP) {
16251 ins->template_id = TEMPLATE_CMP32_REG;
16252 if (get_imm32(ins, &RHS(ins, 1))) {
16253 ins->template_id = TEMPLATE_CMP32_IMM;
16256 /* Generate the instruction sequence that will transform the
16257 * result of the comparison into a logical value.
16259 set = post_triple(state, ins, set_op, &char_type, ins, 0);
16260 use_triple(ins, set);
16261 set->template_id = TEMPLATE_SET;
16263 for(entry = ins->use; entry; entry = next) {
16264 next = entry->next;
16265 if (entry->member == set) {
16268 replace_rhs_use(state, ins, set, entry->member);
16270 fixup_branches(state, ins, set, jmp_op);
16273 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
16275 struct triple *next;
16277 lhs = TRIPLE_LHS(ins->sizes);
16278 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
16279 if (next != LHS(ins, i)) {
16280 internal_error(state, ins, "malformed lhs on %s",
16283 if (next->op != OP_PIECE) {
16284 internal_error(state, ins, "bad lhs op %s at %d on %s",
16285 tops(next->op), i, tops(ins->op));
16287 if (next->u.cval != i) {
16288 internal_error(state, ins, "bad u.cval of %d %d expected",
16295 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
16297 struct ins_template *template;
16298 struct reg_info result;
16300 if (ins->op == OP_PIECE) {
16301 index = ins->u.cval;
16302 ins = MISC(ins, 0);
16304 zlhs = TRIPLE_LHS(ins->sizes);
16305 if (triple_is_def(state, ins)) {
16308 if (index >= zlhs) {
16309 internal_error(state, ins, "index %d out of range for %s\n",
16310 index, tops(ins->op));
16314 template = &ins->u.ainfo->tmpl;
16317 if (ins->template_id > LAST_TEMPLATE) {
16318 internal_error(state, ins, "bad template number %d",
16321 template = &templates[ins->template_id];
16324 result = template->lhs[index];
16325 result.regcm = arch_regcm_normalize(state, result.regcm);
16326 if (result.reg != REG_UNNEEDED) {
16327 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
16329 if (result.regcm == 0) {
16330 internal_error(state, ins, "lhs %d regcm == 0", index);
16335 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
16337 struct reg_info result;
16338 struct ins_template *template;
16339 if ((index > TRIPLE_RHS(ins->sizes)) ||
16340 (ins->op == OP_PIECE)) {
16341 internal_error(state, ins, "index %d out of range for %s\n",
16342 index, tops(ins->op));
16346 template = &ins->u.ainfo->tmpl;
16349 if (ins->template_id > LAST_TEMPLATE) {
16350 internal_error(state, ins, "bad template number %d",
16353 template = &templates[ins->template_id];
16356 result = template->rhs[index];
16357 result.regcm = arch_regcm_normalize(state, result.regcm);
16358 if (result.regcm == 0) {
16359 internal_error(state, ins, "rhs %d regcm == 0", index);
16364 static struct triple *mod_div(struct compile_state *state,
16365 struct triple *ins, int div_op, int index)
16367 struct triple *div, *piece0, *piece1;
16369 /* Generate a piece to hold the remainder */
16370 piece1 = post_triple(state, ins, OP_PIECE, ins->type, 0, 0);
16371 piece1->u.cval = 1;
16373 /* Generate a piece to hold the quotient */
16374 piece0 = post_triple(state, ins, OP_PIECE, ins->type, 0, 0);
16375 piece0->u.cval = 0;
16377 /* Generate the appropriate division instruction */
16378 div = post_triple(state, ins, div_op, ins->type, 0, 0);
16379 RHS(div, 0) = RHS(ins, 0);
16380 RHS(div, 1) = RHS(ins, 1);
16381 LHS(div, 0) = piece0;
16382 LHS(div, 1) = piece1;
16383 div->template_id = TEMPLATE_DIV32;
16384 use_triple(RHS(div, 0), div);
16385 use_triple(RHS(div, 1), div);
16386 use_triple(LHS(div, 0), div);
16387 use_triple(LHS(div, 1), div);
16389 /* Hook on piece0 */
16390 MISC(piece0, 0) = div;
16391 use_triple(div, piece0);
16393 /* Hook on piece1 */
16394 MISC(piece1, 0) = div;
16395 use_triple(div, piece1);
16397 /* Replate uses of ins with the appropriate piece of the div */
16398 propogate_use(state, ins, LHS(div, index));
16399 release_triple(state, ins);
16401 /* Return the address of the next instruction */
16402 return piece1->next;
16405 static struct triple *transform_to_arch_instruction(
16406 struct compile_state *state, struct triple *ins)
16408 /* Transform from generic 3 address instructions
16409 * to archtecture specific instructions.
16410 * And apply architecture specific constraints to instructions.
16411 * Copies are inserted to preserve the register flexibility
16412 * of 3 address instructions.
16414 struct triple *next;
16419 ins->template_id = TEMPLATE_INTCONST32;
16420 if (ins->u.cval < 256) {
16421 ins->template_id = TEMPLATE_INTCONST8;
16425 ins->template_id = TEMPLATE_INTCONST32;
16431 ins->template_id = TEMPLATE_NOP;
16434 size = size_of(state, ins->type);
16435 if (is_imm8(RHS(ins, 0)) && (size <= 1)) {
16436 ins->template_id = TEMPLATE_COPY_IMM8;
16438 else if (is_imm16(RHS(ins, 0)) && (size <= 2)) {
16439 ins->template_id = TEMPLATE_COPY_IMM16;
16441 else if (is_imm32(RHS(ins, 0)) && (size <= 4)) {
16442 ins->template_id = TEMPLATE_COPY_IMM32;
16444 else if (is_const(RHS(ins, 0))) {
16445 internal_error(state, ins, "bad constant passed to copy");
16447 else if (size <= 1) {
16448 ins->template_id = TEMPLATE_COPY8_REG;
16450 else if (size <= 2) {
16451 ins->template_id = TEMPLATE_COPY16_REG;
16453 else if (size <= 4) {
16454 ins->template_id = TEMPLATE_COPY32_REG;
16457 internal_error(state, ins, "bad type passed to copy");
16461 size = size_of(state, ins->type);
16463 ins->template_id = TEMPLATE_PHI8;
16465 else if (size <= 2) {
16466 ins->template_id = TEMPLATE_PHI16;
16468 else if (size <= 4) {
16469 ins->template_id = TEMPLATE_PHI32;
16472 internal_error(state, ins, "bad type passed to phi");
16476 switch(ins->type->type & TYPE_MASK) {
16477 case TYPE_CHAR: case TYPE_UCHAR:
16478 ins->template_id = TEMPLATE_STORE8;
16480 case TYPE_SHORT: case TYPE_USHORT:
16481 ins->template_id = TEMPLATE_STORE16;
16483 case TYPE_INT: case TYPE_UINT:
16484 case TYPE_LONG: case TYPE_ULONG:
16486 ins->template_id = TEMPLATE_STORE32;
16489 internal_error(state, ins, "unknown type in store");
16494 switch(ins->type->type & TYPE_MASK) {
16495 case TYPE_CHAR: case TYPE_UCHAR:
16496 ins->template_id = TEMPLATE_LOAD8;
16500 ins->template_id = TEMPLATE_LOAD16;
16507 ins->template_id = TEMPLATE_LOAD32;
16510 internal_error(state, ins, "unknown type in load");
16520 ins->template_id = TEMPLATE_BINARY32_REG;
16521 if (get_imm32(ins, &RHS(ins, 1))) {
16522 ins->template_id = TEMPLATE_BINARY32_IMM;
16527 ins->template_id = TEMPLATE_DIV32;
16528 next = after_lhs(state, ins);
16530 /* FIXME UMUL does not work yet.. */
16532 ins->template_id = TEMPLATE_UMUL32;
16535 next = mod_div(state, ins, OP_UDIVT, 0);
16538 next = mod_div(state, ins, OP_SDIVT, 0);
16541 next = mod_div(state, ins, OP_UDIVT, 1);
16544 next = mod_div(state, ins, OP_SDIVT, 1);
16549 ins->template_id = TEMPLATE_SL32_CL;
16550 if (get_imm8(ins, &RHS(ins, 1))) {
16551 ins->template_id = TEMPLATE_SL32_IMM;
16552 } else if (size_of(state, RHS(ins, 1)->type) > 1) {
16553 typed_pre_copy(state, &char_type, ins, 1);
16558 ins->template_id = TEMPLATE_UNARY32;
16561 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
16564 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16567 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16570 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16573 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16576 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16579 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16582 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16585 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16588 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16591 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16594 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16597 if (TRIPLE_RHS(ins->sizes) > 0) {
16598 internal_error(state, ins, "bad branch test");
16601 ins->template_id = TEMPLATE_NOP;
16607 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16608 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16609 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16611 if (get_imm8(ins, &RHS(ins, 0))) {
16612 ins->template_id += 1;
16619 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16620 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16621 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16623 if (get_imm8(ins, &RHS(ins, 1))) {
16624 ins->template_id += 1;
16629 ins->template_id = TEMPLATE_BSF;
16632 ins->template_id = TEMPLATE_RDMSR;
16633 next = after_lhs(state, ins);
16636 ins->template_id = TEMPLATE_WRMSR;
16639 ins->template_id = TEMPLATE_NOP;
16642 ins->template_id = TEMPLATE_NOP;
16643 next = after_lhs(state, ins);
16645 /* Already transformed instructions */
16647 ins->template_id = TEMPLATE_TEST32;
16650 ins->template_id = TEMPLATE_CMP32_REG;
16651 if (get_imm32(ins, &RHS(ins, 1))) {
16652 ins->template_id = TEMPLATE_CMP32_IMM;
16655 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16656 case OP_JMP_SLESS: case OP_JMP_ULESS:
16657 case OP_JMP_SMORE: case OP_JMP_UMORE:
16658 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16659 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16660 ins->template_id = TEMPLATE_JMP;
16662 case OP_SET_EQ: case OP_SET_NOTEQ:
16663 case OP_SET_SLESS: case OP_SET_ULESS:
16664 case OP_SET_SMORE: case OP_SET_UMORE:
16665 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16666 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16667 ins->template_id = TEMPLATE_SET;
16669 /* Unhandled instructions */
16672 internal_error(state, ins, "unhandled ins: %d %s\n",
16673 ins->op, tops(ins->op));
16679 static long next_label(struct compile_state *state)
16681 static long label_counter = 0;
16682 return ++label_counter;
16684 static void generate_local_labels(struct compile_state *state)
16686 struct triple *first, *label;
16687 first = RHS(state->main_function, 0);
16690 if ((label->op == OP_LABEL) ||
16691 (label->op == OP_SDECL)) {
16693 label->u.cval = next_label(state);
16699 label = label->next;
16700 } while(label != first);
16703 static int check_reg(struct compile_state *state,
16704 struct triple *triple, int classes)
16708 reg = ID_REG(triple->id);
16709 if (reg == REG_UNSET) {
16710 internal_error(state, triple, "register not set");
16712 mask = arch_reg_regcm(state, reg);
16713 if (!(classes & mask)) {
16714 internal_error(state, triple, "reg %d in wrong class",
16720 static const char *arch_reg_str(int reg)
16723 #error "Registers have renumberd fix arch_reg_str"
16725 static const char *regs[] = {
16729 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16730 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16731 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16734 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16735 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
16736 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16738 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16745 static const char *reg(struct compile_state *state, struct triple *triple,
16749 reg = check_reg(state, triple, classes);
16750 return arch_reg_str(reg);
16753 const char *type_suffix(struct compile_state *state, struct type *type)
16755 const char *suffix;
16756 switch(size_of(state, type)) {
16757 case 1: suffix = "b"; break;
16758 case 2: suffix = "w"; break;
16759 case 4: suffix = "l"; break;
16761 internal_error(state, 0, "unknown suffix");
16768 static void print_const_val(
16769 struct compile_state *state, struct triple *ins, FILE *fp)
16773 fprintf(fp, " $%ld ",
16774 (long_t)(ins->u.cval));
16777 fprintf(fp, " $L%s%lu+%lu ",
16778 state->label_prefix,
16779 MISC(ins, 0)->u.cval,
16783 internal_error(state, ins, "unknown constant type");
16788 static void print_const(struct compile_state *state,
16789 struct triple *ins, FILE *fp)
16793 switch(ins->type->type & TYPE_MASK) {
16796 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16800 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16806 fprintf(fp, ".int %lu\n", ins->u.cval);
16809 internal_error(state, ins, "Unknown constant type");
16813 fprintf(fp, " .int L%s%lu+%lu ",
16814 state->label_prefix,
16815 MISC(ins, 0)->u.cval,
16820 unsigned char *blob;
16822 size = size_of(state, ins->type);
16823 blob = ins->u.blob;
16824 for(i = 0; i < size; i++) {
16825 fprintf(fp, ".byte 0x%02x\n",
16831 internal_error(state, ins, "Unknown constant type");
16836 #define TEXT_SECTION ".rom.text"
16837 #define DATA_SECTION ".rom.data"
16839 static long get_const_pool_ref(
16840 struct compile_state *state, struct triple *ins, FILE *fp)
16843 ref = next_label(state);
16844 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16845 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16846 fprintf(fp, "L%s%lu:\n", state->label_prefix, ref);
16847 print_const(state, ins, fp);
16848 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16852 static void print_binary_op(struct compile_state *state,
16853 const char *op, struct triple *ins, FILE *fp)
16856 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16857 if (RHS(ins, 0)->id != ins->id) {
16858 internal_error(state, ins, "invalid register assignment");
16860 if (is_const(RHS(ins, 1))) {
16861 fprintf(fp, "\t%s ", op);
16862 print_const_val(state, RHS(ins, 1), fp);
16863 fprintf(fp, ", %s\n",
16864 reg(state, RHS(ins, 0), mask));
16867 unsigned lmask, rmask;
16869 lreg = check_reg(state, RHS(ins, 0), mask);
16870 rreg = check_reg(state, RHS(ins, 1), mask);
16871 lmask = arch_reg_regcm(state, lreg);
16872 rmask = arch_reg_regcm(state, rreg);
16873 mask = lmask & rmask;
16874 fprintf(fp, "\t%s %s, %s\n",
16876 reg(state, RHS(ins, 1), mask),
16877 reg(state, RHS(ins, 0), mask));
16880 static void print_unary_op(struct compile_state *state,
16881 const char *op, struct triple *ins, FILE *fp)
16884 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16885 fprintf(fp, "\t%s %s\n",
16887 reg(state, RHS(ins, 0), mask));
16890 static void print_op_shift(struct compile_state *state,
16891 const char *op, struct triple *ins, FILE *fp)
16894 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16895 if (RHS(ins, 0)->id != ins->id) {
16896 internal_error(state, ins, "invalid register assignment");
16898 if (is_const(RHS(ins, 1))) {
16899 fprintf(fp, "\t%s ", op);
16900 print_const_val(state, RHS(ins, 1), fp);
16901 fprintf(fp, ", %s\n",
16902 reg(state, RHS(ins, 0), mask));
16905 fprintf(fp, "\t%s %s, %s\n",
16907 reg(state, RHS(ins, 1), REGCM_GPR8_LO),
16908 reg(state, RHS(ins, 0), mask));
16912 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16919 case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
16920 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16921 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16923 internal_error(state, ins, "not an in operation");
16927 dreg = check_reg(state, ins, mask);
16928 if (!reg_is_reg(state, dreg, REG_EAX)) {
16929 internal_error(state, ins, "dst != %%eax");
16931 if (is_const(RHS(ins, 0))) {
16932 fprintf(fp, "\t%s ", op);
16933 print_const_val(state, RHS(ins, 0), fp);
16934 fprintf(fp, ", %s\n",
16935 reg(state, ins, mask));
16939 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16940 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16941 internal_error(state, ins, "src != %%dx");
16943 fprintf(fp, "\t%s %s, %s\n",
16945 reg(state, RHS(ins, 0), REGCM_GPR16),
16946 reg(state, ins, mask));
16950 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16957 case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
16958 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16959 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16961 internal_error(state, ins, "not an out operation");
16965 lreg = check_reg(state, RHS(ins, 0), mask);
16966 if (!reg_is_reg(state, lreg, REG_EAX)) {
16967 internal_error(state, ins, "src != %%eax");
16969 if (is_const(RHS(ins, 1))) {
16970 fprintf(fp, "\t%s %s,",
16971 op, reg(state, RHS(ins, 0), mask));
16972 print_const_val(state, RHS(ins, 1), fp);
16977 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16978 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16979 internal_error(state, ins, "dst != %%dx");
16981 fprintf(fp, "\t%s %s, %s\n",
16983 reg(state, RHS(ins, 0), mask),
16984 reg(state, RHS(ins, 1), REGCM_GPR16));
16988 static void print_op_move(struct compile_state *state,
16989 struct triple *ins, FILE *fp)
16991 /* op_move is complex because there are many types
16992 * of registers we can move between.
16993 * Because OP_COPY will be introduced in arbitrary locations
16994 * OP_COPY must not affect flags.
16996 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
16997 struct triple *dst, *src;
16998 if (ins->op == OP_COPY) {
17003 internal_error(state, ins, "unknown move operation");
17006 if (!is_const(src)) {
17007 int src_reg, dst_reg;
17008 int src_regcm, dst_regcm;
17009 src_reg = ID_REG(src->id);
17010 dst_reg = ID_REG(dst->id);
17011 src_regcm = arch_reg_regcm(state, src_reg);
17012 dst_regcm = arch_reg_regcm(state, dst_reg);
17013 /* If the class is the same just move the register */
17014 if (src_regcm & dst_regcm &
17015 (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
17016 if ((src_reg != dst_reg) || !omit_copy) {
17017 fprintf(fp, "\tmov %s, %s\n",
17018 reg(state, src, src_regcm),
17019 reg(state, dst, dst_regcm));
17022 /* Move 32bit to 16bit */
17023 else if ((src_regcm & REGCM_GPR32) &&
17024 (dst_regcm & REGCM_GPR16)) {
17025 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
17026 if ((src_reg != dst_reg) || !omit_copy) {
17027 fprintf(fp, "\tmovw %s, %s\n",
17028 arch_reg_str(src_reg),
17029 arch_reg_str(dst_reg));
17032 /* Move from 32bit gprs to 16bit gprs */
17033 else if ((src_regcm & REGCM_GPR32) &&
17034 (dst_regcm & REGCM_GPR16)) {
17035 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17036 if ((src_reg != dst_reg) || !omit_copy) {
17037 fprintf(fp, "\tmov %s, %s\n",
17038 arch_reg_str(src_reg),
17039 arch_reg_str(dst_reg));
17042 /* Move 32bit to 8bit */
17043 else if ((src_regcm & REGCM_GPR32_8) &&
17044 (dst_regcm & REGCM_GPR8_LO))
17046 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
17047 if ((src_reg != dst_reg) || !omit_copy) {
17048 fprintf(fp, "\tmovb %s, %s\n",
17049 arch_reg_str(src_reg),
17050 arch_reg_str(dst_reg));
17053 /* Move 16bit to 8bit */
17054 else if ((src_regcm & REGCM_GPR16_8) &&
17055 (dst_regcm & REGCM_GPR8_LO))
17057 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
17058 if ((src_reg != dst_reg) || !omit_copy) {
17059 fprintf(fp, "\tmovb %s, %s\n",
17060 arch_reg_str(src_reg),
17061 arch_reg_str(dst_reg));
17064 /* Move 8/16bit to 16/32bit */
17065 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
17066 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
17068 op = is_signed(src->type)? "movsx": "movzx";
17069 fprintf(fp, "\t%s %s, %s\n",
17071 reg(state, src, src_regcm),
17072 reg(state, dst, dst_regcm));
17074 /* Move between sse registers */
17075 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
17076 if ((src_reg != dst_reg) || !omit_copy) {
17077 fprintf(fp, "\tmovdqa %s, %s\n",
17078 reg(state, src, src_regcm),
17079 reg(state, dst, dst_regcm));
17082 /* Move between mmx registers */
17083 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
17084 if ((src_reg != dst_reg) || !omit_copy) {
17085 fprintf(fp, "\tmovq %s, %s\n",
17086 reg(state, src, src_regcm),
17087 reg(state, dst, dst_regcm));
17090 /* Move from sse to mmx registers */
17091 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
17092 fprintf(fp, "\tmovdq2q %s, %s\n",
17093 reg(state, src, src_regcm),
17094 reg(state, dst, dst_regcm));
17096 /* Move from mmx to sse registers */
17097 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
17098 fprintf(fp, "\tmovq2dq %s, %s\n",
17099 reg(state, src, src_regcm),
17100 reg(state, dst, dst_regcm));
17102 /* Move between 32bit gprs & mmx/sse registers */
17103 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
17104 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
17105 fprintf(fp, "\tmovd %s, %s\n",
17106 reg(state, src, src_regcm),
17107 reg(state, dst, dst_regcm));
17109 /* Move from 16bit gprs & mmx/sse registers */
17110 else if ((src_regcm & REGCM_GPR16) &&
17111 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
17114 op = is_signed(src->type)? "movsx":"movxz";
17115 mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17116 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
17118 arch_reg_str(src_reg),
17119 arch_reg_str(mid_reg),
17120 arch_reg_str(mid_reg),
17121 arch_reg_str(dst_reg));
17123 /* Move from mmx/sse registers to 16bit gprs */
17124 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17125 (dst_regcm & REGCM_GPR16)) {
17126 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17127 fprintf(fp, "\tmovd %s, %s\n",
17128 arch_reg_str(src_reg),
17129 arch_reg_str(dst_reg));
17131 /* Move from gpr to 64bit dividend */
17132 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) &&
17133 (dst_regcm & REGCM_DIVIDEND64)) {
17134 const char *extend;
17135 extend = is_signed(src->type)? "cltd":"movl $0, %edx";
17136 fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
17137 arch_reg_str(src_reg),
17140 /* Move from 64bit gpr to gpr */
17141 else if ((src_regcm & REGCM_DIVIDEND64) &&
17142 (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
17143 if (dst_regcm & REGCM_GPR32) {
17146 else if (dst_regcm & REGCM_GPR16) {
17149 else if (dst_regcm & REGCM_GPR8_LO) {
17152 fprintf(fp, "\tmov %s, %s\n",
17153 arch_reg_str(src_reg),
17154 arch_reg_str(dst_reg));
17156 /* Move from mmx/sse registers to 64bit gpr */
17157 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17158 (dst_regcm & REGCM_DIVIDEND64)) {
17159 const char *extend;
17160 extend = is_signed(src->type)? "cltd": "movl $0, %edx";
17161 fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
17162 arch_reg_str(src_reg),
17165 /* Move from 64bit gpr to mmx/sse register */
17166 else if ((src_regcm & REGCM_DIVIDEND64) &&
17167 (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
17168 fprintf(fp, "\tmovd %%eax, %s\n",
17169 arch_reg_str(dst_reg));
17171 #if X86_4_8BIT_GPRS
17172 /* Move from 8bit gprs to mmx/sse registers */
17173 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
17174 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
17177 op = is_signed(src->type)? "movsx":"movzx";
17178 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17179 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
17181 reg(state, src, src_regcm),
17182 arch_reg_str(mid_reg),
17183 arch_reg_str(mid_reg),
17184 reg(state, dst, dst_regcm));
17186 /* Move from mmx/sse registers and 8bit gprs */
17187 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17188 (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
17190 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17191 fprintf(fp, "\tmovd %s, %s\n",
17192 reg(state, src, src_regcm),
17193 arch_reg_str(mid_reg));
17195 /* Move from 32bit gprs to 8bit gprs */
17196 else if ((src_regcm & REGCM_GPR32) &&
17197 (dst_regcm & REGCM_GPR8_LO)) {
17198 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17199 if ((src_reg != dst_reg) || !omit_copy) {
17200 fprintf(fp, "\tmov %s, %s\n",
17201 arch_reg_str(src_reg),
17202 arch_reg_str(dst_reg));
17205 /* Move from 16bit gprs to 8bit gprs */
17206 else if ((src_regcm & REGCM_GPR16) &&
17207 (dst_regcm & REGCM_GPR8_LO)) {
17208 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
17209 if ((src_reg != dst_reg) || !omit_copy) {
17210 fprintf(fp, "\tmov %s, %s\n",
17211 arch_reg_str(src_reg),
17212 arch_reg_str(dst_reg));
17215 #endif /* X86_4_8BIT_GPRS */
17217 internal_error(state, ins, "unknown copy type");
17223 dst_reg = ID_REG(dst->id);
17224 dst_regcm = arch_reg_regcm(state, dst_reg);
17225 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
17226 fprintf(fp, "\tmov ");
17227 print_const_val(state, src, fp);
17228 fprintf(fp, ", %s\n",
17229 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
17231 else if (dst_regcm & REGCM_DIVIDEND64) {
17232 if (size_of(state, dst->type) > 4) {
17233 internal_error(state, ins, "64bit constant...");
17235 fprintf(fp, "\tmov $0, %%edx\n");
17236 fprintf(fp, "\tmov ");
17237 print_const_val(state, src, fp);
17238 fprintf(fp, ", %%eax\n");
17240 else if (dst_regcm & REGCM_DIVIDEND32) {
17241 if (size_of(state, dst->type) > 2) {
17242 internal_error(state, ins, "32bit constant...");
17244 fprintf(fp, "\tmov $0, %%dx\n");
17245 fprintf(fp, "\tmov ");
17246 print_const_val(state, src, fp);
17247 fprintf(fp, ", %%ax");
17249 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
17251 ref = get_const_pool_ref(state, src, fp);
17252 fprintf(fp, "\tmovq L%s%lu, %s\n",
17253 state->label_prefix, ref,
17254 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
17257 internal_error(state, ins, "unknown copy immediate type");
17262 static void print_op_load(struct compile_state *state,
17263 struct triple *ins, FILE *fp)
17265 struct triple *dst, *src;
17268 if (is_const(src) || is_const(dst)) {
17269 internal_error(state, ins, "unknown load operation");
17271 fprintf(fp, "\tmov (%s), %s\n",
17272 reg(state, src, REGCM_GPR32),
17273 reg(state, dst, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32));
17277 static void print_op_store(struct compile_state *state,
17278 struct triple *ins, FILE *fp)
17280 struct triple *dst, *src;
17283 if (is_const(src) && (src->op == OP_INTCONST)) {
17285 value = (long_t)(src->u.cval);
17286 fprintf(fp, "\tmov%s $%ld, (%s)\n",
17287 type_suffix(state, src->type),
17289 reg(state, dst, REGCM_GPR32));
17291 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
17292 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
17293 type_suffix(state, src->type),
17294 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
17298 if (is_const(src) || is_const(dst)) {
17299 internal_error(state, ins, "unknown store operation");
17301 fprintf(fp, "\tmov%s %s, (%s)\n",
17302 type_suffix(state, src->type),
17303 reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
17304 reg(state, dst, REGCM_GPR32));
17310 static void print_op_smul(struct compile_state *state,
17311 struct triple *ins, FILE *fp)
17313 if (!is_const(RHS(ins, 1))) {
17314 fprintf(fp, "\timul %s, %s\n",
17315 reg(state, RHS(ins, 1), REGCM_GPR32),
17316 reg(state, RHS(ins, 0), REGCM_GPR32));
17319 fprintf(fp, "\timul ");
17320 print_const_val(state, RHS(ins, 1), fp);
17321 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
17325 static void print_op_cmp(struct compile_state *state,
17326 struct triple *ins, FILE *fp)
17330 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17331 dreg = check_reg(state, ins, REGCM_FLAGS);
17332 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
17333 internal_error(state, ins, "bad dest register for cmp");
17335 if (is_const(RHS(ins, 1))) {
17336 fprintf(fp, "\tcmp ");
17337 print_const_val(state, RHS(ins, 1), fp);
17338 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
17341 unsigned lmask, rmask;
17343 lreg = check_reg(state, RHS(ins, 0), mask);
17344 rreg = check_reg(state, RHS(ins, 1), mask);
17345 lmask = arch_reg_regcm(state, lreg);
17346 rmask = arch_reg_regcm(state, rreg);
17347 mask = lmask & rmask;
17348 fprintf(fp, "\tcmp %s, %s\n",
17349 reg(state, RHS(ins, 1), mask),
17350 reg(state, RHS(ins, 0), mask));
17354 static void print_op_test(struct compile_state *state,
17355 struct triple *ins, FILE *fp)
17358 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17359 fprintf(fp, "\ttest %s, %s\n",
17360 reg(state, RHS(ins, 0), mask),
17361 reg(state, RHS(ins, 0), mask));
17364 static void print_op_branch(struct compile_state *state,
17365 struct triple *branch, FILE *fp)
17367 const char *bop = "j";
17368 if (branch->op == OP_JMP) {
17369 if (TRIPLE_RHS(branch->sizes) != 0) {
17370 internal_error(state, branch, "jmp with condition?");
17375 struct triple *ptr;
17376 if (TRIPLE_RHS(branch->sizes) != 1) {
17377 internal_error(state, branch, "jmpcc without condition?");
17379 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
17380 if ((RHS(branch, 0)->op != OP_CMP) &&
17381 (RHS(branch, 0)->op != OP_TEST)) {
17382 internal_error(state, branch, "bad branch test");
17384 #warning "FIXME I have observed instructions between the test and branch instructions"
17385 ptr = RHS(branch, 0);
17386 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
17387 if (ptr->op != OP_COPY) {
17388 internal_error(state, branch, "branch does not follow test");
17391 switch(branch->op) {
17392 case OP_JMP_EQ: bop = "jz"; break;
17393 case OP_JMP_NOTEQ: bop = "jnz"; break;
17394 case OP_JMP_SLESS: bop = "jl"; break;
17395 case OP_JMP_ULESS: bop = "jb"; break;
17396 case OP_JMP_SMORE: bop = "jg"; break;
17397 case OP_JMP_UMORE: bop = "ja"; break;
17398 case OP_JMP_SLESSEQ: bop = "jle"; break;
17399 case OP_JMP_ULESSEQ: bop = "jbe"; break;
17400 case OP_JMP_SMOREEQ: bop = "jge"; break;
17401 case OP_JMP_UMOREEQ: bop = "jae"; break;
17403 internal_error(state, branch, "Invalid branch op");
17408 fprintf(fp, "\t%s L%s%lu\n",
17410 state->label_prefix,
17411 TARG(branch, 0)->u.cval);
17414 static void print_op_set(struct compile_state *state,
17415 struct triple *set, FILE *fp)
17417 const char *sop = "set";
17418 if (TRIPLE_RHS(set->sizes) != 1) {
17419 internal_error(state, set, "setcc without condition?");
17421 check_reg(state, RHS(set, 0), REGCM_FLAGS);
17422 if ((RHS(set, 0)->op != OP_CMP) &&
17423 (RHS(set, 0)->op != OP_TEST)) {
17424 internal_error(state, set, "bad set test");
17426 if (RHS(set, 0)->next != set) {
17427 internal_error(state, set, "set does not follow test");
17430 case OP_SET_EQ: sop = "setz"; break;
17431 case OP_SET_NOTEQ: sop = "setnz"; break;
17432 case OP_SET_SLESS: sop = "setl"; break;
17433 case OP_SET_ULESS: sop = "setb"; break;
17434 case OP_SET_SMORE: sop = "setg"; break;
17435 case OP_SET_UMORE: sop = "seta"; break;
17436 case OP_SET_SLESSEQ: sop = "setle"; break;
17437 case OP_SET_ULESSEQ: sop = "setbe"; break;
17438 case OP_SET_SMOREEQ: sop = "setge"; break;
17439 case OP_SET_UMOREEQ: sop = "setae"; break;
17441 internal_error(state, set, "Invalid set op");
17444 fprintf(fp, "\t%s %s\n",
17445 sop, reg(state, set, REGCM_GPR8_LO));
17448 static void print_op_bit_scan(struct compile_state *state,
17449 struct triple *ins, FILE *fp)
17453 case OP_BSF: op = "bsf"; break;
17454 case OP_BSR: op = "bsr"; break;
17456 internal_error(state, ins, "unknown bit scan");
17466 reg(state, RHS(ins, 0), REGCM_GPR32),
17467 reg(state, ins, REGCM_GPR32),
17468 reg(state, ins, REGCM_GPR32));
17472 static void print_sdecl(struct compile_state *state,
17473 struct triple *ins, FILE *fp)
17475 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
17476 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
17477 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17478 print_const(state, MISC(ins, 0), fp);
17479 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17483 static void print_instruction(struct compile_state *state,
17484 struct triple *ins, FILE *fp)
17486 /* Assumption: after I have exted the register allocator
17487 * everything is in a valid register.
17491 print_op_asm(state, ins, fp);
17493 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
17494 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
17495 case OP_AND: print_binary_op(state, "and", ins, fp); break;
17496 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
17497 case OP_OR: print_binary_op(state, "or", ins, fp); break;
17498 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
17499 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
17500 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
17501 case OP_POS: break;
17502 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
17503 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
17507 /* Don't generate anything here for constants */
17509 /* Don't generate anything for variable declarations. */
17512 print_sdecl(state, ins, fp);
17515 print_op_move(state, ins, fp);
17518 print_op_load(state, ins, fp);
17521 print_op_store(state, ins, fp);
17524 print_op_smul(state, ins, fp);
17526 case OP_CMP: print_op_cmp(state, ins, fp); break;
17527 case OP_TEST: print_op_test(state, ins, fp); break;
17529 case OP_JMP_EQ: case OP_JMP_NOTEQ:
17530 case OP_JMP_SLESS: case OP_JMP_ULESS:
17531 case OP_JMP_SMORE: case OP_JMP_UMORE:
17532 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
17533 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
17534 print_op_branch(state, ins, fp);
17536 case OP_SET_EQ: case OP_SET_NOTEQ:
17537 case OP_SET_SLESS: case OP_SET_ULESS:
17538 case OP_SET_SMORE: case OP_SET_UMORE:
17539 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
17540 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
17541 print_op_set(state, ins, fp);
17543 case OP_INB: case OP_INW: case OP_INL:
17544 print_op_in(state, ins, fp);
17546 case OP_OUTB: case OP_OUTW: case OP_OUTL:
17547 print_op_out(state, ins, fp);
17551 print_op_bit_scan(state, ins, fp);
17554 after_lhs(state, ins);
17555 fprintf(fp, "\trdmsr\n");
17558 fprintf(fp, "\twrmsr\n");
17561 fprintf(fp, "\thlt\n");
17564 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17567 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17570 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17576 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17578 /* Ignore OP_PIECE */
17581 /* Operations that should never get here */
17582 case OP_SDIV: case OP_UDIV:
17583 case OP_SMOD: case OP_UMOD:
17584 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
17585 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
17586 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
17588 internal_error(state, ins, "unknown op: %d %s",
17589 ins->op, tops(ins->op));
17594 static void print_instructions(struct compile_state *state)
17596 struct triple *first, *ins;
17597 int print_location;
17598 struct occurance *last_occurance;
17600 int max_inline_depth;
17601 max_inline_depth = 0;
17602 print_location = 1;
17603 last_occurance = 0;
17604 fp = state->output;
17605 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17606 first = RHS(state->main_function, 0);
17609 if (print_location &&
17610 last_occurance != ins->occurance) {
17611 if (!ins->occurance->parent) {
17612 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17613 ins->occurance->function,
17614 ins->occurance->filename,
17615 ins->occurance->line,
17616 ins->occurance->col);
17619 struct occurance *ptr;
17621 fprintf(fp, "\t/*\n");
17623 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17625 fprintf(fp, "\t * %s,%s:%d.%d\n",
17631 fprintf(fp, "\t */\n");
17632 if (inline_depth > max_inline_depth) {
17633 max_inline_depth = inline_depth;
17636 if (last_occurance) {
17637 put_occurance(last_occurance);
17639 get_occurance(ins->occurance);
17640 last_occurance = ins->occurance;
17643 print_instruction(state, ins, fp);
17645 } while(ins != first);
17646 if (print_location) {
17647 fprintf(fp, "/* max inline depth %d */\n",
17652 static void generate_code(struct compile_state *state)
17654 generate_local_labels(state);
17655 print_instructions(state);
17659 static void print_tokens(struct compile_state *state)
17662 tk = &state->token[0];
17667 next_token(state, 0);
17669 loc(stdout, state, 0);
17670 printf("%s <- `%s'\n",
17672 tk->ident ? tk->ident->name :
17673 tk->str_len ? tk->val.str : "");
17675 } while(tk->tok != TOK_EOF);
17678 static void compile(const char *filename, const char *ofilename,
17679 int cpu, int debug, int opt, const char *label_prefix)
17682 struct compile_state state;
17683 memset(&state, 0, sizeof(state));
17685 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17686 memset(&state.token[i], 0, sizeof(state.token[i]));
17687 state.token[i].tok = -1;
17689 /* Remember the debug settings */
17691 state.debug = debug;
17692 state.optimize = opt;
17693 /* Remember the output filename */
17694 state.ofilename = ofilename;
17695 state.output = fopen(state.ofilename, "w");
17696 if (!state.output) {
17697 error(&state, 0, "Cannot open output file %s\n",
17700 /* Remember the label prefix */
17701 state.label_prefix = label_prefix;
17702 /* Prep the preprocessor */
17703 state.if_depth = 0;
17704 state.if_value = 0;
17705 /* register the C keywords */
17706 register_keywords(&state);
17707 /* register the keywords the macro preprocessor knows */
17708 register_macro_keywords(&state);
17709 /* Memorize where some special keywords are. */
17710 state.i_continue = lookup(&state, "continue", 8);
17711 state.i_break = lookup(&state, "break", 5);
17712 /* Enter the globl definition scope */
17713 start_scope(&state);
17714 register_builtins(&state);
17715 compile_file(&state, filename, 1);
17717 print_tokens(&state);
17720 /* Exit the global definition scope */
17723 /* Now that basic compilation has happened
17724 * optimize the intermediate code
17728 generate_code(&state);
17730 fprintf(stderr, "done\n");
17734 static void version(void)
17736 printf("romcc " VERSION " released " RELEASE_DATE "\n");
17739 static void usage(void)
17743 "Usage: romcc <source>.c\n"
17744 "Compile a C source file without using ram\n"
17748 static void arg_error(char *fmt, ...)
17751 va_start(args, fmt);
17752 vfprintf(stderr, fmt, args);
17758 int main(int argc, char **argv)
17760 const char *filename;
17761 const char *ofilename;
17762 const char *label_prefix;
17769 ofilename = "auto.inc";
17773 while((argc > 1) && (argc != last_argc)) {
17775 if (strncmp(argv[1], "--debug=", 8) == 0) {
17776 debug = atoi(argv[1] + 8);
17780 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17781 label_prefix= argv[1] + 15;
17785 else if ((strcmp(argv[1],"-O") == 0) ||
17786 (strcmp(argv[1], "-O1") == 0)) {
17791 else if (strcmp(argv[1],"-O2") == 0) {
17796 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17797 ofilename = argv[2];
17801 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17802 cpu = arch_encode_cpu(argv[1] + 6);
17803 if (cpu == BAD_CPU) {
17804 arg_error("Invalid cpu specified: %s\n",
17812 arg_error("Wrong argument count %d\n", argc);
17814 filename = argv[1];
17815 compile(filename, ofilename, cpu, debug, optimize, label_prefix);