blob: f138195432ebb3ee5f72d17da32b1eb469cf28f7 [file] [log] [blame]
Eric Biedermanb138ac82003-04-22 18:44:01 +00001#include <stdarg.h>
2#include <errno.h>
3#include <stdint.h>
4#include <stdlib.h>
5#include <stdio.h>
6#include <sys/types.h>
7#include <sys/stat.h>
8#include <fcntl.h>
9#include <unistd.h>
10#include <stdio.h>
11#include <string.h>
12#include <ctype.h>
13#include <limits.h>
14
15#define DEBUG_ERROR_MESSAGES 0
16#define DEBUG_COLOR_GRAPH 0
17#define DEBUG_SCC 0
18#define X86_4_8BIT_GPRS 1
19
20#warning "FIXME static constant variables"
21#warning "FIXME enable pointers"
22#warning "FIXME enable string constants"
23
24/* Control flow graph of a loop without goto.
25 *
26 * AAA
27 * +---/
28 * /
29 * / +--->CCC
30 * | | / \
31 * | | DDD EEE break;
32 * | | \ \
33 * | | FFF \
34 * \| / \ \
35 * |\ GGG HHH | continue;
36 * | \ \ | |
37 * | \ III | /
38 * | \ | / /
39 * | vvv /
40 * +----BBB /
41 * | /
42 * vv
43 * JJJ
44 *
45 *
46 * AAA
47 * +-----+ | +----+
48 * | \ | / |
49 * | BBB +-+ |
50 * | / \ / | |
51 * | CCC JJJ / /
52 * | / \ / /
53 * | DDD EEE / /
54 * | | +-/ /
55 * | FFF /
56 * | / \ /
57 * | GGG HHH /
58 * | | +-/
59 * | III
60 * +--+
61 *
62 *
63 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
64 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
65 *
66 *
67 * [] == DFlocal(X) U DF(X)
68 * () == DFup(X)
69 *
70 * Dominator graph of the same nodes.
71 *
72 * AAA AAA: [ ] ()
73 * / \
74 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
75 * |
76 * CCC CCC: [ ] ( BBB, JJJ )
77 * / \
78 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
79 * |
80 * FFF FFF: [ ] ( BBB )
81 * / \
82 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
83 * |
84 * III III: [ BBB ] ()
85 *
86 *
87 * BBB and JJJ are definitely the dominance frontier.
88 * Where do I place phi functions and how do I make that decision.
89 *
90 */
91static void die(char *fmt, ...)
92{
93 va_list args;
94
95 va_start(args, fmt);
96 vfprintf(stderr, fmt, args);
97 va_end(args);
98 fflush(stdout);
99 fflush(stderr);
100 exit(1);
101}
102
103#define MALLOC_STRONG_DEBUG
104static void *xmalloc(size_t size, const char *name)
105{
106 void *buf;
107 buf = malloc(size);
108 if (!buf) {
109 die("Cannot malloc %ld bytes to hold %s: %s\n",
110 size + 0UL, name, strerror(errno));
111 }
112 return buf;
113}
114
115static void *xcmalloc(size_t size, const char *name)
116{
117 void *buf;
118 buf = xmalloc(size, name);
119 memset(buf, 0, size);
120 return buf;
121}
122
123static void xfree(const void *ptr)
124{
125 free((void *)ptr);
126}
127
128static char *xstrdup(const char *str)
129{
130 char *new;
131 int len;
132 len = strlen(str);
133 new = xmalloc(len + 1, "xstrdup string");
134 memcpy(new, str, len);
135 new[len] = '\0';
136 return new;
137}
138
139static void xchdir(const char *path)
140{
141 if (chdir(path) != 0) {
142 die("chdir to %s failed: %s\n",
143 path, strerror(errno));
144 }
145}
146
147static int exists(const char *dirname, const char *filename)
148{
149 int does_exist = 1;
150 xchdir(dirname);
151 if (access(filename, O_RDONLY) < 0) {
152 if ((errno != EACCES) && (errno != EROFS)) {
153 does_exist = 0;
154 }
155 }
156 return does_exist;
157}
158
159
160static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
161{
162 int fd;
163 char *buf;
164 off_t size, progress;
165 ssize_t result;
166 struct stat stats;
167
168 if (!filename) {
169 *r_size = 0;
170 return 0;
171 }
172 xchdir(dirname);
173 fd = open(filename, O_RDONLY);
174 if (fd < 0) {
175 die("Cannot open '%s' : %s\n",
176 filename, strerror(errno));
177 }
178 result = fstat(fd, &stats);
179 if (result < 0) {
180 die("Cannot stat: %s: %s\n",
181 filename, strerror(errno));
182 }
183 size = stats.st_size;
184 *r_size = size +1;
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 */
188 progress = 0;
189 while(progress < size) {
190 result = read(fd, buf + progress, size - progress);
191 if (result < 0) {
192 if ((errno == EINTR) || (errno == EAGAIN))
193 continue;
194 die("read on %s of %ld bytes failed: %s\n",
195 filename, (size - progress)+ 0UL, strerror(errno));
196 }
197 progress += result;
198 }
199 result = close(fd);
200 if (result < 0) {
201 die("Close of %s failed: %s\n",
202 filename, strerror(errno));
203 }
204 return buf;
205}
206
207/* Long on the destination platform */
208typedef unsigned long ulong_t;
209typedef long long_t;
210
211struct file_state {
212 struct file_state *prev;
213 const char *basename;
214 char *dirname;
215 char *buf;
216 off_t size;
217 char *pos;
218 int line;
219 char *line_start;
220};
221struct hash_entry;
222struct token {
223 int tok;
224 struct hash_entry *ident;
225 int str_len;
226 union {
227 ulong_t integer;
228 const char *str;
229 } val;
230};
231
232/* I have two classes of types:
233 * Operational types.
234 * Logical types. (The type the C standard says the operation is of)
235 *
236 * The operational types are:
237 * chars
238 * shorts
239 * ints
240 * longs
241 *
242 * floats
243 * doubles
244 * long doubles
245 *
246 * pointer
247 */
248
249
250/* Machine model.
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.
256 */
257
258/* Operations on general purpose registers.
259 */
260
261#define OP_SMUL 0
262#define OP_UMUL 1
263#define OP_SDIV 2
264#define OP_UDIV 3
265#define OP_SMOD 4
266#define OP_UMOD 5
267#define OP_ADD 6
268#define OP_SUB 7
Eric Biederman0babc1c2003-05-09 02:39:00 +0000269#define OP_SL 8
Eric Biedermanb138ac82003-04-22 18:44:01 +0000270#define OP_USR 9
271#define OP_SSR 10
272#define OP_AND 11
273#define OP_XOR 12
274#define OP_OR 13
275#define OP_POS 14 /* Dummy positive operator don't use it */
276#define OP_NEG 15
277#define OP_INVERT 16
278
279#define OP_EQ 20
280#define OP_NOTEQ 21
281#define OP_SLESS 22
282#define OP_ULESS 23
283#define OP_SMORE 24
284#define OP_UMORE 25
285#define OP_SLESSEQ 26
286#define OP_ULESSEQ 27
287#define OP_SMOREEQ 28
288#define OP_UMOREEQ 29
289
290#define OP_LFALSE 30 /* Test if the expression is logically false */
291#define OP_LTRUE 31 /* Test if the expression is logcially true */
292
293#define OP_LOAD 32
294#define OP_STORE 33
295
296#define OP_NOOP 34
297
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
Eric Biederman0babc1c2003-05-09 02:39:00 +0000303/* For OP_BLOBCONST ->type holds the layout and size
Eric Biedermanb138ac82003-04-22 18:44:01 +0000304 * information. u.blob holds a pointer to the raw binary
305 * data for the constant initializer.
306 */
307#define OP_ADDRCONST 52
Eric Biederman0babc1c2003-05-09 02:39:00 +0000308/* 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.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000311 */
312
313#define OP_WRITE 60
314/* OP_WRITE moves one pseudo register to another.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000315 * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
316 * RHS(0) holds the psuedo to move.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000317 */
318
319#define OP_READ 61
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.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000323 * RHS(0) holds points to the triple to read from.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000324 */
325#define OP_COPY 62
Eric Biederman0babc1c2003-05-09 02:39:00 +0000326/* OP_COPY makes a copy of the psedo register or constant in RHS(0).
327 */
328#define OP_PIECE 63
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.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000332 */
333
Eric Biedermanb138ac82003-04-22 18:44:01 +0000334#define OP_DEREF 65
335/* OP_DEREF generates an lvalue from a pointer.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000336 * RHS(0) holds the pointer value.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000337 * OP_DEREF serves as a place holder to indicate all necessary
338 * checks have been done to indicate a value is an lvalue.
339 */
340#define OP_DOT 66
Eric Biederman0babc1c2003-05-09 02:39:00 +0000341/* 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.
344 *
345 * Not seen outside of expressions.
346 */
Eric Biedermanb138ac82003-04-22 18:44:01 +0000347#define OP_VAL 67
348/* OP_VAL returns the value of a subexpression of the current expression.
349 * Useful for operators that have side effects.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000350 * RHS(0) holds the expression.
351 * MISC(0) holds the subexpression of RHS(0) that is the
Eric Biedermanb138ac82003-04-22 18:44:01 +0000352 * value of the expression.
353 *
354 * Not seen outside of expressions.
355 */
356#define OP_LAND 68
Eric Biederman0babc1c2003-05-09 02:39:00 +0000357/* OP_LAND performs a C logical and between RHS(0) and RHS(1).
Eric Biedermanb138ac82003-04-22 18:44:01 +0000358 * Not seen outside of expressions.
359 */
360#define OP_LOR 69
Eric Biederman0babc1c2003-05-09 02:39:00 +0000361/* OP_LOR performs a C logical or between RHS(0) and RHS(1).
Eric Biedermanb138ac82003-04-22 18:44:01 +0000362 * Not seen outside of expressions.
363 */
364#define OP_COND 70
365/* OP_CODE performas a C ? : operation.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000366 * 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.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000369 * Not seen outside of expressions.
370 */
371#define OP_COMMA 71
372/* OP_COMMA performacs a C comma operation.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000373 * That is RHS(0) is evaluated, then RHS(1)
374 * and the value of RHS(1) is returned.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000375 * Not seen outside of expressions.
376 */
377
378#define OP_CALL 72
379/* OP_CALL performs a procedure call.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000380 * MISC(0) holds a pointer to the OP_LIST of a function
381 * RHS(x) holds argument x of a function
382 *
Eric Biedermanb138ac82003-04-22 18:44:01 +0000383 * Currently not seen outside of expressions.
384 */
Eric Biederman0babc1c2003-05-09 02:39:00 +0000385#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.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000390 */
391
392/* statements */
393#define OP_LIST 80
394/* OP_LIST Holds a list of statements, and a result value.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000395 * RHS(0) holds the list of statements.
396 * MISC(0) holds the value of the statements.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000397 */
398
399#define OP_BRANCH 81 /* branch */
400/* For branch instructions
Eric Biederman0babc1c2003-05-09 02:39:00 +0000401 * 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.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000404 * The branch target can only be a decl...
405 */
406
407#define OP_LABEL 83
408/* OP_LABEL is a triple that establishes an target for branches.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000409 * ->use is the list of all branches that use this label.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000410 */
411
412#define OP_ADECL 84
413/* OP_DECL is a triple that establishes an lvalue for assignments.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000414 * ->use is a list of statements that use the variable.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000415 */
416
417#define OP_SDECL 85
418/* OP_VAR is a triple that establishes a variable of static
419 * storage duration.
Eric Biederman0babc1c2003-05-09 02:39:00 +0000420 * ->use is a list of statements that use the variable.
421 * MISC(0) holds the initializer expression.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000422 */
423
424
425#define OP_PHI 86
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.
431 *
Eric Biederman0babc1c2003-05-09 02:39:00 +0000432 * 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
Eric Biedermanb138ac82003-04-22 18:44:01 +0000434 * in which OP_PHI resides. The elements of the array point to point
435 * to the variables OP_PHI is derived from.
436 *
Eric Biederman0babc1c2003-05-09 02:39:00 +0000437 * MISC(0) holds a pointer to the orginal OP_DECL node.
Eric Biedermanb138ac82003-04-22 18:44:01 +0000438 */
439
440/* Architecture specific instructions */
441#define OP_CMP 100
442#define OP_TEST 101
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
453
454#define OP_JMP 112
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
465
466/* Builtin operators that it is just simpler to use the compiler for */
467#define OP_INB 130
468#define OP_INW 131
469#define OP_INL 132
470#define OP_OUTB 133
471#define OP_OUTW 134
472#define OP_OUTL 135
473#define OP_BSF 136
474#define OP_BSR 137
Eric Biedermanb138ac82003-04-22 18:44:01 +0000475#define OP_RDMSR 138
476#define OP_WRMSR 139
Eric Biedermanb138ac82003-04-22 18:44:01 +0000477#define OP_HLT 140
478
Eric Biederman0babc1c2003-05-09 02:39:00 +0000479struct op_info {
480 const char *name;
481 unsigned flags;
482#define PURE 1
483#define IMPURE 2
484#define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
485#define DEF 4
486 unsigned char lhs, rhs, misc, targ;
Eric Biedermanb138ac82003-04-22 18:44:01 +0000487};
488
Eric Biederman0babc1c2003-05-09 02:39:00 +0000489#define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
490 .name = (NAME), \
491 .flags = (FLAGS), \
492 .lhs = (LHS), \
493 .rhs = (RHS), \
494 .misc = (MISC), \
495 .targ = (TARG), \
496 }
497static 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"),
Eric Biedermanb138ac82003-04-22 18:44:01 +0000515
Eric Biederman0babc1c2003-05-09 02:39:00 +0000516[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"),
528
529[OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF, "load"),
530[OP_STORE ] = OP( 1, 1, 0, 0, IMPURE, "store"),
531
532[OP_NOOP ] = OP( 0, 0, 0, 0, PURE, "noop"),
533
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"),
537
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"),
544
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"),
554
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"),
563
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"),
587
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"),
599};
600#undef OP
601#define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
Eric Biedermanb138ac82003-04-22 18:44:01 +0000602
603static const char *tops(int index)
604{
605 static const char unknown[] = "unknown op";
606 if (index < 0) {
607 return unknown;
608 }
609 if (index > OP_MAX) {
610 return unknown;
611 }
Eric Biederman0babc1c2003-05-09 02:39:00 +0000612 return table_ops[index].name;
Eric Biedermanb138ac82003-04-22 18:44:01 +0000613}
614
Eric Biedermanb138ac82003-04-22 18:44:01 +0000615struct triple;
616struct block;
617struct triple_set {
618 struct triple_set *next;
619 struct triple *member;
620};
621
Eric Biederman0babc1c2003-05-09 02:39:00 +0000622#define MAX_LHS 15
623#define MAX_RHS 15
624#define MAX_MISC 15
625#define MAX_TARG 15
626
Eric Biedermanb138ac82003-04-22 18:44:01 +0000627struct triple {
628 struct triple *next, *prev;
629 struct triple_set *use;
630 struct type *type;
Eric Biederman0babc1c2003-05-09 02:39:00 +0000631 short op;
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)])
Eric Biedermanb138ac82003-04-22 18:44:01 +0000655 unsigned id; /* A scratch value and finally the register */
Eric Biederman0babc1c2003-05-09 02:39:00 +0000656#define TRIPLE_FLAG_FLATTENED 1
657 const char *filename;
658 int line;
659 int col;
Eric Biedermanb138ac82003-04-22 18:44:01 +0000660 union {
661 ulong_t cval;
662 struct block *block;
663 void *blob;
Eric Biederman0babc1c2003-05-09 02:39:00 +0000664 struct hash_entry *field;
Eric Biedermanb138ac82003-04-22 18:44:01 +0000665 } u;
Eric Biederman0babc1c2003-05-09 02:39:00 +0000666 struct triple *param[2];
Eric Biedermanb138ac82003-04-22 18:44:01 +0000667};
668
669struct block_set {
670 struct block_set *next;
671 struct block *member;
672};
673struct block {
674 struct block *work_next;
675 struct block *left, *right;
676 struct triple *first, *last;
677 int users;
678 struct block_set *use;
679 struct block_set *idominates;
680 struct block_set *domfrontier;
681 struct block *idom;
682 struct block_set *ipdominates;
683 struct block_set *ipdomfrontier;
684 struct block *ipdom;
685 int vertex;
686
687};
688
689struct symbol {
690 struct symbol *next;
691 struct hash_entry *ident;
692 struct triple *def;
693 struct type *type;
694 int scope_depth;
695};
696
697struct macro {
698 struct hash_entry *ident;
699 char *buf;
700 int buf_len;
701};
702
703struct hash_entry {
704 struct hash_entry *next;
705 const char *name;
706 int name_len;
707 int tok;
708 struct macro *sym_define;
709 struct symbol *sym_label;
710 struct symbol *sym_struct;
711 struct symbol *sym_ident;
712};
713
714#define HASH_TABLE_SIZE 2048
715
716struct compile_state {
717 struct triple *vars;
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;
723 int scope_depth;
724 int if_depth, if_value;
725 int macro_line;
726 struct file_state *macro_file;
727 struct triple *main_function;
728 struct block *first_block, *last_block;
729 int last_vertex;
730 int debug;
731 int optimize;
732};
733
Eric Biederman0babc1c2003-05-09 02:39:00 +0000734/* visibility global/local */
735/* static/auto duration */
736/* typedef, register, inline */
737#define STOR_SHIFT 0
738#define STOR_MASK 0x000f
739/* Visibility */
740#define STOR_GLOBAL 0x0001
741/* Duration */
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
750
751#define QUAL_SHIFT 4
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
757
758#define TYPE_SHIFT 8
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
785/* For TYPE_POINTER:
786 * type->left holds the type pointed to.
787 */
788#define TYPE_FUNCTION 0x1300
789/* For TYPE_FUNCTION:
790 * type->left holds the return type.
791 * type->right holds the...
792 */
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.
797 */
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.
802 */
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.
807 */
808
809#define ELEMENT_COUNT_UNSPECIFIED (~0UL)
810
811struct type {
812 unsigned int type;
813 struct type *left, *right;
814 ulong_t elements;
815 struct hash_entry *field_ident;
816 struct hash_entry *type_ident;
817};
818
Eric Biedermanb138ac82003-04-22 18:44:01 +0000819#define MAX_REGISTERS 75
820#define MAX_REG_EQUIVS 16
821#define MAX_REGC 12
822#define REG_UNSET 0
823
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))
829
830static unsigned alloc_virtual_reg(void)
831{
832 static unsigned virtual_reg = MAX_REGISTERS;
833 virtual_reg += 1;
834 return virtual_reg;
835}
836
837static unsigned arch_reg_regcm(struct compile_state *state, int reg);
838static void arch_reg_equivs(
839 struct compile_state *state, unsigned *equiv, int reg);
840static int arch_select_free_register(
841 struct compile_state *state, char *used, int classes);
842static unsigned arch_regc_size(struct compile_state *state, int class);
843static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
844static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
845static const char *arch_reg_str(int reg);
846
Eric Biederman0babc1c2003-05-09 02:39:00 +0000847#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
Eric Biedermanb138ac82003-04-22 18:44:01 +0000857
858#define GLOBAL_SCOPE_DEPTH 1
859
860static void compile_file(struct compile_state *old_state, char *filename, int local);
861
862static int get_col(struct file_state *file)
863{
864 int col;
865 char *ptr, *end;
866 ptr = file->line_start;
867 end = file->pos;
868 for(col = 0; ptr < end; ptr++) {
869 if (*ptr != '\t') {
870 col++;
871 }
872 else {
873 col = (col & ~7) + 8;
874 }
875 }
876 return col;
877}
878
879static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
880{
881 int col;
882 if (triple) {
883 fprintf(fp, "%s:%d.%d: ",
884 triple->filename, triple->line, triple->col);
885 return;
886 }
887 if (!state->file) {
888 return;
889 }
890 col = get_col(state->file);
891 fprintf(fp, "%s:%d.%d: ",
892 state->file->basename, state->file->line, col);
893}
894
895static void __internal_error(struct compile_state *state, struct triple *ptr,
896 char *fmt, ...)
897{
898 va_list args;
899 va_start(args, fmt);
900 loc(stderr, state, ptr);
901 fprintf(stderr, "Internal compiler error: ");
902 vfprintf(stderr, fmt, args);
903 fprintf(stderr, "\n");
904 va_end(args);
905 abort();
906}
907
908
909static void __internal_warning(struct compile_state *state, struct triple *ptr,
910 char *fmt, ...)
911{
912 va_list args;
913 va_start(args, fmt);
914 loc(stderr, state, ptr);
915 fprintf(stderr, "Internal compiler warning: ");
916 vfprintf(stderr, fmt, args);
917 fprintf(stderr, "\n");
918 va_end(args);
919}
920
921
922
923static void __error(struct compile_state *state, struct triple *ptr,
924 char *fmt, ...)
925{
926 va_list args;
927 va_start(args, fmt);
928 loc(stderr, state, ptr);
929 vfprintf(stderr, fmt, args);
930 va_end(args);
931 fprintf(stderr, "\n");
Eric Biederman0babc1c2003-05-09 02:39:00 +0000932 if (state->debug & DEBUG_ABORT_ON_ERROR) {
933 abort();
934 }
Eric Biedermanb138ac82003-04-22 18:44:01 +0000935 exit(1);
936}
937
938static void __warning(struct compile_state *state, struct triple *ptr,
939 char *fmt, ...)
940{
941 va_list args;
942 va_start(args, fmt);
943 loc(stderr, state, ptr);
944 fprintf(stderr, "warning: ");
945 vfprintf(stderr, fmt, args);
946 fprintf(stderr, "\n");
947 va_end(args);
948}
949
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
955#else
956# define internal_error __internal_error
957# define internal_warning __internal_warning
958# define error __error
959# define warning __warning
960#endif
961#define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
962
963
Eric Biederman0babc1c2003-05-09 02:39:00 +0000964static void valid_op(struct compile_state *state, int op)
Eric Biedermanb138ac82003-04-22 18:44:01 +0000965{
966 char *fmt = "invalid op: %d";
Eric Biederman0babc1c2003-05-09 02:39:00 +0000967 if (op >= OP_MAX) {
968 internal_error(state, 0, fmt, op);
Eric Biedermanb138ac82003-04-22 18:44:01 +0000969 }
Eric Biederman0babc1c2003-05-09 02:39:00 +0000970 if (op < 0) {
971 internal_error(state, 0, fmt, op);
Eric Biedermanb138ac82003-04-22 18:44:01 +0000972 }
973}
974
Eric Biederman0babc1c2003-05-09 02:39:00 +0000975static void valid_ins(struct compile_state *state, struct triple *ptr)
976{
977 valid_op(state, ptr->op);
978}
979
Eric Biedermanb138ac82003-04-22 18:44:01 +0000980static void process_trigraphs(struct compile_state *state)
981{
982 char *src, *dest, *end;
983 struct file_state *file;
984 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] == '?')) {
989 int c = -1;
990 switch(src[2]) {
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;
1000 }
1001 if (c != -1) {
1002 *dest++ = c;
1003 src += 3;
1004 }
1005 else {
1006 *dest++ = *src++;
1007 }
1008 }
1009 else {
1010 *dest++ = *src++;
1011 }
1012 }
1013 while(src != end) {
1014 *dest++ = *src++;
1015 }
1016 file->size = dest - file->buf;
1017}
1018
1019static void splice_lines(struct compile_state *state)
1020{
1021 char *src, *dest, *end;
1022 struct file_state *file;
1023 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')) {
1028 src += 2;
1029 }
1030 else {
1031 *dest++ = *src++;
1032 }
1033 }
1034 while(src != end) {
1035 *dest++ = *src++;
1036 }
1037 file->size = dest - file->buf;
1038}
1039
1040static struct type void_type;
1041static void use_triple(struct triple *used, struct triple *user)
1042{
1043 struct triple_set **ptr, *new;
1044 if (!used)
1045 return;
1046 if (!user)
1047 return;
1048 ptr = &used->use;
1049 while(*ptr) {
1050 if ((*ptr)->member == user) {
1051 return;
1052 }
1053 ptr = &(*ptr)->next;
1054 }
1055 /* Append new to the head of the list,
1056 * copy_func and rename_block_variables
1057 * depends on this.
1058 */
1059 new = xcmalloc(sizeof(*new), "triple_set");
1060 new->member = user;
1061 new->next = used->use;
1062 used->use = new;
1063}
1064
1065static void unuse_triple(struct triple *used, struct triple *unuser)
1066{
1067 struct triple_set *use, **ptr;
1068 ptr = &used->use;
1069 while(*ptr) {
1070 use = *ptr;
1071 if (use->member == unuser) {
1072 *ptr = use->next;
1073 xfree(use);
1074 }
1075 else {
1076 ptr = &use->next;
1077 }
1078 }
1079}
1080
1081static void push_triple(struct triple *used, struct triple *user)
1082{
1083 struct triple_set *new;
1084 if (!used)
1085 return;
1086 if (!user)
1087 return;
1088 /* Append new to the head of the list,
1089 * it's the only sensible behavoir for a stack.
1090 */
1091 new = xcmalloc(sizeof(*new), "triple_set");
1092 new->member = user;
1093 new->next = used->use;
1094 used->use = new;
1095}
1096
1097static void pop_triple(struct triple *used, struct triple *unuser)
1098{
1099 struct triple_set *use, **ptr;
1100 ptr = &used->use;
1101 while(*ptr) {
1102 use = *ptr;
1103 if (use->member == unuser) {
1104 *ptr = use->next;
1105 xfree(use);
1106 /* Only free one occurance from the stack */
1107 return;
1108 }
1109 else {
1110 ptr = &use->next;
1111 }
1112 }
1113}
1114
1115
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.
1119 */
1120static struct triple zero_triple = {
1121 .next = &zero_triple,
1122 .prev = &zero_triple,
1123 .use = 0,
1124 .op = OP_INTCONST,
Eric Biederman0babc1c2003-05-09 02:39:00 +00001125 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
Eric Biedermanb138ac82003-04-22 18:44:01 +00001126 .id = -1, /* An invalid id */
Eric Biedermanb138ac82003-04-22 18:44:01 +00001127 .u = { .cval = 0, },
1128 .filename = __FILE__,
1129 .line = __LINE__,
Eric Biederman0babc1c2003-05-09 02:39:00 +00001130 .col = 0,
1131 .param { [0] = 0, [1] = 0, },
Eric Biedermanb138ac82003-04-22 18:44:01 +00001132};
1133
Eric Biederman0babc1c2003-05-09 02:39:00 +00001134
1135static unsigned short triple_sizes(struct compile_state *state,
1136 int op, struct type *type, int rhs_wanted)
1137{
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;
1144
1145
1146 if (op == OP_CALL) {
1147 struct type *param;
1148 rhs = 0;
1149 param = type->right;
1150 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1151 rhs++;
1152 param = param->right;
1153 }
1154 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1155 rhs++;
1156 }
1157 lhs = 0;
1158 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1159 lhs = type->left->elements;
1160 }
1161 }
1162 else if (op == OP_VAL_VEC) {
1163 rhs = type->elements;
1164 }
1165 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1166 rhs = rhs_wanted;
1167 }
1168 if ((rhs < 0) || (rhs > MAX_RHS)) {
1169 internal_error(state, 0, "bad rhs");
1170 }
1171 if ((lhs < 0) || (lhs > MAX_LHS)) {
1172 internal_error(state, 0, "bad lhs");
1173 }
1174 if ((misc < 0) || (misc > MAX_MISC)) {
1175 internal_error(state, 0, "bad misc");
1176 }
1177 if ((targ < 0) || (targ > MAX_TARG)) {
1178 internal_error(state, 0, "bad targs");
1179 }
1180 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1181}
1182
1183static struct triple *alloc_triple(struct compile_state *state,
1184 int op, struct type *type, int rhs,
Eric Biedermanb138ac82003-04-22 18:44:01 +00001185 const char *filename, int line, int col)
1186{
Eric Biederman0babc1c2003-05-09 02:39:00 +00001187 size_t size, sizes, extra_count, min_count;
Eric Biedermanb138ac82003-04-22 18:44:01 +00001188 struct triple *ret;
Eric Biederman0babc1c2003-05-09 02:39:00 +00001189 sizes = triple_sizes(state, op, type, rhs);
1190
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;
1194
1195 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1196 ret = xcmalloc(size, "tripple");
Eric Biedermanb138ac82003-04-22 18:44:01 +00001197 ret->op = op;
Eric Biederman0babc1c2003-05-09 02:39:00 +00001198 ret->sizes = sizes;
Eric Biedermanb138ac82003-04-22 18:44:01 +00001199 ret->type = type;
Eric Biedermanb138ac82003-04-22 18:44:01 +00001200 ret->next = ret;
1201 ret->prev = ret;
1202 ret->filename = filename;
1203 ret->line = line;
1204 ret->col = col;
1205 return ret;
1206}
1207
Eric Biederman0babc1c2003-05-09 02:39:00 +00001208struct triple *dup_triple(struct compile_state *state, struct triple *src)
1209{
1210 struct triple *dup;
1211 int src_rhs;
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]));
1217 return dup;
1218}
1219
1220static struct triple *new_triple(struct compile_state *state,
1221 int op, struct type *type, int rhs)
Eric Biedermanb138ac82003-04-22 18:44:01 +00001222{
1223 struct triple *ret;
1224 const char *filename;
1225 int line, col;
1226 filename = 0;
1227 line = 0;
1228 col = 0;
1229 if (state->file) {
1230 filename = state->file->basename;
1231 line = state->file->line;
1232 col = get_col(state->file);
1233 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00001234 ret = alloc_triple(state, op, type, rhs,
1235 filename, line, col);
1236 return ret;
1237}
1238
1239static 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)
1242{
1243 struct triple *ret;
1244 size_t count;
1245 ret = alloc_triple(state, op, type, -1, filename, line, col);
1246 count = TRIPLE_SIZE(ret->sizes);
1247 if (count > 0) {
1248 ret->param[0] = left;
1249 }
1250 if (count > 1) {
1251 ret->param[1] = right;
Eric Biedermanb138ac82003-04-22 18:44:01 +00001252 }
1253 return ret;
1254}
1255
Eric Biederman0babc1c2003-05-09 02:39:00 +00001256static struct triple *triple(struct compile_state *state,
1257 int op, struct type *type, struct triple *left, struct triple *right)
1258{
1259 struct triple *ret;
1260 size_t count;
1261 ret = new_triple(state, op, type, -1);
1262 count = TRIPLE_SIZE(ret->sizes);
1263 if (count >= 1) {
1264 ret->param[0] = left;
1265 }
1266 if (count >= 2) {
1267 ret->param[1] = right;
1268 }
1269 return ret;
1270}
1271
1272static struct triple *branch(struct compile_state *state,
1273 struct triple *targ, struct triple *test)
1274{
1275 struct triple *ret;
1276 ret = new_triple(state, OP_BRANCH, &void_type, test?1:0);
1277 if (test) {
1278 RHS(ret, 0) = test;
1279 }
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);
1285 }
1286 return ret;
1287}
1288
1289
Eric Biedermanb138ac82003-04-22 18:44:01 +00001290static void insert_triple(struct compile_state *state,
1291 struct triple *first, struct triple *ptr)
1292{
1293 if (ptr) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00001294 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00001295 internal_error(state, ptr, "expression already used");
1296 }
1297 ptr->next = first;
1298 ptr->prev = first->prev;
1299 ptr->prev->next = ptr;
1300 ptr->next->prev = ptr;
Eric Biederman0babc1c2003-05-09 02:39:00 +00001301 if ((ptr->prev->op == OP_BRANCH) &&
1302 TRIPLE_RHS(ptr->prev->sizes)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00001303 unuse_triple(first, ptr->prev);
1304 use_triple(ptr, ptr->prev);
1305 }
1306 }
1307}
1308
1309static struct triple *pre_triple(struct compile_state *state,
1310 struct triple *base,
1311 int op, struct type *type, struct triple *left, struct triple *right)
1312{
1313 /* Careful this assumes it can do the easy thing to get the block */
1314 struct triple *ret;
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);
1319 return ret;
1320}
1321
1322static struct triple *post_triple(struct compile_state *state,
1323 struct triple *base,
1324 int op, struct type *type, struct triple *left, struct triple *right)
1325{
1326 /* Careful this assumes it can do the easy thing to get the block */
1327 struct triple *ret;
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);
1332 return ret;
1333}
1334
1335static struct triple *label(struct compile_state *state)
1336{
1337 /* Labels don't get a type */
1338 struct triple *result;
1339 result = triple(state, OP_LABEL, &void_type, 0, 0);
1340 return result;
1341}
1342
Eric Biederman0babc1c2003-05-09 02:39:00 +00001343static void display_triple(FILE *fp, struct triple *ins)
1344{
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);
1349 }
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);
1354#if 0
1355 print_ins(state, MISC(ins, 0));
1356#endif
1357 }
1358 else {
1359 int i, count;
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]);
1365 }
1366 for(; i < 2; i++) {
1367 printf(" ");
1368 }
1369 fprintf(fp, " @ %s:%d.%d\n",
1370 ins->filename, ins->line, ins->col);
1371 }
1372 fflush(fp);
1373}
1374
Eric Biedermanb138ac82003-04-22 18:44:01 +00001375static int triple_is_pure(struct compile_state *state, struct triple *ins)
1376{
1377 /* Does the triple have no side effects.
1378 * I.e. Rexecuting the triple with the same arguments
1379 * gives the same value.
1380 */
Eric Biederman0babc1c2003-05-09 02:39:00 +00001381 unsigned pure;
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",
Eric Biedermanb138ac82003-04-22 18:44:01 +00001386 tops(ins->op));
Eric Biedermanb138ac82003-04-22 18:44:01 +00001387 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00001388 return pure == PURE;
Eric Biedermanb138ac82003-04-22 18:44:01 +00001389}
1390
Eric Biederman0babc1c2003-05-09 02:39:00 +00001391static int triple_is_branch(struct compile_state *state, struct triple *ins)
Eric Biedermanb138ac82003-04-22 18:44:01 +00001392{
1393 /* This function is used to determine which triples need
1394 * a register.
1395 */
Eric Biederman0babc1c2003-05-09 02:39:00 +00001396 int is_branch;
1397 valid_ins(state, ins);
1398 is_branch = (table_ops[ins->op].targ != 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00001399 return is_branch;
1400}
1401
Eric Biederman0babc1c2003-05-09 02:39:00 +00001402static int triple_is_def(struct compile_state *state, struct triple *ins)
Eric Biedermanb138ac82003-04-22 18:44:01 +00001403{
1404 /* This function is used to determine which triples need
1405 * a register.
1406 */
Eric Biederman0babc1c2003-05-09 02:39:00 +00001407 int is_def;
1408 valid_ins(state, ins);
1409 is_def = (table_ops[ins->op].flags & DEF) == DEF;
Eric Biedermanb138ac82003-04-22 18:44:01 +00001410 return is_def;
1411}
1412
Eric Biederman0babc1c2003-05-09 02:39:00 +00001413static struct triple **triple_iter(struct compile_state *state,
1414 size_t count, struct triple **vector,
1415 struct triple *ins, struct triple **last)
Eric Biedermanb138ac82003-04-22 18:44:01 +00001416{
1417 struct triple **ret;
1418 ret = 0;
Eric Biederman0babc1c2003-05-09 02:39:00 +00001419 if (count) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00001420 if (!last) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00001421 ret = vector;
Eric Biedermanb138ac82003-04-22 18:44:01 +00001422 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00001423 else if ((last >= vector) && (last < (vector + count - 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00001424 ret = last + 1;
Eric Biedermanb138ac82003-04-22 18:44:01 +00001425 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00001426 }
1427 return ret;
Eric Biederman0babc1c2003-05-09 02:39:00 +00001428
Eric Biedermanb138ac82003-04-22 18:44:01 +00001429}
1430
1431static struct triple **triple_lhs(struct compile_state *state,
Eric Biederman0babc1c2003-05-09 02:39:00 +00001432 struct triple *ins, struct triple **last)
Eric Biedermanb138ac82003-04-22 18:44:01 +00001433{
Eric Biederman0babc1c2003-05-09 02:39:00 +00001434 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1435 ins, last);
1436}
1437
1438static struct triple **triple_rhs(struct compile_state *state,
1439 struct triple *ins, struct triple **last)
1440{
1441 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1442 ins, last);
1443}
1444
1445static struct triple **triple_misc(struct compile_state *state,
1446 struct triple *ins, struct triple **last)
1447{
1448 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1449 ins, last);
1450}
1451static struct triple **triple_targ(struct compile_state *state,
1452 struct triple *ins, struct triple **last)
1453{
1454 return triple_iter(state, TRIPLE_TARG(ins->sizes), &TARG(ins,0),
1455 ins, last);
Eric Biedermanb138ac82003-04-22 18:44:01 +00001456}
1457
1458static void free_triple(struct compile_state *state, struct triple *ptr)
1459{
Eric Biederman0babc1c2003-05-09 02:39:00 +00001460 size_t size;
1461 size = sizeof(*ptr) - sizeof(ptr->param) +
1462 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
Eric Biedermanb138ac82003-04-22 18:44:01 +00001463 ptr->prev->next = ptr->next;
1464 ptr->next->prev = ptr->prev;
1465 if (ptr->use) {
1466 internal_error(state, ptr, "ptr->use != 0");
1467 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00001468 memset(ptr, -1, size);
Eric Biedermanb138ac82003-04-22 18:44:01 +00001469 xfree(ptr);
1470}
1471
1472static void release_triple(struct compile_state *state, struct triple *ptr)
1473{
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)) {
1479 if (*expr) {
1480 unuse_triple(*expr, ptr);
1481 }
1482 }
1483 expr = triple_lhs(state, ptr, 0);
1484 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1485 if (*expr) {
1486 unuse_triple(*expr, ptr);
1487 }
1488 }
1489 expr = triple_targ(state, ptr, 0);
1490 for(; expr; expr = triple_targ(state, ptr, expr)) {
1491 if (*expr) {
1492 unuse_triple(*expr, ptr);
1493 }
1494 }
1495 /* Reomve ptr from use chains where it is used */
1496 for(set = ptr->use; set; set = next) {
1497 next = set->next;
1498 expr = triple_rhs(state, set->member, 0);
1499 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1500 if (*expr == ptr) {
1501 *expr = &zero_triple;
1502 }
1503 }
1504 expr = triple_lhs(state, set->member, 0);
1505 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1506 if (*expr == ptr) {
1507 *expr = &zero_triple;
1508 }
1509 }
1510 expr = triple_targ(state, set->member, 0);
1511 for(; expr; expr = triple_targ(state, set->member, expr)) {
1512 if (*expr == ptr) {
1513 *expr = &zero_triple;
1514 }
1515 }
1516 unuse_triple(ptr, set->member);
1517 }
1518 free_triple(state, ptr);
1519}
1520
1521static void print_triple(struct compile_state *state, struct triple *ptr);
1522
1523#define TOK_UNKNOWN 0
1524#define TOK_SPACE 1
1525#define TOK_SEMI 2
1526#define TOK_LBRACE 3
1527#define TOK_RBRACE 4
1528#define TOK_COMMA 5
1529#define TOK_EQ 6
1530#define TOK_COLON 7
1531#define TOK_LBRACKET 8
1532#define TOK_RBRACKET 9
1533#define TOK_LPAREN 10
1534#define TOK_RPAREN 11
1535#define TOK_STAR 12
1536#define TOK_DOTS 13
1537#define TOK_MORE 14
1538#define TOK_LESS 15
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
1544#define TOK_SLEQ 21
1545#define TOK_SREQ 22
1546#define TOK_ANDEQ 23
1547#define TOK_XOREQ 24
1548#define TOK_OREQ 25
1549#define TOK_EQEQ 26
1550#define TOK_NOTEQ 27
1551#define TOK_QUEST 28
1552#define TOK_LOGOR 29
1553#define TOK_LOGAND 30
1554#define TOK_OR 31
1555#define TOK_AND 32
1556#define TOK_XOR 33
1557#define TOK_LESSEQ 34
1558#define TOK_MOREEQ 35
1559#define TOK_SL 36
1560#define TOK_SR 37
1561#define TOK_PLUS 38
1562#define TOK_MINUS 39
1563#define TOK_DIV 40
1564#define TOK_MOD 41
1565#define TOK_PLUSPLUS 42
1566#define TOK_MINUSMINUS 43
1567#define TOK_BANG 44
1568#define TOK_ARROW 45
1569#define TOK_DOT 46
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
1577
1578#define TOK_IDENT 54
1579#define TOK_STRUCT_NAME 55
1580#define TOK_ENUM_CONST 56
1581#define TOK_TYPE_NAME 57
1582
1583#define TOK_AUTO 58
1584#define TOK_BREAK 59
1585#define TOK_CASE 60
1586#define TOK_CHAR 61
1587#define TOK_CONST 62
1588#define TOK_CONTINUE 63
1589#define TOK_DEFAULT 64
1590#define TOK_DO 65
1591#define TOK_DOUBLE 66
1592#define TOK_ELSE 67
1593#define TOK_ENUM 68
1594#define TOK_EXTERN 69
1595#define TOK_FLOAT 70
1596#define TOK_FOR 71
1597#define TOK_GOTO 72
1598#define TOK_IF 73
1599#define TOK_INLINE 74
1600#define TOK_INT 75
1601#define TOK_LONG 76
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
1614#define TOK_VOID 89
1615#define TOK_VOLATILE 90
1616#define TOK_WHILE 91
1617#define TOK_ASM 92
1618#define TOK_ATTRIBUTE 93
1619#define TOK_ALIGNOF 94
1620#define TOK_FIRST_KEYWORD TOK_AUTO
1621#define TOK_LAST_KEYWORD TOK_ALIGNOF
1622
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
1634
1635#define TOK_FIRST_MACRO TOK_DEFINE
1636#define TOK_LAST_MACRO TOK_ENDIF
1637
1638#define TOK_EOF 111
1639
1640static const char *tokens[] = {
1641[TOK_UNKNOWN ] = "unknown",
1642[TOK_SPACE ] = ":space:",
1643[TOK_SEMI ] = ";",
1644[TOK_LBRACE ] = "{",
1645[TOK_RBRACE ] = "}",
1646[TOK_COMMA ] = ",",
1647[TOK_EQ ] = "=",
1648[TOK_COLON ] = ":",
1649[TOK_LBRACKET ] = "[",
1650[TOK_RBRACKET ] = "]",
1651[TOK_LPAREN ] = "(",
1652[TOK_RPAREN ] = ")",
1653[TOK_STAR ] = "*",
1654[TOK_DOTS ] = "...",
1655[TOK_MORE ] = ">",
1656[TOK_LESS ] = "<",
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 ] = "^=",
1666[TOK_OREQ ] = "|=",
1667[TOK_EQEQ ] = "==",
1668[TOK_NOTEQ ] = "!=",
1669[TOK_QUEST ] = "?",
1670[TOK_LOGOR ] = "||",
1671[TOK_LOGAND ] = "&&",
1672[TOK_OR ] = "|",
1673[TOK_AND ] = "&",
1674[TOK_XOR ] = "^",
1675[TOK_LESSEQ ] = "<=",
1676[TOK_MOREEQ ] = ">=",
1677[TOK_SL ] = "<<",
1678[TOK_SR ] = ">>",
1679[TOK_PLUS ] = "+",
1680[TOK_MINUS ] = "-",
1681[TOK_DIV ] = "/",
1682[TOK_MOD ] = "%",
1683[TOK_PLUSPLUS ] = "++",
1684[TOK_MINUSMINUS ] = "--",
1685[TOK_BANG ] = "!",
1686[TOK_ARROW ] = "->",
1687[TOK_DOT ] = ".",
1688[TOK_TILDE ] = "~",
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:",
1695[TOK_MACRO ] = "#",
1696[TOK_CONCATENATE ] = "##",
1697
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",
1705[TOK_DO ] = "do",
1706[TOK_DOUBLE ] = "double",
1707[TOK_ELSE ] = "else",
1708[TOK_ENUM ] = "enum",
1709[TOK_EXTERN ] = "extern",
1710[TOK_FLOAT ] = "float",
1711[TOK_FOR ] = "for",
1712[TOK_GOTO ] = "goto",
1713[TOK_IF ] = "if",
1714[TOK_INLINE ] = "inline",
1715[TOK_INT ] = "int",
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",
1732[TOK_ASM ] = "asm",
1733[TOK_ATTRIBUTE ] = "__attribute__",
1734[TOK_ALIGNOF ] = "__alignof__",
1735
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",
1747
1748[TOK_EOF ] = "EOF",
1749};
1750
1751static unsigned int hash(const char *str, int str_len)
1752{
1753 unsigned int hash;
1754 const char *end;
1755 end = str + str_len;
1756 hash = 0;
1757 for(; str < end; str++) {
1758 hash = (hash *263) + *str;
1759 }
1760 hash = hash & (HASH_TABLE_SIZE -1);
1761 return hash;
1762}
1763
1764static struct hash_entry *lookup(
1765 struct compile_state *state, const char *name, int name_len)
1766{
1767 struct hash_entry *entry;
1768 unsigned int index;
1769 index = hash(name, name_len);
1770 entry = state->hash_table[index];
1771 while(entry &&
1772 ((entry->name_len != name_len) ||
1773 (memcmp(entry->name, name, name_len) != 0))) {
1774 entry = entry->next;
1775 }
1776 if (!entry) {
1777 char *new_name;
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';
1782
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;
1788
1789 /* Place the new entry in the hash table */
1790 state->hash_table[index] = entry;
1791 }
1792 return entry;
1793}
1794
1795static void ident_to_keyword(struct compile_state *state, struct token *tk)
1796{
1797 struct hash_entry *entry;
1798 entry = tk->ident;
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;
1804 }
1805}
1806
1807static void ident_to_macro(struct compile_state *state, struct token *tk)
1808{
1809 struct hash_entry *entry;
1810 entry = tk->ident;
1811 if (entry &&
1812 (entry->tok >= TOK_FIRST_MACRO) &&
1813 (entry->tok <= TOK_LAST_MACRO)) {
1814 tk->tok = entry->tok;
1815 }
1816}
1817
1818static void hash_keyword(
1819 struct compile_state *state, const char *keyword, int tok)
1820{
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);
1825 }
1826 entry->tok = tok;
1827}
1828
1829static void symbol(
1830 struct compile_state *state, struct hash_entry *ident,
1831 struct symbol **chain, struct triple *def, struct type *type)
1832{
1833 struct symbol *sym;
1834 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
1835 error(state, 0, "%s already defined", ident->name);
1836 }
1837 sym = xcmalloc(sizeof(*sym), "symbol");
1838 sym->ident = ident;
1839 sym->def = def;
1840 sym->type = type;
1841 sym->scope_depth = state->scope_depth;
1842 sym->next = *chain;
1843 *chain = sym;
1844}
1845
1846static void start_scope(struct compile_state *state)
1847{
1848 state->scope_depth++;
1849}
1850
1851static void end_scope_syms(struct symbol **chain, int depth)
1852{
1853 struct symbol *sym, *next;
1854 sym = *chain;
1855 while(sym && (sym->scope_depth == depth)) {
1856 next = sym->next;
1857 xfree(sym);
1858 sym = next;
1859 }
1860 *chain = sym;
1861}
1862
1863static void end_scope(struct compile_state *state)
1864{
1865 int i;
1866 int depth;
1867 /* Walk through the hash table and remove all symbols
1868 * in the current scope.
1869 */
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];
1874 while(entry) {
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;
1879 }
1880 }
1881 state->scope_depth = depth - 1;
1882}
1883
1884static void register_keywords(struct compile_state *state)
1885{
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);
1923}
1924
1925static void register_macro_keywords(struct compile_state *state)
1926{
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);
1938}
1939
1940static int spacep(int c)
1941{
1942 int ret = 0;
1943 switch(c) {
1944 case ' ':
1945 case '\t':
1946 case '\f':
1947 case '\v':
1948 case '\r':
1949 case '\n':
1950 ret = 1;
1951 break;
1952 }
1953 return ret;
1954}
1955
1956static int digitp(int c)
1957{
1958 int ret = 0;
1959 switch(c) {
1960 case '0': case '1': case '2': case '3': case '4':
1961 case '5': case '6': case '7': case '8': case '9':
1962 ret = 1;
1963 break;
1964 }
1965 return ret;
1966}
1967
1968static int hexdigitp(int c)
1969{
1970 int ret = 0;
1971 switch(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':
1976 ret = 1;
1977 break;
1978 }
1979 return ret;
1980}
1981static int hexdigval(int c)
1982{
1983 int val = -1;
1984 if ((c >= '0') && (c <= '9')) {
1985 val = c - '0';
1986 }
1987 else if ((c >= 'A') && (c <= 'F')) {
1988 val = 10 + (c - 'A');
1989 }
1990 else if ((c >= 'a') && (c <= 'f')) {
1991 val = 10 + (c - 'a');
1992 }
1993 return val;
1994}
1995
1996static int octdigitp(int c)
1997{
1998 int ret = 0;
1999 switch(c) {
2000 case '0': case '1': case '2': case '3':
2001 case '4': case '5': case '6': case '7':
2002 ret = 1;
2003 break;
2004 }
2005 return ret;
2006}
2007static int octdigval(int c)
2008{
2009 int val = -1;
2010 if ((c >= '0') && (c <= '7')) {
2011 val = c - '0';
2012 }
2013 return val;
2014}
2015
2016static int letterp(int c)
2017{
2018 int ret = 0;
2019 switch(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':
2025 case 'z':
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':
2031 case 'Z':
2032 case '_':
2033 ret = 1;
2034 break;
2035 }
2036 return ret;
2037}
2038
2039static int char_value(struct compile_state *state,
2040 const signed char **strp, const signed char *end)
2041{
2042 const signed char *str;
2043 int c;
2044 str = *strp;
2045 c = *str++;
2046 if ((c == '\\') && (str < end)) {
2047 switch(*str) {
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;
2059 case 'x':
2060 c = 0;
2061 str++;
2062 while((str < end) && hexdigitp(*str)) {
2063 c <<= 4;
2064 c += hexdigval(*str);
2065 str++;
2066 }
2067 break;
2068 case '0': case '1': case '2': case '3':
2069 case '4': case '5': case '6': case '7':
2070 c = 0;
2071 while((str < end) && octdigitp(*str)) {
2072 c <<= 3;
2073 c += octdigval(*str);
2074 str++;
2075 }
2076 break;
2077 default:
2078 error(state, 0, "Invalid character constant");
2079 break;
2080 }
2081 }
2082 *strp = str;
2083 return c;
2084}
2085
2086static char *after_digits(char *ptr, char *end)
2087{
2088 while((ptr < end) && digitp(*ptr)) {
2089 ptr++;
2090 }
2091 return ptr;
2092}
2093
2094static char *after_octdigits(char *ptr, char *end)
2095{
2096 while((ptr < end) && octdigitp(*ptr)) {
2097 ptr++;
2098 }
2099 return ptr;
2100}
2101
2102static char *after_hexdigits(char *ptr, char *end)
2103{
2104 while((ptr < end) && hexdigitp(*ptr)) {
2105 ptr++;
2106 }
2107 return ptr;
2108}
2109
2110static void save_string(struct compile_state *state,
2111 struct token *tk, char *start, char *end, const char *id)
2112{
2113 char *str;
2114 int str_len;
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';
2120
2121 /* Store the copy in the token */
2122 tk->val.str = str;
2123 tk->str_len = str_len;
2124}
2125static void next_token(struct compile_state *state, int index)
2126{
2127 struct file_state *file;
2128 struct token *tk;
2129 char *token;
2130 int c, c1, c2, c3;
2131 char *tokp, *end;
2132 int tok;
2133next_token:
2134 file = state->file;
2135 tk = &state->token[index];
2136 tk->str_len = 0;
2137 tk->ident = 0;
2138 token = tokp = file->pos;
2139 end = file->buf + file->size;
2140 tok = TOK_UNKNOWN;
2141 c = -1;
2142 if (tokp < end) {
2143 c = *tokp;
2144 }
2145 c1 = -1;
2146 if ((tokp + 1) < end) {
2147 c1 = tokp[1];
2148 }
2149 c2 = -1;
2150 if ((tokp + 2) < end) {
2151 c2 = tokp[2];
2152 }
2153 c3 = -1;
2154 if ((tokp + 3) < end) {
2155 c3 = tokp[3];
2156 }
2157 if (tokp >= end) {
2158 tok = TOK_EOF;
2159 tokp = end;
2160 }
2161 /* Whitespace */
2162 else if (spacep(c)) {
2163 tok = TOK_SPACE;
2164 while ((tokp < end) && spacep(c)) {
2165 if (c == '\n') {
2166 file->line++;
2167 file->line_start = tokp + 1;
2168 }
2169 c = *(++tokp);
2170 }
2171 if (!spacep(c)) {
2172 tokp--;
2173 }
2174 }
2175 /* EOL Comments */
2176 else if ((c == '/') && (c1 == '/')) {
2177 tok = TOK_SPACE;
2178 for(tokp += 2; tokp < end; tokp++) {
2179 c = *tokp;
2180 if (c == '\n') {
2181 file->line++;
2182 file->line_start = tokp +1;
2183 break;
2184 }
2185 }
2186 }
2187 /* Comments */
2188 else if ((c == '/') && (c1 == '*')) {
2189 int line;
2190 char *line_start;
2191 line = file->line;
2192 line_start = file->line_start;
2193 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2194 c = *tokp;
2195 if (c == '\n') {
2196 line++;
2197 line_start = tokp +1;
2198 }
2199 else if ((c == '*') && (tokp[1] == '/')) {
2200 tok = TOK_SPACE;
2201 tokp += 1;
2202 break;
2203 }
2204 }
2205 if (tok == TOK_UNKNOWN) {
2206 error(state, 0, "unterminated comment");
2207 }
2208 file->line = line;
2209 file->line_start = line_start;
2210 }
2211 /* string constants */
2212 else if ((c == '"') ||
2213 ((c == 'L') && (c1 == '"'))) {
2214 int line;
2215 char *line_start;
2216 int wchar;
2217 line = file->line;
2218 line_start = file->line_start;
2219 wchar = 0;
2220 if (c == 'L') {
2221 wchar = 1;
2222 tokp++;
2223 }
2224 for(tokp += 1; tokp < end; tokp++) {
2225 c = *tokp;
2226 if (c == '\n') {
2227 line++;
2228 line_start = tokp + 1;
2229 }
2230 else if ((c == '\\') && (tokp +1 < end)) {
2231 tokp++;
2232 }
2233 else if (c == '"') {
2234 tok = TOK_LIT_STRING;
2235 break;
2236 }
2237 }
2238 if (tok == TOK_UNKNOWN) {
2239 error(state, 0, "unterminated string constant");
2240 }
2241 if (line != file->line) {
2242 warning(state, 0, "multiline string constant");
2243 }
2244 file->line = line;
2245 file->line_start = line_start;
2246
2247 /* Save the string value */
2248 save_string(state, tk, token, tokp, "literal string");
2249 }
2250 /* character constants */
2251 else if ((c == '\'') ||
2252 ((c == 'L') && (c1 == '\''))) {
2253 int line;
2254 char *line_start;
2255 int wchar;
2256 line = file->line;
2257 line_start = file->line_start;
2258 wchar = 0;
2259 if (c == 'L') {
2260 wchar = 1;
2261 tokp++;
2262 }
2263 for(tokp += 1; tokp < end; tokp++) {
2264 c = *tokp;
2265 if (c == '\n') {
2266 line++;
2267 line_start = tokp + 1;
2268 }
2269 else if ((c == '\\') && (tokp +1 < end)) {
2270 tokp++;
2271 }
2272 else if (c == '\'') {
2273 tok = TOK_LIT_CHAR;
2274 break;
2275 }
2276 }
2277 if (tok == TOK_UNKNOWN) {
2278 error(state, 0, "unterminated character constant");
2279 }
2280 if (line != file->line) {
2281 warning(state, 0, "multiline character constant");
2282 }
2283 file->line = line;
2284 file->line_start = line_start;
2285
2286 /* Save the character value */
2287 save_string(state, tk, token, tokp, "literal character");
2288 }
2289 /* integer and floating constants
2290 * Integer Constants
2291 * {digits}
2292 * 0[Xx]{hexdigits}
2293 * 0{octdigit}+
2294 *
2295 * Floating constants
2296 * {digits}.{digits}[Ee][+-]?{digits}
2297 * {digits}.{digits}
2298 * {digits}[Ee][+-]?{digits}
2299 * .{digits}[Ee][+-]?{digits}
2300 * .{digits}
2301 */
2302
2303 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2304 char *next, *new;
2305 int is_float;
2306 is_float = 0;
2307 if (c != '.') {
2308 next = after_digits(tokp, end);
2309 }
2310 else {
2311 next = tokp;
2312 }
2313 if (next[0] == '.') {
2314 new = after_digits(next, end);
2315 is_float = (new != next);
2316 next = new;
2317 }
2318 if ((next[0] == 'e') || (next[0] == 'E')) {
2319 if (((next + 1) < end) &&
2320 ((next[1] == '+') || (next[1] == '-'))) {
2321 next++;
2322 }
2323 new = after_digits(next, end);
2324 is_float = (new != next);
2325 next = new;
2326 }
2327 if (is_float) {
2328 tok = TOK_LIT_FLOAT;
2329 if ((next < end) && (
2330 (next[0] == 'f') ||
2331 (next[0] == 'F') ||
2332 (next[0] == 'l') ||
2333 (next[0] == 'L'))
2334 ) {
2335 next++;
2336 }
2337 }
2338 if (!is_float && digitp(c)) {
2339 tok = TOK_LIT_INT;
2340 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2341 next = after_hexdigits(tokp + 2, end);
2342 }
2343 else if (c == '0') {
2344 next = after_octdigits(tokp, end);
2345 }
2346 else {
2347 next = after_digits(tokp, end);
2348 }
2349 /* crazy integer suffixes */
2350 if ((next < end) &&
2351 ((next[0] == 'u') || (next[0] == 'U'))) {
2352 next++;
2353 if ((next < end) &&
2354 ((next[0] == 'l') || (next[0] == 'L'))) {
2355 next++;
2356 }
2357 }
2358 else if ((next < end) &&
2359 ((next[0] == 'l') || (next[0] == 'L'))) {
2360 next++;
2361 if ((next < end) &&
2362 ((next[0] == 'u') || (next[0] == 'U'))) {
2363 next++;
2364 }
2365 }
2366 }
2367 tokp = next - 1;
2368
2369 /* Save the integer/floating point value */
2370 save_string(state, tk, token, tokp, "literal number");
2371 }
2372 /* identifiers */
2373 else if (letterp(c)) {
2374 tok = TOK_IDENT;
2375 for(tokp += 1; tokp < end; tokp++) {
2376 c = *tokp;
2377 if (!letterp(c) && !digitp(c)) {
2378 break;
2379 }
2380 }
2381 tokp -= 1;
2382 tk->ident = lookup(state, token, tokp +1 - token);
2383 }
2384 /* C99 alternate macro characters */
2385 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2386 tokp += 3;
2387 tok = TOK_CONCATENATE;
2388 }
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 */
2444 char *ptr;
2445 for(ptr = file->line_start; spacep(*ptr); ptr++)
2446 ;
2447 if (ptr != tokp) {
2448 tok = TOK_UNKNOWN;
2449 }
2450 }
2451 if (tok == TOK_UNKNOWN) {
2452 error(state, 0, "unknown token");
2453 }
2454
2455 file->pos = tokp + 1;
2456 tk->tok = tok;
2457 if (tok == TOK_IDENT) {
2458 ident_to_keyword(state, tk);
2459 }
2460 /* Don't return space tokens. */
2461 if (tok == TOK_SPACE) {
2462 goto next_token;
2463 }
2464}
2465
2466static void compile_macro(struct compile_state *state, struct token *tk)
2467{
2468 struct file_state *file;
2469 struct hash_entry *ident;
2470 ident = tk->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;
2481 file->line = 1;
2482 file->prev = state->file;
2483 state->file = file;
2484}
2485
2486
2487static int mpeek(struct compile_state *state, int index)
2488{
2489 struct token *tk;
2490 int rescan;
2491 tk = &state->token[index + 1];
2492 if (tk->tok == -1) {
2493 next_token(state, index + 1);
2494 }
2495 do {
2496 rescan = 0;
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);
2504 xfree(file->buf);
2505 xfree(file);
2506 next_token(state, index + 1);
2507 rescan = 1;
2508 }
2509 else if (tk->ident && tk->ident->sym_define) {
2510 compile_macro(state, tk);
2511 next_token(state, index + 1);
2512 rescan = 1;
2513 }
2514 } while(rescan);
2515 /* Don't show the token on the next line */
2516 if (state->macro_line < state->macro_file->line) {
2517 return TOK_EOF;
2518 }
2519 return state->token[index +1].tok;
2520}
2521
2522static void meat(struct compile_state *state, int index, int tok)
2523{
2524 int next_tok;
2525 int i;
2526 next_tok = mpeek(state, index);
2527 if (next_tok != tok) {
2528 const char *name1, *name2;
2529 name1 = tokens[next_tok];
2530 name2 = "";
2531 if (next_tok == TOK_IDENT) {
2532 name2 = state->token[index + 1].ident->name;
2533 }
2534 error(state, 0, "found %s %s expected %s",
2535 name1, name2, tokens[tok]);
2536 }
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);
2542 }
2543 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2544 state->token[i] = state->token[i + 1];
2545 }
2546 memset(&state->token[i], 0, sizeof(state->token[i]));
2547 state->token[i].tok = -1;
2548}
2549
2550static long_t mcexpr(struct compile_state *state, int index);
2551
2552static long_t mprimary_expr(struct compile_state *state, int index)
2553{
2554 long_t val;
2555 int tok;
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);
2562 }
2563 switch(tok) {
2564 case TOK_LPAREN:
2565 meat(state, index, TOK_LPAREN);
2566 val = mcexpr(state, index);
2567 meat(state, index, TOK_RPAREN);
2568 break;
2569 case TOK_LIT_INT:
2570 {
2571 char *end;
2572 meat(state, index, TOK_LIT_INT);
2573 errno = 0;
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");
2578 }
2579 break;
2580 }
2581 default:
2582 meat(state, index, TOK_LIT_INT);
2583 val = 0;
2584 }
2585 return val;
2586}
2587static long_t munary_expr(struct compile_state *state, int index)
2588{
2589 long_t val;
2590 switch(mpeek(state, index)) {
2591 case TOK_PLUS:
2592 meat(state, index, TOK_PLUS);
2593 val = munary_expr(state, index);
2594 val = + val;
2595 break;
2596 case TOK_MINUS:
2597 meat(state, index, TOK_MINUS);
2598 val = munary_expr(state, index);
2599 val = - val;
2600 break;
2601 case TOK_TILDE:
2602 meat(state, index, TOK_BANG);
2603 val = munary_expr(state, index);
2604 val = ~ val;
2605 break;
2606 case TOK_BANG:
2607 meat(state, index, TOK_BANG);
2608 val = munary_expr(state, index);
2609 val = ! val;
2610 break;
2611 default:
2612 val = mprimary_expr(state, index);
2613 break;
2614 }
2615 return val;
2616
2617}
2618static long_t mmul_expr(struct compile_state *state, int index)
2619{
2620 long_t val;
2621 int done;
2622 val = munary_expr(state, index);
2623 do {
2624 long_t right;
2625 done = 0;
2626 switch(mpeek(state, index)) {
2627 case TOK_STAR:
2628 meat(state, index, TOK_STAR);
2629 right = munary_expr(state, index);
2630 val = val * right;
2631 break;
2632 case TOK_DIV:
2633 meat(state, index, TOK_DIV);
2634 right = munary_expr(state, index);
2635 val = val / right;
2636 break;
2637 case TOK_MOD:
2638 meat(state, index, TOK_MOD);
2639 right = munary_expr(state, index);
2640 val = val % right;
2641 break;
2642 default:
2643 done = 1;
2644 break;
2645 }
2646 } while(!done);
2647
2648 return val;
2649}
2650
2651static long_t madd_expr(struct compile_state *state, int index)
2652{
2653 long_t val;
2654 int done;
2655 val = mmul_expr(state, index);
2656 do {
2657 long_t right;
2658 done = 0;
2659 switch(mpeek(state, index)) {
2660 case TOK_PLUS:
2661 meat(state, index, TOK_PLUS);
2662 right = mmul_expr(state, index);
2663 val = val + right;
2664 break;
2665 case TOK_MINUS:
2666 meat(state, index, TOK_MINUS);
2667 right = mmul_expr(state, index);
2668 val = val - right;
2669 break;
2670 default:
2671 done = 1;
2672 break;
2673 }
2674 } while(!done);
2675
2676 return val;
2677}
2678
2679static long_t mshift_expr(struct compile_state *state, int index)
2680{
2681 long_t val;
2682 int done;
2683 val = madd_expr(state, index);
2684 do {
2685 long_t right;
2686 done = 0;
2687 switch(mpeek(state, index)) {
2688 case TOK_SL:
2689 meat(state, index, TOK_SL);
2690 right = madd_expr(state, index);
2691 val = val << right;
2692 break;
2693 case TOK_SR:
2694 meat(state, index, TOK_SR);
2695 right = madd_expr(state, index);
2696 val = val >> right;
2697 break;
2698 default:
2699 done = 1;
2700 break;
2701 }
2702 } while(!done);
2703
2704 return val;
2705}
2706
2707static long_t mrel_expr(struct compile_state *state, int index)
2708{
2709 long_t val;
2710 int done;
2711 val = mshift_expr(state, index);
2712 do {
2713 long_t right;
2714 done = 0;
2715 switch(mpeek(state, index)) {
2716 case TOK_LESS:
2717 meat(state, index, TOK_LESS);
2718 right = mshift_expr(state, index);
2719 val = val < right;
2720 break;
2721 case TOK_MORE:
2722 meat(state, index, TOK_MORE);
2723 right = mshift_expr(state, index);
2724 val = val > right;
2725 break;
2726 case TOK_LESSEQ:
2727 meat(state, index, TOK_LESSEQ);
2728 right = mshift_expr(state, index);
2729 val = val <= right;
2730 break;
2731 case TOK_MOREEQ:
2732 meat(state, index, TOK_MOREEQ);
2733 right = mshift_expr(state, index);
2734 val = val >= right;
2735 break;
2736 default:
2737 done = 1;
2738 break;
2739 }
2740 } while(!done);
2741 return val;
2742}
2743
2744static long_t meq_expr(struct compile_state *state, int index)
2745{
2746 long_t val;
2747 int done;
2748 val = mrel_expr(state, index);
2749 do {
2750 long_t right;
2751 done = 0;
2752 switch(mpeek(state, index)) {
2753 case TOK_EQEQ:
2754 meat(state, index, TOK_EQEQ);
2755 right = mrel_expr(state, index);
2756 val = val == right;
2757 break;
2758 case TOK_NOTEQ:
2759 meat(state, index, TOK_NOTEQ);
2760 right = mrel_expr(state, index);
2761 val = val != right;
2762 break;
2763 default:
2764 done = 1;
2765 break;
2766 }
2767 } while(!done);
2768 return val;
2769}
2770
2771static long_t mand_expr(struct compile_state *state, int index)
2772{
2773 long_t val;
2774 val = meq_expr(state, index);
2775 if (mpeek(state, index) == TOK_AND) {
2776 long_t right;
2777 meat(state, index, TOK_AND);
2778 right = meq_expr(state, index);
2779 val = val & right;
2780 }
2781 return val;
2782}
2783
2784static long_t mxor_expr(struct compile_state *state, int index)
2785{
2786 long_t val;
2787 val = mand_expr(state, index);
2788 if (mpeek(state, index) == TOK_XOR) {
2789 long_t right;
2790 meat(state, index, TOK_XOR);
2791 right = mand_expr(state, index);
2792 val = val ^ right;
2793 }
2794 return val;
2795}
2796
2797static long_t mor_expr(struct compile_state *state, int index)
2798{
2799 long_t val;
2800 val = mxor_expr(state, index);
2801 if (mpeek(state, index) == TOK_OR) {
2802 long_t right;
2803 meat(state, index, TOK_OR);
2804 right = mxor_expr(state, index);
2805 val = val | right;
2806 }
2807 return val;
2808}
2809
2810static long_t mland_expr(struct compile_state *state, int index)
2811{
2812 long_t val;
2813 val = mor_expr(state, index);
2814 if (mpeek(state, index) == TOK_LOGAND) {
2815 long_t right;
2816 meat(state, index, TOK_LOGAND);
2817 right = mor_expr(state, index);
2818 val = val && right;
2819 }
2820 return val;
2821}
2822static long_t mlor_expr(struct compile_state *state, int index)
2823{
2824 long_t val;
2825 val = mland_expr(state, index);
2826 if (mpeek(state, index) == TOK_LOGOR) {
2827 long_t right;
2828 meat(state, index, TOK_LOGOR);
2829 right = mland_expr(state, index);
2830 val = val || right;
2831 }
2832 return val;
2833}
2834
2835static long_t mcexpr(struct compile_state *state, int index)
2836{
2837 return mlor_expr(state, index);
2838}
2839static void preprocess(struct compile_state *state, int index)
2840{
2841 /* Doing much more with the preprocessor would require
2842 * a parser and a major restructuring.
2843 * Postpone that for later.
2844 */
2845 struct file_state *file;
2846 struct token *tk;
2847 int line;
2848 int tok;
2849
2850 file = state->file;
2851 tk = &state->token[index];
2852 state->macro_line = line = file->line;
2853 state->macro_file = file;
2854
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'",
2859 tk->ident->name);
2860 }
2861 switch(tk->tok) {
2862 case TOK_UNDEF:
2863 case TOK_LINE:
2864 case TOK_PRAGMA:
2865 if (state->if_value < 0) {
2866 break;
2867 }
2868 warning(state, 0, "Ignoring preprocessor directive: %s",
2869 tk->ident->name);
2870 break;
2871 case TOK_ELIF:
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");
2876 }
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;
2880 }
2881 /* If the previous #if was not taken see if the #elif enables the
2882 * trailing code.
2883 */
2884 else if ((state->if_value < 0) &&
2885 (state->if_depth == - state->if_value))
2886 {
2887 if (mcexpr(state, index) != 0) {
2888 state->if_value = state->if_depth;
2889 }
2890 else {
2891 state->if_value = - state->if_depth;
2892 }
2893 }
2894 break;
2895 case TOK_IF:
2896 state->if_depth++;
2897 if (state->if_value < 0) {
2898 break;
2899 }
2900 if (mcexpr(state, index) != 0) {
2901 state->if_value = state->if_depth;
2902 }
2903 else {
2904 state->if_value = - state->if_depth;
2905 }
2906 break;
2907 case TOK_IFNDEF:
2908 state->if_depth++;
2909 if (state->if_value < 0) {
2910 break;
2911 }
2912 next_token(state, index);
2913 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2914 error(state, 0, "Invalid macro name");
2915 }
2916 if (tk->ident->sym_define == 0) {
2917 state->if_value = state->if_depth;
2918 }
2919 else {
2920 state->if_value = - state->if_depth;
2921 }
2922 break;
2923 case TOK_IFDEF:
2924 state->if_depth++;
2925 if (state->if_value < 0) {
2926 break;
2927 }
2928 next_token(state, index);
2929 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2930 error(state, 0, "Invalid macro name");
2931 }
2932 if (tk->ident->sym_define != 0) {
2933 state->if_value = state->if_depth;
2934 }
2935 else {
2936 state->if_value = - state->if_depth;
2937 }
2938 break;
2939 case TOK_ELSE:
2940 if (state->if_depth == 0) {
2941 error(state, 0, "#else without #if");
2942 }
2943 if ((state->if_value >= 0) ||
2944 ((state->if_value < 0) &&
2945 (state->if_depth == -state->if_value)))
2946 {
2947 state->if_value = - state->if_value;
2948 }
2949 break;
2950 case TOK_ENDIF:
2951 if (state->if_depth == 0) {
2952 error(state, 0, "#endif without #if");
2953 }
2954 if ((state->if_value >= 0) ||
2955 ((state->if_value < 0) &&
2956 (state->if_depth == -state->if_value)))
2957 {
2958 state->if_value = state->if_depth - 1;
2959 }
2960 state->if_depth--;
2961 break;
2962 case TOK_DEFINE:
2963 {
2964 struct hash_entry *ident;
2965 struct macro *macro;
2966 char *ptr;
2967
2968 if (state->if_value < 0) /* quit early when #if'd out */
2969 break;
2970
2971 meat(state, index, TOK_IDENT);
2972 ident = tk->ident;
2973
2974
2975 if (*file->pos == '(') {
2976#warning "FIXME macros with arguments not supported"
2977 error(state, 0, "Macros with arguments not supported");
2978 }
2979
2980 /* Find the end of the line to get an estimate of
2981 * the macro's length.
2982 */
2983 for(ptr = file->pos; *ptr != '\n'; ptr++)
2984 ;
2985
2986 if (ident->sym_define != 0) {
2987 error(state, 0, "macro %s already defined\n", ident->name);
2988 }
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");
2993
2994 memcpy(macro->buf, file->pos, macro->buf_len);
2995 macro->buf[macro->buf_len] = '\n';
2996 macro->buf[macro->buf_len +1] = '\0';
2997
2998 ident->sym_define = macro;
2999 break;
3000 }
3001 case TOK_ERROR:
3002 {
3003 char *end;
3004 int len;
3005 /* Find the end of the line */
3006 for(end = file->pos; *end != '\n'; end++)
3007 ;
3008 len = (end - file->pos);
3009 if (state->if_value >= 0) {
3010 error(state, 0, "%*.*s", len, len, file->pos);
3011 }
3012 file->pos = end;
3013 break;
3014 }
3015 case TOK_WARNING:
3016 {
3017 char *end;
3018 int len;
3019 /* Find the end of the line */
3020 for(end = file->pos; *end != '\n'; end++)
3021 ;
3022 len = (end - file->pos);
3023 if (state->if_value >= 0) {
3024 warning(state, 0, "%*.*s", len, len, file->pos);
3025 }
3026 file->pos = end;
3027 break;
3028 }
3029 case TOK_INCLUDE:
3030 {
3031 char *name;
3032 char *ptr;
3033 int local;
3034 local = 0;
3035 name = 0;
3036 next_token(state, index);
3037 if (tk->tok == TOK_LIT_STRING) {
3038 const char *token;
3039 int name_len;
3040 name = xmalloc(tk->str_len, "include");
3041 token = tk->val.str +1;
3042 name_len = tk->str_len -2;
3043 if (*token == '"') {
3044 token++;
3045 name_len--;
3046 }
3047 memcpy(name, token, name_len);
3048 name[name_len] = '\0';
3049 local = 1;
3050 }
3051 else if (tk->tok == TOK_LESS) {
3052 char *start, *end;
3053 start = file->pos;
3054 for(end = start; *end != '\n'; end++) {
3055 if (*end == '>') {
3056 break;
3057 }
3058 }
3059 if (*end == '\n') {
3060 error(state, 0, "Unterminated included directive");
3061 }
3062 name = xmalloc(end - start + 1, "include");
3063 memcpy(name, start, end - start);
3064 name[end - start] = '\0';
3065 file->pos = end +1;
3066 local = 0;
3067 }
3068 else {
3069 error(state, 0, "Invalid include directive");
3070 }
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");
3075 }
3076 }
3077 if (state->if_value >= 0) {
3078 compile_file(state, name, local);
3079 }
3080 xfree(name);
3081 next_token(state, index);
3082 return;
3083 }
3084 default:
3085 /* Ignore # without a following ident */
3086 if (tk->tok == TOK_IDENT) {
3087 error(state, 0, "Invalid preprocessor directive: %s",
3088 tk->ident->name);
3089 }
3090 break;
3091 }
3092 /* Consume the rest of the macro line */
3093 do {
3094 tok = mpeek(state, index);
3095 meat(state, index, tok);
3096 } while(tok != TOK_EOF);
3097 return;
3098}
3099
3100static void token(struct compile_state *state, int index)
3101{
3102 struct file_state *file;
3103 struct token *tk;
3104 int rescan;
3105
3106 tk = &state->token[index];
3107 next_token(state, index);
3108 do {
3109 rescan = 0;
3110 file = state->file;
3111 if (tk->tok == TOK_EOF && file->prev) {
3112 state->file = file->prev;
3113 /* file->basename is used keep it */
3114 xfree(file->dirname);
3115 xfree(file->buf);
3116 xfree(file);
3117 next_token(state, index);
3118 rescan = 1;
3119 }
3120 else if (tk->tok == TOK_MACRO) {
3121 preprocess(state, index);
3122 rescan = 1;
3123 }
3124 else if (tk->ident && tk->ident->sym_define) {
3125 compile_macro(state, tk);
3126 next_token(state, index);
3127 rescan = 1;
3128 }
3129 else if (state->if_value < 0) {
3130 next_token(state, index);
3131 rescan = 1;
3132 }
3133 } while(rescan);
3134}
3135
3136static int peek(struct compile_state *state)
3137{
3138 if (state->token[1].tok == -1) {
3139 token(state, 1);
3140 }
3141 return state->token[1].tok;
3142}
3143
3144static int peek2(struct compile_state *state)
3145{
3146 if (state->token[1].tok == -1) {
3147 token(state, 1);
3148 }
3149 if (state->token[2].tok == -1) {
3150 token(state, 2);
3151 }
3152 return state->token[2].tok;
3153}
3154
Eric Biederman0babc1c2003-05-09 02:39:00 +00003155static void eat(struct compile_state *state, int tok)
Eric Biedermanb138ac82003-04-22 18:44:01 +00003156{
3157 int next_tok;
3158 int i;
3159 next_tok = peek(state);
3160 if (next_tok != tok) {
3161 const char *name1, *name2;
3162 name1 = tokens[next_tok];
3163 name2 = "";
3164 if (next_tok == TOK_IDENT) {
3165 name2 = state->token[1].ident->name;
3166 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00003167 error(state, 0, "\tfound %s %s expected %s",
3168 name1, name2 ,tokens[tok]);
Eric Biedermanb138ac82003-04-22 18:44:01 +00003169 }
3170 /* Free the old token value */
3171 if (state->token[0].str_len) {
3172 xfree((void *)(state->token[0].val.str));
3173 }
3174 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3175 state->token[i] = state->token[i + 1];
3176 }
3177 memset(&state->token[i], 0, sizeof(state->token[i]));
3178 state->token[i].tok = -1;
3179}
Eric Biedermanb138ac82003-04-22 18:44:01 +00003180
3181#warning "FIXME do not hardcode the include paths"
3182static 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",
3186 0
3187};
3188
3189static void compile_file(struct compile_state *state, char *filename, int local)
3190{
3191 char cwd[4096];
3192 char *subdir, *base;
3193 int subdir_len;
3194 struct file_state *file;
3195 char *basename;
3196 file = xmalloc(sizeof(*file), "file_state");
3197
3198 base = strrchr(filename, '/');
3199 subdir = filename;
3200 if (base != 0) {
3201 subdir_len = base - filename;
3202 base++;
3203 }
3204 else {
3205 base = filename;
3206 subdir_len = 0;
3207 }
3208 basename = xmalloc(strlen(base) +1, "basename");
3209 strcpy(basename, base);
3210 file->basename = basename;
3211
3212 if (getcwd(cwd, sizeof(cwd)) == 0) {
3213 die("cwd buffer to small");
3214 }
3215
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';
3220 }
3221 else {
3222 char *dir;
3223 int dirlen;
3224 char **path;
3225 /* Find the appropriate directory... */
3226 dir = 0;
3227 if (!state->file && exists(cwd, filename)) {
3228 dir = cwd;
3229 }
3230 if (local && state->file && exists(state->file->dirname, filename)) {
3231 dir = state->file->dirname;
3232 }
3233 for(path = include_paths; !dir && *path; path++) {
3234 if (exists(*path, filename)) {
3235 dir = *path;
3236 }
3237 }
3238 if (!dir) {
3239 error(state, 0, "Cannot find `%s'\n", filename);
3240 }
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';
3247 }
3248 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3249 xchdir(cwd);
3250
3251 file->pos = file->buf;
3252 file->line_start = file->pos;
3253 file->line = 1;
3254
3255 file->prev = state->file;
3256 state->file = file;
3257
3258 process_trigraphs(state);
3259 splice_lines(state);
3260}
3261
Eric Biederman0babc1c2003-05-09 02:39:00 +00003262/* Type helper functions */
Eric Biedermanb138ac82003-04-22 18:44:01 +00003263
3264static struct type *new_type(
3265 unsigned int type, struct type *left, struct type *right)
3266{
3267 struct type *result;
3268 result = xmalloc(sizeof(*result), "type");
3269 result->type = type;
3270 result->left = left;
3271 result->right = right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00003272 result->field_ident = 0;
3273 result->type_ident = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00003274 return result;
3275}
3276
3277static struct type *clone_type(unsigned int specifiers, struct type *old)
3278{
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;
3284 return result;
3285}
3286
3287#define SIZEOF_SHORT 2
3288#define SIZEOF_INT 4
3289#define SIZEOF_LONG (sizeof(long_t))
3290
3291#define ALIGNOF_SHORT 2
3292#define ALIGNOF_INT 4
3293#define ALIGNOF_LONG (sizeof(long_t))
3294
3295#define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3296#define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3297static inline ulong_t mask_uint(ulong_t x)
3298{
3299 if (SIZEOF_INT < SIZEOF_LONG) {
3300 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3301 x &= mask;
3302 }
3303 return x;
3304}
3305#define MASK_UINT(X) (mask_uint(X))
3306#define MASK_ULONG(X) (X)
3307
Eric Biedermanb138ac82003-04-22 18:44:01 +00003308static struct type void_type = { .type = TYPE_VOID };
3309static struct type char_type = { .type = TYPE_CHAR };
3310static struct type uchar_type = { .type = TYPE_UCHAR };
3311static struct type short_type = { .type = TYPE_SHORT };
3312static struct type ushort_type = { .type = TYPE_USHORT };
3313static struct type int_type = { .type = TYPE_INT };
3314static struct type uint_type = { .type = TYPE_UINT };
3315static struct type long_type = { .type = TYPE_LONG };
3316static struct type ulong_type = { .type = TYPE_ULONG };
3317
3318static struct triple *variable(struct compile_state *state, struct type *type)
3319{
3320 struct triple *result;
3321 if ((type->type & STOR_MASK) != STOR_PERM) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00003322 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3323 result = triple(state, OP_ADECL, type, 0, 0);
3324 } else {
3325 struct type *field;
3326 struct triple **vector;
3327 ulong_t index;
3328 result = new_triple(state, OP_VAL_VEC, type, -1);
3329 vector = &result->param[0];
3330
3331 field = type->left;
3332 index = 0;
3333 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3334 vector[index] = variable(state, field->left);
3335 field = field->right;
3336 index++;
3337 }
3338 vector[index] = variable(state, field);
3339 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00003340 }
3341 else {
3342 result = triple(state, OP_SDECL, type, 0, 0);
3343 }
3344 return result;
3345}
3346
3347static void stor_of(FILE *fp, struct type *type)
3348{
3349 switch(type->type & STOR_MASK) {
3350 case STOR_AUTO:
3351 fprintf(fp, "auto ");
3352 break;
3353 case STOR_STATIC:
3354 fprintf(fp, "static ");
3355 break;
3356 case STOR_EXTERN:
3357 fprintf(fp, "extern ");
3358 break;
3359 case STOR_REGISTER:
3360 fprintf(fp, "register ");
3361 break;
3362 case STOR_TYPEDEF:
3363 fprintf(fp, "typedef ");
3364 break;
3365 case STOR_INLINE:
3366 fprintf(fp, "inline ");
3367 break;
3368 }
3369}
3370static void qual_of(FILE *fp, struct type *type)
3371{
3372 if (type->type & QUAL_CONST) {
3373 fprintf(fp, " const");
3374 }
3375 if (type->type & QUAL_VOLATILE) {
3376 fprintf(fp, " volatile");
3377 }
3378 if (type->type & QUAL_RESTRICT) {
3379 fprintf(fp, " restrict");
3380 }
3381}
Eric Biederman0babc1c2003-05-09 02:39:00 +00003382
Eric Biedermanb138ac82003-04-22 18:44:01 +00003383static void name_of(FILE *fp, struct type *type)
3384{
3385 stor_of(fp, type);
3386 switch(type->type & TYPE_MASK) {
3387 case TYPE_VOID:
3388 fprintf(fp, "void");
3389 qual_of(fp, type);
3390 break;
3391 case TYPE_CHAR:
3392 fprintf(fp, "signed char");
3393 qual_of(fp, type);
3394 break;
3395 case TYPE_UCHAR:
3396 fprintf(fp, "unsigned char");
3397 qual_of(fp, type);
3398 break;
3399 case TYPE_SHORT:
3400 fprintf(fp, "signed short");
3401 qual_of(fp, type);
3402 break;
3403 case TYPE_USHORT:
3404 fprintf(fp, "unsigned short");
3405 qual_of(fp, type);
3406 break;
3407 case TYPE_INT:
3408 fprintf(fp, "signed int");
3409 qual_of(fp, type);
3410 break;
3411 case TYPE_UINT:
3412 fprintf(fp, "unsigned int");
3413 qual_of(fp, type);
3414 break;
3415 case TYPE_LONG:
3416 fprintf(fp, "signed long");
3417 qual_of(fp, type);
3418 break;
3419 case TYPE_ULONG:
3420 fprintf(fp, "unsigned long");
3421 qual_of(fp, type);
3422 break;
3423 case TYPE_POINTER:
3424 name_of(fp, type->left);
3425 fprintf(fp, " * ");
3426 qual_of(fp, type);
3427 break;
3428 case TYPE_PRODUCT:
3429 case TYPE_OVERLAP:
3430 name_of(fp, type->left);
3431 fprintf(fp, ", ");
3432 name_of(fp, type->right);
3433 break;
3434 case TYPE_ENUM:
Eric Biederman0babc1c2003-05-09 02:39:00 +00003435 fprintf(fp, "enum %s", type->type_ident->name);
Eric Biedermanb138ac82003-04-22 18:44:01 +00003436 qual_of(fp, type);
3437 break;
3438 case TYPE_STRUCT:
Eric Biederman0babc1c2003-05-09 02:39:00 +00003439 fprintf(fp, "struct %s", type->type_ident->name);
Eric Biedermanb138ac82003-04-22 18:44:01 +00003440 qual_of(fp, type);
3441 break;
3442 case TYPE_FUNCTION:
3443 {
3444 name_of(fp, type->left);
3445 fprintf(fp, " (*)(");
3446 name_of(fp, type->right);
3447 fprintf(fp, ")");
3448 break;
3449 }
3450 case TYPE_ARRAY:
3451 name_of(fp, type->left);
3452 fprintf(fp, " [%ld]", type->elements);
3453 break;
3454 default:
3455 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3456 break;
3457 }
3458}
3459
3460static size_t align_of(struct compile_state *state, struct type *type)
3461{
3462 size_t align;
3463 align = 0;
3464 switch(type->type & TYPE_MASK) {
3465 case TYPE_VOID:
3466 align = 1;
3467 break;
3468 case TYPE_CHAR:
3469 case TYPE_UCHAR:
3470 align = 1;
3471 break;
3472 case TYPE_SHORT:
3473 case TYPE_USHORT:
3474 align = ALIGNOF_SHORT;
3475 break;
3476 case TYPE_INT:
3477 case TYPE_UINT:
3478 case TYPE_ENUM:
3479 align = ALIGNOF_INT;
3480 break;
3481 case TYPE_LONG:
3482 case TYPE_ULONG:
3483 case TYPE_POINTER:
3484 align = ALIGNOF_LONG;
3485 break;
3486 case TYPE_PRODUCT:
3487 case TYPE_OVERLAP:
3488 {
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;
3493 break;
3494 }
3495 case TYPE_ARRAY:
3496 align = align_of(state, type->left);
3497 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +00003498 case TYPE_STRUCT:
3499 align = align_of(state, type->left);
3500 break;
Eric Biedermanb138ac82003-04-22 18:44:01 +00003501 default:
3502 error(state, 0, "alignof not yet defined for type\n");
3503 break;
3504 }
3505 return align;
3506}
3507
3508static size_t size_of(struct compile_state *state, struct type *type)
3509{
3510 size_t size;
3511 size = 0;
3512 switch(type->type & TYPE_MASK) {
3513 case TYPE_VOID:
3514 size = 0;
3515 break;
3516 case TYPE_CHAR:
3517 case TYPE_UCHAR:
3518 size = 1;
3519 break;
3520 case TYPE_SHORT:
3521 case TYPE_USHORT:
3522 size = SIZEOF_SHORT;
3523 break;
3524 case TYPE_INT:
3525 case TYPE_UINT:
3526 case TYPE_ENUM:
3527 size = SIZEOF_INT;
3528 break;
3529 case TYPE_LONG:
3530 case TYPE_ULONG:
3531 case TYPE_POINTER:
3532 size = SIZEOF_LONG;
3533 break;
3534 case TYPE_PRODUCT:
3535 {
3536 size_t align, pad;
3537 size = size_of(state, type->left);
3538 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3539 type = type->right;
3540 align = align_of(state, type->left);
3541 pad = align - (size % align);
3542 size = size + pad + size_of(state, type->left);
3543 }
3544 align = align_of(state, type->right);
3545 pad = align - (size % align);
3546 size = size + pad + sizeof(type->right);
3547 break;
3548 }
3549 case TYPE_OVERLAP:
3550 {
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;
3555 break;
3556 }
3557 case TYPE_ARRAY:
3558 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3559 internal_error(state, 0, "Invalid array type");
3560 } else {
3561 size = size_of(state, type->left) * type->elements;
3562 }
3563 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +00003564 case TYPE_STRUCT:
3565 size = size_of(state, type->left);
3566 break;
Eric Biedermanb138ac82003-04-22 18:44:01 +00003567 default:
3568 error(state, 0, "sizeof not yet defined for type\n");
3569 break;
3570 }
3571 return size;
3572}
3573
Eric Biederman0babc1c2003-05-09 02:39:00 +00003574static size_t field_offset(struct compile_state *state,
3575 struct type *type, struct hash_entry *field)
3576{
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");
3580 }
3581 size = 0;
3582 type = type->left;
3583 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3584 if (type->left->field_ident == field) {
3585 type = type->left;
3586 }
3587 size += size_of(state, type->left);
3588 type = type->right;
3589 align = align_of(state, type->left);
3590 pad = align - (size % align);
3591 size += pad;
3592 }
3593 if (type->field_ident != field) {
3594 internal_error(state, 0, "field_offset: member %s not present",
3595 field->name);
3596 }
3597 return size;
3598}
3599
3600static struct type *field_type(struct compile_state *state,
3601 struct type *type, struct hash_entry *field)
3602{
3603 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3604 internal_error(state, 0, "field_type only works on structures");
3605 }
3606 type = type->left;
3607 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3608 if (type->left->field_ident == field) {
3609 type = type->left;
3610 break;
3611 }
3612 type = type->right;
3613 }
3614 if (type->field_ident != field) {
3615 internal_error(state, 0, "field_type: member %s not present",
3616 field->name);
3617 }
3618 return type;
3619}
3620
3621static struct triple *struct_field(struct compile_state *state,
3622 struct triple *decl, struct hash_entry *field)
3623{
3624 struct triple **vector;
3625 struct type *type;
3626 ulong_t index;
3627 type = decl->type;
3628 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3629 return decl;
3630 }
3631 if (decl->op != OP_VAL_VEC) {
3632 internal_error(state, 0, "Invalid struct variable");
3633 }
3634 if (!field) {
3635 internal_error(state, 0, "Missing structure field");
3636 }
3637 type = type->left;
3638 vector = &RHS(decl, 0);
3639 index = 0;
3640 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3641 if (type->left->field_ident == field) {
3642 type = type->left;
3643 break;
3644 }
3645 index += 1;
3646 type = type->right;
3647 }
3648 if (type->field_ident != field) {
3649 internal_error(state, 0, "field %s not found?", field->name);
3650 }
3651 return vector[index];
3652}
3653
Eric Biedermanb138ac82003-04-22 18:44:01 +00003654static void arrays_complete(struct compile_state *state, struct type *type)
3655{
3656 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3657 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3658 error(state, 0, "array size not specified");
3659 }
3660 arrays_complete(state, type->left);
3661 }
3662}
3663
3664static unsigned int do_integral_promotion(unsigned int type)
3665{
3666 type &= TYPE_MASK;
3667 if (TYPE_INTEGER(type) &&
3668 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3669 type = TYPE_INT;
3670 }
3671 return type;
3672}
3673
3674static unsigned int do_arithmetic_conversion(
3675 unsigned int left, unsigned int right)
3676{
3677 left &= TYPE_MASK;
3678 right &= TYPE_MASK;
3679 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3680 return TYPE_LDOUBLE;
3681 }
3682 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3683 return TYPE_DOUBLE;
3684 }
3685 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3686 return TYPE_FLOAT;
3687 }
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) {
3692 return left;
3693 }
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;
3697 }
3698 /* If the signed type can hold everything use it */
3699 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3700 return left;
3701 }
3702 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3703 return right;
3704 }
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);
3708 }
3709 else {
3710 return TYPE_MKUNSIGNED(right);
3711 }
3712}
3713
3714/* see if two types are the same except for qualifiers */
3715static int equiv_types(struct type *left, struct type *right)
3716{
3717 unsigned int type;
3718 /* Error if the basic types do not match */
3719 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3720 return 0;
3721 }
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)) {
3725 return 1;
3726 }
3727 /* If it is a pointer type recurse and keep testing */
3728 if (type == TYPE_POINTER) {
3729 return equiv_types(left->left, right->left);
3730 }
3731 else if (type == TYPE_ARRAY) {
3732 return (left->elements == right->elements) &&
3733 equiv_types(left->left, right->left);
3734 }
3735 /* test for struct/union equality */
3736 else if (type == TYPE_STRUCT) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00003737 return left->type_ident == right->type_ident;
Eric Biedermanb138ac82003-04-22 18:44:01 +00003738 }
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);
3743 }
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);
3748 }
3749 /* We should see TYPE_OVERLAP */
3750 else {
3751 return 0;
3752 }
3753}
3754
3755static int equiv_ptrs(struct type *left, struct type *right)
3756{
3757 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3758 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3759 return 0;
3760 }
3761 return equiv_types(left->left, right->left);
3762}
3763
3764static struct type *compatible_types(struct type *left, struct type *right)
3765{
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)) {
3770 return 0;
3771 }
3772 type = left->type & TYPE_MASK;
3773 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3774 result = 0;
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);
3778 }
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);
3782 if (result) {
3783 result = new_type(qual_type, result, 0);
3784 }
3785 }
3786 /* test for struct/union equality */
3787 else if (type == TYPE_STRUCT) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00003788 if (left->type_ident == right->type_ident) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00003789 result = left;
3790 }
3791 }
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);
3797 if (lf && rf) {
3798 result = new_type(qual_type, lf, rf);
3799 }
3800 }
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);
3806 if (lf && rf) {
3807 result = new_type(qual_type, lf, rf);
3808 }
3809 }
3810 else {
3811 /* Nothing else is compatible */
3812 }
3813 return result;
3814}
3815
3816static struct type *compatible_ptrs(struct type *left, struct type *right)
3817{
3818 struct type *result;
3819 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3820 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3821 return 0;
3822 }
3823 result = compatible_types(left->left, right->left);
3824 if (result) {
3825 unsigned int qual_type;
3826 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3827 result = new_type(qual_type, result, 0);
3828 }
3829 return result;
3830
3831}
3832static struct triple *integral_promotion(
3833 struct compile_state *state, struct triple *def)
3834{
3835 struct type *type;
3836 type = def->type;
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.
3840 */
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);
3847 }
3848 }
3849 return def;
3850}
3851
3852
3853static void arithmetic(struct compile_state *state, struct triple *def)
3854{
3855 if (!TYPE_ARITHMETIC(def->type->type)) {
3856 error(state, def, "arithmetic type expexted");
3857 }
3858}
3859
3860static void ptr_arithmetic(struct compile_state *state, struct triple *def)
3861{
3862 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
3863 error(state, def, "pointer or arithmetic type expected");
3864 }
3865}
3866
3867static int is_integral(struct triple *ins)
3868{
3869 return TYPE_INTEGER(ins->type->type);
3870}
3871
3872static void integral(struct compile_state *state, struct triple *def)
3873{
3874 if (!is_integral(def)) {
3875 error(state, 0, "integral type expected");
3876 }
3877}
3878
3879
3880static void bool(struct compile_state *state, struct triple *def)
3881{
3882 if (!TYPE_ARITHMETIC(def->type->type) &&
3883 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
3884 error(state, 0, "arithmetic or pointer type expected");
3885 }
3886}
3887
3888static int is_signed(struct type *type)
3889{
3890 return !!TYPE_SIGNED(type->type);
3891}
3892
Eric Biederman0babc1c2003-05-09 02:39:00 +00003893/* Is this value located in a register otherwise it must be in memory */
3894static int is_in_reg(struct compile_state *state, struct triple *def)
3895{
3896 int in_reg;
3897 if (def->op == OP_ADECL) {
3898 in_reg = 1;
3899 }
3900 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
3901 in_reg = 0;
3902 }
3903 else if (def->op == OP_VAL_VEC) {
3904 in_reg = is_in_reg(state, RHS(def, 0));
3905 }
3906 else if (def->op == OP_DOT) {
3907 in_reg = is_in_reg(state, RHS(def, 0));
3908 }
3909 else {
3910 internal_error(state, 0, "unknown expr storage location");
3911 in_reg = -1;
3912 }
3913 return in_reg;
3914}
3915
Eric Biedermanb138ac82003-04-22 18:44:01 +00003916/* Is this a stable variable location otherwise it must be a temporary */
Eric Biederman0babc1c2003-05-09 02:39:00 +00003917static int is_stable(struct compile_state *state, struct triple *def)
Eric Biedermanb138ac82003-04-22 18:44:01 +00003918{
3919 int ret;
3920 ret = 0;
3921 if (!def) {
3922 return 0;
3923 }
3924 if ((def->op == OP_ADECL) ||
3925 (def->op == OP_SDECL) ||
3926 (def->op == OP_DEREF) ||
3927 (def->op == OP_BLOBCONST)) {
3928 ret = 1;
3929 }
3930 else if (def->op == OP_DOT) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00003931 ret = is_stable(state, RHS(def, 0));
3932 }
3933 else if (def->op == OP_VAL_VEC) {
3934 struct triple **vector;
3935 ulong_t i;
3936 ret = 1;
3937 vector = &RHS(def, 0);
3938 for(i = 0; i < def->type->elements; i++) {
3939 if (!is_stable(state, vector[i])) {
3940 ret = 0;
3941 break;
3942 }
3943 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00003944 }
3945 return ret;
3946}
3947
Eric Biederman0babc1c2003-05-09 02:39:00 +00003948static int is_lvalue(struct compile_state *state, struct triple *def)
Eric Biedermanb138ac82003-04-22 18:44:01 +00003949{
3950 int ret;
3951 ret = 1;
3952 if (!def) {
3953 return 0;
3954 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00003955 if (!is_stable(state, def)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00003956 return 0;
3957 }
3958 if (def->type->type & QUAL_CONST) {
3959 ret = 0;
3960 }
3961 else if (def->op == OP_DOT) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00003962 ret = is_lvalue(state, RHS(def, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00003963 }
3964 return ret;
3965}
3966
3967static void lvalue(struct compile_state *state, struct triple *def)
3968{
3969 if (!def) {
3970 internal_error(state, def, "nothing where lvalue expected?");
3971 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00003972 if (!is_lvalue(state, def)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00003973 error(state, def, "lvalue expected");
3974 }
3975}
3976
3977static int is_pointer(struct triple *def)
3978{
3979 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
3980}
3981
3982static void pointer(struct compile_state *state, struct triple *def)
3983{
3984 if (!is_pointer(def)) {
3985 error(state, def, "pointer expected");
3986 }
3987}
3988
3989static struct triple *int_const(
3990 struct compile_state *state, struct type *type, ulong_t value)
3991{
3992 struct triple *result;
3993 switch(type->type & TYPE_MASK) {
3994 case TYPE_CHAR:
3995 case TYPE_INT: case TYPE_UINT:
3996 case TYPE_LONG: case TYPE_ULONG:
3997 break;
3998 default:
3999 internal_error(state, 0, "constant for unkown type");
4000 }
4001 result = triple(state, OP_INTCONST, type, 0, 0);
4002 result->u.cval = value;
4003 return result;
4004}
4005
4006
Eric Biederman0babc1c2003-05-09 02:39:00 +00004007static struct triple *do_mk_addr_expr(struct compile_state *state,
4008 struct triple *expr, struct type *type, ulong_t offset)
Eric Biedermanb138ac82003-04-22 18:44:01 +00004009{
4010 struct triple *result;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004011 lvalue(state, expr);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004012
4013 result = 0;
4014 if (expr->op == OP_ADECL) {
4015 error(state, expr, "address of auto variables not supported");
4016 }
4017 else if (expr->op == OP_SDECL) {
4018 result = triple(state, OP_ADDRCONST, type, expr, 0);
4019 result->u.cval = offset;
4020 }
4021 else if (expr->op == OP_DEREF) {
4022 result = triple(state, OP_ADD, type,
Eric Biederman0babc1c2003-05-09 02:39:00 +00004023 RHS(expr, 0),
Eric Biedermanb138ac82003-04-22 18:44:01 +00004024 int_const(state, &ulong_type, offset));
4025 }
4026 return result;
4027}
4028
Eric Biederman0babc1c2003-05-09 02:39:00 +00004029static struct triple *mk_addr_expr(
4030 struct compile_state *state, struct triple *expr, ulong_t offset)
4031{
4032 struct type *type;
4033
4034 type = new_type(
4035 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4036 expr->type, 0);
4037
4038 return do_mk_addr_expr(state, expr, type, offset);
4039}
4040
Eric Biedermanb138ac82003-04-22 18:44:01 +00004041static struct triple *mk_deref_expr(
4042 struct compile_state *state, struct triple *expr)
4043{
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)) {
4048 error(state, 0,
4049 "Only pointer and arithmetic values can be dereferenced");
4050 }
4051 return triple(state, OP_DEREF, base_type, expr, 0);
4052}
4053
Eric Biederman0babc1c2003-05-09 02:39:00 +00004054static struct triple *deref_field(
4055 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4056{
4057 struct triple *result;
4058 struct type *type, *member;
4059 if (!field) {
4060 internal_error(state, 0, "No field passed to deref_field");
4061 }
4062 result = 0;
4063 type = expr->type;
4064 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4065 error(state, 0, "request for member %s in something not a struct or union",
4066 field->name);
4067 }
4068 member = type->left;
4069 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4070 if (member->left->field_ident == field) {
4071 member = member->left;
4072 break;
4073 }
4074 member = member->right;
4075 }
4076 if (member->field_ident != field) {
4077 error(state, 0, "%s is not a member", field->name);
4078 }
4079 if ((type->type & STOR_MASK) == STOR_PERM) {
4080 /* Do the pointer arithmetic to get a deref the field */
4081 ulong_t offset;
4082 offset = field_offset(state, type, field);
4083 result = do_mk_addr_expr(state, expr, member, offset);
4084 result = mk_deref_expr(state, result);
4085 }
4086 else {
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;
4091 }
4092 return result;
4093}
4094
Eric Biedermanb138ac82003-04-22 18:44:01 +00004095static struct triple *read_expr(struct compile_state *state, struct triple *def)
4096{
4097 int op;
4098 if (!def) {
4099 return 0;
4100 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004101 if (!is_stable(state, def)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00004102 return def;
4103 }
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) {
4107 struct type *type;
4108 type = new_type(
4109 TYPE_POINTER | (def->type->type & QUAL_MASK),
4110 def->type->left, 0);
4111 return triple(state, OP_ADDRCONST, type, def, 0);
4112 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004113 if (is_in_reg(state, def)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00004114 op = OP_READ;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004115 } else {
Eric Biedermanb138ac82003-04-22 18:44:01 +00004116 op = OP_LOAD;
4117 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004118 return triple(state, op, def->type, def, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004119}
4120
4121static void write_compatible(struct compile_state *state,
4122 struct type *dest, struct type *rval)
4123{
4124 int compatible = 0;
4125 /* Both operands have arithmetic type */
4126 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4127 compatible = 1;
4128 }
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))) {
4134 compatible = 1;
4135 }
4136 /* If both types are the same without qualifiers we are good */
4137 else if (equiv_ptrs(dest, rval)) {
4138 compatible = 1;
4139 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004140 /* 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)) {
4144 compatible = 1;
4145 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004146 if (!compatible) {
4147 error(state, 0, "Incompatible types in assignment");
4148 }
4149}
4150
4151static struct triple *write_expr(
4152 struct compile_state *state, struct triple *dest, struct triple *rval)
4153{
4154 struct triple *def;
4155 int op;
4156
4157 def = 0;
4158 if (!rval) {
4159 internal_error(state, 0, "missing rval");
4160 }
4161
4162 if (rval->op == OP_LIST) {
4163 internal_error(state, 0, "expression of type OP_LIST?");
4164 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004165 if (!is_lvalue(state, dest)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00004166 internal_error(state, 0, "writing to a non lvalue?");
4167 }
4168
4169 write_compatible(state, dest->type, rval->type);
4170
4171 /* Now figure out which assignment operator to use */
4172 op = -1;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004173 if (is_in_reg(state, dest)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00004174 op = OP_WRITE;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004175 } else {
Eric Biedermanb138ac82003-04-22 18:44:01 +00004176 op = OP_STORE;
4177 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004178 def = triple(state, op, dest->type, dest, rval);
4179 return def;
4180}
4181
4182static struct triple *init_expr(
4183 struct compile_state *state, struct triple *dest, struct triple *rval)
4184{
4185 struct triple *def;
4186
4187 def = 0;
4188 if (!rval) {
4189 internal_error(state, 0, "missing rval");
4190 }
4191 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4192 rval = read_expr(state, rval);
4193 def = write_expr(state, dest, rval);
4194 }
4195 else {
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;
4201 }
4202 }
4203 if (!equiv_types(dest->type, rval->type)) {
4204 error(state, 0, "Incompatible types in inializer");
4205 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004206 MISC(dest, 0) = rval;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004207 }
4208 return def;
4209}
4210
4211struct type *arithmetic_result(
4212 struct compile_state *state, struct triple *left, struct triple *right)
4213{
4214 struct type *type;
4215 /* Sanity checks to ensure I am working with arithmetic types */
4216 arithmetic(state, left);
4217 arithmetic(state, right);
4218 type = new_type(
4219 do_arithmetic_conversion(
4220 left->type->type,
4221 right->type->type), 0, 0);
4222 return type;
4223}
4224
4225struct type *ptr_arithmetic_result(
4226 struct compile_state *state, struct triple *left, struct triple *right)
4227{
4228 struct type *type;
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);
4235 }
4236 else if (TYPE_PTR(left->type->type)) {
4237 type = left->type;
4238 }
4239 else {
4240 internal_error(state, 0, "huh?");
4241 type = 0;
4242 }
4243 return type;
4244}
4245
4246
4247/* boolean helper function */
4248
4249static struct triple *ltrue_expr(struct compile_state *state,
4250 struct triple *expr)
4251{
4252 switch(expr->op) {
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 */
4257 break;
4258 default:
4259 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4260 break;
4261 }
4262 return expr;
4263}
4264
4265static struct triple *lfalse_expr(struct compile_state *state,
4266 struct triple *expr)
4267{
4268 return triple(state, OP_LFALSE, &int_type, expr, 0);
4269}
4270
4271static struct triple *cond_expr(
4272 struct compile_state *state,
4273 struct triple *test, struct triple *left, struct triple *right)
4274{
4275 struct triple *def;
4276 struct type *result_type;
4277 unsigned int left_type, right_type;
4278 bool(state, test);
4279 left_type = left->type->type;
4280 right_type = right->type->type;
4281 result_type = 0;
4282 /* Both operands have arithmetic type */
4283 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4284 result_type = arithmetic_result(state, left, right);
4285 }
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;
4290 }
4291 /* pointers to the same type... */
4292 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4293 ;
4294 }
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;
4300 }
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;
4306 }
4307 if (!result_type) {
4308 error(state, 0, "Incompatible types in conditional expression");
4309 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004310 def = new_triple(state, OP_COND, result_type, 3);
4311 def->param[0] = test;
4312 def->param[1] = left;
4313 def->param[2] = right;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004314 return def;
4315}
4316
4317
Eric Biederman0babc1c2003-05-09 02:39:00 +00004318static int expr_depth(struct compile_state *state, struct triple *ins)
Eric Biedermanb138ac82003-04-22 18:44:01 +00004319{
4320 int count;
4321 count = 0;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004322 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4323 count = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004324 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004325 else if (ins->op == OP_DEREF) {
4326 count = expr_depth(state, RHS(ins, 0)) - 1;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004327 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004328 else if (ins->op == OP_VAL) {
4329 count = expr_depth(state, RHS(ins, 0)) - 1;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004330 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004331 else if (ins->op == OP_COMMA) {
4332 int ldepth, rdepth;
4333 ldepth = expr_depth(state, RHS(ins, 0));
4334 rdepth = expr_depth(state, RHS(ins, 1));
4335 count = (ldepth >= rdepth)? ldepth : rdepth;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004336 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004337 else if (ins->op == OP_CALL) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00004338 /* Don't figure the depth of a call just guess it is huge */
4339 count = 1000;
4340 }
4341 else {
4342 struct triple **expr;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004343 expr = triple_rhs(state, ins, 0);
4344 for(;expr; expr = triple_rhs(state, ins, expr)) {
4345 if (*expr) {
4346 int depth;
4347 depth = expr_depth(state, *expr);
4348 if (depth > count) {
4349 count = depth;
4350 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004351 }
4352 }
4353 }
4354 return count + 1;
4355}
4356
4357static struct triple *flatten(
4358 struct compile_state *state, struct triple *first, struct triple *ptr);
4359
Eric Biederman0babc1c2003-05-09 02:39:00 +00004360static struct triple *flatten_generic(
Eric Biedermanb138ac82003-04-22 18:44:01 +00004361 struct compile_state *state, struct triple *first, struct triple *ptr)
4362{
Eric Biederman0babc1c2003-05-09 02:39:00 +00004363 struct rhs_vector {
4364 int depth;
4365 struct triple **ins;
4366 } vector[MAX_RHS];
4367 int i, rhs, lhs;
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",
Eric Biedermanb138ac82003-04-22 18:44:01 +00004373 ptr->op, tops(ptr->op));
4374 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004375 /* 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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004379 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004380 /* Selection sort the rhs */
4381 for(i = 0; i < rhs; i++) {
4382 int j, max = i;
4383 for(j = i + 1; j < rhs; j++ ) {
4384 if (vector[j].depth > vector[max].depth) {
4385 max = j;
4386 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004387 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004388 if (max != i) {
4389 struct rhs_vector tmp;
4390 tmp = vector[i];
4391 vector[i] = vector[max];
4392 vector[max] = tmp;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004393 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004394 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004395 /* 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);
4399 }
4400
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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004406 }
4407 return ptr;
4408}
4409
4410static struct triple *flatten_land(
4411 struct compile_state *state, struct triple *first, struct triple *ptr)
4412{
4413 struct triple *left, *right;
4414 struct triple *val, *test, *jmp, *label1, *end;
4415
4416 /* Find the triples */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004417 left = RHS(ptr, 0);
4418 right = RHS(ptr, 1);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004419
4420 /* Generate the needed triples */
4421 end = label(state);
4422
4423 /* Thread the triples together */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004424 val = flatten(state, first, variable(state, ptr->type));
4425 left = flatten(state, first, write_expr(state, val, left));
4426 test = flatten(state, first,
Eric Biedermanb138ac82003-04-22 18:44:01 +00004427 lfalse_expr(state, read_expr(state, val)));
Eric Biederman0babc1c2003-05-09 02:39:00 +00004428 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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004432
4433 /* Now give the caller something to chew on */
4434 return read_expr(state, val);
4435}
4436
4437static struct triple *flatten_lor(
4438 struct compile_state *state, struct triple *first, struct triple *ptr)
4439{
4440 struct triple *left, *right;
4441 struct triple *val, *jmp, *label1, *end;
4442
4443 /* Find the triples */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004444 left = RHS(ptr, 0);
4445 right = RHS(ptr, 1);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004446
4447 /* Generate the needed triples */
4448 end = label(state);
4449
4450 /* Thread the triples together */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004451 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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004457
4458
4459 /* Now give the caller something to chew on */
4460 return read_expr(state, val);
4461}
4462
4463static struct triple *flatten_cond(
4464 struct compile_state *state, struct triple *first, struct triple *ptr)
4465{
4466 struct triple *test, *left, *right;
4467 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004468
4469 /* Find the triples */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004470 test = RHS(ptr, 0);
4471 left = RHS(ptr, 1);
4472 right = RHS(ptr, 2);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004473
4474 /* Generate the needed triples */
4475 end = label(state);
4476 middle = label(state);
4477
4478 /* Thread the triples together */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004479 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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004490
4491 /* Now give the caller something to chew on */
4492 return read_expr(state, val);
4493}
4494
4495struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4496{
4497 struct triple *nfunc;
4498 struct triple *nfirst, *ofirst;
4499 struct triple *new, *old;
4500
4501#if 0
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");
4507#endif
4508
4509 /* Make a new copy of the old function */
4510 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4511 nfirst = 0;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004512 ofirst = old = RHS(ofunc, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004513 do {
4514 struct triple *new;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004515 int old_rhs;
4516 old_rhs = TRIPLE_RHS(old->sizes);
4517 new = alloc_triple(state, old->op, old->type, old_rhs,
Eric Biedermanb138ac82003-04-22 18:44:01 +00004518 old->filename, old->line, old->col);
4519 if (IS_CONST_OP(new->op)) {
4520 memcpy(&new->u, &old->u, sizeof(new->u));
4521 }
4522#warning "WISHLIST find a way to handle SDECL without a special case..."
Eric Biederman0babc1c2003-05-09 02:39:00 +00004523 /* The problem is that I don't flatten the misc field,
4524 * so I cannot look the value the misc field should have.
4525 */
Eric Biedermanb138ac82003-04-22 18:44:01 +00004526 else if (new->op == OP_SDECL) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00004527 MISC(new, 0) = MISC(old, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004528 }
4529 if (!nfirst) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00004530 RHS(nfunc, 0) = nfirst = new;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004531 }
4532 else {
4533 insert_triple(state, nfirst, new);
4534 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004535 new->id |= TRIPLE_FLAG_FLATTENED;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004536
4537 /* During the copy remember new as user of old */
4538 use_triple(old, new);
4539
4540 /* Populate the return type if present */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004541 if (old == MISC(ofunc, 0)) {
4542 MISC(nfunc, 0) = new;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004543 }
4544 old = old->next;
4545 } while(old != ofirst);
4546
4547 /* Make a second pass to fix up any unresolved references */
4548 old = ofirst;
4549 new = nfirst;
4550 do {
Eric Biederman0babc1c2003-05-09 02:39:00 +00004551 struct triple **oexpr, **nexpr;
4552 int count, i;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004553 /* Lookup where the copy is, to join pointers */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004554 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?");
4562 }
4563 use_triple(*nexpr, new);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004564 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004565 if (!*nexpr && *oexpr) {
4566 internal_error(state, 0, "Could not copy %d\n", i);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004567 }
4568 }
4569 old = old->next;
4570 new = new->next;
4571 } while((old != ofirst) && (new != nfirst));
4572
4573 /* Make a third pass to cleanup the extra useses */
4574 old = ofirst;
4575 new = nfirst;
4576 do {
4577 unuse_triple(old, new);
4578 old = old->next;
4579 new = new->next;
4580 } while ((old != ofirst) && (new != nfirst));
4581 return nfunc;
4582}
4583
4584static struct triple *flatten_call(
4585 struct compile_state *state, struct triple *first, struct triple *ptr)
4586{
4587 /* Inline the function call */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004588 struct type *ptype;
4589 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004590 struct triple *end, *nend;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004591 int pvals, i;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004592
4593 /* Find the triples */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004594 ofunc = MISC(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004595 if (ofunc->op != OP_LIST) {
4596 internal_error(state, 0, "improper function");
4597 }
4598 nfunc = copy_func(state, ofunc);
Eric Biederman0babc1c2003-05-09 02:39:00 +00004599 nfirst = RHS(nfunc, 0)->next;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004600 /* Prepend the parameter reading into the new function list */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004601 ptype = nfunc->type->right;
4602 param = RHS(nfunc, 0)->next;
4603 pvals = TRIPLE_RHS(ptr->sizes);
4604 for(i = 0; i < pvals; i++) {
4605 struct type *atype;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004606 struct triple *arg;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004607 atype = ptype;
4608 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4609 atype = ptype->left;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004610 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00004611 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4612 param = param->next;
4613 }
4614 arg = RHS(ptr, i);
4615 flatten(state, nfirst, write_expr(state, param, arg));
4616 ptype = ptype->right;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004617 param = param->next;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004618 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004619 result = 0;
4620 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00004621 result = read_expr(state, MISC(nfunc,0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00004622 }
4623#if 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");
4629#endif
4630
4631 /* Get rid of the extra triples */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004632 nfirst = RHS(nfunc, 0)->next;
4633 free_triple(state, RHS(nfunc, 0));
4634 RHS(nfunc, 0) = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004635 free_triple(state, nfunc);
4636
4637 /* Append the new function list onto the return list */
4638 end = first->prev;
4639 nend = nfirst->prev;
4640 end->next = nfirst;
4641 nfirst->prev = end;
4642 nend->next = first;
4643 first->prev = nend;
4644
4645 return result;
4646}
4647
4648static struct triple *flatten(
4649 struct compile_state *state, struct triple *first, struct triple *ptr)
4650{
4651 struct triple *orig_ptr;
4652 if (!ptr)
4653 return 0;
4654 do {
4655 orig_ptr = ptr;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004656 /* Only flatten triples once */
4657 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4658 return ptr;
4659 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004660 switch(ptr->op) {
4661 case OP_WRITE:
4662 case OP_STORE:
Eric Biederman0babc1c2003-05-09 02:39:00 +00004663 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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004667 break;
4668 case OP_COMMA:
Eric Biederman0babc1c2003-05-09 02:39:00 +00004669 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4670 ptr = RHS(ptr, 1);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004671 break;
4672 case OP_VAL:
Eric Biederman0babc1c2003-05-09 02:39:00 +00004673 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4674 return MISC(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004675 break;
4676 case OP_LAND:
4677 ptr = flatten_land(state, first, ptr);
4678 break;
4679 case OP_LOR:
4680 ptr = flatten_lor(state, first, ptr);
4681 break;
4682 case OP_COND:
4683 ptr = flatten_cond(state, first, ptr);
4684 break;
4685 case OP_CALL:
4686 ptr = flatten_call(state, first, ptr);
4687 break;
4688 case OP_READ:
4689 case OP_LOAD:
Eric Biederman0babc1c2003-05-09 02:39:00 +00004690 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4691 use_triple(RHS(ptr, 0), ptr);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004692 break;
4693 case OP_BRANCH:
Eric Biederman0babc1c2003-05-09 02:39:00 +00004694 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);
4699 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004700 }
4701 break;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004702 case OP_BLOBCONST:
4703 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
Eric Biederman0babc1c2003-05-09 02:39:00 +00004704 use_triple(MISC(ptr, 0), ptr);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004705 break;
4706 case OP_DEREF:
4707 /* Since OP_DEREF is just a marker delete it when I flatten it */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004708 ptr = RHS(ptr, 0);
4709 RHS(orig_ptr, 0) = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004710 free_triple(state, orig_ptr);
4711 break;
Eric Biedermanb138ac82003-04-22 18:44:01 +00004712 case OP_DOT:
Eric Biederman0babc1c2003-05-09 02:39:00 +00004713 {
4714 struct triple *base;
4715 base = RHS(ptr, 0);
4716 base = flatten(state, first, base);
4717 if (base->op == OP_VAL_VEC) {
4718 ptr = struct_field(state, base, ptr->u.field);
4719 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004720 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +00004721 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004722 case OP_SDECL:
4723 case OP_ADECL:
Eric Biedermanb138ac82003-04-22 18:44:01 +00004724 break;
4725 default:
4726 /* Flatten the easy cases we don't override */
Eric Biederman0babc1c2003-05-09 02:39:00 +00004727 ptr = flatten_generic(state, first, ptr);
Eric Biedermanb138ac82003-04-22 18:44:01 +00004728 break;
4729 }
4730 } while(ptr && (ptr != orig_ptr));
Eric Biederman0babc1c2003-05-09 02:39:00 +00004731 if (ptr) {
4732 insert_triple(state, first, ptr);
4733 ptr->id |= TRIPLE_FLAG_FLATTENED;
4734 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00004735 return ptr;
4736}
4737
4738static void release_expr(struct compile_state *state, struct triple *expr)
4739{
4740 struct triple *head;
4741 head = label(state);
4742 flatten(state, head, expr);
4743 while(head->next != head) {
4744 release_triple(state, head->next);
4745 }
4746 free_triple(state, head);
4747}
4748
4749static int replace_rhs_use(struct compile_state *state,
4750 struct triple *orig, struct triple *new, struct triple *use)
4751{
4752 struct triple **expr;
4753 int found;
4754 found = 0;
4755 expr = triple_rhs(state, use, 0);
4756 for(;expr; expr = triple_rhs(state, use, expr)) {
4757 if (*expr == orig) {
4758 *expr = new;
4759 found = 1;
4760 }
4761 }
4762 if (found) {
4763 unuse_triple(orig, use);
4764 use_triple(new, use);
4765 }
4766 return found;
4767}
4768
4769static int replace_lhs_use(struct compile_state *state,
4770 struct triple *orig, struct triple *new, struct triple *use)
4771{
4772 struct triple **expr;
4773 int found;
4774 found = 0;
4775 expr = triple_lhs(state, use, 0);
4776 for(;expr; expr = triple_lhs(state, use, expr)) {
4777 if (*expr == orig) {
4778 *expr = new;
4779 found = 1;
4780 }
4781 }
4782 if (found) {
4783 unuse_triple(orig, use);
4784 use_triple(new, use);
4785 }
4786 return found;
4787}
4788
4789static void propogate_use(struct compile_state *state,
4790 struct triple *orig, struct triple *new)
4791{
4792 struct triple_set *user, *next;
4793 for(user = orig->use; user; user = next) {
4794 struct triple *use;
4795 int found;
4796 next = user->next;
4797 use = user->member;
4798 found = 0;
4799 found |= replace_rhs_use(state, orig, new, use);
4800 found |= replace_lhs_use(state, orig, new, use);
4801 if (!found) {
4802 internal_error(state, use, "use without use");
4803 }
4804 }
4805 if (orig->use) {
4806 internal_error(state, orig, "used after propogate_use");
4807 }
4808}
4809
4810/*
4811 * Code generators
4812 * ===========================
4813 */
4814
4815static struct triple *mk_add_expr(
4816 struct compile_state *state, struct triple *left, struct triple *right)
4817{
4818 struct type *result_type;
4819 /* Put pointer operands on the left */
4820 if (is_pointer(right)) {
4821 struct triple *tmp;
4822 tmp = left;
4823 left = right;
4824 right = tmp;
4825 }
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,
4832 &ulong_type,
4833 right,
4834 int_const(state, &ulong_type,
4835 size_of(state, left->type->left)));
4836 }
4837 return triple(state, OP_ADD, result_type, left, right);
4838}
4839
4840static struct triple *mk_sub_expr(
4841 struct compile_state *state, struct triple *left, struct triple *right)
4842{
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,
4850 &ulong_type,
4851 right,
4852 int_const(state, &ulong_type,
4853 size_of(state, left->type->left)));
4854 }
4855 return triple(state, OP_SUB, result_type, left, right);
4856}
4857
4858static struct triple *mk_pre_inc_expr(
4859 struct compile_state *state, struct triple *def)
4860{
4861 struct triple *val;
4862 lvalue(state, 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),
4866 val);
4867}
4868
4869static struct triple *mk_pre_dec_expr(
4870 struct compile_state *state, struct triple *def)
4871{
4872 struct triple *val;
4873 lvalue(state, 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),
4877 val);
4878}
4879
4880static struct triple *mk_post_inc_expr(
4881 struct compile_state *state, struct triple *def)
4882{
4883 struct triple *val;
4884 lvalue(state, 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)))
4889 , val);
4890}
4891
4892static struct triple *mk_post_dec_expr(
4893 struct compile_state *state, struct triple *def)
4894{
4895 struct triple *val;
4896 lvalue(state, 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)))
4901 , val);
4902}
4903
4904static struct triple *mk_subscript_expr(
4905 struct compile_state *state, struct triple *left, struct triple *right)
4906{
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");
4911 }
4912 return mk_deref_expr(state, mk_add_expr(state, left, right));
4913}
4914
4915/*
4916 * Compile time evaluation
4917 * ===========================
4918 */
4919static int is_const(struct triple *ins)
4920{
4921 return IS_CONST_OP(ins->op);
4922}
4923
4924static int constants_equal(struct compile_state *state,
4925 struct triple *left, struct triple *right)
4926{
4927 int equal;
4928 if (!is_const(left) || !is_const(right)) {
4929 equal = 0;
4930 }
4931 else if (left->op != right->op) {
4932 equal = 0;
4933 }
4934 else if (!equiv_types(left->type, right->type)) {
4935 equal = 0;
4936 }
4937 else {
4938 equal = 0;
4939 switch(left->op) {
4940 case OP_INTCONST:
4941 if (left->u.cval == right->u.cval) {
4942 equal = 1;
4943 }
4944 break;
4945 case OP_BLOBCONST:
4946 {
4947 size_t lsize, rsize;
4948 lsize = size_of(state, left->type);
4949 rsize = size_of(state, right->type);
4950 if (lsize != rsize) {
4951 break;
4952 }
4953 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
4954 equal = 1;
4955 }
4956 break;
4957 }
4958 case OP_ADDRCONST:
Eric Biederman0babc1c2003-05-09 02:39:00 +00004959 if ((RHS(left, 0) == RHS(right, 0)) &&
Eric Biedermanb138ac82003-04-22 18:44:01 +00004960 (left->u.cval == right->u.cval)) {
4961 equal = 1;
4962 }
4963 break;
4964 default:
4965 internal_error(state, left, "uknown constant type");
4966 break;
4967 }
4968 }
4969 return equal;
4970}
4971
4972static int is_zero(struct triple *ins)
4973{
4974 return is_const(ins) && (ins->u.cval == 0);
4975}
4976
4977static int is_one(struct triple *ins)
4978{
4979 return is_const(ins) && (ins->u.cval == 1);
4980}
4981
4982static long_t bsr(ulong_t value)
4983{
4984 int i;
4985 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
4986 ulong_t mask;
4987 mask = 1;
4988 mask <<= i;
4989 if (value & mask) {
4990 return i;
4991 }
4992 }
4993 return -1;
4994}
4995
4996static long_t bsf(ulong_t value)
4997{
4998 int i;
4999 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5000 ulong_t mask;
5001 mask = 1;
5002 mask <<= 1;
5003 if (value & mask) {
5004 return i;
5005 }
5006 }
5007 return -1;
5008}
5009
5010static long_t log2(ulong_t value)
5011{
5012 return bsr(value);
5013}
5014
5015static long_t tlog2(struct triple *ins)
5016{
5017 return log2(ins->u.cval);
5018}
5019
5020static int is_pow2(struct triple *ins)
5021{
5022 ulong_t value, mask;
5023 long_t log;
5024 if (!is_const(ins)) {
5025 return 0;
5026 }
5027 value = ins->u.cval;
5028 log = log2(value);
5029 if (log == -1) {
5030 return 0;
5031 }
5032 mask = 1;
5033 mask <<= log;
5034 return ((value & mask) == value);
5035}
5036
5037static ulong_t read_const(struct compile_state *state,
5038 struct triple *ins, struct triple **expr)
5039{
5040 struct triple *rhs;
5041 rhs = *expr;
5042 switch(rhs->type->type &TYPE_MASK) {
5043 case TYPE_CHAR:
5044 case TYPE_SHORT:
5045 case TYPE_INT:
5046 case TYPE_LONG:
5047 case TYPE_UCHAR:
5048 case TYPE_USHORT:
5049 case TYPE_UINT:
5050 case TYPE_ULONG:
5051 case TYPE_POINTER:
5052 break;
5053 default:
5054 internal_error(state, rhs, "bad type to read_const\n");
5055 break;
5056 }
5057 return rhs->u.cval;
5058}
5059
5060static long_t read_sconst(struct triple *ins, struct triple **expr)
5061{
5062 struct triple *rhs;
5063 rhs = *expr;
5064 return (long_t)(rhs->u.cval);
5065}
5066
5067static void unuse_rhs(struct compile_state *state, struct triple *ins)
5068{
5069 struct triple **expr;
5070 expr = triple_rhs(state, ins, 0);
5071 for(;expr;expr = triple_rhs(state, ins, expr)) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00005072 if (*expr) {
5073 unuse_triple(*expr, ins);
5074 *expr = 0;
5075 }
5076 }
5077}
5078
5079static void unuse_lhs(struct compile_state *state, struct triple *ins)
5080{
5081 struct triple **expr;
5082 expr = triple_lhs(state, ins, 0);
5083 for(;expr;expr = triple_lhs(state, ins, expr)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005084 unuse_triple(*expr, ins);
5085 *expr = 0;
5086 }
5087}
Eric Biederman0babc1c2003-05-09 02:39:00 +00005088
Eric Biedermanb138ac82003-04-22 18:44:01 +00005089static void check_lhs(struct compile_state *state, struct triple *ins)
5090{
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");
5095 }
5096
5097}
5098static void check_targ(struct compile_state *state, struct triple *ins)
5099{
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");
5104 }
5105}
5106
5107static void wipe_ins(struct compile_state *state, struct triple *ins)
5108{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005109 /* Becareful which instructions you replace the wiped
5110 * instruction with, as there are not enough slots
5111 * in all instructions to hold all others.
5112 */
Eric Biedermanb138ac82003-04-22 18:44:01 +00005113 check_targ(state, ins);
5114 unuse_rhs(state, ins);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005115 unuse_lhs(state, ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005116}
5117
5118static void mkcopy(struct compile_state *state,
5119 struct triple *ins, struct triple *rhs)
5120{
5121 wipe_ins(state, ins);
5122 ins->op = OP_COPY;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005123 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5124 RHS(ins, 0) = rhs;
5125 use_triple(RHS(ins, 0), ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005126}
5127
5128static void mkconst(struct compile_state *state,
5129 struct triple *ins, ulong_t value)
5130{
5131 if (!is_integral(ins) && !is_pointer(ins)) {
5132 internal_error(state, ins, "unknown type to make constant\n");
5133 }
5134 wipe_ins(state, ins);
5135 ins->op = OP_INTCONST;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005136 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005137 ins->u.cval = value;
5138}
5139
5140static void mkaddr_const(struct compile_state *state,
5141 struct triple *ins, struct triple *sdecl, ulong_t value)
5142{
5143 wipe_ins(state, ins);
5144 ins->op = OP_ADDRCONST;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005145 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5146 RHS(ins, 0) = sdecl;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005147 ins->u.cval = value;
5148 use_triple(sdecl, ins);
5149}
5150
Eric Biederman0babc1c2003-05-09 02:39:00 +00005151/* Transform multicomponent variables into simple register variables */
5152static void flatten_structures(struct compile_state *state)
5153{
5154 struct triple *ins, *first;
5155 first = RHS(state->main_function, 0);
5156 ins = first;
5157 /* Pass one expand structure values into valvecs.
5158 */
5159 ins = first;
5160 do {
5161 struct triple *next;
5162 next = ins->next;
5163 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5164 if (ins->op == OP_VAL_VEC) {
5165 /* Do nothing */
5166 }
5167 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5168 struct triple *def, **vector;
5169 struct type *tptr;
5170 int op;
5171 ulong_t i;
5172
5173 op = ins->op;
5174 def = RHS(ins, 0);
5175 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5176 ins->filename, ins->line, ins->col);
5177
5178 vector = &RHS(next, 0);
5179 tptr = next->type->left;
5180 for(i = 0; i < next->type->elements; i++) {
5181 struct triple *sfield;
5182 struct type *mtype;
5183 mtype = tptr;
5184 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5185 mtype = mtype->left;
5186 }
5187 sfield = deref_field(state, def, mtype->field_ident);
5188
5189 vector[i] = triple(
5190 state, op, mtype, sfield, 0);
5191 vector[i]->filename = next->filename;
5192 vector[i]->line = next->line;
5193 vector[i]->col = next->col;
5194 tptr = tptr->right;
5195 }
5196 propogate_use(state, ins, next);
5197 flatten(state, ins, next);
5198 free_triple(state, ins);
5199 }
5200 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5201 struct triple *src, *dst, **vector;
5202 struct type *tptr;
5203 int op;
5204 ulong_t i;
5205
5206 op = ins->op;
5207 src = RHS(ins, 0);
5208 dst = LHS(ins, 0);
5209 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5210 ins->filename, ins->line, ins->col);
5211
5212 vector = &RHS(next, 0);
5213 tptr = next->type->left;
5214 for(i = 0; i < ins->type->elements; i++) {
5215 struct triple *dfield, *sfield;
5216 struct type *mtype;
5217 mtype = tptr;
5218 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5219 mtype = mtype->left;
5220 }
5221 sfield = deref_field(state, src, mtype->field_ident);
5222 dfield = deref_field(state, dst, mtype->field_ident);
5223 vector[i] = triple(
5224 state, op, mtype, dfield, sfield);
5225 vector[i]->filename = next->filename;
5226 vector[i]->line = next->line;
5227 vector[i]->col = next->col;
5228 tptr = tptr->right;
5229 }
5230 propogate_use(state, ins, next);
5231 flatten(state, ins, next);
5232 free_triple(state, ins);
5233 }
5234 }
5235 ins = next;
5236 } while(ins != first);
5237 /* Pass two flatten the valvecs.
5238 */
5239 ins = first;
5240 do {
5241 struct triple *next;
5242 next = ins->next;
5243 if (ins->op == OP_VAL_VEC) {
5244 release_triple(state, ins);
5245 }
5246 ins = next;
5247 } while(ins != first);
5248 /* Pass three verify the state and set ->id to 0.
5249 */
5250 ins = first;
5251 do {
5252 ins->id = 0;
5253 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5254 internal_error(state, 0, "STRUCT_TYPE remains?");
5255 }
5256 if (ins->op == OP_DOT) {
5257 internal_error(state, 0, "OP_DOT remains?");
5258 }
5259 if (ins->op == OP_VAL_VEC) {
5260 internal_error(state, 0, "OP_VAL_VEC remains?");
5261 }
5262 ins = ins->next;
5263 } while(ins != first);
5264}
5265
Eric Biedermanb138ac82003-04-22 18:44:01 +00005266/* For those operations that cannot be simplified */
5267static void simplify_noop(struct compile_state *state, struct triple *ins)
5268{
5269 return;
5270}
5271
5272static void simplify_smul(struct compile_state *state, struct triple *ins)
5273{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005274 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005275 struct triple *tmp;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005276 tmp = RHS(ins, 0);
5277 RHS(ins, 0) = RHS(ins, 1);
5278 RHS(ins, 1) = tmp;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005279 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005280 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005281 long_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005282 left = read_sconst(ins, &RHS(ins, 0));
5283 right = read_sconst(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005284 mkconst(state, ins, left * right);
5285 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005286 else if (is_zero(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005287 mkconst(state, ins, 0);
5288 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005289 else if (is_one(RHS(ins, 1))) {
5290 mkcopy(state, ins, RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005291 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005292 else if (is_pow2(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005293 struct triple *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005294 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005295 ins->op = OP_SL;
5296 insert_triple(state, ins, val);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005297 unuse_triple(RHS(ins, 1), ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005298 use_triple(val, ins);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005299 RHS(ins, 1) = val;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005300 }
5301}
5302
5303static void simplify_umul(struct compile_state *state, struct triple *ins)
5304{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005305 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005306 struct triple *tmp;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005307 tmp = RHS(ins, 0);
5308 RHS(ins, 0) = RHS(ins, 1);
5309 RHS(ins, 1) = tmp;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005310 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005311 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005312 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005313 left = read_const(state, ins, &RHS(ins, 0));
5314 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005315 mkconst(state, ins, left * right);
5316 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005317 else if (is_zero(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005318 mkconst(state, ins, 0);
5319 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005320 else if (is_one(RHS(ins, 1))) {
5321 mkcopy(state, ins, RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005322 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005323 else if (is_pow2(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005324 struct triple *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005325 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005326 ins->op = OP_SL;
5327 insert_triple(state, ins, val);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005328 unuse_triple(RHS(ins, 1), ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005329 use_triple(val, ins);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005330 RHS(ins, 1) = val;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005331 }
5332}
5333
5334static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5335{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005336 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005337 long_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005338 left = read_sconst(ins, &RHS(ins, 0));
5339 right = read_sconst(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005340 mkconst(state, ins, left / right);
5341 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005342 else if (is_zero(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005343 mkconst(state, ins, 0);
5344 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005345 else if (is_zero(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005346 error(state, ins, "division by zero");
5347 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005348 else if (is_one(RHS(ins, 1))) {
5349 mkcopy(state, ins, RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005350 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005351 else if (is_pow2(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005352 struct triple *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005353 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005354 ins->op = OP_SSR;
5355 insert_triple(state, ins, val);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005356 unuse_triple(RHS(ins, 1), ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005357 use_triple(val, ins);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005358 RHS(ins, 1) = val;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005359 }
5360}
5361
5362static void simplify_udiv(struct compile_state *state, struct triple *ins)
5363{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005364 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005365 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005366 left = read_const(state, ins, &RHS(ins, 0));
5367 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005368 mkconst(state, ins, left / right);
5369 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005370 else if (is_zero(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005371 mkconst(state, ins, 0);
5372 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005373 else if (is_zero(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005374 error(state, ins, "division by zero");
5375 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005376 else if (is_one(RHS(ins, 1))) {
5377 mkcopy(state, ins, RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005378 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005379 else if (is_pow2(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005380 struct triple *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005381 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005382 ins->op = OP_USR;
5383 insert_triple(state, ins, val);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005384 unuse_triple(RHS(ins, 1), ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005385 use_triple(val, ins);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005386 RHS(ins, 1) = val;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005387 }
5388}
5389
5390static void simplify_smod(struct compile_state *state, struct triple *ins)
5391{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005392 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005393 long_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005394 left = read_const(state, ins, &RHS(ins, 0));
5395 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005396 mkconst(state, ins, left % right);
5397 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005398 else if (is_zero(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005399 mkconst(state, ins, 0);
5400 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005401 else if (is_zero(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005402 error(state, ins, "division by zero");
5403 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005404 else if (is_one(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005405 mkconst(state, ins, 0);
5406 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005407 else if (is_pow2(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005408 struct triple *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005409 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005410 ins->op = OP_AND;
5411 insert_triple(state, ins, val);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005412 unuse_triple(RHS(ins, 1), ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005413 use_triple(val, ins);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005414 RHS(ins, 1) = val;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005415 }
5416}
5417static void simplify_umod(struct compile_state *state, struct triple *ins)
5418{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005419 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005420 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005421 left = read_const(state, ins, &RHS(ins, 0));
5422 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005423 mkconst(state, ins, left % right);
5424 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005425 else if (is_zero(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005426 mkconst(state, ins, 0);
5427 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005428 else if (is_zero(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005429 error(state, ins, "division by zero");
5430 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005431 else if (is_one(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005432 mkconst(state, ins, 0);
5433 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005434 else if (is_pow2(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005435 struct triple *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005436 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005437 ins->op = OP_AND;
5438 insert_triple(state, ins, val);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005439 unuse_triple(RHS(ins, 1), ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005440 use_triple(val, ins);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005441 RHS(ins, 1) = val;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005442 }
5443}
5444
5445static void simplify_add(struct compile_state *state, struct triple *ins)
5446{
5447 /* start with the pointer on the left */
Eric Biederman0babc1c2003-05-09 02:39:00 +00005448 if (is_pointer(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005449 struct triple *tmp;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005450 tmp = RHS(ins, 0);
5451 RHS(ins, 0) = RHS(ins, 1);
5452 RHS(ins, 1) = tmp;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005453 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005454 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5455 if (!is_pointer(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005456 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005457 left = read_const(state, ins, &RHS(ins, 0));
5458 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005459 mkconst(state, ins, left + right);
5460 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005461 else /* op == OP_ADDRCONST */ {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005462 struct triple *sdecl;
5463 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005464 sdecl = RHS(RHS(ins, 0), 0);
5465 left = RHS(ins, 0)->u.cval;
5466 right = RHS(ins, 1)->u.cval;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005467 mkaddr_const(state, ins, sdecl, left + right);
5468 }
5469 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005470 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005471 struct triple *tmp;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005472 tmp = RHS(ins, 1);
5473 RHS(ins, 1) = RHS(ins, 0);
5474 RHS(ins, 0) = tmp;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005475 }
5476}
5477
5478static void simplify_sub(struct compile_state *state, struct triple *ins)
5479{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005480 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5481 if (!is_pointer(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005482 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005483 left = read_const(state, ins, &RHS(ins, 0));
5484 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005485 mkconst(state, ins, left - right);
5486 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005487 else /* op == OP_ADDRCONST */ {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005488 struct triple *sdecl;
5489 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005490 sdecl = RHS(RHS(ins, 0), 0);
5491 left = RHS(ins, 0)->u.cval;
5492 right = RHS(ins, 1)->u.cval;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005493 mkaddr_const(state, ins, sdecl, left - right);
5494 }
5495 }
5496}
5497
5498static void simplify_sl(struct compile_state *state, struct triple *ins)
5499{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005500 if (is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005501 ulong_t right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005502 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005503 if (right >= (size_of(state, ins->type)*8)) {
5504 warning(state, ins, "left shift count >= width of type");
5505 }
5506 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005507 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005508 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005509 left = read_const(state, ins, &RHS(ins, 0));
5510 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005511 mkconst(state, ins, left << right);
5512 }
5513}
5514
5515static void simplify_usr(struct compile_state *state, struct triple *ins)
5516{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005517 if (is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005518 ulong_t right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005519 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005520 if (right >= (size_of(state, ins->type)*8)) {
5521 warning(state, ins, "right shift count >= width of type");
5522 }
5523 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005524 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005525 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005526 left = read_const(state, ins, &RHS(ins, 0));
5527 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005528 mkconst(state, ins, left >> right);
5529 }
5530}
5531
5532static void simplify_ssr(struct compile_state *state, struct triple *ins)
5533{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005534 if (is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005535 ulong_t right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005536 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005537 if (right >= (size_of(state, ins->type)*8)) {
5538 warning(state, ins, "right shift count >= width of type");
5539 }
5540 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005541 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005542 long_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005543 left = read_sconst(ins, &RHS(ins, 0));
5544 right = read_sconst(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005545 mkconst(state, ins, left >> right);
5546 }
5547}
5548
5549static void simplify_and(struct compile_state *state, struct triple *ins)
5550{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005551 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005552 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005553 left = read_const(state, ins, &RHS(ins, 0));
5554 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005555 mkconst(state, ins, left & right);
5556 }
5557}
5558
5559static void simplify_or(struct compile_state *state, struct triple *ins)
5560{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005561 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005562 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005563 left = read_const(state, ins, &RHS(ins, 0));
5564 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005565 mkconst(state, ins, left | right);
5566 }
5567}
5568
5569static void simplify_xor(struct compile_state *state, struct triple *ins)
5570{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005571 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005572 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005573 left = read_const(state, ins, &RHS(ins, 0));
5574 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005575 mkconst(state, ins, left ^ right);
5576 }
5577}
5578
5579static void simplify_pos(struct compile_state *state, struct triple *ins)
5580{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005581 if (is_const(RHS(ins, 0))) {
5582 mkconst(state, ins, RHS(ins, 0)->u.cval);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005583 }
5584 else {
Eric Biederman0babc1c2003-05-09 02:39:00 +00005585 mkcopy(state, ins, RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005586 }
5587}
5588
5589static void simplify_neg(struct compile_state *state, struct triple *ins)
5590{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005591 if (is_const(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005592 ulong_t left;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005593 left = read_const(state, ins, &RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005594 mkconst(state, ins, -left);
5595 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005596 else if (RHS(ins, 0)->op == OP_NEG) {
5597 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005598 }
5599}
5600
5601static void simplify_invert(struct compile_state *state, struct triple *ins)
5602{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005603 if (is_const(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005604 ulong_t left;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005605 left = read_const(state, ins, &RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005606 mkconst(state, ins, ~left);
5607 }
5608}
5609
5610static void simplify_eq(struct compile_state *state, struct triple *ins)
5611{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005612 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005613 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005614 left = read_const(state, ins, &RHS(ins, 0));
5615 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005616 mkconst(state, ins, left == right);
5617 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005618 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005619 mkconst(state, ins, 1);
5620 }
5621}
5622
5623static void simplify_noteq(struct compile_state *state, struct triple *ins)
5624{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005625 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005626 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005627 left = read_const(state, ins, &RHS(ins, 0));
5628 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005629 mkconst(state, ins, left != right);
5630 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005631 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005632 mkconst(state, ins, 0);
5633 }
5634}
5635
5636static void simplify_sless(struct compile_state *state, struct triple *ins)
5637{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005638 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005639 long_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005640 left = read_sconst(ins, &RHS(ins, 0));
5641 right = read_sconst(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005642 mkconst(state, ins, left < right);
5643 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005644 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005645 mkconst(state, ins, 0);
5646 }
5647}
5648
5649static void simplify_uless(struct compile_state *state, struct triple *ins)
5650{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005651 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005652 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005653 left = read_const(state, ins, &RHS(ins, 0));
5654 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005655 mkconst(state, ins, left < right);
5656 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005657 else if (is_zero(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005658 mkconst(state, ins, 1);
5659 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005660 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005661 mkconst(state, ins, 0);
5662 }
5663}
5664
5665static void simplify_smore(struct compile_state *state, struct triple *ins)
5666{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005667 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005668 long_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005669 left = read_sconst(ins, &RHS(ins, 0));
5670 right = read_sconst(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005671 mkconst(state, ins, left > right);
5672 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005673 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005674 mkconst(state, ins, 0);
5675 }
5676}
5677
5678static void simplify_umore(struct compile_state *state, struct triple *ins)
5679{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005680 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005681 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005682 left = read_const(state, ins, &RHS(ins, 0));
5683 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005684 mkconst(state, ins, left > right);
5685 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005686 else if (is_zero(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005687 mkconst(state, ins, 1);
5688 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005689 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005690 mkconst(state, ins, 0);
5691 }
5692}
5693
5694
5695static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5696{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005697 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005698 long_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005699 left = read_sconst(ins, &RHS(ins, 0));
5700 right = read_sconst(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005701 mkconst(state, ins, left <= right);
5702 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005703 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005704 mkconst(state, ins, 1);
5705 }
5706}
5707
5708static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5709{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005710 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005711 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005712 left = read_const(state, ins, &RHS(ins, 0));
5713 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005714 mkconst(state, ins, left <= right);
5715 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005716 else if (is_zero(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005717 mkconst(state, ins, 1);
5718 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005719 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005720 mkconst(state, ins, 1);
5721 }
5722}
5723
5724static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5725{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005726 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005727 long_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005728 left = read_sconst(ins, &RHS(ins, 0));
5729 right = read_sconst(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005730 mkconst(state, ins, left >= right);
5731 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005732 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005733 mkconst(state, ins, 1);
5734 }
5735}
5736
5737static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5738{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005739 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005740 ulong_t left, right;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005741 left = read_const(state, ins, &RHS(ins, 0));
5742 right = read_const(state, ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005743 mkconst(state, ins, left >= right);
5744 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005745 else if (is_zero(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005746 mkconst(state, ins, 1);
5747 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005748 else if (RHS(ins, 0) == RHS(ins, 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005749 mkconst(state, ins, 1);
5750 }
5751}
5752
5753static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5754{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005755 if (is_const(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005756 ulong_t left;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005757 left = read_const(state, ins, &RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005758 mkconst(state, ins, left == 0);
5759 }
5760 /* Otherwise if I am the only user... */
Eric Biederman0babc1c2003-05-09 02:39:00 +00005761 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005762 int need_copy = 1;
5763 /* Invert a boolean operation */
Eric Biederman0babc1c2003-05-09 02:39:00 +00005764 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;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005777 default:
5778 need_copy = 0;
5779 break;
5780 }
5781 if (need_copy) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00005782 mkcopy(state, ins, RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005783 }
5784 }
5785}
5786
5787static void simplify_ltrue (struct compile_state *state, struct triple *ins)
5788{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005789 if (is_const(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005790 ulong_t left;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005791 left = read_const(state, ins, &RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005792 mkconst(state, ins, left != 0);
5793 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005794 else switch(RHS(ins, 0)->op) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005795 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:
Eric Biederman0babc1c2003-05-09 02:39:00 +00005798 mkcopy(state, ins, RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005799 }
5800
5801}
5802
5803static void simplify_copy(struct compile_state *state, struct triple *ins)
5804{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005805 if (is_const(RHS(ins, 0))) {
5806 switch(RHS(ins, 0)->op) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005807 case OP_INTCONST:
5808 {
5809 ulong_t left;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005810 left = read_const(state, ins, &RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005811 mkconst(state, ins, left);
5812 break;
5813 }
5814 case OP_ADDRCONST:
5815 {
5816 struct triple *sdecl;
5817 ulong_t offset;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005818 sdecl = RHS(ins, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005819 offset = ins->u.cval;
5820 mkaddr_const(state, ins, sdecl, offset);
5821 break;
5822 }
5823 default:
5824 internal_error(state, ins, "uknown constant");
5825 break;
5826 }
5827 }
5828}
5829
Eric Biedermanb138ac82003-04-22 18:44:01 +00005830static void simplify_branch(struct compile_state *state, struct triple *ins)
5831{
5832 struct block *block;
5833 if (ins->op != OP_BRANCH) {
5834 internal_error(state, ins, "not branch");
5835 }
5836 if (ins->use != 0) {
5837 internal_error(state, ins, "branch use");
5838 }
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.
5843 */
5844 block = ins->u.block;
5845
Eric Biederman0babc1c2003-05-09 02:39:00 +00005846 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
5847 struct triple *targ;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005848 ulong_t value;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005849 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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005853 if (value) {
5854 unuse_triple(ins->next, ins);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005855 TARG(ins, 0) = targ;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005856 }
5857 else {
Eric Biederman0babc1c2003-05-09 02:39:00 +00005858 unuse_triple(targ, ins);
5859 TARG(ins, 0) = ins->next;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005860 }
5861#warning "FIXME handle the case of making a branch unconditional"
5862 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005863 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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00005867 unuse_triple(ins->next, ins);
5868 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00005869 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5870 ins->op = OP_NOOP;
Eric Biedermanb138ac82003-04-22 18:44:01 +00005871 if (ins->use) {
5872 internal_error(state, ins, "noop use != 0");
5873 }
5874#warning "FIXME handle the case of killing a branch"
5875 }
5876}
5877
5878static void simplify_phi(struct compile_state *state, struct triple *ins)
5879{
5880 struct triple **expr;
5881 ulong_t value;
5882 expr = triple_rhs(state, ins, 0);
Eric Biederman0babc1c2003-05-09 02:39:00 +00005883 if (!*expr || !is_const(*expr)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005884 return;
5885 }
5886 value = read_const(state, ins, expr);
5887 for(;expr;expr = triple_rhs(state, ins, expr)) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00005888 if (!*expr || !is_const(*expr)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005889 return;
5890 }
5891 if (value != read_const(state, ins, expr)) {
5892 return;
5893 }
5894 }
5895 mkconst(state, ins, value);
5896}
5897
5898
5899static void simplify_bsf(struct compile_state *state, struct triple *ins)
5900{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005901 if (is_const(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005902 ulong_t left;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005903 left = read_const(state, ins, &RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005904 mkconst(state, ins, bsf(left));
5905 }
5906}
5907
5908static void simplify_bsr(struct compile_state *state, struct triple *ins)
5909{
Eric Biederman0babc1c2003-05-09 02:39:00 +00005910 if (is_const(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00005911 ulong_t left;
Eric Biederman0babc1c2003-05-09 02:39:00 +00005912 left = read_const(state, ins, &RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00005913 mkconst(state, ins, bsr(left));
5914 }
5915}
5916
5917
5918typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
5919static const simplify_t table_simplify[] = {
5920#if 0
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
5927#endif
5928#if 0
5929#define simplify_add simplify_noop
5930#define simplify_sub simplify_noop
5931#endif
5932#if 0
5933#define simplify_sl simplify_noop
5934#define simplify_usr simplify_noop
5935#define simplify_ssr simplify_noop
5936#endif
5937#if 0
5938#define simplify_and simplify_noop
5939#define simplify_xor simplify_noop
5940#define simplify_or simplify_noop
5941#endif
5942#if 0
5943#define simplify_pos simplify_noop
5944#define simplify_neg simplify_noop
5945#define simplify_invert simplify_noop
5946#endif
5947
5948#if 0
5949#define simplify_eq simplify_noop
5950#define simplify_noteq simplify_noop
5951#endif
5952#if 0
5953#define simplify_sless simplify_noop
5954#define simplify_uless simplify_noop
5955#define simplify_smore simplify_noop
5956#define simplify_umore simplify_noop
5957#endif
5958#if 0
5959#define simplify_slesseq simplify_noop
5960#define simplify_ulesseq simplify_noop
5961#define simplify_smoreeq simplify_noop
5962#define simplify_umoreeq simplify_noop
5963#endif
5964#if 0
5965#define simplify_lfalse simplify_noop
5966#endif
5967#if 0
5968#define simplify_ltrue simplify_noop
5969#endif
5970
5971#if 0
5972#define simplify_copy simplify_noop
5973#endif
5974
5975#if 0
Eric Biedermanb138ac82003-04-22 18:44:01 +00005976#define simplify_branch simplify_noop
5977#endif
5978
5979#if 0
5980#define simplify_phi simplify_noop
5981#endif
5982
5983#if 0
5984#define simplify_bsf simplify_noop
5985#define simplify_bsr simplify_noop
5986#endif
5987
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,
6005
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,
6018
6019[OP_LOAD ] = simplify_noop,
6020[OP_STORE ] = simplify_noop,
6021
6022[OP_NOOP ] = simplify_noop,
6023
6024[OP_INTCONST ] = simplify_noop,
6025[OP_BLOBCONST ] = simplify_noop,
6026[OP_ADDRCONST ] = simplify_noop,
6027
6028[OP_WRITE ] = simplify_noop,
6029[OP_READ ] = simplify_noop,
6030[OP_COPY ] = simplify_copy,
Eric Biederman0babc1c2003-05-09 02:39:00 +00006031[OP_PIECE ] = simplify_noop,
6032
6033[OP_DOT ] = simplify_noop,
6034[OP_VAL_VEC ] = simplify_noop,
Eric Biedermanb138ac82003-04-22 18:44:01 +00006035
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,
6042
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,
Eric Biederman0babc1c2003-05-09 02:39:00 +00006050[OP_BSR ] = simplify_bsr,
6051[OP_RDMSR ] = simplify_noop,
6052[OP_WRMSR ] = simplify_noop,
6053[OP_HLT ] = simplify_noop,
Eric Biedermanb138ac82003-04-22 18:44:01 +00006054};
6055
6056static void simplify(struct compile_state *state, struct triple *ins)
6057{
6058 int op;
6059 simplify_t do_simplify;
6060 do {
6061 op = ins->op;
6062 do_simplify = 0;
6063 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6064 do_simplify = 0;
6065 }
6066 else {
6067 do_simplify = table_simplify[op];
6068 }
6069 if (!do_simplify) {
6070 internal_error(state, ins, "cannot simplify op: %d %s\n",
6071 op, tops(op));
6072 return;
6073 }
6074 do_simplify(state, ins);
6075 } while(ins->op != op);
6076}
6077
6078static void simplify_all(struct compile_state *state)
6079{
6080 struct triple *ins, *first;
Eric Biederman0babc1c2003-05-09 02:39:00 +00006081 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00006082 ins = first;
6083 do {
6084 simplify(state, ins);
6085 ins = ins->next;
6086 } while(ins != first);
6087}
6088
6089/*
6090 * Builtins....
6091 * ============================
6092 */
6093
Eric Biederman0babc1c2003-05-09 02:39:00 +00006094static void register_builtin_function(struct compile_state *state,
6095 const char *name, int op, struct type *rtype, ...)
Eric Biedermanb138ac82003-04-22 18:44:01 +00006096{
Eric Biederman0babc1c2003-05-09 02:39:00 +00006097 struct type *ftype, *atype, *param, **next;
6098 struct triple *def, *arg, *result, *work, *last, *first;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006099 struct hash_entry *ident;
Eric Biederman0babc1c2003-05-09 02:39:00 +00006100 struct file_state file;
6101 int parameters;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006102 int name_len;
Eric Biederman0babc1c2003-05-09 02:39:00 +00006103 va_list args;
6104 int i;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006105
6106 /* Dummy file state to get debug handling right */
Eric Biedermanb138ac82003-04-22 18:44:01 +00006107 memset(&file, 0, sizeof(file));
6108 file.basename = name;
6109 file.line = 1;
6110 file.prev = state->file;
6111 state->file = &file;
Eric Biederman0babc1c2003-05-09 02:39:00 +00006112
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");
6118 }
6119
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 *);
6126 if (!*next) {
6127 *next = atype;
6128 } else {
6129 *next = new_type(TYPE_PRODUCT, *next, atype);
6130 next = &((*next)->right);
6131 }
6132 }
6133 if (!*next) {
6134 *next = &void_type;
6135 }
6136 va_end(args);
6137
Eric Biedermanb138ac82003-04-22 18:44:01 +00006138 /* Generate the needed triples */
6139 def = triple(state, OP_LIST, ftype, 0, 0);
6140 first = label(state);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006141 RHS(def, 0) = first;
6142
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;
6148 } else {
6149 atype = param;
6150 }
6151 arg = flatten(state, first, variable(state, atype));
6152 param = param->right;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006153 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00006154 result = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006155 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00006156 result = flatten(state, first, variable(state, rtype));
Eric Biedermanb138ac82003-04-22 18:44:01 +00006157 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00006158 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);
6162 }
6163 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6164 struct triple *val;
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");
6171 }
6172 val = new_triple(state, OP_VAL_VEC, rtype, -1);
6173 for(i = 0; i < rtype->elements; i++) {
6174 struct triple *piece;
6175 atype = param;
6176 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6177 atype = param->left;
6178 }
6179 if (!TYPE_ARITHMETIC(atype->type) &&
6180 !TYPE_PTR(atype->type)) {
6181 internal_error(state, 0, "Invalid lhs type");
6182 }
6183 piece = triple(state, OP_PIECE, atype, work, 0);
6184 piece->u.cval = i;
6185 LHS(work, i) = piece;
6186 RHS(val, i) = piece;
6187 }
6188 work = val;
6189 }
6190 if (result) {
6191 work = write_expr(state, result, work);
Eric Biedermanb138ac82003-04-22 18:44:01 +00006192 }
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);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006198
Eric Biedermanb138ac82003-04-22 18:44:01 +00006199 state->file = file.prev;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006200#if 0
6201 fprintf(stdout, "\n");
6202 loc(stdout, state, 0);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006203 fprintf(stdout, "\n__________ builtin_function _________\n");
Eric Biedermanb138ac82003-04-22 18:44:01 +00006204 print_triple(state, def);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006205 fprintf(stdout, "__________ builtin_function _________ done\n\n");
Eric Biedermanb138ac82003-04-22 18:44:01 +00006206#endif
6207}
6208
Eric Biederman0babc1c2003-05-09 02:39:00 +00006209static struct type *partial_struct(struct compile_state *state,
6210 const char *field_name, struct type *type, struct type *rest)
Eric Biedermanb138ac82003-04-22 18:44:01 +00006211{
Eric Biederman0babc1c2003-05-09 02:39:00 +00006212 struct hash_entry *field_ident;
6213 struct type *result;
6214 int field_name_len;
6215
6216 field_name_len = strlen(field_name);
6217 field_ident = lookup(state, field_name, field_name_len);
6218
6219 result = clone_type(0, type);
6220 result->field_ident = field_ident;
6221
6222 if (rest) {
6223 result = new_type(TYPE_PRODUCT, result, rest);
6224 }
6225 return result;
6226}
6227
6228static struct type *register_builtin_type(struct compile_state *state,
6229 const char *name, struct type *type)
6230{
Eric Biedermanb138ac82003-04-22 18:44:01 +00006231 struct hash_entry *ident;
6232 int name_len;
Eric Biederman0babc1c2003-05-09 02:39:00 +00006233
Eric Biedermanb138ac82003-04-22 18:44:01 +00006234 name_len = strlen(name);
6235 ident = lookup(state, name, name_len);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006236
6237 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6238 ulong_t elements = 0;
6239 struct type *field;
6240 type = new_type(TYPE_STRUCT, type, 0);
6241 field = type->left;
6242 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6243 elements++;
6244 field = field->right;
6245 }
6246 elements++;
6247 symbol(state, ident, &ident->sym_struct, 0, type);
6248 type->type_ident = ident;
6249 type->elements = elements;
6250 }
6251 symbol(state, ident, &ident->sym_ident, 0, type);
6252 ident->tok = TOK_TYPE_NAME;
6253 return type;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006254}
6255
Eric Biederman0babc1c2003-05-09 02:39:00 +00006256
Eric Biedermanb138ac82003-04-22 18:44:01 +00006257static void register_builtins(struct compile_state *state)
6258{
Eric Biederman0babc1c2003-05-09 02:39:00 +00006259 struct type *msr_type;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006260
Eric Biederman0babc1c2003-05-09 02:39:00 +00006261 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6262 &ushort_type);
6263 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6264 &ushort_type);
6265 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6266 &ushort_type);
6267
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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00006274
Eric Biederman0babc1c2003-05-09 02:39:00 +00006275 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6276 &int_type);
6277 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6278 &int_type);
6279
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)));
6283
6284 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6285 &ulong_type);
6286 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6287 &ulong_type, &ulong_type, &ulong_type);
Eric Biedermanb138ac82003-04-22 18:44:01 +00006288
Eric Biederman0babc1c2003-05-09 02:39:00 +00006289 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6290 &void_type);
Eric Biedermanb138ac82003-04-22 18:44:01 +00006291}
6292
6293static struct type *declarator(
6294 struct compile_state *state, struct type *type,
6295 struct hash_entry **ident, int need_ident);
6296static void decl(struct compile_state *state, struct triple *first);
6297static struct type *specifier_qualifier_list(struct compile_state *state);
6298static int isdecl_specifier(int tok);
6299static struct type *decl_specifiers(struct compile_state *state);
6300static int istype(int tok);
6301static struct triple *expr(struct compile_state *state);
6302static struct triple *assignment_expr(struct compile_state *state);
6303static struct type *type_name(struct compile_state *state);
6304static void statement(struct compile_state *state, struct triple *fist);
6305
6306static struct triple *call_expr(
6307 struct compile_state *state, struct triple *func)
6308{
Eric Biederman0babc1c2003-05-09 02:39:00 +00006309 struct triple *def;
6310 struct type *param, *type;
6311 ulong_t pvals, index;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006312
6313 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6314 error(state, 0, "Called object is not a function");
6315 }
6316 if (func->op != OP_LIST) {
6317 internal_error(state, 0, "improper function");
6318 }
6319 eat(state, TOK_LPAREN);
6320 /* Find the return type without any specifiers */
6321 type = clone_type(0, func->type->left);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006322 def = new_triple(state, OP_CALL, func->type, -1);
6323 def->type = type;
6324
6325 pvals = TRIPLE_RHS(def->sizes);
6326 MISC(def, 0) = func;
6327
6328 param = func->type->right;
6329 for(index = 0; index < pvals; index++) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00006330 struct triple *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00006331 struct type *arg_type;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006332 val = read_expr(state, assignment_expr(state));
Eric Biedermanb138ac82003-04-22 18:44:01 +00006333 arg_type = param;
6334 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6335 arg_type = param->left;
6336 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00006337 write_compatible(state, arg_type, val->type);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006338 RHS(def, index) = val;
6339 if (index != (pvals - 1)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00006340 eat(state, TOK_COMMA);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006341 param = param->right;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006342 }
6343 }
6344 eat(state, TOK_RPAREN);
6345 return def;
6346}
6347
6348
6349static struct triple *character_constant(struct compile_state *state)
6350{
6351 struct triple *def;
6352 struct token *tk;
6353 const signed char *str, *end;
6354 int c;
6355 int str_len;
6356 eat(state, TOK_LIT_CHAR);
6357 tk = &state->token[0];
6358 str = tk->val.str + 1;
6359 str_len = tk->str_len - 2;
6360 if (str_len <= 0) {
6361 error(state, 0, "empty character constant");
6362 }
6363 end = str + str_len;
6364 c = char_value(state, &str, end);
6365 if (str != end) {
6366 error(state, 0, "multibyte character constant not supported");
6367 }
6368 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6369 return def;
6370}
6371
6372static struct triple *string_constant(struct compile_state *state)
6373{
6374 struct triple *def;
6375 struct token *tk;
6376 struct type *type;
6377 const signed char *str, *end;
6378 signed char *buf, *ptr;
6379 int str_len;
6380
6381 buf = 0;
6382 type = new_type(TYPE_ARRAY, &char_type, 0);
6383 type->elements = 0;
6384 /* The while loop handles string concatenation */
6385 do {
6386 eat(state, TOK_LIT_STRING);
6387 tk = &state->token[0];
6388 str = tk->val.str + 1;
6389 str_len = tk->str_len - 2;
Eric Biedermanab2ea6b2003-04-26 03:20:53 +00006390 if (str_len < 0) {
6391 error(state, 0, "negative string constant length");
Eric Biedermanb138ac82003-04-22 18:44:01 +00006392 }
6393 end = str + str_len;
6394 ptr = buf;
6395 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6396 memcpy(buf, ptr, type->elements);
6397 ptr = buf + type->elements;
6398 do {
6399 *ptr++ = char_value(state, &str, end);
6400 } while(str < end);
6401 type->elements = ptr - buf;
6402 } while(peek(state) == TOK_LIT_STRING);
6403 *ptr = '\0';
6404 type->elements += 1;
6405 def = triple(state, OP_BLOBCONST, type, 0, 0);
6406 def->u.blob = buf;
6407 return def;
6408}
6409
6410
6411static struct triple *integer_constant(struct compile_state *state)
6412{
6413 struct triple *def;
6414 unsigned long val;
6415 struct token *tk;
6416 char *end;
6417 int u, l, decimal;
6418 struct type *type;
6419
6420 eat(state, TOK_LIT_INT);
6421 tk = &state->token[0];
6422 errno = 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");
6427 }
6428 u = l = 0;
6429 if ((*end == 'u') || (*end == 'U')) {
6430 u = 1;
6431 end++;
6432 }
6433 if ((*end == 'l') || (*end == 'L')) {
6434 l = 1;
6435 end++;
6436 }
6437 if ((*end == 'u') || (*end == 'U')) {
6438 u = 1;
6439 end++;
6440 }
6441 if (*end) {
6442 error(state, 0, "Junk at end of integer constant");
6443 }
6444 if (u && l) {
6445 type = &ulong_type;
6446 }
6447 else if (l) {
6448 type = &long_type;
6449 if (!decimal && (val > LONG_MAX)) {
6450 type = &ulong_type;
6451 }
6452 }
6453 else if (u) {
6454 type = &uint_type;
6455 if (val > UINT_MAX) {
6456 type = &ulong_type;
6457 }
6458 }
6459 else {
6460 type = &int_type;
6461 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6462 type = &uint_type;
6463 }
6464 else if (!decimal && (val > LONG_MAX)) {
6465 type = &ulong_type;
6466 }
6467 else if (val > INT_MAX) {
6468 type = &long_type;
6469 }
6470 }
6471 def = int_const(state, type, val);
6472 return def;
6473}
6474
6475static struct triple *primary_expr(struct compile_state *state)
6476{
6477 struct triple *def;
6478 int tok;
6479 tok = peek(state);
6480 switch(tok) {
6481 case TOK_IDENT:
6482 {
6483 struct hash_entry *ident;
6484 /* Here ident is either:
6485 * a varable name
6486 * a function name
6487 * an enumeration constant.
6488 */
6489 eat(state, TOK_IDENT);
6490 ident = state->token[0].ident;
6491 if (!ident->sym_ident) {
6492 error(state, 0, "%s undeclared", ident->name);
6493 }
6494 def = ident->sym_ident->def;
6495 break;
6496 }
6497 case TOK_ENUM_CONST:
6498 /* Here ident is an enumeration constant */
6499 eat(state, TOK_ENUM_CONST);
6500 def = 0;
6501 FINISHME();
6502 break;
6503 case TOK_LPAREN:
6504 eat(state, TOK_LPAREN);
6505 def = expr(state);
6506 eat(state, TOK_RPAREN);
6507 break;
6508 case TOK_LIT_INT:
6509 def = integer_constant(state);
6510 break;
6511 case TOK_LIT_FLOAT:
6512 eat(state, TOK_LIT_FLOAT);
6513 error(state, 0, "Floating point constants not supported");
6514 def = 0;
6515 FINISHME();
6516 break;
6517 case TOK_LIT_CHAR:
6518 def = character_constant(state);
6519 break;
6520 case TOK_LIT_STRING:
6521 def = string_constant(state);
6522 break;
6523 default:
6524 def = 0;
6525 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6526 }
6527 return def;
6528}
6529
6530static struct triple *postfix_expr(struct compile_state *state)
6531{
6532 struct triple *def;
6533 int postfix;
6534 def = primary_expr(state);
6535 do {
6536 struct triple *left;
6537 int tok;
6538 postfix = 1;
6539 left = def;
6540 switch((tok = peek(state))) {
6541 case TOK_LBRACKET:
6542 eat(state, TOK_LBRACKET);
6543 def = mk_subscript_expr(state, left, expr(state));
6544 eat(state, TOK_RBRACKET);
6545 break;
6546 case TOK_LPAREN:
6547 def = call_expr(state, def);
6548 break;
6549 case TOK_DOT:
Eric Biederman0babc1c2003-05-09 02:39:00 +00006550 {
6551 struct hash_entry *field;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006552 eat(state, TOK_DOT);
6553 eat(state, TOK_IDENT);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006554 field = state->token[0].ident;
6555 def = deref_field(state, def, field);
Eric Biedermanb138ac82003-04-22 18:44:01 +00006556 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +00006557 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00006558 case TOK_ARROW:
Eric Biederman0babc1c2003-05-09 02:39:00 +00006559 {
6560 struct hash_entry *field;
Eric Biedermanb138ac82003-04-22 18:44:01 +00006561 eat(state, TOK_ARROW);
6562 eat(state, TOK_IDENT);
Eric Biederman0babc1c2003-05-09 02:39:00 +00006563 field = state->token[0].ident;
6564 def = mk_deref_expr(state, read_expr(state, def));
6565 def = deref_field(state, def, field);
Eric Biedermanb138ac82003-04-22 18:44:01 +00006566 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +00006567 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00006568 case TOK_PLUSPLUS:
6569 eat(state, TOK_PLUSPLUS);
6570 def = mk_post_inc_expr(state, left);
6571 break;
6572 case TOK_MINUSMINUS:
6573 eat(state, TOK_MINUSMINUS);
6574 def = mk_post_dec_expr(state, left);
6575 break;
6576 default:
6577 postfix = 0;
6578 break;
6579 }
6580 } while(postfix);
6581 return def;
6582}
6583
6584static struct triple *cast_expr(struct compile_state *state);
6585
6586static struct triple *unary_expr(struct compile_state *state)
6587{
6588 struct triple *def, *right;
6589 int tok;
6590 switch((tok = peek(state))) {
6591 case TOK_PLUSPLUS:
6592 eat(state, TOK_PLUSPLUS);
6593 def = mk_pre_inc_expr(state, unary_expr(state));
6594 break;
6595 case TOK_MINUSMINUS:
6596 eat(state, TOK_MINUSMINUS);
6597 def = mk_pre_dec_expr(state, unary_expr(state));
6598 break;
6599 case TOK_AND:
6600 eat(state, TOK_AND);
6601 def = mk_addr_expr(state, cast_expr(state), 0);
6602 break;
6603 case TOK_STAR:
6604 eat(state, TOK_STAR);
6605 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6606 break;
6607 case TOK_PLUS:
6608 eat(state, TOK_PLUS);
6609 right = read_expr(state, cast_expr(state));
6610 arithmetic(state, right);
6611 def = integral_promotion(state, right);
6612 break;
6613 case TOK_MINUS:
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);
6619 break;
6620 case TOK_TILDE:
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);
6626 break;
6627 case TOK_BANG:
6628 eat(state, TOK_BANG);
6629 right = read_expr(state, cast_expr(state));
6630 bool(state, right);
6631 def = lfalse_expr(state, right);
6632 break;
6633 case TOK_SIZEOF:
6634 {
6635 struct type *type;
6636 int tok1, tok2;
6637 eat(state, TOK_SIZEOF);
6638 tok1 = peek(state);
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);
6644 }
6645 else {
6646 struct triple *expr;
6647 expr = unary_expr(state);
6648 type = expr->type;
6649 release_expr(state, expr);
6650 }
6651 def = int_const(state, &ulong_type, size_of(state, type));
6652 break;
6653 }
6654 case TOK_ALIGNOF:
6655 {
6656 struct type *type;
6657 int tok1, tok2;
6658 eat(state, TOK_ALIGNOF);
6659 tok1 = peek(state);
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);
6665 }
6666 else {
6667 struct triple *expr;
6668 expr = unary_expr(state);
6669 type = expr->type;
6670 release_expr(state, expr);
6671 }
6672 def = int_const(state, &ulong_type, align_of(state, type));
6673 break;
6674 }
6675 default:
6676 def = postfix_expr(state);
6677 break;
6678 }
6679 return def;
6680}
6681
6682static struct triple *cast_expr(struct compile_state *state)
6683{
6684 struct triple *def;
6685 int tok1, tok2;
6686 tok1 = peek(state);
6687 tok2 = peek2(state);
6688 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6689 struct type *type;
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?"
6696 }
6697 else {
6698 def = unary_expr(state);
6699 }
6700 return def;
6701}
6702
6703static struct triple *mult_expr(struct compile_state *state)
6704{
6705 struct triple *def;
6706 int done;
6707 def = cast_expr(state);
6708 do {
6709 struct triple *left, *right;
6710 struct type *result_type;
6711 int tok, op, sign;
6712 done = 0;
6713 switch(tok = (peek(state))) {
6714 case TOK_STAR:
6715 case TOK_DIV:
6716 case TOK_MOD:
6717 left = read_expr(state, def);
6718 arithmetic(state, left);
6719
6720 eat(state, tok);
6721
6722 right = read_expr(state, cast_expr(state));
6723 arithmetic(state, right);
6724
6725 result_type = arithmetic_result(state, left, right);
6726 sign = is_signed(result_type);
6727 op = -1;
6728 switch(tok) {
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;
6732 }
6733 def = triple(state, op, result_type, left, right);
6734 break;
6735 default:
6736 done = 1;
6737 break;
6738 }
6739 } while(!done);
6740 return def;
6741}
6742
6743static struct triple *add_expr(struct compile_state *state)
6744{
6745 struct triple *def;
6746 int done;
6747 def = mult_expr(state);
6748 do {
6749 done = 0;
6750 switch( peek(state)) {
6751 case TOK_PLUS:
6752 eat(state, TOK_PLUS);
6753 def = mk_add_expr(state, def, mult_expr(state));
6754 break;
6755 case TOK_MINUS:
6756 eat(state, TOK_MINUS);
6757 def = mk_sub_expr(state, def, mult_expr(state));
6758 break;
6759 default:
6760 done = 1;
6761 break;
6762 }
6763 } while(!done);
6764 return def;
6765}
6766
6767static struct triple *shift_expr(struct compile_state *state)
6768{
6769 struct triple *def;
6770 int done;
6771 def = add_expr(state);
6772 do {
6773 struct triple *left, *right;
6774 int tok, op;
6775 done = 0;
6776 switch((tok = peek(state))) {
6777 case TOK_SL:
6778 case TOK_SR:
6779 left = read_expr(state, def);
6780 integral(state, left);
6781 left = integral_promotion(state, left);
6782
6783 eat(state, tok);
6784
6785 right = read_expr(state, add_expr(state));
6786 integral(state, right);
6787 right = integral_promotion(state, right);
6788
6789 op = (tok == TOK_SL)? OP_SL :
6790 is_signed(left->type)? OP_SSR: OP_USR;
6791
6792 def = triple(state, op, left->type, left, right);
6793 break;
6794 default:
6795 done = 1;
6796 break;
6797 }
6798 } while(!done);
6799 return def;
6800}
6801
6802static struct triple *relational_expr(struct compile_state *state)
6803{
6804#warning "Extend relational exprs to work on more than arithmetic types"
6805 struct triple *def;
6806 int done;
6807 def = shift_expr(state);
6808 do {
6809 struct triple *left, *right;
6810 struct type *arg_type;
6811 int tok, op, sign;
6812 done = 0;
6813 switch((tok = peek(state))) {
6814 case TOK_LESS:
6815 case TOK_MORE:
6816 case TOK_LESSEQ:
6817 case TOK_MOREEQ:
6818 left = read_expr(state, def);
6819 arithmetic(state, left);
6820
6821 eat(state, tok);
6822
6823 right = read_expr(state, shift_expr(state));
6824 arithmetic(state, right);
6825
6826 arg_type = arithmetic_result(state, left, right);
6827 sign = is_signed(arg_type);
6828 op = -1;
6829 switch(tok) {
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;
6834 }
6835 def = triple(state, op, &int_type, left, right);
6836 break;
6837 default:
6838 done = 1;
6839 break;
6840 }
6841 } while(!done);
6842 return def;
6843}
6844
6845static struct triple *equality_expr(struct compile_state *state)
6846{
6847#warning "Extend equality exprs to work on more than arithmetic types"
6848 struct triple *def;
6849 int done;
6850 def = relational_expr(state);
6851 do {
6852 struct triple *left, *right;
6853 int tok, op;
6854 done = 0;
6855 switch((tok = peek(state))) {
6856 case TOK_EQEQ:
6857 case TOK_NOTEQ:
6858 left = read_expr(state, def);
6859 arithmetic(state, left);
6860 eat(state, tok);
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);
6865 break;
6866 default:
6867 done = 1;
6868 break;
6869 }
6870 } while(!done);
6871 return def;
6872}
6873
6874static struct triple *and_expr(struct compile_state *state)
6875{
6876 struct triple *def;
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);
6888 }
6889 return def;
6890}
6891
6892static struct triple *xor_expr(struct compile_state *state)
6893{
6894 struct triple *def;
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);
6906 }
6907 return def;
6908}
6909
6910static struct triple *or_expr(struct compile_state *state)
6911{
6912 struct triple *def;
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);
6919 eat(state, TOK_OR);
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);
6924 }
6925 return def;
6926}
6927
6928static struct triple *land_expr(struct compile_state *state)
6929{
6930 struct triple *def;
6931 def = or_expr(state);
6932 while(peek(state) == TOK_LOGAND) {
6933 struct triple *left, *right;
6934 left = read_expr(state, def);
6935 bool(state, left);
6936 eat(state, TOK_LOGAND);
6937 right = read_expr(state, or_expr(state));
6938 bool(state, right);
6939
6940 def = triple(state, OP_LAND, &int_type,
6941 ltrue_expr(state, left),
6942 ltrue_expr(state, right));
6943 }
6944 return def;
6945}
6946
6947static struct triple *lor_expr(struct compile_state *state)
6948{
6949 struct triple *def;
6950 def = land_expr(state);
6951 while(peek(state) == TOK_LOGOR) {
6952 struct triple *left, *right;
6953 left = read_expr(state, def);
6954 bool(state, left);
6955 eat(state, TOK_LOGOR);
6956 right = read_expr(state, land_expr(state));
6957 bool(state, right);
6958
6959 def = triple(state, OP_LOR, &int_type,
6960 ltrue_expr(state, left),
6961 ltrue_expr(state, right));
6962 }
6963 return def;
6964}
6965
6966static struct triple *conditional_expr(struct compile_state *state)
6967{
6968 struct triple *def;
6969 def = lor_expr(state);
6970 if (peek(state) == TOK_QUEST) {
6971 struct triple *test, *left, *right;
6972 bool(state, def);
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));
6978
6979 def = cond_expr(state, test, left, right);
6980 }
6981 return def;
6982}
6983
6984static struct triple *eval_const_expr(
6985 struct compile_state *state, struct triple *expr)
6986{
6987 struct triple *def;
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);
6993 }
6994 /* Remove the constant value the tail of the list */
6995 def = head->prev;
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");
7001 }
7002 /* Free the intermediate expressions */
7003 while(head->next != head) {
7004 release_triple(state, head->next);
7005 }
7006 free_triple(state, head);
7007 return def;
7008}
7009
7010static struct triple *constant_expr(struct compile_state *state)
7011{
7012 return eval_const_expr(state, conditional_expr(state));
7013}
7014
7015static struct triple *assignment_expr(struct compile_state *state)
7016{
7017 struct triple *def, *left, *right;
7018 int tok, op, sign;
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.
7023 *
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.
7029 *
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.
7033 *
7034 * GCC has this bug as well, so surprises should be minimal.
7035 */
7036 def = conditional_expr(state);
7037 left = def;
7038 switch((tok = peek(state))) {
7039 case TOK_EQ:
7040 lvalue(state, left);
7041 eat(state, TOK_EQ);
7042 def = write_expr(state, left,
7043 read_expr(state, assignment_expr(state)));
7044 break;
7045 case TOK_TIMESEQ:
7046 case TOK_DIVEQ:
7047 case TOK_MODEQ:
7048 case TOK_PLUSEQ:
7049 case TOK_MINUSEQ:
7050 lvalue(state, left);
7051 arithmetic(state, left);
7052 eat(state, tok);
7053 right = read_expr(state, assignment_expr(state));
7054 arithmetic(state, right);
7055
7056 sign = is_signed(left->type);
7057 op = -1;
7058 switch(tok) {
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;
7064 }
7065 def = write_expr(state, left,
7066 triple(state, op, left->type,
7067 read_expr(state, left), right));
7068 break;
7069 case TOK_SLEQ:
7070 case TOK_SREQ:
7071 case TOK_ANDEQ:
7072 case TOK_XOREQ:
7073 case TOK_OREQ:
7074 lvalue(state, left);
7075 integral(state, left);
7076 eat(state, tok);
7077 right = read_expr(state, assignment_expr(state));
7078 integral(state, right);
7079 right = integral_promotion(state, right);
7080 sign = is_signed(left->type);
7081 op = -1;
7082 switch(tok) {
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;
7088 }
7089 def = write_expr(state, left,
7090 triple(state, op, left->type,
7091 read_expr(state, left), right));
7092 break;
7093 }
7094 return def;
7095}
7096
7097static struct triple *expr(struct compile_state *state)
7098{
7099 struct triple *def;
7100 def = assignment_expr(state);
7101 while(peek(state) == TOK_COMMA) {
7102 struct triple *left, *right;
7103 left = def;
7104 eat(state, TOK_COMMA);
7105 right = assignment_expr(state);
7106 def = triple(state, OP_COMMA, right->type, left, right);
7107 }
7108 return def;
7109}
7110
7111static void expr_statement(struct compile_state *state, struct triple *first)
7112{
7113 if (peek(state) != TOK_SEMI) {
7114 flatten(state, first, expr(state));
7115 }
7116 eat(state, TOK_SEMI);
7117}
7118
7119static void if_statement(struct compile_state *state, struct triple *first)
7120{
7121 struct triple *test, *jmp1, *jmp2, *middle, *end;
7122
7123 jmp1 = jmp2 = middle = 0;
7124 eat(state, TOK_IF);
7125 eat(state, TOK_LPAREN);
7126 test = expr(state);
7127 bool(state, test);
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);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007133 jmp1 = branch(state, middle, test);
Eric Biedermanb138ac82003-04-22 18:44:01 +00007134 /* 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 */
7142 end = label(state);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007143 jmp2 = branch(state, end, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00007144 /* Thread them together */
7145 flatten(state, first, jmp2);
7146 flatten(state, first, middle);
7147 statement(state, first);
7148 flatten(state, first, end);
7149 }
7150 else {
7151 flatten(state, first, middle);
7152 }
7153}
7154
7155static void for_statement(struct compile_state *state, struct triple *first)
7156{
7157 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7158 struct triple *label1, *label2, *label3;
7159 struct hash_entry *ident;
7160
7161 eat(state, TOK_FOR);
7162 eat(state, TOK_LPAREN);
7163 head = test = tail = jmp1 = jmp2 = 0;
7164 if (peek(state) != TOK_SEMI) {
7165 head = expr(state);
7166 }
7167 eat(state, TOK_SEMI);
7168 if (peek(state) != TOK_SEMI) {
7169 test = expr(state);
7170 bool(state, test);
7171 test = ltrue_expr(state, read_expr(state, test));
7172 }
7173 eat(state, TOK_SEMI);
7174 if (peek(state) != TOK_RPAREN) {
7175 tail = expr(state);
7176 }
7177 eat(state, TOK_RPAREN);
7178 /* Generate the needed pieces */
7179 label1 = label(state);
7180 label2 = label(state);
7181 label3 = label(state);
7182 if (test) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00007183 jmp1 = branch(state, label3, 0);
7184 jmp2 = branch(state, label1, test);
Eric Biedermanb138ac82003-04-22 18:44:01 +00007185 }
7186 else {
Eric Biederman0babc1c2003-05-09 02:39:00 +00007187 jmp2 = branch(state, label1, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00007188 }
7189 end = label(state);
7190 /* Remember where break and continue go */
7191 start_scope(state);
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 */
7208 end_scope(state);
7209}
7210
7211static void while_statement(struct compile_state *state, struct triple *first)
7212{
7213 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7214 struct hash_entry *ident;
7215 eat(state, TOK_WHILE);
7216 eat(state, TOK_LPAREN);
7217 test = expr(state);
7218 bool(state, test);
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);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007224 jmp1 = branch(state, label2, 0);
7225 jmp2 = branch(state, label1, test);
Eric Biedermanb138ac82003-04-22 18:44:01 +00007226 end = label(state);
7227 /* Remember where break and continue go */
7228 start_scope(state);
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 */
7242 end_scope(state);
7243}
7244
7245static void do_statement(struct compile_state *state, struct triple *first)
7246{
7247 struct triple *label1, *label2, *test, *end;
7248 struct hash_entry *ident;
7249 eat(state, TOK_DO);
7250 /* Generate the needed pieces */
7251 label1 = label(state);
7252 label2 = label(state);
7253 end = label(state);
7254 /* Remember where break and continue go */
7255 start_scope(state);
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 */
7264 end_scope(state);
7265 /* Eat the rest of the loop */
7266 eat(state, TOK_WHILE);
7267 eat(state, TOK_LPAREN);
7268 test = read_expr(state, expr(state));
7269 bool(state, test);
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);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007276 flatten(state, first, branch(state, label1, test));
Eric Biedermanb138ac82003-04-22 18:44:01 +00007277 flatten(state, first, end);
7278}
7279
7280
7281static void return_statement(struct compile_state *state, struct triple *first)
7282{
7283 struct triple *jmp, *mv, *dest, *var, *val;
7284 int last;
7285 eat(state, TOK_RETURN);
7286
7287#warning "FIXME implement a more general excess branch elimination"
7288 val = 0;
7289 /* If we have a return value do some more work */
7290 if (peek(state) != TOK_SEMI) {
7291 val = read_expr(state, expr(state));
7292 }
7293 eat(state, TOK_SEMI);
7294
7295 /* See if this last statement in a function */
7296 last = ((peek(state) == TOK_RBRACE) &&
7297 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7298
7299 /* Find the return variable */
Eric Biederman0babc1c2003-05-09 02:39:00 +00007300 var = MISC(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00007301 /* Find the return destination */
Eric Biederman0babc1c2003-05-09 02:39:00 +00007302 dest = RHS(state->main_function, 0)->prev;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007303 mv = jmp = 0;
7304 /* If needed generate a jump instruction */
7305 if (!last) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00007306 jmp = branch(state, dest, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00007307 }
7308 /* If needed generate an assignment instruction */
7309 if (val) {
7310 mv = write_expr(state, var, val);
7311 }
7312 /* Now put the code together */
7313 if (mv) {
7314 flatten(state, first, mv);
7315 flatten(state, first, jmp);
7316 }
7317 else if (jmp) {
7318 flatten(state, first, jmp);
7319 }
7320}
7321
7322static void break_statement(struct compile_state *state, struct triple *first)
7323{
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");
7329 }
7330 dest = state->i_break->sym_ident->def;
Eric Biederman0babc1c2003-05-09 02:39:00 +00007331 flatten(state, first, branch(state, dest, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00007332}
7333
7334static void continue_statement(struct compile_state *state, struct triple *first)
7335{
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");
7341 }
7342 dest = state->i_continue->sym_ident->def;
Eric Biederman0babc1c2003-05-09 02:39:00 +00007343 flatten(state, first, branch(state, dest, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00007344}
7345
7346static void goto_statement(struct compile_state *state, struct triple *first)
7347{
7348 FINISHME();
7349 eat(state, TOK_GOTO);
7350 eat(state, TOK_IDENT);
7351 eat(state, TOK_SEMI);
7352 error(state, 0, "goto is not implemeted");
7353 FINISHME();
7354}
7355
7356static void labeled_statement(struct compile_state *state, struct triple *first)
7357{
7358 FINISHME();
7359 eat(state, TOK_IDENT);
7360 eat(state, TOK_COLON);
7361 statement(state, first);
7362 error(state, 0, "labeled statements are not implemented");
7363 FINISHME();
7364}
7365
7366static void switch_statement(struct compile_state *state, struct triple *first)
7367{
7368 FINISHME();
7369 eat(state, TOK_SWITCH);
7370 eat(state, TOK_LPAREN);
7371 expr(state);
7372 eat(state, TOK_RPAREN);
7373 statement(state, first);
7374 error(state, 0, "switch statements are not implemented");
7375 FINISHME();
7376}
7377
7378static void case_statement(struct compile_state *state, struct triple *first)
7379{
7380 FINISHME();
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");
7386 FINISHME();
7387}
7388
7389static void default_statement(struct compile_state *state, struct triple *first)
7390{
7391 FINISHME();
7392 eat(state, TOK_DEFAULT);
7393 eat(state, TOK_COLON);
7394 statement(state, first);
7395 error(state, 0, "default statements are not implemented");
7396 FINISHME();
7397}
7398
7399static void asm_statement(struct compile_state *state, struct triple *first)
7400{
7401 FINISHME();
7402 error(state, 0, "FIXME finish asm_statement");
7403}
7404
7405
7406static int isdecl(int tok)
7407{
7408 switch(tok) {
7409 case TOK_AUTO:
7410 case TOK_REGISTER:
7411 case TOK_STATIC:
7412 case TOK_EXTERN:
7413 case TOK_TYPEDEF:
7414 case TOK_CONST:
7415 case TOK_RESTRICT:
7416 case TOK_VOLATILE:
7417 case TOK_VOID:
7418 case TOK_CHAR:
7419 case TOK_SHORT:
7420 case TOK_INT:
7421 case TOK_LONG:
7422 case TOK_FLOAT:
7423 case TOK_DOUBLE:
7424 case TOK_SIGNED:
7425 case TOK_UNSIGNED:
7426 case TOK_STRUCT:
7427 case TOK_UNION:
7428 case TOK_ENUM:
7429 case TOK_TYPE_NAME: /* typedef name */
7430 return 1;
7431 default:
7432 return 0;
7433 }
7434}
7435
7436static void compound_statement(struct compile_state *state, struct triple *first)
7437{
7438 eat(state, TOK_LBRACE);
7439 start_scope(state);
7440
7441 /* statement-list opt */
7442 while (peek(state) != TOK_RBRACE) {
7443 statement(state, first);
7444 }
7445 end_scope(state);
7446 eat(state, TOK_RBRACE);
7447}
7448
7449static void statement(struct compile_state *state, struct triple *first)
7450{
7451 int tok;
7452 tok = peek(state);
7453 if (tok == TOK_LBRACE) {
7454 compound_statement(state, first);
7455 }
7456 else if (tok == TOK_IF) {
7457 if_statement(state, first);
7458 }
7459 else if (tok == TOK_FOR) {
7460 for_statement(state, first);
7461 }
7462 else if (tok == TOK_WHILE) {
7463 while_statement(state, first);
7464 }
7465 else if (tok == TOK_DO) {
7466 do_statement(state, first);
7467 }
7468 else if (tok == TOK_RETURN) {
7469 return_statement(state, first);
7470 }
7471 else if (tok == TOK_BREAK) {
7472 break_statement(state, first);
7473 }
7474 else if (tok == TOK_CONTINUE) {
7475 continue_statement(state, first);
7476 }
7477 else if (tok == TOK_GOTO) {
7478 goto_statement(state, first);
7479 }
7480 else if (tok == TOK_SWITCH) {
7481 switch_statement(state, first);
7482 }
7483 else if (tok == TOK_ASM) {
7484 asm_statement(state, first);
7485 }
7486 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7487 labeled_statement(state, first);
7488 }
7489 else if (tok == TOK_CASE) {
7490 case_statement(state, first);
7491 }
7492 else if (tok == TOK_DEFAULT) {
7493 default_statement(state, first);
7494 }
7495 else if (isdecl(tok)) {
7496 /* This handles C99 intermixing of statements and decls */
7497 decl(state, first);
7498 }
7499 else {
7500 expr_statement(state, first);
7501 }
7502}
7503
7504static struct type *param_decl(struct compile_state *state)
7505{
7506 struct type *type;
7507 struct hash_entry *ident;
7508 /* Cheat so the declarator will know we are not global */
7509 start_scope(state);
7510 ident = 0;
7511 type = decl_specifiers(state);
7512 type = declarator(state, type, &ident, 0);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007513 type->field_ident = ident;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007514 end_scope(state);
7515 return type;
7516}
7517
7518static struct type *param_type_list(struct compile_state *state, struct type *type)
7519{
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");
7528 }
7529 else {
7530 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7531 next = &((*next)->right);
7532 }
7533 }
7534 return ftype;
7535}
7536
7537
7538static struct type *type_name(struct compile_state *state)
7539{
7540 struct type *type;
7541 type = specifier_qualifier_list(state);
7542 /* abstract-declarator (may consume no tokens) */
7543 type = declarator(state, type, 0, 0);
7544 return type;
7545}
7546
7547static struct type *direct_declarator(
7548 struct compile_state *state, struct type *type,
7549 struct hash_entry **ident, int need_ident)
7550{
7551 struct type *outer;
7552 int op;
7553 outer = 0;
7554 arrays_complete(state, type);
7555 switch(peek(state)) {
7556 case TOK_IDENT:
7557 eat(state, TOK_IDENT);
7558 if (!ident) {
7559 error(state, 0, "Unexpected identifier found");
7560 }
7561 /* The name of what we are declaring */
7562 *ident = state->token[0].ident;
7563 break;
7564 case TOK_LPAREN:
7565 eat(state, TOK_LPAREN);
7566 outer = declarator(state, type, ident, need_ident);
7567 eat(state, TOK_RPAREN);
7568 break;
7569 default:
7570 if (need_ident) {
7571 error(state, 0, "Identifier expected");
7572 }
7573 break;
7574 }
7575 do {
7576 op = 1;
7577 arrays_complete(state, type);
7578 switch(peek(state)) {
7579 case TOK_LPAREN:
7580 eat(state, TOK_LPAREN);
7581 type = param_type_list(state, type);
7582 eat(state, TOK_RPAREN);
7583 break;
7584 case TOK_LBRACKET:
7585 {
7586 unsigned int qualifiers;
7587 struct triple *value;
7588 value = 0;
7589 eat(state, TOK_LBRACKET);
7590 if (peek(state) != TOK_RBRACKET) {
7591 value = constant_expr(state);
7592 integral(state, value);
7593 }
7594 eat(state, TOK_RBRACKET);
7595
7596 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
7597 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
7598 if (value) {
7599 type->elements = value->u.cval;
7600 free_triple(state, value);
7601 } else {
7602 type->elements = ELEMENT_COUNT_UNSPECIFIED;
7603 op = 0;
7604 }
7605 }
7606 break;
7607 default:
7608 op = 0;
7609 break;
7610 }
7611 } while(op);
7612 if (outer) {
7613 struct type *inner;
7614 arrays_complete(state, type);
7615 FINISHME();
7616 for(inner = outer; inner->left; inner = inner->left)
7617 ;
7618 inner->left = type;
7619 type = outer;
7620 }
7621 return type;
7622}
7623
7624static struct type *declarator(
7625 struct compile_state *state, struct type *type,
7626 struct hash_entry **ident, int need_ident)
7627{
7628 while(peek(state) == TOK_STAR) {
7629 eat(state, TOK_STAR);
7630 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
7631 }
7632 type = direct_declarator(state, type, ident, need_ident);
7633 return type;
7634}
7635
7636
7637static struct type *typedef_name(
7638 struct compile_state *state, unsigned int specifiers)
7639{
7640 struct hash_entry *ident;
7641 struct type *type;
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);
7649 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00007650 return type;
7651}
7652
7653static struct type *enum_specifier(
7654 struct compile_state *state, unsigned int specifiers)
7655{
7656 int tok;
7657 struct type *type;
7658 type = 0;
7659 FINISHME();
7660 eat(state, TOK_ENUM);
7661 tok = peek(state);
7662 if (tok == TOK_IDENT) {
7663 eat(state, TOK_IDENT);
7664 }
7665 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
7666 eat(state, TOK_LBRACE);
7667 do {
7668 eat(state, TOK_IDENT);
7669 if (peek(state) == TOK_EQ) {
7670 eat(state, TOK_EQ);
7671 constant_expr(state);
7672 }
7673 if (peek(state) == TOK_COMMA) {
7674 eat(state, TOK_COMMA);
7675 }
7676 } while(peek(state) != TOK_RBRACE);
7677 eat(state, TOK_RBRACE);
7678 }
7679 FINISHME();
7680 return type;
7681}
7682
7683#if 0
7684static struct type *struct_declarator(
7685 struct compile_state *state, struct type *type, struct hash_entry **ident)
7686{
7687 int tok;
7688#warning "struct_declarator is complicated because of bitfields, kill them?"
7689 tok = peek(state);
7690 if (tok != TOK_COLON) {
7691 type = declarator(state, type, ident, 1);
7692 }
7693 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
7694 eat(state, TOK_COLON);
7695 constant_expr(state);
7696 }
7697 FINISHME();
7698 return type;
7699}
7700#endif
7701
7702static struct type *struct_or_union_specifier(
7703 struct compile_state *state, unsigned int specifiers)
7704{
Eric Biederman0babc1c2003-05-09 02:39:00 +00007705 struct type *struct_type;
7706 struct hash_entry *ident;
7707 unsigned int type_join;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007708 int tok;
Eric Biederman0babc1c2003-05-09 02:39:00 +00007709 struct_type = 0;
7710 ident = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007711 switch(peek(state)) {
7712 case TOK_STRUCT:
7713 eat(state, TOK_STRUCT);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007714 type_join = TYPE_PRODUCT;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007715 break;
7716 case TOK_UNION:
7717 eat(state, TOK_UNION);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007718 type_join = TYPE_OVERLAP;
7719 error(state, 0, "unions not yet supported\n");
Eric Biedermanb138ac82003-04-22 18:44:01 +00007720 break;
7721 default:
7722 eat(state, TOK_STRUCT);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007723 type_join = TYPE_PRODUCT;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007724 break;
7725 }
7726 tok = peek(state);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007727 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
7728 eat(state, tok);
7729 ident = state->token[0].ident;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007730 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00007731 if (!ident || (peek(state) == TOK_LBRACE)) {
7732 ulong_t elements;
7733 elements = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007734 eat(state, TOK_LBRACE);
7735 do {
7736 struct type *base_type;
Eric Biederman0babc1c2003-05-09 02:39:00 +00007737 struct type **next;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007738 int done;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007739 base_type = specifier_qualifier_list(state);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007740 next = &struct_type;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007741 do {
7742 struct type *type;
Eric Biederman0babc1c2003-05-09 02:39:00 +00007743 struct hash_entry *fident;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007744 done = 1;
Eric Biederman0babc1c2003-05-09 02:39:00 +00007745 type = declarator(state, base_type, &fident, 1);
7746 elements++;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007747 if (peek(state) == TOK_COMMA) {
7748 done = 0;
7749 eat(state, TOK_COMMA);
7750 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00007751 type = clone_type(0, type);
7752 type->field_ident = fident;
7753 if (*next) {
7754 *next = new_type(type_join, *next, type);
7755 next = &((*next)->right);
7756 } else {
7757 *next = type;
7758 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00007759 } while(!done);
7760 eat(state, TOK_SEMI);
7761 } while(peek(state) != TOK_RBRACE);
7762 eat(state, TOK_RBRACE);
Eric Biederman0babc1c2003-05-09 02:39:00 +00007763 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);
Eric Biedermanb138ac82003-04-22 18:44:01 +00007767 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00007768 if (ident && ident->sym_struct) {
7769 struct_type = ident->sym_struct->type;
7770 }
7771 else if (ident && !ident->sym_struct) {
7772 error(state, 0, "struct %s undeclared", ident->name);
7773 }
7774 return struct_type;
Eric Biedermanb138ac82003-04-22 18:44:01 +00007775}
7776
7777static unsigned int storage_class_specifier_opt(struct compile_state *state)
7778{
7779 unsigned int specifiers;
7780 switch(peek(state)) {
7781 case TOK_AUTO:
7782 eat(state, TOK_AUTO);
7783 specifiers = STOR_AUTO;
7784 break;
7785 case TOK_REGISTER:
7786 eat(state, TOK_REGISTER);
7787 specifiers = STOR_REGISTER;
7788 break;
7789 case TOK_STATIC:
7790 eat(state, TOK_STATIC);
7791 specifiers = STOR_STATIC;
7792 break;
7793 case TOK_EXTERN:
7794 eat(state, TOK_EXTERN);
7795 specifiers = STOR_EXTERN;
7796 break;
7797 case TOK_TYPEDEF:
7798 eat(state, TOK_TYPEDEF);
7799 specifiers = STOR_TYPEDEF;
7800 break;
7801 default:
7802 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
7803 specifiers = STOR_STATIC;
7804 }
7805 else {
7806 specifiers = STOR_AUTO;
7807 }
7808 }
7809 return specifiers;
7810}
7811
7812static unsigned int function_specifier_opt(struct compile_state *state)
7813{
7814 /* Ignore the inline keyword */
7815 unsigned int specifiers;
7816 specifiers = 0;
7817 switch(peek(state)) {
7818 case TOK_INLINE:
7819 eat(state, TOK_INLINE);
7820 specifiers = STOR_INLINE;
7821 }
7822 return specifiers;
7823}
7824
7825static unsigned int type_qualifiers(struct compile_state *state)
7826{
7827 unsigned int specifiers;
7828 int done;
7829 done = 0;
7830 specifiers = QUAL_NONE;
7831 do {
7832 switch(peek(state)) {
7833 case TOK_CONST:
7834 eat(state, TOK_CONST);
7835 specifiers = QUAL_CONST;
7836 break;
7837 case TOK_VOLATILE:
7838 eat(state, TOK_VOLATILE);
7839 specifiers = QUAL_VOLATILE;
7840 break;
7841 case TOK_RESTRICT:
7842 eat(state, TOK_RESTRICT);
7843 specifiers = QUAL_RESTRICT;
7844 break;
7845 default:
7846 done = 1;
7847 break;
7848 }
7849 } while(!done);
7850 return specifiers;
7851}
7852
7853static struct type *type_specifier(
7854 struct compile_state *state, unsigned int spec)
7855{
7856 struct type *type;
7857 type = 0;
7858 switch(peek(state)) {
7859 case TOK_VOID:
7860 eat(state, TOK_VOID);
7861 type = new_type(TYPE_VOID | spec, 0, 0);
7862 break;
7863 case TOK_CHAR:
7864 eat(state, TOK_CHAR);
7865 type = new_type(TYPE_CHAR | spec, 0, 0);
7866 break;
7867 case TOK_SHORT:
7868 eat(state, TOK_SHORT);
7869 if (peek(state) == TOK_INT) {
7870 eat(state, TOK_INT);
7871 }
7872 type = new_type(TYPE_SHORT | spec, 0, 0);
7873 break;
7874 case TOK_INT:
7875 eat(state, TOK_INT);
7876 type = new_type(TYPE_INT | spec, 0, 0);
7877 break;
7878 case TOK_LONG:
7879 eat(state, TOK_LONG);
7880 switch(peek(state)) {
7881 case TOK_LONG:
7882 eat(state, TOK_LONG);
7883 error(state, 0, "long long not supported");
7884 break;
7885 case TOK_DOUBLE:
7886 eat(state, TOK_DOUBLE);
7887 error(state, 0, "long double not supported");
7888 break;
7889 case TOK_INT:
7890 eat(state, TOK_INT);
7891 type = new_type(TYPE_LONG | spec, 0, 0);
7892 break;
7893 default:
7894 type = new_type(TYPE_LONG | spec, 0, 0);
7895 break;
7896 }
7897 break;
7898 case TOK_FLOAT:
7899 eat(state, TOK_FLOAT);
7900 error(state, 0, "type float not supported");
7901 break;
7902 case TOK_DOUBLE:
7903 eat(state, TOK_DOUBLE);
7904 error(state, 0, "type double not supported");
7905 break;
7906 case TOK_SIGNED:
7907 eat(state, TOK_SIGNED);
7908 switch(peek(state)) {
7909 case TOK_LONG:
7910 eat(state, TOK_LONG);
7911 switch(peek(state)) {
7912 case TOK_LONG:
7913 eat(state, TOK_LONG);
7914 error(state, 0, "type long long not supported");
7915 break;
7916 case TOK_INT:
7917 eat(state, TOK_INT);
7918 type = new_type(TYPE_LONG | spec, 0, 0);
7919 break;
7920 default:
7921 type = new_type(TYPE_LONG | spec, 0, 0);
7922 break;
7923 }
7924 break;
7925 case TOK_INT:
7926 eat(state, TOK_INT);
7927 type = new_type(TYPE_INT | spec, 0, 0);
7928 break;
7929 case TOK_SHORT:
7930 eat(state, TOK_SHORT);
7931 type = new_type(TYPE_SHORT | spec, 0, 0);
7932 break;
7933 case TOK_CHAR:
7934 eat(state, TOK_CHAR);
7935 type = new_type(TYPE_CHAR | spec, 0, 0);
7936 break;
7937 default:
7938 type = new_type(TYPE_INT | spec, 0, 0);
7939 break;
7940 }
7941 break;
7942 case TOK_UNSIGNED:
7943 eat(state, TOK_UNSIGNED);
7944 switch(peek(state)) {
7945 case TOK_LONG:
7946 eat(state, TOK_LONG);
7947 switch(peek(state)) {
7948 case TOK_LONG:
7949 eat(state, TOK_LONG);
7950 error(state, 0, "unsigned long long not supported");
7951 break;
7952 case TOK_INT:
7953 eat(state, TOK_INT);
7954 type = new_type(TYPE_ULONG | spec, 0, 0);
7955 break;
7956 default:
7957 type = new_type(TYPE_ULONG | spec, 0, 0);
7958 break;
7959 }
7960 break;
7961 case TOK_INT:
7962 eat(state, TOK_INT);
7963 type = new_type(TYPE_UINT | spec, 0, 0);
7964 break;
7965 case TOK_SHORT:
7966 eat(state, TOK_SHORT);
7967 type = new_type(TYPE_USHORT | spec, 0, 0);
7968 break;
7969 case TOK_CHAR:
7970 eat(state, TOK_CHAR);
7971 type = new_type(TYPE_UCHAR | spec, 0, 0);
7972 break;
7973 default:
7974 type = new_type(TYPE_UINT | spec, 0, 0);
7975 break;
7976 }
7977 break;
7978 /* struct or union specifier */
7979 case TOK_STRUCT:
7980 case TOK_UNION:
7981 type = struct_or_union_specifier(state, spec);
7982 break;
7983 /* enum-spefifier */
7984 case TOK_ENUM:
7985 type = enum_specifier(state, spec);
7986 break;
7987 /* typedef name */
7988 case TOK_TYPE_NAME:
7989 type = typedef_name(state, spec);
7990 break;
7991 default:
7992 error(state, 0, "bad type specifier %s",
7993 tokens[peek(state)]);
7994 break;
7995 }
7996 return type;
7997}
7998
7999static int istype(int tok)
8000{
8001 switch(tok) {
8002 case TOK_CONST:
8003 case TOK_RESTRICT:
8004 case TOK_VOLATILE:
8005 case TOK_VOID:
8006 case TOK_CHAR:
8007 case TOK_SHORT:
8008 case TOK_INT:
8009 case TOK_LONG:
8010 case TOK_FLOAT:
8011 case TOK_DOUBLE:
8012 case TOK_SIGNED:
8013 case TOK_UNSIGNED:
8014 case TOK_STRUCT:
8015 case TOK_UNION:
8016 case TOK_ENUM:
8017 case TOK_TYPE_NAME:
8018 return 1;
8019 default:
8020 return 0;
8021 }
8022}
8023
8024
8025static struct type *specifier_qualifier_list(struct compile_state *state)
8026{
8027 struct type *type;
8028 unsigned int specifiers = 0;
8029
8030 /* type qualifiers */
8031 specifiers |= type_qualifiers(state);
8032
8033 /* type specifier */
8034 type = type_specifier(state, specifiers);
8035
8036 return type;
8037}
8038
8039static int isdecl_specifier(int tok)
8040{
8041 switch(tok) {
8042 /* storage class specifier */
8043 case TOK_AUTO:
8044 case TOK_REGISTER:
8045 case TOK_STATIC:
8046 case TOK_EXTERN:
8047 case TOK_TYPEDEF:
8048 /* type qualifier */
8049 case TOK_CONST:
8050 case TOK_RESTRICT:
8051 case TOK_VOLATILE:
8052 /* type specifiers */
8053 case TOK_VOID:
8054 case TOK_CHAR:
8055 case TOK_SHORT:
8056 case TOK_INT:
8057 case TOK_LONG:
8058 case TOK_FLOAT:
8059 case TOK_DOUBLE:
8060 case TOK_SIGNED:
8061 case TOK_UNSIGNED:
8062 /* struct or union specifier */
8063 case TOK_STRUCT:
8064 case TOK_UNION:
8065 /* enum-spefifier */
8066 case TOK_ENUM:
8067 /* typedef name */
8068 case TOK_TYPE_NAME:
8069 /* function specifiers */
8070 case TOK_INLINE:
8071 return 1;
8072 default:
8073 return 0;
8074 }
8075}
8076
8077static struct type *decl_specifiers(struct compile_state *state)
8078{
8079 struct type *type;
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.
8084 */
8085 specifiers = 0;
8086
8087 /* storage class specifier */
8088 specifiers |= storage_class_specifier_opt(state);
8089
8090 /* function-specifier */
8091 specifiers |= function_specifier_opt(state);
8092
8093 /* type qualifier */
8094 specifiers |= type_qualifiers(state);
8095
8096 /* type specifier */
8097 type = type_specifier(state, specifiers);
8098 return type;
8099}
8100
8101static unsigned designator(struct compile_state *state)
8102{
8103 int tok;
8104 unsigned index;
8105 index = -1U;
8106 do {
8107 switch(peek(state)) {
8108 case TOK_LBRACKET:
8109 {
8110 struct triple *value;
8111 eat(state, TOK_LBRACKET);
8112 value = constant_expr(state);
8113 eat(state, TOK_RBRACKET);
8114 index = value->u.cval;
8115 break;
8116 }
8117 case TOK_DOT:
8118 eat(state, TOK_DOT);
8119 eat(state, TOK_IDENT);
8120 error(state, 0, "Struct Designators not currently supported");
8121 break;
8122 default:
8123 error(state, 0, "Invalid designator");
8124 }
8125 tok = peek(state);
8126 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8127 eat(state, TOK_EQ);
8128 return index;
8129}
8130
8131static struct triple *initializer(
8132 struct compile_state *state, struct type *type)
8133{
8134 struct triple *result;
8135 if (peek(state) != TOK_LBRACE) {
8136 result = assignment_expr(state);
8137 }
8138 else {
8139 int comma;
8140 unsigned index, max_index;
8141 void *buf;
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) {
8146 type->elements = 0;
8147 }
8148 } else {
8149 error(state, 0, "Struct initializers not currently supported");
8150 }
8151 buf = xcmalloc(size_of(state, type), "initializer");
8152 eat(state, TOK_LBRACE);
8153 do {
8154 struct triple *value;
8155 struct type *value_type;
8156 size_t value_size;
8157 int tok;
8158 comma = 0;
8159 tok = peek(state);
8160 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8161 index = designator(state);
8162 }
8163 if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8164 (index > max_index)) {
8165 error(state, 0, "element beyond bounds");
8166 }
8167 value_type = 0;
8168 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8169 value_type = type->left;
8170 }
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)) {
8176 void *old_buf;
8177 size_t old_size;
8178 old_buf = buf;
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);
8183 xfree(old_buf);
8184 }
8185 if (value->op == OP_BLOBCONST) {
8186 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8187 }
8188 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8189 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8190 }
8191 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8192 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8193 }
8194 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8195 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8196 }
8197 else {
8198 fprintf(stderr, "%d %d\n",
8199 value->op, value_size);
8200 internal_error(state, 0, "unhandled constant initializer");
8201 }
8202 if (peek(state) == TOK_COMMA) {
8203 eat(state, TOK_COMMA);
8204 comma = 1;
8205 }
8206 index += 1;
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;
8211 }
8212 return result;
8213}
8214
8215static struct triple *function_definition(
8216 struct compile_state *state, struct type *type)
8217{
8218 struct triple *def, *tmp, *first, *end;
8219 struct hash_entry *ident;
8220 struct type *param;
8221 int i;
8222 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8223 error(state, 0, "Invalid function header");
8224 }
8225
8226 /* Verify the function type */
8227 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8228 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
Eric Biederman0babc1c2003-05-09 02:39:00 +00008229 (type->right->field_ident == 0)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00008230 error(state, 0, "Invalid function parameters");
8231 }
8232 param = type->right;
8233 i = 0;
8234 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8235 i++;
Eric Biederman0babc1c2003-05-09 02:39:00 +00008236 if (!param->left->field_ident) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00008237 error(state, 0, "No identifier for parameter %d\n", i);
8238 }
8239 param = param->right;
8240 }
8241 i++;
Eric Biederman0babc1c2003-05-09 02:39:00 +00008242 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00008243 error(state, 0, "No identifier for paramter %d\n", i);
8244 }
8245
8246 /* Get a list of statements for this function. */
8247 def = triple(state, OP_LIST, type, 0, 0);
8248
8249 /* Start a new scope for the passed parameters */
8250 start_scope(state);
8251
8252 /* Put a label at the very start of a function */
8253 first = label(state);
Eric Biederman0babc1c2003-05-09 02:39:00 +00008254 RHS(def, 0) = first;
Eric Biedermanb138ac82003-04-22 18:44:01 +00008255
8256 /* Put a label at the very end of a function */
8257 end = label(state);
8258 flatten(state, first, end);
8259
8260 /* Walk through the parameters and create symbol table entries
8261 * for them.
8262 */
8263 param = type->right;
8264 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
Eric Biederman0babc1c2003-05-09 02:39:00 +00008265 ident = param->left->field_ident;
Eric Biedermanb138ac82003-04-22 18:44:01 +00008266 tmp = variable(state, param->left);
8267 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8268 flatten(state, end, tmp);
8269 param = param->right;
8270 }
8271 if ((param->type & TYPE_MASK) != TYPE_VOID) {
8272 /* And don't forget the last parameter */
Eric Biederman0babc1c2003-05-09 02:39:00 +00008273 ident = param->field_ident;
Eric Biedermanb138ac82003-04-22 18:44:01 +00008274 tmp = variable(state, param);
8275 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8276 flatten(state, end, tmp);
8277 }
8278 /* Add a variable for the return value */
Eric Biederman0babc1c2003-05-09 02:39:00 +00008279 MISC(def, 0) = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00008280 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 */
Eric Biederman0babc1c2003-05-09 02:39:00 +00008285 MISC(def, 0) = tmp;
Eric Biedermanb138ac82003-04-22 18:44:01 +00008286 }
8287
8288 /* Remember which function I am compiling.
8289 * Also assume the last defined function is the main function.
8290 */
8291 state->main_function = def;
8292
8293 /* Now get the actual function definition */
8294 compound_statement(state, end);
8295
8296 /* Remove the parameter scope */
8297 end_scope(state);
8298#if 0
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");
8304#endif
8305
8306 return def;
8307}
8308
8309static struct triple *do_decl(struct compile_state *state,
8310 struct type *type, struct hash_entry *ident)
8311{
8312 struct triple *def;
8313 def = 0;
8314 /* Clean up the storage types used */
8315 switch (type->type & STOR_MASK) {
8316 case STOR_AUTO:
8317 case STOR_STATIC:
8318 /* These are the good types I am aiming for */
8319 break;
8320 case STOR_REGISTER:
8321 type->type &= ~STOR_MASK;
8322 type->type |= STOR_AUTO;
8323 break;
8324 case STOR_EXTERN:
8325 type->type &= ~STOR_MASK;
8326 type->type |= STOR_STATIC;
8327 break;
8328 case STOR_TYPEDEF:
Eric Biederman0babc1c2003-05-09 02:39:00 +00008329 if (!ident) {
8330 error(state, 0, "typedef without name");
8331 }
8332 symbol(state, ident, &ident->sym_ident, 0, type);
8333 ident->tok = TOK_TYPE_NAME;
8334 return 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00008335 break;
8336 default:
8337 internal_error(state, 0, "Undefined storage class");
8338 }
8339 if (((type->type & STOR_MASK) == STOR_STATIC) &&
8340 ((type->type & QUAL_CONST) == 0)) {
8341 error(state, 0, "non const static variables not supported");
8342 }
8343 if (ident) {
8344 def = variable(state, type);
8345 symbol(state, ident, &ident->sym_ident, def, type);
8346 }
8347 return def;
8348}
8349
8350static void decl(struct compile_state *state, struct triple *first)
8351{
8352 struct type *base_type, *type;
8353 struct hash_entry *ident;
8354 struct triple *def;
8355 int global;
8356 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8357 base_type = decl_specifiers(state);
8358 ident = 0;
8359 type = declarator(state, base_type, &ident, 0);
8360 if (global && ident && (peek(state) == TOK_LBRACE)) {
8361 /* function */
8362 def = function_definition(state, type);
8363 symbol(state, ident, &ident->sym_ident, def, type);
8364 }
8365 else {
8366 int done;
8367 flatten(state, first, do_decl(state, type, ident));
8368 /* type or variable definition */
8369 do {
8370 done = 1;
8371 if (peek(state) == TOK_EQ) {
8372 if (!ident) {
8373 error(state, 0, "cannot assign to a type");
8374 }
8375 eat(state, TOK_EQ);
8376 flatten(state, first,
8377 init_expr(state,
8378 ident->sym_ident->def,
8379 initializer(state, type)));
8380 }
8381 arrays_complete(state, type);
8382 if (peek(state) == TOK_COMMA) {
8383 eat(state, TOK_COMMA);
8384 ident = 0;
8385 type = declarator(state, base_type, &ident, 0);
8386 flatten(state, first, do_decl(state, type, ident));
8387 done = 0;
8388 }
8389 } while(!done);
8390 eat(state, TOK_SEMI);
8391 }
8392}
8393
8394static void decls(struct compile_state *state)
8395{
8396 struct triple *list;
8397 int tok;
8398 list = label(state);
8399 while(1) {
8400 tok = peek(state);
8401 if (tok == TOK_EOF) {
8402 return;
8403 }
8404 if (tok == TOK_SPACE) {
8405 eat(state, TOK_SPACE);
8406 }
8407 decl(state, list);
8408 if (list->next != list) {
8409 error(state, 0, "global variables not supported");
8410 }
8411 }
8412}
8413
8414/*
8415 * Data structurs for optimation.
8416 */
8417
8418static void do_use_block(
8419 struct block *used, struct block_set **head, struct block *user,
8420 int front)
8421{
8422 struct block_set **ptr, *new;
8423 if (!used)
8424 return;
8425 if (!user)
8426 return;
8427 ptr = head;
8428 while(*ptr) {
8429 if ((*ptr)->member == user) {
8430 return;
8431 }
8432 ptr = &(*ptr)->next;
8433 }
8434 new = xcmalloc(sizeof(*new), "block_set");
8435 new->member = user;
8436 if (front) {
8437 new->next = *head;
8438 *head = new;
8439 }
8440 else {
8441 new->next = 0;
8442 *ptr = new;
8443 }
8444}
8445static void do_unuse_block(
8446 struct block *used, struct block_set **head, struct block *unuser)
8447{
8448 struct block_set *use, **ptr;
8449 ptr = head;
8450 while(*ptr) {
8451 use = *ptr;
8452 if (use->member == unuser) {
8453 *ptr = use->next;
8454 memset(use, -1, sizeof(*use));
8455 xfree(use);
8456 }
8457 else {
8458 ptr = &use->next;
8459 }
8460 }
8461}
8462
8463static void use_block(struct block *used, struct block *user)
8464{
8465 /* Append new to the head of the list, print_block
8466 * depends on this.
8467 */
8468 do_use_block(used, &used->use, user, 1);
8469 used->users++;
8470}
8471static void unuse_block(struct block *used, struct block *unuser)
8472{
8473 do_unuse_block(used, &used->use, unuser);
8474 used->users--;
8475}
8476
8477static void idom_block(struct block *idom, struct block *user)
8478{
8479 do_use_block(idom, &idom->idominates, user, 0);
8480}
8481
8482static void unidom_block(struct block *idom, struct block *unuser)
8483{
8484 do_unuse_block(idom, &idom->idominates, unuser);
8485}
8486
8487static void domf_block(struct block *block, struct block *domf)
8488{
8489 do_use_block(block, &block->domfrontier, domf, 0);
8490}
8491
8492static void undomf_block(struct block *block, struct block *undomf)
8493{
8494 do_unuse_block(block, &block->domfrontier, undomf);
8495}
8496
8497static void ipdom_block(struct block *ipdom, struct block *user)
8498{
8499 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8500}
8501
8502static void unipdom_block(struct block *ipdom, struct block *unuser)
8503{
8504 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8505}
8506
8507static void ipdomf_block(struct block *block, struct block *ipdomf)
8508{
8509 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8510}
8511
8512static void unipdomf_block(struct block *block, struct block *unipdomf)
8513{
8514 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8515}
8516
8517
8518
8519static 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))
8522{
8523 int result;
8524 result = cb(state, ptr, depth);
8525 if ((result == 0) && (ptr->op == OP_LIST)) {
8526 struct triple *list;
8527 list = ptr;
Eric Biederman0babc1c2003-05-09 02:39:00 +00008528 ptr = RHS(list, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00008529 do {
8530 result = do_walk_triple(state, ptr, depth + 1, cb);
8531 if (ptr->next->prev != ptr) {
8532 internal_error(state, ptr->next, "bad prev");
8533 }
8534 ptr = ptr->next;
8535
Eric Biederman0babc1c2003-05-09 02:39:00 +00008536 } while((result == 0) && (ptr != RHS(list, 0)));
Eric Biedermanb138ac82003-04-22 18:44:01 +00008537 }
8538 return result;
8539}
8540
8541static int walk_triple(
8542 struct compile_state *state,
8543 struct triple *ptr,
8544 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8545{
8546 return do_walk_triple(state, ptr, 0, cb);
8547}
8548
8549static void do_print_prefix(int depth)
8550{
8551 int i;
8552 for(i = 0; i < depth; i++) {
8553 printf(" ");
8554 }
8555}
8556
8557#define PRINT_LIST 1
8558static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8559{
8560 int op;
8561 op = ins->op;
8562 if (op == OP_LIST) {
8563#if !PRINT_LIST
8564 return 0;
8565#endif
8566 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00008567 if ((op == OP_LABEL) && (ins->use)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00008568 printf("\n%p:\n", ins);
8569 }
Eric Biedermanb138ac82003-04-22 18:44:01 +00008570 do_print_prefix(depth);
Eric Biederman0babc1c2003-05-09 02:39:00 +00008571 display_triple(stdout, ins);
8572
Eric Biedermanb138ac82003-04-22 18:44:01 +00008573 if ((ins->op == OP_BRANCH) && ins->use) {
8574 internal_error(state, ins, "branch used?");
8575 }
8576#if 0
8577 {
8578 struct triple_set *user;
8579 for(user = ins->use; user; user = user->next) {
8580 printf("use: %p\n", user->member);
8581 }
8582 }
8583#endif
Eric Biederman0babc1c2003-05-09 02:39:00 +00008584 if (triple_is_branch(state, ins)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00008585 printf("\n");
8586 }
8587 return 0;
8588}
8589
8590static void print_triple(struct compile_state *state, struct triple *ins)
8591{
8592 walk_triple(state, ins, do_print_triple);
8593}
8594
8595static void print_triples(struct compile_state *state)
8596{
8597 print_triple(state, state->main_function);
8598}
8599
8600struct cf_block {
8601 struct block *block;
8602};
8603static void find_cf_blocks(struct cf_block *cf, struct block *block)
8604{
8605 if (!block || (cf[block->vertex].block == block)) {
8606 return;
8607 }
8608 cf[block->vertex].block = block;
8609 find_cf_blocks(cf, block->left);
8610 find_cf_blocks(cf, block->right);
8611}
8612
8613static void print_control_flow(struct compile_state *state)
8614{
8615 struct cf_block *cf;
8616 int i;
8617 printf("\ncontrol flow\n");
8618 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
8619 find_cf_blocks(cf, state->first_block);
8620
8621 for(i = 1; i <= state->last_vertex; i++) {
8622 struct block *block;
8623 block = cf[i].block;
8624 if (!block)
8625 continue;
8626 printf("(%p) %d:", block, block->vertex);
8627 if (block->left) {
8628 printf(" %d", block->left->vertex);
8629 }
8630 if (block->right && (block->right != block->left)) {
8631 printf(" %d", block->right->vertex);
8632 }
8633 printf("\n");
8634 }
8635
8636 xfree(cf);
8637}
8638
8639
8640static struct block *basic_block(struct compile_state *state,
8641 struct triple *first)
8642{
8643 struct block *block;
8644 struct triple *ptr;
8645 int op;
8646 if (first->op != OP_LABEL) {
8647 internal_error(state, 0, "block does not start with a label");
8648 }
8649 /* See if this basic block has already been setup */
8650 if (first->u.block != 0) {
8651 return first->u.block;
8652 }
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;
8658 ptr = first;
8659 do {
8660 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
8661 break;
8662 }
8663 block->last = ptr;
8664 /* If ptr->u is not used remember where the baic block is */
8665 if (!is_const(ptr)) {
8666 ptr->u.block = block;
8667 }
8668 if (ptr->op == OP_BRANCH) {
8669 break;
8670 }
8671 ptr = ptr->next;
Eric Biederman0babc1c2003-05-09 02:39:00 +00008672 } while (ptr != RHS(state->main_function, 0));
8673 if (ptr == RHS(state->main_function, 0))
Eric Biedermanb138ac82003-04-22 18:44:01 +00008674 return block;
8675 op = ptr->op;
8676 if (op == OP_LABEL) {
8677 block->left = basic_block(state, ptr);
8678 block->right = 0;
8679 use_block(block->left, block);
8680 }
8681 else if (op == OP_BRANCH) {
8682 block->left = 0;
8683 /* Trace the branch target */
Eric Biederman0babc1c2003-05-09 02:39:00 +00008684 block->right = basic_block(state, TARG(ptr, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00008685 use_block(block->right, block);
8686 /* If there is a test trace the branch as well */
Eric Biederman0babc1c2003-05-09 02:39:00 +00008687 if (TRIPLE_RHS(ptr->sizes)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00008688 block->left = basic_block(state, ptr->next);
8689 use_block(block->left, block);
8690 }
8691 }
8692 else {
8693 internal_error(state, 0, "Bad basic block split");
8694 }
8695 return block;
8696}
8697
8698
8699static void walk_blocks(struct compile_state *state,
8700 void (*cb)(struct compile_state *state, struct block *block, void *arg),
8701 void *arg)
8702{
8703 struct triple *ptr, *first;
8704 struct block *last_block;
8705 last_block = 0;
Eric Biederman0babc1c2003-05-09 02:39:00 +00008706 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00008707 ptr = first;
8708 do {
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);
8714 }
8715 last_block = block;
8716 }
8717 ptr = ptr->next;
8718 } while(ptr != first);
8719}
8720
8721static void print_block(
8722 struct compile_state *state, struct block *block, void *arg)
8723{
8724 struct triple *ptr;
8725
8726 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
8727 block,
8728 block->vertex,
8729 block->left,
8730 block->left && block->left->use?block->left->use->member : 0,
8731 block->right,
8732 block->right && block->right->use?block->right->use->member : 0);
8733 if (block->first->op == OP_LABEL) {
8734 printf("%p:\n", block->first);
8735 }
8736 for(ptr = block->first; ; ptr = ptr->next) {
8737 struct triple_set *user;
8738 int op = ptr->op;
8739
8740 if (!IS_CONST_OP(op)) {
8741 if (ptr->u.block != block) {
8742 internal_error(state, ptr,
8743 "Wrong block pointer: %p\n",
8744 ptr->u.block);
8745 }
8746 }
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",
8752 user->member);
8753 }
8754 }
8755 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00008756 display_triple(stdout, ptr);
8757
Eric Biedermanb138ac82003-04-22 18:44:01 +00008758 /* Sanity checks... */
Eric Biederman0babc1c2003-05-09 02:39:00 +00008759 valid_ins(state, ptr);
Eric Biedermanb138ac82003-04-22 18:44:01 +00008760 for(user = ptr->use; user; user = user->next) {
8761 struct triple *use;
8762 use = user->member;
Eric Biederman0babc1c2003-05-09 02:39:00 +00008763 valid_ins(state, use);
Eric Biedermanb138ac82003-04-22 18:44:01 +00008764 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?",
8768 user->member);
8769 }
8770 }
8771
8772 if (ptr == block->last)
8773 break;
8774 }
8775 printf("\n");
8776}
8777
8778
8779static void print_blocks(struct compile_state *state)
8780{
8781 printf("--------------- blocks ---------------\n");
8782 walk_blocks(state, print_block, 0);
8783}
8784
8785static void prune_nonblock_triples(struct compile_state *state)
8786{
8787 struct block *block;
8788 struct triple *first, *ins;
8789 /* Delete the triples not in a basic block */
Eric Biederman0babc1c2003-05-09 02:39:00 +00008790 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00008791 block = 0;
8792 ins = first;
8793 do {
8794 if (ins->op == OP_LABEL) {
8795 block = ins->u.block;
8796 }
8797 ins = ins->next;
8798 if (!block) {
8799 release_triple(state, ins->prev);
8800 }
8801 } while(ins != first);
8802}
8803
8804static void setup_basic_blocks(struct compile_state *state)
8805{
8806 /* Find the basic blocks */
8807 state->last_vertex = 0;
Eric Biederman0babc1c2003-05-09 02:39:00 +00008808 state->first_block = basic_block(state, RHS(state->main_function,0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00008809 /* Delete the triples not in a basic block */
8810 prune_nonblock_triples(state);
8811 /* Find the last basic block */
Eric Biederman0babc1c2003-05-09 02:39:00 +00008812 state->last_block = RHS(state->main_function, 0)->prev->u.block;
Eric Biedermanb138ac82003-04-22 18:44:01 +00008813 if (!state->last_block) {
8814 internal_error(state, 0, "end not used?");
8815 }
8816 /* Insert an extra unused edge from start to the end
8817 * This helps with reverse control flow calculations.
8818 */
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);
8824 }
8825}
8826
8827static void free_basic_block(struct compile_state *state, struct block *block)
8828{
8829 struct block_set *entry, *next;
8830 struct block *child;
8831 if (!block) {
8832 return;
8833 }
8834 if (block->vertex == -1) {
8835 return;
8836 }
8837 block->vertex = -1;
8838 if (block->left) {
8839 unuse_block(block->left, block);
8840 }
8841 if (block->right) {
8842 unuse_block(block->right, block);
8843 }
8844 if (block->idom) {
8845 unidom_block(block->idom, block);
8846 }
8847 block->idom = 0;
8848 if (block->ipdom) {
8849 unipdom_block(block->ipdom, block);
8850 }
8851 block->ipdom = 0;
8852 for(entry = block->use; entry; entry = next) {
8853 next = entry->next;
8854 child = entry->member;
8855 unuse_block(block, child);
8856 if (child->left == block) {
8857 child->left = 0;
8858 }
8859 if (child->right == block) {
8860 child->right = 0;
8861 }
8862 }
8863 for(entry = block->idominates; entry; entry = next) {
8864 next = entry->next;
8865 child = entry->member;
8866 unidom_block(block, child);
8867 child->idom = 0;
8868 }
8869 for(entry = block->domfrontier; entry; entry = next) {
8870 next = entry->next;
8871 child = entry->member;
8872 undomf_block(block, child);
8873 }
8874 for(entry = block->ipdominates; entry; entry = next) {
8875 next = entry->next;
8876 child = entry->member;
8877 unipdom_block(block, child);
8878 child->ipdom = 0;
8879 }
8880 for(entry = block->ipdomfrontier; entry; entry = next) {
8881 next = entry->next;
8882 child = entry->member;
8883 unipdomf_block(block, child);
8884 }
8885 if (block->users != 0) {
8886 internal_error(state, 0, "block still has users");
8887 }
8888 free_basic_block(state, block->left);
8889 block->left = 0;
8890 free_basic_block(state, block->right);
8891 block->right = 0;
8892 memset(block, -1, sizeof(*block));
8893 xfree(block);
8894}
8895
8896static void free_basic_blocks(struct compile_state *state)
8897{
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;
Eric Biederman0babc1c2003-05-09 02:39:00 +00008902 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00008903 ins = first;
8904 do {
8905 if (!is_const(ins)) {
8906 ins->u.block = 0;
8907 }
8908 ins = ins->next;
8909 } while(ins != first);
8910
8911}
8912
8913struct sdom_block {
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;
8921 int vertex;
8922};
8923
8924
8925static void unsdom_block(struct sdom_block *block)
8926{
8927 struct sdom_block **ptr;
8928 if (!block->sdom_next) {
8929 return;
8930 }
8931 ptr = &block->sdom->sdominates;
8932 while(*ptr) {
8933 if ((*ptr) == block) {
8934 *ptr = block->sdom_next;
8935 return;
8936 }
8937 ptr = &(*ptr)->sdom_next;
8938 }
8939}
8940
8941static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
8942{
8943 unsdom_block(block);
8944 block->sdom = sdom;
8945 block->sdom_next = sdom->sdominates;
8946 sdom->sdominates = block;
8947}
8948
8949
8950
8951static int initialize_sdblock(struct sdom_block *sd,
8952 struct block *parent, struct block *block, int vertex)
8953{
8954 if (!block || (sd[block->vertex].block == block)) {
8955 return vertex;
8956 }
8957 vertex += 1;
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);
8968 return vertex;
8969}
8970
8971static int initialize_sdpblock(struct sdom_block *sd,
8972 struct block *parent, struct block *block, int vertex)
8973{
8974 struct block_set *user;
8975 if (!block || (sd[block->vertex].block == block)) {
8976 return vertex;
8977 }
8978 vertex += 1;
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);
8989 }
8990 return vertex;
8991}
8992
8993static void compress_ancestors(struct sdom_block *v)
8994{
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));
9000 * }
9001 * ancestor(v) = ancestor(ancestor(v));
9002 * }
9003 */
9004 if (!v->ancestor) {
9005 return;
9006 }
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;
9011 }
9012 v->ancestor = v->ancestor->ancestor;
9013 }
9014}
9015
9016static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9017{
9018 int i;
9019 /* // step 2
9020 * for each v <= pred(w) {
9021 * u = EVAL(v);
9022 * if (semi[u] < semi[w] {
9023 * semi[w] = semi[u];
9024 * }
9025 * }
9026 * add w to bucket(vertex(semi[w]));
9027 * LINK(parent(w), w);
9028 *
9029 * // step 3
9030 * for each v <= bucket(parent(w)) {
9031 * delete v from bucket(parent(w));
9032 * u = EVAL(v);
9033 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9034 * }
9035 */
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;
9042 /* Step 2 */
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;
9049 }
9050 }
9051 sdom_block(sd[i].sdom, &sd[i]);
9052 sd[i].ancestor = parent;
9053 /* Step 3 */
9054 for(v = parent->sdominates; v; v = next) {
9055 struct sdom_block *u;
9056 next = v->sdom_next;
9057 unsdom_block(v);
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;
9061 }
9062 }
9063}
9064
9065static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9066{
9067 int i;
9068 /* // step 2
9069 * for each v <= pred(w) {
9070 * u = EVAL(v);
9071 * if (semi[u] < semi[w] {
9072 * semi[w] = semi[u];
9073 * }
9074 * }
9075 * add w to bucket(vertex(semi[w]));
9076 * LINK(parent(w), w);
9077 *
9078 * // step 3
9079 * for each v <= bucket(parent(w)) {
9080 * delete v from bucket(parent(w));
9081 * u = EVAL(v);
9082 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9083 * }
9084 */
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;
9090 /* Step 2 */
9091 if (block->left) {
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;
9096 }
9097 }
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;
9103 }
9104 }
9105 sdom_block(sd[i].sdom, &sd[i]);
9106 sd[i].ancestor = parent;
9107 /* Step 3 */
9108 for(v = parent->sdominates; v; v = next) {
9109 struct sdom_block *u;
9110 next = v->sdom_next;
9111 unsdom_block(v);
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;
9115 }
9116 }
9117}
9118
9119static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9120{
9121 int i;
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;
9127 }
9128 idom_block(block->idom, block);
9129 }
9130 sd[1].block->idom = 0;
9131}
9132
9133static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9134{
9135 int i;
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;
9141 }
9142 ipdom_block(block->ipdom, block);
9143 }
9144 sd[1].block->ipdom = 0;
9145}
9146
9147 /* Theorem 1:
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.
9154 */
9155 /* Lemma 1:
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
9158 * of v and w in T.
9159 */
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) */
9163 /* Theorem 2:
9164 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9165 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9166 */
9167 /* Theorem 3:
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).
9171 */
9172 /* Lemma 5: Let vertices v,w satisfy v -> w.
9173 * Then v -> idom(w) or idom(w) -> idom(v)
9174 */
9175
9176static void find_immediate_dominators(struct compile_state *state)
9177{
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}
9181 */
9182 /* Theorem 4:
9183 * For any vertex w != r.
9184 * sdom(w) = min(
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})
9187 */
9188 /* Corollary 1:
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.
9191 * Then:
9192 * { sdom(w) if sdom(w) = sdom(u),
9193 * idom(w) = {
9194 * { idom(u) otherwise
9195 */
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
9207 * by number.
9208 */
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);
9212#if 0
9213 sd[1].size = 0;
9214 sd[1].label = 0;
9215 sd[1].sdom = 0;
9216#endif
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);
9222 xfree(sd);
9223}
9224
9225static void find_post_dominators(struct compile_state *state)
9226{
9227 struct sdom_block *sd;
9228 /* Step 1 initialize the basic block information */
9229 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9230
9231 initialize_sdpblock(sd, 0, state->last_block, 0);
9232
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);
9238 xfree(sd);
9239}
9240
9241
9242
9243static void find_block_domf(struct compile_state *state, struct block *block)
9244{
9245 struct block *child;
9246 struct block_set *user;
9247 if (block->domfrontier != 0) {
9248 internal_error(state, block->first, "domfrontier present?");
9249 }
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");
9254 }
9255 find_block_domf(state, child);
9256 }
9257 if (block->left && block->left->idom != block) {
9258 domf_block(block, block->left);
9259 }
9260 if (block->right && block->right->idom != block) {
9261 domf_block(block, block->right);
9262 }
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);
9269 }
9270 }
9271 }
9272}
9273
9274static void find_block_ipdomf(struct compile_state *state, struct block *block)
9275{
9276 struct block *child;
9277 struct block_set *user;
9278 if (block->ipdomfrontier != 0) {
9279 internal_error(state, block->first, "ipdomfrontier present?");
9280 }
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");
9285 }
9286 find_block_ipdomf(state, child);
9287 }
9288 if (block->left && block->left->ipdom != block) {
9289 ipdomf_block(block, block->left);
9290 }
9291 if (block->right && block->right->ipdom != block) {
9292 ipdomf_block(block, block->right);
9293 }
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);
9300 }
9301 }
9302 }
9303}
9304
9305static int print_dominated(
9306 struct compile_state *state, struct block *block, int vertex)
9307{
9308 struct block_set *user;
9309
9310 if (!block || (block->vertex != vertex + 1)) {
9311 return vertex;
9312 }
9313 vertex += 1;
9314
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");
9320 }
9321 }
9322 printf("\n");
9323 vertex = print_dominated(state, block->left, vertex);
9324 vertex = print_dominated(state, block->right, vertex);
9325 return vertex;
9326}
9327
9328static void print_dominators(struct compile_state *state)
9329{
9330 printf("\ndominates\n");
9331 print_dominated(state, state->first_block, 0);
9332}
9333
9334
9335static int print_frontiers(
9336 struct compile_state *state, struct block *block, int vertex)
9337{
9338 struct block_set *user;
9339
9340 if (!block || (block->vertex != vertex + 1)) {
9341 return vertex;
9342 }
9343 vertex += 1;
9344
9345 printf("%d:", block->vertex);
9346 for(user = block->domfrontier; user; user = user->next) {
9347 printf(" %d", user->member->vertex);
9348 }
9349 printf("\n");
9350
9351 vertex = print_frontiers(state, block->left, vertex);
9352 vertex = print_frontiers(state, block->right, vertex);
9353 return vertex;
9354}
9355static void print_dominance_frontiers(struct compile_state *state)
9356{
9357 printf("\ndominance frontiers\n");
9358 print_frontiers(state, state->first_block, 0);
9359
9360}
9361
9362static void analyze_idominators(struct compile_state *state)
9363{
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);
9373 }
9374}
9375
9376
9377
9378static int print_ipdominated(
9379 struct compile_state *state, struct block *block, int vertex)
9380{
9381 struct block_set *user;
9382
9383 if (!block || (block->vertex != vertex + 1)) {
9384 return vertex;
9385 }
9386 vertex += 1;
9387
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");
9393 }
9394 }
9395 printf("\n");
9396 for(user = block->use; user; user = user->next) {
9397 vertex = print_ipdominated(state, user->member, vertex);
9398 }
9399 return vertex;
9400}
9401
9402static void print_ipdominators(struct compile_state *state)
9403{
9404 printf("\nipdominates\n");
9405 print_ipdominated(state, state->last_block, 0);
9406}
9407
9408static int print_pfrontiers(
9409 struct compile_state *state, struct block *block, int vertex)
9410{
9411 struct block_set *user;
9412
9413 if (!block || (block->vertex != vertex + 1)) {
9414 return vertex;
9415 }
9416 vertex += 1;
9417
9418 printf("%d:", block->vertex);
9419 for(user = block->ipdomfrontier; user; user = user->next) {
9420 printf(" %d", user->member->vertex);
9421 }
9422 printf("\n");
9423 for(user = block->use; user; user = user->next) {
9424 vertex = print_pfrontiers(state, user->member, vertex);
9425 }
9426 return vertex;
9427}
9428static void print_ipdominance_frontiers(struct compile_state *state)
9429{
9430 printf("\nipdominance frontiers\n");
9431 print_pfrontiers(state, state->last_block, 0);
9432
9433}
9434
9435static void analyze_ipdominators(struct compile_state *state)
9436{
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);
9446 }
9447}
9448
9449
9450static void insert_phi_operations(struct compile_state *state)
9451{
9452 size_t size;
9453 struct triple *first;
9454 int *has_already, *work;
9455 struct block *work_list, **work_list_tail;
9456 int iter;
9457 struct triple *var;
9458
9459 size = sizeof(int) * (state->last_vertex + 1);
9460 has_already = xcmalloc(size, "has_already");
9461 work = xcmalloc(size, "work");
9462 iter = 0;
9463
Eric Biederman0babc1c2003-05-09 02:39:00 +00009464 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009465 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) {
9469 continue;
9470 }
9471 iter += 1;
9472 work_list = 0;
9473 work_list_tail = &work_list;
9474 for(user = var->use; user; user = user->next) {
9475 if (user->member->op == OP_READ) {
9476 continue;
9477 }
9478 if (user->member->op != OP_WRITE) {
9479 internal_error(state, user->member,
9480 "bad variable access");
9481 }
9482 block = user->member->u.block;
9483 if (!block) {
9484 warning(state, user->member, "dead code");
9485 }
9486 work[block->vertex] = iter;
9487 *work_list_tail = block;
9488 block->work_next = 0;
9489 work_list_tail = &block->work_next;
9490 }
9491 for(block = work_list; block; block = block->work_next) {
9492 struct block_set *df;
9493 for(df = block->domfrontier; df; df = df->next) {
9494 struct triple *phi;
9495 struct block *front;
9496 int in_edges;
9497 front = df->member;
9498
9499 if (has_already[front->vertex] >= iter) {
9500 continue;
9501 }
9502 /* Count how many edges flow into this block */
9503 in_edges = front->users;
9504 /* Insert a phi function for this variable */
Eric Biederman0babc1c2003-05-09 02:39:00 +00009505 phi = alloc_triple(
9506 state, OP_PHI, var->type, in_edges,
9507 front->first->filename,
9508 front->first->line,
9509 front->first->col);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009510 phi->u.block = front;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009511 MISC(phi, 0) = var;
Eric Biedermanb138ac82003-04-22 18:44:01 +00009512 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;
9517 }
9518 has_already[front->vertex] = iter;
9519
9520 /* If necessary plan to visit the basic block */
9521 if (work[front->vertex] >= iter) {
9522 continue;
9523 }
9524 work[front->vertex] = iter;
9525 *work_list_tail = front;
9526 front->work_next = 0;
9527 work_list_tail = &front->work_next;
9528 }
9529 }
9530 }
9531 xfree(has_already);
9532 xfree(work);
9533}
9534
9535/*
9536 * C(V)
9537 * S(V)
9538 */
9539static void fixup_block_phi_variables(
9540 struct compile_state *state, struct block *parent, struct block *block)
9541{
9542 struct block_set *set;
9543 struct triple *ptr;
9544 int edge;
9545 if (!parent || !block)
9546 return;
9547 /* Find the edge I am coming in on */
9548 edge = 0;
9549 for(set = block->use; set; set = set->next, edge++) {
9550 if (set->member == parent) {
9551 break;
9552 }
9553 }
9554 if (!set) {
9555 internal_error(state, 0, "phi input is not on a control predecessor");
9556 }
9557 for(ptr = block->first; ; ptr = ptr->next) {
9558 if (ptr->op == OP_PHI) {
9559 struct triple *var, *val, **slot;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009560 var = MISC(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009561 /* 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");
9565 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00009566 if (edge >= TRIPLE_RHS(ptr->sizes)) {
9567 internal_error(state, ptr, "edges > phi rhs");
9568 }
9569 slot = &RHS(ptr, edge);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009570 if ((*slot != 0) && (*slot != val)) {
9571 internal_error(state, ptr, "phi already bound on this edge");
9572 }
9573 *slot = val;
9574 use_triple(val, ptr);
9575 }
9576 if (ptr == block->last) {
9577 break;
9578 }
9579 }
9580}
9581
9582
9583static void rename_block_variables(
9584 struct compile_state *state, struct block *block)
9585{
9586 struct block_set *user;
9587 struct triple *ptr, *next, *last;
9588 int done;
9589 if (!block)
9590 return;
9591 last = block->first;
9592 done = 0;
9593 for(ptr = block->first; !done; ptr = next) {
9594 next = ptr->next;
9595 if (ptr == block->last) {
9596 done = 1;
9597 }
9598 /* RHS(A) */
9599 if (ptr->op == OP_READ) {
9600 struct triple *var, *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009601 var = RHS(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009602 unuse_triple(var, ptr);
9603 if (!var->use) {
9604 error(state, ptr, "variable used without being set");
9605 }
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");
9610 }
9611 propogate_use(state, ptr, val);
9612 release_triple(state, ptr);
9613 continue;
9614 }
9615 /* LHS(A) */
9616 if (ptr->op == OP_WRITE) {
9617 struct triple *var, *val;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009618 var = LHS(ptr, 0);
9619 val = RHS(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009620 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9621 internal_error(state, val, "bad value in write");
9622 }
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);
9627 }
9628 if (ptr->op == OP_PHI) {
9629 struct triple *var;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009630 var = MISC(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009631 /* Push OP_PHI onto a stack of variable uses */
9632 push_triple(var, ptr);
9633 }
9634 last = ptr;
9635 }
9636 block->last = last;
9637
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);
9644 }
9645 /* pop the renamed variable stack */
9646 last = block->first;
9647 done = 0;
9648 for(ptr = block->first; !done ; ptr = next) {
9649 next = ptr->next;
9650 if (ptr == block->last) {
9651 done = 1;
9652 }
9653 if (ptr->op == OP_WRITE) {
9654 struct triple *var;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009655 var = LHS(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009656 /* Pop OP_WRITE ptr->right from the stack of variable uses */
Eric Biederman0babc1c2003-05-09 02:39:00 +00009657 pop_triple(var, RHS(ptr, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +00009658 release_triple(state, ptr);
9659 continue;
9660 }
9661 if (ptr->op == OP_PHI) {
9662 struct triple *var;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009663 var = MISC(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009664 /* Pop OP_WRITE ptr->right from the stack of variable uses */
9665 pop_triple(var, ptr);
9666 }
9667 last = ptr;
9668 }
9669 block->last = last;
9670}
9671
9672static void prune_block_variables(struct compile_state *state,
9673 struct block *block)
9674{
9675 struct block_set *user;
9676 struct triple *next, *last, *ptr;
9677 int done;
9678 last = block->first;
9679 done = 0;
9680 for(ptr = block->first; !done; ptr = next) {
9681 next = ptr->next;
9682 if (ptr == block->last) {
9683 done = 1;
9684 }
9685 if (ptr->op == OP_ADECL) {
9686 struct triple_set *user, *next;
9687 for(user = ptr->use; user; user = next) {
9688 struct triple *use;
9689 next = user->next;
9690 use = user->member;
9691 if (use->op != OP_PHI) {
9692 internal_error(state, use, "decl still used");
9693 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00009694 if (MISC(use, 0) != ptr) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00009695 internal_error(state, use, "bad phi use of decl");
9696 }
9697 unuse_triple(ptr, use);
Eric Biederman0babc1c2003-05-09 02:39:00 +00009698 MISC(use, 0) = 0;
Eric Biedermanb138ac82003-04-22 18:44:01 +00009699 }
9700 release_triple(state, ptr);
9701 continue;
9702 }
9703 last = ptr;
9704 }
9705 block->last = last;
9706 for(user = block->idominates; user; user = user->next) {
9707 prune_block_variables(state, user->member);
9708 }
9709}
9710
9711static void transform_to_ssa_form(struct compile_state *state)
9712{
9713 insert_phi_operations(state);
9714#if 0
9715 printf("@%s:%d\n", __FILE__, __LINE__);
9716 print_blocks(state);
9717#endif
9718 rename_block_variables(state, state->first_block);
9719 prune_block_variables(state, state->first_block);
9720}
9721
9722
9723static void transform_from_ssa_form(struct compile_state *state)
9724{
9725 /* To get out of ssa form we insert moves on the incoming
9726 * edges to blocks containting phi functions.
9727 */
9728 struct triple *first;
9729 struct triple *phi, *next;
9730
9731 /* Walk all of the operations to find the phi functions */
Eric Biederman0babc1c2003-05-09 02:39:00 +00009732 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009733 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;
9738 int edge;
9739 next = phi->next;
9740 if (phi->op != OP_PHI) {
9741 continue;
9742 }
9743 block = phi->u.block;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009744 slot = &RHS(phi, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009745
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);
9751
9752 /* Replaces uses of the phi with variable reads */
9753 propogate_use(state, phi, read);
9754
9755 /* Walk all of the incoming edges/blocks and insert moves.
9756 */
9757 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9758 struct block *eblock;
9759 struct triple *move;
9760 struct triple *val;
9761 eblock = set->member;
9762 val = slot[edge];
9763 unuse_triple(val, phi);
9764
9765 if (val == phi) {
9766 continue;
9767 }
9768
9769 move = post_triple(state,
9770 val, OP_WRITE, phi->type, var, val);
9771 use_triple(val, move);
9772 use_triple(var, move);
9773 }
9774 release_triple(state, phi);
9775 }
9776
9777}
9778
9779static void insert_copies_to_phi(struct compile_state *state)
9780{
9781 /* To get out of ssa form we insert moves on the incoming
9782 * edges to blocks containting phi functions.
9783 */
9784 struct triple *first;
9785 struct triple *phi;
9786
9787 /* Walk all of the operations to find the phi functions */
Eric Biederman0babc1c2003-05-09 02:39:00 +00009788 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009789 for(phi = first->next; phi != first ; phi = phi->next) {
9790 struct block_set *set;
9791 struct block *block;
9792 struct triple **slot;
9793 int edge;
9794 if (phi->op != OP_PHI) {
9795 continue;
9796 }
9797 if (ID_REG(phi->id) == REG_UNSET) {
9798 phi->id = MK_REG_ID(alloc_virtual_reg(),
9799 ID_REG_CLASSES(phi->id));
9800 }
9801 block = phi->u.block;
Eric Biederman0babc1c2003-05-09 02:39:00 +00009802 slot = &RHS(phi, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009803 /* Walk all of the incoming edges/blocks and insert moves.
9804 */
9805 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9806 struct block *eblock;
9807 struct triple *move;
9808 struct triple *val;
9809 struct triple *ptr;
9810 eblock = set->member;
9811 val = slot[edge];
9812
9813 if (val == phi) {
9814 continue;
9815 }
9816
9817 move = build_triple(state, OP_COPY, phi->type, val, 0,
9818 val->filename, val->line, val->col);
9819 move->u.block = eblock;
9820 move->id = phi->id;
9821 use_triple(val, move);
9822
9823 slot[edge] = move;
9824 unuse_triple(val, phi);
9825 use_triple(move, phi);
9826
9827 /* Walk through the block backwards to find
9828 * an appropriate location for the OP_COPY.
9829 */
9830 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
9831 struct triple **expr;
9832 if ((ptr == phi) || (ptr == val)) {
9833 goto out;
9834 }
9835 expr = triple_rhs(state, ptr, 0);
9836 for(;expr; expr = triple_rhs(state, ptr, expr)) {
9837 if ((*expr) == phi) {
9838 goto out;
9839 }
9840 }
9841 }
9842 out:
Eric Biederman0babc1c2003-05-09 02:39:00 +00009843 if (triple_is_branch(state, ptr)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +00009844 internal_error(state, ptr,
9845 "Could not insert write to phi");
9846 }
9847 insert_triple(state, ptr->next, move);
9848 if (eblock->last == ptr) {
9849 eblock->last = move;
9850 }
9851 }
9852 }
9853}
9854
9855struct triple_reg_set {
9856 struct triple_reg_set *next;
9857 struct triple *member;
9858 struct triple *new;
9859};
9860
9861struct reg_block {
9862 struct block *block;
9863 struct triple_reg_set *in;
9864 struct triple_reg_set *out;
9865 int vertex;
9866};
9867
9868static int do_triple_set(struct triple_reg_set **head,
9869 struct triple *member, struct triple *new_member)
9870{
9871 struct triple_reg_set **ptr, *new;
9872 if (!member)
9873 return 0;
9874 ptr = head;
9875 while(*ptr) {
9876 if ((*ptr)->member == member) {
9877 return 0;
9878 }
9879 ptr = &(*ptr)->next;
9880 }
9881 new = xcmalloc(sizeof(*new), "triple_set");
9882 new->member = member;
9883 new->new = new_member;
9884 new->next = *head;
9885 *head = new;
9886 return 1;
9887}
9888
9889static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
9890{
9891 struct triple_reg_set *entry, **ptr;
9892 ptr = head;
9893 while(*ptr) {
9894 entry = *ptr;
9895 if (entry->member == member) {
9896 *ptr = entry->next;
9897 xfree(entry);
9898 return;
9899 }
9900 else {
9901 ptr = &entry->next;
9902 }
9903 }
9904}
9905
9906static int in_triple(struct reg_block *rb, struct triple *in)
9907{
9908 return do_triple_set(&rb->in, in, 0);
9909}
9910static void unin_triple(struct reg_block *rb, struct triple *unin)
9911{
9912 do_triple_unset(&rb->in, unin);
9913}
9914
9915static int out_triple(struct reg_block *rb, struct triple *out)
9916{
9917 return do_triple_set(&rb->out, out, 0);
9918}
9919static void unout_triple(struct reg_block *rb, struct triple *unout)
9920{
9921 do_triple_unset(&rb->out, unout);
9922}
9923
9924static int initialize_regblock(struct reg_block *blocks,
9925 struct block *block, int vertex)
9926{
9927 struct block_set *user;
9928 if (!block || (blocks[block->vertex].block == block)) {
9929 return vertex;
9930 }
9931 vertex += 1;
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);
9938 }
9939 return vertex;
9940}
9941
9942static int phi_in(struct compile_state *state, struct reg_block *blocks,
9943 struct reg_block *rb, struct block *suc)
9944{
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.
9948 */
9949 struct block_set *set;
9950 struct triple *ptr;
9951 int edge;
9952 int done, change;
9953 change = 0;
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) {
9957 break;
9958 }
9959 }
9960 if (!set) {
9961 internal_error(state, 0, "Not coming on a control edge?");
9962 }
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) {
9968 continue;
9969 }
Eric Biederman0babc1c2003-05-09 02:39:00 +00009970 slot = &RHS(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +00009971 expr = slot[edge];
9972 out_change = out_triple(rb, expr);
9973 if (!out_change) {
9974 continue;
9975 }
9976 /* If we don't define the variable also plast it
9977 * in the current blocks input set.
9978 */
9979 ptr2 = rb->block->first;
9980 for(done2 = 0; !done2; ptr2 = ptr2->next) {
9981 if (ptr2 == expr) {
9982 break;
9983 }
9984 done2 = (ptr2 == rb->block->last);
9985 }
9986 if (!done2) {
9987 continue;
9988 }
9989 change |= in_triple(rb, expr);
9990 }
9991 return change;
9992}
9993
9994static int reg_in(struct compile_state *state, struct reg_block *blocks,
9995 struct reg_block *rb, struct block *suc)
9996{
9997 struct triple_reg_set *in_set;
9998 int change;
9999 change = 0;
10000 /* Read the input set of a successor block
10001 * and place it in the current blocks output set.
10002 */
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);
10008 if (!out_change) {
10009 continue;
10010 }
10011 /* If we don't define the variable also place it
10012 * in the current blocks input set.
10013 */
10014 first = rb->block->first;
10015 last = rb->block->last;
10016 done = 0;
10017 for(ptr = first; !done; ptr = ptr->next) {
10018 if (ptr == in_set->member) {
10019 break;
10020 }
10021 done = (ptr == last);
10022 }
10023 if (!done) {
10024 continue;
10025 }
10026 change |= in_triple(rb, in_set->member);
10027 }
10028 change |= phi_in(state, blocks, rb, suc);
10029 return change;
10030}
10031
10032
10033static int use_in(struct compile_state *state, struct reg_block *rb)
10034{
10035 /* Find the variables we use but don't define and add
10036 * it to the current blocks input set.
10037 */
10038#warning "FIXME is this O(N^2) algorithm bad?"
10039 struct block *block;
10040 struct triple *ptr;
10041 int done;
10042 int change;
10043 block = rb->block;
10044 change = 0;
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
10050 * here.
10051 */
10052 if (ptr->op == OP_PHI) {
10053 continue;
10054 }
10055 expr = triple_rhs(state, ptr, 0);
10056 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10057 struct triple *rhs, *test;
10058 int tdone;
10059 rhs = *expr;
Eric Biederman0babc1c2003-05-09 02:39:00 +000010060 if (!rhs) {
10061 continue;
10062 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000010063 /* See if rhs is defined in this block */
10064 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10065 tdone = (test == block->first);
10066 if (test == rhs) {
10067 rhs = 0;
10068 break;
10069 }
10070 }
10071 /* If the triple is not a definition skip it. */
Eric Biederman0babc1c2003-05-09 02:39:00 +000010072 if (!triple_is_def(state, ptr)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000010073 continue;
10074 }
10075 /* If I still have a valid rhs add it to in */
10076 change |= in_triple(rb, rhs);
10077 }
10078 }
10079 return change;
10080}
10081
10082static struct reg_block *compute_variable_lifetimes(
10083 struct compile_state *state)
10084{
10085 struct reg_block *blocks;
10086 int change;
10087 blocks = xcmalloc(
10088 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10089 initialize_regblock(blocks, state->last_block, 0);
10090 do {
10091 int i;
10092 change = 0;
10093 for(i = 1; i <= state->last_vertex; i++) {
10094 struct reg_block *rb;
10095 rb = &blocks[i];
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);
10099 }
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);
10104 }
10105 /* Add use to in... */
10106 change |= use_in(state, rb);
10107 }
10108 } while(change);
10109 return blocks;
10110}
10111
10112static void free_variable_lifetimes(
10113 struct compile_state *state, struct reg_block *blocks)
10114{
10115 int i;
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;
10120 rb = &blocks[i];
10121 for(entry = rb->in; entry ; entry = next) {
10122 next = entry->next;
10123 do_triple_unset(&rb->in, entry->member);
10124 }
10125 for(entry = rb->out; entry; entry = next) {
10126 next = entry->next;
10127 do_triple_unset(&rb->out, entry->member);
10128 }
10129 }
10130 xfree(blocks);
10131
10132}
10133
10134typedef 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);
10138
10139static void walk_variable_lifetimes(struct compile_state *state,
10140 struct reg_block *blocks, wvl_cb_t cb, void *arg)
10141{
10142 int i;
10143
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;
10150 int done;
10151
10152 /* Get the blocks */
10153 rb = &blocks[i];
10154 block = rb->block;
10155
10156 /* Copy out into live */
10157 live = 0;
10158 for(entry = rb->out; entry; entry = next) {
10159 next = entry->next;
10160 do_triple_set(&live, entry->member, entry->new);
10161 }
10162 /* Walk through the basic block calculating live */
10163 for(done = 0, ptr = block->last; !done; ptr = prev) {
10164 struct triple **expr;
10165
10166 prev = ptr->prev;
10167 done = (ptr == block->first);
10168
10169 /* Remove the current definition from live */
10170 do_triple_unset(&live, ptr);
10171
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;
10176 }
10177 continue;
10178 }
10179
10180 /* Add the current uses to live.
10181 *
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.
10186 */
10187 if (ptr->op == OP_PHI) {
10188 continue;
10189 }
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. */
Eric Biederman0babc1c2003-05-09 02:39:00 +000010193 if (!*expr || !triple_is_def(state, *expr)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000010194 continue;
10195 }
10196 do_triple_set(&live, *expr, 0);
10197 }
10198
10199 }
10200 /* Free live */
10201 for(entry = live; entry; entry = next) {
10202 next = entry->next;
10203 do_triple_unset(&live, entry->member);
10204 }
10205 }
10206}
10207
10208static int count_triples(struct compile_state *state)
10209{
10210 struct triple *first, *ins;
10211 int triples = 0;
Eric Biederman0babc1c2003-05-09 02:39:00 +000010212 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000010213 ins = first;
10214 do {
10215 triples++;
10216 ins = ins->next;
10217 } while (ins != first);
10218 return triples;
10219}
10220struct dead_triple {
10221 struct triple *triple;
10222 struct dead_triple *work_next;
10223 struct block *block;
10224 int color;
10225 int flags;
10226#define TRIPLE_FLAG_ALIVE 1
10227};
10228
10229
10230static void awaken(
10231 struct compile_state *state,
10232 struct dead_triple *dtriple, struct triple **expr,
10233 struct dead_triple ***work_list_tail)
10234{
10235 struct triple *triple;
10236 struct dead_triple *dt;
10237 if (!expr) {
10238 return;
10239 }
10240 triple = *expr;
10241 if (!triple) {
10242 return;
10243 }
10244 if (triple->id <= 0) {
10245 internal_error(state, triple, "bad triple id: %d",
10246 triple->id);
10247 }
10248 if (triple->op == OP_NOOP) {
10249 internal_warning(state, triple, "awakening noop?");
10250 return;
10251 }
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;
10258 }
10259 }
10260}
10261
10262static void eliminate_inefectual_code(struct compile_state *state)
10263{
10264 struct block *block;
10265 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
10266 int triples, i;
10267 struct triple *first, *ins;
10268
10269 /* Setup the work list */
10270 work_list = 0;
10271 work_list_tail = &work_list;
10272
Eric Biederman0babc1c2003-05-09 02:39:00 +000010273 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000010274
10275 /* Count how many triples I have */
10276 triples = count_triples(state);
10277
10278 /* Now put then in an array and mark all of the triples dead */
10279 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
10280
10281 ins = first;
10282 i = 1;
10283 block = 0;
10284 do {
10285 if (ins->op == OP_LABEL) {
10286 block = ins->u.block;
10287 }
10288 dtriple[i].triple = ins;
10289 dtriple[i].block = block;
10290 dtriple[i].flags = 0;
10291 dtriple[i].color = ins->id;
10292 ins->id = i;
10293 /* See if it is an operation we always keep */
10294#warning "FIXME handle the case of killing a branch instruction"
Eric Biederman0babc1c2003-05-09 02:39:00 +000010295 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000010296 awaken(state, dtriple, &ins, &work_list_tail);
10297 }
10298 i++;
10299 ins = ins->next;
10300 } while(ins != first);
10301 while(work_list) {
10302 struct dead_triple *dt;
10303 struct block_set *user;
10304 struct triple **expr;
10305 dt = work_list;
10306 work_list = dt->work_next;
10307 if (!work_list) {
10308 work_list_tail = &work_list;
10309 }
10310 /* Wake up the data depencencies of this triple */
10311 expr = 0;
10312 do {
10313 expr = triple_rhs(state, dt->triple, expr);
10314 awaken(state, dtriple, expr, &work_list_tail);
10315 } while(expr);
10316 do {
10317 expr = triple_lhs(state, dt->triple, expr);
10318 awaken(state, dtriple, expr, &work_list_tail);
10319 } while(expr);
10320 /* Wake up the forward control dependencies */
10321 do {
10322 expr = triple_targ(state, dt->triple, expr);
10323 awaken(state, dtriple, expr, &work_list_tail);
10324 } while(expr);
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);
10328 }
10329 }
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?");
10334 }
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) {
10339 continue;
10340 }
10341 if (dt->block->last == dt->triple) {
10342 dt->block->last = dt->triple->prev;
10343 }
10344 release_triple(state, dt->triple);
10345 }
10346 }
10347 xfree(dtriple);
10348}
10349
10350
10351struct live_range_edge;
10352struct live_range {
10353 struct live_range_edge *edges;
10354 struct triple *def;
10355 unsigned color;
10356 unsigned classes;
10357 unsigned degree;
10358 struct live_range *group_next, **group_prev;
10359};
10360
10361struct live_range_edge {
10362 struct live_range_edge *next;
10363 struct live_range *node;
10364};
10365
10366#define LRE_HASH_SIZE 2048
10367struct lre_hash {
10368 struct lre_hash *next;
10369 struct live_range *left;
10370 struct live_range *right;
10371};
10372
10373
10374struct reg_state {
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;
10380 unsigned ranges;
10381};
10382
10383
10384static unsigned regc_max_size(struct compile_state *state, int classes)
10385{
10386 unsigned max_size;
10387 int i;
10388 max_size = 0;
10389 for(i = 0; i < MAX_REGC; i++) {
10390 if (classes & (1 << i)) {
10391 unsigned size;
10392 size = arch_regc_size(state, i);
10393 if (size > max_size) {
10394 max_size = size;
10395 }
10396 }
10397 }
10398 return max_size;
10399}
10400
10401static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
10402{
10403 unsigned equivs[MAX_REG_EQUIVS];
10404 int i;
10405 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
10406 internal_error(state, 0, "invalid register");
10407 }
10408 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
10409 internal_error(state, 0, "invalid register");
10410 }
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) {
10414 return 1;
10415 }
10416 }
10417 return 0;
10418}
10419
10420static void reg_fill_used(struct compile_state *state, char *used, int reg)
10421{
10422 unsigned equivs[MAX_REG_EQUIVS];
10423 int i;
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;
10427 }
10428 return;
10429}
10430
10431static unsigned int hash_live_edge(
10432 struct live_range *left, struct live_range *right)
10433{
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);
10438 hash = 0;
10439 while(lval) {
10440 val = lval & 0xff;
10441 lval >>= 8;
10442 hash = (hash *263) + val;
10443 }
10444 while(rval) {
10445 val = rval & 0xff;
10446 rval >>= 8;
10447 hash = (hash *263) + val;
10448 }
10449 hash = hash & (LRE_HASH_SIZE - 1);
10450 return hash;
10451}
10452
10453static struct lre_hash **lre_probe(struct reg_state *rstate,
10454 struct live_range *left, struct live_range *right)
10455{
10456 struct lre_hash **ptr;
10457 unsigned int index;
10458 /* Ensure left <= right */
10459 if (left > right) {
10460 struct live_range *tmp;
10461 tmp = left;
10462 left = right;
10463 right = tmp;
10464 }
10465 index = hash_live_edge(left, right);
10466
10467 ptr = &rstate->hash[index];
10468 while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
10469 ptr = &(*ptr)->next;
10470 }
10471 return ptr;
10472}
10473
10474static int interfere(struct reg_state *rstate,
10475 struct live_range *left, struct live_range *right)
10476{
10477 struct lre_hash **ptr;
10478 ptr = lre_probe(rstate, left, right);
10479 return ptr && *ptr;
10480}
10481
10482static void add_live_edge(struct reg_state *rstate,
10483 struct live_range *left, struct live_range *right)
10484{
10485 /* FIXME the memory allocation overhead is noticeable here... */
10486 struct lre_hash **ptr, *new_hash;
10487 struct live_range_edge *edge;
10488
10489 if (left == right) {
10490 return;
10491 }
10492 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
10493 return;
10494 }
10495 /* Ensure left <= right */
10496 if (left > right) {
10497 struct live_range *tmp;
10498 tmp = left;
10499 left = right;
10500 right = tmp;
10501 }
10502 ptr = lre_probe(rstate, left, right);
10503 if (*ptr) {
10504 return;
10505 }
10506 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
10507 new_hash->next = *ptr;
10508 new_hash->left = left;
10509 new_hash->right = right;
10510 *ptr = new_hash;
10511
10512 edge = xmalloc(sizeof(*edge), "live_range_edge");
10513 edge->next = left->edges;
10514 edge->node = right;
10515 left->edges = edge;
10516 left->degree += 1;
10517
10518 edge = xmalloc(sizeof(*edge), "live_range_edge");
10519 edge->next = right->edges;
10520 edge->node = left;
10521 right->edges = edge;
10522 right->degree += 1;
10523}
10524
10525static void remove_live_edge(struct reg_state *rstate,
10526 struct live_range *left, struct live_range *right)
10527{
10528 struct live_range_edge *edge, **ptr;
10529 struct lre_hash **hptr, *entry;
10530 hptr = lre_probe(rstate, left, right);
10531 if (!hptr || !*hptr) {
10532 return;
10533 }
10534 entry = *hptr;
10535 *hptr = entry->next;
10536 xfree(entry);
10537
10538 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
10539 edge = *ptr;
10540 if (edge->node == right) {
10541 *ptr = edge->next;
10542 memset(edge, 0, sizeof(*edge));
10543 xfree(edge);
10544 break;
10545 }
10546 }
10547 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
10548 edge = *ptr;
10549 if (edge->node == left) {
10550 *ptr = edge->next;
10551 memset(edge, 0, sizeof(*edge));
10552 xfree(edge);
10553 break;
10554 }
10555 }
10556}
10557
10558static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
10559{
10560 struct live_range_edge *edge, *next;
10561 for(edge = range->edges; edge; edge = next) {
10562 next = edge->next;
10563 remove_live_edge(rstate, range, edge->node);
10564 }
10565}
10566
10567
10568/* Interference graph...
10569 *
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
10576 *
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.
10580 */
10581
10582/*
10583 * +---------------------------------------------------+
10584 * | +--------------+ |
10585 * v v | |
10586 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
10587 *
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.
10592 *
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.
10596 *
10597 *
10598 */
10599
10600static void different_colored(
10601 struct compile_state *state, struct reg_state *rstate,
10602 struct triple *parent, struct triple *ins)
10603{
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;
Eric Biederman0babc1c2003-05-09 02:39:00 +000010610 if (!*expr || (*expr == parent) || (*expr == ins)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000010611 continue;
10612 }
10613 lr2 = &rstate->lr[(*expr)->id];
10614 if (lr->color == lr2->color) {
10615 internal_error(state, ins, "live range too big");
10616 }
10617 }
10618}
10619
10620static void initialize_live_ranges(
10621 struct compile_state *state, struct reg_state *rstate)
10622{
10623 struct triple *ins, *first;
10624 size_t size;
10625 int i;
10626
Eric Biederman0babc1c2003-05-09 02:39:00 +000010627 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000010628 /* First count how many live ranges I will need.
10629 */
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;
10637 i = 0;
10638 ins = first;
10639 do {
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);
10646 }
10647
10648 /* If the triple is a variable definition give it a live range. */
Eric Biederman0babc1c2003-05-09 02:39:00 +000010649 if (triple_is_def(state, ins)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000010650 i++;
10651 ins->id = i;
10652 rstate->lr[i].def = ins;
10653 rstate->lr[i].color = color;
10654 rstate->lr[i].classes = classes;
10655 rstate->lr[i].degree = 0;
10656 if (!classes) {
10657 internal_error(state, ins,
10658 "live range without a class");
10659 }
10660 }
10661 /* Otherwise give the triple the dummy live range. */
10662 else {
10663 ins->id = 0;
10664 }
10665 ins = ins->next;
10666 } while(ins != first);
10667 rstate->ranges = i;
10668 /* Make a second pass to handle achitecture specific register
10669 * constraints.
10670 */
10671 ins = first;
10672 do {
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.
10679 */
10680 expr = triple_rhs(state, ins, 0);
10681 for(;expr; expr = triple_rhs(state, ins, expr)) {
10682 struct live_range *lr2;
Eric Biederman0babc1c2003-05-09 02:39:00 +000010683 if (!*expr || (ins == *expr)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000010684 continue;
10685 }
10686 lr2 = &rstate->lr[(*expr)->id];
10687 if (lr->color == lr2->color) {
10688 different_colored(state, rstate,
10689 ins, *expr);
10690 (*expr)->id = ins->id;
10691
10692 }
10693 }
10694 }
10695 ins = ins->next;
10696 } while(ins != first);
10697
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;
10702 }
10703 }
10704}
10705
10706static 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)
10710{
10711 struct reg_state *rstate = arg;
10712 struct live_range *def;
10713 struct triple_reg_set *entry;
10714
10715 /* If the triple does not start a live range
10716 * we do not have a definition to add to
10717 * the interference graph.
10718 */
10719 if (ins->id <= 0) {
10720 return ins;
10721 }
10722 def = &rstate->lr[ins->id];
10723
10724 /* Create an edge between ins and everything that is
10725 * alive, unless the live_range cannot share
10726 * a physical register with ins.
10727 */
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)) {
10732 continue;
10733 }
10734 add_live_edge(rstate, def, lr);
10735 }
10736 return ins;
10737}
10738
10739
10740static 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)
10744{
10745 struct reg_state *rstate = arg;
10746 struct live_range *lr;
10747
10748 lr = &rstate->lr[ins->id];
Eric Biederman0babc1c2003-05-09 02:39:00 +000010749 display_triple(stdout, ins);
Eric Biedermanb138ac82003-04-22 18:44:01 +000010750 if (live) {
10751 struct triple_reg_set *entry;
10752 printf(" live:");
10753 for(entry = live; entry; entry = entry->next) {
10754 printf(" %-10p", entry->member);
10755 }
10756 printf("\n");
10757 }
10758 if (lr->edges) {
10759 struct live_range_edge *entry;
10760 printf(" edges:");
10761 for(entry = lr->edges; entry; entry = entry->next) {
10762 printf(" %-10p", entry->node->def);
10763 }
10764 printf("\n");
10765 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000010766 if (triple_is_branch(state, ins)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000010767 printf("\n");
10768 }
10769 return ins;
10770}
10771
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)
10778#else
10779#define cgdebug_printf(...)
10780#define cgdebug_flush()
10781#endif
10782
10783static void select_free_color(struct compile_state *state,
10784 struct reg_state *rstate, struct live_range *range)
10785{
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;
10791
10792 /* If a color is already assigned don't change it */
10793 if (range->color != REG_UNSET) {
10794 return;
10795 }
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
10798 * copies.
10799 */
10800
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) {
10805 continue;
10806 }
10807 reg_fill_used(state, used, edge->node->color);
10808 }
10809#if DEBUG_COLOR_GRAPH > 1
10810 {
10811 int i;
10812 i = 0;
10813 for(edge = range->edges; edge; edge = edge->next) {
10814 i++;
10815 }
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++) {
10820 if (used[i]) {
10821 cgdebug_printf("used: %s\n",
10822 arch_reg_str(i));
10823 }
10824 }
10825 }
10826#endif
10827
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.
10831 */
10832 phi = 0;
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) {
10838 continue;
10839 }
10840 if (!phi && (lr->def->op == OP_PHI) &&
10841 !interfere(rstate, range, lr)) {
10842 phi = lr;
10843 }
10844 if ((lr->color == REG_UNSET) ||
10845 ((lr->classes & range->classes) == 0) ||
10846 (used[lr->color])) {
10847 continue;
10848 }
10849 if (interfere(rstate, range, lr)) {
10850 continue;
10851 }
10852 range->color = lr->color;
10853 }
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.
10856 */
10857 if (phi) {
10858 if (phi->color != REG_UNSET) {
10859 if (used[phi->color]) {
10860 range->color = phi->color;
10861 }
10862 }
10863 else {
10864 expr = triple_rhs(state, phi->def, 0);
10865 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
10866 struct live_range *lr;
Eric Biederman0babc1c2003-05-09 02:39:00 +000010867 if (!*expr) {
10868 continue;
10869 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000010870 lr = &rstate->lr[(*expr)->id];
10871 if ((lr->color == REG_UNSET) ||
10872 ((lr->classes & range->classes) == 0) ||
10873 (used[lr->color])) {
10874 continue;
10875 }
10876 if (interfere(rstate, range, lr)) {
10877 continue;
10878 }
10879 range->color = lr->color;
10880 }
10881 }
10882 }
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;
Eric Biederman0babc1c2003-05-09 02:39:00 +000010888 if (!*expr) {
10889 continue;
10890 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000010891 lr = &rstate->lr[(*expr)->id];
10892 if ((lr->color == -1) ||
10893 ((lr->classes & range->classes) == 0) ||
10894 (used[lr->color])) {
10895 continue;
10896 }
10897 if (interfere(rstate, range, lr)) {
10898 continue;
10899 }
10900 range->color = lr->color;
10901 break;
10902 }
10903 }
10904 /* If I have not opportunitically picked a useful color
10905 * pick the first color that is free.
10906 */
10907 if (range->color == REG_UNSET) {
10908 range->color =
10909 arch_select_free_register(state, used, range->classes);
10910 }
10911 if (range->color == REG_UNSET) {
10912 int i;
10913 for(edge = range->edges; edge; edge = edge->next) {
10914 if (edge->node->color == REG_UNSET) {
10915 continue;
10916 }
10917 warning(state, edge->node->def, "reg %s",
10918 arch_reg_str(edge->node->color));
10919 }
10920 warning(state, range->def, "classes: %x",
10921 range->classes);
10922 for(i = 0; i < MAX_REGISTERS; i++) {
10923 if (used[i]) {
10924 warning(state, range->def, "used: %s",
10925 arch_reg_str(i));
10926 }
10927 }
10928#if DEBUG_COLOR_GRAPH < 2
10929 error(state, range->def, "too few registers");
10930#else
10931 internal_error(state, range->def, "too few registers");
10932#endif
10933 }
10934 range->classes = arch_reg_regcm(state, range->color);
10935 return;
10936}
10937
10938static void color_graph(struct compile_state *state, struct reg_state *rstate)
10939{
10940 struct live_range_edge *edge;
10941 struct live_range *range;
10942 if (rstate->low) {
10943 cgdebug_printf("Lo: ");
10944 range = rstate->low;
10945 if (*range->group_prev != range) {
10946 internal_error(state, 0, "lo: *prev != range?");
10947 }
10948 *range->group_prev = range->group_next;
10949 if (range->group_next) {
10950 range->group_next->group_prev = range->group_prev;
10951 }
10952 if (&range->group_next == rstate->low_tail) {
10953 rstate->low_tail = range->group_prev;
10954 }
10955 if (rstate->low == range) {
10956 internal_error(state, 0, "low: next != prev?");
10957 }
10958 }
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?");
10964 }
10965 *range->group_prev = range->group_next;
10966 if (range->group_next) {
10967 range->group_next->group_prev = range->group_prev;
10968 }
10969 if (&range->group_next == rstate->high_tail) {
10970 rstate->high_tail = range->group_prev;
10971 }
10972 if (rstate->high == range) {
10973 internal_error(state, 0, "high: next != prev?");
10974 }
10975 }
10976 else {
10977 return;
10978 }
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;
10983 node = edge->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?");
10989 }
10990 *node->group_prev = node->group_next;
10991 if (node->group_next) {
10992 node->group_next->group_prev = node->group_prev;
10993 }
10994 if (&node->group_next == rstate->high_tail) {
10995 rstate->high_tail = node->group_prev;
10996 }
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?");
11004 }
11005 }
11006 node->degree -= 1;
11007 }
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);
11012 cgdebug_flush();
11013 select_free_color(state, rstate, range);
11014 if (range->color == -1) {
11015 internal_error(state, range->def, "select_free_color did not?");
11016 }
11017 cgdebug_printf(" %s\n", arch_reg_str(range->color));
11018}
11019
11020static void color_triples(struct compile_state *state, struct reg_state *rstate)
11021{
11022 struct live_range *lr;
11023 struct triple *first, *triple;
Eric Biederman0babc1c2003-05-09 02:39:00 +000011024 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011025 triple = first;
11026 do {
11027 if ((triple->id < 0) || (triple->id > rstate->ranges)) {
11028 internal_error(state, triple,
11029 "triple without a live range");
11030 }
11031 lr = &rstate->lr[triple->id];
11032 triple->id = MK_REG_ID(lr->color, 0);
11033 triple = triple->next;
11034 } while (triple != first);
11035}
11036
11037static void print_interference_block(
11038 struct compile_state *state, struct block *block, void *arg)
11039
11040{
11041 struct reg_state *rstate = arg;
11042 struct reg_block *rb;
11043 struct triple *ptr;
11044 int phi_present;
11045 int done;
11046 rb = &rstate->blocks[block->vertex];
11047
11048 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
11049 block,
11050 block->vertex,
11051 block->left,
11052 block->left && block->left->use?block->left->use->member : 0,
11053 block->right,
11054 block->right && block->right->use?block->right->use->member : 0);
11055 if (rb->in) {
11056 struct triple_reg_set *in_set;
11057 printf(" in:");
11058 for(in_set = rb->in; in_set; in_set = in_set->next) {
11059 printf(" %-10p", in_set->member);
11060 }
11061 printf("\n");
11062 }
11063 phi_present = 0;
11064 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11065 done = (ptr == block->last);
11066 if (ptr->op == OP_PHI) {
11067 phi_present = 1;
11068 break;
11069 }
11070 }
11071 if (phi_present) {
11072 int edge;
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) {
11079 continue;
11080 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000011081 slot = &RHS(ptr, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011082 printf(" %-10p", slot[edge]);
11083 }
11084 printf("\n");
11085 }
11086 }
11087 if (block->first->op == OP_LABEL) {
11088 printf("%p:\n", block->first);
11089 }
11090 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11091 struct triple_set *user;
11092 struct live_range *lr;
Eric Biederman0babc1c2003-05-09 02:39:00 +000011093 unsigned id;
Eric Biedermanb138ac82003-04-22 18:44:01 +000011094 int op;
11095 op = ptr->op;
11096 done = (ptr == block->last);
11097 lr = &rstate->lr[ptr->id];
11098
11099 if (!IS_CONST_OP(op)) {
11100 if (ptr->u.block != block) {
11101 internal_error(state, ptr,
11102 "Wrong block pointer: %p",
11103 ptr->u.block);
11104 }
11105 }
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?",
11113 user->member);
11114 }
11115
11116 }
11117 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000011118 id = ptr->id;
11119 ptr->id = MK_REG_ID(lr->color, 0);
11120 display_triple(stdout, ptr);
11121 ptr->id = id;
11122
Eric Biedermanb138ac82003-04-22 18:44:01 +000011123 if (lr->edges > 0) {
11124 struct live_range_edge *edge;
11125 printf(" ");
11126 for(edge = lr->edges; edge; edge = edge->next) {
11127 printf(" %-10p", edge->node->def);
11128 }
11129 printf("\n");
11130 }
11131 /* Do a bunch of sanity checks */
Eric Biederman0babc1c2003-05-09 02:39:00 +000011132 valid_ins(state, ptr);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011133 if ((ptr->id < 0) || (ptr->id > rstate->ranges)) {
11134 internal_error(state, ptr, "Invalid triple id: %d",
11135 ptr->id);
11136 }
11137 for(user = ptr->use; user; user = user->next) {
11138 struct triple *use;
11139 struct live_range *ulr;
11140 use = user->member;
Eric Biederman0babc1c2003-05-09 02:39:00 +000011141 valid_ins(state, use);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011142 if ((use->id < 0) || (use->id > rstate->ranges)) {
11143 internal_error(state, use, "Invalid triple id: %d",
11144 use->id);
11145 }
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?",
11151 user->member);
11152 }
11153 }
11154 }
11155 if (rb->out) {
11156 struct triple_reg_set *out_set;
11157 printf(" out:");
11158 for(out_set = rb->out; out_set; out_set = out_set->next) {
11159 printf(" %-10p", out_set->member);
11160 }
11161 printf("\n");
11162 }
11163 printf("\n");
11164}
11165
11166static struct live_range *merge_sort_lr(
11167 struct live_range *first, struct live_range *last)
11168{
11169 struct live_range *mid, *join, **join_tail, *pick;
11170 size_t size;
11171 size = (last - first) + 1;
11172 if (size >= 2) {
11173 mid = first + size/2;
11174 first = merge_sort_lr(first, mid -1);
11175 mid = merge_sort_lr(mid, last);
11176
11177 join = 0;
11178 join_tail = &join;
11179 /* merge the two lists */
11180 while(first && mid) {
11181 if (first->degree <= mid->degree) {
11182 pick = first;
11183 first = first->group_next;
11184 if (first) {
11185 first->group_prev = 0;
11186 }
11187 }
11188 else {
11189 pick = mid;
11190 mid = mid->group_next;
11191 if (mid) {
11192 mid->group_prev = 0;
11193 }
11194 }
11195 pick->group_next = 0;
11196 pick->group_prev = join_tail;
11197 *join_tail = pick;
11198 join_tail = &pick->group_next;
11199 }
11200 /* Splice the remaining list */
11201 pick = (first)? first : mid;
11202 *join_tail = pick;
11203 pick->group_prev = join_tail;
11204 }
11205 else {
11206 if (!first->def) {
11207 first = 0;
11208 }
11209 join = first;
11210 }
11211 return join;
11212}
11213
11214static void allocate_registers(struct compile_state *state)
11215{
11216 struct reg_state rstate;
11217 struct live_range **point, **next;
11218 int i;
11219
11220 /* Clear out the reg_state */
11221 memset(&rstate, 0, sizeof(rstate));
11222
11223 /* Compute the variable lifetimes */
11224 rstate.blocks = compute_variable_lifetimes(state);
11225
11226 /* Allocate and initialize the live ranges */
11227 initialize_live_ranges(state, &rstate);
11228
11229 /* Compute the interference graph */
11230 walk_variable_lifetimes(
11231 state, rstate.blocks, graph_ins, &rstate);
11232
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);
11241 }
11242
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.
11246 *
11247 * It might be worth testing this reducing the number of
11248 * live_ragnes as opposed to splitting them seems to help.
11249 */
11250
11251 /* Build the groups low and high. But with the nodes
11252 * first sorted by degree order.
11253 */
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]);
Eric Biederman0babc1c2003-05-09 02:39:00 +000011257 if (rstate.high) {
11258 rstate.high->group_prev = &rstate.high;
11259 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000011260 for(point = &rstate.high; *point; point = &(*point)->group_next)
11261 ;
11262 rstate.high_tail = point;
11263 /* Walk through the high list and move everything that needs
11264 * to be onto low.
11265 */
11266 for(point = &rstate.high; *point; point = next) {
11267 struct live_range *range;
11268 next = &(*point)->group_next;
11269 range = *point;
11270
11271 /* If it has a low degree or it already has a color
11272 * place the node in low.
11273 */
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;
11282 }
11283 if (&range->group_next == rstate.high_tail) {
11284 rstate.high_tail = range->group_prev;
11285 }
11286 range->group_prev = rstate.low_tail;
11287 range->group_next = 0;
11288 *rstate.low_tail = range;
11289 rstate.low_tail = &range->group_next;
11290 next = point;
11291 }
11292 else {
11293 cgdebug_printf("hi: %5d degree %5d%s\n",
11294 range - rstate.lr, range->degree,
11295 (range->color != REG_UNSET) ? " (colored)": "");
11296 }
11297
11298 }
11299 /* Color the live_ranges */
11300 color_graph(state, &rstate);
11301
11302 /* Move the colors from the graph to the triples */
11303 color_triples(state, &rstate);
11304
11305 /* Free the edges on each node */
11306 for(i = 1; i <= rstate.ranges; i++) {
11307 remove_live_edges(&rstate, &rstate.lr[i]);
11308 }
11309 xfree(rstate.lr);
11310
11311 /* Free the variable lifetime information */
11312 free_variable_lifetimes(state, rstate.blocks);
11313
11314}
11315
11316/* Sparce Conditional Constant Propogation
11317 * =========================================
11318 */
11319struct ssa_edge;
11320struct flow_block;
11321struct 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
11329 */
Eric Biedermanb138ac82003-04-22 18:44:01 +000011330};
11331struct ssa_edge {
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;
11337};
11338struct flow_edge {
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;
11345 int executable;
11346};
11347struct flow_block {
11348 struct block *block;
11349 struct flow_edge *in;
11350 struct flow_edge *out;
11351 struct flow_edge left, right;
11352};
11353
11354struct scc_state {
Eric Biederman0babc1c2003-05-09 02:39:00 +000011355 int ins_count;
Eric Biedermanb138ac82003-04-22 18:44:01 +000011356 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;
11361};
11362
11363
11364static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
11365 struct flow_edge *fedge)
11366{
11367 if (!scc->flow_work_list) {
11368 scc->flow_work_list = fedge;
11369 fedge->work_next = fedge->work_prev = fedge;
11370 }
11371 else {
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;
11378 }
11379}
11380
11381static struct flow_edge *scc_next_fedge(
11382 struct compile_state *state, struct scc_state *scc)
11383{
11384 struct flow_edge *fedge;
11385 fedge = scc->flow_work_list;
11386 if (fedge) {
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;
11391 } else {
11392 scc->flow_work_list = 0;
11393 }
11394 }
11395 return fedge;
11396}
11397
11398static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
11399 struct ssa_edge *sedge)
11400{
11401 if (!scc->ssa_work_list) {
11402 scc->ssa_work_list = sedge;
11403 sedge->work_next = sedge->work_prev = sedge;
11404 }
11405 else {
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;
11412 }
11413}
11414
11415static struct ssa_edge *scc_next_sedge(
11416 struct compile_state *state, struct scc_state *scc)
11417{
11418 struct ssa_edge *sedge;
11419 sedge = scc->ssa_work_list;
11420 if (sedge) {
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;
11425 } else {
11426 scc->ssa_work_list = 0;
11427 }
11428 }
11429 return sedge;
11430}
11431
11432static void initialize_scc_state(
11433 struct compile_state *state, struct scc_state *scc)
11434{
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;
11440
11441 memset(scc, 0, sizeof(*scc));
11442
11443 /* Inialize pass zero find out how much memory we need */
Eric Biederman0babc1c2003-05-09 02:39:00 +000011444 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011445 ins = first;
11446 ins_count = ssa_edge_count = 0;
11447 do {
11448 struct triple_set *edge;
11449 ins_count += 1;
11450 for(edge = ins->use; edge; edge = edge->next) {
11451 ssa_edge_count++;
11452 }
11453 ins = ins->next;
11454 } while(ins != first);
11455#if DEBUG_SCC
11456 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
11457 ins_count, ssa_edge_count, state->last_vertex);
11458#endif
Eric Biederman0babc1c2003-05-09 02:39:00 +000011459 scc->ins_count = ins_count;
Eric Biedermanb138ac82003-04-22 18:44:01 +000011460 scc->lattice =
11461 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
11462 scc->ssa_edges =
11463 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
11464 scc->flow_blocks =
11465 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
11466 "flow_blocks");
11467
11468 /* Initialize pass one collect up the nodes */
11469 fblock = 0;
11470 block = 0;
11471 ins_index = ssa_edge_index = fblock_index = 0;
11472 ins = first;
11473 do {
11474 ins->id = 0;
11475 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11476 block = ins->u.block;
11477 if (!block) {
11478 internal_error(state, ins, "label without block");
11479 }
11480 fblock_index += 1;
11481 block->vertex = fblock_index;
11482 fblock = &scc->flow_blocks[fblock_index];
11483 fblock->block = block;
11484 }
11485 {
11486 struct lattice_node *lnode;
11487 ins_index += 1;
11488 ins->id = ins_index;
11489 lnode = &scc->lattice[ins_index];
11490 lnode->def = ins;
11491 lnode->out = 0;
11492 lnode->fblock = fblock;
11493 lnode->val = ins; /* LATTICE HIGH */
11494 }
11495 ins = ins->next;
11496 } while(ins != first);
11497 /* Initialize pass two collect up the edges */
11498 block = 0;
11499 fblock = 0;
11500 ins = first;
11501 do {
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];
11507 fblock->in = 0;
11508 fblock->out = 0;
11509 ftail = &fblock->out;
11510 if (block->left) {
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");
11514 }
11515 fblock->left.out_next = 0;
11516 *ftail = &fblock->left;
11517 ftail = &fblock->left.out_next;
11518 }
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");
11523 }
11524 fblock->right.out_next = 0;
11525 *ftail = &fblock->right;
11526 ftail = &fblock->right.out_next;
11527 }
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;
11532 }
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];
11540 sfedge = 0;
11541 if (src_block->left == block) {
11542 sfedge = &sfblock->left;
11543 } else {
11544 sfedge = &sfblock->right;
11545 }
11546 *ftail = sfedge;
11547 ftail = &sfedge->in_next;
11548 sfedge->in_next = 0;
11549 }
11550 }
11551 {
11552 struct triple_set *edge;
11553 struct ssa_edge **stail;
11554 struct lattice_node *lnode;
11555 lnode = &scc->lattice[ins->id];
11556 lnode->out = 0;
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];
11562 *stail = sedge;
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;
11568 }
11569 }
11570 ins = ins->next;
11571 } while(ins != first);
11572 /* Setup a dummy block 0 as a node above the start node */
11573 {
11574 struct flow_block *fblock, *dst;
11575 struct flow_edge *fedge;
11576 fblock = &scc->flow_blocks[0];
11577 fblock->block = 0;
11578 fblock->in = 0;
11579 fblock->out = &fblock->left;
11580 dst = &scc->flow_blocks[state->first_block->vertex];
11581 fedge = &fblock->left;
11582 fedge->src = fblock;
11583 fedge->dst = dst;
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;
11590
11591 /* Initialize the work lists */
11592 scc->flow_work_list = 0;
11593 scc->ssa_work_list = 0;
11594 scc_add_fedge(state, scc, fedge);
11595 }
11596#if DEBUG_SCC
11597 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
11598 ins_index, ssa_edge_index, fblock_index);
11599#endif
11600}
11601
11602
11603static void free_scc_state(
11604 struct compile_state *state, struct scc_state *scc)
11605{
Eric Biederman0babc1c2003-05-09 02:39:00 +000011606 int i;
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);
11611 }
11612 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000011613 xfree(scc->flow_blocks);
11614 xfree(scc->ssa_edges);
11615 xfree(scc->lattice);
Eric Biederman0babc1c2003-05-09 02:39:00 +000011616
Eric Biedermanb138ac82003-04-22 18:44:01 +000011617}
11618
11619static struct lattice_node *triple_to_lattice(
11620 struct compile_state *state, struct scc_state *scc, struct triple *ins)
11621{
11622 if (ins->id <= 0) {
11623 internal_error(state, ins, "bad id");
11624 }
11625 return &scc->lattice[ins->id];
11626}
11627
11628static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
11629 struct lattice_node *lnode)
11630{
11631 struct lattice_node *tmp;
11632 struct triple **slot;
11633 struct flow_edge *fedge;
11634 int index;
11635 if (lnode->def->op != OP_PHI) {
11636 internal_error(state, lnode->def, "not phi");
11637 }
11638 /* default to lattice high */
11639 lnode->val = lnode->def;
Eric Biederman0babc1c2003-05-09 02:39:00 +000011640 slot = &RHS(lnode->def, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011641 index = 0;
11642 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
11643 if (!fedge->executable) {
11644 continue;
11645 }
11646 if (!slot[index]) {
11647 internal_error(state, lnode->def, "no phi value");
11648 }
11649 tmp = triple_to_lattice(state, scc, slot[index]);
11650 /* meet(X, lattice low) = lattice low */
11651 if (!tmp->val) {
11652 lnode->val = 0;
11653 }
11654 /* meet(X, lattice high) = X */
11655 else if (!tmp->val) {
11656 lnode->val = lnode->val;
11657 }
11658 /* meet(lattice high, X) = X */
11659 else if (!is_const(lnode->val)) {
11660 lnode->val = tmp->val;
11661 }
11662 /* meet(const, const) = const or lattice low */
11663 else if (!constants_equal(state, lnode->val, tmp->val)) {
11664 lnode->val = 0;
11665 }
11666 if (!lnode->val) {
11667 break;
11668 }
11669 }
11670 /* Do I need to update any work lists here? */
11671#if DEBUG_SCC
11672 fprintf(stderr, "phi: %d -> %s\n",
11673 lnode->def->id,
11674 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11675#endif
11676}
11677
11678static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
11679 struct lattice_node *lnode)
11680{
11681 int changed;
Eric Biederman0babc1c2003-05-09 02:39:00 +000011682 struct triple *old, *scratch;
Eric Biedermanb138ac82003-04-22 18:44:01 +000011683 struct triple **dexpr, **vexpr;
Eric Biederman0babc1c2003-05-09 02:39:00 +000011684 int count, i;
Eric Biedermanb138ac82003-04-22 18:44:01 +000011685
Eric Biederman0babc1c2003-05-09 02:39:00 +000011686 if (lnode->def->op != OP_STORE) {
11687 check_lhs(state, lnode->def);
11688 }
11689
Eric Biedermanb138ac82003-04-22 18:44:01 +000011690 /* Store the original value */
11691 if (lnode->val) {
Eric Biederman0babc1c2003-05-09 02:39:00 +000011692 old = dup_triple(state, lnode->val);
11693 if (lnode->val != lnode->def) {
11694 xfree(lnode->val);
11695 }
11696 lnode->val = 0;
11697
Eric Biedermanb138ac82003-04-22 18:44:01 +000011698 } else {
11699 old = 0;
11700 }
11701 /* Reinitialize the value */
Eric Biederman0babc1c2003-05-09 02:39:00 +000011702 lnode->val = scratch = dup_triple(state, lnode->def);
11703 scratch->next = scratch;
11704 scratch->prev = scratch;
11705 scratch->use = 0;
11706
11707 count = TRIPLE_SIZE(scratch->sizes);
11708 for(i = 0; i < count; i++) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000011709 struct lattice_node *tmp;
Eric Biederman0babc1c2003-05-09 02:39:00 +000011710 dexpr = &lnode->def->param[i];
11711 vexpr = &scratch->param[i];
11712 *vexpr = 0;
11713 if (*dexpr) {
11714 tmp = triple_to_lattice(state, scc, *dexpr);
11715 *vexpr = (tmp->val)? tmp->val : tmp->def;
11716 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000011717 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000011718 if (scratch->op == OP_BRANCH) {
11719 scratch->next = lnode->def->next;
Eric Biedermanb138ac82003-04-22 18:44:01 +000011720 }
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.
11725 */
Eric Biederman0babc1c2003-05-09 02:39:00 +000011726 simplify(state, scratch);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011727 /* Cleanup my value */
Eric Biederman0babc1c2003-05-09 02:39:00 +000011728 if (scratch->use) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000011729 internal_error(state, lnode->def, "scratch used?");
11730 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000011731 if ((scratch->prev != scratch) ||
11732 ((scratch->next != scratch) &&
Eric Biedermanb138ac82003-04-22 18:44:01 +000011733 ((lnode->def->op != OP_BRANCH) ||
Eric Biederman0babc1c2003-05-09 02:39:00 +000011734 (scratch->next != lnode->def->next)))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000011735 internal_error(state, lnode->def, "scratch in list?");
11736 }
11737 /* undo any uses... */
Eric Biederman0babc1c2003-05-09 02:39:00 +000011738 count = TRIPLE_SIZE(scratch->sizes);
11739 for(i = 0; i < count; i++) {
11740 vexpr = &scratch->param[i];
11741 if (*vexpr) {
11742 unuse_triple(*vexpr, scratch);
11743 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000011744 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000011745 if (!is_const(scratch)) {
11746 for(i = 0; i < count; i++) {
11747 dexpr = &lnode->def->param[i];
11748 if (*dexpr) {
11749 struct lattice_node *tmp;
11750 tmp = triple_to_lattice(state, scc, *dexpr);
11751 if (!tmp->val) {
11752 lnode->val = 0;
11753 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000011754 }
11755 }
11756 }
11757 if (lnode->val &&
11758 (lnode->val->op == lnode->def->op) &&
Eric Biederman0babc1c2003-05-09 02:39:00 +000011759 (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)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000011762 lnode->val = lnode->def;
11763 }
11764 /* Find the cases that are always lattice lo */
11765 if (lnode->val &&
Eric Biederman0babc1c2003-05-09 02:39:00 +000011766 triple_is_def(state, lnode->val) &&
Eric Biedermanb138ac82003-04-22 18:44:01 +000011767 !triple_is_pure(state, lnode->val)) {
11768 lnode->val = 0;
11769 }
11770#if 1
11771 if (lnode->val &&
11772 (lnode->val->op == OP_SDECL) &&
11773 (lnode->val != lnode->def)) {
11774 internal_error(state, lnode->def, "bad sdecl");
11775 }
11776#endif
11777 /* See if the lattice value has changed */
11778 changed = 1;
11779 if (!old && !lnode->val) {
11780 changed = 0;
11781 }
11782 if (changed && lnode->val && !is_const(lnode->val)) {
11783 changed = 0;
11784 }
11785 if (changed &&
11786 lnode->val && old &&
11787 (lnode->val->op == old->op) &&
Eric Biederman0babc1c2003-05-09 02:39:00 +000011788 (memcmp(lnode->val->param, old->param,
11789 count * sizeof(lnode->val->param[0])) == 0) &&
Eric Biedermanb138ac82003-04-22 18:44:01 +000011790 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
11791 changed = 0;
11792 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000011793 if (old) {
11794 xfree(old);
11795 }
11796 if (lnode->val != scratch) {
11797 xfree(scratch);
11798 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000011799 return changed;
Eric Biedermanb138ac82003-04-22 18:44:01 +000011800}
Eric Biederman0babc1c2003-05-09 02:39:00 +000011801
Eric Biedermanb138ac82003-04-22 18:44:01 +000011802static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
11803 struct lattice_node *lnode)
11804{
11805 struct lattice_node *cond;
11806#if DEBUG_SCC
11807 {
11808 struct flow_edge *fedge;
11809 fprintf(stderr, "branch: %d (",
11810 lnode->def->id);
11811
11812 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
11813 fprintf(stderr, " %d", fedge->dst->block->vertex);
11814 }
11815 fprintf(stderr, " )");
Eric Biederman0babc1c2003-05-09 02:39:00 +000011816 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000011817 fprintf(stderr, " <- %d",
Eric Biederman0babc1c2003-05-09 02:39:00 +000011818 RHS(lnode->def)->id);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011819 }
11820 fprintf(stderr, "\n");
11821 }
11822#endif
11823 if (lnode->def->op != OP_BRANCH) {
11824 internal_error(state, lnode->def, "not branch");
11825 }
11826 /* This only applies to conditional branches */
Eric Biederman0babc1c2003-05-09 02:39:00 +000011827 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000011828 return;
11829 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000011830 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
Eric Biedermanb138ac82003-04-22 18:44:01 +000011831 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?");
11834 return;
11835 }
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);
11839 }
11840 else if (cond->val->u.cval) {
11841 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11842
11843 } else {
11844 scc_add_fedge(state, scc, cond->fblock->out);
11845 }
11846
11847}
11848
11849static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
11850 struct lattice_node *lnode)
11851{
11852 int changed;
11853
11854 changed = compute_lnode_val(state, scc, lnode);
11855#if DEBUG_SCC
11856 {
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)) {
Eric Biederman0babc1c2003-05-09 02:39:00 +000011862 if (*expr) {
11863 fprintf(stderr, " %d", (*expr)->id);
11864 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000011865 }
11866 fprintf(stderr, " ) -> %s\n",
11867 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11868 }
11869#endif
11870 if (lnode->def->op == OP_BRANCH) {
11871 scc_visit_branch(state, scc, lnode);
11872
11873 }
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);
11878 }
11879 }
11880}
11881
11882static void scc_writeback_values(
11883 struct compile_state *state, struct scc_state *scc)
11884{
11885 struct triple *first, *ins;
Eric Biederman0babc1c2003-05-09 02:39:00 +000011886 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011887 ins = first;
11888 do {
11889 struct lattice_node *lnode;
11890 lnode = triple_to_lattice(state, scc, ins);
11891#if DEBUG_SCC
11892 if (lnode->val && !is_const(lnode->val)) {
11893 warning(state, lnode->def,
11894 "lattice node still high?");
11895 }
11896#endif
11897 if (lnode->val && (lnode->val != ins)) {
11898 /* See if it something I know how to write back */
11899 switch(lnode->val->op) {
11900 case OP_INTCONST:
11901 mkconst(state, ins, lnode->val->u.cval);
11902 break;
11903 case OP_ADDRCONST:
11904 mkaddr_const(state, ins,
Eric Biederman0babc1c2003-05-09 02:39:00 +000011905 RHS(lnode->val, 0), lnode->val->u.cval);
Eric Biedermanb138ac82003-04-22 18:44:01 +000011906 break;
11907 default:
11908 /* By default don't copy the changes,
11909 * recompute them in place instead.
11910 */
11911 simplify(state, ins);
11912 break;
11913 }
11914 }
11915 ins = ins->next;
11916 } while(ins != first);
11917}
11918
11919static void scc_transform(struct compile_state *state)
11920{
11921 struct scc_state scc;
11922
11923 initialize_scc_state(state, &scc);
11924
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;
11933 int time;
11934 int done;
11935 if (fedge->executable) {
11936 continue;
11937 }
11938 if (!fedge->dst) {
11939 internal_error(state, 0, "fedge without dst");
11940 }
11941 if (!fedge->src) {
11942 internal_error(state, 0, "fedge without src");
11943 }
11944 fedge->executable = 1;
11945 fblock = fedge->dst;
11946 block = fblock->block;
11947 time = 0;
11948 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
11949 if (fptr->executable) {
11950 time++;
11951 }
11952 }
11953#if DEBUG_SCC
11954 fprintf(stderr, "vertex: %d time: %d\n",
11955 block->vertex, time);
11956
11957#endif
11958 done = 0;
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);
11965 }
11966 else if (time == 1) {
11967 scc_visit_expr(state, &scc, lnode);
11968 }
11969 }
11970 if (fblock->out && !fblock->out->out_next) {
11971 scc_add_fedge(state, &scc, fblock->out);
11972 }
11973 }
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;
11979#if DEBUG_SCC
11980 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
11981 sedge - scc.ssa_edges,
11982 sedge->src->def->id,
11983 sedge->dst->def->id);
11984#endif
11985 if (lnode->def->op == OP_PHI) {
11986 scc_visit_phi(state, &scc, lnode);
11987 }
11988 else {
11989 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
11990 if (fptr->executable) {
11991 break;
11992 }
11993 }
11994 if (fptr) {
11995 scc_visit_expr(state, &scc, lnode);
11996 }
11997 }
11998 }
11999 }
12000
12001 scc_writeback_values(state, &scc);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012002 free_scc_state(state, &scc);
12003}
12004
12005
12006static void transform_to_arch_instructions(struct compile_state *state);
12007
12008
12009static void optimize(struct compile_state *state)
12010{
12011 if (state->debug & DEBUG_TRIPLES) {
12012 print_triples(state);
12013 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000012014 /* Replace structures with simpler data types */
12015 flatten_structures(state);
12016 if (state->debug & DEBUG_TRIPLES) {
12017 print_triples(state);
12018 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000012019 /* 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);
12028 }
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);
12038
12039 }
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.
12045 */
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);
12051 }
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);
12057 }
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);
12063 }
12064 if (state->debug & DEBUG_CONTROL_FLOW) {
12065 print_control_flow(state);
12066 }
12067 /* Remove the optimization information.
12068 * This is more to check for memory consistency than to free memory.
12069 */
12070 free_basic_blocks(state);
12071}
12072
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
12079#define REGC_MMX 5
12080#define REGC_XMM 6
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"
12086#endif
12087
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)
12098
12099/* The x86 registers */
12100#define REG_EFLAGS 1
12101#define REGC_FLAGS_FIRST REG_EFLAGS
12102#define REGC_FLAGS_LAST REG_EFLAGS
12103#define REG_AL 2
12104#define REG_BL 3
12105#define REG_CL 4
12106#define REG_DL 5
12107#define REG_AH 6
12108#define REG_BH 7
12109#define REG_CH 8
12110#define REG_DH 9
12111#define REGC_GPR8_FIRST REG_AL
12112#if X86_4_8BIT_GPRS
12113#define REGC_GPR8_LAST REG_DL
12114#else
12115#define REGC_GPR8_LAST REG_DH
12116#endif
12117#define REG_AX 10
12118#define REG_BX 11
12119#define REG_CX 12
12120#define REG_DX 13
12121#define REG_SI 14
12122#define REG_DI 15
12123#define REG_BP 16
12124#define REG_SP 17
12125#define REGC_GPR16_FIRST REG_AX
12126#define REGC_GPR16_LAST REG_SP
12127#define REG_EAX 18
12128#define REG_EBX 19
12129#define REG_ECX 20
12130#define REG_EDX 21
12131#define REG_ESI 22
12132#define REG_EDI 23
12133#define REG_EBP 24
12134#define REG_ESP 25
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
12162
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
12167
12168#if LAST_REG >= MAX_REGISTERS
12169#error "MAX_REGISTERS to low"
12170#endif
12171
12172static unsigned arch_regc_size(struct compile_state *state, int class)
12173{
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,
12184 };
12185 if ((class < 0) || (class > LAST_REGC)) {
12186 return 0;
12187 }
12188 return regc_size[class];
12189}
12190static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
12191{
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;
12195
12196 return (regcm1 & regcm2) ||
12197 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
12198}
12199
12200static void arch_reg_equivs(
12201 struct compile_state *state, unsigned *equiv, int reg)
12202{
12203 if ((reg < 0) || (reg > LAST_REG)) {
12204 internal_error(state, 0, "invalid register");
12205 }
12206 *equiv++ = reg;
12207 switch(reg) {
12208 case REG_AL:
12209 case REG_AH:
12210 *equiv++ = REG_AX;
12211 *equiv++ = REG_EAX;
12212 *equiv++ = REG_EDXEAX;
12213 break;
12214 case REG_BL:
12215 case REG_BH:
12216 *equiv++ = REG_BX;
12217 *equiv++ = REG_EBX;
12218 break;
12219 case REG_CL:
12220 case REG_CH:
12221 *equiv++ = REG_CX;
12222 *equiv++ = REG_ECX;
12223 break;
12224 case REG_DL:
12225 case REG_DH:
12226 *equiv++ = REG_DX;
12227 *equiv++ = REG_EDX;
12228 *equiv++ = REG_EDXEAX;
12229 break;
12230 case REG_AX:
12231 *equiv++ = REG_AL;
12232 *equiv++ = REG_AH;
12233 *equiv++ = REG_EAX;
12234 *equiv++ = REG_EDXEAX;
12235 break;
12236 case REG_BX:
12237 *equiv++ = REG_BL;
12238 *equiv++ = REG_BH;
12239 *equiv++ = REG_EBX;
12240 break;
12241 case REG_CX:
12242 *equiv++ = REG_CL;
12243 *equiv++ = REG_CH;
12244 *equiv++ = REG_ECX;
12245 break;
12246 case REG_DX:
12247 *equiv++ = REG_DL;
12248 *equiv++ = REG_DH;
12249 *equiv++ = REG_EDX;
12250 *equiv++ = REG_EDXEAX;
12251 break;
12252 case REG_SI:
12253 *equiv++ = REG_ESI;
12254 break;
12255 case REG_DI:
12256 *equiv++ = REG_EDI;
12257 break;
12258 case REG_BP:
12259 *equiv++ = REG_EBP;
12260 break;
12261 case REG_SP:
12262 *equiv++ = REG_ESP;
12263 break;
12264 case REG_EAX:
12265 *equiv++ = REG_AL;
12266 *equiv++ = REG_AH;
12267 *equiv++ = REG_AX;
12268 *equiv++ = REG_EDXEAX;
12269 break;
12270 case REG_EBX:
12271 *equiv++ = REG_BL;
12272 *equiv++ = REG_BH;
12273 *equiv++ = REG_BX;
12274 break;
12275 case REG_ECX:
12276 *equiv++ = REG_CL;
12277 *equiv++ = REG_CH;
12278 *equiv++ = REG_CX;
12279 break;
12280 case REG_EDX:
12281 *equiv++ = REG_DL;
12282 *equiv++ = REG_DH;
12283 *equiv++ = REG_DX;
12284 *equiv++ = REG_EDXEAX;
12285 break;
12286 case REG_ESI:
12287 *equiv++ = REG_SI;
12288 break;
12289 case REG_EDI:
12290 *equiv++ = REG_DI;
12291 break;
12292 case REG_EBP:
12293 *equiv++ = REG_BP;
12294 break;
12295 case REG_ESP:
12296 *equiv++ = REG_SP;
12297 break;
12298 case REG_EDXEAX:
12299 *equiv++ = REG_AL;
12300 *equiv++ = REG_AH;
12301 *equiv++ = REG_DL;
12302 *equiv++ = REG_DH;
12303 *equiv++ = REG_AX;
12304 *equiv++ = REG_DX;
12305 *equiv++ = REG_EAX;
12306 *equiv++ = REG_EDX;
12307 break;
12308 }
12309 *equiv++ = REG_UNSET;
12310}
12311
12312
12313static unsigned arch_reg_regcm(struct compile_state *state, int reg)
12314{
12315 static const struct {
12316 int first, last;
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 },
12327 };
12328 unsigned mask;
12329 int class;
12330 mask = 0;
12331 for(class = 0; class <= LAST_REGC; class++) {
12332 if ((reg >= bound[class].first) &&
12333 (reg <= bound[class].last)) {
12334 mask |= (1 << class);
12335 }
12336 }
12337 if (!mask) {
12338 internal_error(state, 0, "reg %d not in any class", reg);
12339 }
12340 return mask;
12341}
12342
12343static int do_select_reg(struct compile_state *state,
12344 char *used, int reg, unsigned classes)
12345{
12346 unsigned mask;
12347 if (used[reg]) {
12348 return REG_UNSET;
12349 }
12350 mask = arch_reg_regcm(state, reg);
12351 return (classes & mask) ? reg : REG_UNSET;
12352}
12353
12354static int arch_select_free_register(
12355 struct compile_state *state, char *used, int classes)
12356{
12357 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
12358 * other types of registers.
12359 */
12360 int i, reg;
12361 reg = REG_UNSET;
12362 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
12363 reg = do_select_reg(state, used, i, classes);
12364 }
12365 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
12366 reg = do_select_reg(state, used, i, classes);
12367 }
12368 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
12369 reg = do_select_reg(state, used, i, classes);
12370 }
12371 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
12372 reg = do_select_reg(state, used, i, classes);
12373 }
12374 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
12375 reg = do_select_reg(state, used, i, classes);
12376 }
12377 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
12378 reg = do_select_reg(state, used, i, classes);
12379 }
12380 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
12381 reg = do_select_reg(state, used, i, classes);
12382 }
12383 return reg;
12384}
12385
12386static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
12387{
12388#warning "FIXME force types smaller (if legal) before I get here"
12389 int use_mmx = 0;
12390 int use_sse = 0;
12391 unsigned avail_mask;
12392 unsigned mask;
12393 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
12394 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64;
12395#if 1
12396 /* Don't enable 8 bit values until I can force both operands
12397 * to be 8bits simultaneously.
12398 */
12399 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
12400#endif
12401 if (use_mmx) {
12402 avail_mask |= REGCM_MMX;
12403 }
12404 if (use_sse) {
12405 avail_mask |= REGCM_XMM;
12406 }
12407 mask = 0;
12408 switch(type->type & TYPE_MASK) {
12409 case TYPE_ARRAY:
12410 case TYPE_VOID:
12411 mask = 0;
12412 break;
12413 case TYPE_CHAR:
12414 case TYPE_UCHAR:
12415 mask = REGCM_GPR8 |
12416 REGCM_GPR16_8 | REGCM_GPR16 |
12417 REGCM_GPR32 | REGCM_GPR32_8 |
12418 REGCM_GPR64 |
12419 REGCM_MMX | REGCM_XMM;
12420 break;
12421 case TYPE_SHORT:
12422 case TYPE_USHORT:
12423 mask = REGCM_GPR16 | REGCM_GPR16_8 |
12424 REGCM_GPR32 | REGCM_GPR32_8 |
12425 REGCM_GPR64 |
12426 REGCM_MMX | REGCM_XMM;
12427 break;
12428 case TYPE_INT:
12429 case TYPE_UINT:
12430 case TYPE_LONG:
12431 case TYPE_ULONG:
12432 case TYPE_POINTER:
12433 mask = REGCM_GPR32 | REGCM_GPR32_8 |
12434 REGCM_GPR64 | REGCM_MMX | REGCM_XMM;
12435 break;
12436 default:
12437 internal_error(state, 0, "no register class for type");
12438 break;
12439 }
12440 mask &= avail_mask;
12441 return mask;
12442}
12443
12444static void get_imm32(struct triple *ins, struct triple **expr)
12445{
12446 struct triple *imm;
12447 if ((*expr)->op != OP_COPY) {
12448 return;
12449 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000012450 imm = RHS((*expr), 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012451 while(imm->op == OP_COPY) {
Eric Biederman0babc1c2003-05-09 02:39:00 +000012452 imm = RHS(imm, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012453 }
12454 if (imm->op != OP_INTCONST) {
12455 return;
12456 }
12457 *expr = imm;
12458 unuse_triple(*expr, ins);
12459 use_triple(*expr, ins);
12460}
12461
12462static void get_imm8(struct triple *ins, struct triple **expr)
12463{
12464 struct triple *imm;
12465 if ((*expr)->op != OP_COPY) {
12466 return;
12467 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000012468 imm = RHS((*expr), 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012469 while(imm->op == OP_COPY) {
Eric Biederman0babc1c2003-05-09 02:39:00 +000012470 imm = RHS(imm, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012471 }
12472 if (imm->op != OP_INTCONST) {
12473 return;
12474 }
12475 /* For imm8 only a sufficienlty small constant can be used */
12476 if (imm->u.cval > 0xff) {
12477 return;
12478 }
12479 *expr = imm;
12480 unuse_triple(*expr, ins);
12481 use_triple(*expr, ins);
12482}
12483
12484static struct triple *pre_copy(struct compile_state *state,
12485 struct triple *ins, struct triple **expr,
12486 unsigned reg, unsigned mask)
12487{
12488 /* Carefully insert enough operations so that I can
12489 * enter any operation with a GPR32.
12490 */
12491 struct triple *in;
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);
12495 }
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);
Eric Biederman0babc1c2003-05-09 02:39:00 +000012505 use_triple(RHS(tmp, 0), tmp);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012506 insert_triple(state, ins, tmp);
12507
12508 in = triple(state, OP_COPY, tmp->type, tmp, 0);
12509 }
12510 else {
12511 internal_error(state, ins, "bad copy type");
12512 in = 0;
12513 }
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);
12520 *expr = in;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012521 use_triple(RHS(in, 0), in);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012522 use_triple(in, ins);
12523 insert_triple(state, ins, in);
12524 return in;
12525}
12526
12527static struct triple *post_copy(struct compile_state *state, struct triple *ins)
12528{
12529 struct triple_set *entry, *next;
12530 struct triple *out, *label;
12531 struct block *block;
12532 label = ins;
12533 while(label->op != OP_LABEL) {
12534 label = label->prev;
12535 }
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) {
12547 block->last = out;
12548 }
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) {
12553 continue;
12554 }
12555 replace_rhs_use(state, ins, out, entry->member);
12556 }
12557 return out;
12558}
12559
12560static void fixup_branches(struct compile_state *state,
12561 struct triple *cmp, struct triple *use, int jmp_op)
12562{
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);
12568 }
12569 else if (entry->member->op == OP_BRANCH) {
12570 struct triple *branch, *test;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012571 struct triple *left, *right;
12572 left = right = 0;
12573 left = RHS(cmp, 0);
12574 if (TRIPLE_RHS(cmp->sizes) > 1) {
12575 right = RHS(cmp, 1);
12576 }
Eric Biedermanb138ac82003-04-22 18:44:01 +000012577 branch = entry->member;
12578 test = pre_triple(state, branch,
Eric Biederman0babc1c2003-05-09 02:39:00 +000012579 cmp->op, cmp->type, left, right);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012580 test->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
Eric Biederman0babc1c2003-05-09 02:39:00 +000012581 unuse_triple(RHS(branch, 0), branch);
12582 RHS(branch, 0) = test;
Eric Biedermanb138ac82003-04-22 18:44:01 +000012583 branch->op = jmp_op;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012584 use_triple(RHS(branch, 0), branch);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012585 }
12586 }
12587}
12588
12589static void bool_cmp(struct compile_state *state,
12590 struct triple *ins, int cmp_op, int jmp_op, int set_op)
12591{
12592 struct block *block;
12593 struct triple_set *entry, *next;
12594 struct triple *set, *tmp1, *tmp2;
12595
12596#warning "WISHLIST implement an expression simplifier to reduce the use of set?"
12597
12598 block = ins->u.block;
12599
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.
12603 */
12604
12605 /* Modify the comparison operator */
12606 ins->op = cmp_op;
12607 ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12608 if (cmp_op == OP_CMP) {
Eric Biederman0babc1c2003-05-09 02:39:00 +000012609 get_imm32(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +000012610 }
12611 /* Generate the instruction sequence that will transform the
12612 * result of the comparison into a logical value.
12613 */
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);
12622
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);
12632
12633 if (block->last == ins) {
12634 block->last = tmp2;
12635 }
12636
12637 set = tmp2;
12638 for(entry = ins->use; entry; entry = next) {
12639 next = entry->next;
12640 if (entry->member == tmp1) {
12641 continue;
12642 }
12643 replace_rhs_use(state, ins, set, entry->member);
12644 }
12645 fixup_branches(state, ins, set, jmp_op);
12646}
12647
Eric Biederman0babc1c2003-05-09 02:39:00 +000012648static void verify_lhs(struct compile_state *state, struct triple *ins)
12649{
12650 struct triple *next;
12651 int lhs, i;
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",
12656 tops(ins->op));
12657 }
12658 }
12659}
Eric Biedermanb138ac82003-04-22 18:44:01 +000012660
12661static void transform_to_arch_instructions(struct compile_state *state)
12662{
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.
12668 */
12669 struct triple *ins, *first, *next;
12670 struct triple *in, *in2;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012671 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012672 ins = first;
12673 do {
12674 next = ins->next;
12675 ins->id = MK_REG_ID(REG_UNSET, arch_type_to_regcm(state, ins->type));
12676 switch(ins->op) {
12677 case OP_INTCONST:
12678 case OP_ADDRCONST:
12679 ins->id = 0;
12680 post_copy(state, ins);
12681 break;
12682 case OP_NOOP:
12683 case OP_SDECL:
12684 case OP_BLOBCONST:
12685 case OP_LABEL:
12686 ins->id = 0;
12687 break;
12688 /* instructions that can be used as is */
12689 case OP_COPY:
12690 case OP_PHI:
12691 break;
12692 case OP_STORE:
12693 {
12694 unsigned mask;
12695 ins->id = 0;
12696 switch(ins->type->type & TYPE_MASK) {
12697 case TYPE_CHAR: case TYPE_UCHAR:
12698 mask = REGCM_GPR8;
12699 break;
12700 case TYPE_SHORT: case TYPE_USHORT:
12701 mask = REGCM_GPR16;
12702 break;
12703 case TYPE_INT: case TYPE_UINT:
12704 case TYPE_LONG: case TYPE_ULONG:
12705 case TYPE_POINTER:
12706 mask = REGCM_GPR32;
12707 break;
12708 default:
12709 internal_error(state, ins, "unknown type in store");
12710 mask = 0;
12711 break;
12712 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000012713 in = pre_copy(state, ins, &RHS(ins, 0), REG_UNSET, mask);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012714 break;
12715 }
12716 case OP_LOAD:
12717 switch(ins->type->type & TYPE_MASK) {
12718 case TYPE_CHAR: case TYPE_UCHAR:
12719 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12720 break;
12721 case TYPE_SHORT:
12722 case TYPE_USHORT:
12723 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR16);
12724 break;
12725 case TYPE_INT:
12726 case TYPE_UINT:
12727 case TYPE_LONG:
12728 case TYPE_ULONG:
12729 case TYPE_POINTER:
12730 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32);
12731 break;
12732 default:
12733 internal_error(state, ins, "unknown type in load");
12734 break;
12735 }
12736 break;
12737 case OP_ADD:
12738 case OP_SUB:
12739 case OP_AND:
12740 case OP_XOR:
12741 case OP_OR:
Eric Biederman0babc1c2003-05-09 02:39:00 +000012742 get_imm32(ins, &RHS(ins, 1));
12743 in = pre_copy(state, ins, &RHS(ins, 0),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012744 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12745 ins->id = in->id;
12746 break;
12747 case OP_SL:
12748 case OP_SSR:
12749 case OP_USR:
Eric Biederman0babc1c2003-05-09 02:39:00 +000012750 get_imm8(ins, &RHS(ins, 1));
12751 in = pre_copy(state, ins, &RHS(ins, 0),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012752 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12753 ins->id = in->id;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012754 if (!is_const(RHS(ins, 1))) {
12755 in2 = pre_copy(state, ins, &RHS(ins, 1),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012756 REG_CL, REGCM_GPR8);
12757 }
12758 break;
12759 case OP_INVERT:
12760 case OP_NEG:
Eric Biederman0babc1c2003-05-09 02:39:00 +000012761 in = pre_copy(state, ins, &RHS(ins, 0),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012762 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12763 ins->id = in->id;
12764 break;
12765 case OP_SMUL:
Eric Biederman0babc1c2003-05-09 02:39:00 +000012766 get_imm32(ins, &RHS(ins, 1));
12767 in = pre_copy(state, ins, &RHS(ins, 0),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012768 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12769 ins->id = in->id;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012770 if (!is_const(RHS(ins, 1))) {
12771 in2 = pre_copy(state, ins, &RHS(ins, 1),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012772 REG_UNSET, REGCM_GPR32);
12773 }
12774 break;
12775 case OP_EQ:
12776 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
12777 break;
12778 case OP_NOTEQ:
12779 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12780 break;
12781 case OP_SLESS:
12782 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
12783 break;
12784 case OP_ULESS:
12785 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
12786 break;
12787 case OP_SMORE:
12788 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
12789 break;
12790 case OP_UMORE:
12791 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
12792 break;
12793 case OP_SLESSEQ:
12794 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
12795 break;
12796 case OP_ULESSEQ:
12797 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
12798 break;
12799 case OP_SMOREEQ:
12800 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
12801 break;
12802 case OP_UMOREEQ:
12803 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
12804 break;
12805 case OP_LTRUE:
12806 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12807 break;
12808 case OP_LFALSE:
12809 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
12810 break;
12811 case OP_BRANCH:
Eric Biederman0babc1c2003-05-09 02:39:00 +000012812 if (TRIPLE_RHS(ins->sizes) > 0) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000012813 internal_error(state, ins, "bad branch test");
12814 }
12815 ins->op = OP_JMP;
12816 break;
12817
12818 case OP_INB:
12819 case OP_INW:
12820 case OP_INL:
Eric Biederman0babc1c2003-05-09 02:39:00 +000012821 get_imm8(ins, &RHS(ins, 0));
Eric Biedermanb138ac82003-04-22 18:44:01 +000012822 switch(ins->op) {
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;
12826 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000012827 if (!is_const(RHS(ins, 0))) {
12828 in = pre_copy(state, ins, &RHS(ins, 0),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012829 REG_DX, REGCM_GPR16);
12830 }
12831 break;
12832 case OP_OUTB:
12833 case OP_OUTW:
12834 case OP_OUTL:
12835 {
12836 unsigned reg, mask;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012837 get_imm8(ins, &RHS(ins, 1));
Eric Biedermanb138ac82003-04-22 18:44:01 +000012838 switch(ins->op) {
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;
12843 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000012844 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),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012847 REG_DX, REGCM_GPR16);
12848 }
12849 break;
12850 }
12851 case OP_BSF:
12852 case OP_BSR:
Eric Biederman0babc1c2003-05-09 02:39:00 +000012853 in = pre_copy(state, ins, &RHS(ins, 0),
Eric Biedermanb138ac82003-04-22 18:44:01 +000012854 REG_UNSET, REGCM_GPR32);
12855 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32 | REGCM_GPR32_8);
12856 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012857 case OP_RDMSR:
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;
12864 break;
12865 case OP_WRMSR:
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);
12869 break;
12870 case OP_HLT:
12871 break;
Eric Biedermanb138ac82003-04-22 18:44:01 +000012872 /* Already transformed instructions */
12873 case OP_CMP:
12874 case OP_TEST:
12875 ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12876 break;
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:
12887 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012888 /* Unhandled instructions */
12889 case OP_PIECE:
Eric Biedermanb138ac82003-04-22 18:44:01 +000012890 default:
12891 internal_error(state, ins, "unhandled ins: %d %s\n",
12892 ins->op, tops(ins->op));
12893 break;
12894 }
12895 ins = next;
12896 } while(ins != first);
12897}
12898
Eric Biedermanb138ac82003-04-22 18:44:01 +000012899static void generate_local_labels(struct compile_state *state)
12900{
12901 struct triple *first, *label;
12902 int label_counter;
12903 label_counter = 0;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012904 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000012905 label = first;
12906 do {
12907 if ((label->op == OP_LABEL) ||
12908 (label->op == OP_SDECL)) {
12909 if (label->use) {
12910 label->u.cval = ++label_counter;
12911 } else {
12912 label->u.cval = 0;
12913 }
12914
12915 }
12916 label = label->next;
12917 } while(label != first);
12918}
12919
12920static int check_reg(struct compile_state *state,
12921 struct triple *triple, int classes)
12922{
12923 unsigned mask;
12924 int reg;
12925 reg = ID_REG(triple->id);
12926 if (reg == REG_UNSET) {
12927 internal_error(state, triple, "register not set");
12928 }
12929 if (ID_REG_CLASSES(triple->id)) {
12930 internal_error(state, triple, "class specifier present");
12931 }
12932 mask = arch_reg_regcm(state, reg);
12933 if (!(classes & mask)) {
12934 internal_error(state, triple, "reg %d in wrong class",
12935 reg);
12936 }
12937 return reg;
12938}
12939
12940static const char *arch_reg_str(int reg)
12941{
12942 static const char *regs[] = {
12943 "%bad_register",
12944 "%eflags",
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",
12948 "%edx:%eax",
12949 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
12950 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
12951 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
12952 };
12953 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
12954 reg = 0;
12955 }
12956 return regs[reg];
12957}
12958
12959static const char *reg(struct compile_state *state, struct triple *triple,
12960 int classes)
12961{
12962 int reg;
12963 reg = check_reg(state, triple, classes);
12964 return arch_reg_str(reg);
12965}
12966
12967const char *type_suffix(struct compile_state *state, struct type *type)
12968{
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;
12974 default:
12975 internal_error(state, 0, "unknown suffix");
12976 suffix = 0;
12977 break;
12978 }
12979 return suffix;
12980}
12981
12982static void print_binary_op(struct compile_state *state,
12983 const char *op, struct triple *ins, FILE *fp)
12984{
12985 unsigned mask;
12986 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
Eric Biederman0babc1c2003-05-09 02:39:00 +000012987 if (RHS(ins, 0)->id != ins->id) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000012988 internal_error(state, ins, "invalid register assignment");
12989 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000012990 if (is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000012991 fprintf(fp, "\t%s $%lu, %s\n",
12992 op,
Eric Biederman0babc1c2003-05-09 02:39:00 +000012993 RHS(ins, 1)->u.cval,
12994 reg(state, RHS(ins, 0), mask));
Eric Biedermanb138ac82003-04-22 18:44:01 +000012995
12996 }
12997 else {
12998 unsigned lmask, rmask;
12999 int lreg, rreg;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013000 lreg = check_reg(state, RHS(ins, 0), mask);
13001 rreg = check_reg(state, RHS(ins, 1), mask);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013002 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",
13006 op,
Eric Biederman0babc1c2003-05-09 02:39:00 +000013007 reg(state, RHS(ins, 1), mask),
13008 reg(state, RHS(ins, 0), mask));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013009 }
13010}
13011static void print_unary_op(struct compile_state *state,
13012 const char *op, struct triple *ins, FILE *fp)
13013{
13014 unsigned mask;
13015 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13016 fprintf(fp, "\t%s %s\n",
13017 op,
Eric Biederman0babc1c2003-05-09 02:39:00 +000013018 reg(state, RHS(ins, 0), mask));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013019}
13020
13021static void print_op_shift(struct compile_state *state,
13022 const char *op, struct triple *ins, FILE *fp)
13023{
13024 unsigned mask;
13025 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013026 if (RHS(ins, 0)->id != ins->id) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013027 internal_error(state, ins, "invalid register assignment");
13028 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013029 if (is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013030 fprintf(fp, "\t%s $%lu, %s\n",
13031 op,
Eric Biederman0babc1c2003-05-09 02:39:00 +000013032 RHS(ins, 1)->u.cval,
13033 reg(state, RHS(ins, 0), mask));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013034
13035 }
13036 else {
13037 fprintf(fp, "\t%s %s, %s\n",
13038 op,
Eric Biederman0babc1c2003-05-09 02:39:00 +000013039 reg(state, RHS(ins, 1), REGCM_GPR8),
13040 reg(state, RHS(ins, 0), mask));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013041 }
13042}
13043
13044static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
13045{
13046 const char *op;
13047 int mask;
13048 int dreg;
13049 mask = 0;
13050 switch(ins->op) {
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;
13054 default:
13055 internal_error(state, ins, "not an in operation");
13056 op = 0;
13057 break;
13058 }
13059 dreg = check_reg(state, ins, mask);
13060 if (!reg_is_reg(state, dreg, REG_EAX)) {
13061 internal_error(state, ins, "dst != %%eax");
13062 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013063 if (is_const(RHS(ins, 0))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013064 fprintf(fp, "\t%s $%lu, %s\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013065 op, RHS(ins, 0)->u.cval,
Eric Biedermanb138ac82003-04-22 18:44:01 +000013066 reg(state, ins, mask));
13067 }
13068 else {
13069 int addr_reg;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013070 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013071 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13072 internal_error(state, ins, "src != %%dx");
13073 }
13074 fprintf(fp, "\t%s %s, %s\n",
13075 op,
Eric Biederman0babc1c2003-05-09 02:39:00 +000013076 reg(state, RHS(ins, 0), REGCM_GPR16),
Eric Biedermanb138ac82003-04-22 18:44:01 +000013077 reg(state, ins, mask));
13078 }
13079}
13080
13081static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
13082{
13083 const char *op;
13084 int mask;
13085 int lreg;
13086 mask = 0;
13087 switch(ins->op) {
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;
13091 default:
13092 internal_error(state, ins, "not an out operation");
13093 op = 0;
13094 break;
13095 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013096 lreg = check_reg(state, RHS(ins, 0), mask);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013097 if (!reg_is_reg(state, lreg, REG_EAX)) {
13098 internal_error(state, ins, "src != %%eax");
13099 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013100 if (is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013101 fprintf(fp, "\t%s %s, $%lu\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013102 op, reg(state, RHS(ins, 0), mask),
13103 RHS(ins, 1)->u.cval);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013104 }
13105 else {
13106 int addr_reg;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013107 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013108 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13109 internal_error(state, ins, "dst != %%dx");
13110 }
13111 fprintf(fp, "\t%s %s, %s\n",
13112 op,
Eric Biederman0babc1c2003-05-09 02:39:00 +000013113 reg(state, RHS(ins, 0), mask),
13114 reg(state, RHS(ins, 1), REGCM_GPR16));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013115 }
13116}
13117
13118static void print_op_move(struct compile_state *state,
13119 struct triple *ins, FILE *fp)
13120{
13121 /* op_move is complex because there are many types
13122 * of registers we can move between.
13123 */
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) {
Eric Biederman0babc1c2003-05-09 02:39:00 +000013127 src = RHS(ins, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013128 dst = ins;
13129 }
13130 else if (ins->op == OP_WRITE) {
Eric Biederman0babc1c2003-05-09 02:39:00 +000013131 dst = LHS(ins, 0);
13132 src = RHS(ins, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013133 }
13134 else {
13135 internal_error(state, ins, "unknown move operation");
13136 src = dst = 0;
13137 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013138 if (!is_const(src)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013139 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));
13152 }
13153 }
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));
13162 }
13163 }
13164 /* Move 32bit to 8bit */
13165 else if ((src_regcm & REGCM_GPR32_8) &&
13166 (dst_regcm & REGCM_GPR8))
13167 {
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));
13173 }
13174 }
13175 /* Move 16bit to 8bit */
13176 else if ((src_regcm & REGCM_GPR16_8) &&
13177 (dst_regcm & REGCM_GPR8))
13178 {
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));
13184 }
13185 }
13186 /* Move 8/16bit to 16/32bit */
13187 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
13188 (dst_regcm & (REGC_GPR16 | REGCM_GPR32))) {
13189 const char *op;
13190 op = is_signed(src->type)? "movsx": "movzx";
13191 fprintf(fp, "\t%s %s, %s\n",
13192 op,
13193 reg(state, src, src_regcm),
13194 reg(state, dst, dst_regcm));
13195 }
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));
13202 }
13203 }
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));
13211 }
13212 }
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));
13219 }
13220 else {
13221 internal_error(state, ins, "unknown copy type");
13222 }
13223 }
13224 else switch(src->op) {
13225 case OP_INTCONST:
13226 {
13227 long_t value;
13228 value = (long_t)(src->u.cval);
13229 fprintf(fp, "\tmov $%ld, %s\n",
13230 value,
13231 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
13232 break;
13233 }
13234 case OP_ADDRCONST:
13235 fprintf(fp, "\tmov $L%lu+%lu, %s\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013236 RHS(src, 0)->u.cval,
Eric Biedermanb138ac82003-04-22 18:44:01 +000013237 src->u.cval,
13238 reg(state, dst, REGCM_GPR32));
13239 break;
13240 default:
13241 internal_error(state, ins, "uknown copy operation");
13242 }
13243}
13244
13245static void print_op_load(struct compile_state *state,
13246 struct triple *ins, FILE *fp)
13247{
13248 struct triple *dst, *src;
13249 dst = ins;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013250 src = RHS(ins, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013251 if (is_const(src) || is_const(dst)) {
13252 internal_error(state, ins, "unknown load operation");
13253 }
13254 fprintf(fp, "\tmov (%s), %s\n",
13255 reg(state, src, REGCM_GPR32),
13256 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
13257}
13258
13259
13260static void print_op_store(struct compile_state *state,
13261 struct triple *ins, FILE *fp)
13262{
13263 struct triple *dst, *src;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013264 dst = LHS(ins, 0);
13265 src = RHS(ins, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013266 if (is_const(src) && (src->op == OP_INTCONST)) {
13267 long_t value;
13268 value = (long_t)(src->u.cval);
13269 fprintf(fp, "\tmov%s $%ld, (%s)\n",
13270 type_suffix(state, src->type),
13271 value,
13272 reg(state, dst, REGCM_GPR32));
13273 }
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),
13278 dst->u.cval);
13279 }
13280 else {
13281 if (is_const(src) || is_const(dst)) {
13282 internal_error(state, ins, "unknown store operation");
13283 }
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));
13288 }
13289
13290
13291}
13292
13293static void print_op_smul(struct compile_state *state,
13294 struct triple *ins, FILE *fp)
13295{
Eric Biederman0babc1c2003-05-09 02:39:00 +000013296 if (!is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013297 fprintf(fp, "\timul %s, %s\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013298 reg(state, RHS(ins, 1), REGCM_GPR32),
13299 reg(state, RHS(ins, 0), REGCM_GPR32));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013300 }
13301 else {
13302 fprintf(fp, "\timul $%ld, %s\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013303 RHS(ins, 1)->u.cval,
13304 reg(state, RHS(ins, 0), REGCM_GPR32));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013305 }
13306}
13307
13308static void print_op_cmp(struct compile_state *state,
13309 struct triple *ins, FILE *fp)
13310{
13311 unsigned mask;
13312 int dreg;
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");
13317 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013318 if (is_const(RHS(ins, 1))) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013319 fprintf(fp, "\tcmp $%lu, %s\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013320 RHS(ins, 1)->u.cval,
13321 reg(state, RHS(ins, 0), mask));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013322 }
13323 else {
13324 unsigned lmask, rmask;
13325 int lreg, rreg;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013326 lreg = check_reg(state, RHS(ins, 0), mask);
13327 rreg = check_reg(state, RHS(ins, 1), mask);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013328 lmask = arch_reg_regcm(state, lreg);
13329 rmask = arch_reg_regcm(state, rreg);
13330 mask = lmask & rmask;
13331 fprintf(fp, "\tcmp %s, %s\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013332 reg(state, RHS(ins, 1), mask),
13333 reg(state, RHS(ins, 0), mask));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013334 }
13335}
13336
13337static void print_op_test(struct compile_state *state,
13338 struct triple *ins, FILE *fp)
13339{
13340 unsigned mask;
13341 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13342 fprintf(fp, "\ttest %s, %s\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013343 reg(state, RHS(ins, 0), mask),
13344 reg(state, RHS(ins, 0), mask));
Eric Biedermanb138ac82003-04-22 18:44:01 +000013345}
13346
13347static void print_op_branch(struct compile_state *state,
13348 struct triple *branch, FILE *fp)
13349{
13350 const char *bop = "j";
13351 if (branch->op == OP_JMP) {
Eric Biederman0babc1c2003-05-09 02:39:00 +000013352 if (TRIPLE_RHS(branch->sizes) != 0) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013353 internal_error(state, branch, "jmp with condition?");
13354 }
13355 bop = "jmp";
13356 }
13357 else {
Eric Biederman0babc1c2003-05-09 02:39:00 +000013358 if (TRIPLE_RHS(branch->sizes) != 1) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013359 internal_error(state, branch, "jmpcc without condition?");
13360 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013361 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
13362 if ((RHS(branch, 0)->op != OP_CMP) &&
13363 (RHS(branch, 0)->op != OP_TEST)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013364 internal_error(state, branch, "bad branch test");
13365 }
13366#warning "FIXME I have observed instructions between the test and branch instructions"
Eric Biederman0babc1c2003-05-09 02:39:00 +000013367 if (RHS(branch, 0)->next != branch) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013368 internal_error(state, branch, "branch does not follow test");
13369 }
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;
13381 default:
13382 internal_error(state, branch, "Invalid branch op");
13383 break;
13384 }
13385
13386 }
13387 fprintf(fp, "\t%s L%lu\n",
Eric Biederman0babc1c2003-05-09 02:39:00 +000013388 bop, TARG(branch, 0)->u.cval);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013389}
13390
13391static void print_op_set(struct compile_state *state,
13392 struct triple *set, FILE *fp)
13393{
13394 const char *sop = "set";
Eric Biederman0babc1c2003-05-09 02:39:00 +000013395 if (TRIPLE_RHS(set->sizes) != 1) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013396 internal_error(state, set, "setcc without condition?");
13397 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013398 check_reg(state, RHS(set, 0), REGCM_FLAGS);
13399 if ((RHS(set, 0)->op != OP_CMP) &&
13400 (RHS(set, 0)->op != OP_TEST)) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013401 internal_error(state, set, "bad set test");
13402 }
Eric Biederman0babc1c2003-05-09 02:39:00 +000013403 if (RHS(set, 0)->next != set) {
Eric Biedermanb138ac82003-04-22 18:44:01 +000013404 internal_error(state, set, "set does not follow test");
13405 }
13406 switch(set->op) {
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;
13417 default:
13418 internal_error(state, set, "Invalid set op");
13419 break;
13420 }
13421 fprintf(fp, "\t%s %s\n",
13422 sop, reg(state, set, REGCM_GPR8));
13423}
13424
13425static void print_op_bit_scan(struct compile_state *state,
13426 struct triple *ins, FILE *fp)
13427{
13428 const char *op;
13429 switch(ins->op) {
13430 case OP_BSF: op = "bsf"; break;
13431 case OP_BSR: op = "bsr"; break;
13432 default:
13433 internal_error(state, ins, "unknown bit scan");
13434 op = 0;
13435 break;
13436 }
13437 fprintf(fp,
13438 "\t%s %s, %s\n"
13439 "\tjnz 1f\n"
13440 "\tmovl $-1, %s\n"
13441 "1:\n",
13442 op,
Eric Biederman0babc1c2003-05-09 02:39:00 +000013443 reg(state, RHS(ins, 0), REGCM_GPR32),
Eric Biedermanb138ac82003-04-22 18:44:01 +000013444 reg(state, ins, REGCM_GPR32),
13445 reg(state, ins, REGCM_GPR32));
13446}
13447
13448static void print_const(struct compile_state *state,
13449 struct triple *ins, FILE *fp)
13450{
13451 switch(ins->op) {
13452 case OP_INTCONST:
13453 switch(ins->type->type & TYPE_MASK) {
13454 case TYPE_CHAR:
13455 case TYPE_UCHAR:
13456 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
13457 break;
13458 case TYPE_SHORT:
13459 case TYPE_USHORT:
13460 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
13461 break;
13462 case TYPE_INT:
13463 case TYPE_UINT:
13464 case TYPE_LONG:
13465 case TYPE_ULONG:
13466 fprintf(fp, ".int %lu\n", ins->u.cval);
13467 break;
13468 default:
13469 internal_error(state, ins, "Unknown constant type");
13470 }
13471 break;
13472 case OP_BLOBCONST:
13473 {
13474 unsigned char *blob;
13475 size_t size, i;
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",
13480 blob[i]);
13481 }
13482 break;
13483 }
13484#if 0
13485 case OP_ADDRCONST:
13486 fprintf(fp, ".int $L%lu+%lu",
13487 ins->left->u.cval,
13488 ins->u.cval);
13489 break;
13490#endif
13491 default:
13492 internal_error(state, ins, "Unknown constant type");
13493 break;
13494 }
13495}
13496
13497static void print_sdecl(struct compile_state *state,
13498 struct triple *ins, FILE *fp)
13499{
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);
Eric Biederman0babc1c2003-05-09 02:39:00 +000013503 print_const(state, MISC(ins, 0), fp);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013504 fprintf(fp, ".section \".rom.text\"\n");
13505
13506}
13507
13508static void print_instruction(struct compile_state *state,
13509 struct triple *ins, FILE *fp)
13510{
13511 /* Assumption: after I have exted the register allocator
13512 * everything is in a valid register.
13513 */
13514 switch(ins->op) {
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;
13526 case OP_INTCONST:
13527 case OP_ADDRCONST:
13528 /* Don't generate anything here for constants */
13529 case OP_PHI:
13530 /* Don't generate anything for variable declarations. */
13531 break;
13532 case OP_SDECL:
13533 print_sdecl(state, ins, fp);
13534 break;
13535 case OP_WRITE:
13536 case OP_COPY:
13537 print_op_move(state, ins, fp);
13538 break;
13539 case OP_LOAD:
13540 print_op_load(state, ins, fp);
13541 break;
13542 case OP_STORE:
13543 print_op_store(state, ins, fp);
13544 break;
13545 case OP_SMUL:
13546 print_op_smul(state, ins, fp);
13547 break;
13548 case OP_CMP: print_op_cmp(state, ins, fp); break;
13549 case OP_TEST: print_op_test(state, ins, fp); break;
13550 case OP_JMP:
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);
13557 break;
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);
13564 break;
13565 case OP_INB: case OP_INW: case OP_INL:
13566 print_op_in(state, ins, fp);
13567 break;
13568 case OP_OUTB: case OP_OUTW: case OP_OUTL:
13569 print_op_out(state, ins, fp);
13570 break;
13571 case OP_BSF:
13572 case OP_BSR:
13573 print_op_bit_scan(state, ins, fp);
13574 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013575 case OP_RDMSR:
13576 verify_lhs(state, ins);
13577 fprintf(fp, "\trdmsr\n");
13578 break;
13579 case OP_WRMSR:
13580 fprintf(fp, "\twrmsr\n");
13581 break;
Eric Biedermanb138ac82003-04-22 18:44:01 +000013582 case OP_HLT:
13583 fprintf(fp, "\thlt\n");
13584 break;
13585 case OP_LABEL:
13586 if (!ins->use) {
13587 return;
13588 }
13589 fprintf(fp, "L%lu:\n", ins->u.cval);
13590 break;
Eric Biederman0babc1c2003-05-09 02:39:00 +000013591 /* Ignore OP_PIECE */
13592 case OP_PIECE:
13593 break;
Eric Biedermanb138ac82003-04-22 18:44:01 +000013594 /* Operations I am not yet certain how to handle */
13595 case OP_UMUL:
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:
13602 default:
13603 internal_error(state, ins, "unknown op: %d %s",
13604 ins->op, tops(ins->op));
13605 break;
13606 }
13607}
13608
13609static void print_instructions(struct compile_state *state)
13610{
13611 struct triple *first, *ins;
13612 int print_location;
13613 int last_line;
13614 int last_col;
13615 const char *last_filename;
13616 FILE *fp;
13617 print_location = 1;
13618 last_line = -1;
13619 last_col = -1;
13620 last_filename = 0;
13621 fp = stdout;
13622 fprintf(fp, ".section \".rom.text\"\n");
Eric Biederman0babc1c2003-05-09 02:39:00 +000013623 first = RHS(state->main_function, 0);
Eric Biedermanb138ac82003-04-22 18:44:01 +000013624 ins = first;
13625 do {
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;
13635 }
13636
13637 print_instruction(state, ins, fp);
13638 ins = ins->next;
13639 } while(ins != first);
13640
13641}
13642static void generate_code(struct compile_state *state)
13643{
13644 generate_local_labels(state);
13645 print_instructions(state);
13646
13647}
13648
13649static void print_tokens(struct compile_state *state)
13650{
13651 struct token *tk;
13652 tk = &state->token[0];
13653 do {
13654#if 1
13655 token(state, 0);
13656#else
13657 next_token(state, 0);
13658#endif
13659 loc(stdout, state, 0);
13660 printf("%s <- `%s'\n",
13661 tokens[tk->tok],
13662 tk->ident ? tk->ident->name :
13663 tk->str_len ? tk->val.str : "");
13664
13665 } while(tk->tok != TOK_EOF);
13666}
13667
13668static void compile(char *filename, int debug, int opt)
13669{
13670 int i;
13671 struct compile_state state;
13672 memset(&state, 0, sizeof(state));
13673 state.file = 0;
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;
13677 }
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);
13695#if 0
13696 print_tokens(&state);
13697#endif
13698 decls(&state);
13699 /* Exit the global definition scope */
13700 end_scope(&state);
13701
13702 /* Now that basic compilation has happened
13703 * optimize the intermediate code
13704 */
13705 optimize(&state);
13706 generate_code(&state);
13707 if (state.debug) {
13708 fprintf(stderr, "done\n");
13709 }
13710}
13711
13712static void version(void)
13713{
13714 printf("romcc " VERSION " released " RELEASE_DATE "\n");
13715}
13716
13717static void usage(void)
13718{
13719 version();
13720 printf(
13721 "Usage: romcc <source>.c\n"
13722 "Compile a C source file without using ram\n"
13723 );
13724}
13725
13726static void arg_error(char *fmt, ...)
13727{
13728 va_list args;
13729 va_start(args, fmt);
13730 vfprintf(stderr, fmt, args);
13731 va_end(args);
13732 usage();
13733 exit(1);
13734}
13735
13736int main(int argc, char **argv)
13737{
13738 char *filename;
13739 int last_argc;
13740 int debug;
13741 int optimize;
13742 optimize = 0;
13743 debug = 0;
13744 last_argc = -1;
13745 while((argc > 1) && (argc != last_argc)) {
13746 last_argc = argc;
13747 if (strncmp(argv[1], "--debug=", 8) == 0) {
13748 debug = atoi(argv[1] + 8);
13749 argv++;
13750 argc--;
13751 }
13752 else if ((strcmp(argv[1],"-O") == 0) ||
13753 (strcmp(argv[1], "-O1") == 0)) {
13754 optimize = 1;
13755 argv++;
13756 argc--;
13757 }
13758 else if (strcmp(argv[1],"-O2") == 0) {
13759 optimize = 2;
13760 argv++;
13761 argc--;
13762 }
13763 }
13764 if (argc != 2) {
13765 arg_error("Wrong argument count %d\n", argc);
13766 }
13767 filename = argv[1];
13768 compile(filename, debug, optimize);
13769
13770 return 0;
13771}