15 #define DEBUG_ERROR_MESSAGES 0
16 #define DEBUG_COLOR_GRAPH 0
18 #define X86_4_8BIT_GPRS 1
20 #warning "FIXME static constant variables"
21 #warning "FIXME enable pointers"
22 #warning "FIXME enable string constants"
24 /* Control flow graph of a loop without goto.
35 * |\ GGG HHH | continue;
63 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
64 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
67 * [] == DFlocal(X) U DF(X)
70 * Dominator graph of the same nodes.
74 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
76 * CCC CCC: [ ] ( BBB, JJJ )
78 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
80 * FFF FFF: [ ] ( BBB )
82 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
87 * BBB and JJJ are definitely the dominance frontier.
88 * Where do I place phi functions and how do I make that decision.
91 static void die(char *fmt, ...)
96 vfprintf(stderr, fmt, args);
103 #define MALLOC_STRONG_DEBUG
104 static void *xmalloc(size_t size, const char *name)
109 die("Cannot malloc %ld bytes to hold %s: %s\n",
110 size + 0UL, name, strerror(errno));
115 static void *xcmalloc(size_t size, const char *name)
118 buf = xmalloc(size, name);
119 memset(buf, 0, size);
123 static void xfree(const void *ptr)
128 static char *xstrdup(const char *str)
133 new = xmalloc(len + 1, "xstrdup string");
134 memcpy(new, str, len);
139 static void xchdir(const char *path)
141 if (chdir(path) != 0) {
142 die("chdir to %s failed: %s\n",
143 path, strerror(errno));
147 static int exists(const char *dirname, const char *filename)
151 if (access(filename, O_RDONLY) < 0) {
152 if ((errno != EACCES) && (errno != EROFS)) {
160 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
164 off_t size, progress;
173 fd = open(filename, O_RDONLY);
175 die("Cannot open '%s' : %s\n",
176 filename, strerror(errno));
178 result = fstat(fd, &stats);
180 die("Cannot stat: %s: %s\n",
181 filename, strerror(errno));
183 size = stats.st_size;
185 buf = xmalloc(size +2, filename);
186 buf[size] = '\n'; /* Make certain the file is newline terminated */
187 buf[size+1] = '\0'; /* Null terminate the file for good measure */
189 while(progress < size) {
190 result = read(fd, buf + progress, size - progress);
192 if ((errno == EINTR) || (errno == EAGAIN))
194 die("read on %s of %ld bytes failed: %s\n",
195 filename, (size - progress)+ 0UL, strerror(errno));
201 die("Close of %s failed: %s\n",
202 filename, strerror(errno));
207 /* Long on the destination platform */
208 typedef unsigned long ulong_t;
212 struct file_state *prev;
213 const char *basename;
224 struct hash_entry *ident;
232 /* I have two classes of types:
234 * Logical types. (The type the C standard says the operation is of)
236 * The operational types are:
251 * No memory is useable by the compiler.
252 * There is no floating point support.
253 * All operations take place in general purpose registers.
254 * There is one type of general purpose register.
255 * Unsigned longs are stored in that general purpose register.
258 /* Operations on general purpose registers.
275 #define OP_POS 14 /* Dummy positive operator don't use it */
285 #define OP_SLESSEQ 26
286 #define OP_ULESSEQ 27
287 #define OP_SMOREEQ 28
288 #define OP_UMOREEQ 29
290 #define OP_LFALSE 30 /* Test if the expression is logically false */
291 #define OP_LTRUE 31 /* Test if the expression is logcially true */
298 #define OP_MIN_CONST 50
299 #define OP_MAX_CONST 59
300 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
301 #define OP_INTCONST 50
302 #define OP_BLOBCONST 51
303 /* For OP_BLOBCONST ->type holds the layout and size
304 * information. u.blob holds a pointer to the raw binary
305 * data for the constant initializer.
307 #define OP_ADDRCONST 52
308 /* For OP_ADDRCONST ->type holds the type.
309 * RHS(0) holds the reference to the static variable.
310 * ->u.cval holds an offset from that value.
314 /* OP_WRITE moves one pseudo register to another.
315 * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
316 * RHS(0) holds the psuedo to move.
320 /* OP_READ reads the value of a variable and makes
321 * it available for the pseudo operation.
322 * Useful for things like def-use chains.
323 * RHS(0) holds points to the triple to read from.
326 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
329 /* OP_PIECE returns one piece of a instruction that returns a structure.
330 * RHS(0) is the instruction
331 * u.cval is the LHS piece of the instruction to return.
335 /* OP_DEREF generates an lvalue from a pointer.
336 * RHS(0) holds the pointer value.
337 * OP_DEREF serves as a place holder to indicate all necessary
338 * checks have been done to indicate a value is an lvalue.
341 /* OP_DOT references a submember of a structure lvalue.
342 * RHS(0) holds the lvalue.
343 * ->u.field holds the name of the field we want.
345 * Not seen outside of expressions.
348 /* OP_VAL returns the value of a subexpression of the current expression.
349 * Useful for operators that have side effects.
350 * RHS(0) holds the expression.
351 * MISC(0) holds the subexpression of RHS(0) that is the
352 * value of the expression.
354 * Not seen outside of expressions.
357 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
358 * Not seen outside of expressions.
361 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
362 * Not seen outside of expressions.
365 /* OP_CODE performas a C ? : operation.
366 * RHS(0) holds the test.
367 * RHS(1) holds the expression to evaluate if the test returns true.
368 * RHS(2) holds the expression to evaluate if the test returns false.
369 * Not seen outside of expressions.
372 /* OP_COMMA performacs a C comma operation.
373 * That is RHS(0) is evaluated, then RHS(1)
374 * and the value of RHS(1) is returned.
375 * Not seen outside of expressions.
379 /* OP_CALL performs a procedure call.
380 * MISC(0) holds a pointer to the OP_LIST of a function
381 * RHS(x) holds argument x of a function
383 * Currently not seen outside of expressions.
385 #define OP_VAL_VEC 74
386 /* OP_VAL_VEC is an array of triples that are either variable
387 * or values for a structure or an array.
388 * RHS(x) holds element x of the vector.
389 * triple->type->elements holds the size of the vector.
394 /* OP_LIST Holds a list of statements, and a result value.
395 * RHS(0) holds the list of statements.
396 * MISC(0) holds the value of the statements.
399 #define OP_BRANCH 81 /* branch */
400 /* For branch instructions
401 * TARG(0) holds the branch target.
402 * RHS(0) if present holds the branch condition.
403 * ->next holds where to branch to if the branch is not taken.
404 * The branch target can only be a decl...
408 /* OP_LABEL is a triple that establishes an target for branches.
409 * ->use is the list of all branches that use this label.
413 /* OP_DECL is a triple that establishes an lvalue for assignments.
414 * ->use is a list of statements that use the variable.
418 /* OP_VAR is a triple that establishes a variable of static
420 * ->use is a list of statements that use the variable.
421 * MISC(0) holds the initializer expression.
426 /* OP_PHI is a triple used in SSA form code.
427 * It is used when multiple code paths merge and a variable needs
428 * a single assignment from any of those code paths.
429 * The operation is a cross between OP_DECL and OP_WRITE, which
430 * is what OP_PHI is geneared from.
432 * RHS(x) points to the value from code path x
433 * The number of RHS entries is the number of control paths into the block
434 * in which OP_PHI resides. The elements of the array point to point
435 * to the variables OP_PHI is derived from.
437 * MISC(0) holds a pointer to the orginal OP_DECL node.
440 /* Architecture specific instructions */
443 #define OP_SET_EQ 102
444 #define OP_SET_NOTEQ 103
445 #define OP_SET_SLESS 104
446 #define OP_SET_ULESS 105
447 #define OP_SET_SMORE 106
448 #define OP_SET_UMORE 107
449 #define OP_SET_SLESSEQ 108
450 #define OP_SET_ULESSEQ 109
451 #define OP_SET_SMOREEQ 110
452 #define OP_SET_UMOREEQ 111
455 #define OP_JMP_EQ 113
456 #define OP_JMP_NOTEQ 114
457 #define OP_JMP_SLESS 115
458 #define OP_JMP_ULESS 116
459 #define OP_JMP_SMORE 117
460 #define OP_JMP_UMORE 118
461 #define OP_JMP_SLESSEQ 119
462 #define OP_JMP_ULESSEQ 120
463 #define OP_JMP_SMOREEQ 121
464 #define OP_JMP_UMOREEQ 122
466 /* Builtin operators that it is just simpler to use the compiler for */
484 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
486 unsigned char lhs, rhs, misc, targ;
489 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
497 static const struct op_info table_ops[] = {
498 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF, "smul"),
499 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF, "umul"),
500 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF, "sdiv"),
501 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF, "udiv"),
502 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF, "smod"),
503 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF, "umod"),
504 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF, "add"),
505 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF, "sub"),
506 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF, "sl"),
507 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF, "usr"),
508 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF, "ssr"),
509 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF, "and"),
510 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF, "xor"),
511 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF, "or"),
512 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF, "pos"),
513 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF, "neg"),
514 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF, "invert"),
516 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF, "eq"),
517 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "noteq"),
518 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF, "sless"),
519 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF, "uless"),
520 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF, "smore"),
521 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF, "umore"),
522 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "slesseq"),
523 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "ulesseq"),
524 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "smoreeq"),
525 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF, "umoreeq"),
526 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF, "lfalse"),
527 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF, "ltrue"),
529 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF, "load"),
530 [OP_STORE ] = OP( 1, 1, 0, 0, IMPURE, "store"),
532 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE, "noop"),
534 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE, "intconst"),
535 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
536 [OP_ADDRCONST ] = OP( 0, 1, 0, 0, PURE, "addrconst"),
538 [OP_WRITE ] = OP( 1, 1, 0, 0, PURE, "write"),
539 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF, "read"),
540 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF, "copy"),
541 [OP_PIECE ] = OP( 0, 1, 0, 0, PURE | DEF, "piece"),
542 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF, "deref"),
543 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF, "dot"),
545 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF, "val"),
546 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF, "land"),
547 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF, "lor"),
548 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF, "cond"),
549 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF, "comma"),
550 /* Call is special most it can stand in for anything so it depends on context */
551 [OP_CALL ] = OP(-1, -1, 1, 0, 0, "call"),
552 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
553 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0, "valvec"),
555 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
556 /* The number of targets for OP_BRANCH depends on context */
557 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE, "branch"),
558 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE, "label"),
559 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE, "adecl"),
560 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE, "sdecl"),
561 /* The number of RHS elements of OP_PHI depend upon context */
562 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF, "phi"),
564 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF, "cmp"),
565 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF, "test"),
566 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF, "set_eq"),
567 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF, "set_noteq"),
568 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF, "set_sless"),
569 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF, "set_uless"),
570 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF, "set_smore"),
571 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF, "set_umore"),
572 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF, "set_slesseq"),
573 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF, "set_ulesseq"),
574 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF, "set_smoreq"),
575 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF, "set_umoreq"),
576 [OP_JMP ] = OP( 0, 0, 0, 1, PURE, "jmp"),
577 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE, "jmp_eq"),
578 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE, "jmp_noteq"),
579 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE, "jmp_sless"),
580 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE, "jmp_uless"),
581 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE, "jmp_smore"),
582 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE, "jmp_umore"),
583 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE, "jmp_slesseq"),
584 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE, "jmp_ulesseq"),
585 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE, "jmp_smoreq"),
586 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE, "jmp_umoreq"),
588 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF, "__inb"),
589 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF, "__inw"),
590 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF, "__inl"),
591 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE, "__outb"),
592 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE, "__outw"),
593 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE, "__outl"),
594 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF, "__bsf"),
595 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF, "__bsr"),
596 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE, "__rdmsr"),
597 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE, "__wrmsr"),
598 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE, "__hlt"),
601 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
603 static const char *tops(int index)
605 static const char unknown[] = "unknown op";
609 if (index > OP_MAX) {
612 return table_ops[index].name;
618 struct triple_set *next;
619 struct triple *member;
628 struct triple *next, *prev;
629 struct triple_set *use;
632 unsigned short sizes;
633 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
634 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0x0f)
635 #define TRIPLE_MISC(SIZES) (((SIZES) >> 8) & 0x0f)
636 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
637 #define TRIPLE_SIZE(SIZES) \
638 ((((SIZES) >> 0) & 0x0f) + \
639 (((SIZES) >> 4) & 0x0f) + \
640 (((SIZES) >> 8) & 0x0f) + \
641 (((SIZES) >> 12) & 0x0f))
642 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
643 ((((LHS) & 0x0f) << 0) | \
644 (((RHS) & 0x0f) << 4) | \
645 (((MISC) & 0x0f) << 8) | \
646 (((TARG) & 0x0f) << 12))
647 #define TRIPLE_LHS_OFF(SIZES) (0)
648 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
649 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
650 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
651 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
652 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
653 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
654 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
655 unsigned id; /* A scratch value and finally the register */
656 #define TRIPLE_FLAG_FLATTENED 1
657 const char *filename;
664 struct hash_entry *field;
666 struct triple *param[2];
670 struct block_set *next;
671 struct block *member;
674 struct block *work_next;
675 struct block *left, *right;
676 struct triple *first, *last;
678 struct block_set *use;
679 struct block_set *idominates;
680 struct block_set *domfrontier;
682 struct block_set *ipdominates;
683 struct block_set *ipdomfrontier;
691 struct hash_entry *ident;
698 struct hash_entry *ident;
704 struct hash_entry *next;
708 struct macro *sym_define;
709 struct symbol *sym_label;
710 struct symbol *sym_struct;
711 struct symbol *sym_ident;
714 #define HASH_TABLE_SIZE 2048
716 struct compile_state {
718 struct file_state *file;
719 struct token token[4];
720 struct hash_entry *hash_table[HASH_TABLE_SIZE];
721 struct hash_entry *i_continue;
722 struct hash_entry *i_break;
724 int if_depth, if_value;
726 struct file_state *macro_file;
727 struct triple *main_function;
728 struct block *first_block, *last_block;
734 /* visibility global/local */
735 /* static/auto duration */
736 /* typedef, register, inline */
738 #define STOR_MASK 0x000f
740 #define STOR_GLOBAL 0x0001
742 #define STOR_PERM 0x0002
743 /* Storage specifiers */
744 #define STOR_AUTO 0x0000
745 #define STOR_STATIC 0x0002
746 #define STOR_EXTERN 0x0003
747 #define STOR_REGISTER 0x0004
748 #define STOR_TYPEDEF 0x0008
749 #define STOR_INLINE 0x000c
752 #define QUAL_MASK 0x0070
753 #define QUAL_NONE 0x0000
754 #define QUAL_CONST 0x0010
755 #define QUAL_VOLATILE 0x0020
756 #define QUAL_RESTRICT 0x0040
759 #define TYPE_MASK 0x1f00
760 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
761 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
762 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
763 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
764 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
765 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
766 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
767 #define TYPE_DEFAULT 0x0000
768 #define TYPE_VOID 0x0100
769 #define TYPE_CHAR 0x0200
770 #define TYPE_UCHAR 0x0300
771 #define TYPE_SHORT 0x0400
772 #define TYPE_USHORT 0x0500
773 #define TYPE_INT 0x0600
774 #define TYPE_UINT 0x0700
775 #define TYPE_LONG 0x0800
776 #define TYPE_ULONG 0x0900
777 #define TYPE_LLONG 0x0a00 /* long long */
778 #define TYPE_ULLONG 0x0b00
779 #define TYPE_FLOAT 0x0c00
780 #define TYPE_DOUBLE 0x0d00
781 #define TYPE_LDOUBLE 0x0e00 /* long double */
782 #define TYPE_STRUCT 0x1000
783 #define TYPE_ENUM 0x1100
784 #define TYPE_POINTER 0x1200
786 * type->left holds the type pointed to.
788 #define TYPE_FUNCTION 0x1300
789 /* For TYPE_FUNCTION:
790 * type->left holds the return type.
791 * type->right holds the...
793 #define TYPE_PRODUCT 0x1400
794 /* TYPE_PRODUCT is a basic building block when defining structures
795 * type->left holds the type that appears first in memory.
796 * type->right holds the type that appears next in memory.
798 #define TYPE_OVERLAP 0x1500
799 /* TYPE_OVERLAP is a basic building block when defining unions
800 * type->left and type->right holds to types that overlap
801 * each other in memory.
803 #define TYPE_ARRAY 0x1600
804 /* TYPE_ARRAY is a basic building block when definitng arrays.
805 * type->left holds the type we are an array of.
806 * type-> holds the number of elements.
809 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
813 struct type *left, *right;
815 struct hash_entry *field_ident;
816 struct hash_entry *type_ident;
819 #define MAX_REGISTERS 75
820 #define MAX_REG_EQUIVS 16
824 /* Provision for 8 register classes */
825 #define REGC_MASK ((1 << MAX_REGC) - 1)
826 #define ID_REG_CLASSES(ID) ((ID) & REGC_MASK)
827 #define ID_REG(ID) ((ID) >> MAX_REGC)
828 #define MK_REG_ID(REG, CLASSES) (((REG) << MAX_REGC) | ((CLASSES) & REGC_MASK))
830 static unsigned alloc_virtual_reg(void)
832 static unsigned virtual_reg = MAX_REGISTERS;
837 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
838 static void arch_reg_equivs(
839 struct compile_state *state, unsigned *equiv, int reg);
840 static int arch_select_free_register(
841 struct compile_state *state, char *used, int classes);
842 static unsigned arch_regc_size(struct compile_state *state, int class);
843 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
844 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
845 static const char *arch_reg_str(int reg);
847 #define DEBUG_ABORT_ON_ERROR 0x0001
848 #define DEBUG_INTERMEDIATE_CODE 0x0002
849 #define DEBUG_CONTROL_FLOW 0x0004
850 #define DEBUG_BASIC_BLOCKS 0x0008
851 #define DEBUG_FDOMINATORS 0x0010
852 #define DEBUG_RDOMINATORS 0x0020
853 #define DEBUG_TRIPLES 0x0040
854 #define DEBUG_INTERFERENCE 0x0080
855 #define DEBUG_ARCH_CODE 0x0100
856 #define DEBUG_CODE_ELIMINATION 0x0200
858 #define GLOBAL_SCOPE_DEPTH 1
860 static void compile_file(struct compile_state *old_state, char *filename, int local);
862 static int get_col(struct file_state *file)
866 ptr = file->line_start;
868 for(col = 0; ptr < end; ptr++) {
873 col = (col & ~7) + 8;
879 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
883 fprintf(fp, "%s:%d.%d: ",
884 triple->filename, triple->line, triple->col);
890 col = get_col(state->file);
891 fprintf(fp, "%s:%d.%d: ",
892 state->file->basename, state->file->line, col);
895 static void __internal_error(struct compile_state *state, struct triple *ptr,
900 loc(stderr, state, ptr);
901 fprintf(stderr, "Internal compiler error: ");
902 vfprintf(stderr, fmt, args);
903 fprintf(stderr, "\n");
909 static void __internal_warning(struct compile_state *state, struct triple *ptr,
914 loc(stderr, state, ptr);
915 fprintf(stderr, "Internal compiler warning: ");
916 vfprintf(stderr, fmt, args);
917 fprintf(stderr, "\n");
923 static void __error(struct compile_state *state, struct triple *ptr,
928 loc(stderr, state, ptr);
929 vfprintf(stderr, fmt, args);
931 fprintf(stderr, "\n");
932 if (state->debug & DEBUG_ABORT_ON_ERROR) {
938 static void __warning(struct compile_state *state, struct triple *ptr,
943 loc(stderr, state, ptr);
944 fprintf(stderr, "warning: ");
945 vfprintf(stderr, fmt, args);
946 fprintf(stderr, "\n");
950 #if DEBUG_ERROR_MESSAGES
951 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
952 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
953 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
954 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
956 # define internal_error __internal_error
957 # define internal_warning __internal_warning
958 # define error __error
959 # define warning __warning
961 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
964 static void valid_op(struct compile_state *state, int op)
966 char *fmt = "invalid op: %d";
968 internal_error(state, 0, fmt, op);
971 internal_error(state, 0, fmt, op);
975 static void valid_ins(struct compile_state *state, struct triple *ptr)
977 valid_op(state, ptr->op);
980 static void process_trigraphs(struct compile_state *state)
982 char *src, *dest, *end;
983 struct file_state *file;
985 src = dest = file->buf;
986 end = file->buf + file->size;
987 while((end - src) >= 3) {
988 if ((src[0] == '?') && (src[1] == '?')) {
991 case '=': c = '#'; break;
992 case '/': c = '\\'; break;
993 case '\'': c = '^'; break;
994 case '(': c = '['; break;
995 case ')': c = ']'; break;
996 case '!': c = '!'; break;
997 case '<': c = '{'; break;
998 case '>': c = '}'; break;
999 case '-': c = '~'; break;
1016 file->size = dest - file->buf;
1019 static void splice_lines(struct compile_state *state)
1021 char *src, *dest, *end;
1022 struct file_state *file;
1024 src = dest = file->buf;
1025 end = file->buf + file->size;
1026 while((end - src) >= 2) {
1027 if ((src[0] == '\\') && (src[1] == '\n')) {
1037 file->size = dest - file->buf;
1040 static struct type void_type;
1041 static void use_triple(struct triple *used, struct triple *user)
1043 struct triple_set **ptr, *new;
1050 if ((*ptr)->member == user) {
1053 ptr = &(*ptr)->next;
1055 /* Append new to the head of the list,
1056 * copy_func and rename_block_variables
1059 new = xcmalloc(sizeof(*new), "triple_set");
1061 new->next = used->use;
1065 static void unuse_triple(struct triple *used, struct triple *unuser)
1067 struct triple_set *use, **ptr;
1071 if (use->member == unuser) {
1081 static void push_triple(struct triple *used, struct triple *user)
1083 struct triple_set *new;
1088 /* Append new to the head of the list,
1089 * it's the only sensible behavoir for a stack.
1091 new = xcmalloc(sizeof(*new), "triple_set");
1093 new->next = used->use;
1097 static void pop_triple(struct triple *used, struct triple *unuser)
1099 struct triple_set *use, **ptr;
1103 if (use->member == unuser) {
1106 /* Only free one occurance from the stack */
1116 /* The zero triple is used as a place holder when we are removing pointers
1117 * from a triple. Having allows certain sanity checks to pass even
1118 * when the original triple that was pointed to is gone.
1120 static struct triple zero_triple = {
1121 .next = &zero_triple,
1122 .prev = &zero_triple,
1125 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1126 .id = -1, /* An invalid id */
1127 .u = { .cval = 0, },
1128 .filename = __FILE__,
1131 .param { [0] = 0, [1] = 0, },
1135 static unsigned short triple_sizes(struct compile_state *state,
1136 int op, struct type *type, int rhs_wanted)
1138 int lhs, rhs, misc, targ;
1139 valid_op(state, op);
1140 lhs = table_ops[op].lhs;
1141 rhs = table_ops[op].rhs;
1142 misc = table_ops[op].misc;
1143 targ = table_ops[op].targ;
1146 if (op == OP_CALL) {
1149 param = type->right;
1150 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1152 param = param->right;
1154 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1158 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1159 lhs = type->left->elements;
1162 else if (op == OP_VAL_VEC) {
1163 rhs = type->elements;
1165 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1168 if ((rhs < 0) || (rhs > MAX_RHS)) {
1169 internal_error(state, 0, "bad rhs");
1171 if ((lhs < 0) || (lhs > MAX_LHS)) {
1172 internal_error(state, 0, "bad lhs");
1174 if ((misc < 0) || (misc > MAX_MISC)) {
1175 internal_error(state, 0, "bad misc");
1177 if ((targ < 0) || (targ > MAX_TARG)) {
1178 internal_error(state, 0, "bad targs");
1180 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1183 static struct triple *alloc_triple(struct compile_state *state,
1184 int op, struct type *type, int rhs,
1185 const char *filename, int line, int col)
1187 size_t size, sizes, extra_count, min_count;
1189 sizes = triple_sizes(state, op, type, rhs);
1191 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1192 extra_count = TRIPLE_SIZE(sizes);
1193 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1195 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1196 ret = xcmalloc(size, "tripple");
1202 ret->filename = filename;
1208 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1212 src_rhs = TRIPLE_RHS(src->sizes);
1213 dup = alloc_triple(state, src->op, src->type, src_rhs,
1214 src->filename, src->line, src->col);
1215 memcpy(dup, src, sizeof(*src));
1216 memcpy(dup->param, src->param, src_rhs * sizeof(src->param[0]));
1220 static struct triple *new_triple(struct compile_state *state,
1221 int op, struct type *type, int rhs)
1224 const char *filename;
1230 filename = state->file->basename;
1231 line = state->file->line;
1232 col = get_col(state->file);
1234 ret = alloc_triple(state, op, type, rhs,
1235 filename, line, col);
1239 static struct triple *build_triple(struct compile_state *state,
1240 int op, struct type *type, struct triple *left, struct triple *right,
1241 const char *filename, int line, int col)
1245 ret = alloc_triple(state, op, type, -1, filename, line, col);
1246 count = TRIPLE_SIZE(ret->sizes);
1248 ret->param[0] = left;
1251 ret->param[1] = right;
1256 static struct triple *triple(struct compile_state *state,
1257 int op, struct type *type, struct triple *left, struct triple *right)
1261 ret = new_triple(state, op, type, -1);
1262 count = TRIPLE_SIZE(ret->sizes);
1264 ret->param[0] = left;
1267 ret->param[1] = right;
1272 static struct triple *branch(struct compile_state *state,
1273 struct triple *targ, struct triple *test)
1276 ret = new_triple(state, OP_BRANCH, &void_type, test?1:0);
1280 TARG(ret, 0) = targ;
1281 /* record the branch target was used */
1282 if (!targ || (targ->op != OP_LABEL)) {
1283 internal_error(state, 0, "branch not to label");
1284 use_triple(targ, ret);
1290 static void insert_triple(struct compile_state *state,
1291 struct triple *first, struct triple *ptr)
1294 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1295 internal_error(state, ptr, "expression already used");
1298 ptr->prev = first->prev;
1299 ptr->prev->next = ptr;
1300 ptr->next->prev = ptr;
1301 if ((ptr->prev->op == OP_BRANCH) &&
1302 TRIPLE_RHS(ptr->prev->sizes)) {
1303 unuse_triple(first, ptr->prev);
1304 use_triple(ptr, ptr->prev);
1309 static struct triple *pre_triple(struct compile_state *state,
1310 struct triple *base,
1311 int op, struct type *type, struct triple *left, struct triple *right)
1313 /* Careful this assumes it can do the easy thing to get the block */
1315 ret = build_triple(state, op, type, left, right,
1316 base->filename, base->line, base->col);
1317 ret->u.block = base->u.block;
1318 insert_triple(state, base, ret);
1322 static struct triple *post_triple(struct compile_state *state,
1323 struct triple *base,
1324 int op, struct type *type, struct triple *left, struct triple *right)
1326 /* Careful this assumes it can do the easy thing to get the block */
1328 ret = build_triple(state, op, type, left, right,
1329 base->filename, base->line, base->col);
1330 ret->u.block = base->u.block;
1331 insert_triple(state, base->next, ret);
1335 static struct triple *label(struct compile_state *state)
1337 /* Labels don't get a type */
1338 struct triple *result;
1339 result = triple(state, OP_LABEL, &void_type, 0, 0);
1343 static void display_triple(FILE *fp, struct triple *ins)
1345 if (ins->op == OP_INTCONST) {
1346 fprintf(fp, "(%p) %3d %-10s 0x%08lx @ %s:%d.%d\n",
1347 ins, ID_REG(ins->id), tops(ins->op), ins->u.cval,
1348 ins->filename, ins->line, ins->col);
1350 else if (ins->op == OP_SDECL) {
1351 fprintf(fp, "(%p) %3d %-10s %-10p @ %s:%d.%d\n",
1352 ins, ID_REG(ins->id), tops(ins->op), MISC(ins, 0),
1353 ins->filename, ins->line, ins->col);
1355 print_ins(state, MISC(ins, 0));
1360 fprintf(fp, "(%p) %3d %-10s",
1361 ins, ID_REG(ins->id), tops(ins->op));
1362 count = TRIPLE_SIZE(ins->sizes);
1363 for(i = 0; i < count; i++) {
1364 fprintf(fp, " %-10p", ins->param[i]);
1369 fprintf(fp, " @ %s:%d.%d\n",
1370 ins->filename, ins->line, ins->col);
1375 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1377 /* Does the triple have no side effects.
1378 * I.e. Rexecuting the triple with the same arguments
1379 * gives the same value.
1382 valid_ins(state, ins);
1383 pure = PURE_BITS(table_ops[ins->op].flags);
1384 if ((pure != PURE) && (pure != IMPURE)) {
1385 internal_error(state, 0, "Purity of %s not known\n",
1388 return pure == PURE;
1391 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1393 /* This function is used to determine which triples need
1397 valid_ins(state, ins);
1398 is_branch = (table_ops[ins->op].targ != 0);
1402 static int triple_is_def(struct compile_state *state, struct triple *ins)
1404 /* This function is used to determine which triples need
1408 valid_ins(state, ins);
1409 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1413 static struct triple **triple_iter(struct compile_state *state,
1414 size_t count, struct triple **vector,
1415 struct triple *ins, struct triple **last)
1417 struct triple **ret;
1423 else if ((last >= vector) && (last < (vector + count - 1))) {
1431 static struct triple **triple_lhs(struct compile_state *state,
1432 struct triple *ins, struct triple **last)
1434 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1438 static struct triple **triple_rhs(struct compile_state *state,
1439 struct triple *ins, struct triple **last)
1441 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1445 static struct triple **triple_misc(struct compile_state *state,
1446 struct triple *ins, struct triple **last)
1448 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1451 static struct triple **triple_targ(struct compile_state *state,
1452 struct triple *ins, struct triple **last)
1454 return triple_iter(state, TRIPLE_TARG(ins->sizes), &TARG(ins,0),
1458 static void free_triple(struct compile_state *state, struct triple *ptr)
1461 size = sizeof(*ptr) - sizeof(ptr->param) +
1462 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1463 ptr->prev->next = ptr->next;
1464 ptr->next->prev = ptr->prev;
1466 internal_error(state, ptr, "ptr->use != 0");
1468 memset(ptr, -1, size);
1472 static void release_triple(struct compile_state *state, struct triple *ptr)
1474 struct triple_set *set, *next;
1475 struct triple **expr;
1476 /* Remove ptr from use chains where it is the user */
1477 expr = triple_rhs(state, ptr, 0);
1478 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1480 unuse_triple(*expr, ptr);
1483 expr = triple_lhs(state, ptr, 0);
1484 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1486 unuse_triple(*expr, ptr);
1489 expr = triple_targ(state, ptr, 0);
1490 for(; expr; expr = triple_targ(state, ptr, expr)) {
1492 unuse_triple(*expr, ptr);
1495 /* Reomve ptr from use chains where it is used */
1496 for(set = ptr->use; set; set = next) {
1498 expr = triple_rhs(state, set->member, 0);
1499 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1501 *expr = &zero_triple;
1504 expr = triple_lhs(state, set->member, 0);
1505 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1507 *expr = &zero_triple;
1510 expr = triple_targ(state, set->member, 0);
1511 for(; expr; expr = triple_targ(state, set->member, expr)) {
1513 *expr = &zero_triple;
1516 unuse_triple(ptr, set->member);
1518 free_triple(state, ptr);
1521 static void print_triple(struct compile_state *state, struct triple *ptr);
1523 #define TOK_UNKNOWN 0
1526 #define TOK_LBRACE 3
1527 #define TOK_RBRACE 4
1531 #define TOK_LBRACKET 8
1532 #define TOK_RBRACKET 9
1533 #define TOK_LPAREN 10
1534 #define TOK_RPAREN 11
1539 #define TOK_TIMESEQ 16
1540 #define TOK_DIVEQ 17
1541 #define TOK_MODEQ 18
1542 #define TOK_PLUSEQ 19
1543 #define TOK_MINUSEQ 20
1546 #define TOK_ANDEQ 23
1547 #define TOK_XOREQ 24
1550 #define TOK_NOTEQ 27
1551 #define TOK_QUEST 28
1552 #define TOK_LOGOR 29
1553 #define TOK_LOGAND 30
1557 #define TOK_LESSEQ 34
1558 #define TOK_MOREEQ 35
1562 #define TOK_MINUS 39
1565 #define TOK_PLUSPLUS 42
1566 #define TOK_MINUSMINUS 43
1568 #define TOK_ARROW 45
1570 #define TOK_TILDE 47
1571 #define TOK_LIT_STRING 48
1572 #define TOK_LIT_CHAR 49
1573 #define TOK_LIT_INT 50
1574 #define TOK_LIT_FLOAT 51
1575 #define TOK_MACRO 52
1576 #define TOK_CONCATENATE 53
1578 #define TOK_IDENT 54
1579 #define TOK_STRUCT_NAME 55
1580 #define TOK_ENUM_CONST 56
1581 #define TOK_TYPE_NAME 57
1584 #define TOK_BREAK 59
1587 #define TOK_CONST 62
1588 #define TOK_CONTINUE 63
1589 #define TOK_DEFAULT 64
1591 #define TOK_DOUBLE 66
1594 #define TOK_EXTERN 69
1595 #define TOK_FLOAT 70
1599 #define TOK_INLINE 74
1602 #define TOK_REGISTER 77
1603 #define TOK_RESTRICT 78
1604 #define TOK_RETURN 79
1605 #define TOK_SHORT 80
1606 #define TOK_SIGNED 81
1607 #define TOK_SIZEOF 82
1608 #define TOK_STATIC 83
1609 #define TOK_STRUCT 84
1610 #define TOK_SWITCH 85
1611 #define TOK_TYPEDEF 86
1612 #define TOK_UNION 87
1613 #define TOK_UNSIGNED 88
1615 #define TOK_VOLATILE 90
1616 #define TOK_WHILE 91
1618 #define TOK_ATTRIBUTE 93
1619 #define TOK_ALIGNOF 94
1620 #define TOK_FIRST_KEYWORD TOK_AUTO
1621 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1623 #define TOK_DEFINE 100
1624 #define TOK_UNDEF 101
1625 #define TOK_INCLUDE 102
1626 #define TOK_LINE 103
1627 #define TOK_ERROR 104
1628 #define TOK_WARNING 105
1629 #define TOK_PRAGMA 106
1630 #define TOK_IFDEF 107
1631 #define TOK_IFNDEF 108
1632 #define TOK_ELIF 109
1633 #define TOK_ENDIF 110
1635 #define TOK_FIRST_MACRO TOK_DEFINE
1636 #define TOK_LAST_MACRO TOK_ENDIF
1640 static const char *tokens[] = {
1641 [TOK_UNKNOWN ] = "unknown",
1642 [TOK_SPACE ] = ":space:",
1644 [TOK_LBRACE ] = "{",
1645 [TOK_RBRACE ] = "}",
1649 [TOK_LBRACKET ] = "[",
1650 [TOK_RBRACKET ] = "]",
1651 [TOK_LPAREN ] = "(",
1652 [TOK_RPAREN ] = ")",
1654 [TOK_DOTS ] = "...",
1657 [TOK_TIMESEQ ] = "*=",
1658 [TOK_DIVEQ ] = "/=",
1659 [TOK_MODEQ ] = "%=",
1660 [TOK_PLUSEQ ] = "+=",
1661 [TOK_MINUSEQ ] = "-=",
1662 [TOK_SLEQ ] = "<<=",
1663 [TOK_SREQ ] = ">>=",
1664 [TOK_ANDEQ ] = "&=",
1665 [TOK_XOREQ ] = "^=",
1668 [TOK_NOTEQ ] = "!=",
1670 [TOK_LOGOR ] = "||",
1671 [TOK_LOGAND ] = "&&",
1675 [TOK_LESSEQ ] = "<=",
1676 [TOK_MOREEQ ] = ">=",
1683 [TOK_PLUSPLUS ] = "++",
1684 [TOK_MINUSMINUS ] = "--",
1686 [TOK_ARROW ] = "->",
1689 [TOK_LIT_STRING ] = ":string:",
1690 [TOK_IDENT ] = ":ident:",
1691 [TOK_TYPE_NAME ] = ":typename:",
1692 [TOK_LIT_CHAR ] = ":char:",
1693 [TOK_LIT_INT ] = ":integer:",
1694 [TOK_LIT_FLOAT ] = ":float:",
1696 [TOK_CONCATENATE ] = "##",
1698 [TOK_AUTO ] = "auto",
1699 [TOK_BREAK ] = "break",
1700 [TOK_CASE ] = "case",
1701 [TOK_CHAR ] = "char",
1702 [TOK_CONST ] = "const",
1703 [TOK_CONTINUE ] = "continue",
1704 [TOK_DEFAULT ] = "default",
1706 [TOK_DOUBLE ] = "double",
1707 [TOK_ELSE ] = "else",
1708 [TOK_ENUM ] = "enum",
1709 [TOK_EXTERN ] = "extern",
1710 [TOK_FLOAT ] = "float",
1712 [TOK_GOTO ] = "goto",
1714 [TOK_INLINE ] = "inline",
1716 [TOK_LONG ] = "long",
1717 [TOK_REGISTER ] = "register",
1718 [TOK_RESTRICT ] = "restrict",
1719 [TOK_RETURN ] = "return",
1720 [TOK_SHORT ] = "short",
1721 [TOK_SIGNED ] = "signed",
1722 [TOK_SIZEOF ] = "sizeof",
1723 [TOK_STATIC ] = "static",
1724 [TOK_STRUCT ] = "struct",
1725 [TOK_SWITCH ] = "switch",
1726 [TOK_TYPEDEF ] = "typedef",
1727 [TOK_UNION ] = "union",
1728 [TOK_UNSIGNED ] = "unsigned",
1729 [TOK_VOID ] = "void",
1730 [TOK_VOLATILE ] = "volatile",
1731 [TOK_WHILE ] = "while",
1733 [TOK_ATTRIBUTE ] = "__attribute__",
1734 [TOK_ALIGNOF ] = "__alignof__",
1736 [TOK_DEFINE ] = "define",
1737 [TOK_UNDEF ] = "undef",
1738 [TOK_INCLUDE ] = "include",
1739 [TOK_LINE ] = "line",
1740 [TOK_ERROR ] = "error",
1741 [TOK_WARNING ] = "warning",
1742 [TOK_PRAGMA ] = "pragma",
1743 [TOK_IFDEF ] = "ifdef",
1744 [TOK_IFNDEF ] = "ifndef",
1745 [TOK_ELIF ] = "elif",
1746 [TOK_ENDIF ] = "endif",
1751 static unsigned int hash(const char *str, int str_len)
1755 end = str + str_len;
1757 for(; str < end; str++) {
1758 hash = (hash *263) + *str;
1760 hash = hash & (HASH_TABLE_SIZE -1);
1764 static struct hash_entry *lookup(
1765 struct compile_state *state, const char *name, int name_len)
1767 struct hash_entry *entry;
1769 index = hash(name, name_len);
1770 entry = state->hash_table[index];
1772 ((entry->name_len != name_len) ||
1773 (memcmp(entry->name, name, name_len) != 0))) {
1774 entry = entry->next;
1778 /* Get a private copy of the name */
1779 new_name = xmalloc(name_len + 1, "hash_name");
1780 memcpy(new_name, name, name_len);
1781 new_name[name_len] = '\0';
1783 /* Create a new hash entry */
1784 entry = xcmalloc(sizeof(*entry), "hash_entry");
1785 entry->next = state->hash_table[index];
1786 entry->name = new_name;
1787 entry->name_len = name_len;
1789 /* Place the new entry in the hash table */
1790 state->hash_table[index] = entry;
1795 static void ident_to_keyword(struct compile_state *state, struct token *tk)
1797 struct hash_entry *entry;
1799 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
1800 (entry->tok == TOK_ENUM_CONST) ||
1801 ((entry->tok >= TOK_FIRST_KEYWORD) &&
1802 (entry->tok <= TOK_LAST_KEYWORD)))) {
1803 tk->tok = entry->tok;
1807 static void ident_to_macro(struct compile_state *state, struct token *tk)
1809 struct hash_entry *entry;
1812 (entry->tok >= TOK_FIRST_MACRO) &&
1813 (entry->tok <= TOK_LAST_MACRO)) {
1814 tk->tok = entry->tok;
1818 static void hash_keyword(
1819 struct compile_state *state, const char *keyword, int tok)
1821 struct hash_entry *entry;
1822 entry = lookup(state, keyword, strlen(keyword));
1823 if (entry && entry->tok != TOK_UNKNOWN) {
1824 die("keyword %s already hashed", keyword);
1830 struct compile_state *state, struct hash_entry *ident,
1831 struct symbol **chain, struct triple *def, struct type *type)
1834 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
1835 error(state, 0, "%s already defined", ident->name);
1837 sym = xcmalloc(sizeof(*sym), "symbol");
1841 sym->scope_depth = state->scope_depth;
1846 static void start_scope(struct compile_state *state)
1848 state->scope_depth++;
1851 static void end_scope_syms(struct symbol **chain, int depth)
1853 struct symbol *sym, *next;
1855 while(sym && (sym->scope_depth == depth)) {
1863 static void end_scope(struct compile_state *state)
1867 /* Walk through the hash table and remove all symbols
1868 * in the current scope.
1870 depth = state->scope_depth;
1871 for(i = 0; i < HASH_TABLE_SIZE; i++) {
1872 struct hash_entry *entry;
1873 entry = state->hash_table[i];
1875 end_scope_syms(&entry->sym_label, depth);
1876 end_scope_syms(&entry->sym_struct, depth);
1877 end_scope_syms(&entry->sym_ident, depth);
1878 entry = entry->next;
1881 state->scope_depth = depth - 1;
1884 static void register_keywords(struct compile_state *state)
1886 hash_keyword(state, "auto", TOK_AUTO);
1887 hash_keyword(state, "break", TOK_BREAK);
1888 hash_keyword(state, "case", TOK_CASE);
1889 hash_keyword(state, "char", TOK_CHAR);
1890 hash_keyword(state, "const", TOK_CONST);
1891 hash_keyword(state, "continue", TOK_CONTINUE);
1892 hash_keyword(state, "default", TOK_DEFAULT);
1893 hash_keyword(state, "do", TOK_DO);
1894 hash_keyword(state, "double", TOK_DOUBLE);
1895 hash_keyword(state, "else", TOK_ELSE);
1896 hash_keyword(state, "enum", TOK_ENUM);
1897 hash_keyword(state, "extern", TOK_EXTERN);
1898 hash_keyword(state, "float", TOK_FLOAT);
1899 hash_keyword(state, "for", TOK_FOR);
1900 hash_keyword(state, "goto", TOK_GOTO);
1901 hash_keyword(state, "if", TOK_IF);
1902 hash_keyword(state, "inline", TOK_INLINE);
1903 hash_keyword(state, "int", TOK_INT);
1904 hash_keyword(state, "long", TOK_LONG);
1905 hash_keyword(state, "register", TOK_REGISTER);
1906 hash_keyword(state, "restrict", TOK_RESTRICT);
1907 hash_keyword(state, "return", TOK_RETURN);
1908 hash_keyword(state, "short", TOK_SHORT);
1909 hash_keyword(state, "signed", TOK_SIGNED);
1910 hash_keyword(state, "sizeof", TOK_SIZEOF);
1911 hash_keyword(state, "static", TOK_STATIC);
1912 hash_keyword(state, "struct", TOK_STRUCT);
1913 hash_keyword(state, "switch", TOK_SWITCH);
1914 hash_keyword(state, "typedef", TOK_TYPEDEF);
1915 hash_keyword(state, "union", TOK_UNION);
1916 hash_keyword(state, "unsigned", TOK_UNSIGNED);
1917 hash_keyword(state, "void", TOK_VOID);
1918 hash_keyword(state, "volatile", TOK_VOLATILE);
1919 hash_keyword(state, "while", TOK_WHILE);
1920 hash_keyword(state, "asm", TOK_ASM);
1921 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
1922 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
1925 static void register_macro_keywords(struct compile_state *state)
1927 hash_keyword(state, "define", TOK_DEFINE);
1928 hash_keyword(state, "undef", TOK_UNDEF);
1929 hash_keyword(state, "include", TOK_INCLUDE);
1930 hash_keyword(state, "line", TOK_LINE);
1931 hash_keyword(state, "error", TOK_ERROR);
1932 hash_keyword(state, "warning", TOK_WARNING);
1933 hash_keyword(state, "pragma", TOK_PRAGMA);
1934 hash_keyword(state, "ifdef", TOK_IFDEF);
1935 hash_keyword(state, "ifndef", TOK_IFNDEF);
1936 hash_keyword(state, "elif", TOK_ELIF);
1937 hash_keyword(state, "endif", TOK_ENDIF);
1940 static int spacep(int c)
1956 static int digitp(int c)
1960 case '0': case '1': case '2': case '3': case '4':
1961 case '5': case '6': case '7': case '8': case '9':
1968 static int hexdigitp(int c)
1972 case '0': case '1': case '2': case '3': case '4':
1973 case '5': case '6': case '7': case '8': case '9':
1974 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1975 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1981 static int hexdigval(int c)
1984 if ((c >= '0') && (c <= '9')) {
1987 else if ((c >= 'A') && (c <= 'F')) {
1988 val = 10 + (c - 'A');
1990 else if ((c >= 'a') && (c <= 'f')) {
1991 val = 10 + (c - 'a');
1996 static int octdigitp(int c)
2000 case '0': case '1': case '2': case '3':
2001 case '4': case '5': case '6': case '7':
2007 static int octdigval(int c)
2010 if ((c >= '0') && (c <= '7')) {
2016 static int letterp(int c)
2020 case 'a': case 'b': case 'c': case 'd': case 'e':
2021 case 'f': case 'g': case 'h': case 'i': case 'j':
2022 case 'k': case 'l': case 'm': case 'n': case 'o':
2023 case 'p': case 'q': case 'r': case 's': case 't':
2024 case 'u': case 'v': case 'w': case 'x': case 'y':
2026 case 'A': case 'B': case 'C': case 'D': case 'E':
2027 case 'F': case 'G': case 'H': case 'I': case 'J':
2028 case 'K': case 'L': case 'M': case 'N': case 'O':
2029 case 'P': case 'Q': case 'R': case 'S': case 'T':
2030 case 'U': case 'V': case 'W': case 'X': case 'Y':
2039 static int char_value(struct compile_state *state,
2040 const signed char **strp, const signed char *end)
2042 const signed char *str;
2046 if ((c == '\\') && (str < end)) {
2048 case 'n': c = '\n'; str++; break;
2049 case 't': c = '\t'; str++; break;
2050 case 'v': c = '\v'; str++; break;
2051 case 'b': c = '\b'; str++; break;
2052 case 'r': c = '\r'; str++; break;
2053 case 'f': c = '\f'; str++; break;
2054 case 'a': c = '\a'; str++; break;
2055 case '\\': c = '\\'; str++; break;
2056 case '?': c = '?'; str++; break;
2057 case '\'': c = '\''; str++; break;
2058 case '"': c = '"'; break;
2062 while((str < end) && hexdigitp(*str)) {
2064 c += hexdigval(*str);
2068 case '0': case '1': case '2': case '3':
2069 case '4': case '5': case '6': case '7':
2071 while((str < end) && octdigitp(*str)) {
2073 c += octdigval(*str);
2078 error(state, 0, "Invalid character constant");
2086 static char *after_digits(char *ptr, char *end)
2088 while((ptr < end) && digitp(*ptr)) {
2094 static char *after_octdigits(char *ptr, char *end)
2096 while((ptr < end) && octdigitp(*ptr)) {
2102 static char *after_hexdigits(char *ptr, char *end)
2104 while((ptr < end) && hexdigitp(*ptr)) {
2110 static void save_string(struct compile_state *state,
2111 struct token *tk, char *start, char *end, const char *id)
2115 /* Create a private copy of the string */
2116 str_len = end - start + 1;
2117 str = xmalloc(str_len + 1, id);
2118 memcpy(str, start, str_len);
2119 str[str_len] = '\0';
2121 /* Store the copy in the token */
2123 tk->str_len = str_len;
2125 static void next_token(struct compile_state *state, int index)
2127 struct file_state *file;
2135 tk = &state->token[index];
2138 token = tokp = file->pos;
2139 end = file->buf + file->size;
2146 if ((tokp + 1) < end) {
2150 if ((tokp + 2) < end) {
2154 if ((tokp + 3) < end) {
2162 else if (spacep(c)) {
2164 while ((tokp < end) && spacep(c)) {
2167 file->line_start = tokp + 1;
2176 else if ((c == '/') && (c1 == '/')) {
2178 for(tokp += 2; tokp < end; tokp++) {
2182 file->line_start = tokp +1;
2188 else if ((c == '/') && (c1 == '*')) {
2192 line_start = file->line_start;
2193 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2197 line_start = tokp +1;
2199 else if ((c == '*') && (tokp[1] == '/')) {
2205 if (tok == TOK_UNKNOWN) {
2206 error(state, 0, "unterminated comment");
2209 file->line_start = line_start;
2211 /* string constants */
2212 else if ((c == '"') ||
2213 ((c == 'L') && (c1 == '"'))) {
2218 line_start = file->line_start;
2224 for(tokp += 1; tokp < end; tokp++) {
2228 line_start = tokp + 1;
2230 else if ((c == '\\') && (tokp +1 < end)) {
2233 else if (c == '"') {
2234 tok = TOK_LIT_STRING;
2238 if (tok == TOK_UNKNOWN) {
2239 error(state, 0, "unterminated string constant");
2241 if (line != file->line) {
2242 warning(state, 0, "multiline string constant");
2245 file->line_start = line_start;
2247 /* Save the string value */
2248 save_string(state, tk, token, tokp, "literal string");
2250 /* character constants */
2251 else if ((c == '\'') ||
2252 ((c == 'L') && (c1 == '\''))) {
2257 line_start = file->line_start;
2263 for(tokp += 1; tokp < end; tokp++) {
2267 line_start = tokp + 1;
2269 else if ((c == '\\') && (tokp +1 < end)) {
2272 else if (c == '\'') {
2277 if (tok == TOK_UNKNOWN) {
2278 error(state, 0, "unterminated character constant");
2280 if (line != file->line) {
2281 warning(state, 0, "multiline character constant");
2284 file->line_start = line_start;
2286 /* Save the character value */
2287 save_string(state, tk, token, tokp, "literal character");
2289 /* integer and floating constants
2295 * Floating constants
2296 * {digits}.{digits}[Ee][+-]?{digits}
2298 * {digits}[Ee][+-]?{digits}
2299 * .{digits}[Ee][+-]?{digits}
2303 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2308 next = after_digits(tokp, end);
2313 if (next[0] == '.') {
2314 new = after_digits(next, end);
2315 is_float = (new != next);
2318 if ((next[0] == 'e') || (next[0] == 'E')) {
2319 if (((next + 1) < end) &&
2320 ((next[1] == '+') || (next[1] == '-'))) {
2323 new = after_digits(next, end);
2324 is_float = (new != next);
2328 tok = TOK_LIT_FLOAT;
2329 if ((next < end) && (
2338 if (!is_float && digitp(c)) {
2340 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2341 next = after_hexdigits(tokp + 2, end);
2343 else if (c == '0') {
2344 next = after_octdigits(tokp, end);
2347 next = after_digits(tokp, end);
2349 /* crazy integer suffixes */
2351 ((next[0] == 'u') || (next[0] == 'U'))) {
2354 ((next[0] == 'l') || (next[0] == 'L'))) {
2358 else if ((next < end) &&
2359 ((next[0] == 'l') || (next[0] == 'L'))) {
2362 ((next[0] == 'u') || (next[0] == 'U'))) {
2369 /* Save the integer/floating point value */
2370 save_string(state, tk, token, tokp, "literal number");
2373 else if (letterp(c)) {
2375 for(tokp += 1; tokp < end; tokp++) {
2377 if (!letterp(c) && !digitp(c)) {
2382 tk->ident = lookup(state, token, tokp +1 - token);
2384 /* C99 alternate macro characters */
2385 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2387 tok = TOK_CONCATENATE;
2389 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2390 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2391 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2392 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2393 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2394 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2395 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2396 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2397 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2398 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2399 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2400 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2401 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2402 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2403 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2404 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2405 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2406 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2407 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2408 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2409 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2410 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2411 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2412 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2413 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2414 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2415 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2416 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2417 else if (c == ';') { tok = TOK_SEMI; }
2418 else if (c == '{') { tok = TOK_LBRACE; }
2419 else if (c == '}') { tok = TOK_RBRACE; }
2420 else if (c == ',') { tok = TOK_COMMA; }
2421 else if (c == '=') { tok = TOK_EQ; }
2422 else if (c == ':') { tok = TOK_COLON; }
2423 else if (c == '[') { tok = TOK_LBRACKET; }
2424 else if (c == ']') { tok = TOK_RBRACKET; }
2425 else if (c == '(') { tok = TOK_LPAREN; }
2426 else if (c == ')') { tok = TOK_RPAREN; }
2427 else if (c == '*') { tok = TOK_STAR; }
2428 else if (c == '>') { tok = TOK_MORE; }
2429 else if (c == '<') { tok = TOK_LESS; }
2430 else if (c == '?') { tok = TOK_QUEST; }
2431 else if (c == '|') { tok = TOK_OR; }
2432 else if (c == '&') { tok = TOK_AND; }
2433 else if (c == '^') { tok = TOK_XOR; }
2434 else if (c == '+') { tok = TOK_PLUS; }
2435 else if (c == '-') { tok = TOK_MINUS; }
2436 else if (c == '/') { tok = TOK_DIV; }
2437 else if (c == '%') { tok = TOK_MOD; }
2438 else if (c == '!') { tok = TOK_BANG; }
2439 else if (c == '.') { tok = TOK_DOT; }
2440 else if (c == '~') { tok = TOK_TILDE; }
2441 else if (c == '#') { tok = TOK_MACRO; }
2442 if (tok == TOK_MACRO) {
2443 /* Only match preprocessor directives at the start of a line */
2445 for(ptr = file->line_start; spacep(*ptr); ptr++)
2451 if (tok == TOK_UNKNOWN) {
2452 error(state, 0, "unknown token");
2455 file->pos = tokp + 1;
2457 if (tok == TOK_IDENT) {
2458 ident_to_keyword(state, tk);
2460 /* Don't return space tokens. */
2461 if (tok == TOK_SPACE) {
2466 static void compile_macro(struct compile_state *state, struct token *tk)
2468 struct file_state *file;
2469 struct hash_entry *ident;
2471 file = xmalloc(sizeof(*file), "file_state");
2472 file->basename = xstrdup(tk->ident->name);
2473 file->dirname = xstrdup("");
2474 file->size = ident->sym_define->buf_len;
2475 file->buf = xmalloc(file->size +2, file->basename);
2476 memcpy(file->buf, ident->sym_define->buf, file->size);
2477 file->buf[file->size] = '\n';
2478 file->buf[file->size + 1] = '\0';
2479 file->pos = file->buf;
2480 file->line_start = file->pos;
2482 file->prev = state->file;
2487 static int mpeek(struct compile_state *state, int index)
2491 tk = &state->token[index + 1];
2492 if (tk->tok == -1) {
2493 next_token(state, index + 1);
2497 if ((tk->tok == TOK_EOF) &&
2498 (state->file != state->macro_file) &&
2499 (state->file->prev)) {
2500 struct file_state *file = state->file;
2501 state->file = file->prev;
2502 /* file->basename is used keep it */
2503 xfree(file->dirname);
2506 next_token(state, index + 1);
2509 else if (tk->ident && tk->ident->sym_define) {
2510 compile_macro(state, tk);
2511 next_token(state, index + 1);
2515 /* Don't show the token on the next line */
2516 if (state->macro_line < state->macro_file->line) {
2519 return state->token[index +1].tok;
2522 static void meat(struct compile_state *state, int index, int tok)
2526 next_tok = mpeek(state, index);
2527 if (next_tok != tok) {
2528 const char *name1, *name2;
2529 name1 = tokens[next_tok];
2531 if (next_tok == TOK_IDENT) {
2532 name2 = state->token[index + 1].ident->name;
2534 error(state, 0, "found %s %s expected %s",
2535 name1, name2, tokens[tok]);
2537 /* Free the old token value */
2538 if (state->token[index].str_len) {
2539 memset((void *)(state->token[index].val.str), -1,
2540 state->token[index].str_len);
2541 xfree(state->token[index].val.str);
2543 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2544 state->token[i] = state->token[i + 1];
2546 memset(&state->token[i], 0, sizeof(state->token[i]));
2547 state->token[i].tok = -1;
2550 static long_t mcexpr(struct compile_state *state, int index);
2552 static long_t mprimary_expr(struct compile_state *state, int index)
2556 tok = mpeek(state, index);
2557 while(state->token[index + 1].ident &&
2558 state->token[index + 1].ident->sym_define) {
2559 meat(state, index, tok);
2560 compile_macro(state, &state->token[index]);
2561 tok = mpeek(state, index);
2565 meat(state, index, TOK_LPAREN);
2566 val = mcexpr(state, index);
2567 meat(state, index, TOK_RPAREN);
2572 meat(state, index, TOK_LIT_INT);
2574 val = strtol(state->token[index].val.str, &end, 0);
2575 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2576 (errno == ERANGE)) {
2577 error(state, 0, "Integer constant to large");
2582 meat(state, index, TOK_LIT_INT);
2587 static long_t munary_expr(struct compile_state *state, int index)
2590 switch(mpeek(state, index)) {
2592 meat(state, index, TOK_PLUS);
2593 val = munary_expr(state, index);
2597 meat(state, index, TOK_MINUS);
2598 val = munary_expr(state, index);
2602 meat(state, index, TOK_BANG);
2603 val = munary_expr(state, index);
2607 meat(state, index, TOK_BANG);
2608 val = munary_expr(state, index);
2612 val = mprimary_expr(state, index);
2618 static long_t mmul_expr(struct compile_state *state, int index)
2622 val = munary_expr(state, index);
2626 switch(mpeek(state, index)) {
2628 meat(state, index, TOK_STAR);
2629 right = munary_expr(state, index);
2633 meat(state, index, TOK_DIV);
2634 right = munary_expr(state, index);
2638 meat(state, index, TOK_MOD);
2639 right = munary_expr(state, index);
2651 static long_t madd_expr(struct compile_state *state, int index)
2655 val = mmul_expr(state, index);
2659 switch(mpeek(state, index)) {
2661 meat(state, index, TOK_PLUS);
2662 right = mmul_expr(state, index);
2666 meat(state, index, TOK_MINUS);
2667 right = mmul_expr(state, index);
2679 static long_t mshift_expr(struct compile_state *state, int index)
2683 val = madd_expr(state, index);
2687 switch(mpeek(state, index)) {
2689 meat(state, index, TOK_SL);
2690 right = madd_expr(state, index);
2694 meat(state, index, TOK_SR);
2695 right = madd_expr(state, index);
2707 static long_t mrel_expr(struct compile_state *state, int index)
2711 val = mshift_expr(state, index);
2715 switch(mpeek(state, index)) {
2717 meat(state, index, TOK_LESS);
2718 right = mshift_expr(state, index);
2722 meat(state, index, TOK_MORE);
2723 right = mshift_expr(state, index);
2727 meat(state, index, TOK_LESSEQ);
2728 right = mshift_expr(state, index);
2732 meat(state, index, TOK_MOREEQ);
2733 right = mshift_expr(state, index);
2744 static long_t meq_expr(struct compile_state *state, int index)
2748 val = mrel_expr(state, index);
2752 switch(mpeek(state, index)) {
2754 meat(state, index, TOK_EQEQ);
2755 right = mrel_expr(state, index);
2759 meat(state, index, TOK_NOTEQ);
2760 right = mrel_expr(state, index);
2771 static long_t mand_expr(struct compile_state *state, int index)
2774 val = meq_expr(state, index);
2775 if (mpeek(state, index) == TOK_AND) {
2777 meat(state, index, TOK_AND);
2778 right = meq_expr(state, index);
2784 static long_t mxor_expr(struct compile_state *state, int index)
2787 val = mand_expr(state, index);
2788 if (mpeek(state, index) == TOK_XOR) {
2790 meat(state, index, TOK_XOR);
2791 right = mand_expr(state, index);
2797 static long_t mor_expr(struct compile_state *state, int index)
2800 val = mxor_expr(state, index);
2801 if (mpeek(state, index) == TOK_OR) {
2803 meat(state, index, TOK_OR);
2804 right = mxor_expr(state, index);
2810 static long_t mland_expr(struct compile_state *state, int index)
2813 val = mor_expr(state, index);
2814 if (mpeek(state, index) == TOK_LOGAND) {
2816 meat(state, index, TOK_LOGAND);
2817 right = mor_expr(state, index);
2822 static long_t mlor_expr(struct compile_state *state, int index)
2825 val = mland_expr(state, index);
2826 if (mpeek(state, index) == TOK_LOGOR) {
2828 meat(state, index, TOK_LOGOR);
2829 right = mland_expr(state, index);
2835 static long_t mcexpr(struct compile_state *state, int index)
2837 return mlor_expr(state, index);
2839 static void preprocess(struct compile_state *state, int index)
2841 /* Doing much more with the preprocessor would require
2842 * a parser and a major restructuring.
2843 * Postpone that for later.
2845 struct file_state *file;
2851 tk = &state->token[index];
2852 state->macro_line = line = file->line;
2853 state->macro_file = file;
2855 next_token(state, index);
2856 ident_to_macro(state, tk);
2857 if (tk->tok == TOK_IDENT) {
2858 error(state, 0, "undefined preprocessing directive `%s'",
2865 if (state->if_value < 0) {
2868 warning(state, 0, "Ignoring preprocessor directive: %s",
2872 error(state, 0, "#elif not supported");
2873 #warning "FIXME multiple #elif and #else in an #if do not work properly"
2874 if (state->if_depth == 0) {
2875 error(state, 0, "#elif without #if");
2877 /* If the #if was taken the #elif just disables the following code */
2878 if (state->if_value >= 0) {
2879 state->if_value = - state->if_value;
2881 /* If the previous #if was not taken see if the #elif enables the
2884 else if ((state->if_value < 0) &&
2885 (state->if_depth == - state->if_value))
2887 if (mcexpr(state, index) != 0) {
2888 state->if_value = state->if_depth;
2891 state->if_value = - state->if_depth;
2897 if (state->if_value < 0) {
2900 if (mcexpr(state, index) != 0) {
2901 state->if_value = state->if_depth;
2904 state->if_value = - state->if_depth;
2909 if (state->if_value < 0) {
2912 next_token(state, index);
2913 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2914 error(state, 0, "Invalid macro name");
2916 if (tk->ident->sym_define == 0) {
2917 state->if_value = state->if_depth;
2920 state->if_value = - state->if_depth;
2925 if (state->if_value < 0) {
2928 next_token(state, index);
2929 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2930 error(state, 0, "Invalid macro name");
2932 if (tk->ident->sym_define != 0) {
2933 state->if_value = state->if_depth;
2936 state->if_value = - state->if_depth;
2940 if (state->if_depth == 0) {
2941 error(state, 0, "#else without #if");
2943 if ((state->if_value >= 0) ||
2944 ((state->if_value < 0) &&
2945 (state->if_depth == -state->if_value)))
2947 state->if_value = - state->if_value;
2951 if (state->if_depth == 0) {
2952 error(state, 0, "#endif without #if");
2954 if ((state->if_value >= 0) ||
2955 ((state->if_value < 0) &&
2956 (state->if_depth == -state->if_value)))
2958 state->if_value = state->if_depth - 1;
2964 struct hash_entry *ident;
2965 struct macro *macro;
2968 if (state->if_value < 0) /* quit early when #if'd out */
2971 meat(state, index, TOK_IDENT);
2975 if (*file->pos == '(') {
2976 #warning "FIXME macros with arguments not supported"
2977 error(state, 0, "Macros with arguments not supported");
2980 /* Find the end of the line to get an estimate of
2981 * the macro's length.
2983 for(ptr = file->pos; *ptr != '\n'; ptr++)
2986 if (ident->sym_define != 0) {
2987 error(state, 0, "macro %s already defined\n", ident->name);
2989 macro = xmalloc(sizeof(*macro), "macro");
2990 macro->ident = ident;
2991 macro->buf_len = ptr - file->pos +1;
2992 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
2994 memcpy(macro->buf, file->pos, macro->buf_len);
2995 macro->buf[macro->buf_len] = '\n';
2996 macro->buf[macro->buf_len +1] = '\0';
2998 ident->sym_define = macro;
3005 /* Find the end of the line */
3006 for(end = file->pos; *end != '\n'; end++)
3008 len = (end - file->pos);
3009 if (state->if_value >= 0) {
3010 error(state, 0, "%*.*s", len, len, file->pos);
3019 /* Find the end of the line */
3020 for(end = file->pos; *end != '\n'; end++)
3022 len = (end - file->pos);
3023 if (state->if_value >= 0) {
3024 warning(state, 0, "%*.*s", len, len, file->pos);
3036 next_token(state, index);
3037 if (tk->tok == TOK_LIT_STRING) {
3040 name = xmalloc(tk->str_len, "include");
3041 token = tk->val.str +1;
3042 name_len = tk->str_len -2;
3043 if (*token == '"') {
3047 memcpy(name, token, name_len);
3048 name[name_len] = '\0';
3051 else if (tk->tok == TOK_LESS) {
3054 for(end = start; *end != '\n'; end++) {
3060 error(state, 0, "Unterminated included directive");
3062 name = xmalloc(end - start + 1, "include");
3063 memcpy(name, start, end - start);
3064 name[end - start] = '\0';
3069 error(state, 0, "Invalid include directive");
3071 /* Error if there are any characters after the include */
3072 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3073 if (!isspace(*ptr)) {
3074 error(state, 0, "garbage after include directive");
3077 if (state->if_value >= 0) {
3078 compile_file(state, name, local);
3081 next_token(state, index);
3085 /* Ignore # without a following ident */
3086 if (tk->tok == TOK_IDENT) {
3087 error(state, 0, "Invalid preprocessor directive: %s",
3092 /* Consume the rest of the macro line */
3094 tok = mpeek(state, index);
3095 meat(state, index, tok);
3096 } while(tok != TOK_EOF);
3100 static void token(struct compile_state *state, int index)
3102 struct file_state *file;
3106 tk = &state->token[index];
3107 next_token(state, index);
3111 if (tk->tok == TOK_EOF && file->prev) {
3112 state->file = file->prev;
3113 /* file->basename is used keep it */
3114 xfree(file->dirname);
3117 next_token(state, index);
3120 else if (tk->tok == TOK_MACRO) {
3121 preprocess(state, index);
3124 else if (tk->ident && tk->ident->sym_define) {
3125 compile_macro(state, tk);
3126 next_token(state, index);
3129 else if (state->if_value < 0) {
3130 next_token(state, index);
3136 static int peek(struct compile_state *state)
3138 if (state->token[1].tok == -1) {
3141 return state->token[1].tok;
3144 static int peek2(struct compile_state *state)
3146 if (state->token[1].tok == -1) {
3149 if (state->token[2].tok == -1) {
3152 return state->token[2].tok;
3155 static void eat(struct compile_state *state, int tok)
3159 next_tok = peek(state);
3160 if (next_tok != tok) {
3161 const char *name1, *name2;
3162 name1 = tokens[next_tok];
3164 if (next_tok == TOK_IDENT) {
3165 name2 = state->token[1].ident->name;
3167 error(state, 0, "\tfound %s %s expected %s",
3168 name1, name2 ,tokens[tok]);
3170 /* Free the old token value */
3171 if (state->token[0].str_len) {
3172 xfree((void *)(state->token[0].val.str));
3174 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3175 state->token[i] = state->token[i + 1];
3177 memset(&state->token[i], 0, sizeof(state->token[i]));
3178 state->token[i].tok = -1;
3181 #warning "FIXME do not hardcode the include paths"
3182 static char *include_paths[] = {
3183 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3184 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3185 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3189 static void compile_file(struct compile_state *state, char *filename, int local)
3192 char *subdir, *base;
3194 struct file_state *file;
3196 file = xmalloc(sizeof(*file), "file_state");
3198 base = strrchr(filename, '/');
3201 subdir_len = base - filename;
3208 basename = xmalloc(strlen(base) +1, "basename");
3209 strcpy(basename, base);
3210 file->basename = basename;
3212 if (getcwd(cwd, sizeof(cwd)) == 0) {
3213 die("cwd buffer to small");
3216 if (subdir[0] == '/') {
3217 file->dirname = xmalloc(subdir_len + 1, "dirname");
3218 memcpy(file->dirname, subdir, subdir_len);
3219 file->dirname[subdir_len] = '\0';
3225 /* Find the appropriate directory... */
3227 if (!state->file && exists(cwd, filename)) {
3230 if (local && state->file && exists(state->file->dirname, filename)) {
3231 dir = state->file->dirname;
3233 for(path = include_paths; !dir && *path; path++) {
3234 if (exists(*path, filename)) {
3239 error(state, 0, "Cannot find `%s'\n", filename);
3241 dirlen = strlen(dir);
3242 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3243 memcpy(file->dirname, dir, dirlen);
3244 file->dirname[dirlen] = '/';
3245 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3246 file->dirname[dirlen + 1 + subdir_len] = '\0';
3248 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3251 file->pos = file->buf;
3252 file->line_start = file->pos;
3255 file->prev = state->file;
3258 process_trigraphs(state);
3259 splice_lines(state);
3262 /* Type helper functions */
3264 static struct type *new_type(
3265 unsigned int type, struct type *left, struct type *right)
3267 struct type *result;
3268 result = xmalloc(sizeof(*result), "type");
3269 result->type = type;
3270 result->left = left;
3271 result->right = right;
3272 result->field_ident = 0;
3273 result->type_ident = 0;
3277 static struct type *clone_type(unsigned int specifiers, struct type *old)
3279 struct type *result;
3280 result = xmalloc(sizeof(*result), "type");
3281 memcpy(result, old, sizeof(*result));
3282 result->type &= TYPE_MASK;
3283 result->type |= specifiers;
3287 #define SIZEOF_SHORT 2
3288 #define SIZEOF_INT 4
3289 #define SIZEOF_LONG (sizeof(long_t))
3291 #define ALIGNOF_SHORT 2
3292 #define ALIGNOF_INT 4
3293 #define ALIGNOF_LONG (sizeof(long_t))
3295 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3296 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3297 static inline ulong_t mask_uint(ulong_t x)
3299 if (SIZEOF_INT < SIZEOF_LONG) {
3300 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3305 #define MASK_UINT(X) (mask_uint(X))
3306 #define MASK_ULONG(X) (X)
3308 static struct type void_type = { .type = TYPE_VOID };
3309 static struct type char_type = { .type = TYPE_CHAR };
3310 static struct type uchar_type = { .type = TYPE_UCHAR };
3311 static struct type short_type = { .type = TYPE_SHORT };
3312 static struct type ushort_type = { .type = TYPE_USHORT };
3313 static struct type int_type = { .type = TYPE_INT };
3314 static struct type uint_type = { .type = TYPE_UINT };
3315 static struct type long_type = { .type = TYPE_LONG };
3316 static struct type ulong_type = { .type = TYPE_ULONG };
3318 static struct triple *variable(struct compile_state *state, struct type *type)
3320 struct triple *result;
3321 if ((type->type & STOR_MASK) != STOR_PERM) {
3322 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3323 result = triple(state, OP_ADECL, type, 0, 0);
3326 struct triple **vector;
3328 result = new_triple(state, OP_VAL_VEC, type, -1);
3329 vector = &result->param[0];
3333 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3334 vector[index] = variable(state, field->left);
3335 field = field->right;
3338 vector[index] = variable(state, field);
3342 result = triple(state, OP_SDECL, type, 0, 0);
3347 static void stor_of(FILE *fp, struct type *type)
3349 switch(type->type & STOR_MASK) {
3351 fprintf(fp, "auto ");
3354 fprintf(fp, "static ");
3357 fprintf(fp, "extern ");
3360 fprintf(fp, "register ");
3363 fprintf(fp, "typedef ");
3366 fprintf(fp, "inline ");
3370 static void qual_of(FILE *fp, struct type *type)
3372 if (type->type & QUAL_CONST) {
3373 fprintf(fp, " const");
3375 if (type->type & QUAL_VOLATILE) {
3376 fprintf(fp, " volatile");
3378 if (type->type & QUAL_RESTRICT) {
3379 fprintf(fp, " restrict");
3383 static void name_of(FILE *fp, struct type *type)
3386 switch(type->type & TYPE_MASK) {
3388 fprintf(fp, "void");
3392 fprintf(fp, "signed char");
3396 fprintf(fp, "unsigned char");
3400 fprintf(fp, "signed short");
3404 fprintf(fp, "unsigned short");
3408 fprintf(fp, "signed int");
3412 fprintf(fp, "unsigned int");
3416 fprintf(fp, "signed long");
3420 fprintf(fp, "unsigned long");
3424 name_of(fp, type->left);
3430 name_of(fp, type->left);
3432 name_of(fp, type->right);
3435 fprintf(fp, "enum %s", type->type_ident->name);
3439 fprintf(fp, "struct %s", type->type_ident->name);
3444 name_of(fp, type->left);
3445 fprintf(fp, " (*)(");
3446 name_of(fp, type->right);
3451 name_of(fp, type->left);
3452 fprintf(fp, " [%ld]", type->elements);
3455 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3460 static size_t align_of(struct compile_state *state, struct type *type)
3464 switch(type->type & TYPE_MASK) {
3474 align = ALIGNOF_SHORT;
3479 align = ALIGNOF_INT;
3484 align = ALIGNOF_LONG;
3489 size_t left_align, right_align;
3490 left_align = align_of(state, type->left);
3491 right_align = align_of(state, type->right);
3492 align = (left_align >= right_align) ? left_align : right_align;
3496 align = align_of(state, type->left);
3499 align = align_of(state, type->left);
3502 error(state, 0, "alignof not yet defined for type\n");
3508 static size_t size_of(struct compile_state *state, struct type *type)
3512 switch(type->type & TYPE_MASK) {
3522 size = SIZEOF_SHORT;
3537 size = size_of(state, type->left);
3538 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3540 align = align_of(state, type->left);
3541 pad = align - (size % align);
3542 size = size + pad + size_of(state, type->left);
3544 align = align_of(state, type->right);
3545 pad = align - (size % align);
3546 size = size + pad + sizeof(type->right);
3551 size_t size_left, size_right;
3552 size_left = size_of(state, type->left);
3553 size_right = size_of(state, type->right);
3554 size = (size_left >= size_right)? size_left : size_right;
3558 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3559 internal_error(state, 0, "Invalid array type");
3561 size = size_of(state, type->left) * type->elements;
3565 size = size_of(state, type->left);
3568 error(state, 0, "sizeof not yet defined for type\n");
3574 static size_t field_offset(struct compile_state *state,
3575 struct type *type, struct hash_entry *field)
3577 size_t size, align, pad;
3578 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3579 internal_error(state, 0, "field_offset only works on structures");
3583 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3584 if (type->left->field_ident == field) {
3587 size += size_of(state, type->left);
3589 align = align_of(state, type->left);
3590 pad = align - (size % align);
3593 if (type->field_ident != field) {
3594 internal_error(state, 0, "field_offset: member %s not present",
3600 static struct type *field_type(struct compile_state *state,
3601 struct type *type, struct hash_entry *field)
3603 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3604 internal_error(state, 0, "field_type only works on structures");
3607 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3608 if (type->left->field_ident == field) {
3614 if (type->field_ident != field) {
3615 internal_error(state, 0, "field_type: member %s not present",
3621 static struct triple *struct_field(struct compile_state *state,
3622 struct triple *decl, struct hash_entry *field)
3624 struct triple **vector;
3628 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3631 if (decl->op != OP_VAL_VEC) {
3632 internal_error(state, 0, "Invalid struct variable");
3635 internal_error(state, 0, "Missing structure field");
3638 vector = &RHS(decl, 0);
3640 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3641 if (type->left->field_ident == field) {
3648 if (type->field_ident != field) {
3649 internal_error(state, 0, "field %s not found?", field->name);
3651 return vector[index];
3654 static void arrays_complete(struct compile_state *state, struct type *type)
3656 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3657 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3658 error(state, 0, "array size not specified");
3660 arrays_complete(state, type->left);
3664 static unsigned int do_integral_promotion(unsigned int type)
3667 if (TYPE_INTEGER(type) &&
3668 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3674 static unsigned int do_arithmetic_conversion(
3675 unsigned int left, unsigned int right)
3679 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3680 return TYPE_LDOUBLE;
3682 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3685 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3688 left = do_integral_promotion(left);
3689 right = do_integral_promotion(right);
3690 /* If both operands have the same size done */
3691 if (left == right) {
3694 /* If both operands have the same signedness pick the larger */
3695 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3696 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3698 /* If the signed type can hold everything use it */
3699 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3702 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3705 /* Convert to the unsigned type with the same rank as the signed type */
3706 else if (TYPE_SIGNED(left)) {
3707 return TYPE_MKUNSIGNED(left);
3710 return TYPE_MKUNSIGNED(right);
3714 /* see if two types are the same except for qualifiers */
3715 static int equiv_types(struct type *left, struct type *right)
3718 /* Error if the basic types do not match */
3719 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3722 type = left->type & TYPE_MASK;
3723 /* if the basic types match and it is an arithmetic type we are done */
3724 if (TYPE_ARITHMETIC(type)) {
3727 /* If it is a pointer type recurse and keep testing */
3728 if (type == TYPE_POINTER) {
3729 return equiv_types(left->left, right->left);
3731 else if (type == TYPE_ARRAY) {
3732 return (left->elements == right->elements) &&
3733 equiv_types(left->left, right->left);
3735 /* test for struct/union equality */
3736 else if (type == TYPE_STRUCT) {
3737 return left->type_ident == right->type_ident;
3739 /* Test for equivalent functions */
3740 else if (type == TYPE_FUNCTION) {
3741 return equiv_types(left->left, right->left) &&
3742 equiv_types(left->right, right->right);
3744 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3745 else if (type == TYPE_PRODUCT) {
3746 return equiv_types(left->left, right->left) &&
3747 equiv_types(left->right, right->right);
3749 /* We should see TYPE_OVERLAP */
3755 static int equiv_ptrs(struct type *left, struct type *right)
3757 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3758 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3761 return equiv_types(left->left, right->left);
3764 static struct type *compatible_types(struct type *left, struct type *right)
3766 struct type *result;
3767 unsigned int type, qual_type;
3768 /* Error if the basic types do not match */
3769 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3772 type = left->type & TYPE_MASK;
3773 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3775 /* if the basic types match and it is an arithmetic type we are done */
3776 if (TYPE_ARITHMETIC(type)) {
3777 result = new_type(qual_type, 0, 0);
3779 /* If it is a pointer type recurse and keep testing */
3780 else if (type == TYPE_POINTER) {
3781 result = compatible_types(left->left, right->left);
3783 result = new_type(qual_type, result, 0);
3786 /* test for struct/union equality */
3787 else if (type == TYPE_STRUCT) {
3788 if (left->type_ident == right->type_ident) {
3792 /* Test for equivalent functions */
3793 else if (type == TYPE_FUNCTION) {
3794 struct type *lf, *rf;
3795 lf = compatible_types(left->left, right->left);
3796 rf = compatible_types(left->right, right->right);
3798 result = new_type(qual_type, lf, rf);
3801 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3802 else if (type == TYPE_PRODUCT) {
3803 struct type *lf, *rf;
3804 lf = compatible_types(left->left, right->left);
3805 rf = compatible_types(left->right, right->right);
3807 result = new_type(qual_type, lf, rf);
3811 /* Nothing else is compatible */
3816 static struct type *compatible_ptrs(struct type *left, struct type *right)
3818 struct type *result;
3819 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3820 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3823 result = compatible_types(left->left, right->left);
3825 unsigned int qual_type;
3826 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3827 result = new_type(qual_type, result, 0);
3832 static struct triple *integral_promotion(
3833 struct compile_state *state, struct triple *def)
3837 /* As all operations are carried out in registers
3838 * the values are converted on load I just convert
3839 * logical type of the operand.
3841 if (TYPE_INTEGER(type->type)) {
3842 unsigned int int_type;
3843 int_type = type->type & ~TYPE_MASK;
3844 int_type |= do_integral_promotion(type->type);
3845 if (int_type != type->type) {
3846 def->type = new_type(int_type, 0, 0);
3853 static void arithmetic(struct compile_state *state, struct triple *def)
3855 if (!TYPE_ARITHMETIC(def->type->type)) {
3856 error(state, def, "arithmetic type expexted");
3860 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
3862 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
3863 error(state, def, "pointer or arithmetic type expected");
3867 static int is_integral(struct triple *ins)
3869 return TYPE_INTEGER(ins->type->type);
3872 static void integral(struct compile_state *state, struct triple *def)
3874 if (!is_integral(def)) {
3875 error(state, 0, "integral type expected");
3880 static void bool(struct compile_state *state, struct triple *def)
3882 if (!TYPE_ARITHMETIC(def->type->type) &&
3883 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
3884 error(state, 0, "arithmetic or pointer type expected");
3888 static int is_signed(struct type *type)
3890 return !!TYPE_SIGNED(type->type);
3893 /* Is this value located in a register otherwise it must be in memory */
3894 static int is_in_reg(struct compile_state *state, struct triple *def)
3897 if (def->op == OP_ADECL) {
3900 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
3903 else if (def->op == OP_VAL_VEC) {
3904 in_reg = is_in_reg(state, RHS(def, 0));
3906 else if (def->op == OP_DOT) {
3907 in_reg = is_in_reg(state, RHS(def, 0));
3910 internal_error(state, 0, "unknown expr storage location");
3916 /* Is this a stable variable location otherwise it must be a temporary */
3917 static int is_stable(struct compile_state *state, struct triple *def)
3924 if ((def->op == OP_ADECL) ||
3925 (def->op == OP_SDECL) ||
3926 (def->op == OP_DEREF) ||
3927 (def->op == OP_BLOBCONST)) {
3930 else if (def->op == OP_DOT) {
3931 ret = is_stable(state, RHS(def, 0));
3933 else if (def->op == OP_VAL_VEC) {
3934 struct triple **vector;
3937 vector = &RHS(def, 0);
3938 for(i = 0; i < def->type->elements; i++) {
3939 if (!is_stable(state, vector[i])) {
3948 static int is_lvalue(struct compile_state *state, struct triple *def)
3955 if (!is_stable(state, def)) {
3958 if (def->type->type & QUAL_CONST) {
3961 else if (def->op == OP_DOT) {
3962 ret = is_lvalue(state, RHS(def, 0));
3967 static void lvalue(struct compile_state *state, struct triple *def)
3970 internal_error(state, def, "nothing where lvalue expected?");
3972 if (!is_lvalue(state, def)) {
3973 error(state, def, "lvalue expected");
3977 static int is_pointer(struct triple *def)
3979 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
3982 static void pointer(struct compile_state *state, struct triple *def)
3984 if (!is_pointer(def)) {
3985 error(state, def, "pointer expected");
3989 static struct triple *int_const(
3990 struct compile_state *state, struct type *type, ulong_t value)
3992 struct triple *result;
3993 switch(type->type & TYPE_MASK) {
3995 case TYPE_INT: case TYPE_UINT:
3996 case TYPE_LONG: case TYPE_ULONG:
3999 internal_error(state, 0, "constant for unkown type");
4001 result = triple(state, OP_INTCONST, type, 0, 0);
4002 result->u.cval = value;
4007 static struct triple *do_mk_addr_expr(struct compile_state *state,
4008 struct triple *expr, struct type *type, ulong_t offset)
4010 struct triple *result;
4011 lvalue(state, expr);
4014 if (expr->op == OP_ADECL) {
4015 error(state, expr, "address of auto variables not supported");
4017 else if (expr->op == OP_SDECL) {
4018 result = triple(state, OP_ADDRCONST, type, expr, 0);
4019 result->u.cval = offset;
4021 else if (expr->op == OP_DEREF) {
4022 result = triple(state, OP_ADD, type,
4024 int_const(state, &ulong_type, offset));
4029 static struct triple *mk_addr_expr(
4030 struct compile_state *state, struct triple *expr, ulong_t offset)
4035 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4038 return do_mk_addr_expr(state, expr, type, offset);
4041 static struct triple *mk_deref_expr(
4042 struct compile_state *state, struct triple *expr)
4044 struct type *base_type;
4045 pointer(state, expr);
4046 base_type = expr->type->left;
4047 if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4049 "Only pointer and arithmetic values can be dereferenced");
4051 return triple(state, OP_DEREF, base_type, expr, 0);
4054 static struct triple *deref_field(
4055 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4057 struct triple *result;
4058 struct type *type, *member;
4060 internal_error(state, 0, "No field passed to deref_field");
4064 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4065 error(state, 0, "request for member %s in something not a struct or union",
4068 member = type->left;
4069 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4070 if (member->left->field_ident == field) {
4071 member = member->left;
4074 member = member->right;
4076 if (member->field_ident != field) {
4077 error(state, 0, "%s is not a member", field->name);
4079 if ((type->type & STOR_MASK) == STOR_PERM) {
4080 /* Do the pointer arithmetic to get a deref the field */
4082 offset = field_offset(state, type, field);
4083 result = do_mk_addr_expr(state, expr, member, offset);
4084 result = mk_deref_expr(state, result);
4087 /* Find the variable for the field I want. */
4088 result = triple(state, OP_DOT,
4089 field_type(state, type, field), expr, 0);
4090 result->u.field = field;
4095 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4101 if (!is_stable(state, def)) {
4104 /* Tranform an array to a pointer to the first element */
4105 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4106 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4109 TYPE_POINTER | (def->type->type & QUAL_MASK),
4110 def->type->left, 0);
4111 return triple(state, OP_ADDRCONST, type, def, 0);
4113 if (is_in_reg(state, def)) {
4118 return triple(state, op, def->type, def, 0);
4121 static void write_compatible(struct compile_state *state,
4122 struct type *dest, struct type *rval)
4125 /* Both operands have arithmetic type */
4126 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4129 /* One operand is a pointer and the other is a pointer to void */
4130 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4131 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4132 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4133 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4136 /* If both types are the same without qualifiers we are good */
4137 else if (equiv_ptrs(dest, rval)) {
4140 /* test for struct/union equality */
4141 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4142 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4143 (dest->type_ident == rval->type_ident)) {
4147 error(state, 0, "Incompatible types in assignment");
4151 static struct triple *write_expr(
4152 struct compile_state *state, struct triple *dest, struct triple *rval)
4159 internal_error(state, 0, "missing rval");
4162 if (rval->op == OP_LIST) {
4163 internal_error(state, 0, "expression of type OP_LIST?");
4165 if (!is_lvalue(state, dest)) {
4166 internal_error(state, 0, "writing to a non lvalue?");
4169 write_compatible(state, dest->type, rval->type);
4171 /* Now figure out which assignment operator to use */
4173 if (is_in_reg(state, dest)) {
4178 def = triple(state, op, dest->type, dest, rval);
4182 static struct triple *init_expr(
4183 struct compile_state *state, struct triple *dest, struct triple *rval)
4189 internal_error(state, 0, "missing rval");
4191 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4192 rval = read_expr(state, rval);
4193 def = write_expr(state, dest, rval);
4196 /* Fill in the array size if necessary */
4197 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4198 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4199 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4200 dest->type->elements = rval->type->elements;
4203 if (!equiv_types(dest->type, rval->type)) {
4204 error(state, 0, "Incompatible types in inializer");
4206 MISC(dest, 0) = rval;
4211 struct type *arithmetic_result(
4212 struct compile_state *state, struct triple *left, struct triple *right)
4215 /* Sanity checks to ensure I am working with arithmetic types */
4216 arithmetic(state, left);
4217 arithmetic(state, right);
4219 do_arithmetic_conversion(
4221 right->type->type), 0, 0);
4225 struct type *ptr_arithmetic_result(
4226 struct compile_state *state, struct triple *left, struct triple *right)
4229 /* Sanity checks to ensure I am working with the proper types */
4230 ptr_arithmetic(state, left);
4231 arithmetic(state, right);
4232 if (TYPE_ARITHMETIC(left->type->type) &&
4233 TYPE_ARITHMETIC(right->type->type)) {
4234 type = arithmetic_result(state, left, right);
4236 else if (TYPE_PTR(left->type->type)) {
4240 internal_error(state, 0, "huh?");
4247 /* boolean helper function */
4249 static struct triple *ltrue_expr(struct compile_state *state,
4250 struct triple *expr)
4253 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4254 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4255 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4256 /* If the expression is already boolean do nothing */
4259 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4265 static struct triple *lfalse_expr(struct compile_state *state,
4266 struct triple *expr)
4268 return triple(state, OP_LFALSE, &int_type, expr, 0);
4271 static struct triple *cond_expr(
4272 struct compile_state *state,
4273 struct triple *test, struct triple *left, struct triple *right)
4276 struct type *result_type;
4277 unsigned int left_type, right_type;
4279 left_type = left->type->type;
4280 right_type = right->type->type;
4282 /* Both operands have arithmetic type */
4283 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4284 result_type = arithmetic_result(state, left, right);
4286 /* Both operands have void type */
4287 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4288 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4289 result_type = &void_type;
4291 /* pointers to the same type... */
4292 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4295 /* Both operands are pointers and left is a pointer to void */
4296 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4297 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4298 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4299 result_type = right->type;
4301 /* Both operands are pointers and right is a pointer to void */
4302 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4303 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4304 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4305 result_type = left->type;
4308 error(state, 0, "Incompatible types in conditional expression");
4310 def = new_triple(state, OP_COND, result_type, 3);
4311 def->param[0] = test;
4312 def->param[1] = left;
4313 def->param[2] = right;
4318 static int expr_depth(struct compile_state *state, struct triple *ins)
4322 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4325 else if (ins->op == OP_DEREF) {
4326 count = expr_depth(state, RHS(ins, 0)) - 1;
4328 else if (ins->op == OP_VAL) {
4329 count = expr_depth(state, RHS(ins, 0)) - 1;
4331 else if (ins->op == OP_COMMA) {
4333 ldepth = expr_depth(state, RHS(ins, 0));
4334 rdepth = expr_depth(state, RHS(ins, 1));
4335 count = (ldepth >= rdepth)? ldepth : rdepth;
4337 else if (ins->op == OP_CALL) {
4338 /* Don't figure the depth of a call just guess it is huge */
4342 struct triple **expr;
4343 expr = triple_rhs(state, ins, 0);
4344 for(;expr; expr = triple_rhs(state, ins, expr)) {
4347 depth = expr_depth(state, *expr);
4348 if (depth > count) {
4357 static struct triple *flatten(
4358 struct compile_state *state, struct triple *first, struct triple *ptr);
4360 static struct triple *flatten_generic(
4361 struct compile_state *state, struct triple *first, struct triple *ptr)
4365 struct triple **ins;
4368 /* Only operations with just a rhs should come here */
4369 rhs = TRIPLE_RHS(ptr->sizes);
4370 lhs = TRIPLE_LHS(ptr->sizes);
4371 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4372 internal_error(state, ptr, "unexpected args for: %d %s",
4373 ptr->op, tops(ptr->op));
4375 /* Find the depth of the rhs elements */
4376 for(i = 0; i < rhs; i++) {
4377 vector[i].ins = &RHS(ptr, i);
4378 vector[i].depth = expr_depth(state, *vector[i].ins);
4380 /* Selection sort the rhs */
4381 for(i = 0; i < rhs; i++) {
4383 for(j = i + 1; j < rhs; j++ ) {
4384 if (vector[j].depth > vector[max].depth) {
4389 struct rhs_vector tmp;
4391 vector[i] = vector[max];
4395 /* Now flatten the rhs elements */
4396 for(i = 0; i < rhs; i++) {
4397 *vector[i].ins = flatten(state, first, *vector[i].ins);
4398 use_triple(*vector[i].ins, ptr);
4401 /* Now flatten the lhs elements */
4402 for(i = 0; i < lhs; i++) {
4403 struct triple **ins = &LHS(ptr, i);
4404 *ins = flatten(state, first, *ins);
4405 use_triple(*ins, ptr);
4410 static struct triple *flatten_land(
4411 struct compile_state *state, struct triple *first, struct triple *ptr)
4413 struct triple *left, *right;
4414 struct triple *val, *test, *jmp, *label1, *end;
4416 /* Find the triples */
4418 right = RHS(ptr, 1);
4420 /* Generate the needed triples */
4423 /* Thread the triples together */
4424 val = flatten(state, first, variable(state, ptr->type));
4425 left = flatten(state, first, write_expr(state, val, left));
4426 test = flatten(state, first,
4427 lfalse_expr(state, read_expr(state, val)));
4428 jmp = flatten(state, first, branch(state, end, test));
4429 label1 = flatten(state, first, label(state));
4430 right = flatten(state, first, write_expr(state, val, right));
4431 TARG(jmp, 0) = flatten(state, first, end);
4433 /* Now give the caller something to chew on */
4434 return read_expr(state, val);
4437 static struct triple *flatten_lor(
4438 struct compile_state *state, struct triple *first, struct triple *ptr)
4440 struct triple *left, *right;
4441 struct triple *val, *jmp, *label1, *end;
4443 /* Find the triples */
4445 right = RHS(ptr, 1);
4447 /* Generate the needed triples */
4450 /* Thread the triples together */
4451 val = flatten(state, first, variable(state, ptr->type));
4452 left = flatten(state, first, write_expr(state, val, left));
4453 jmp = flatten(state, first, branch(state, end, left));
4454 label1 = flatten(state, first, label(state));
4455 right = flatten(state, first, write_expr(state, val, right));
4456 TARG(jmp, 0) = flatten(state, first, end);
4459 /* Now give the caller something to chew on */
4460 return read_expr(state, val);
4463 static struct triple *flatten_cond(
4464 struct compile_state *state, struct triple *first, struct triple *ptr)
4466 struct triple *test, *left, *right;
4467 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4469 /* Find the triples */
4472 right = RHS(ptr, 2);
4474 /* Generate the needed triples */
4476 middle = label(state);
4478 /* Thread the triples together */
4479 val = flatten(state, first, variable(state, ptr->type));
4480 test = flatten(state, first, test);
4481 jmp1 = flatten(state, first, branch(state, middle, test));
4482 label1 = flatten(state, first, label(state));
4483 left = flatten(state, first, left);
4484 mv1 = flatten(state, first, write_expr(state, val, left));
4485 jmp2 = flatten(state, first, branch(state, end, 0));
4486 TARG(jmp1, 0) = flatten(state, first, middle);
4487 right = flatten(state, first, right);
4488 mv2 = flatten(state, first, write_expr(state, val, right));
4489 TARG(jmp2, 0) = flatten(state, first, end);
4491 /* Now give the caller something to chew on */
4492 return read_expr(state, val);
4495 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4497 struct triple *nfunc;
4498 struct triple *nfirst, *ofirst;
4499 struct triple *new, *old;
4502 fprintf(stdout, "\n");
4503 loc(stdout, state, 0);
4504 fprintf(stdout, "\n__________ copy_func _________\n");
4505 print_triple(state, ofunc);
4506 fprintf(stdout, "__________ copy_func _________ done\n\n");
4509 /* Make a new copy of the old function */
4510 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4512 ofirst = old = RHS(ofunc, 0);
4516 old_rhs = TRIPLE_RHS(old->sizes);
4517 new = alloc_triple(state, old->op, old->type, old_rhs,
4518 old->filename, old->line, old->col);
4519 if (IS_CONST_OP(new->op)) {
4520 memcpy(&new->u, &old->u, sizeof(new->u));
4522 #warning "WISHLIST find a way to handle SDECL without a special case..."
4523 /* The problem is that I don't flatten the misc field,
4524 * so I cannot look the value the misc field should have.
4526 else if (new->op == OP_SDECL) {
4527 MISC(new, 0) = MISC(old, 0);
4530 RHS(nfunc, 0) = nfirst = new;
4533 insert_triple(state, nfirst, new);
4535 new->id |= TRIPLE_FLAG_FLATTENED;
4537 /* During the copy remember new as user of old */
4538 use_triple(old, new);
4540 /* Populate the return type if present */
4541 if (old == MISC(ofunc, 0)) {
4542 MISC(nfunc, 0) = new;
4545 } while(old != ofirst);
4547 /* Make a second pass to fix up any unresolved references */
4551 struct triple **oexpr, **nexpr;
4553 /* Lookup where the copy is, to join pointers */
4554 count = TRIPLE_SIZE(old->sizes);
4555 for(i = 0; i < count; i++) {
4556 oexpr = &old->param[i];
4557 nexpr = &new->param[i];
4558 if (!*nexpr && *oexpr && (*oexpr)->use) {
4559 *nexpr = (*oexpr)->use->member;
4560 if (*nexpr == old) {
4561 internal_error(state, 0, "new == old?");
4563 use_triple(*nexpr, new);
4565 if (!*nexpr && *oexpr) {
4566 internal_error(state, 0, "Could not copy %d\n", i);
4571 } while((old != ofirst) && (new != nfirst));
4573 /* Make a third pass to cleanup the extra useses */
4577 unuse_triple(old, new);
4580 } while ((old != ofirst) && (new != nfirst));
4584 static struct triple *flatten_call(
4585 struct compile_state *state, struct triple *first, struct triple *ptr)
4587 /* Inline the function call */
4589 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4590 struct triple *end, *nend;
4593 /* Find the triples */
4594 ofunc = MISC(ptr, 0);
4595 if (ofunc->op != OP_LIST) {
4596 internal_error(state, 0, "improper function");
4598 nfunc = copy_func(state, ofunc);
4599 nfirst = RHS(nfunc, 0)->next;
4600 /* Prepend the parameter reading into the new function list */
4601 ptype = nfunc->type->right;
4602 param = RHS(nfunc, 0)->next;
4603 pvals = TRIPLE_RHS(ptr->sizes);
4604 for(i = 0; i < pvals; i++) {
4608 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4609 atype = ptype->left;
4611 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4612 param = param->next;
4615 flatten(state, nfirst, write_expr(state, param, arg));
4616 ptype = ptype->right;
4617 param = param->next;
4620 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4621 result = read_expr(state, MISC(nfunc,0));
4624 fprintf(stdout, "\n");
4625 loc(stdout, state, 0);
4626 fprintf(stdout, "\n__________ flatten_call _________\n");
4627 print_triple(state, nfunc);
4628 fprintf(stdout, "__________ flatten_call _________ done\n\n");
4631 /* Get rid of the extra triples */
4632 nfirst = RHS(nfunc, 0)->next;
4633 free_triple(state, RHS(nfunc, 0));
4635 free_triple(state, nfunc);
4637 /* Append the new function list onto the return list */
4639 nend = nfirst->prev;
4648 static struct triple *flatten(
4649 struct compile_state *state, struct triple *first, struct triple *ptr)
4651 struct triple *orig_ptr;
4656 /* Only flatten triples once */
4657 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4663 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4664 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4665 use_triple(LHS(ptr, 0), ptr);
4666 use_triple(RHS(ptr, 0), ptr);
4669 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4673 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4674 return MISC(ptr, 0);
4677 ptr = flatten_land(state, first, ptr);
4680 ptr = flatten_lor(state, first, ptr);
4683 ptr = flatten_cond(state, first, ptr);
4686 ptr = flatten_call(state, first, ptr);
4690 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4691 use_triple(RHS(ptr, 0), ptr);
4694 use_triple(TARG(ptr, 0), ptr);
4695 if (TRIPLE_RHS(ptr->sizes)) {
4696 use_triple(RHS(ptr, 0), ptr);
4697 if (ptr->next != ptr) {
4698 use_triple(ptr->next, ptr);
4703 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4704 use_triple(MISC(ptr, 0), ptr);
4707 /* Since OP_DEREF is just a marker delete it when I flatten it */
4709 RHS(orig_ptr, 0) = 0;
4710 free_triple(state, orig_ptr);
4714 struct triple *base;
4716 base = flatten(state, first, base);
4717 if (base->op == OP_VAL_VEC) {
4718 ptr = struct_field(state, base, ptr->u.field);
4726 /* Flatten the easy cases we don't override */
4727 ptr = flatten_generic(state, first, ptr);
4730 } while(ptr && (ptr != orig_ptr));
4732 insert_triple(state, first, ptr);
4733 ptr->id |= TRIPLE_FLAG_FLATTENED;
4738 static void release_expr(struct compile_state *state, struct triple *expr)
4740 struct triple *head;
4741 head = label(state);
4742 flatten(state, head, expr);
4743 while(head->next != head) {
4744 release_triple(state, head->next);
4746 free_triple(state, head);
4749 static int replace_rhs_use(struct compile_state *state,
4750 struct triple *orig, struct triple *new, struct triple *use)
4752 struct triple **expr;
4755 expr = triple_rhs(state, use, 0);
4756 for(;expr; expr = triple_rhs(state, use, expr)) {
4757 if (*expr == orig) {
4763 unuse_triple(orig, use);
4764 use_triple(new, use);
4769 static int replace_lhs_use(struct compile_state *state,
4770 struct triple *orig, struct triple *new, struct triple *use)
4772 struct triple **expr;
4775 expr = triple_lhs(state, use, 0);
4776 for(;expr; expr = triple_lhs(state, use, expr)) {
4777 if (*expr == orig) {
4783 unuse_triple(orig, use);
4784 use_triple(new, use);
4789 static void propogate_use(struct compile_state *state,
4790 struct triple *orig, struct triple *new)
4792 struct triple_set *user, *next;
4793 for(user = orig->use; user; user = next) {
4799 found |= replace_rhs_use(state, orig, new, use);
4800 found |= replace_lhs_use(state, orig, new, use);
4802 internal_error(state, use, "use without use");
4806 internal_error(state, orig, "used after propogate_use");
4812 * ===========================
4815 static struct triple *mk_add_expr(
4816 struct compile_state *state, struct triple *left, struct triple *right)
4818 struct type *result_type;
4819 /* Put pointer operands on the left */
4820 if (is_pointer(right)) {
4826 result_type = ptr_arithmetic_result(state, left, right);
4827 left = read_expr(state, left);
4828 right = read_expr(state, right);
4829 if (is_pointer(left)) {
4830 right = triple(state,
4831 is_signed(right->type)? OP_SMUL : OP_UMUL,
4834 int_const(state, &ulong_type,
4835 size_of(state, left->type->left)));
4837 return triple(state, OP_ADD, result_type, left, right);
4840 static struct triple *mk_sub_expr(
4841 struct compile_state *state, struct triple *left, struct triple *right)
4843 struct type *result_type;
4844 result_type = ptr_arithmetic_result(state, left, right);
4845 left = read_expr(state, left);
4846 right = read_expr(state, right);
4847 if (is_pointer(left)) {
4848 right = triple(state,
4849 is_signed(right->type)? OP_SMUL : OP_UMUL,
4852 int_const(state, &ulong_type,
4853 size_of(state, left->type->left)));
4855 return triple(state, OP_SUB, result_type, left, right);
4858 static struct triple *mk_pre_inc_expr(
4859 struct compile_state *state, struct triple *def)
4863 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
4864 return triple(state, OP_VAL, def->type,
4865 write_expr(state, def, val),
4869 static struct triple *mk_pre_dec_expr(
4870 struct compile_state *state, struct triple *def)
4874 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
4875 return triple(state, OP_VAL, def->type,
4876 write_expr(state, def, val),
4880 static struct triple *mk_post_inc_expr(
4881 struct compile_state *state, struct triple *def)
4885 val = read_expr(state, def);
4886 return triple(state, OP_VAL, def->type,
4887 write_expr(state, def,
4888 mk_add_expr(state, val, int_const(state, &int_type, 1)))
4892 static struct triple *mk_post_dec_expr(
4893 struct compile_state *state, struct triple *def)
4897 val = read_expr(state, def);
4898 return triple(state, OP_VAL, def->type,
4899 write_expr(state, def,
4900 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
4904 static struct triple *mk_subscript_expr(
4905 struct compile_state *state, struct triple *left, struct triple *right)
4907 left = read_expr(state, left);
4908 right = read_expr(state, right);
4909 if (!is_pointer(left) && !is_pointer(right)) {
4910 error(state, left, "subscripted value is not a pointer");
4912 return mk_deref_expr(state, mk_add_expr(state, left, right));
4916 * Compile time evaluation
4917 * ===========================
4919 static int is_const(struct triple *ins)
4921 return IS_CONST_OP(ins->op);
4924 static int constants_equal(struct compile_state *state,
4925 struct triple *left, struct triple *right)
4928 if (!is_const(left) || !is_const(right)) {
4931 else if (left->op != right->op) {
4934 else if (!equiv_types(left->type, right->type)) {
4941 if (left->u.cval == right->u.cval) {
4947 size_t lsize, rsize;
4948 lsize = size_of(state, left->type);
4949 rsize = size_of(state, right->type);
4950 if (lsize != rsize) {
4953 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
4959 if ((RHS(left, 0) == RHS(right, 0)) &&
4960 (left->u.cval == right->u.cval)) {
4965 internal_error(state, left, "uknown constant type");
4972 static int is_zero(struct triple *ins)
4974 return is_const(ins) && (ins->u.cval == 0);
4977 static int is_one(struct triple *ins)
4979 return is_const(ins) && (ins->u.cval == 1);
4982 static long_t bsr(ulong_t value)
4985 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
4996 static long_t bsf(ulong_t value)
4999 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5010 static long_t log2(ulong_t value)
5015 static long_t tlog2(struct triple *ins)
5017 return log2(ins->u.cval);
5020 static int is_pow2(struct triple *ins)
5022 ulong_t value, mask;
5024 if (!is_const(ins)) {
5027 value = ins->u.cval;
5034 return ((value & mask) == value);
5037 static ulong_t read_const(struct compile_state *state,
5038 struct triple *ins, struct triple **expr)
5042 switch(rhs->type->type &TYPE_MASK) {
5054 internal_error(state, rhs, "bad type to read_const\n");
5060 static long_t read_sconst(struct triple *ins, struct triple **expr)
5064 return (long_t)(rhs->u.cval);
5067 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5069 struct triple **expr;
5070 expr = triple_rhs(state, ins, 0);
5071 for(;expr;expr = triple_rhs(state, ins, expr)) {
5073 unuse_triple(*expr, ins);
5079 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5081 struct triple **expr;
5082 expr = triple_lhs(state, ins, 0);
5083 for(;expr;expr = triple_lhs(state, ins, expr)) {
5084 unuse_triple(*expr, ins);
5089 static void check_lhs(struct compile_state *state, struct triple *ins)
5091 struct triple **expr;
5092 expr = triple_lhs(state, ins, 0);
5093 for(;expr;expr = triple_lhs(state, ins, expr)) {
5094 internal_error(state, ins, "unexpected lhs");
5098 static void check_targ(struct compile_state *state, struct triple *ins)
5100 struct triple **expr;
5101 expr = triple_targ(state, ins, 0);
5102 for(;expr;expr = triple_targ(state, ins, expr)) {
5103 internal_error(state, ins, "unexpected targ");
5107 static void wipe_ins(struct compile_state *state, struct triple *ins)
5109 /* Becareful which instructions you replace the wiped
5110 * instruction with, as there are not enough slots
5111 * in all instructions to hold all others.
5113 check_targ(state, ins);
5114 unuse_rhs(state, ins);
5115 unuse_lhs(state, ins);
5118 static void mkcopy(struct compile_state *state,
5119 struct triple *ins, struct triple *rhs)
5121 wipe_ins(state, ins);
5123 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5125 use_triple(RHS(ins, 0), ins);
5128 static void mkconst(struct compile_state *state,
5129 struct triple *ins, ulong_t value)
5131 if (!is_integral(ins) && !is_pointer(ins)) {
5132 internal_error(state, ins, "unknown type to make constant\n");
5134 wipe_ins(state, ins);
5135 ins->op = OP_INTCONST;
5136 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5137 ins->u.cval = value;
5140 static void mkaddr_const(struct compile_state *state,
5141 struct triple *ins, struct triple *sdecl, ulong_t value)
5143 wipe_ins(state, ins);
5144 ins->op = OP_ADDRCONST;
5145 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5146 RHS(ins, 0) = sdecl;
5147 ins->u.cval = value;
5148 use_triple(sdecl, ins);
5151 /* Transform multicomponent variables into simple register variables */
5152 static void flatten_structures(struct compile_state *state)
5154 struct triple *ins, *first;
5155 first = RHS(state->main_function, 0);
5157 /* Pass one expand structure values into valvecs.
5161 struct triple *next;
5163 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5164 if (ins->op == OP_VAL_VEC) {
5167 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5168 struct triple *def, **vector;
5175 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5176 ins->filename, ins->line, ins->col);
5178 vector = &RHS(next, 0);
5179 tptr = next->type->left;
5180 for(i = 0; i < next->type->elements; i++) {
5181 struct triple *sfield;
5184 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5185 mtype = mtype->left;
5187 sfield = deref_field(state, def, mtype->field_ident);
5190 state, op, mtype, sfield, 0);
5191 vector[i]->filename = next->filename;
5192 vector[i]->line = next->line;
5193 vector[i]->col = next->col;
5196 propogate_use(state, ins, next);
5197 flatten(state, ins, next);
5198 free_triple(state, ins);
5200 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5201 struct triple *src, *dst, **vector;
5209 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5210 ins->filename, ins->line, ins->col);
5212 vector = &RHS(next, 0);
5213 tptr = next->type->left;
5214 for(i = 0; i < ins->type->elements; i++) {
5215 struct triple *dfield, *sfield;
5218 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5219 mtype = mtype->left;
5221 sfield = deref_field(state, src, mtype->field_ident);
5222 dfield = deref_field(state, dst, mtype->field_ident);
5224 state, op, mtype, dfield, sfield);
5225 vector[i]->filename = next->filename;
5226 vector[i]->line = next->line;
5227 vector[i]->col = next->col;
5230 propogate_use(state, ins, next);
5231 flatten(state, ins, next);
5232 free_triple(state, ins);
5236 } while(ins != first);
5237 /* Pass two flatten the valvecs.
5241 struct triple *next;
5243 if (ins->op == OP_VAL_VEC) {
5244 release_triple(state, ins);
5247 } while(ins != first);
5248 /* Pass three verify the state and set ->id to 0.
5253 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5254 internal_error(state, 0, "STRUCT_TYPE remains?");
5256 if (ins->op == OP_DOT) {
5257 internal_error(state, 0, "OP_DOT remains?");
5259 if (ins->op == OP_VAL_VEC) {
5260 internal_error(state, 0, "OP_VAL_VEC remains?");
5263 } while(ins != first);
5266 /* For those operations that cannot be simplified */
5267 static void simplify_noop(struct compile_state *state, struct triple *ins)
5272 static void simplify_smul(struct compile_state *state, struct triple *ins)
5274 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5277 RHS(ins, 0) = RHS(ins, 1);
5280 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5282 left = read_sconst(ins, &RHS(ins, 0));
5283 right = read_sconst(ins, &RHS(ins, 1));
5284 mkconst(state, ins, left * right);
5286 else if (is_zero(RHS(ins, 1))) {
5287 mkconst(state, ins, 0);
5289 else if (is_one(RHS(ins, 1))) {
5290 mkcopy(state, ins, RHS(ins, 0));
5292 else if (is_pow2(RHS(ins, 1))) {
5294 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5296 insert_triple(state, ins, val);
5297 unuse_triple(RHS(ins, 1), ins);
5298 use_triple(val, ins);
5303 static void simplify_umul(struct compile_state *state, struct triple *ins)
5305 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5308 RHS(ins, 0) = RHS(ins, 1);
5311 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5312 ulong_t left, right;
5313 left = read_const(state, ins, &RHS(ins, 0));
5314 right = read_const(state, ins, &RHS(ins, 1));
5315 mkconst(state, ins, left * right);
5317 else if (is_zero(RHS(ins, 1))) {
5318 mkconst(state, ins, 0);
5320 else if (is_one(RHS(ins, 1))) {
5321 mkcopy(state, ins, RHS(ins, 0));
5323 else if (is_pow2(RHS(ins, 1))) {
5325 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5327 insert_triple(state, ins, val);
5328 unuse_triple(RHS(ins, 1), ins);
5329 use_triple(val, ins);
5334 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5336 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5338 left = read_sconst(ins, &RHS(ins, 0));
5339 right = read_sconst(ins, &RHS(ins, 1));
5340 mkconst(state, ins, left / right);
5342 else if (is_zero(RHS(ins, 0))) {
5343 mkconst(state, ins, 0);
5345 else if (is_zero(RHS(ins, 1))) {
5346 error(state, ins, "division by zero");
5348 else if (is_one(RHS(ins, 1))) {
5349 mkcopy(state, ins, RHS(ins, 0));
5351 else if (is_pow2(RHS(ins, 1))) {
5353 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5355 insert_triple(state, ins, val);
5356 unuse_triple(RHS(ins, 1), ins);
5357 use_triple(val, ins);
5362 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5364 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5365 ulong_t left, right;
5366 left = read_const(state, ins, &RHS(ins, 0));
5367 right = read_const(state, ins, &RHS(ins, 1));
5368 mkconst(state, ins, left / right);
5370 else if (is_zero(RHS(ins, 0))) {
5371 mkconst(state, ins, 0);
5373 else if (is_zero(RHS(ins, 1))) {
5374 error(state, ins, "division by zero");
5376 else if (is_one(RHS(ins, 1))) {
5377 mkcopy(state, ins, RHS(ins, 0));
5379 else if (is_pow2(RHS(ins, 1))) {
5381 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5383 insert_triple(state, ins, val);
5384 unuse_triple(RHS(ins, 1), ins);
5385 use_triple(val, ins);
5390 static void simplify_smod(struct compile_state *state, struct triple *ins)
5392 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5394 left = read_const(state, ins, &RHS(ins, 0));
5395 right = read_const(state, ins, &RHS(ins, 1));
5396 mkconst(state, ins, left % right);
5398 else if (is_zero(RHS(ins, 0))) {
5399 mkconst(state, ins, 0);
5401 else if (is_zero(RHS(ins, 1))) {
5402 error(state, ins, "division by zero");
5404 else if (is_one(RHS(ins, 1))) {
5405 mkconst(state, ins, 0);
5407 else if (is_pow2(RHS(ins, 1))) {
5409 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5411 insert_triple(state, ins, val);
5412 unuse_triple(RHS(ins, 1), ins);
5413 use_triple(val, ins);
5417 static void simplify_umod(struct compile_state *state, struct triple *ins)
5419 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5420 ulong_t left, right;
5421 left = read_const(state, ins, &RHS(ins, 0));
5422 right = read_const(state, ins, &RHS(ins, 1));
5423 mkconst(state, ins, left % right);
5425 else if (is_zero(RHS(ins, 0))) {
5426 mkconst(state, ins, 0);
5428 else if (is_zero(RHS(ins, 1))) {
5429 error(state, ins, "division by zero");
5431 else if (is_one(RHS(ins, 1))) {
5432 mkconst(state, ins, 0);
5434 else if (is_pow2(RHS(ins, 1))) {
5436 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5438 insert_triple(state, ins, val);
5439 unuse_triple(RHS(ins, 1), ins);
5440 use_triple(val, ins);
5445 static void simplify_add(struct compile_state *state, struct triple *ins)
5447 /* start with the pointer on the left */
5448 if (is_pointer(RHS(ins, 1))) {
5451 RHS(ins, 0) = RHS(ins, 1);
5454 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5455 if (!is_pointer(RHS(ins, 0))) {
5456 ulong_t left, right;
5457 left = read_const(state, ins, &RHS(ins, 0));
5458 right = read_const(state, ins, &RHS(ins, 1));
5459 mkconst(state, ins, left + right);
5461 else /* op == OP_ADDRCONST */ {
5462 struct triple *sdecl;
5463 ulong_t left, right;
5464 sdecl = RHS(RHS(ins, 0), 0);
5465 left = RHS(ins, 0)->u.cval;
5466 right = RHS(ins, 1)->u.cval;
5467 mkaddr_const(state, ins, sdecl, left + right);
5470 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5473 RHS(ins, 1) = RHS(ins, 0);
5478 static void simplify_sub(struct compile_state *state, struct triple *ins)
5480 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5481 if (!is_pointer(RHS(ins, 0))) {
5482 ulong_t left, right;
5483 left = read_const(state, ins, &RHS(ins, 0));
5484 right = read_const(state, ins, &RHS(ins, 1));
5485 mkconst(state, ins, left - right);
5487 else /* op == OP_ADDRCONST */ {
5488 struct triple *sdecl;
5489 ulong_t left, right;
5490 sdecl = RHS(RHS(ins, 0), 0);
5491 left = RHS(ins, 0)->u.cval;
5492 right = RHS(ins, 1)->u.cval;
5493 mkaddr_const(state, ins, sdecl, left - right);
5498 static void simplify_sl(struct compile_state *state, struct triple *ins)
5500 if (is_const(RHS(ins, 1))) {
5502 right = read_const(state, ins, &RHS(ins, 1));
5503 if (right >= (size_of(state, ins->type)*8)) {
5504 warning(state, ins, "left shift count >= width of type");
5507 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5508 ulong_t left, right;
5509 left = read_const(state, ins, &RHS(ins, 0));
5510 right = read_const(state, ins, &RHS(ins, 1));
5511 mkconst(state, ins, left << right);
5515 static void simplify_usr(struct compile_state *state, struct triple *ins)
5517 if (is_const(RHS(ins, 1))) {
5519 right = read_const(state, ins, &RHS(ins, 1));
5520 if (right >= (size_of(state, ins->type)*8)) {
5521 warning(state, ins, "right shift count >= width of type");
5524 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5525 ulong_t left, right;
5526 left = read_const(state, ins, &RHS(ins, 0));
5527 right = read_const(state, ins, &RHS(ins, 1));
5528 mkconst(state, ins, left >> right);
5532 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5534 if (is_const(RHS(ins, 1))) {
5536 right = read_const(state, ins, &RHS(ins, 1));
5537 if (right >= (size_of(state, ins->type)*8)) {
5538 warning(state, ins, "right shift count >= width of type");
5541 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5543 left = read_sconst(ins, &RHS(ins, 0));
5544 right = read_sconst(ins, &RHS(ins, 1));
5545 mkconst(state, ins, left >> right);
5549 static void simplify_and(struct compile_state *state, struct triple *ins)
5551 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5552 ulong_t left, right;
5553 left = read_const(state, ins, &RHS(ins, 0));
5554 right = read_const(state, ins, &RHS(ins, 1));
5555 mkconst(state, ins, left & right);
5559 static void simplify_or(struct compile_state *state, struct triple *ins)
5561 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5562 ulong_t left, right;
5563 left = read_const(state, ins, &RHS(ins, 0));
5564 right = read_const(state, ins, &RHS(ins, 1));
5565 mkconst(state, ins, left | right);
5569 static void simplify_xor(struct compile_state *state, struct triple *ins)
5571 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5572 ulong_t left, right;
5573 left = read_const(state, ins, &RHS(ins, 0));
5574 right = read_const(state, ins, &RHS(ins, 1));
5575 mkconst(state, ins, left ^ right);
5579 static void simplify_pos(struct compile_state *state, struct triple *ins)
5581 if (is_const(RHS(ins, 0))) {
5582 mkconst(state, ins, RHS(ins, 0)->u.cval);
5585 mkcopy(state, ins, RHS(ins, 0));
5589 static void simplify_neg(struct compile_state *state, struct triple *ins)
5591 if (is_const(RHS(ins, 0))) {
5593 left = read_const(state, ins, &RHS(ins, 0));
5594 mkconst(state, ins, -left);
5596 else if (RHS(ins, 0)->op == OP_NEG) {
5597 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5601 static void simplify_invert(struct compile_state *state, struct triple *ins)
5603 if (is_const(RHS(ins, 0))) {
5605 left = read_const(state, ins, &RHS(ins, 0));
5606 mkconst(state, ins, ~left);
5610 static void simplify_eq(struct compile_state *state, struct triple *ins)
5612 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5613 ulong_t left, right;
5614 left = read_const(state, ins, &RHS(ins, 0));
5615 right = read_const(state, ins, &RHS(ins, 1));
5616 mkconst(state, ins, left == right);
5618 else if (RHS(ins, 0) == RHS(ins, 1)) {
5619 mkconst(state, ins, 1);
5623 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5625 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5626 ulong_t left, right;
5627 left = read_const(state, ins, &RHS(ins, 0));
5628 right = read_const(state, ins, &RHS(ins, 1));
5629 mkconst(state, ins, left != right);
5631 else if (RHS(ins, 0) == RHS(ins, 1)) {
5632 mkconst(state, ins, 0);
5636 static void simplify_sless(struct compile_state *state, struct triple *ins)
5638 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5640 left = read_sconst(ins, &RHS(ins, 0));
5641 right = read_sconst(ins, &RHS(ins, 1));
5642 mkconst(state, ins, left < right);
5644 else if (RHS(ins, 0) == RHS(ins, 1)) {
5645 mkconst(state, ins, 0);
5649 static void simplify_uless(struct compile_state *state, struct triple *ins)
5651 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5652 ulong_t left, right;
5653 left = read_const(state, ins, &RHS(ins, 0));
5654 right = read_const(state, ins, &RHS(ins, 1));
5655 mkconst(state, ins, left < right);
5657 else if (is_zero(RHS(ins, 0))) {
5658 mkconst(state, ins, 1);
5660 else if (RHS(ins, 0) == RHS(ins, 1)) {
5661 mkconst(state, ins, 0);
5665 static void simplify_smore(struct compile_state *state, struct triple *ins)
5667 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5669 left = read_sconst(ins, &RHS(ins, 0));
5670 right = read_sconst(ins, &RHS(ins, 1));
5671 mkconst(state, ins, left > right);
5673 else if (RHS(ins, 0) == RHS(ins, 1)) {
5674 mkconst(state, ins, 0);
5678 static void simplify_umore(struct compile_state *state, struct triple *ins)
5680 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5681 ulong_t left, right;
5682 left = read_const(state, ins, &RHS(ins, 0));
5683 right = read_const(state, ins, &RHS(ins, 1));
5684 mkconst(state, ins, left > right);
5686 else if (is_zero(RHS(ins, 1))) {
5687 mkconst(state, ins, 1);
5689 else if (RHS(ins, 0) == RHS(ins, 1)) {
5690 mkconst(state, ins, 0);
5695 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5697 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5699 left = read_sconst(ins, &RHS(ins, 0));
5700 right = read_sconst(ins, &RHS(ins, 1));
5701 mkconst(state, ins, left <= right);
5703 else if (RHS(ins, 0) == RHS(ins, 1)) {
5704 mkconst(state, ins, 1);
5708 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5710 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5711 ulong_t left, right;
5712 left = read_const(state, ins, &RHS(ins, 0));
5713 right = read_const(state, ins, &RHS(ins, 1));
5714 mkconst(state, ins, left <= right);
5716 else if (is_zero(RHS(ins, 0))) {
5717 mkconst(state, ins, 1);
5719 else if (RHS(ins, 0) == RHS(ins, 1)) {
5720 mkconst(state, ins, 1);
5724 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5726 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5728 left = read_sconst(ins, &RHS(ins, 0));
5729 right = read_sconst(ins, &RHS(ins, 1));
5730 mkconst(state, ins, left >= right);
5732 else if (RHS(ins, 0) == RHS(ins, 1)) {
5733 mkconst(state, ins, 1);
5737 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5739 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5740 ulong_t left, right;
5741 left = read_const(state, ins, &RHS(ins, 0));
5742 right = read_const(state, ins, &RHS(ins, 1));
5743 mkconst(state, ins, left >= right);
5745 else if (is_zero(RHS(ins, 1))) {
5746 mkconst(state, ins, 1);
5748 else if (RHS(ins, 0) == RHS(ins, 1)) {
5749 mkconst(state, ins, 1);
5753 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5755 if (is_const(RHS(ins, 0))) {
5757 left = read_const(state, ins, &RHS(ins, 0));
5758 mkconst(state, ins, left == 0);
5760 /* Otherwise if I am the only user... */
5761 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
5763 /* Invert a boolean operation */
5764 switch(RHS(ins, 0)->op) {
5765 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
5766 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
5767 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
5768 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
5769 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
5770 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
5771 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
5772 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
5773 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
5774 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
5775 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
5776 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
5782 mkcopy(state, ins, RHS(ins, 0));
5787 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
5789 if (is_const(RHS(ins, 0))) {
5791 left = read_const(state, ins, &RHS(ins, 0));
5792 mkconst(state, ins, left != 0);
5794 else switch(RHS(ins, 0)->op) {
5795 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
5796 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
5797 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
5798 mkcopy(state, ins, RHS(ins, 0));
5803 static void simplify_copy(struct compile_state *state, struct triple *ins)
5805 if (is_const(RHS(ins, 0))) {
5806 switch(RHS(ins, 0)->op) {
5810 left = read_const(state, ins, &RHS(ins, 0));
5811 mkconst(state, ins, left);
5816 struct triple *sdecl;
5818 sdecl = RHS(ins, 0);
5819 offset = ins->u.cval;
5820 mkaddr_const(state, ins, sdecl, offset);
5824 internal_error(state, ins, "uknown constant");
5830 static void simplify_branch(struct compile_state *state, struct triple *ins)
5832 struct block *block;
5833 if (ins->op != OP_BRANCH) {
5834 internal_error(state, ins, "not branch");
5836 if (ins->use != 0) {
5837 internal_error(state, ins, "branch use");
5839 #warning "FIXME implement simplify branch."
5840 /* The challenge here with simplify branch is that I need to
5841 * make modifications to the control flow graph as well
5842 * as to the branch instruction itself.
5844 block = ins->u.block;
5846 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
5847 struct triple *targ;
5849 value = read_const(state, ins, &RHS(ins, 0));
5850 unuse_triple(RHS(ins, 0), ins);
5851 targ = TARG(ins, 0);
5852 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
5854 unuse_triple(ins->next, ins);
5855 TARG(ins, 0) = targ;
5858 unuse_triple(targ, ins);
5859 TARG(ins, 0) = ins->next;
5861 #warning "FIXME handle the case of making a branch unconditional"
5863 if (TARG(ins, 0) == ins->next) {
5864 unuse_triple(ins->next, ins);
5865 if (TRIPLE_RHS(ins->sizes)) {
5866 unuse_triple(RHS(ins, 0), ins);
5867 unuse_triple(ins->next, ins);
5869 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5872 internal_error(state, ins, "noop use != 0");
5874 #warning "FIXME handle the case of killing a branch"
5878 static void simplify_phi(struct compile_state *state, struct triple *ins)
5880 struct triple **expr;
5882 expr = triple_rhs(state, ins, 0);
5883 if (!*expr || !is_const(*expr)) {
5886 value = read_const(state, ins, expr);
5887 for(;expr;expr = triple_rhs(state, ins, expr)) {
5888 if (!*expr || !is_const(*expr)) {
5891 if (value != read_const(state, ins, expr)) {
5895 mkconst(state, ins, value);
5899 static void simplify_bsf(struct compile_state *state, struct triple *ins)
5901 if (is_const(RHS(ins, 0))) {
5903 left = read_const(state, ins, &RHS(ins, 0));
5904 mkconst(state, ins, bsf(left));
5908 static void simplify_bsr(struct compile_state *state, struct triple *ins)
5910 if (is_const(RHS(ins, 0))) {
5912 left = read_const(state, ins, &RHS(ins, 0));
5913 mkconst(state, ins, bsr(left));
5918 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
5919 static const simplify_t table_simplify[] = {
5921 #define simplify_smul simplify_noop
5922 #define simplify_umul simplify_noop
5923 #define simplify_sdiv simplify_noop
5924 #define simplify_udiv simplify_noop
5925 #define simplify_smod simplify_noop
5926 #define simplify_umod simplify_noop
5929 #define simplify_add simplify_noop
5930 #define simplify_sub simplify_noop
5933 #define simplify_sl simplify_noop
5934 #define simplify_usr simplify_noop
5935 #define simplify_ssr simplify_noop
5938 #define simplify_and simplify_noop
5939 #define simplify_xor simplify_noop
5940 #define simplify_or simplify_noop
5943 #define simplify_pos simplify_noop
5944 #define simplify_neg simplify_noop
5945 #define simplify_invert simplify_noop
5949 #define simplify_eq simplify_noop
5950 #define simplify_noteq simplify_noop
5953 #define simplify_sless simplify_noop
5954 #define simplify_uless simplify_noop
5955 #define simplify_smore simplify_noop
5956 #define simplify_umore simplify_noop
5959 #define simplify_slesseq simplify_noop
5960 #define simplify_ulesseq simplify_noop
5961 #define simplify_smoreeq simplify_noop
5962 #define simplify_umoreeq simplify_noop
5965 #define simplify_lfalse simplify_noop
5968 #define simplify_ltrue simplify_noop
5972 #define simplify_copy simplify_noop
5976 #define simplify_branch simplify_noop
5980 #define simplify_phi simplify_noop
5984 #define simplify_bsf simplify_noop
5985 #define simplify_bsr simplify_noop
5988 [OP_SMUL ] = simplify_smul,
5989 [OP_UMUL ] = simplify_umul,
5990 [OP_SDIV ] = simplify_sdiv,
5991 [OP_UDIV ] = simplify_udiv,
5992 [OP_SMOD ] = simplify_smod,
5993 [OP_UMOD ] = simplify_umod,
5994 [OP_ADD ] = simplify_add,
5995 [OP_SUB ] = simplify_sub,
5996 [OP_SL ] = simplify_sl,
5997 [OP_USR ] = simplify_usr,
5998 [OP_SSR ] = simplify_ssr,
5999 [OP_AND ] = simplify_and,
6000 [OP_XOR ] = simplify_xor,
6001 [OP_OR ] = simplify_or,
6002 [OP_POS ] = simplify_pos,
6003 [OP_NEG ] = simplify_neg,
6004 [OP_INVERT ] = simplify_invert,
6006 [OP_EQ ] = simplify_eq,
6007 [OP_NOTEQ ] = simplify_noteq,
6008 [OP_SLESS ] = simplify_sless,
6009 [OP_ULESS ] = simplify_uless,
6010 [OP_SMORE ] = simplify_smore,
6011 [OP_UMORE ] = simplify_umore,
6012 [OP_SLESSEQ ] = simplify_slesseq,
6013 [OP_ULESSEQ ] = simplify_ulesseq,
6014 [OP_SMOREEQ ] = simplify_smoreeq,
6015 [OP_UMOREEQ ] = simplify_umoreeq,
6016 [OP_LFALSE ] = simplify_lfalse,
6017 [OP_LTRUE ] = simplify_ltrue,
6019 [OP_LOAD ] = simplify_noop,
6020 [OP_STORE ] = simplify_noop,
6022 [OP_NOOP ] = simplify_noop,
6024 [OP_INTCONST ] = simplify_noop,
6025 [OP_BLOBCONST ] = simplify_noop,
6026 [OP_ADDRCONST ] = simplify_noop,
6028 [OP_WRITE ] = simplify_noop,
6029 [OP_READ ] = simplify_noop,
6030 [OP_COPY ] = simplify_copy,
6031 [OP_PIECE ] = simplify_noop,
6033 [OP_DOT ] = simplify_noop,
6034 [OP_VAL_VEC ] = simplify_noop,
6036 [OP_LIST ] = simplify_noop,
6037 [OP_BRANCH ] = simplify_branch,
6038 [OP_LABEL ] = simplify_noop,
6039 [OP_ADECL ] = simplify_noop,
6040 [OP_SDECL ] = simplify_noop,
6041 [OP_PHI ] = simplify_phi,
6043 [OP_INB ] = simplify_noop,
6044 [OP_INW ] = simplify_noop,
6045 [OP_INL ] = simplify_noop,
6046 [OP_OUTB ] = simplify_noop,
6047 [OP_OUTW ] = simplify_noop,
6048 [OP_OUTL ] = simplify_noop,
6049 [OP_BSF ] = simplify_bsf,
6050 [OP_BSR ] = simplify_bsr,
6051 [OP_RDMSR ] = simplify_noop,
6052 [OP_WRMSR ] = simplify_noop,
6053 [OP_HLT ] = simplify_noop,
6056 static void simplify(struct compile_state *state, struct triple *ins)
6059 simplify_t do_simplify;
6063 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6067 do_simplify = table_simplify[op];
6070 internal_error(state, ins, "cannot simplify op: %d %s\n",
6074 do_simplify(state, ins);
6075 } while(ins->op != op);
6078 static void simplify_all(struct compile_state *state)
6080 struct triple *ins, *first;
6081 first = RHS(state->main_function, 0);
6084 simplify(state, ins);
6086 } while(ins != first);
6091 * ============================
6094 static void register_builtin_function(struct compile_state *state,
6095 const char *name, int op, struct type *rtype, ...)
6097 struct type *ftype, *atype, *param, **next;
6098 struct triple *def, *arg, *result, *work, *last, *first;
6099 struct hash_entry *ident;
6100 struct file_state file;
6106 /* Dummy file state to get debug handling right */
6107 memset(&file, 0, sizeof(file));
6108 file.basename = name;
6110 file.prev = state->file;
6111 state->file = &file;
6113 /* Find the Parameter count */
6114 valid_op(state, op);
6115 parameters = table_ops[op].rhs;
6116 if (parameters < 0 ) {
6117 internal_error(state, 0, "Invalid builtin parameter count");
6120 /* Find the function type */
6121 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6122 next = &ftype->right;
6123 va_start(args, rtype);
6124 for(i = 0; i < parameters; i++) {
6125 atype = va_arg(args, struct type *);
6129 *next = new_type(TYPE_PRODUCT, *next, atype);
6130 next = &((*next)->right);
6138 /* Generate the needed triples */
6139 def = triple(state, OP_LIST, ftype, 0, 0);
6140 first = label(state);
6141 RHS(def, 0) = first;
6143 /* Now string them together */
6144 param = ftype->right;
6145 for(i = 0; i < parameters; i++) {
6146 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6147 atype = param->left;
6151 arg = flatten(state, first, variable(state, atype));
6152 param = param->right;
6155 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6156 result = flatten(state, first, variable(state, rtype));
6158 MISC(def, 0) = result;
6159 work = new_triple(state, op, rtype, parameters);
6160 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6161 RHS(work, i) = read_expr(state, arg);
6163 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6165 /* Populate the LHS with the target registers */
6166 work = flatten(state, first, work);
6167 work->type = &void_type;
6168 param = rtype->left;
6169 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6170 internal_error(state, 0, "Invalid result type");
6172 val = new_triple(state, OP_VAL_VEC, rtype, -1);
6173 for(i = 0; i < rtype->elements; i++) {
6174 struct triple *piece;
6176 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6177 atype = param->left;
6179 if (!TYPE_ARITHMETIC(atype->type) &&
6180 !TYPE_PTR(atype->type)) {
6181 internal_error(state, 0, "Invalid lhs type");
6183 piece = triple(state, OP_PIECE, atype, work, 0);
6185 LHS(work, i) = piece;
6186 RHS(val, i) = piece;
6191 work = write_expr(state, result, work);
6193 work = flatten(state, first, work);
6194 last = flatten(state, first, label(state));
6195 name_len = strlen(name);
6196 ident = lookup(state, name, name_len);
6197 symbol(state, ident, &ident->sym_ident, def, ftype);
6199 state->file = file.prev;
6201 fprintf(stdout, "\n");
6202 loc(stdout, state, 0);
6203 fprintf(stdout, "\n__________ builtin_function _________\n");
6204 print_triple(state, def);
6205 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6209 static struct type *partial_struct(struct compile_state *state,
6210 const char *field_name, struct type *type, struct type *rest)
6212 struct hash_entry *field_ident;
6213 struct type *result;
6216 field_name_len = strlen(field_name);
6217 field_ident = lookup(state, field_name, field_name_len);
6219 result = clone_type(0, type);
6220 result->field_ident = field_ident;
6223 result = new_type(TYPE_PRODUCT, result, rest);
6228 static struct type *register_builtin_type(struct compile_state *state,
6229 const char *name, struct type *type)
6231 struct hash_entry *ident;
6234 name_len = strlen(name);
6235 ident = lookup(state, name, name_len);
6237 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6238 ulong_t elements = 0;
6240 type = new_type(TYPE_STRUCT, type, 0);
6242 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6244 field = field->right;
6247 symbol(state, ident, &ident->sym_struct, 0, type);
6248 type->type_ident = ident;
6249 type->elements = elements;
6251 symbol(state, ident, &ident->sym_ident, 0, type);
6252 ident->tok = TOK_TYPE_NAME;
6257 static void register_builtins(struct compile_state *state)
6259 struct type *msr_type;
6261 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6263 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6265 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6268 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6269 &uchar_type, &ushort_type);
6270 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6271 &ushort_type, &ushort_type);
6272 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6273 &uint_type, &ushort_type);
6275 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6277 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6280 msr_type = register_builtin_type(state, "__builtin_msr_t",
6281 partial_struct(state, "lo", &ulong_type,
6282 partial_struct(state, "hi", &ulong_type, 0)));
6284 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6286 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6287 &ulong_type, &ulong_type, &ulong_type);
6289 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6293 static struct type *declarator(
6294 struct compile_state *state, struct type *type,
6295 struct hash_entry **ident, int need_ident);
6296 static void decl(struct compile_state *state, struct triple *first);
6297 static struct type *specifier_qualifier_list(struct compile_state *state);
6298 static int isdecl_specifier(int tok);
6299 static struct type *decl_specifiers(struct compile_state *state);
6300 static int istype(int tok);
6301 static struct triple *expr(struct compile_state *state);
6302 static struct triple *assignment_expr(struct compile_state *state);
6303 static struct type *type_name(struct compile_state *state);
6304 static void statement(struct compile_state *state, struct triple *fist);
6306 static struct triple *call_expr(
6307 struct compile_state *state, struct triple *func)
6310 struct type *param, *type;
6311 ulong_t pvals, index;
6313 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6314 error(state, 0, "Called object is not a function");
6316 if (func->op != OP_LIST) {
6317 internal_error(state, 0, "improper function");
6319 eat(state, TOK_LPAREN);
6320 /* Find the return type without any specifiers */
6321 type = clone_type(0, func->type->left);
6322 def = new_triple(state, OP_CALL, func->type, -1);
6325 pvals = TRIPLE_RHS(def->sizes);
6326 MISC(def, 0) = func;
6328 param = func->type->right;
6329 for(index = 0; index < pvals; index++) {
6331 struct type *arg_type;
6332 val = read_expr(state, assignment_expr(state));
6334 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6335 arg_type = param->left;
6337 write_compatible(state, arg_type, val->type);
6338 RHS(def, index) = val;
6339 if (index != (pvals - 1)) {
6340 eat(state, TOK_COMMA);
6341 param = param->right;
6344 eat(state, TOK_RPAREN);
6349 static struct triple *character_constant(struct compile_state *state)
6353 const signed char *str, *end;
6356 eat(state, TOK_LIT_CHAR);
6357 tk = &state->token[0];
6358 str = tk->val.str + 1;
6359 str_len = tk->str_len - 2;
6361 error(state, 0, "empty character constant");
6363 end = str + str_len;
6364 c = char_value(state, &str, end);
6366 error(state, 0, "multibyte character constant not supported");
6368 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6372 static struct triple *string_constant(struct compile_state *state)
6377 const signed char *str, *end;
6378 signed char *buf, *ptr;
6382 type = new_type(TYPE_ARRAY, &char_type, 0);
6384 /* The while loop handles string concatenation */
6386 eat(state, TOK_LIT_STRING);
6387 tk = &state->token[0];
6388 str = tk->val.str + 1;
6389 str_len = tk->str_len - 2;
6391 error(state, 0, "negative string constant length");
6393 end = str + str_len;
6395 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6396 memcpy(buf, ptr, type->elements);
6397 ptr = buf + type->elements;
6399 *ptr++ = char_value(state, &str, end);
6401 type->elements = ptr - buf;
6402 } while(peek(state) == TOK_LIT_STRING);
6404 type->elements += 1;
6405 def = triple(state, OP_BLOBCONST, type, 0, 0);
6411 static struct triple *integer_constant(struct compile_state *state)
6420 eat(state, TOK_LIT_INT);
6421 tk = &state->token[0];
6423 decimal = (tk->val.str[0] != '0');
6424 val = strtoul(tk->val.str, &end, 0);
6425 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6426 error(state, 0, "Integer constant to large");
6429 if ((*end == 'u') || (*end == 'U')) {
6433 if ((*end == 'l') || (*end == 'L')) {
6437 if ((*end == 'u') || (*end == 'U')) {
6442 error(state, 0, "Junk at end of integer constant");
6449 if (!decimal && (val > LONG_MAX)) {
6455 if (val > UINT_MAX) {
6461 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6464 else if (!decimal && (val > LONG_MAX)) {
6467 else if (val > INT_MAX) {
6471 def = int_const(state, type, val);
6475 static struct triple *primary_expr(struct compile_state *state)
6483 struct hash_entry *ident;
6484 /* Here ident is either:
6487 * an enumeration constant.
6489 eat(state, TOK_IDENT);
6490 ident = state->token[0].ident;
6491 if (!ident->sym_ident) {
6492 error(state, 0, "%s undeclared", ident->name);
6494 def = ident->sym_ident->def;
6497 case TOK_ENUM_CONST:
6498 /* Here ident is an enumeration constant */
6499 eat(state, TOK_ENUM_CONST);
6504 eat(state, TOK_LPAREN);
6506 eat(state, TOK_RPAREN);
6509 def = integer_constant(state);
6512 eat(state, TOK_LIT_FLOAT);
6513 error(state, 0, "Floating point constants not supported");
6518 def = character_constant(state);
6520 case TOK_LIT_STRING:
6521 def = string_constant(state);
6525 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6530 static struct triple *postfix_expr(struct compile_state *state)
6534 def = primary_expr(state);
6536 struct triple *left;
6540 switch((tok = peek(state))) {
6542 eat(state, TOK_LBRACKET);
6543 def = mk_subscript_expr(state, left, expr(state));
6544 eat(state, TOK_RBRACKET);
6547 def = call_expr(state, def);
6551 struct hash_entry *field;
6552 eat(state, TOK_DOT);
6553 eat(state, TOK_IDENT);
6554 field = state->token[0].ident;
6555 def = deref_field(state, def, field);
6560 struct hash_entry *field;
6561 eat(state, TOK_ARROW);
6562 eat(state, TOK_IDENT);
6563 field = state->token[0].ident;
6564 def = mk_deref_expr(state, read_expr(state, def));
6565 def = deref_field(state, def, field);
6569 eat(state, TOK_PLUSPLUS);
6570 def = mk_post_inc_expr(state, left);
6572 case TOK_MINUSMINUS:
6573 eat(state, TOK_MINUSMINUS);
6574 def = mk_post_dec_expr(state, left);
6584 static struct triple *cast_expr(struct compile_state *state);
6586 static struct triple *unary_expr(struct compile_state *state)
6588 struct triple *def, *right;
6590 switch((tok = peek(state))) {
6592 eat(state, TOK_PLUSPLUS);
6593 def = mk_pre_inc_expr(state, unary_expr(state));
6595 case TOK_MINUSMINUS:
6596 eat(state, TOK_MINUSMINUS);
6597 def = mk_pre_dec_expr(state, unary_expr(state));
6600 eat(state, TOK_AND);
6601 def = mk_addr_expr(state, cast_expr(state), 0);
6604 eat(state, TOK_STAR);
6605 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6608 eat(state, TOK_PLUS);
6609 right = read_expr(state, cast_expr(state));
6610 arithmetic(state, right);
6611 def = integral_promotion(state, right);
6614 eat(state, TOK_MINUS);
6615 right = read_expr(state, cast_expr(state));
6616 arithmetic(state, right);
6617 def = integral_promotion(state, right);
6618 def = triple(state, OP_NEG, def->type, def, 0);
6621 eat(state, TOK_TILDE);
6622 right = read_expr(state, cast_expr(state));
6623 integral(state, right);
6624 def = integral_promotion(state, right);
6625 def = triple(state, OP_INVERT, def->type, def, 0);
6628 eat(state, TOK_BANG);
6629 right = read_expr(state, cast_expr(state));
6631 def = lfalse_expr(state, right);
6637 eat(state, TOK_SIZEOF);
6639 tok2 = peek2(state);
6640 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6641 eat(state, TOK_LPAREN);
6642 type = type_name(state);
6643 eat(state, TOK_RPAREN);
6646 struct triple *expr;
6647 expr = unary_expr(state);
6649 release_expr(state, expr);
6651 def = int_const(state, &ulong_type, size_of(state, type));
6658 eat(state, TOK_ALIGNOF);
6660 tok2 = peek2(state);
6661 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6662 eat(state, TOK_LPAREN);
6663 type = type_name(state);
6664 eat(state, TOK_RPAREN);
6667 struct triple *expr;
6668 expr = unary_expr(state);
6670 release_expr(state, expr);
6672 def = int_const(state, &ulong_type, align_of(state, type));
6676 def = postfix_expr(state);
6682 static struct triple *cast_expr(struct compile_state *state)
6687 tok2 = peek2(state);
6688 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6690 eat(state, TOK_LPAREN);
6691 type = type_name(state);
6692 eat(state, TOK_RPAREN);
6693 def = read_expr(state, cast_expr(state));
6694 def = triple(state, OP_COPY, type, def, 0);
6695 #warning "FIXME do I need an OP_CAST expr to be semantically correct here?"
6698 def = unary_expr(state);
6703 static struct triple *mult_expr(struct compile_state *state)
6707 def = cast_expr(state);
6709 struct triple *left, *right;
6710 struct type *result_type;
6713 switch(tok = (peek(state))) {
6717 left = read_expr(state, def);
6718 arithmetic(state, left);
6722 right = read_expr(state, cast_expr(state));
6723 arithmetic(state, right);
6725 result_type = arithmetic_result(state, left, right);
6726 sign = is_signed(result_type);
6729 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6730 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
6731 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
6733 def = triple(state, op, result_type, left, right);
6743 static struct triple *add_expr(struct compile_state *state)
6747 def = mult_expr(state);
6750 switch( peek(state)) {
6752 eat(state, TOK_PLUS);
6753 def = mk_add_expr(state, def, mult_expr(state));
6756 eat(state, TOK_MINUS);
6757 def = mk_sub_expr(state, def, mult_expr(state));
6767 static struct triple *shift_expr(struct compile_state *state)
6771 def = add_expr(state);
6773 struct triple *left, *right;
6776 switch((tok = peek(state))) {
6779 left = read_expr(state, def);
6780 integral(state, left);
6781 left = integral_promotion(state, left);
6785 right = read_expr(state, add_expr(state));
6786 integral(state, right);
6787 right = integral_promotion(state, right);
6789 op = (tok == TOK_SL)? OP_SL :
6790 is_signed(left->type)? OP_SSR: OP_USR;
6792 def = triple(state, op, left->type, left, right);
6802 static struct triple *relational_expr(struct compile_state *state)
6804 #warning "Extend relational exprs to work on more than arithmetic types"
6807 def = shift_expr(state);
6809 struct triple *left, *right;
6810 struct type *arg_type;
6813 switch((tok = peek(state))) {
6818 left = read_expr(state, def);
6819 arithmetic(state, left);
6823 right = read_expr(state, shift_expr(state));
6824 arithmetic(state, right);
6826 arg_type = arithmetic_result(state, left, right);
6827 sign = is_signed(arg_type);
6830 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
6831 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
6832 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
6833 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
6835 def = triple(state, op, &int_type, left, right);
6845 static struct triple *equality_expr(struct compile_state *state)
6847 #warning "Extend equality exprs to work on more than arithmetic types"
6850 def = relational_expr(state);
6852 struct triple *left, *right;
6855 switch((tok = peek(state))) {
6858 left = read_expr(state, def);
6859 arithmetic(state, left);
6861 right = read_expr(state, relational_expr(state));
6862 arithmetic(state, right);
6863 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
6864 def = triple(state, op, &int_type, left, right);
6874 static struct triple *and_expr(struct compile_state *state)
6877 def = equality_expr(state);
6878 while(peek(state) == TOK_AND) {
6879 struct triple *left, *right;
6880 struct type *result_type;
6881 left = read_expr(state, def);
6882 integral(state, left);
6883 eat(state, TOK_AND);
6884 right = read_expr(state, equality_expr(state));
6885 integral(state, right);
6886 result_type = arithmetic_result(state, left, right);
6887 def = triple(state, OP_AND, result_type, left, right);
6892 static struct triple *xor_expr(struct compile_state *state)
6895 def = and_expr(state);
6896 while(peek(state) == TOK_XOR) {
6897 struct triple *left, *right;
6898 struct type *result_type;
6899 left = read_expr(state, def);
6900 integral(state, left);
6901 eat(state, TOK_XOR);
6902 right = read_expr(state, and_expr(state));
6903 integral(state, right);
6904 result_type = arithmetic_result(state, left, right);
6905 def = triple(state, OP_XOR, result_type, left, right);
6910 static struct triple *or_expr(struct compile_state *state)
6913 def = xor_expr(state);
6914 while(peek(state) == TOK_OR) {
6915 struct triple *left, *right;
6916 struct type *result_type;
6917 left = read_expr(state, def);
6918 integral(state, left);
6920 right = read_expr(state, xor_expr(state));
6921 integral(state, right);
6922 result_type = arithmetic_result(state, left, right);
6923 def = triple(state, OP_OR, result_type, left, right);
6928 static struct triple *land_expr(struct compile_state *state)
6931 def = or_expr(state);
6932 while(peek(state) == TOK_LOGAND) {
6933 struct triple *left, *right;
6934 left = read_expr(state, def);
6936 eat(state, TOK_LOGAND);
6937 right = read_expr(state, or_expr(state));
6940 def = triple(state, OP_LAND, &int_type,
6941 ltrue_expr(state, left),
6942 ltrue_expr(state, right));
6947 static struct triple *lor_expr(struct compile_state *state)
6950 def = land_expr(state);
6951 while(peek(state) == TOK_LOGOR) {
6952 struct triple *left, *right;
6953 left = read_expr(state, def);
6955 eat(state, TOK_LOGOR);
6956 right = read_expr(state, land_expr(state));
6959 def = triple(state, OP_LOR, &int_type,
6960 ltrue_expr(state, left),
6961 ltrue_expr(state, right));
6966 static struct triple *conditional_expr(struct compile_state *state)
6969 def = lor_expr(state);
6970 if (peek(state) == TOK_QUEST) {
6971 struct triple *test, *left, *right;
6973 test = ltrue_expr(state, read_expr(state, def));
6974 eat(state, TOK_QUEST);
6975 left = read_expr(state, expr(state));
6976 eat(state, TOK_COLON);
6977 right = read_expr(state, conditional_expr(state));
6979 def = cond_expr(state, test, left, right);
6984 static struct triple *eval_const_expr(
6985 struct compile_state *state, struct triple *expr)
6988 struct triple *head, *ptr;
6989 head = label(state); /* dummy initial triple */
6990 flatten(state, head, expr);
6991 for(ptr = head->next; ptr != head; ptr = ptr->next) {
6992 simplify(state, ptr);
6994 /* Remove the constant value the tail of the list */
6996 def->prev->next = def->next;
6997 def->next->prev = def->prev;
6998 def->next = def->prev = def;
6999 if (!is_const(def)) {
7000 internal_error(state, 0, "Not a constant expression");
7002 /* Free the intermediate expressions */
7003 while(head->next != head) {
7004 release_triple(state, head->next);
7006 free_triple(state, head);
7010 static struct triple *constant_expr(struct compile_state *state)
7012 return eval_const_expr(state, conditional_expr(state));
7015 static struct triple *assignment_expr(struct compile_state *state)
7017 struct triple *def, *left, *right;
7019 /* The C grammer in K&R shows assignment expressions
7020 * only taking unary expressions as input on their
7021 * left hand side. But specifies the precedence of
7022 * assignemnt as the lowest operator except for comma.
7024 * Allowing conditional expressions on the left hand side
7025 * of an assignement results in a grammar that accepts
7026 * a larger set of statements than standard C. As long
7027 * as the subset of the grammar that is standard C behaves
7028 * correctly this should cause no problems.
7030 * For the extra token strings accepted by the grammar
7031 * none of them should produce a valid lvalue, so they
7032 * should not produce functioning programs.
7034 * GCC has this bug as well, so surprises should be minimal.
7036 def = conditional_expr(state);
7038 switch((tok = peek(state))) {
7040 lvalue(state, left);
7042 def = write_expr(state, left,
7043 read_expr(state, assignment_expr(state)));
7050 lvalue(state, left);
7051 arithmetic(state, left);
7053 right = read_expr(state, assignment_expr(state));
7054 arithmetic(state, right);
7056 sign = is_signed(left->type);
7059 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7060 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7061 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7062 case TOK_PLUSEQ: op = OP_ADD; break;
7063 case TOK_MINUSEQ: op = OP_SUB; break;
7065 def = write_expr(state, left,
7066 triple(state, op, left->type,
7067 read_expr(state, left), right));
7074 lvalue(state, left);
7075 integral(state, left);
7077 right = read_expr(state, assignment_expr(state));
7078 integral(state, right);
7079 right = integral_promotion(state, right);
7080 sign = is_signed(left->type);
7083 case TOK_SLEQ: op = OP_SL; break;
7084 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7085 case TOK_ANDEQ: op = OP_AND; break;
7086 case TOK_XOREQ: op = OP_XOR; break;
7087 case TOK_OREQ: op = OP_OR; break;
7089 def = write_expr(state, left,
7090 triple(state, op, left->type,
7091 read_expr(state, left), right));
7097 static struct triple *expr(struct compile_state *state)
7100 def = assignment_expr(state);
7101 while(peek(state) == TOK_COMMA) {
7102 struct triple *left, *right;
7104 eat(state, TOK_COMMA);
7105 right = assignment_expr(state);
7106 def = triple(state, OP_COMMA, right->type, left, right);
7111 static void expr_statement(struct compile_state *state, struct triple *first)
7113 if (peek(state) != TOK_SEMI) {
7114 flatten(state, first, expr(state));
7116 eat(state, TOK_SEMI);
7119 static void if_statement(struct compile_state *state, struct triple *first)
7121 struct triple *test, *jmp1, *jmp2, *middle, *end;
7123 jmp1 = jmp2 = middle = 0;
7125 eat(state, TOK_LPAREN);
7128 /* Cleanup and invert the test */
7129 test = lfalse_expr(state, read_expr(state, test));
7130 eat(state, TOK_RPAREN);
7131 /* Generate the needed pieces */
7132 middle = label(state);
7133 jmp1 = branch(state, middle, test);
7134 /* Thread the pieces together */
7135 flatten(state, first, test);
7136 flatten(state, first, jmp1);
7137 flatten(state, first, label(state));
7138 statement(state, first);
7139 if (peek(state) == TOK_ELSE) {
7140 eat(state, TOK_ELSE);
7141 /* Generate the rest of the pieces */
7143 jmp2 = branch(state, end, 0);
7144 /* Thread them together */
7145 flatten(state, first, jmp2);
7146 flatten(state, first, middle);
7147 statement(state, first);
7148 flatten(state, first, end);
7151 flatten(state, first, middle);
7155 static void for_statement(struct compile_state *state, struct triple *first)
7157 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7158 struct triple *label1, *label2, *label3;
7159 struct hash_entry *ident;
7161 eat(state, TOK_FOR);
7162 eat(state, TOK_LPAREN);
7163 head = test = tail = jmp1 = jmp2 = 0;
7164 if (peek(state) != TOK_SEMI) {
7167 eat(state, TOK_SEMI);
7168 if (peek(state) != TOK_SEMI) {
7171 test = ltrue_expr(state, read_expr(state, test));
7173 eat(state, TOK_SEMI);
7174 if (peek(state) != TOK_RPAREN) {
7177 eat(state, TOK_RPAREN);
7178 /* Generate the needed pieces */
7179 label1 = label(state);
7180 label2 = label(state);
7181 label3 = label(state);
7183 jmp1 = branch(state, label3, 0);
7184 jmp2 = branch(state, label1, test);
7187 jmp2 = branch(state, label1, 0);
7190 /* Remember where break and continue go */
7192 ident = state->i_break;
7193 symbol(state, ident, &ident->sym_ident, end, end->type);
7194 ident = state->i_continue;
7195 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7196 /* Now include the body */
7197 flatten(state, first, head);
7198 flatten(state, first, jmp1);
7199 flatten(state, first, label1);
7200 statement(state, first);
7201 flatten(state, first, label2);
7202 flatten(state, first, tail);
7203 flatten(state, first, label3);
7204 flatten(state, first, test);
7205 flatten(state, first, jmp2);
7206 flatten(state, first, end);
7207 /* Cleanup the break/continue scope */
7211 static void while_statement(struct compile_state *state, struct triple *first)
7213 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7214 struct hash_entry *ident;
7215 eat(state, TOK_WHILE);
7216 eat(state, TOK_LPAREN);
7219 test = ltrue_expr(state, read_expr(state, test));
7220 eat(state, TOK_RPAREN);
7221 /* Generate the needed pieces */
7222 label1 = label(state);
7223 label2 = label(state);
7224 jmp1 = branch(state, label2, 0);
7225 jmp2 = branch(state, label1, test);
7227 /* Remember where break and continue go */
7229 ident = state->i_break;
7230 symbol(state, ident, &ident->sym_ident, end, end->type);
7231 ident = state->i_continue;
7232 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7233 /* Thread them together */
7234 flatten(state, first, jmp1);
7235 flatten(state, first, label1);
7236 statement(state, first);
7237 flatten(state, first, label2);
7238 flatten(state, first, test);
7239 flatten(state, first, jmp2);
7240 flatten(state, first, end);
7241 /* Cleanup the break/continue scope */
7245 static void do_statement(struct compile_state *state, struct triple *first)
7247 struct triple *label1, *label2, *test, *end;
7248 struct hash_entry *ident;
7250 /* Generate the needed pieces */
7251 label1 = label(state);
7252 label2 = label(state);
7254 /* Remember where break and continue go */
7256 ident = state->i_break;
7257 symbol(state, ident, &ident->sym_ident, end, end->type);
7258 ident = state->i_continue;
7259 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7260 /* Now include the body */
7261 flatten(state, first, label1);
7262 statement(state, first);
7263 /* Cleanup the break/continue scope */
7265 /* Eat the rest of the loop */
7266 eat(state, TOK_WHILE);
7267 eat(state, TOK_LPAREN);
7268 test = read_expr(state, expr(state));
7270 eat(state, TOK_RPAREN);
7271 eat(state, TOK_SEMI);
7272 /* Thread the pieces together */
7273 test = ltrue_expr(state, test);
7274 flatten(state, first, label2);
7275 flatten(state, first, test);
7276 flatten(state, first, branch(state, label1, test));
7277 flatten(state, first, end);
7281 static void return_statement(struct compile_state *state, struct triple *first)
7283 struct triple *jmp, *mv, *dest, *var, *val;
7285 eat(state, TOK_RETURN);
7287 #warning "FIXME implement a more general excess branch elimination"
7289 /* If we have a return value do some more work */
7290 if (peek(state) != TOK_SEMI) {
7291 val = read_expr(state, expr(state));
7293 eat(state, TOK_SEMI);
7295 /* See if this last statement in a function */
7296 last = ((peek(state) == TOK_RBRACE) &&
7297 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7299 /* Find the return variable */
7300 var = MISC(state->main_function, 0);
7301 /* Find the return destination */
7302 dest = RHS(state->main_function, 0)->prev;
7304 /* If needed generate a jump instruction */
7306 jmp = branch(state, dest, 0);
7308 /* If needed generate an assignment instruction */
7310 mv = write_expr(state, var, val);
7312 /* Now put the code together */
7314 flatten(state, first, mv);
7315 flatten(state, first, jmp);
7318 flatten(state, first, jmp);
7322 static void break_statement(struct compile_state *state, struct triple *first)
7324 struct triple *dest;
7325 eat(state, TOK_BREAK);
7326 eat(state, TOK_SEMI);
7327 if (!state->i_break->sym_ident) {
7328 error(state, 0, "break statement not within loop or switch");
7330 dest = state->i_break->sym_ident->def;
7331 flatten(state, first, branch(state, dest, 0));
7334 static void continue_statement(struct compile_state *state, struct triple *first)
7336 struct triple *dest;
7337 eat(state, TOK_CONTINUE);
7338 eat(state, TOK_SEMI);
7339 if (!state->i_continue->sym_ident) {
7340 error(state, 0, "continue statement outside of a loop");
7342 dest = state->i_continue->sym_ident->def;
7343 flatten(state, first, branch(state, dest, 0));
7346 static void goto_statement(struct compile_state *state, struct triple *first)
7349 eat(state, TOK_GOTO);
7350 eat(state, TOK_IDENT);
7351 eat(state, TOK_SEMI);
7352 error(state, 0, "goto is not implemeted");
7356 static void labeled_statement(struct compile_state *state, struct triple *first)
7359 eat(state, TOK_IDENT);
7360 eat(state, TOK_COLON);
7361 statement(state, first);
7362 error(state, 0, "labeled statements are not implemented");
7366 static void switch_statement(struct compile_state *state, struct triple *first)
7369 eat(state, TOK_SWITCH);
7370 eat(state, TOK_LPAREN);
7372 eat(state, TOK_RPAREN);
7373 statement(state, first);
7374 error(state, 0, "switch statements are not implemented");
7378 static void case_statement(struct compile_state *state, struct triple *first)
7381 eat(state, TOK_CASE);
7382 constant_expr(state);
7383 eat(state, TOK_COLON);
7384 statement(state, first);
7385 error(state, 0, "case statements are not implemented");
7389 static void default_statement(struct compile_state *state, struct triple *first)
7392 eat(state, TOK_DEFAULT);
7393 eat(state, TOK_COLON);
7394 statement(state, first);
7395 error(state, 0, "default statements are not implemented");
7399 static void asm_statement(struct compile_state *state, struct triple *first)
7402 error(state, 0, "FIXME finish asm_statement");
7406 static int isdecl(int tok)
7429 case TOK_TYPE_NAME: /* typedef name */
7436 static void compound_statement(struct compile_state *state, struct triple *first)
7438 eat(state, TOK_LBRACE);
7441 /* statement-list opt */
7442 while (peek(state) != TOK_RBRACE) {
7443 statement(state, first);
7446 eat(state, TOK_RBRACE);
7449 static void statement(struct compile_state *state, struct triple *first)
7453 if (tok == TOK_LBRACE) {
7454 compound_statement(state, first);
7456 else if (tok == TOK_IF) {
7457 if_statement(state, first);
7459 else if (tok == TOK_FOR) {
7460 for_statement(state, first);
7462 else if (tok == TOK_WHILE) {
7463 while_statement(state, first);
7465 else if (tok == TOK_DO) {
7466 do_statement(state, first);
7468 else if (tok == TOK_RETURN) {
7469 return_statement(state, first);
7471 else if (tok == TOK_BREAK) {
7472 break_statement(state, first);
7474 else if (tok == TOK_CONTINUE) {
7475 continue_statement(state, first);
7477 else if (tok == TOK_GOTO) {
7478 goto_statement(state, first);
7480 else if (tok == TOK_SWITCH) {
7481 switch_statement(state, first);
7483 else if (tok == TOK_ASM) {
7484 asm_statement(state, first);
7486 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7487 labeled_statement(state, first);
7489 else if (tok == TOK_CASE) {
7490 case_statement(state, first);
7492 else if (tok == TOK_DEFAULT) {
7493 default_statement(state, first);
7495 else if (isdecl(tok)) {
7496 /* This handles C99 intermixing of statements and decls */
7500 expr_statement(state, first);
7504 static struct type *param_decl(struct compile_state *state)
7507 struct hash_entry *ident;
7508 /* Cheat so the declarator will know we are not global */
7511 type = decl_specifiers(state);
7512 type = declarator(state, type, &ident, 0);
7513 type->field_ident = ident;
7518 static struct type *param_type_list(struct compile_state *state, struct type *type)
7520 struct type *ftype, **next;
7521 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7522 next = &ftype->right;
7523 while(peek(state) == TOK_COMMA) {
7524 eat(state, TOK_COMMA);
7525 if (peek(state) == TOK_DOTS) {
7526 eat(state, TOK_DOTS);
7527 error(state, 0, "variadic functions not supported");
7530 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7531 next = &((*next)->right);
7538 static struct type *type_name(struct compile_state *state)
7541 type = specifier_qualifier_list(state);
7542 /* abstract-declarator (may consume no tokens) */
7543 type = declarator(state, type, 0, 0);
7547 static struct type *direct_declarator(
7548 struct compile_state *state, struct type *type,
7549 struct hash_entry **ident, int need_ident)
7554 arrays_complete(state, type);
7555 switch(peek(state)) {
7557 eat(state, TOK_IDENT);
7559 error(state, 0, "Unexpected identifier found");
7561 /* The name of what we are declaring */
7562 *ident = state->token[0].ident;
7565 eat(state, TOK_LPAREN);
7566 outer = declarator(state, type, ident, need_ident);
7567 eat(state, TOK_RPAREN);
7571 error(state, 0, "Identifier expected");
7577 arrays_complete(state, type);
7578 switch(peek(state)) {
7580 eat(state, TOK_LPAREN);
7581 type = param_type_list(state, type);
7582 eat(state, TOK_RPAREN);
7586 unsigned int qualifiers;
7587 struct triple *value;
7589 eat(state, TOK_LBRACKET);
7590 if (peek(state) != TOK_RBRACKET) {
7591 value = constant_expr(state);
7592 integral(state, value);
7594 eat(state, TOK_RBRACKET);
7596 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
7597 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
7599 type->elements = value->u.cval;
7600 free_triple(state, value);
7602 type->elements = ELEMENT_COUNT_UNSPECIFIED;
7614 arrays_complete(state, type);
7616 for(inner = outer; inner->left; inner = inner->left)
7624 static struct type *declarator(
7625 struct compile_state *state, struct type *type,
7626 struct hash_entry **ident, int need_ident)
7628 while(peek(state) == TOK_STAR) {
7629 eat(state, TOK_STAR);
7630 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
7632 type = direct_declarator(state, type, ident, need_ident);
7637 static struct type *typedef_name(
7638 struct compile_state *state, unsigned int specifiers)
7640 struct hash_entry *ident;
7642 eat(state, TOK_TYPE_NAME);
7643 ident = state->token[0].ident;
7644 type = ident->sym_ident->type;
7645 specifiers |= type->type & QUAL_MASK;
7646 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
7647 (type->type & (STOR_MASK | QUAL_MASK))) {
7648 type = clone_type(specifiers, type);
7653 static struct type *enum_specifier(
7654 struct compile_state *state, unsigned int specifiers)
7660 eat(state, TOK_ENUM);
7662 if (tok == TOK_IDENT) {
7663 eat(state, TOK_IDENT);
7665 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
7666 eat(state, TOK_LBRACE);
7668 eat(state, TOK_IDENT);
7669 if (peek(state) == TOK_EQ) {
7671 constant_expr(state);
7673 if (peek(state) == TOK_COMMA) {
7674 eat(state, TOK_COMMA);
7676 } while(peek(state) != TOK_RBRACE);
7677 eat(state, TOK_RBRACE);
7684 static struct type *struct_declarator(
7685 struct compile_state *state, struct type *type, struct hash_entry **ident)
7688 #warning "struct_declarator is complicated because of bitfields, kill them?"
7690 if (tok != TOK_COLON) {
7691 type = declarator(state, type, ident, 1);
7693 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
7694 eat(state, TOK_COLON);
7695 constant_expr(state);
7702 static struct type *struct_or_union_specifier(
7703 struct compile_state *state, unsigned int specifiers)
7705 struct type *struct_type;
7706 struct hash_entry *ident;
7707 unsigned int type_join;
7711 switch(peek(state)) {
7713 eat(state, TOK_STRUCT);
7714 type_join = TYPE_PRODUCT;
7717 eat(state, TOK_UNION);
7718 type_join = TYPE_OVERLAP;
7719 error(state, 0, "unions not yet supported\n");
7722 eat(state, TOK_STRUCT);
7723 type_join = TYPE_PRODUCT;
7727 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
7729 ident = state->token[0].ident;
7731 if (!ident || (peek(state) == TOK_LBRACE)) {
7734 eat(state, TOK_LBRACE);
7736 struct type *base_type;
7739 base_type = specifier_qualifier_list(state);
7740 next = &struct_type;
7743 struct hash_entry *fident;
7745 type = declarator(state, base_type, &fident, 1);
7747 if (peek(state) == TOK_COMMA) {
7749 eat(state, TOK_COMMA);
7751 type = clone_type(0, type);
7752 type->field_ident = fident;
7754 *next = new_type(type_join, *next, type);
7755 next = &((*next)->right);
7760 eat(state, TOK_SEMI);
7761 } while(peek(state) != TOK_RBRACE);
7762 eat(state, TOK_RBRACE);
7763 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
7764 struct_type->type_ident = ident;
7765 struct_type->elements = elements;
7766 symbol(state, ident, &ident->sym_struct, 0, struct_type);
7768 if (ident && ident->sym_struct) {
7769 struct_type = ident->sym_struct->type;
7771 else if (ident && !ident->sym_struct) {
7772 error(state, 0, "struct %s undeclared", ident->name);
7777 static unsigned int storage_class_specifier_opt(struct compile_state *state)
7779 unsigned int specifiers;
7780 switch(peek(state)) {
7782 eat(state, TOK_AUTO);
7783 specifiers = STOR_AUTO;
7786 eat(state, TOK_REGISTER);
7787 specifiers = STOR_REGISTER;
7790 eat(state, TOK_STATIC);
7791 specifiers = STOR_STATIC;
7794 eat(state, TOK_EXTERN);
7795 specifiers = STOR_EXTERN;
7798 eat(state, TOK_TYPEDEF);
7799 specifiers = STOR_TYPEDEF;
7802 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
7803 specifiers = STOR_STATIC;
7806 specifiers = STOR_AUTO;
7812 static unsigned int function_specifier_opt(struct compile_state *state)
7814 /* Ignore the inline keyword */
7815 unsigned int specifiers;
7817 switch(peek(state)) {
7819 eat(state, TOK_INLINE);
7820 specifiers = STOR_INLINE;
7825 static unsigned int type_qualifiers(struct compile_state *state)
7827 unsigned int specifiers;
7830 specifiers = QUAL_NONE;
7832 switch(peek(state)) {
7834 eat(state, TOK_CONST);
7835 specifiers = QUAL_CONST;
7838 eat(state, TOK_VOLATILE);
7839 specifiers = QUAL_VOLATILE;
7842 eat(state, TOK_RESTRICT);
7843 specifiers = QUAL_RESTRICT;
7853 static struct type *type_specifier(
7854 struct compile_state *state, unsigned int spec)
7858 switch(peek(state)) {
7860 eat(state, TOK_VOID);
7861 type = new_type(TYPE_VOID | spec, 0, 0);
7864 eat(state, TOK_CHAR);
7865 type = new_type(TYPE_CHAR | spec, 0, 0);
7868 eat(state, TOK_SHORT);
7869 if (peek(state) == TOK_INT) {
7870 eat(state, TOK_INT);
7872 type = new_type(TYPE_SHORT | spec, 0, 0);
7875 eat(state, TOK_INT);
7876 type = new_type(TYPE_INT | spec, 0, 0);
7879 eat(state, TOK_LONG);
7880 switch(peek(state)) {
7882 eat(state, TOK_LONG);
7883 error(state, 0, "long long not supported");
7886 eat(state, TOK_DOUBLE);
7887 error(state, 0, "long double not supported");
7890 eat(state, TOK_INT);
7891 type = new_type(TYPE_LONG | spec, 0, 0);
7894 type = new_type(TYPE_LONG | spec, 0, 0);
7899 eat(state, TOK_FLOAT);
7900 error(state, 0, "type float not supported");
7903 eat(state, TOK_DOUBLE);
7904 error(state, 0, "type double not supported");
7907 eat(state, TOK_SIGNED);
7908 switch(peek(state)) {
7910 eat(state, TOK_LONG);
7911 switch(peek(state)) {
7913 eat(state, TOK_LONG);
7914 error(state, 0, "type long long not supported");
7917 eat(state, TOK_INT);
7918 type = new_type(TYPE_LONG | spec, 0, 0);
7921 type = new_type(TYPE_LONG | spec, 0, 0);
7926 eat(state, TOK_INT);
7927 type = new_type(TYPE_INT | spec, 0, 0);
7930 eat(state, TOK_SHORT);
7931 type = new_type(TYPE_SHORT | spec, 0, 0);
7934 eat(state, TOK_CHAR);
7935 type = new_type(TYPE_CHAR | spec, 0, 0);
7938 type = new_type(TYPE_INT | spec, 0, 0);
7943 eat(state, TOK_UNSIGNED);
7944 switch(peek(state)) {
7946 eat(state, TOK_LONG);
7947 switch(peek(state)) {
7949 eat(state, TOK_LONG);
7950 error(state, 0, "unsigned long long not supported");
7953 eat(state, TOK_INT);
7954 type = new_type(TYPE_ULONG | spec, 0, 0);
7957 type = new_type(TYPE_ULONG | spec, 0, 0);
7962 eat(state, TOK_INT);
7963 type = new_type(TYPE_UINT | spec, 0, 0);
7966 eat(state, TOK_SHORT);
7967 type = new_type(TYPE_USHORT | spec, 0, 0);
7970 eat(state, TOK_CHAR);
7971 type = new_type(TYPE_UCHAR | spec, 0, 0);
7974 type = new_type(TYPE_UINT | spec, 0, 0);
7978 /* struct or union specifier */
7981 type = struct_or_union_specifier(state, spec);
7983 /* enum-spefifier */
7985 type = enum_specifier(state, spec);
7989 type = typedef_name(state, spec);
7992 error(state, 0, "bad type specifier %s",
7993 tokens[peek(state)]);
7999 static int istype(int tok)
8025 static struct type *specifier_qualifier_list(struct compile_state *state)
8028 unsigned int specifiers = 0;
8030 /* type qualifiers */
8031 specifiers |= type_qualifiers(state);
8033 /* type specifier */
8034 type = type_specifier(state, specifiers);
8039 static int isdecl_specifier(int tok)
8042 /* storage class specifier */
8048 /* type qualifier */
8052 /* type specifiers */
8062 /* struct or union specifier */
8065 /* enum-spefifier */
8069 /* function specifiers */
8077 static struct type *decl_specifiers(struct compile_state *state)
8080 unsigned int specifiers;
8081 /* I am overly restrictive in the arragement of specifiers supported.
8082 * C is overly flexible in this department it makes interpreting
8083 * the parse tree difficult.
8087 /* storage class specifier */
8088 specifiers |= storage_class_specifier_opt(state);
8090 /* function-specifier */
8091 specifiers |= function_specifier_opt(state);
8093 /* type qualifier */
8094 specifiers |= type_qualifiers(state);
8096 /* type specifier */
8097 type = type_specifier(state, specifiers);
8101 static unsigned designator(struct compile_state *state)
8107 switch(peek(state)) {
8110 struct triple *value;
8111 eat(state, TOK_LBRACKET);
8112 value = constant_expr(state);
8113 eat(state, TOK_RBRACKET);
8114 index = value->u.cval;
8118 eat(state, TOK_DOT);
8119 eat(state, TOK_IDENT);
8120 error(state, 0, "Struct Designators not currently supported");
8123 error(state, 0, "Invalid designator");
8126 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8131 static struct triple *initializer(
8132 struct compile_state *state, struct type *type)
8134 struct triple *result;
8135 if (peek(state) != TOK_LBRACE) {
8136 result = assignment_expr(state);
8140 unsigned index, max_index;
8142 max_index = index = 0;
8143 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8144 max_index = type->elements;
8145 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8149 error(state, 0, "Struct initializers not currently supported");
8151 buf = xcmalloc(size_of(state, type), "initializer");
8152 eat(state, TOK_LBRACE);
8154 struct triple *value;
8155 struct type *value_type;
8160 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8161 index = designator(state);
8163 if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8164 (index > max_index)) {
8165 error(state, 0, "element beyond bounds");
8168 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8169 value_type = type->left;
8171 value = eval_const_expr(state, initializer(state, value_type));
8172 value_size = size_of(state, value_type);
8173 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8174 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8175 (type->elements <= index)) {
8179 old_size = size_of(state, type);
8180 type->elements = index + 1;
8181 buf = xmalloc(size_of(state, type), "initializer");
8182 memcpy(buf, old_buf, old_size);
8185 if (value->op == OP_BLOBCONST) {
8186 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8188 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8189 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8191 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8192 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8194 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8195 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8198 fprintf(stderr, "%d %d\n",
8199 value->op, value_size);
8200 internal_error(state, 0, "unhandled constant initializer");
8202 if (peek(state) == TOK_COMMA) {
8203 eat(state, TOK_COMMA);
8207 } while(comma && (peek(state) != TOK_RBRACE));
8208 eat(state, TOK_RBRACE);
8209 result = triple(state, OP_BLOBCONST, type, 0, 0);
8210 result->u.blob = buf;
8215 static struct triple *function_definition(
8216 struct compile_state *state, struct type *type)
8218 struct triple *def, *tmp, *first, *end;
8219 struct hash_entry *ident;
8222 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8223 error(state, 0, "Invalid function header");
8226 /* Verify the function type */
8227 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8228 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8229 (type->right->field_ident == 0)) {
8230 error(state, 0, "Invalid function parameters");
8232 param = type->right;
8234 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8236 if (!param->left->field_ident) {
8237 error(state, 0, "No identifier for parameter %d\n", i);
8239 param = param->right;
8242 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8243 error(state, 0, "No identifier for paramter %d\n", i);
8246 /* Get a list of statements for this function. */
8247 def = triple(state, OP_LIST, type, 0, 0);
8249 /* Start a new scope for the passed parameters */
8252 /* Put a label at the very start of a function */
8253 first = label(state);
8254 RHS(def, 0) = first;
8256 /* Put a label at the very end of a function */
8258 flatten(state, first, end);
8260 /* Walk through the parameters and create symbol table entries
8263 param = type->right;
8264 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8265 ident = param->left->field_ident;
8266 tmp = variable(state, param->left);
8267 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8268 flatten(state, end, tmp);
8269 param = param->right;
8271 if ((param->type & TYPE_MASK) != TYPE_VOID) {
8272 /* And don't forget the last parameter */
8273 ident = param->field_ident;
8274 tmp = variable(state, param);
8275 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8276 flatten(state, end, tmp);
8278 /* Add a variable for the return value */
8280 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8281 /* Remove all type qualifiers from the return type */
8282 tmp = variable(state, clone_type(0, type->left));
8283 flatten(state, end, tmp);
8284 /* Remember where the return value is */
8288 /* Remember which function I am compiling.
8289 * Also assume the last defined function is the main function.
8291 state->main_function = def;
8293 /* Now get the actual function definition */
8294 compound_statement(state, end);
8296 /* Remove the parameter scope */
8299 fprintf(stdout, "\n");
8300 loc(stdout, state, 0);
8301 fprintf(stdout, "\n__________ function_definition _________\n");
8302 print_triple(state, def);
8303 fprintf(stdout, "__________ function_definition _________ done\n\n");
8309 static struct triple *do_decl(struct compile_state *state,
8310 struct type *type, struct hash_entry *ident)
8314 /* Clean up the storage types used */
8315 switch (type->type & STOR_MASK) {
8318 /* These are the good types I am aiming for */
8321 type->type &= ~STOR_MASK;
8322 type->type |= STOR_AUTO;
8325 type->type &= ~STOR_MASK;
8326 type->type |= STOR_STATIC;
8330 error(state, 0, "typedef without name");
8332 symbol(state, ident, &ident->sym_ident, 0, type);
8333 ident->tok = TOK_TYPE_NAME;
8337 internal_error(state, 0, "Undefined storage class");
8339 if (((type->type & STOR_MASK) == STOR_STATIC) &&
8340 ((type->type & QUAL_CONST) == 0)) {
8341 error(state, 0, "non const static variables not supported");
8344 def = variable(state, type);
8345 symbol(state, ident, &ident->sym_ident, def, type);
8350 static void decl(struct compile_state *state, struct triple *first)
8352 struct type *base_type, *type;
8353 struct hash_entry *ident;
8356 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8357 base_type = decl_specifiers(state);
8359 type = declarator(state, base_type, &ident, 0);
8360 if (global && ident && (peek(state) == TOK_LBRACE)) {
8362 def = function_definition(state, type);
8363 symbol(state, ident, &ident->sym_ident, def, type);
8367 flatten(state, first, do_decl(state, type, ident));
8368 /* type or variable definition */
8371 if (peek(state) == TOK_EQ) {
8373 error(state, 0, "cannot assign to a type");
8376 flatten(state, first,
8378 ident->sym_ident->def,
8379 initializer(state, type)));
8381 arrays_complete(state, type);
8382 if (peek(state) == TOK_COMMA) {
8383 eat(state, TOK_COMMA);
8385 type = declarator(state, base_type, &ident, 0);
8386 flatten(state, first, do_decl(state, type, ident));
8390 eat(state, TOK_SEMI);
8394 static void decls(struct compile_state *state)
8396 struct triple *list;
8398 list = label(state);
8401 if (tok == TOK_EOF) {
8404 if (tok == TOK_SPACE) {
8405 eat(state, TOK_SPACE);
8408 if (list->next != list) {
8409 error(state, 0, "global variables not supported");
8415 * Data structurs for optimation.
8418 static void do_use_block(
8419 struct block *used, struct block_set **head, struct block *user,
8422 struct block_set **ptr, *new;
8429 if ((*ptr)->member == user) {
8432 ptr = &(*ptr)->next;
8434 new = xcmalloc(sizeof(*new), "block_set");
8445 static void do_unuse_block(
8446 struct block *used, struct block_set **head, struct block *unuser)
8448 struct block_set *use, **ptr;
8452 if (use->member == unuser) {
8454 memset(use, -1, sizeof(*use));
8463 static void use_block(struct block *used, struct block *user)
8465 /* Append new to the head of the list, print_block
8468 do_use_block(used, &used->use, user, 1);
8471 static void unuse_block(struct block *used, struct block *unuser)
8473 do_unuse_block(used, &used->use, unuser);
8477 static void idom_block(struct block *idom, struct block *user)
8479 do_use_block(idom, &idom->idominates, user, 0);
8482 static void unidom_block(struct block *idom, struct block *unuser)
8484 do_unuse_block(idom, &idom->idominates, unuser);
8487 static void domf_block(struct block *block, struct block *domf)
8489 do_use_block(block, &block->domfrontier, domf, 0);
8492 static void undomf_block(struct block *block, struct block *undomf)
8494 do_unuse_block(block, &block->domfrontier, undomf);
8497 static void ipdom_block(struct block *ipdom, struct block *user)
8499 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8502 static void unipdom_block(struct block *ipdom, struct block *unuser)
8504 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8507 static void ipdomf_block(struct block *block, struct block *ipdomf)
8509 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8512 static void unipdomf_block(struct block *block, struct block *unipdomf)
8514 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8519 static int do_walk_triple(struct compile_state *state,
8520 struct triple *ptr, int depth,
8521 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8524 result = cb(state, ptr, depth);
8525 if ((result == 0) && (ptr->op == OP_LIST)) {
8526 struct triple *list;
8530 result = do_walk_triple(state, ptr, depth + 1, cb);
8531 if (ptr->next->prev != ptr) {
8532 internal_error(state, ptr->next, "bad prev");
8536 } while((result == 0) && (ptr != RHS(list, 0)));
8541 static int walk_triple(
8542 struct compile_state *state,
8544 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8546 return do_walk_triple(state, ptr, 0, cb);
8549 static void do_print_prefix(int depth)
8552 for(i = 0; i < depth; i++) {
8557 #define PRINT_LIST 1
8558 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8562 if (op == OP_LIST) {
8567 if ((op == OP_LABEL) && (ins->use)) {
8568 printf("\n%p:\n", ins);
8570 do_print_prefix(depth);
8571 display_triple(stdout, ins);
8573 if ((ins->op == OP_BRANCH) && ins->use) {
8574 internal_error(state, ins, "branch used?");
8578 struct triple_set *user;
8579 for(user = ins->use; user; user = user->next) {
8580 printf("use: %p\n", user->member);
8584 if (triple_is_branch(state, ins)) {
8590 static void print_triple(struct compile_state *state, struct triple *ins)
8592 walk_triple(state, ins, do_print_triple);
8595 static void print_triples(struct compile_state *state)
8597 print_triple(state, state->main_function);
8601 struct block *block;
8603 static void find_cf_blocks(struct cf_block *cf, struct block *block)
8605 if (!block || (cf[block->vertex].block == block)) {
8608 cf[block->vertex].block = block;
8609 find_cf_blocks(cf, block->left);
8610 find_cf_blocks(cf, block->right);
8613 static void print_control_flow(struct compile_state *state)
8615 struct cf_block *cf;
8617 printf("\ncontrol flow\n");
8618 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
8619 find_cf_blocks(cf, state->first_block);
8621 for(i = 1; i <= state->last_vertex; i++) {
8622 struct block *block;
8623 block = cf[i].block;
8626 printf("(%p) %d:", block, block->vertex);
8628 printf(" %d", block->left->vertex);
8630 if (block->right && (block->right != block->left)) {
8631 printf(" %d", block->right->vertex);
8640 static struct block *basic_block(struct compile_state *state,
8641 struct triple *first)
8643 struct block *block;
8646 if (first->op != OP_LABEL) {
8647 internal_error(state, 0, "block does not start with a label");
8649 /* See if this basic block has already been setup */
8650 if (first->u.block != 0) {
8651 return first->u.block;
8653 /* Allocate another basic block structure */
8654 state->last_vertex += 1;
8655 block = xcmalloc(sizeof(*block), "block");
8656 block->first = block->last = first;
8657 block->vertex = state->last_vertex;
8660 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
8664 /* If ptr->u is not used remember where the baic block is */
8665 if (!is_const(ptr)) {
8666 ptr->u.block = block;
8668 if (ptr->op == OP_BRANCH) {
8672 } while (ptr != RHS(state->main_function, 0));
8673 if (ptr == RHS(state->main_function, 0))
8676 if (op == OP_LABEL) {
8677 block->left = basic_block(state, ptr);
8679 use_block(block->left, block);
8681 else if (op == OP_BRANCH) {
8683 /* Trace the branch target */
8684 block->right = basic_block(state, TARG(ptr, 0));
8685 use_block(block->right, block);
8686 /* If there is a test trace the branch as well */
8687 if (TRIPLE_RHS(ptr->sizes)) {
8688 block->left = basic_block(state, ptr->next);
8689 use_block(block->left, block);
8693 internal_error(state, 0, "Bad basic block split");
8699 static void walk_blocks(struct compile_state *state,
8700 void (*cb)(struct compile_state *state, struct block *block, void *arg),
8703 struct triple *ptr, *first;
8704 struct block *last_block;
8706 first = RHS(state->main_function, 0);
8709 struct block *block;
8710 if (ptr->op == OP_LABEL) {
8711 block = ptr->u.block;
8712 if (block && (block != last_block)) {
8713 cb(state, block, arg);
8718 } while(ptr != first);
8721 static void print_block(
8722 struct compile_state *state, struct block *block, void *arg)
8726 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
8730 block->left && block->left->use?block->left->use->member : 0,
8732 block->right && block->right->use?block->right->use->member : 0);
8733 if (block->first->op == OP_LABEL) {
8734 printf("%p:\n", block->first);
8736 for(ptr = block->first; ; ptr = ptr->next) {
8737 struct triple_set *user;
8740 if (!IS_CONST_OP(op)) {
8741 if (ptr->u.block != block) {
8742 internal_error(state, ptr,
8743 "Wrong block pointer: %p\n",
8747 if (op == OP_ADECL) {
8748 for(user = ptr->use; user; user = user->next) {
8749 if (!user->member->u.block) {
8750 internal_error(state, user->member,
8751 "Use %p not in a block?\n",
8756 display_triple(stdout, ptr);
8758 /* Sanity checks... */
8759 valid_ins(state, ptr);
8760 for(user = ptr->use; user; user = user->next) {
8763 valid_ins(state, use);
8764 if (!IS_CONST_OP(user->member->op) &&
8765 !user->member->u.block) {
8766 internal_error(state, user->member,
8767 "Use %p not in a block?",
8772 if (ptr == block->last)
8779 static void print_blocks(struct compile_state *state)
8781 printf("--------------- blocks ---------------\n");
8782 walk_blocks(state, print_block, 0);
8785 static void prune_nonblock_triples(struct compile_state *state)
8787 struct block *block;
8788 struct triple *first, *ins;
8789 /* Delete the triples not in a basic block */
8790 first = RHS(state->main_function, 0);
8794 if (ins->op == OP_LABEL) {
8795 block = ins->u.block;
8799 release_triple(state, ins->prev);
8801 } while(ins != first);
8804 static void setup_basic_blocks(struct compile_state *state)
8806 /* Find the basic blocks */
8807 state->last_vertex = 0;
8808 state->first_block = basic_block(state, RHS(state->main_function,0));
8809 /* Delete the triples not in a basic block */
8810 prune_nonblock_triples(state);
8811 /* Find the last basic block */
8812 state->last_block = RHS(state->main_function, 0)->prev->u.block;
8813 if (!state->last_block) {
8814 internal_error(state, 0, "end not used?");
8816 /* Insert an extra unused edge from start to the end
8817 * This helps with reverse control flow calculations.
8819 use_block(state->first_block, state->last_block);
8820 /* If we are debugging print what I have just done */
8821 if (state->debug & DEBUG_BASIC_BLOCKS) {
8822 print_blocks(state);
8823 print_control_flow(state);
8827 static void free_basic_block(struct compile_state *state, struct block *block)
8829 struct block_set *entry, *next;
8830 struct block *child;
8834 if (block->vertex == -1) {
8839 unuse_block(block->left, block);
8842 unuse_block(block->right, block);
8845 unidom_block(block->idom, block);
8849 unipdom_block(block->ipdom, block);
8852 for(entry = block->use; entry; entry = next) {
8854 child = entry->member;
8855 unuse_block(block, child);
8856 if (child->left == block) {
8859 if (child->right == block) {
8863 for(entry = block->idominates; entry; entry = next) {
8865 child = entry->member;
8866 unidom_block(block, child);
8869 for(entry = block->domfrontier; entry; entry = next) {
8871 child = entry->member;
8872 undomf_block(block, child);
8874 for(entry = block->ipdominates; entry; entry = next) {
8876 child = entry->member;
8877 unipdom_block(block, child);
8880 for(entry = block->ipdomfrontier; entry; entry = next) {
8882 child = entry->member;
8883 unipdomf_block(block, child);
8885 if (block->users != 0) {
8886 internal_error(state, 0, "block still has users");
8888 free_basic_block(state, block->left);
8890 free_basic_block(state, block->right);
8892 memset(block, -1, sizeof(*block));
8896 static void free_basic_blocks(struct compile_state *state)
8898 struct triple *first, *ins;
8899 free_basic_block(state, state->first_block);
8900 state->last_vertex = 0;
8901 state->first_block = state->last_block = 0;
8902 first = RHS(state->main_function, 0);
8905 if (!is_const(ins)) {
8909 } while(ins != first);
8914 struct block *block;
8915 struct sdom_block *sdominates;
8916 struct sdom_block *sdom_next;
8917 struct sdom_block *sdom;
8918 struct sdom_block *label;
8919 struct sdom_block *parent;
8920 struct sdom_block *ancestor;
8925 static void unsdom_block(struct sdom_block *block)
8927 struct sdom_block **ptr;
8928 if (!block->sdom_next) {
8931 ptr = &block->sdom->sdominates;
8933 if ((*ptr) == block) {
8934 *ptr = block->sdom_next;
8937 ptr = &(*ptr)->sdom_next;
8941 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
8943 unsdom_block(block);
8945 block->sdom_next = sdom->sdominates;
8946 sdom->sdominates = block;
8951 static int initialize_sdblock(struct sdom_block *sd,
8952 struct block *parent, struct block *block, int vertex)
8954 if (!block || (sd[block->vertex].block == block)) {
8958 /* Renumber the blocks in a convinient fashion */
8959 block->vertex = vertex;
8960 sd[vertex].block = block;
8961 sd[vertex].sdom = &sd[vertex];
8962 sd[vertex].label = &sd[vertex];
8963 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
8964 sd[vertex].ancestor = 0;
8965 sd[vertex].vertex = vertex;
8966 vertex = initialize_sdblock(sd, block, block->left, vertex);
8967 vertex = initialize_sdblock(sd, block, block->right, vertex);
8971 static int initialize_sdpblock(struct sdom_block *sd,
8972 struct block *parent, struct block *block, int vertex)
8974 struct block_set *user;
8975 if (!block || (sd[block->vertex].block == block)) {
8979 /* Renumber the blocks in a convinient fashion */
8980 block->vertex = vertex;
8981 sd[vertex].block = block;
8982 sd[vertex].sdom = &sd[vertex];
8983 sd[vertex].label = &sd[vertex];
8984 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
8985 sd[vertex].ancestor = 0;
8986 sd[vertex].vertex = vertex;
8987 for(user = block->use; user; user = user->next) {
8988 vertex = initialize_sdpblock(sd, block, user->member, vertex);
8993 static void compress_ancestors(struct sdom_block *v)
8995 /* This procedure assumes ancestor(v) != 0 */
8996 /* if (ancestor(ancestor(v)) != 0) {
8997 * compress(ancestor(ancestor(v)));
8998 * if (semi(label(ancestor(v))) < semi(label(v))) {
8999 * label(v) = label(ancestor(v));
9001 * ancestor(v) = ancestor(ancestor(v));
9007 if (v->ancestor->ancestor) {
9008 compress_ancestors(v->ancestor->ancestor);
9009 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9010 v->label = v->ancestor->label;
9012 v->ancestor = v->ancestor->ancestor;
9016 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9020 * for each v <= pred(w) {
9022 * if (semi[u] < semi[w] {
9023 * semi[w] = semi[u];
9026 * add w to bucket(vertex(semi[w]));
9027 * LINK(parent(w), w);
9030 * for each v <= bucket(parent(w)) {
9031 * delete v from bucket(parent(w));
9033 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9036 for(i = state->last_vertex; i >= 2; i--) {
9037 struct sdom_block *v, *parent, *next;
9038 struct block_set *user;
9039 struct block *block;
9040 block = sd[i].block;
9041 parent = sd[i].parent;
9043 for(user = block->use; user; user = user->next) {
9044 struct sdom_block *v, *u;
9045 v = &sd[user->member->vertex];
9046 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9047 if (u->sdom->vertex < sd[i].sdom->vertex) {
9048 sd[i].sdom = u->sdom;
9051 sdom_block(sd[i].sdom, &sd[i]);
9052 sd[i].ancestor = parent;
9054 for(v = parent->sdominates; v; v = next) {
9055 struct sdom_block *u;
9056 next = v->sdom_next;
9058 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9059 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9060 u->block : parent->block;
9065 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9069 * for each v <= pred(w) {
9071 * if (semi[u] < semi[w] {
9072 * semi[w] = semi[u];
9075 * add w to bucket(vertex(semi[w]));
9076 * LINK(parent(w), w);
9079 * for each v <= bucket(parent(w)) {
9080 * delete v from bucket(parent(w));
9082 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9085 for(i = state->last_vertex; i >= 2; i--) {
9086 struct sdom_block *u, *v, *parent, *next;
9087 struct block *block;
9088 block = sd[i].block;
9089 parent = sd[i].parent;
9092 v = &sd[block->left->vertex];
9093 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9094 if (u->sdom->vertex < sd[i].sdom->vertex) {
9095 sd[i].sdom = u->sdom;
9098 if (block->right && (block->right != block->left)) {
9099 v = &sd[block->right->vertex];
9100 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9101 if (u->sdom->vertex < sd[i].sdom->vertex) {
9102 sd[i].sdom = u->sdom;
9105 sdom_block(sd[i].sdom, &sd[i]);
9106 sd[i].ancestor = parent;
9108 for(v = parent->sdominates; v; v = next) {
9109 struct sdom_block *u;
9110 next = v->sdom_next;
9112 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9113 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9114 u->block : parent->block;
9119 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9122 for(i = 2; i <= state->last_vertex; i++) {
9123 struct block *block;
9124 block = sd[i].block;
9125 if (block->idom->vertex != sd[i].sdom->vertex) {
9126 block->idom = block->idom->idom;
9128 idom_block(block->idom, block);
9130 sd[1].block->idom = 0;
9133 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9136 for(i = 2; i <= state->last_vertex; i++) {
9137 struct block *block;
9138 block = sd[i].block;
9139 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9140 block->ipdom = block->ipdom->ipdom;
9142 ipdom_block(block->ipdom, block);
9144 sd[1].block->ipdom = 0;
9148 * Every vertex of a flowgraph G = (V, E, r) except r has
9149 * a unique immediate dominator.
9150 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9151 * rooted at r, called the dominator tree of G, such that
9152 * v dominates w if and only if v is a proper ancestor of w in
9153 * the dominator tree.
9156 * If v and w are vertices of G such that v <= w,
9157 * than any path from v to w must contain a common ancestor
9160 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9161 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9162 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9164 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9165 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9168 * Let w != r and let u be a vertex for which sdom(u) is
9169 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9170 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9172 /* Lemma 5: Let vertices v,w satisfy v -> w.
9173 * Then v -> idom(w) or idom(w) -> idom(v)
9176 static void find_immediate_dominators(struct compile_state *state)
9178 struct sdom_block *sd;
9179 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9180 * vi > w for (1 <= i <= k - 1}
9183 * For any vertex w != r.
9185 * {v|(v,w) <= E and v < w } U
9186 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9189 * Let w != r and let u be a vertex for which sdom(u) is
9190 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9192 * { sdom(w) if sdom(w) = sdom(u),
9194 * { idom(u) otherwise
9196 /* The algorithm consists of the following 4 steps.
9197 * Step 1. Carry out a depth-first search of the problem graph.
9198 * Number the vertices from 1 to N as they are reached during
9199 * the search. Initialize the variables used in succeeding steps.
9200 * Step 2. Compute the semidominators of all vertices by applying
9201 * theorem 4. Carry out the computation vertex by vertex in
9202 * decreasing order by number.
9203 * Step 3. Implicitly define the immediate dominator of each vertex
9204 * by applying Corollary 1.
9205 * Step 4. Explicitly define the immediate dominator of each vertex,
9206 * carrying out the computation vertex by vertex in increasing order
9209 /* Step 1 initialize the basic block information */
9210 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9211 initialize_sdblock(sd, 0, state->first_block, 0);
9217 /* Step 2 compute the semidominators */
9218 /* Step 3 implicitly define the immediate dominator of each vertex */
9219 compute_sdom(state, sd);
9220 /* Step 4 explicitly define the immediate dominator of each vertex */
9221 compute_idom(state, sd);
9225 static void find_post_dominators(struct compile_state *state)
9227 struct sdom_block *sd;
9228 /* Step 1 initialize the basic block information */
9229 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9231 initialize_sdpblock(sd, 0, state->last_block, 0);
9233 /* Step 2 compute the semidominators */
9234 /* Step 3 implicitly define the immediate dominator of each vertex */
9235 compute_spdom(state, sd);
9236 /* Step 4 explicitly define the immediate dominator of each vertex */
9237 compute_ipdom(state, sd);
9243 static void find_block_domf(struct compile_state *state, struct block *block)
9245 struct block *child;
9246 struct block_set *user;
9247 if (block->domfrontier != 0) {
9248 internal_error(state, block->first, "domfrontier present?");
9250 for(user = block->idominates; user; user = user->next) {
9251 child = user->member;
9252 if (child->idom != block) {
9253 internal_error(state, block->first, "bad idom");
9255 find_block_domf(state, child);
9257 if (block->left && block->left->idom != block) {
9258 domf_block(block, block->left);
9260 if (block->right && block->right->idom != block) {
9261 domf_block(block, block->right);
9263 for(user = block->idominates; user; user = user->next) {
9264 struct block_set *frontier;
9265 child = user->member;
9266 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9267 if (frontier->member->idom != block) {
9268 domf_block(block, frontier->member);
9274 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9276 struct block *child;
9277 struct block_set *user;
9278 if (block->ipdomfrontier != 0) {
9279 internal_error(state, block->first, "ipdomfrontier present?");
9281 for(user = block->ipdominates; user; user = user->next) {
9282 child = user->member;
9283 if (child->ipdom != block) {
9284 internal_error(state, block->first, "bad ipdom");
9286 find_block_ipdomf(state, child);
9288 if (block->left && block->left->ipdom != block) {
9289 ipdomf_block(block, block->left);
9291 if (block->right && block->right->ipdom != block) {
9292 ipdomf_block(block, block->right);
9294 for(user = block->idominates; user; user = user->next) {
9295 struct block_set *frontier;
9296 child = user->member;
9297 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9298 if (frontier->member->ipdom != block) {
9299 ipdomf_block(block, frontier->member);
9305 static int print_dominated(
9306 struct compile_state *state, struct block *block, int vertex)
9308 struct block_set *user;
9310 if (!block || (block->vertex != vertex + 1)) {
9315 printf("%d:", block->vertex);
9316 for(user = block->idominates; user; user = user->next) {
9317 printf(" %d", user->member->vertex);
9318 if (user->member->idom != block) {
9319 internal_error(state, user->member->first, "bad idom");
9323 vertex = print_dominated(state, block->left, vertex);
9324 vertex = print_dominated(state, block->right, vertex);
9328 static void print_dominators(struct compile_state *state)
9330 printf("\ndominates\n");
9331 print_dominated(state, state->first_block, 0);
9335 static int print_frontiers(
9336 struct compile_state *state, struct block *block, int vertex)
9338 struct block_set *user;
9340 if (!block || (block->vertex != vertex + 1)) {
9345 printf("%d:", block->vertex);
9346 for(user = block->domfrontier; user; user = user->next) {
9347 printf(" %d", user->member->vertex);
9351 vertex = print_frontiers(state, block->left, vertex);
9352 vertex = print_frontiers(state, block->right, vertex);
9355 static void print_dominance_frontiers(struct compile_state *state)
9357 printf("\ndominance frontiers\n");
9358 print_frontiers(state, state->first_block, 0);
9362 static void analyze_idominators(struct compile_state *state)
9364 /* Find the immediate dominators */
9365 find_immediate_dominators(state);
9366 /* Find the dominance frontiers */
9367 find_block_domf(state, state->first_block);
9368 /* If debuging print the print what I have just found */
9369 if (state->debug & DEBUG_FDOMINATORS) {
9370 print_dominators(state);
9371 print_dominance_frontiers(state);
9372 print_control_flow(state);
9378 static int print_ipdominated(
9379 struct compile_state *state, struct block *block, int vertex)
9381 struct block_set *user;
9383 if (!block || (block->vertex != vertex + 1)) {
9388 printf("%d:", block->vertex);
9389 for(user = block->ipdominates; user; user = user->next) {
9390 printf(" %d", user->member->vertex);
9391 if (user->member->ipdom != block) {
9392 internal_error(state, user->member->first, "bad ipdom");
9396 for(user = block->use; user; user = user->next) {
9397 vertex = print_ipdominated(state, user->member, vertex);
9402 static void print_ipdominators(struct compile_state *state)
9404 printf("\nipdominates\n");
9405 print_ipdominated(state, state->last_block, 0);
9408 static int print_pfrontiers(
9409 struct compile_state *state, struct block *block, int vertex)
9411 struct block_set *user;
9413 if (!block || (block->vertex != vertex + 1)) {
9418 printf("%d:", block->vertex);
9419 for(user = block->ipdomfrontier; user; user = user->next) {
9420 printf(" %d", user->member->vertex);
9423 for(user = block->use; user; user = user->next) {
9424 vertex = print_pfrontiers(state, user->member, vertex);
9428 static void print_ipdominance_frontiers(struct compile_state *state)
9430 printf("\nipdominance frontiers\n");
9431 print_pfrontiers(state, state->last_block, 0);
9435 static void analyze_ipdominators(struct compile_state *state)
9437 /* Find the post dominators */
9438 find_post_dominators(state);
9439 /* Find the control dependencies (post dominance frontiers) */
9440 find_block_ipdomf(state, state->last_block);
9441 /* If debuging print the print what I have just found */
9442 if (state->debug & DEBUG_RDOMINATORS) {
9443 print_ipdominators(state);
9444 print_ipdominance_frontiers(state);
9445 print_control_flow(state);
9450 static void insert_phi_operations(struct compile_state *state)
9453 struct triple *first;
9454 int *has_already, *work;
9455 struct block *work_list, **work_list_tail;
9459 size = sizeof(int) * (state->last_vertex + 1);
9460 has_already = xcmalloc(size, "has_already");
9461 work = xcmalloc(size, "work");
9464 first = RHS(state->main_function, 0);
9465 for(var = first->next; var != first ; var = var->next) {
9466 struct block *block;
9467 struct triple_set *user;
9468 if ((var->op != OP_ADECL) || !var->use) {
9473 work_list_tail = &work_list;
9474 for(user = var->use; user; user = user->next) {
9475 if (user->member->op == OP_READ) {
9478 if (user->member->op != OP_WRITE) {
9479 internal_error(state, user->member,
9480 "bad variable access");
9482 block = user->member->u.block;
9484 warning(state, user->member, "dead code");
9486 work[block->vertex] = iter;
9487 *work_list_tail = block;
9488 block->work_next = 0;
9489 work_list_tail = &block->work_next;
9491 for(block = work_list; block; block = block->work_next) {
9492 struct block_set *df;
9493 for(df = block->domfrontier; df; df = df->next) {
9495 struct block *front;
9499 if (has_already[front->vertex] >= iter) {
9502 /* Count how many edges flow into this block */
9503 in_edges = front->users;
9504 /* Insert a phi function for this variable */
9506 state, OP_PHI, var->type, in_edges,
9507 front->first->filename,
9510 phi->u.block = front;
9512 use_triple(var, phi);
9513 /* Insert the phi functions immediately after the label */
9514 insert_triple(state, front->first->next, phi);
9515 if (front->first == front->last) {
9516 front->last = front->first->next;
9518 has_already[front->vertex] = iter;
9520 /* If necessary plan to visit the basic block */
9521 if (work[front->vertex] >= iter) {
9524 work[front->vertex] = iter;
9525 *work_list_tail = front;
9526 front->work_next = 0;
9527 work_list_tail = &front->work_next;
9539 static void fixup_block_phi_variables(
9540 struct compile_state *state, struct block *parent, struct block *block)
9542 struct block_set *set;
9545 if (!parent || !block)
9547 /* Find the edge I am coming in on */
9549 for(set = block->use; set; set = set->next, edge++) {
9550 if (set->member == parent) {
9555 internal_error(state, 0, "phi input is not on a control predecessor");
9557 for(ptr = block->first; ; ptr = ptr->next) {
9558 if (ptr->op == OP_PHI) {
9559 struct triple *var, *val, **slot;
9561 /* Find the current value of the variable */
9562 val = var->use->member;
9563 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9564 internal_error(state, val, "bad value in phi");
9566 if (edge >= TRIPLE_RHS(ptr->sizes)) {
9567 internal_error(state, ptr, "edges > phi rhs");
9569 slot = &RHS(ptr, edge);
9570 if ((*slot != 0) && (*slot != val)) {
9571 internal_error(state, ptr, "phi already bound on this edge");
9574 use_triple(val, ptr);
9576 if (ptr == block->last) {
9583 static void rename_block_variables(
9584 struct compile_state *state, struct block *block)
9586 struct block_set *user;
9587 struct triple *ptr, *next, *last;
9591 last = block->first;
9593 for(ptr = block->first; !done; ptr = next) {
9595 if (ptr == block->last) {
9599 if (ptr->op == OP_READ) {
9600 struct triple *var, *val;
9602 unuse_triple(var, ptr);
9604 error(state, ptr, "variable used without being set");
9606 /* Find the current value of the variable */
9607 val = var->use->member;
9608 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9609 internal_error(state, val, "bad value in read");
9611 propogate_use(state, ptr, val);
9612 release_triple(state, ptr);
9616 if (ptr->op == OP_WRITE) {
9617 struct triple *var, *val;
9620 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9621 internal_error(state, val, "bad value in write");
9623 propogate_use(state, ptr, val);
9624 unuse_triple(var, ptr);
9625 /* Push OP_WRITE ptr->right onto a stack of variable uses */
9626 push_triple(var, val);
9628 if (ptr->op == OP_PHI) {
9631 /* Push OP_PHI onto a stack of variable uses */
9632 push_triple(var, ptr);
9638 /* Fixup PHI functions in the cf successors */
9639 fixup_block_phi_variables(state, block, block->left);
9640 fixup_block_phi_variables(state, block, block->right);
9641 /* rename variables in the dominated nodes */
9642 for(user = block->idominates; user; user = user->next) {
9643 rename_block_variables(state, user->member);
9645 /* pop the renamed variable stack */
9646 last = block->first;
9648 for(ptr = block->first; !done ; ptr = next) {
9650 if (ptr == block->last) {
9653 if (ptr->op == OP_WRITE) {
9656 /* Pop OP_WRITE ptr->right from the stack of variable uses */
9657 pop_triple(var, RHS(ptr, 0));
9658 release_triple(state, ptr);
9661 if (ptr->op == OP_PHI) {
9664 /* Pop OP_WRITE ptr->right from the stack of variable uses */
9665 pop_triple(var, ptr);
9672 static void prune_block_variables(struct compile_state *state,
9673 struct block *block)
9675 struct block_set *user;
9676 struct triple *next, *last, *ptr;
9678 last = block->first;
9680 for(ptr = block->first; !done; ptr = next) {
9682 if (ptr == block->last) {
9685 if (ptr->op == OP_ADECL) {
9686 struct triple_set *user, *next;
9687 for(user = ptr->use; user; user = next) {
9691 if (use->op != OP_PHI) {
9692 internal_error(state, use, "decl still used");
9694 if (MISC(use, 0) != ptr) {
9695 internal_error(state, use, "bad phi use of decl");
9697 unuse_triple(ptr, use);
9700 release_triple(state, ptr);
9706 for(user = block->idominates; user; user = user->next) {
9707 prune_block_variables(state, user->member);
9711 static void transform_to_ssa_form(struct compile_state *state)
9713 insert_phi_operations(state);
9715 printf("@%s:%d\n", __FILE__, __LINE__);
9716 print_blocks(state);
9718 rename_block_variables(state, state->first_block);
9719 prune_block_variables(state, state->first_block);
9723 static void transform_from_ssa_form(struct compile_state *state)
9725 /* To get out of ssa form we insert moves on the incoming
9726 * edges to blocks containting phi functions.
9728 struct triple *first;
9729 struct triple *phi, *next;
9731 /* Walk all of the operations to find the phi functions */
9732 first = RHS(state->main_function, 0);
9733 for(phi = first->next; phi != first ; phi = next) {
9734 struct block_set *set;
9735 struct block *block;
9736 struct triple **slot;
9737 struct triple *var, *read;
9740 if (phi->op != OP_PHI) {
9743 block = phi->u.block;
9744 slot = &RHS(phi, 0);
9746 /* A variable to replace the phi function */
9747 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
9748 /* A read of the single value that is set into the variable */
9749 read = post_triple(state, var, OP_READ, phi->type, var, 0);
9750 use_triple(var, read);
9752 /* Replaces uses of the phi with variable reads */
9753 propogate_use(state, phi, read);
9755 /* Walk all of the incoming edges/blocks and insert moves.
9757 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9758 struct block *eblock;
9759 struct triple *move;
9761 eblock = set->member;
9763 unuse_triple(val, phi);
9769 move = post_triple(state,
9770 val, OP_WRITE, phi->type, var, val);
9771 use_triple(val, move);
9772 use_triple(var, move);
9774 release_triple(state, phi);
9779 static void insert_copies_to_phi(struct compile_state *state)
9781 /* To get out of ssa form we insert moves on the incoming
9782 * edges to blocks containting phi functions.
9784 struct triple *first;
9787 /* Walk all of the operations to find the phi functions */
9788 first = RHS(state->main_function, 0);
9789 for(phi = first->next; phi != first ; phi = phi->next) {
9790 struct block_set *set;
9791 struct block *block;
9792 struct triple **slot;
9794 if (phi->op != OP_PHI) {
9797 if (ID_REG(phi->id) == REG_UNSET) {
9798 phi->id = MK_REG_ID(alloc_virtual_reg(),
9799 ID_REG_CLASSES(phi->id));
9801 block = phi->u.block;
9802 slot = &RHS(phi, 0);
9803 /* Walk all of the incoming edges/blocks and insert moves.
9805 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9806 struct block *eblock;
9807 struct triple *move;
9810 eblock = set->member;
9817 move = build_triple(state, OP_COPY, phi->type, val, 0,
9818 val->filename, val->line, val->col);
9819 move->u.block = eblock;
9821 use_triple(val, move);
9824 unuse_triple(val, phi);
9825 use_triple(move, phi);
9827 /* Walk through the block backwards to find
9828 * an appropriate location for the OP_COPY.
9830 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
9831 struct triple **expr;
9832 if ((ptr == phi) || (ptr == val)) {
9835 expr = triple_rhs(state, ptr, 0);
9836 for(;expr; expr = triple_rhs(state, ptr, expr)) {
9837 if ((*expr) == phi) {
9843 if (triple_is_branch(state, ptr)) {
9844 internal_error(state, ptr,
9845 "Could not insert write to phi");
9847 insert_triple(state, ptr->next, move);
9848 if (eblock->last == ptr) {
9849 eblock->last = move;
9855 struct triple_reg_set {
9856 struct triple_reg_set *next;
9857 struct triple *member;
9862 struct block *block;
9863 struct triple_reg_set *in;
9864 struct triple_reg_set *out;
9868 static int do_triple_set(struct triple_reg_set **head,
9869 struct triple *member, struct triple *new_member)
9871 struct triple_reg_set **ptr, *new;
9876 if ((*ptr)->member == member) {
9879 ptr = &(*ptr)->next;
9881 new = xcmalloc(sizeof(*new), "triple_set");
9882 new->member = member;
9883 new->new = new_member;
9889 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
9891 struct triple_reg_set *entry, **ptr;
9895 if (entry->member == member) {
9906 static int in_triple(struct reg_block *rb, struct triple *in)
9908 return do_triple_set(&rb->in, in, 0);
9910 static void unin_triple(struct reg_block *rb, struct triple *unin)
9912 do_triple_unset(&rb->in, unin);
9915 static int out_triple(struct reg_block *rb, struct triple *out)
9917 return do_triple_set(&rb->out, out, 0);
9919 static void unout_triple(struct reg_block *rb, struct triple *unout)
9921 do_triple_unset(&rb->out, unout);
9924 static int initialize_regblock(struct reg_block *blocks,
9925 struct block *block, int vertex)
9927 struct block_set *user;
9928 if (!block || (blocks[block->vertex].block == block)) {
9932 /* Renumber the blocks in a convinient fashion */
9933 block->vertex = vertex;
9934 blocks[vertex].block = block;
9935 blocks[vertex].vertex = vertex;
9936 for(user = block->use; user; user = user->next) {
9937 vertex = initialize_regblock(blocks, user->member, vertex);
9942 static int phi_in(struct compile_state *state, struct reg_block *blocks,
9943 struct reg_block *rb, struct block *suc)
9945 /* Read the conditional input set of a successor block
9946 * (i.e. the input to the phi nodes) and place it in the
9947 * current blocks output set.
9949 struct block_set *set;
9954 /* Find the edge I am coming in on */
9955 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
9956 if (set->member == rb->block) {
9961 internal_error(state, 0, "Not coming on a control edge?");
9963 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
9964 struct triple **slot, *expr, *ptr2;
9965 int out_change, done2;
9966 done = (ptr == suc->last);
9967 if (ptr->op != OP_PHI) {
9970 slot = &RHS(ptr, 0);
9972 out_change = out_triple(rb, expr);
9976 /* If we don't define the variable also plast it
9977 * in the current blocks input set.
9979 ptr2 = rb->block->first;
9980 for(done2 = 0; !done2; ptr2 = ptr2->next) {
9984 done2 = (ptr2 == rb->block->last);
9989 change |= in_triple(rb, expr);
9994 static int reg_in(struct compile_state *state, struct reg_block *blocks,
9995 struct reg_block *rb, struct block *suc)
9997 struct triple_reg_set *in_set;
10000 /* Read the input set of a successor block
10001 * and place it in the current blocks output set.
10003 in_set = blocks[suc->vertex].in;
10004 for(; in_set; in_set = in_set->next) {
10005 int out_change, done;
10006 struct triple *first, *last, *ptr;
10007 out_change = out_triple(rb, in_set->member);
10011 /* If we don't define the variable also place it
10012 * in the current blocks input set.
10014 first = rb->block->first;
10015 last = rb->block->last;
10017 for(ptr = first; !done; ptr = ptr->next) {
10018 if (ptr == in_set->member) {
10021 done = (ptr == last);
10026 change |= in_triple(rb, in_set->member);
10028 change |= phi_in(state, blocks, rb, suc);
10033 static int use_in(struct compile_state *state, struct reg_block *rb)
10035 /* Find the variables we use but don't define and add
10036 * it to the current blocks input set.
10038 #warning "FIXME is this O(N^2) algorithm bad?"
10039 struct block *block;
10040 struct triple *ptr;
10045 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10046 struct triple **expr;
10047 done = (ptr == block->first);
10048 /* The variable a phi function uses depends on the
10049 * control flow, and is handled in phi_in, not
10052 if (ptr->op == OP_PHI) {
10055 expr = triple_rhs(state, ptr, 0);
10056 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10057 struct triple *rhs, *test;
10063 /* See if rhs is defined in this block */
10064 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10065 tdone = (test == block->first);
10071 /* If the triple is not a definition skip it. */
10072 if (!triple_is_def(state, ptr)) {
10075 /* If I still have a valid rhs add it to in */
10076 change |= in_triple(rb, rhs);
10082 static struct reg_block *compute_variable_lifetimes(
10083 struct compile_state *state)
10085 struct reg_block *blocks;
10088 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10089 initialize_regblock(blocks, state->last_block, 0);
10093 for(i = 1; i <= state->last_vertex; i++) {
10094 struct reg_block *rb;
10096 /* Add the left successor's input set to in */
10097 if (rb->block->left) {
10098 change |= reg_in(state, blocks, rb, rb->block->left);
10100 /* Add the right successor's input set to in */
10101 if ((rb->block->right) &&
10102 (rb->block->right != rb->block->left)) {
10103 change |= reg_in(state, blocks, rb, rb->block->right);
10105 /* Add use to in... */
10106 change |= use_in(state, rb);
10112 static void free_variable_lifetimes(
10113 struct compile_state *state, struct reg_block *blocks)
10116 /* free in_set && out_set on each block */
10117 for(i = 1; i <= state->last_vertex; i++) {
10118 struct triple_reg_set *entry, *next;
10119 struct reg_block *rb;
10121 for(entry = rb->in; entry ; entry = next) {
10122 next = entry->next;
10123 do_triple_unset(&rb->in, entry->member);
10125 for(entry = rb->out; entry; entry = next) {
10126 next = entry->next;
10127 do_triple_unset(&rb->out, entry->member);
10134 typedef struct triple *(*wvl_cb_t)(
10135 struct compile_state *state,
10136 struct reg_block *blocks, struct triple_reg_set *live,
10137 struct reg_block *rb, struct triple *ins, void *arg);
10139 static void walk_variable_lifetimes(struct compile_state *state,
10140 struct reg_block *blocks, wvl_cb_t cb, void *arg)
10144 for(i = 1; i <= state->last_vertex; i++) {
10145 struct triple_reg_set *live;
10146 struct triple_reg_set *entry, *next;
10147 struct triple *ptr, *prev;
10148 struct reg_block *rb;
10149 struct block *block;
10152 /* Get the blocks */
10156 /* Copy out into live */
10158 for(entry = rb->out; entry; entry = next) {
10159 next = entry->next;
10160 do_triple_set(&live, entry->member, entry->new);
10162 /* Walk through the basic block calculating live */
10163 for(done = 0, ptr = block->last; !done; ptr = prev) {
10164 struct triple **expr;
10167 done = (ptr == block->first);
10169 /* Remove the current definition from live */
10170 do_triple_unset(&live, ptr);
10172 /* If the current instruction was deleted continue */
10173 if (!cb(state, blocks, live, rb, ptr, arg)) {
10174 if (block->last == ptr) {
10175 block->last = prev;
10180 /* Add the current uses to live.
10182 * It is safe to skip phi functions because they do
10183 * not have any block local uses, and the block
10184 * output sets already properly account for what
10185 * control flow depedent uses phi functions do have.
10187 if (ptr->op == OP_PHI) {
10190 expr = triple_rhs(state, ptr, 0);
10191 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10192 /* If the triple is not a definition skip it. */
10193 if (!*expr || !triple_is_def(state, *expr)) {
10196 do_triple_set(&live, *expr, 0);
10201 for(entry = live; entry; entry = next) {
10202 next = entry->next;
10203 do_triple_unset(&live, entry->member);
10208 static int count_triples(struct compile_state *state)
10210 struct triple *first, *ins;
10212 first = RHS(state->main_function, 0);
10217 } while (ins != first);
10220 struct dead_triple {
10221 struct triple *triple;
10222 struct dead_triple *work_next;
10223 struct block *block;
10226 #define TRIPLE_FLAG_ALIVE 1
10230 static void awaken(
10231 struct compile_state *state,
10232 struct dead_triple *dtriple, struct triple **expr,
10233 struct dead_triple ***work_list_tail)
10235 struct triple *triple;
10236 struct dead_triple *dt;
10244 if (triple->id <= 0) {
10245 internal_error(state, triple, "bad triple id: %d",
10248 if (triple->op == OP_NOOP) {
10249 internal_warning(state, triple, "awakening noop?");
10252 dt = &dtriple[triple->id];
10253 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10254 dt->flags |= TRIPLE_FLAG_ALIVE;
10255 if (!dt->work_next) {
10256 **work_list_tail = dt;
10257 *work_list_tail = &dt->work_next;
10262 static void eliminate_inefectual_code(struct compile_state *state)
10264 struct block *block;
10265 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
10267 struct triple *first, *ins;
10269 /* Setup the work list */
10271 work_list_tail = &work_list;
10273 first = RHS(state->main_function, 0);
10275 /* Count how many triples I have */
10276 triples = count_triples(state);
10278 /* Now put then in an array and mark all of the triples dead */
10279 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
10285 if (ins->op == OP_LABEL) {
10286 block = ins->u.block;
10288 dtriple[i].triple = ins;
10289 dtriple[i].block = block;
10290 dtriple[i].flags = 0;
10291 dtriple[i].color = ins->id;
10293 /* See if it is an operation we always keep */
10294 #warning "FIXME handle the case of killing a branch instruction"
10295 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
10296 awaken(state, dtriple, &ins, &work_list_tail);
10300 } while(ins != first);
10302 struct dead_triple *dt;
10303 struct block_set *user;
10304 struct triple **expr;
10306 work_list = dt->work_next;
10308 work_list_tail = &work_list;
10310 /* Wake up the data depencencies of this triple */
10313 expr = triple_rhs(state, dt->triple, expr);
10314 awaken(state, dtriple, expr, &work_list_tail);
10317 expr = triple_lhs(state, dt->triple, expr);
10318 awaken(state, dtriple, expr, &work_list_tail);
10320 /* Wake up the forward control dependencies */
10322 expr = triple_targ(state, dt->triple, expr);
10323 awaken(state, dtriple, expr, &work_list_tail);
10325 /* Wake up the reverse control dependencies of this triple */
10326 for(user = dt->block->ipdomfrontier; user; user = user->next) {
10327 awaken(state, dtriple, &user->member->last, &work_list_tail);
10330 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
10331 if ((dt->triple->op == OP_NOOP) &&
10332 (dt->flags & TRIPLE_FLAG_ALIVE)) {
10333 internal_error(state, dt->triple, "noop effective?");
10335 dt->triple->id = dt->color; /* Restore the color */
10336 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10337 #warning "FIXME handle the case of killing a basic block"
10338 if (dt->block->first == dt->triple) {
10341 if (dt->block->last == dt->triple) {
10342 dt->block->last = dt->triple->prev;
10344 release_triple(state, dt->triple);
10351 struct live_range_edge;
10352 struct live_range {
10353 struct live_range_edge *edges;
10354 struct triple *def;
10358 struct live_range *group_next, **group_prev;
10361 struct live_range_edge {
10362 struct live_range_edge *next;
10363 struct live_range *node;
10366 #define LRE_HASH_SIZE 2048
10368 struct lre_hash *next;
10369 struct live_range *left;
10370 struct live_range *right;
10375 struct lre_hash *hash[LRE_HASH_SIZE];
10376 struct reg_block *blocks;
10377 struct live_range *lr;
10378 struct live_range *low, **low_tail;
10379 struct live_range *high, **high_tail;
10384 static unsigned regc_max_size(struct compile_state *state, int classes)
10389 for(i = 0; i < MAX_REGC; i++) {
10390 if (classes & (1 << i)) {
10392 size = arch_regc_size(state, i);
10393 if (size > max_size) {
10401 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
10403 unsigned equivs[MAX_REG_EQUIVS];
10405 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
10406 internal_error(state, 0, "invalid register");
10408 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
10409 internal_error(state, 0, "invalid register");
10411 arch_reg_equivs(state, equivs, reg1);
10412 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
10413 if (equivs[i] == reg2) {
10420 static void reg_fill_used(struct compile_state *state, char *used, int reg)
10422 unsigned equivs[MAX_REG_EQUIVS];
10424 arch_reg_equivs(state, equivs, reg);
10425 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
10426 used[equivs[i]] = 1;
10431 static unsigned int hash_live_edge(
10432 struct live_range *left, struct live_range *right)
10434 unsigned int hash, val;
10435 unsigned long lval, rval;
10436 lval = ((unsigned long)left)/sizeof(struct live_range);
10437 rval = ((unsigned long)right)/sizeof(struct live_range);
10442 hash = (hash *263) + val;
10447 hash = (hash *263) + val;
10449 hash = hash & (LRE_HASH_SIZE - 1);
10453 static struct lre_hash **lre_probe(struct reg_state *rstate,
10454 struct live_range *left, struct live_range *right)
10456 struct lre_hash **ptr;
10457 unsigned int index;
10458 /* Ensure left <= right */
10459 if (left > right) {
10460 struct live_range *tmp;
10465 index = hash_live_edge(left, right);
10467 ptr = &rstate->hash[index];
10468 while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
10469 ptr = &(*ptr)->next;
10474 static int interfere(struct reg_state *rstate,
10475 struct live_range *left, struct live_range *right)
10477 struct lre_hash **ptr;
10478 ptr = lre_probe(rstate, left, right);
10479 return ptr && *ptr;
10482 static void add_live_edge(struct reg_state *rstate,
10483 struct live_range *left, struct live_range *right)
10485 /* FIXME the memory allocation overhead is noticeable here... */
10486 struct lre_hash **ptr, *new_hash;
10487 struct live_range_edge *edge;
10489 if (left == right) {
10492 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
10495 /* Ensure left <= right */
10496 if (left > right) {
10497 struct live_range *tmp;
10502 ptr = lre_probe(rstate, left, right);
10506 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
10507 new_hash->next = *ptr;
10508 new_hash->left = left;
10509 new_hash->right = right;
10512 edge = xmalloc(sizeof(*edge), "live_range_edge");
10513 edge->next = left->edges;
10514 edge->node = right;
10515 left->edges = edge;
10518 edge = xmalloc(sizeof(*edge), "live_range_edge");
10519 edge->next = right->edges;
10521 right->edges = edge;
10522 right->degree += 1;
10525 static void remove_live_edge(struct reg_state *rstate,
10526 struct live_range *left, struct live_range *right)
10528 struct live_range_edge *edge, **ptr;
10529 struct lre_hash **hptr, *entry;
10530 hptr = lre_probe(rstate, left, right);
10531 if (!hptr || !*hptr) {
10535 *hptr = entry->next;
10538 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
10540 if (edge->node == right) {
10542 memset(edge, 0, sizeof(*edge));
10547 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
10549 if (edge->node == left) {
10551 memset(edge, 0, sizeof(*edge));
10558 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
10560 struct live_range_edge *edge, *next;
10561 for(edge = range->edges; edge; edge = next) {
10563 remove_live_edge(rstate, range, edge->node);
10568 /* Interference graph...
10570 * new(n) --- Return a graph with n nodes but no edges.
10571 * add(g,x,y) --- Return a graph including g with an between x and y
10572 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
10573 * x and y in the graph g
10574 * degree(g, x) --- Return the degree of the node x in the graph g
10575 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
10577 * Implement with a hash table && a set of adjcency vectors.
10578 * The hash table supports constant time implementations of add and interfere.
10579 * The adjacency vectors support an efficient implementation of neighbors.
10583 * +---------------------------------------------------+
10584 * | +--------------+ |
10586 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
10588 * -- In simplify implment optimistic coloring... (No backtracking)
10589 * -- Implement Rematerialization it is the only form of spilling we can perform
10590 * Essentially this means dropping a constant from a register because
10591 * we can regenerate it later.
10593 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
10594 * coalesce at phi points...
10595 * --- Bias coloring if at all possible do the coalesing a compile time.
10600 static void different_colored(
10601 struct compile_state *state, struct reg_state *rstate,
10602 struct triple *parent, struct triple *ins)
10604 struct live_range *lr;
10605 struct triple **expr;
10606 lr = &rstate->lr[ins->id];
10607 expr = triple_rhs(state, ins, 0);
10608 for(;expr; expr = triple_rhs(state, ins, expr)) {
10609 struct live_range *lr2;
10610 if (!*expr || (*expr == parent) || (*expr == ins)) {
10613 lr2 = &rstate->lr[(*expr)->id];
10614 if (lr->color == lr2->color) {
10615 internal_error(state, ins, "live range too big");
10620 static void initialize_live_ranges(
10621 struct compile_state *state, struct reg_state *rstate)
10623 struct triple *ins, *first;
10627 first = RHS(state->main_function, 0);
10628 /* First count how many live ranges I will need.
10630 rstate->ranges = count_triples(state);
10631 size = sizeof(rstate->lr[0]) * (rstate->ranges + 1);
10632 rstate->lr = xcmalloc(size, "live_range");
10633 /* Setup the dummy live range */
10634 rstate->lr[0].classes = 0;
10635 rstate->lr[0].color = REG_UNSET;
10636 rstate->lr[0].def = 0;
10640 unsigned color, classes;
10641 /* Find the architecture specific color information */
10642 color = ID_REG(ins->id);
10643 classes = ID_REG_CLASSES(ins->id);
10644 if ((color != REG_UNSET) && (color < MAX_REGISTERS)) {
10645 classes = arch_reg_regcm(state, color);
10648 /* If the triple is a variable definition give it a live range. */
10649 if (triple_is_def(state, ins)) {
10652 rstate->lr[i].def = ins;
10653 rstate->lr[i].color = color;
10654 rstate->lr[i].classes = classes;
10655 rstate->lr[i].degree = 0;
10657 internal_error(state, ins,
10658 "live range without a class");
10661 /* Otherwise give the triple the dummy live range. */
10666 } while(ins != first);
10667 rstate->ranges = i;
10668 /* Make a second pass to handle achitecture specific register
10673 struct live_range *lr;
10674 lr = &rstate->lr[ins->id];
10675 if (lr->color != REG_UNSET) {
10676 struct triple **expr;
10677 /* This assumes the virtual register is only
10678 * used by one input operation.
10680 expr = triple_rhs(state, ins, 0);
10681 for(;expr; expr = triple_rhs(state, ins, expr)) {
10682 struct live_range *lr2;
10683 if (!*expr || (ins == *expr)) {
10686 lr2 = &rstate->lr[(*expr)->id];
10687 if (lr->color == lr2->color) {
10688 different_colored(state, rstate,
10690 (*expr)->id = ins->id;
10696 } while(ins != first);
10698 /* Make a third pass and forget the virtual registers */
10699 for(i = 1; i <= rstate->ranges; i++) {
10700 if (rstate->lr[i].color >= MAX_REGISTERS) {
10701 rstate->lr[i].color = REG_UNSET;
10706 static struct triple *graph_ins(
10707 struct compile_state *state,
10708 struct reg_block *blocks, struct triple_reg_set *live,
10709 struct reg_block *rb, struct triple *ins, void *arg)
10711 struct reg_state *rstate = arg;
10712 struct live_range *def;
10713 struct triple_reg_set *entry;
10715 /* If the triple does not start a live range
10716 * we do not have a definition to add to
10717 * the interference graph.
10719 if (ins->id <= 0) {
10722 def = &rstate->lr[ins->id];
10724 /* Create an edge between ins and everything that is
10725 * alive, unless the live_range cannot share
10726 * a physical register with ins.
10728 for(entry = live; entry; entry = entry->next) {
10729 struct live_range *lr;
10730 lr= &rstate->lr[entry->member->id];
10731 if (!arch_regcm_intersect(def->classes, lr->classes)) {
10734 add_live_edge(rstate, def, lr);
10740 static struct triple *print_interference_ins(
10741 struct compile_state *state,
10742 struct reg_block *blocks, struct triple_reg_set *live,
10743 struct reg_block *rb, struct triple *ins, void *arg)
10745 struct reg_state *rstate = arg;
10746 struct live_range *lr;
10748 lr = &rstate->lr[ins->id];
10749 display_triple(stdout, ins);
10751 struct triple_reg_set *entry;
10753 for(entry = live; entry; entry = entry->next) {
10754 printf(" %-10p", entry->member);
10759 struct live_range_edge *entry;
10761 for(entry = lr->edges; entry; entry = entry->next) {
10762 printf(" %-10p", entry->node->def);
10766 if (triple_is_branch(state, ins)) {
10772 #if DEBUG_COLOR_GRAPH > 1
10773 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
10774 #define cgdebug_flush() fflush(stdout)
10775 #elif DEBUG_COLOR_GRAPH == 1
10776 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
10777 #define cgdebug_flush() fflush(stderr)
10779 #define cgdebug_printf(...)
10780 #define cgdebug_flush()
10783 static void select_free_color(struct compile_state *state,
10784 struct reg_state *rstate, struct live_range *range)
10786 struct triple_set *entry;
10787 struct live_range *phi;
10788 struct live_range_edge *edge;
10789 char used[MAX_REGISTERS];
10790 struct triple **expr;
10792 /* If a color is already assigned don't change it */
10793 if (range->color != REG_UNSET) {
10796 /* Instead of doing just the trivial color select here I try
10797 * a few extra things because a good color selection will help reduce
10801 /* Find the registers currently in use */
10802 memset(used, 0, sizeof(used));
10803 for(edge = range->edges; edge; edge = edge->next) {
10804 if (edge->node->color == REG_UNSET) {
10807 reg_fill_used(state, used, edge->node->color);
10809 #if DEBUG_COLOR_GRAPH > 1
10813 for(edge = range->edges; edge; edge = edge->next) {
10816 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
10817 tops(range->def->op), i,
10818 range->def->filename, range->def->line, range->def->col);
10819 for(i = 0; i < MAX_REGISTERS; i++) {
10821 cgdebug_printf("used: %s\n",
10828 /* If I feed into an expression reuse it's color.
10829 * This should help remove copies in the case of 2 register instructions
10830 * and phi functions.
10833 entry = range->def->use;
10834 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
10835 struct live_range *lr;
10836 lr = &rstate->lr[entry->member->id];
10837 if (entry->member->id == 0) {
10840 if (!phi && (lr->def->op == OP_PHI) &&
10841 !interfere(rstate, range, lr)) {
10844 if ((lr->color == REG_UNSET) ||
10845 ((lr->classes & range->classes) == 0) ||
10846 (used[lr->color])) {
10849 if (interfere(rstate, range, lr)) {
10852 range->color = lr->color;
10854 /* If I feed into a phi function reuse it's color of the color
10855 * of something else that feeds into the phi function.
10858 if (phi->color != REG_UNSET) {
10859 if (used[phi->color]) {
10860 range->color = phi->color;
10864 expr = triple_rhs(state, phi->def, 0);
10865 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
10866 struct live_range *lr;
10870 lr = &rstate->lr[(*expr)->id];
10871 if ((lr->color == REG_UNSET) ||
10872 ((lr->classes & range->classes) == 0) ||
10873 (used[lr->color])) {
10876 if (interfere(rstate, range, lr)) {
10879 range->color = lr->color;
10883 /* If I don't interfere with a rhs node reuse it's color */
10884 if (range->color == REG_UNSET) {
10885 expr = triple_rhs(state, range->def, 0);
10886 for(; expr; expr = triple_rhs(state, range->def, expr)) {
10887 struct live_range *lr;
10891 lr = &rstate->lr[(*expr)->id];
10892 if ((lr->color == -1) ||
10893 ((lr->classes & range->classes) == 0) ||
10894 (used[lr->color])) {
10897 if (interfere(rstate, range, lr)) {
10900 range->color = lr->color;
10904 /* If I have not opportunitically picked a useful color
10905 * pick the first color that is free.
10907 if (range->color == REG_UNSET) {
10909 arch_select_free_register(state, used, range->classes);
10911 if (range->color == REG_UNSET) {
10913 for(edge = range->edges; edge; edge = edge->next) {
10914 if (edge->node->color == REG_UNSET) {
10917 warning(state, edge->node->def, "reg %s",
10918 arch_reg_str(edge->node->color));
10920 warning(state, range->def, "classes: %x",
10922 for(i = 0; i < MAX_REGISTERS; i++) {
10924 warning(state, range->def, "used: %s",
10928 #if DEBUG_COLOR_GRAPH < 2
10929 error(state, range->def, "too few registers");
10931 internal_error(state, range->def, "too few registers");
10934 range->classes = arch_reg_regcm(state, range->color);
10938 static void color_graph(struct compile_state *state, struct reg_state *rstate)
10940 struct live_range_edge *edge;
10941 struct live_range *range;
10943 cgdebug_printf("Lo: ");
10944 range = rstate->low;
10945 if (*range->group_prev != range) {
10946 internal_error(state, 0, "lo: *prev != range?");
10948 *range->group_prev = range->group_next;
10949 if (range->group_next) {
10950 range->group_next->group_prev = range->group_prev;
10952 if (&range->group_next == rstate->low_tail) {
10953 rstate->low_tail = range->group_prev;
10955 if (rstate->low == range) {
10956 internal_error(state, 0, "low: next != prev?");
10959 else if (rstate->high) {
10960 cgdebug_printf("Hi: ");
10961 range = rstate->high;
10962 if (*range->group_prev != range) {
10963 internal_error(state, 0, "hi: *prev != range?");
10965 *range->group_prev = range->group_next;
10966 if (range->group_next) {
10967 range->group_next->group_prev = range->group_prev;
10969 if (&range->group_next == rstate->high_tail) {
10970 rstate->high_tail = range->group_prev;
10972 if (rstate->high == range) {
10973 internal_error(state, 0, "high: next != prev?");
10979 cgdebug_printf(" %d\n", range - rstate->lr);
10980 range->group_prev = 0;
10981 for(edge = range->edges; edge; edge = edge->next) {
10982 struct live_range *node;
10984 /* Move nodes from the high to the low list */
10985 if (node->group_prev && (node->color == REG_UNSET) &&
10986 (node->degree == regc_max_size(state, node->classes))) {
10987 if (*node->group_prev != node) {
10988 internal_error(state, 0, "move: *prev != node?");
10990 *node->group_prev = node->group_next;
10991 if (node->group_next) {
10992 node->group_next->group_prev = node->group_prev;
10994 if (&node->group_next == rstate->high_tail) {
10995 rstate->high_tail = node->group_prev;
10997 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
10998 node->group_prev = rstate->low_tail;
10999 node->group_next = 0;
11000 *rstate->low_tail = node;
11001 rstate->low_tail = &node->group_next;
11002 if (*node->group_prev != node) {
11003 internal_error(state, 0, "move2: *prev != node?");
11008 color_graph(state, rstate);
11009 cgdebug_printf("Coloring %d @%s:%d.%d:",
11010 range - rstate->lr,
11011 range->def->filename, range->def->line, range->def->col);
11013 select_free_color(state, rstate, range);
11014 if (range->color == -1) {
11015 internal_error(state, range->def, "select_free_color did not?");
11017 cgdebug_printf(" %s\n", arch_reg_str(range->color));
11020 static void color_triples(struct compile_state *state, struct reg_state *rstate)
11022 struct live_range *lr;
11023 struct triple *first, *triple;
11024 first = RHS(state->main_function, 0);
11027 if ((triple->id < 0) || (triple->id > rstate->ranges)) {
11028 internal_error(state, triple,
11029 "triple without a live range");
11031 lr = &rstate->lr[triple->id];
11032 triple->id = MK_REG_ID(lr->color, 0);
11033 triple = triple->next;
11034 } while (triple != first);
11037 static void print_interference_block(
11038 struct compile_state *state, struct block *block, void *arg)
11041 struct reg_state *rstate = arg;
11042 struct reg_block *rb;
11043 struct triple *ptr;
11046 rb = &rstate->blocks[block->vertex];
11048 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
11052 block->left && block->left->use?block->left->use->member : 0,
11054 block->right && block->right->use?block->right->use->member : 0);
11056 struct triple_reg_set *in_set;
11058 for(in_set = rb->in; in_set; in_set = in_set->next) {
11059 printf(" %-10p", in_set->member);
11064 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11065 done = (ptr == block->last);
11066 if (ptr->op == OP_PHI) {
11073 for(edge = 0; edge < block->users; edge++) {
11074 printf(" in(%d):", edge);
11075 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11076 struct triple **slot;
11077 done = (ptr == block->last);
11078 if (ptr->op != OP_PHI) {
11081 slot = &RHS(ptr, 0);
11082 printf(" %-10p", slot[edge]);
11087 if (block->first->op == OP_LABEL) {
11088 printf("%p:\n", block->first);
11090 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11091 struct triple_set *user;
11092 struct live_range *lr;
11096 done = (ptr == block->last);
11097 lr = &rstate->lr[ptr->id];
11099 if (!IS_CONST_OP(op)) {
11100 if (ptr->u.block != block) {
11101 internal_error(state, ptr,
11102 "Wrong block pointer: %p",
11106 if (op == OP_ADECL) {
11107 for(user = ptr->use; user; user = user->next) {
11108 struct live_range *lr;
11109 lr = &rstate->lr[user->member->id];
11110 if (!user->member->u.block) {
11111 internal_error(state, user->member,
11112 "Use %p not in a block?",
11119 ptr->id = MK_REG_ID(lr->color, 0);
11120 display_triple(stdout, ptr);
11123 if (lr->edges > 0) {
11124 struct live_range_edge *edge;
11126 for(edge = lr->edges; edge; edge = edge->next) {
11127 printf(" %-10p", edge->node->def);
11131 /* Do a bunch of sanity checks */
11132 valid_ins(state, ptr);
11133 if ((ptr->id < 0) || (ptr->id > rstate->ranges)) {
11134 internal_error(state, ptr, "Invalid triple id: %d",
11137 for(user = ptr->use; user; user = user->next) {
11138 struct triple *use;
11139 struct live_range *ulr;
11140 use = user->member;
11141 valid_ins(state, use);
11142 if ((use->id < 0) || (use->id > rstate->ranges)) {
11143 internal_error(state, use, "Invalid triple id: %d",
11146 ulr = &rstate->lr[user->member->id];
11147 if (!IS_CONST_OP(user->member->op) &&
11148 !user->member->u.block) {
11149 internal_error(state, user->member,
11150 "Use %p not in a block?",
11156 struct triple_reg_set *out_set;
11158 for(out_set = rb->out; out_set; out_set = out_set->next) {
11159 printf(" %-10p", out_set->member);
11166 static struct live_range *merge_sort_lr(
11167 struct live_range *first, struct live_range *last)
11169 struct live_range *mid, *join, **join_tail, *pick;
11171 size = (last - first) + 1;
11173 mid = first + size/2;
11174 first = merge_sort_lr(first, mid -1);
11175 mid = merge_sort_lr(mid, last);
11179 /* merge the two lists */
11180 while(first && mid) {
11181 if (first->degree <= mid->degree) {
11183 first = first->group_next;
11185 first->group_prev = 0;
11190 mid = mid->group_next;
11192 mid->group_prev = 0;
11195 pick->group_next = 0;
11196 pick->group_prev = join_tail;
11198 join_tail = &pick->group_next;
11200 /* Splice the remaining list */
11201 pick = (first)? first : mid;
11203 pick->group_prev = join_tail;
11214 static void allocate_registers(struct compile_state *state)
11216 struct reg_state rstate;
11217 struct live_range **point, **next;
11220 /* Clear out the reg_state */
11221 memset(&rstate, 0, sizeof(rstate));
11223 /* Compute the variable lifetimes */
11224 rstate.blocks = compute_variable_lifetimes(state);
11226 /* Allocate and initialize the live ranges */
11227 initialize_live_ranges(state, &rstate);
11229 /* Compute the interference graph */
11230 walk_variable_lifetimes(
11231 state, rstate.blocks, graph_ins, &rstate);
11233 /* Display the interference graph if desired */
11234 if (state->debug & DEBUG_INTERFERENCE) {
11235 printf("\nlive variables by block\n");
11236 walk_blocks(state, print_interference_block, &rstate);
11237 printf("\nlive variables by instruction\n");
11238 walk_variable_lifetimes(
11239 state, rstate.blocks,
11240 print_interference_ins, &rstate);
11243 /* Do not perform coalescing! It is a neat idea but it limits what
11244 * we can do later. It has no benefits that decrease register pressure.
11245 * It only decreases instruction count.
11247 * It might be worth testing this reducing the number of
11248 * live_ragnes as opposed to splitting them seems to help.
11251 /* Build the groups low and high. But with the nodes
11252 * first sorted by degree order.
11254 rstate.low_tail = &rstate.low;
11255 rstate.high_tail = &rstate.high;
11256 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
11258 rstate.high->group_prev = &rstate.high;
11260 for(point = &rstate.high; *point; point = &(*point)->group_next)
11262 rstate.high_tail = point;
11263 /* Walk through the high list and move everything that needs
11266 for(point = &rstate.high; *point; point = next) {
11267 struct live_range *range;
11268 next = &(*point)->group_next;
11271 /* If it has a low degree or it already has a color
11272 * place the node in low.
11274 if ((range->degree < regc_max_size(state, range->classes)) ||
11275 (range->color != REG_UNSET)) {
11276 cgdebug_printf("Lo: %5d degree %5d%s\n",
11277 range - rstate.lr, range->degree,
11278 (range->color != REG_UNSET) ? " (colored)": "");
11279 *range->group_prev = range->group_next;
11280 if (range->group_next) {
11281 range->group_next->group_prev = range->group_prev;
11283 if (&range->group_next == rstate.high_tail) {
11284 rstate.high_tail = range->group_prev;
11286 range->group_prev = rstate.low_tail;
11287 range->group_next = 0;
11288 *rstate.low_tail = range;
11289 rstate.low_tail = &range->group_next;
11293 cgdebug_printf("hi: %5d degree %5d%s\n",
11294 range - rstate.lr, range->degree,
11295 (range->color != REG_UNSET) ? " (colored)": "");
11299 /* Color the live_ranges */
11300 color_graph(state, &rstate);
11302 /* Move the colors from the graph to the triples */
11303 color_triples(state, &rstate);
11305 /* Free the edges on each node */
11306 for(i = 1; i <= rstate.ranges; i++) {
11307 remove_live_edges(&rstate, &rstate.lr[i]);
11311 /* Free the variable lifetime information */
11312 free_variable_lifetimes(state, rstate.blocks);
11316 /* Sparce Conditional Constant Propogation
11317 * =========================================
11321 struct lattice_node {
11322 struct triple *def;
11323 struct ssa_edge *out;
11324 struct flow_block *fblock;
11325 struct triple *val;
11326 /* lattice high val && !is_const(val)
11327 * lattice const is_const(val)
11328 * lattice low val == 0
11332 struct lattice_node *src;
11333 struct lattice_node *dst;
11334 struct ssa_edge *work_next;
11335 struct ssa_edge *work_prev;
11336 struct ssa_edge *out_next;
11339 struct flow_block *src;
11340 struct flow_block *dst;
11341 struct flow_edge *work_next;
11342 struct flow_edge *work_prev;
11343 struct flow_edge *in_next;
11344 struct flow_edge *out_next;
11347 struct flow_block {
11348 struct block *block;
11349 struct flow_edge *in;
11350 struct flow_edge *out;
11351 struct flow_edge left, right;
11356 struct lattice_node *lattice;
11357 struct ssa_edge *ssa_edges;
11358 struct flow_block *flow_blocks;
11359 struct flow_edge *flow_work_list;
11360 struct ssa_edge *ssa_work_list;
11364 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
11365 struct flow_edge *fedge)
11367 if (!scc->flow_work_list) {
11368 scc->flow_work_list = fedge;
11369 fedge->work_next = fedge->work_prev = fedge;
11372 struct flow_edge *ftail;
11373 ftail = scc->flow_work_list->work_prev;
11374 fedge->work_next = ftail->work_next;
11375 fedge->work_prev = ftail;
11376 fedge->work_next->work_prev = fedge;
11377 fedge->work_prev->work_next = fedge;
11381 static struct flow_edge *scc_next_fedge(
11382 struct compile_state *state, struct scc_state *scc)
11384 struct flow_edge *fedge;
11385 fedge = scc->flow_work_list;
11387 fedge->work_next->work_prev = fedge->work_prev;
11388 fedge->work_prev->work_next = fedge->work_next;
11389 if (fedge->work_next != fedge) {
11390 scc->flow_work_list = fedge->work_next;
11392 scc->flow_work_list = 0;
11398 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
11399 struct ssa_edge *sedge)
11401 if (!scc->ssa_work_list) {
11402 scc->ssa_work_list = sedge;
11403 sedge->work_next = sedge->work_prev = sedge;
11406 struct ssa_edge *stail;
11407 stail = scc->ssa_work_list->work_prev;
11408 sedge->work_next = stail->work_next;
11409 sedge->work_prev = stail;
11410 sedge->work_next->work_prev = sedge;
11411 sedge->work_prev->work_next = sedge;
11415 static struct ssa_edge *scc_next_sedge(
11416 struct compile_state *state, struct scc_state *scc)
11418 struct ssa_edge *sedge;
11419 sedge = scc->ssa_work_list;
11421 sedge->work_next->work_prev = sedge->work_prev;
11422 sedge->work_prev->work_next = sedge->work_next;
11423 if (sedge->work_next != sedge) {
11424 scc->ssa_work_list = sedge->work_next;
11426 scc->ssa_work_list = 0;
11432 static void initialize_scc_state(
11433 struct compile_state *state, struct scc_state *scc)
11435 int ins_count, ssa_edge_count;
11436 int ins_index, ssa_edge_index, fblock_index;
11437 struct triple *first, *ins;
11438 struct block *block;
11439 struct flow_block *fblock;
11441 memset(scc, 0, sizeof(*scc));
11443 /* Inialize pass zero find out how much memory we need */
11444 first = RHS(state->main_function, 0);
11446 ins_count = ssa_edge_count = 0;
11448 struct triple_set *edge;
11450 for(edge = ins->use; edge; edge = edge->next) {
11454 } while(ins != first);
11456 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
11457 ins_count, ssa_edge_count, state->last_vertex);
11459 scc->ins_count = ins_count;
11461 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
11463 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
11465 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
11468 /* Initialize pass one collect up the nodes */
11471 ins_index = ssa_edge_index = fblock_index = 0;
11475 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11476 block = ins->u.block;
11478 internal_error(state, ins, "label without block");
11481 block->vertex = fblock_index;
11482 fblock = &scc->flow_blocks[fblock_index];
11483 fblock->block = block;
11486 struct lattice_node *lnode;
11488 ins->id = ins_index;
11489 lnode = &scc->lattice[ins_index];
11492 lnode->fblock = fblock;
11493 lnode->val = ins; /* LATTICE HIGH */
11496 } while(ins != first);
11497 /* Initialize pass two collect up the edges */
11502 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11503 struct flow_edge *fedge, **ftail;
11504 struct block_set *bedge;
11505 block = ins->u.block;
11506 fblock = &scc->flow_blocks[block->vertex];
11509 ftail = &fblock->out;
11511 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
11512 if (fblock->left.dst->block != block->left) {
11513 internal_error(state, 0, "block mismatch");
11515 fblock->left.out_next = 0;
11516 *ftail = &fblock->left;
11517 ftail = &fblock->left.out_next;
11519 if (block->right) {
11520 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
11521 if (fblock->right.dst->block != block->right) {
11522 internal_error(state, 0, "block mismatch");
11524 fblock->right.out_next = 0;
11525 *ftail = &fblock->right;
11526 ftail = &fblock->right.out_next;
11528 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
11529 fedge->src = fblock;
11530 fedge->work_next = fedge->work_prev = fedge;
11531 fedge->executable = 0;
11533 ftail = &fblock->in;
11534 for(bedge = block->use; bedge; bedge = bedge->next) {
11535 struct block *src_block;
11536 struct flow_block *sfblock;
11537 struct flow_edge *sfedge;
11538 src_block = bedge->member;
11539 sfblock = &scc->flow_blocks[src_block->vertex];
11541 if (src_block->left == block) {
11542 sfedge = &sfblock->left;
11544 sfedge = &sfblock->right;
11547 ftail = &sfedge->in_next;
11548 sfedge->in_next = 0;
11552 struct triple_set *edge;
11553 struct ssa_edge **stail;
11554 struct lattice_node *lnode;
11555 lnode = &scc->lattice[ins->id];
11557 stail = &lnode->out;
11558 for(edge = ins->use; edge; edge = edge->next) {
11559 struct ssa_edge *sedge;
11560 ssa_edge_index += 1;
11561 sedge = &scc->ssa_edges[ssa_edge_index];
11563 stail = &sedge->out_next;
11564 sedge->src = lnode;
11565 sedge->dst = &scc->lattice[edge->member->id];
11566 sedge->work_next = sedge->work_prev = sedge;
11567 sedge->out_next = 0;
11571 } while(ins != first);
11572 /* Setup a dummy block 0 as a node above the start node */
11574 struct flow_block *fblock, *dst;
11575 struct flow_edge *fedge;
11576 fblock = &scc->flow_blocks[0];
11579 fblock->out = &fblock->left;
11580 dst = &scc->flow_blocks[state->first_block->vertex];
11581 fedge = &fblock->left;
11582 fedge->src = fblock;
11584 fedge->work_next = fedge;
11585 fedge->work_prev = fedge;
11586 fedge->in_next = fedge->dst->in;
11587 fedge->out_next = 0;
11588 fedge->executable = 0;
11589 fedge->dst->in = fedge;
11591 /* Initialize the work lists */
11592 scc->flow_work_list = 0;
11593 scc->ssa_work_list = 0;
11594 scc_add_fedge(state, scc, fedge);
11597 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
11598 ins_index, ssa_edge_index, fblock_index);
11603 static void free_scc_state(
11604 struct compile_state *state, struct scc_state *scc)
11607 for(i = 0; i < scc->ins_count; i++) {
11608 if (scc->lattice[i].val &&
11609 (scc->lattice[i].val != scc->lattice[i].def)) {
11610 xfree(scc->lattice[i].val);
11613 xfree(scc->flow_blocks);
11614 xfree(scc->ssa_edges);
11615 xfree(scc->lattice);
11619 static struct lattice_node *triple_to_lattice(
11620 struct compile_state *state, struct scc_state *scc, struct triple *ins)
11622 if (ins->id <= 0) {
11623 internal_error(state, ins, "bad id");
11625 return &scc->lattice[ins->id];
11628 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
11629 struct lattice_node *lnode)
11631 struct lattice_node *tmp;
11632 struct triple **slot;
11633 struct flow_edge *fedge;
11635 if (lnode->def->op != OP_PHI) {
11636 internal_error(state, lnode->def, "not phi");
11638 /* default to lattice high */
11639 lnode->val = lnode->def;
11640 slot = &RHS(lnode->def, 0);
11642 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
11643 if (!fedge->executable) {
11646 if (!slot[index]) {
11647 internal_error(state, lnode->def, "no phi value");
11649 tmp = triple_to_lattice(state, scc, slot[index]);
11650 /* meet(X, lattice low) = lattice low */
11654 /* meet(X, lattice high) = X */
11655 else if (!tmp->val) {
11656 lnode->val = lnode->val;
11658 /* meet(lattice high, X) = X */
11659 else if (!is_const(lnode->val)) {
11660 lnode->val = tmp->val;
11662 /* meet(const, const) = const or lattice low */
11663 else if (!constants_equal(state, lnode->val, tmp->val)) {
11670 /* Do I need to update any work lists here? */
11672 fprintf(stderr, "phi: %d -> %s\n",
11674 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11678 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
11679 struct lattice_node *lnode)
11682 struct triple *old, *scratch;
11683 struct triple **dexpr, **vexpr;
11686 if (lnode->def->op != OP_STORE) {
11687 check_lhs(state, lnode->def);
11690 /* Store the original value */
11692 old = dup_triple(state, lnode->val);
11693 if (lnode->val != lnode->def) {
11701 /* Reinitialize the value */
11702 lnode->val = scratch = dup_triple(state, lnode->def);
11703 scratch->next = scratch;
11704 scratch->prev = scratch;
11707 count = TRIPLE_SIZE(scratch->sizes);
11708 for(i = 0; i < count; i++) {
11709 struct lattice_node *tmp;
11710 dexpr = &lnode->def->param[i];
11711 vexpr = &scratch->param[i];
11714 tmp = triple_to_lattice(state, scc, *dexpr);
11715 *vexpr = (tmp->val)? tmp->val : tmp->def;
11718 if (scratch->op == OP_BRANCH) {
11719 scratch->next = lnode->def->next;
11721 /* Recompute the value */
11722 #warning "FIXME see if simplify does anything bad"
11723 /* So far it looks like only the strength reduction
11724 * optimization are things I need to worry about.
11726 simplify(state, scratch);
11727 /* Cleanup my value */
11728 if (scratch->use) {
11729 internal_error(state, lnode->def, "scratch used?");
11731 if ((scratch->prev != scratch) ||
11732 ((scratch->next != scratch) &&
11733 ((lnode->def->op != OP_BRANCH) ||
11734 (scratch->next != lnode->def->next)))) {
11735 internal_error(state, lnode->def, "scratch in list?");
11737 /* undo any uses... */
11738 count = TRIPLE_SIZE(scratch->sizes);
11739 for(i = 0; i < count; i++) {
11740 vexpr = &scratch->param[i];
11742 unuse_triple(*vexpr, scratch);
11745 if (!is_const(scratch)) {
11746 for(i = 0; i < count; i++) {
11747 dexpr = &lnode->def->param[i];
11749 struct lattice_node *tmp;
11750 tmp = triple_to_lattice(state, scc, *dexpr);
11758 (lnode->val->op == lnode->def->op) &&
11759 (memcmp(lnode->val->param, lnode->def->param,
11760 count * sizeof(lnode->val->param[0])) == 0) &&
11761 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
11762 lnode->val = lnode->def;
11764 /* Find the cases that are always lattice lo */
11766 triple_is_def(state, lnode->val) &&
11767 !triple_is_pure(state, lnode->val)) {
11772 (lnode->val->op == OP_SDECL) &&
11773 (lnode->val != lnode->def)) {
11774 internal_error(state, lnode->def, "bad sdecl");
11777 /* See if the lattice value has changed */
11779 if (!old && !lnode->val) {
11782 if (changed && lnode->val && !is_const(lnode->val)) {
11786 lnode->val && old &&
11787 (lnode->val->op == old->op) &&
11788 (memcmp(lnode->val->param, old->param,
11789 count * sizeof(lnode->val->param[0])) == 0) &&
11790 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
11796 if (lnode->val != scratch) {
11802 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
11803 struct lattice_node *lnode)
11805 struct lattice_node *cond;
11808 struct flow_edge *fedge;
11809 fprintf(stderr, "branch: %d (",
11812 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
11813 fprintf(stderr, " %d", fedge->dst->block->vertex);
11815 fprintf(stderr, " )");
11816 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
11817 fprintf(stderr, " <- %d",
11818 RHS(lnode->def)->id);
11820 fprintf(stderr, "\n");
11823 if (lnode->def->op != OP_BRANCH) {
11824 internal_error(state, lnode->def, "not branch");
11826 /* This only applies to conditional branches */
11827 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
11830 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
11831 if (cond->val && !is_const(cond->val)) {
11832 #warning "FIXME do I need to do something here?"
11833 warning(state, cond->def, "condition not constant?");
11836 if (cond->val == 0) {
11837 scc_add_fedge(state, scc, cond->fblock->out);
11838 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11840 else if (cond->val->u.cval) {
11841 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11844 scc_add_fedge(state, scc, cond->fblock->out);
11849 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
11850 struct lattice_node *lnode)
11854 changed = compute_lnode_val(state, scc, lnode);
11857 struct triple **expr;
11858 fprintf(stderr, "expr: %3d %10s (",
11859 lnode->def->id, tops(lnode->def->op));
11860 expr = triple_rhs(state, lnode->def, 0);
11861 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
11863 fprintf(stderr, " %d", (*expr)->id);
11866 fprintf(stderr, " ) -> %s\n",
11867 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11870 if (lnode->def->op == OP_BRANCH) {
11871 scc_visit_branch(state, scc, lnode);
11874 else if (changed) {
11875 struct ssa_edge *sedge;
11876 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
11877 scc_add_sedge(state, scc, sedge);
11882 static void scc_writeback_values(
11883 struct compile_state *state, struct scc_state *scc)
11885 struct triple *first, *ins;
11886 first = RHS(state->main_function, 0);
11889 struct lattice_node *lnode;
11890 lnode = triple_to_lattice(state, scc, ins);
11892 if (lnode->val && !is_const(lnode->val)) {
11893 warning(state, lnode->def,
11894 "lattice node still high?");
11897 if (lnode->val && (lnode->val != ins)) {
11898 /* See if it something I know how to write back */
11899 switch(lnode->val->op) {
11901 mkconst(state, ins, lnode->val->u.cval);
11904 mkaddr_const(state, ins,
11905 RHS(lnode->val, 0), lnode->val->u.cval);
11908 /* By default don't copy the changes,
11909 * recompute them in place instead.
11911 simplify(state, ins);
11916 } while(ins != first);
11919 static void scc_transform(struct compile_state *state)
11921 struct scc_state scc;
11923 initialize_scc_state(state, &scc);
11925 while(scc.flow_work_list || scc.ssa_work_list) {
11926 struct flow_edge *fedge;
11927 struct ssa_edge *sedge;
11928 struct flow_edge *fptr;
11929 while((fedge = scc_next_fedge(state, &scc))) {
11930 struct block *block;
11931 struct triple *ptr;
11932 struct flow_block *fblock;
11935 if (fedge->executable) {
11939 internal_error(state, 0, "fedge without dst");
11942 internal_error(state, 0, "fedge without src");
11944 fedge->executable = 1;
11945 fblock = fedge->dst;
11946 block = fblock->block;
11948 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
11949 if (fptr->executable) {
11954 fprintf(stderr, "vertex: %d time: %d\n",
11955 block->vertex, time);
11959 for(ptr = block->first; !done; ptr = ptr->next) {
11960 struct lattice_node *lnode;
11961 done = (ptr == block->last);
11962 lnode = &scc.lattice[ptr->id];
11963 if (ptr->op == OP_PHI) {
11964 scc_visit_phi(state, &scc, lnode);
11966 else if (time == 1) {
11967 scc_visit_expr(state, &scc, lnode);
11970 if (fblock->out && !fblock->out->out_next) {
11971 scc_add_fedge(state, &scc, fblock->out);
11974 while((sedge = scc_next_sedge(state, &scc))) {
11975 struct lattice_node *lnode;
11976 struct flow_block *fblock;
11977 lnode = sedge->dst;
11978 fblock = lnode->fblock;
11980 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
11981 sedge - scc.ssa_edges,
11982 sedge->src->def->id,
11983 sedge->dst->def->id);
11985 if (lnode->def->op == OP_PHI) {
11986 scc_visit_phi(state, &scc, lnode);
11989 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
11990 if (fptr->executable) {
11995 scc_visit_expr(state, &scc, lnode);
12001 scc_writeback_values(state, &scc);
12002 free_scc_state(state, &scc);
12006 static void transform_to_arch_instructions(struct compile_state *state);
12009 static void optimize(struct compile_state *state)
12011 if (state->debug & DEBUG_TRIPLES) {
12012 print_triples(state);
12014 /* Replace structures with simpler data types */
12015 flatten_structures(state);
12016 if (state->debug & DEBUG_TRIPLES) {
12017 print_triples(state);
12019 /* Analize the intermediate code */
12020 setup_basic_blocks(state);
12021 analyze_idominators(state);
12022 analyze_ipdominators(state);
12023 /* Transform the code to ssa form */
12024 transform_to_ssa_form(state);
12025 /* Do strength reduction and simple constant optimizations */
12026 if (state->optimize >= 1) {
12027 simplify_all(state);
12029 /* Propogate constants throughout the code */
12030 if (state->optimize >= 2) {
12031 scc_transform(state);
12032 transform_from_ssa_form(state);
12033 free_basic_blocks(state);
12034 setup_basic_blocks(state);
12035 analyze_idominators(state);
12036 analyze_ipdominators(state);
12037 transform_to_ssa_form(state);
12040 #warning "WISHLIST implement single use constants (least possible register pressure)"
12041 #warning "WISHLIST implement induction variable elimination"
12042 #warning "WISHLIST implement strength reduction"
12043 /* Select architecture instructions and an initial partial
12044 * coloring based on architecture constraints.
12046 transform_to_arch_instructions(state);
12047 if (state->debug & DEBUG_ARCH_CODE) {
12048 printf("After transform_to_arch_instructions\n");
12049 print_blocks(state);
12050 print_control_flow(state);
12052 eliminate_inefectual_code(state);
12053 if (state->debug & DEBUG_CODE_ELIMINATION) {
12054 printf("After eliminate_inefectual_code\n");
12055 print_blocks(state);
12056 print_control_flow(state);
12058 /* Color all of the variables to see if they will fit in registers */
12059 insert_copies_to_phi(state);
12060 allocate_registers(state);
12061 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
12062 print_blocks(state);
12064 if (state->debug & DEBUG_CONTROL_FLOW) {
12065 print_control_flow(state);
12067 /* Remove the optimization information.
12068 * This is more to check for memory consistency than to free memory.
12070 free_basic_blocks(state);
12073 /* The x86 register classes */
12074 #define REGC_FLAGS 0
12075 #define REGC_GPR8 1
12076 #define REGC_GPR16 2
12077 #define REGC_GPR32 3
12078 #define REGC_GPR64 4
12081 #define REGC_GPR32_8 7
12082 #define REGC_GPR16_8 8
12083 #define LAST_REGC REGC_GPR16_8
12084 #if LAST_REGC >= MAX_REGC
12085 #error "MAX_REGC is to low"
12088 /* Register class masks */
12089 #define REGCM_FLAGS (1 << REGC_FLAGS)
12090 #define REGCM_GPR8 (1 << REGC_GPR8)
12091 #define REGCM_GPR16 (1 << REGC_GPR16)
12092 #define REGCM_GPR32 (1 << REGC_GPR32)
12093 #define REGCM_GPR64 (1 << REGC_GPR64)
12094 #define REGCM_MMX (1 << REGC_MMX)
12095 #define REGCM_XMM (1 << REGC_XMM)
12096 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
12097 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
12099 /* The x86 registers */
12100 #define REG_EFLAGS 1
12101 #define REGC_FLAGS_FIRST REG_EFLAGS
12102 #define REGC_FLAGS_LAST REG_EFLAGS
12111 #define REGC_GPR8_FIRST REG_AL
12112 #if X86_4_8BIT_GPRS
12113 #define REGC_GPR8_LAST REG_DL
12115 #define REGC_GPR8_LAST REG_DH
12125 #define REGC_GPR16_FIRST REG_AX
12126 #define REGC_GPR16_LAST REG_SP
12135 #define REGC_GPR32_FIRST REG_EAX
12136 #define REGC_GPR32_LAST REG_ESP
12137 #define REG_EDXEAX 26
12138 #define REGC_GPR64_FIRST REG_EDXEAX
12139 #define REGC_GPR64_LAST REG_EDXEAX
12140 #define REG_MMX0 27
12141 #define REG_MMX1 28
12142 #define REG_MMX2 29
12143 #define REG_MMX3 30
12144 #define REG_MMX4 31
12145 #define REG_MMX5 32
12146 #define REG_MMX6 33
12147 #define REG_MMX7 34
12148 #define REGC_MMX_FIRST REG_MMX0
12149 #define REGC_MMX_LAST REG_MMX7
12150 #define REG_XMM0 35
12151 #define REG_XMM1 36
12152 #define REG_XMM2 37
12153 #define REG_XMM3 38
12154 #define REG_XMM4 39
12155 #define REG_XMM5 40
12156 #define REG_XMM6 41
12157 #define REG_XMM7 42
12158 #define REGC_XMM_FIRST REG_XMM0
12159 #define REGC_XMM_LAST REG_XMM7
12160 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
12161 #define LAST_REG REG_XMM7
12163 #define REGC_GPR32_8_FIRST REG_EAX
12164 #define REGC_GPR32_8_LAST REG_EDX
12165 #define REGC_GPR16_8_FIRST REG_AX
12166 #define REGC_GPR16_8_LAST REG_DX
12168 #if LAST_REG >= MAX_REGISTERS
12169 #error "MAX_REGISTERS to low"
12172 static unsigned arch_regc_size(struct compile_state *state, int class)
12174 static unsigned regc_size[LAST_REGC +1] = {
12175 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
12176 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
12177 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
12178 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
12179 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
12180 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
12181 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
12182 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
12183 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
12185 if ((class < 0) || (class > LAST_REGC)) {
12188 return regc_size[class];
12190 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
12192 /* See if two register classes may have overlapping registers */
12193 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
12194 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
12196 return (regcm1 & regcm2) ||
12197 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
12200 static void arch_reg_equivs(
12201 struct compile_state *state, unsigned *equiv, int reg)
12203 if ((reg < 0) || (reg > LAST_REG)) {
12204 internal_error(state, 0, "invalid register");
12211 *equiv++ = REG_EAX;
12212 *equiv++ = REG_EDXEAX;
12217 *equiv++ = REG_EBX;
12222 *equiv++ = REG_ECX;
12227 *equiv++ = REG_EDX;
12228 *equiv++ = REG_EDXEAX;
12233 *equiv++ = REG_EAX;
12234 *equiv++ = REG_EDXEAX;
12239 *equiv++ = REG_EBX;
12244 *equiv++ = REG_ECX;
12249 *equiv++ = REG_EDX;
12250 *equiv++ = REG_EDXEAX;
12253 *equiv++ = REG_ESI;
12256 *equiv++ = REG_EDI;
12259 *equiv++ = REG_EBP;
12262 *equiv++ = REG_ESP;
12268 *equiv++ = REG_EDXEAX;
12284 *equiv++ = REG_EDXEAX;
12305 *equiv++ = REG_EAX;
12306 *equiv++ = REG_EDX;
12309 *equiv++ = REG_UNSET;
12313 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
12315 static const struct {
12317 } bound[LAST_REGC + 1] = {
12318 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
12319 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
12320 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
12321 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
12322 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
12323 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
12324 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
12325 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
12326 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
12331 for(class = 0; class <= LAST_REGC; class++) {
12332 if ((reg >= bound[class].first) &&
12333 (reg <= bound[class].last)) {
12334 mask |= (1 << class);
12338 internal_error(state, 0, "reg %d not in any class", reg);
12343 static int do_select_reg(struct compile_state *state,
12344 char *used, int reg, unsigned classes)
12350 mask = arch_reg_regcm(state, reg);
12351 return (classes & mask) ? reg : REG_UNSET;
12354 static int arch_select_free_register(
12355 struct compile_state *state, char *used, int classes)
12357 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
12358 * other types of registers.
12362 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
12363 reg = do_select_reg(state, used, i, classes);
12365 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
12366 reg = do_select_reg(state, used, i, classes);
12368 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
12369 reg = do_select_reg(state, used, i, classes);
12371 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
12372 reg = do_select_reg(state, used, i, classes);
12374 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
12375 reg = do_select_reg(state, used, i, classes);
12377 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
12378 reg = do_select_reg(state, used, i, classes);
12380 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
12381 reg = do_select_reg(state, used, i, classes);
12386 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
12388 #warning "FIXME force types smaller (if legal) before I get here"
12391 unsigned avail_mask;
12393 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
12394 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64;
12396 /* Don't enable 8 bit values until I can force both operands
12397 * to be 8bits simultaneously.
12399 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
12402 avail_mask |= REGCM_MMX;
12405 avail_mask |= REGCM_XMM;
12408 switch(type->type & TYPE_MASK) {
12415 mask = REGCM_GPR8 |
12416 REGCM_GPR16_8 | REGCM_GPR16 |
12417 REGCM_GPR32 | REGCM_GPR32_8 |
12419 REGCM_MMX | REGCM_XMM;
12423 mask = REGCM_GPR16 | REGCM_GPR16_8 |
12424 REGCM_GPR32 | REGCM_GPR32_8 |
12426 REGCM_MMX | REGCM_XMM;
12433 mask = REGCM_GPR32 | REGCM_GPR32_8 |
12434 REGCM_GPR64 | REGCM_MMX | REGCM_XMM;
12437 internal_error(state, 0, "no register class for type");
12440 mask &= avail_mask;
12444 static void get_imm32(struct triple *ins, struct triple **expr)
12446 struct triple *imm;
12447 if ((*expr)->op != OP_COPY) {
12450 imm = RHS((*expr), 0);
12451 while(imm->op == OP_COPY) {
12454 if (imm->op != OP_INTCONST) {
12458 unuse_triple(*expr, ins);
12459 use_triple(*expr, ins);
12462 static void get_imm8(struct triple *ins, struct triple **expr)
12464 struct triple *imm;
12465 if ((*expr)->op != OP_COPY) {
12468 imm = RHS((*expr), 0);
12469 while(imm->op == OP_COPY) {
12472 if (imm->op != OP_INTCONST) {
12475 /* For imm8 only a sufficienlty small constant can be used */
12476 if (imm->u.cval > 0xff) {
12480 unuse_triple(*expr, ins);
12481 use_triple(*expr, ins);
12484 static struct triple *pre_copy(struct compile_state *state,
12485 struct triple *ins, struct triple **expr,
12486 unsigned reg, unsigned mask)
12488 /* Carefully insert enough operations so that I can
12489 * enter any operation with a GPR32.
12492 /* See if I can directly reach the result from a GPR32 */
12493 if (mask & (REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)) {
12494 in = triple(state, OP_COPY, (*expr)->type, *expr, 0);
12496 /* If it is a byte value force a earlier copy to a GPR32_8 */
12497 else if (mask & REGCM_GPR8) {
12498 struct triple *tmp;
12499 tmp = triple(state, OP_COPY, (*expr)->type, *expr, 0);
12500 tmp->filename = ins->filename;
12501 tmp->line = ins->line;
12502 tmp->col = ins->col;
12503 tmp->u.block = ins->u.block;
12504 tmp->id = MK_REG_ID(REG_UNSET, REGCM_GPR32_8 | REGCM_GPR16_8);
12505 use_triple(RHS(tmp, 0), tmp);
12506 insert_triple(state, ins, tmp);
12508 in = triple(state, OP_COPY, tmp->type, tmp, 0);
12511 internal_error(state, ins, "bad copy type");
12514 in->filename = ins->filename;
12515 in->line = ins->line;
12516 in->col = ins->col;
12517 in->u.block = ins->u.block;
12518 in->id = MK_REG_ID(reg, mask);
12519 unuse_triple(*expr, ins);
12521 use_triple(RHS(in, 0), in);
12522 use_triple(in, ins);
12523 insert_triple(state, ins, in);
12527 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
12529 struct triple_set *entry, *next;
12530 struct triple *out, *label;
12531 struct block *block;
12533 while(label->op != OP_LABEL) {
12534 label = label->prev;
12536 block = label->u.block;
12537 out = triple(state, OP_COPY, ins->type, ins, 0);
12538 out->filename = ins->filename;
12539 out->line = ins->line;
12540 out->col = ins->col;
12541 out->u.block = block;
12542 out->id = MK_REG_ID(REG_UNSET,
12543 arch_type_to_regcm(state, ins->type));
12544 use_triple(ins, out);
12545 insert_triple(state, ins->next, out);
12546 if (block->last == ins) {
12549 /* Get the users of ins to use out instead */
12550 for(entry = ins->use; entry; entry = next) {
12551 next = entry->next;
12552 if (entry->member == out) {
12555 replace_rhs_use(state, ins, out, entry->member);
12560 static void fixup_branches(struct compile_state *state,
12561 struct triple *cmp, struct triple *use, int jmp_op)
12563 struct triple_set *entry, *next;
12564 for(entry = use->use; entry; entry = next) {
12565 next = entry->next;
12566 if (entry->member->op == OP_COPY) {
12567 fixup_branches(state, cmp, entry->member, jmp_op);
12569 else if (entry->member->op == OP_BRANCH) {
12570 struct triple *branch, *test;
12571 struct triple *left, *right;
12573 left = RHS(cmp, 0);
12574 if (TRIPLE_RHS(cmp->sizes) > 1) {
12575 right = RHS(cmp, 1);
12577 branch = entry->member;
12578 test = pre_triple(state, branch,
12579 cmp->op, cmp->type, left, right);
12580 test->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12581 unuse_triple(RHS(branch, 0), branch);
12582 RHS(branch, 0) = test;
12583 branch->op = jmp_op;
12584 use_triple(RHS(branch, 0), branch);
12589 static void bool_cmp(struct compile_state *state,
12590 struct triple *ins, int cmp_op, int jmp_op, int set_op)
12592 struct block *block;
12593 struct triple_set *entry, *next;
12594 struct triple *set, *tmp1, *tmp2;
12596 #warning "WISHLIST implement an expression simplifier to reduce the use of set?"
12598 block = ins->u.block;
12600 /* Put a barrier up before the cmp which preceeds the
12601 * copy instruction. If a set actually occurs this gives
12602 * us a chance to move variables in registers out of the way.
12605 /* Modify the comparison operator */
12607 ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12608 if (cmp_op == OP_CMP) {
12609 get_imm32(ins, &RHS(ins, 1));
12611 /* Generate the instruction sequence that will transform the
12612 * result of the comparison into a logical value.
12614 tmp1 = triple(state, set_op, ins->type, ins, 0);
12615 tmp1->filename = ins->filename;
12616 tmp1->line = ins->line;
12617 tmp1->col = ins->col;
12618 tmp1->u.block = block;
12619 tmp1->id = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12620 use_triple(ins, tmp1);
12621 insert_triple(state, ins->next, tmp1);
12623 tmp2 = triple(state, OP_COPY, ins->type, tmp1, 0);
12624 tmp2->filename = ins->filename;
12625 tmp2->line = ins->line;
12626 tmp2->col = ins->col;
12627 tmp2->u.block = block;
12628 tmp2->id = MK_REG_ID(REG_UNSET,
12629 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR16 | REGCM_GPR16_8 | REGCM_GPR8);
12630 use_triple(tmp1, tmp2);
12631 insert_triple(state, tmp1->next, tmp2);
12633 if (block->last == ins) {
12634 block->last = tmp2;
12638 for(entry = ins->use; entry; entry = next) {
12639 next = entry->next;
12640 if (entry->member == tmp1) {
12643 replace_rhs_use(state, ins, set, entry->member);
12645 fixup_branches(state, ins, set, jmp_op);
12648 static void verify_lhs(struct compile_state *state, struct triple *ins)
12650 struct triple *next;
12652 lhs = TRIPLE_LHS(ins->sizes);
12653 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
12654 if (next != LHS(ins, i)) {
12655 internal_error(state, ins, "malformed lhs on %s",
12661 static void transform_to_arch_instructions(struct compile_state *state)
12663 /* Transform from generic 3 address instructions
12664 * to archtecture specific instructions.
12665 * And apply architecture specific constrains to instructions.
12666 * Copies are inserted to preserve the register flexibility
12667 * of 3 address instructions.
12669 struct triple *ins, *first, *next;
12670 struct triple *in, *in2;
12671 first = RHS(state->main_function, 0);
12675 ins->id = MK_REG_ID(REG_UNSET, arch_type_to_regcm(state, ins->type));
12680 post_copy(state, ins);
12688 /* instructions that can be used as is */
12696 switch(ins->type->type & TYPE_MASK) {
12697 case TYPE_CHAR: case TYPE_UCHAR:
12700 case TYPE_SHORT: case TYPE_USHORT:
12701 mask = REGCM_GPR16;
12703 case TYPE_INT: case TYPE_UINT:
12704 case TYPE_LONG: case TYPE_ULONG:
12706 mask = REGCM_GPR32;
12709 internal_error(state, ins, "unknown type in store");
12713 in = pre_copy(state, ins, &RHS(ins, 0), REG_UNSET, mask);
12717 switch(ins->type->type & TYPE_MASK) {
12718 case TYPE_CHAR: case TYPE_UCHAR:
12719 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12723 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR16);
12730 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32);
12733 internal_error(state, ins, "unknown type in load");
12742 get_imm32(ins, &RHS(ins, 1));
12743 in = pre_copy(state, ins, &RHS(ins, 0),
12744 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12750 get_imm8(ins, &RHS(ins, 1));
12751 in = pre_copy(state, ins, &RHS(ins, 0),
12752 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12754 if (!is_const(RHS(ins, 1))) {
12755 in2 = pre_copy(state, ins, &RHS(ins, 1),
12756 REG_CL, REGCM_GPR8);
12761 in = pre_copy(state, ins, &RHS(ins, 0),
12762 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12766 get_imm32(ins, &RHS(ins, 1));
12767 in = pre_copy(state, ins, &RHS(ins, 0),
12768 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12770 if (!is_const(RHS(ins, 1))) {
12771 in2 = pre_copy(state, ins, &RHS(ins, 1),
12772 REG_UNSET, REGCM_GPR32);
12776 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
12779 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12782 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
12785 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
12788 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
12791 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
12794 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
12797 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
12800 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
12803 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
12806 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12809 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
12812 if (TRIPLE_RHS(ins->sizes) > 0) {
12813 internal_error(state, ins, "bad branch test");
12821 get_imm8(ins, &RHS(ins, 0));
12823 case OP_INB: ins->id = MK_REG_ID(REG_AL, REGCM_GPR8); break;
12824 case OP_INW: ins->id = MK_REG_ID(REG_AX, REGCM_GPR16); break;
12825 case OP_INL: ins->id = MK_REG_ID(REG_EAX, REGCM_GPR32); break;
12827 if (!is_const(RHS(ins, 0))) {
12828 in = pre_copy(state, ins, &RHS(ins, 0),
12829 REG_DX, REGCM_GPR16);
12836 unsigned reg, mask;
12837 get_imm8(ins, &RHS(ins, 1));
12839 case OP_OUTB: reg = REG_AL; mask = REGCM_GPR8; break;
12840 case OP_OUTW: reg = REG_AX; mask = REGCM_GPR16; break;
12841 case OP_OUTL: reg = REG_EAX; mask = REGCM_GPR32; break;
12842 default: reg = REG_UNSET; mask = 0; break;
12844 in = pre_copy(state, ins, &RHS(ins, 0), reg, mask);
12845 if (!is_const(RHS(ins, 1))) {
12846 in2 = pre_copy(state, ins, &RHS(ins, 1),
12847 REG_DX, REGCM_GPR16);
12853 in = pre_copy(state, ins, &RHS(ins, 0),
12854 REG_UNSET, REGCM_GPR32);
12855 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32 | REGCM_GPR32_8);
12858 in = pre_copy(state, ins, &RHS(ins, 0),
12859 REG_ECX, REGCM_GPR32);
12860 verify_lhs(state, ins);
12861 LHS(ins,0)->id = MK_REG_ID(REG_EAX, REGCM_GPR32);
12862 LHS(ins,1)->id = MK_REG_ID(REG_EDX, REGCM_GPR32);
12863 next = ins->next->next->next;
12866 pre_copy(state, ins, &RHS(ins, 0), REG_ECX, REGCM_GPR32);
12867 pre_copy(state, ins, &RHS(ins, 1), REG_EAX, REGCM_GPR32);
12868 pre_copy(state, ins, &RHS(ins, 2), REG_EDX, REGCM_GPR32);
12872 /* Already transformed instructions */
12875 ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12877 case OP_JMP_EQ: case OP_JMP_NOTEQ:
12878 case OP_JMP_SLESS: case OP_JMP_ULESS:
12879 case OP_JMP_SMORE: case OP_JMP_UMORE:
12880 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
12881 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
12882 case OP_SET_EQ: case OP_SET_NOTEQ:
12883 case OP_SET_SLESS: case OP_SET_ULESS:
12884 case OP_SET_SMORE: case OP_SET_UMORE:
12885 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
12886 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
12888 /* Unhandled instructions */
12891 internal_error(state, ins, "unhandled ins: %d %s\n",
12892 ins->op, tops(ins->op));
12896 } while(ins != first);
12899 static void generate_local_labels(struct compile_state *state)
12901 struct triple *first, *label;
12904 first = RHS(state->main_function, 0);
12907 if ((label->op == OP_LABEL) ||
12908 (label->op == OP_SDECL)) {
12910 label->u.cval = ++label_counter;
12916 label = label->next;
12917 } while(label != first);
12920 static int check_reg(struct compile_state *state,
12921 struct triple *triple, int classes)
12925 reg = ID_REG(triple->id);
12926 if (reg == REG_UNSET) {
12927 internal_error(state, triple, "register not set");
12929 if (ID_REG_CLASSES(triple->id)) {
12930 internal_error(state, triple, "class specifier present");
12932 mask = arch_reg_regcm(state, reg);
12933 if (!(classes & mask)) {
12934 internal_error(state, triple, "reg %d in wrong class",
12940 static const char *arch_reg_str(int reg)
12942 static const char *regs[] = {
12945 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
12946 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
12947 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
12949 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
12950 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
12951 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
12953 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
12959 static const char *reg(struct compile_state *state, struct triple *triple,
12963 reg = check_reg(state, triple, classes);
12964 return arch_reg_str(reg);
12967 const char *type_suffix(struct compile_state *state, struct type *type)
12969 const char *suffix;
12970 switch(size_of(state, type)) {
12971 case 1: suffix = "b"; break;
12972 case 2: suffix = "w"; break;
12973 case 4: suffix = "l"; break;
12975 internal_error(state, 0, "unknown suffix");
12982 static void print_binary_op(struct compile_state *state,
12983 const char *op, struct triple *ins, FILE *fp)
12986 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
12987 if (RHS(ins, 0)->id != ins->id) {
12988 internal_error(state, ins, "invalid register assignment");
12990 if (is_const(RHS(ins, 1))) {
12991 fprintf(fp, "\t%s $%lu, %s\n",
12993 RHS(ins, 1)->u.cval,
12994 reg(state, RHS(ins, 0), mask));
12998 unsigned lmask, rmask;
13000 lreg = check_reg(state, RHS(ins, 0), mask);
13001 rreg = check_reg(state, RHS(ins, 1), mask);
13002 lmask = arch_reg_regcm(state, lreg);
13003 rmask = arch_reg_regcm(state, rreg);
13004 mask = lmask & rmask;
13005 fprintf(fp, "\t%s %s, %s\n",
13007 reg(state, RHS(ins, 1), mask),
13008 reg(state, RHS(ins, 0), mask));
13011 static void print_unary_op(struct compile_state *state,
13012 const char *op, struct triple *ins, FILE *fp)
13015 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13016 fprintf(fp, "\t%s %s\n",
13018 reg(state, RHS(ins, 0), mask));
13021 static void print_op_shift(struct compile_state *state,
13022 const char *op, struct triple *ins, FILE *fp)
13025 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13026 if (RHS(ins, 0)->id != ins->id) {
13027 internal_error(state, ins, "invalid register assignment");
13029 if (is_const(RHS(ins, 1))) {
13030 fprintf(fp, "\t%s $%lu, %s\n",
13032 RHS(ins, 1)->u.cval,
13033 reg(state, RHS(ins, 0), mask));
13037 fprintf(fp, "\t%s %s, %s\n",
13039 reg(state, RHS(ins, 1), REGCM_GPR8),
13040 reg(state, RHS(ins, 0), mask));
13044 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
13051 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
13052 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
13053 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
13055 internal_error(state, ins, "not an in operation");
13059 dreg = check_reg(state, ins, mask);
13060 if (!reg_is_reg(state, dreg, REG_EAX)) {
13061 internal_error(state, ins, "dst != %%eax");
13063 if (is_const(RHS(ins, 0))) {
13064 fprintf(fp, "\t%s $%lu, %s\n",
13065 op, RHS(ins, 0)->u.cval,
13066 reg(state, ins, mask));
13070 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
13071 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13072 internal_error(state, ins, "src != %%dx");
13074 fprintf(fp, "\t%s %s, %s\n",
13076 reg(state, RHS(ins, 0), REGCM_GPR16),
13077 reg(state, ins, mask));
13081 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
13088 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
13089 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
13090 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
13092 internal_error(state, ins, "not an out operation");
13096 lreg = check_reg(state, RHS(ins, 0), mask);
13097 if (!reg_is_reg(state, lreg, REG_EAX)) {
13098 internal_error(state, ins, "src != %%eax");
13100 if (is_const(RHS(ins, 1))) {
13101 fprintf(fp, "\t%s %s, $%lu\n",
13102 op, reg(state, RHS(ins, 0), mask),
13103 RHS(ins, 1)->u.cval);
13107 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
13108 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13109 internal_error(state, ins, "dst != %%dx");
13111 fprintf(fp, "\t%s %s, %s\n",
13113 reg(state, RHS(ins, 0), mask),
13114 reg(state, RHS(ins, 1), REGCM_GPR16));
13118 static void print_op_move(struct compile_state *state,
13119 struct triple *ins, FILE *fp)
13121 /* op_move is complex because there are many types
13122 * of registers we can move between.
13124 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
13125 struct triple *dst, *src;
13126 if (ins->op == OP_COPY) {
13130 else if (ins->op == OP_WRITE) {
13135 internal_error(state, ins, "unknown move operation");
13138 if (!is_const(src)) {
13139 int src_reg, dst_reg;
13140 int src_regcm, dst_regcm;
13141 src_reg = ID_REG(src->id);
13142 dst_reg = ID_REG(dst->id);
13143 src_regcm = arch_reg_regcm(state, src_reg);
13144 dst_regcm = arch_reg_regcm(state, dst_reg);
13145 /* If the class is the same just move the register */
13146 if (src_regcm & dst_regcm &
13147 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
13148 if ((src_reg != dst_reg) || !omit_copy) {
13149 fprintf(fp, "\tmov %s, %s\n",
13150 reg(state, src, src_regcm),
13151 reg(state, dst, dst_regcm));
13154 /* Move 32bit to 16bit */
13155 else if ((src_regcm & REGCM_GPR32) &&
13156 (dst_regcm & REGCM_GPR16)) {
13157 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
13158 if ((src_reg != dst_reg) || !omit_copy) {
13159 fprintf(fp, "\tmovw %s, %s\n",
13160 arch_reg_str(src_reg),
13161 arch_reg_str(dst_reg));
13164 /* Move 32bit to 8bit */
13165 else if ((src_regcm & REGCM_GPR32_8) &&
13166 (dst_regcm & REGCM_GPR8))
13168 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
13169 if ((src_reg != dst_reg) || !omit_copy) {
13170 fprintf(fp, "\tmovb %s, %s\n",
13171 arch_reg_str(src_reg),
13172 arch_reg_str(dst_reg));
13175 /* Move 16bit to 8bit */
13176 else if ((src_regcm & REGCM_GPR16_8) &&
13177 (dst_regcm & REGCM_GPR8))
13179 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
13180 if ((src_reg != dst_reg) || !omit_copy) {
13181 fprintf(fp, "\tmovb %s, %s\n",
13182 arch_reg_str(src_reg),
13183 arch_reg_str(dst_reg));
13186 /* Move 8/16bit to 16/32bit */
13187 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
13188 (dst_regcm & (REGC_GPR16 | REGCM_GPR32))) {
13190 op = is_signed(src->type)? "movsx": "movzx";
13191 fprintf(fp, "\t%s %s, %s\n",
13193 reg(state, src, src_regcm),
13194 reg(state, dst, dst_regcm));
13196 /* Move between sse registers */
13197 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
13198 if ((src_reg != dst_reg) || !omit_copy) {
13199 fprintf(fp, "\tmovdqa %s %s\n",
13200 reg(state, src, src_regcm),
13201 reg(state, dst, dst_regcm));
13204 /* Move between mmx registers or mmx & sse registers */
13205 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
13206 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
13207 if ((src_reg != dst_reg) || !omit_copy) {
13208 fprintf(fp, "\tmovq %s %s\n",
13209 reg(state, src, src_regcm),
13210 reg(state, dst, dst_regcm));
13213 /* Move between 32bit gprs & mmx/sse registers */
13214 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
13215 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
13216 fprintf(fp, "\tmovd %s, %s\n",
13217 reg(state, src, src_regcm),
13218 reg(state, dst, dst_regcm));
13221 internal_error(state, ins, "unknown copy type");
13224 else switch(src->op) {
13228 value = (long_t)(src->u.cval);
13229 fprintf(fp, "\tmov $%ld, %s\n",
13231 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
13235 fprintf(fp, "\tmov $L%lu+%lu, %s\n",
13236 RHS(src, 0)->u.cval,
13238 reg(state, dst, REGCM_GPR32));
13241 internal_error(state, ins, "uknown copy operation");
13245 static void print_op_load(struct compile_state *state,
13246 struct triple *ins, FILE *fp)
13248 struct triple *dst, *src;
13251 if (is_const(src) || is_const(dst)) {
13252 internal_error(state, ins, "unknown load operation");
13254 fprintf(fp, "\tmov (%s), %s\n",
13255 reg(state, src, REGCM_GPR32),
13256 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
13260 static void print_op_store(struct compile_state *state,
13261 struct triple *ins, FILE *fp)
13263 struct triple *dst, *src;
13266 if (is_const(src) && (src->op == OP_INTCONST)) {
13268 value = (long_t)(src->u.cval);
13269 fprintf(fp, "\tmov%s $%ld, (%s)\n",
13270 type_suffix(state, src->type),
13272 reg(state, dst, REGCM_GPR32));
13274 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
13275 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
13276 type_suffix(state, src->type),
13277 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
13281 if (is_const(src) || is_const(dst)) {
13282 internal_error(state, ins, "unknown store operation");
13284 fprintf(fp, "\tmov%s %s, (%s)\n",
13285 type_suffix(state, src->type),
13286 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
13287 reg(state, dst, REGCM_GPR32));
13293 static void print_op_smul(struct compile_state *state,
13294 struct triple *ins, FILE *fp)
13296 if (!is_const(RHS(ins, 1))) {
13297 fprintf(fp, "\timul %s, %s\n",
13298 reg(state, RHS(ins, 1), REGCM_GPR32),
13299 reg(state, RHS(ins, 0), REGCM_GPR32));
13302 fprintf(fp, "\timul $%ld, %s\n",
13303 RHS(ins, 1)->u.cval,
13304 reg(state, RHS(ins, 0), REGCM_GPR32));
13308 static void print_op_cmp(struct compile_state *state,
13309 struct triple *ins, FILE *fp)
13313 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13314 dreg = check_reg(state, ins, REGCM_FLAGS);
13315 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
13316 internal_error(state, ins, "bad dest register for cmp");
13318 if (is_const(RHS(ins, 1))) {
13319 fprintf(fp, "\tcmp $%lu, %s\n",
13320 RHS(ins, 1)->u.cval,
13321 reg(state, RHS(ins, 0), mask));
13324 unsigned lmask, rmask;
13326 lreg = check_reg(state, RHS(ins, 0), mask);
13327 rreg = check_reg(state, RHS(ins, 1), mask);
13328 lmask = arch_reg_regcm(state, lreg);
13329 rmask = arch_reg_regcm(state, rreg);
13330 mask = lmask & rmask;
13331 fprintf(fp, "\tcmp %s, %s\n",
13332 reg(state, RHS(ins, 1), mask),
13333 reg(state, RHS(ins, 0), mask));
13337 static void print_op_test(struct compile_state *state,
13338 struct triple *ins, FILE *fp)
13341 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13342 fprintf(fp, "\ttest %s, %s\n",
13343 reg(state, RHS(ins, 0), mask),
13344 reg(state, RHS(ins, 0), mask));
13347 static void print_op_branch(struct compile_state *state,
13348 struct triple *branch, FILE *fp)
13350 const char *bop = "j";
13351 if (branch->op == OP_JMP) {
13352 if (TRIPLE_RHS(branch->sizes) != 0) {
13353 internal_error(state, branch, "jmp with condition?");
13358 if (TRIPLE_RHS(branch->sizes) != 1) {
13359 internal_error(state, branch, "jmpcc without condition?");
13361 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
13362 if ((RHS(branch, 0)->op != OP_CMP) &&
13363 (RHS(branch, 0)->op != OP_TEST)) {
13364 internal_error(state, branch, "bad branch test");
13366 #warning "FIXME I have observed instructions between the test and branch instructions"
13367 if (RHS(branch, 0)->next != branch) {
13368 internal_error(state, branch, "branch does not follow test");
13370 switch(branch->op) {
13371 case OP_JMP_EQ: bop = "jz"; break;
13372 case OP_JMP_NOTEQ: bop = "jnz"; break;
13373 case OP_JMP_SLESS: bop = "jl"; break;
13374 case OP_JMP_ULESS: bop = "jb"; break;
13375 case OP_JMP_SMORE: bop = "jg"; break;
13376 case OP_JMP_UMORE: bop = "ja"; break;
13377 case OP_JMP_SLESSEQ: bop = "jle"; break;
13378 case OP_JMP_ULESSEQ: bop = "jbe"; break;
13379 case OP_JMP_SMOREEQ: bop = "jge"; break;
13380 case OP_JMP_UMOREEQ: bop = "jae"; break;
13382 internal_error(state, branch, "Invalid branch op");
13387 fprintf(fp, "\t%s L%lu\n",
13388 bop, TARG(branch, 0)->u.cval);
13391 static void print_op_set(struct compile_state *state,
13392 struct triple *set, FILE *fp)
13394 const char *sop = "set";
13395 if (TRIPLE_RHS(set->sizes) != 1) {
13396 internal_error(state, set, "setcc without condition?");
13398 check_reg(state, RHS(set, 0), REGCM_FLAGS);
13399 if ((RHS(set, 0)->op != OP_CMP) &&
13400 (RHS(set, 0)->op != OP_TEST)) {
13401 internal_error(state, set, "bad set test");
13403 if (RHS(set, 0)->next != set) {
13404 internal_error(state, set, "set does not follow test");
13407 case OP_SET_EQ: sop = "setz"; break;
13408 case OP_SET_NOTEQ: sop = "setnz"; break;
13409 case OP_SET_SLESS: sop = "setl"; break;
13410 case OP_SET_ULESS: sop = "setb"; break;
13411 case OP_SET_SMORE: sop = "setg"; break;
13412 case OP_SET_UMORE: sop = "seta"; break;
13413 case OP_SET_SLESSEQ: sop = "setle"; break;
13414 case OP_SET_ULESSEQ: sop = "setbe"; break;
13415 case OP_SET_SMOREEQ: sop = "setge"; break;
13416 case OP_SET_UMOREEQ: sop = "setae"; break;
13418 internal_error(state, set, "Invalid set op");
13421 fprintf(fp, "\t%s %s\n",
13422 sop, reg(state, set, REGCM_GPR8));
13425 static void print_op_bit_scan(struct compile_state *state,
13426 struct triple *ins, FILE *fp)
13430 case OP_BSF: op = "bsf"; break;
13431 case OP_BSR: op = "bsr"; break;
13433 internal_error(state, ins, "unknown bit scan");
13443 reg(state, RHS(ins, 0), REGCM_GPR32),
13444 reg(state, ins, REGCM_GPR32),
13445 reg(state, ins, REGCM_GPR32));
13448 static void print_const(struct compile_state *state,
13449 struct triple *ins, FILE *fp)
13453 switch(ins->type->type & TYPE_MASK) {
13456 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
13460 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
13466 fprintf(fp, ".int %lu\n", ins->u.cval);
13469 internal_error(state, ins, "Unknown constant type");
13474 unsigned char *blob;
13476 size = size_of(state, ins->type);
13477 blob = ins->u.blob;
13478 for(i = 0; i < size; i++) {
13479 fprintf(fp, ".byte 0x%02x\n",
13486 fprintf(fp, ".int $L%lu+%lu",
13492 internal_error(state, ins, "Unknown constant type");
13497 static void print_sdecl(struct compile_state *state,
13498 struct triple *ins, FILE *fp)
13500 fprintf(fp, ".section \".rom.data\"\n");
13501 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
13502 fprintf(fp, "L%lu:\n", ins->u.cval);
13503 print_const(state, MISC(ins, 0), fp);
13504 fprintf(fp, ".section \".rom.text\"\n");
13508 static void print_instruction(struct compile_state *state,
13509 struct triple *ins, FILE *fp)
13511 /* Assumption: after I have exted the register allocator
13512 * everything is in a valid register.
13515 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
13516 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
13517 case OP_AND: print_binary_op(state, "and", ins, fp); break;
13518 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
13519 case OP_OR: print_binary_op(state, "or", ins, fp); break;
13520 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
13521 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
13522 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
13523 case OP_POS: break;
13524 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
13525 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
13528 /* Don't generate anything here for constants */
13530 /* Don't generate anything for variable declarations. */
13533 print_sdecl(state, ins, fp);
13537 print_op_move(state, ins, fp);
13540 print_op_load(state, ins, fp);
13543 print_op_store(state, ins, fp);
13546 print_op_smul(state, ins, fp);
13548 case OP_CMP: print_op_cmp(state, ins, fp); break;
13549 case OP_TEST: print_op_test(state, ins, fp); break;
13551 case OP_JMP_EQ: case OP_JMP_NOTEQ:
13552 case OP_JMP_SLESS: case OP_JMP_ULESS:
13553 case OP_JMP_SMORE: case OP_JMP_UMORE:
13554 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
13555 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
13556 print_op_branch(state, ins, fp);
13558 case OP_SET_EQ: case OP_SET_NOTEQ:
13559 case OP_SET_SLESS: case OP_SET_ULESS:
13560 case OP_SET_SMORE: case OP_SET_UMORE:
13561 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
13562 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
13563 print_op_set(state, ins, fp);
13565 case OP_INB: case OP_INW: case OP_INL:
13566 print_op_in(state, ins, fp);
13568 case OP_OUTB: case OP_OUTW: case OP_OUTL:
13569 print_op_out(state, ins, fp);
13573 print_op_bit_scan(state, ins, fp);
13576 verify_lhs(state, ins);
13577 fprintf(fp, "\trdmsr\n");
13580 fprintf(fp, "\twrmsr\n");
13583 fprintf(fp, "\thlt\n");
13589 fprintf(fp, "L%lu:\n", ins->u.cval);
13591 /* Ignore OP_PIECE */
13594 /* Operations I am not yet certain how to handle */
13596 case OP_SDIV: case OP_UDIV:
13597 case OP_SMOD: case OP_UMOD:
13598 /* Operations that should never get here */
13599 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
13600 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
13601 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
13603 internal_error(state, ins, "unknown op: %d %s",
13604 ins->op, tops(ins->op));
13609 static void print_instructions(struct compile_state *state)
13611 struct triple *first, *ins;
13612 int print_location;
13615 const char *last_filename;
13617 print_location = 1;
13622 fprintf(fp, ".section \".rom.text\"\n");
13623 first = RHS(state->main_function, 0);
13626 if (print_location &&
13627 ((last_filename != ins->filename) ||
13628 (last_line != ins->line) ||
13629 (last_col != ins->col))) {
13630 fprintf(fp, "\t/* %s:%d */\n",
13631 ins->filename, ins->line);
13632 last_filename = ins->filename;
13633 last_line = ins->line;
13634 last_col = ins->col;
13637 print_instruction(state, ins, fp);
13639 } while(ins != first);
13642 static void generate_code(struct compile_state *state)
13644 generate_local_labels(state);
13645 print_instructions(state);
13649 static void print_tokens(struct compile_state *state)
13652 tk = &state->token[0];
13657 next_token(state, 0);
13659 loc(stdout, state, 0);
13660 printf("%s <- `%s'\n",
13662 tk->ident ? tk->ident->name :
13663 tk->str_len ? tk->val.str : "");
13665 } while(tk->tok != TOK_EOF);
13668 static void compile(char *filename, int debug, int opt)
13671 struct compile_state state;
13672 memset(&state, 0, sizeof(state));
13674 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
13675 memset(&state.token[i], 0, sizeof(state.token[i]));
13676 state.token[i].tok = -1;
13678 /* Remember the debug settings */
13679 state.debug = debug;
13680 state.optimize = opt;
13681 /* Prep the preprocessor */
13682 state.if_depth = 0;
13683 state.if_value = 0;
13684 /* register the C keywords */
13685 register_keywords(&state);
13686 /* register the keywords the macro preprocessor knows */
13687 register_macro_keywords(&state);
13688 /* Memorize where some special keywords are. */
13689 state.i_continue = lookup(&state, "continue", 8);
13690 state.i_break = lookup(&state, "break", 5);
13691 /* Enter the globl definition scope */
13692 start_scope(&state);
13693 register_builtins(&state);
13694 compile_file(&state, filename, 1);
13696 print_tokens(&state);
13699 /* Exit the global definition scope */
13702 /* Now that basic compilation has happened
13703 * optimize the intermediate code
13706 generate_code(&state);
13708 fprintf(stderr, "done\n");
13712 static void version(void)
13714 printf("romcc " VERSION " released " RELEASE_DATE "\n");
13717 static void usage(void)
13721 "Usage: romcc <source>.c\n"
13722 "Compile a C source file without using ram\n"
13726 static void arg_error(char *fmt, ...)
13729 va_start(args, fmt);
13730 vfprintf(stderr, fmt, args);
13736 int main(int argc, char **argv)
13745 while((argc > 1) && (argc != last_argc)) {
13747 if (strncmp(argv[1], "--debug=", 8) == 0) {
13748 debug = atoi(argv[1] + 8);
13752 else if ((strcmp(argv[1],"-O") == 0) ||
13753 (strcmp(argv[1], "-O1") == 0)) {
13758 else if (strcmp(argv[1],"-O2") == 0) {
13765 arg_error("Wrong argument count %d\n", argc);
13767 filename = argv[1];
13768 compile(filename, debug, optimize);