5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 /***********************************************************************
29 * Type sizes used at multiple points in the IR codegen
32 size_t type_sizeof[TYPE_COUNT] = {
39 1, /* TYPE_FUNCTION */
47 uint16_t type_store_instr[TYPE_COUNT] = {
48 INSTR_STORE_F, /* should use I when having integer support */
55 INSTR_STORE_ENT, /* should use I */
57 INSTR_STORE_ENT, /* integer type */
59 INSTR_STORE_V, /* variant, should never be accessed */
62 uint16_t type_storep_instr[TYPE_COUNT] = {
63 INSTR_STOREP_F, /* should use I when having integer support */
70 INSTR_STOREP_ENT, /* should use I */
72 INSTR_STOREP_ENT, /* integer type */
74 INSTR_STOREP_V, /* variant, should never be accessed */
77 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
79 /***********************************************************************
83 ir_builder* ir_builder_new(const char *modulename)
87 self = (ir_builder*)mem_a(sizeof(*self));
91 MEM_VECTOR_INIT(self, functions);
92 MEM_VECTOR_INIT(self, globals);
94 if (!ir_builder_set_name(self, modulename)) {
99 /* globals which always exist */
101 /* for now we give it a vector size */
102 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
107 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
108 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
110 void ir_builder_delete(ir_builder* self)
113 mem_d((void*)self->name);
114 for (i = 0; i != self->functions_count; ++i) {
115 ir_function_delete(self->functions[i]);
117 MEM_VECTOR_CLEAR(self, functions);
118 for (i = 0; i != self->globals_count; ++i) {
119 ir_value_delete(self->globals[i]);
121 MEM_VECTOR_CLEAR(self, globals);
125 bool ir_builder_set_name(ir_builder *self, const char *name)
128 mem_d((void*)self->name);
129 self->name = util_strdup(name);
133 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
136 for (i = 0; i < self->functions_count; ++i) {
137 if (!strcmp(name, self->functions[i]->name))
138 return self->functions[i];
143 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
145 ir_function *fn = ir_builder_get_function(self, name);
150 fn = ir_function_new(self, outtype);
151 if (!ir_function_set_name(fn, name) ||
152 !ir_builder_functions_add(self, fn) )
154 ir_function_delete(fn);
158 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
160 ir_function_delete(fn);
164 fn->value->isconst = true;
165 fn->value->outtype = outtype;
166 fn->value->constval.vfunc = fn;
167 fn->value->context = fn->context;
172 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
175 for (i = 0; i < self->globals_count; ++i) {
176 if (!strcmp(self->globals[i]->name, name))
177 return self->globals[i];
182 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
184 ir_value *ve = ir_builder_get_global(self, name);
189 ve = ir_value_var(name, store_global, vtype);
190 if (!ir_builder_globals_add(self, ve)) {
197 /***********************************************************************
201 bool ir_function_naive_phi(ir_function*);
202 void ir_function_enumerate(ir_function*);
203 bool ir_function_calculate_liferanges(ir_function*);
204 bool ir_function_allocate_locals(ir_function*);
206 ir_function* ir_function_new(ir_builder* owner, int outtype)
209 self = (ir_function*)mem_a(sizeof(*self));
215 if (!ir_function_set_name(self, "<@unnamed>")) {
220 self->context.file = "<@no context>";
221 self->context.line = 0;
222 self->outtype = outtype;
225 MEM_VECTOR_INIT(self, params);
226 MEM_VECTOR_INIT(self, blocks);
227 MEM_VECTOR_INIT(self, values);
228 MEM_VECTOR_INIT(self, locals);
233 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
234 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
235 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
236 MEM_VEC_FUNCTIONS(ir_function, int, params)
238 bool ir_function_set_name(ir_function *self, const char *name)
241 mem_d((void*)self->name);
242 self->name = util_strdup(name);
246 void ir_function_delete(ir_function *self)
249 mem_d((void*)self->name);
251 for (i = 0; i != self->blocks_count; ++i)
252 ir_block_delete(self->blocks[i]);
253 MEM_VECTOR_CLEAR(self, blocks);
255 MEM_VECTOR_CLEAR(self, params);
257 for (i = 0; i != self->values_count; ++i)
258 ir_value_delete(self->values[i]);
259 MEM_VECTOR_CLEAR(self, values);
261 for (i = 0; i != self->locals_count; ++i)
262 ir_value_delete(self->locals[i]);
263 MEM_VECTOR_CLEAR(self, locals);
265 /* self->value is deleted by the builder */
270 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
272 return ir_function_values_add(self, v);
275 ir_block* ir_function_create_block(ir_function *self, const char *label)
277 ir_block* bn = ir_block_new(self, label);
278 memcpy(&bn->context, &self->context, sizeof(self->context));
279 if (!ir_function_blocks_add(self, bn)) {
286 bool ir_function_finalize(ir_function *self)
291 if (!ir_function_naive_phi(self))
294 ir_function_enumerate(self);
296 if (!ir_function_calculate_liferanges(self))
299 if (!ir_function_allocate_locals(self))
304 ir_value* ir_function_get_local(ir_function *self, const char *name)
307 for (i = 0; i < self->locals_count; ++i) {
308 if (!strcmp(self->locals[i]->name, name))
309 return self->locals[i];
314 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
316 ir_value *ve = ir_function_get_local(self, name);
322 self->locals_count &&
323 self->locals[self->locals_count-1]->store != store_param) {
324 printf("cannot add parameters after adding locals\n");
328 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
329 if (!ir_function_locals_add(self, ve)) {
336 /***********************************************************************
340 ir_block* ir_block_new(ir_function* owner, const char *name)
343 self = (ir_block*)mem_a(sizeof(*self));
347 memset(self, 0, sizeof(*self));
350 if (!ir_block_set_label(self, name)) {
355 self->context.file = "<@no context>";
356 self->context.line = 0;
358 MEM_VECTOR_INIT(self, instr);
359 MEM_VECTOR_INIT(self, entries);
360 MEM_VECTOR_INIT(self, exits);
363 self->is_return = false;
365 MEM_VECTOR_INIT(self, living);
367 self->generated = false;
371 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
372 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
373 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
374 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
376 void ir_block_delete(ir_block* self)
380 for (i = 0; i != self->instr_count; ++i)
381 ir_instr_delete(self->instr[i]);
382 MEM_VECTOR_CLEAR(self, instr);
383 MEM_VECTOR_CLEAR(self, entries);
384 MEM_VECTOR_CLEAR(self, exits);
385 MEM_VECTOR_CLEAR(self, living);
389 bool ir_block_set_label(ir_block *self, const char *name)
392 mem_d((void*)self->label);
393 self->label = util_strdup(name);
394 return !!self->label;
397 /***********************************************************************
401 ir_instr* ir_instr_new(ir_block* owner, int op)
404 self = (ir_instr*)mem_a(sizeof(*self));
409 self->context.file = "<@no context>";
410 self->context.line = 0;
412 self->_ops[0] = NULL;
413 self->_ops[1] = NULL;
414 self->_ops[2] = NULL;
415 self->bops[0] = NULL;
416 self->bops[1] = NULL;
417 MEM_VECTOR_INIT(self, phi);
418 MEM_VECTOR_INIT(self, params);
423 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
424 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
426 void ir_instr_delete(ir_instr *self)
429 /* The following calls can only delete from
430 * vectors, we still want to delete this instruction
431 * so ignore the return value. Since with the warn_unused_result attribute
432 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
433 * I have to improvise here and use if(foo());
435 for (i = 0; i < self->phi_count; ++i) {
437 if (ir_value_writes_find(self->phi[i].value, self, &idx))
438 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
439 if (ir_value_reads_find(self->phi[i].value, self, &idx))
440 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
442 MEM_VECTOR_CLEAR(self, phi);
443 for (i = 0; i < self->params_count; ++i) {
445 if (ir_value_writes_find(self->params[i], self, &idx))
446 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
447 if (ir_value_reads_find(self->params[i], self, &idx))
448 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
450 MEM_VECTOR_CLEAR(self, params);
451 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
452 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
453 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
457 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
459 if (self->_ops[op]) {
461 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
463 if (!ir_value_writes_remove(self->_ops[op], idx))
466 else if (ir_value_reads_find(self->_ops[op], self, &idx))
468 if (!ir_value_reads_remove(self->_ops[op], idx))
474 if (!ir_value_writes_add(v, self))
477 if (!ir_value_reads_add(v, self))
485 /***********************************************************************
489 ir_value* ir_value_var(const char *name, int storetype, int vtype)
492 self = (ir_value*)mem_a(sizeof(*self));
494 self->fieldtype = TYPE_VOID;
495 self->outtype = TYPE_VOID;
496 self->store = storetype;
497 MEM_VECTOR_INIT(self, reads);
498 MEM_VECTOR_INIT(self, writes);
499 self->isconst = false;
500 self->context.file = "<@no context>";
501 self->context.line = 0;
503 ir_value_set_name(self, name);
505 memset(&self->constval, 0, sizeof(self->constval));
506 memset(&self->code, 0, sizeof(self->code));
508 MEM_VECTOR_INIT(self, life);
511 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
512 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
513 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
515 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
517 ir_value *v = ir_value_var(name, storetype, vtype);
520 if (!ir_function_collect_value(owner, v))
528 void ir_value_delete(ir_value* self)
531 mem_d((void*)self->name);
534 if (self->vtype == TYPE_STRING)
535 mem_d((void*)self->constval.vstring);
537 MEM_VECTOR_CLEAR(self, reads);
538 MEM_VECTOR_CLEAR(self, writes);
539 MEM_VECTOR_CLEAR(self, life);
543 void ir_value_set_name(ir_value *self, const char *name)
546 mem_d((void*)self->name);
547 self->name = util_strdup(name);
550 bool ir_value_set_float(ir_value *self, float f)
552 if (self->vtype != TYPE_FLOAT)
554 self->constval.vfloat = f;
555 self->isconst = true;
559 bool ir_value_set_func(ir_value *self, int f)
561 if (self->vtype != TYPE_FUNCTION)
563 self->constval.vint = f;
564 self->isconst = true;
568 bool ir_value_set_vector(ir_value *self, vector v)
570 if (self->vtype != TYPE_VECTOR)
572 self->constval.vvec = v;
573 self->isconst = true;
577 bool ir_value_set_string(ir_value *self, const char *str)
579 if (self->vtype != TYPE_STRING)
581 self->constval.vstring = util_strdup(str);
582 self->isconst = true;
587 bool ir_value_set_int(ir_value *self, int i)
589 if (self->vtype != TYPE_INTEGER)
591 self->constval.vint = i;
592 self->isconst = true;
597 bool ir_value_lives(ir_value *self, size_t at)
600 for (i = 0; i < self->life_count; ++i)
602 ir_life_entry_t *life = &self->life[i];
603 if (life->start <= at && at <= life->end)
605 if (life->start > at) /* since it's ordered */
611 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
614 if (!ir_value_life_add(self, e)) /* naive... */
616 for (k = self->life_count-1; k > idx; --k)
617 self->life[k] = self->life[k-1];
622 bool ir_value_life_merge(ir_value *self, size_t s)
625 ir_life_entry_t *life = NULL;
626 ir_life_entry_t *before = NULL;
627 ir_life_entry_t new_entry;
629 /* Find the first range >= s */
630 for (i = 0; i < self->life_count; ++i)
633 life = &self->life[i];
637 /* nothing found? append */
638 if (i == self->life_count) {
640 if (life && life->end+1 == s)
642 /* previous life range can be merged in */
646 if (life && life->end >= s)
649 if (!ir_value_life_add(self, e))
650 return false; /* failing */
656 if (before->end + 1 == s &&
657 life->start - 1 == s)
660 before->end = life->end;
661 if (!ir_value_life_remove(self, i))
662 return false; /* failing */
665 if (before->end + 1 == s)
671 /* already contained */
672 if (before->end >= s)
676 if (life->start - 1 == s)
681 /* insert a new entry */
682 new_entry.start = new_entry.end = s;
683 return ir_value_life_insert(self, i, new_entry);
686 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
690 if (!other->life_count)
693 if (!self->life_count) {
694 for (i = 0; i < other->life_count; ++i) {
695 if (!ir_value_life_add(self, other->life[i]))
702 for (i = 0; i < other->life_count; ++i)
704 const ir_life_entry_t *life = &other->life[i];
707 ir_life_entry_t *entry = &self->life[myi];
709 if (life->end+1 < entry->start)
711 /* adding an interval before entry */
712 if (!ir_value_life_insert(self, myi, *life))
718 if (life->start < entry->start &&
719 life->end >= entry->start)
721 /* starts earlier and overlaps */
722 entry->start = life->start;
725 if (life->end > entry->end &&
726 life->start-1 <= entry->end)
728 /* ends later and overlaps */
729 entry->end = life->end;
732 /* see if our change combines it with the next ranges */
733 while (myi+1 < self->life_count &&
734 entry->end+1 >= self->life[1+myi].start)
736 /* overlaps with (myi+1) */
737 if (entry->end < self->life[1+myi].end)
738 entry->end = self->life[1+myi].end;
739 if (!ir_value_life_remove(self, myi+1))
741 entry = &self->life[myi];
744 /* see if we're after the entry */
745 if (life->start > entry->end)
748 /* append if we're at the end */
749 if (myi >= self->life_count) {
750 if (!ir_value_life_add(self, *life))
754 /* otherweise check the next range */
763 bool ir_values_overlap(const ir_value *a, const ir_value *b)
765 /* For any life entry in A see if it overlaps with
766 * any life entry in B.
767 * Note that the life entries are orderes, so we can make a
768 * more efficient algorithm there than naively translating the
772 ir_life_entry_t *la, *lb, *enda, *endb;
774 /* first of all, if either has no life range, they cannot clash */
775 if (!a->life_count || !b->life_count)
780 enda = la + a->life_count;
781 endb = lb + b->life_count;
784 /* check if the entries overlap, for that,
785 * both must start before the other one ends.
787 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
788 if (la->start <= lb->end &&
789 lb->start <= la->end)
791 if (la->start < lb->end &&
798 /* entries are ordered
799 * one entry is earlier than the other
800 * that earlier entry will be moved forward
802 if (la->start < lb->start)
804 /* order: A B, move A forward
805 * check if we hit the end with A
810 else if (lb->start < la->start)
812 /* order: B A, move B forward
813 * check if we hit the end with B
822 /***********************************************************************
826 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
828 if (target->store == store_value) {
829 fprintf(stderr, "cannot store to an SSA value\n");
830 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
833 ir_instr *in = ir_instr_new(self, op);
836 if (!ir_instr_op(in, 0, target, true) ||
837 !ir_instr_op(in, 1, what, false) ||
838 !ir_block_instr_add(self, in) )
846 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
850 if (target->vtype == TYPE_VARIANT)
853 vtype = target->vtype;
856 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
857 op = INSTR_CONV_ITOF;
858 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
859 op = INSTR_CONV_FTOI;
861 op = type_store_instr[vtype];
863 return ir_block_create_store_op(self, op, target, what);
866 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
871 if (target->vtype != TYPE_POINTER)
874 /* storing using pointer - target is a pointer, type must be
875 * inferred from source
879 op = type_storep_instr[vtype];
881 return ir_block_create_store_op(self, op, target, what);
884 bool ir_block_create_return(ir_block *self, ir_value *v)
888 fprintf(stderr, "block already ended (%s)\n", self->label);
892 self->is_return = true;
893 in = ir_instr_new(self, INSTR_RETURN);
897 if (!ir_instr_op(in, 0, v, false) ||
898 !ir_block_instr_add(self, in) )
905 bool ir_block_create_if(ir_block *self, ir_value *v,
906 ir_block *ontrue, ir_block *onfalse)
910 fprintf(stderr, "block already ended (%s)\n", self->label);
914 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
915 in = ir_instr_new(self, VINSTR_COND);
919 if (!ir_instr_op(in, 0, v, false)) {
924 in->bops[0] = ontrue;
925 in->bops[1] = onfalse;
927 if (!ir_block_instr_add(self, in))
930 if (!ir_block_exits_add(self, ontrue) ||
931 !ir_block_exits_add(self, onfalse) ||
932 !ir_block_entries_add(ontrue, self) ||
933 !ir_block_entries_add(onfalse, self) )
940 bool ir_block_create_jump(ir_block *self, ir_block *to)
944 fprintf(stderr, "block already ended (%s)\n", self->label);
948 in = ir_instr_new(self, VINSTR_JUMP);
953 if (!ir_block_instr_add(self, in))
956 if (!ir_block_exits_add(self, to) ||
957 !ir_block_entries_add(to, self) )
964 bool ir_block_create_goto(ir_block *self, ir_block *to)
968 fprintf(stderr, "block already ended (%s)\n", self->label);
972 in = ir_instr_new(self, INSTR_GOTO);
977 if (!ir_block_instr_add(self, in))
980 if (!ir_block_exits_add(self, to) ||
981 !ir_block_entries_add(to, self) )
988 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
992 in = ir_instr_new(self, VINSTR_PHI);
995 out = ir_value_out(self->owner, label, store_value, ot);
1000 if (!ir_instr_op(in, 0, out, true)) {
1001 ir_instr_delete(in);
1002 ir_value_delete(out);
1005 if (!ir_block_instr_add(self, in)) {
1006 ir_instr_delete(in);
1007 ir_value_delete(out);
1013 ir_value* ir_phi_value(ir_instr *self)
1015 return self->_ops[0];
1018 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1022 if (!ir_block_entries_find(self->owner, b, NULL)) {
1023 /* Must not be possible to cause this, otherwise the AST
1024 * is doing something wrong.
1026 fprintf(stderr, "Invalid entry block for PHI\n");
1032 if (!ir_value_reads_add(v, self))
1034 return ir_instr_phi_add(self, pe);
1037 /* call related code */
1038 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1042 in = ir_instr_new(self, INSTR_CALL0);
1045 out = ir_value_out(self->owner, label, store_return, func->outtype);
1047 ir_instr_delete(in);
1050 if (!ir_instr_op(in, 0, out, true) ||
1051 !ir_instr_op(in, 1, func, false) ||
1052 !ir_block_instr_add(self, in))
1054 ir_instr_delete(in);
1055 ir_value_delete(out);
1061 ir_value* ir_call_value(ir_instr *self)
1063 return self->_ops[0];
1066 bool ir_call_param(ir_instr* self, ir_value *v)
1068 if (!ir_instr_params_add(self, v))
1070 if (!ir_value_reads_add(v, self)) {
1071 if (!ir_instr_params_remove(self, self->params_count-1))
1072 GMQCC_SUPPRESS_EMPTY_BODY;
1078 /* binary op related code */
1080 ir_value* ir_block_create_binop(ir_block *self,
1081 const char *label, int opcode,
1082 ir_value *left, ir_value *right)
1104 case INSTR_SUB_S: /* -- offset of string as float */
1109 case INSTR_BITOR_IF:
1110 case INSTR_BITOR_FI:
1111 case INSTR_BITAND_FI:
1112 case INSTR_BITAND_IF:
1127 case INSTR_BITAND_I:
1130 case INSTR_RSHIFT_I:
1131 case INSTR_LSHIFT_I:
1153 /* boolean operations result in floats */
1154 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1156 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1159 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1164 if (ot == TYPE_VOID) {
1165 /* The AST or parser were supposed to check this! */
1169 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1172 ir_value* ir_block_create_unary(ir_block *self,
1173 const char *label, int opcode,
1176 int ot = TYPE_FLOAT;
1188 /* QC doesn't have other unary operations. We expect extensions to fill
1189 * the above list, otherwise we assume out-type = in-type, eg for an
1193 ot = operand->vtype;
1196 if (ot == TYPE_VOID) {
1197 /* The AST or parser were supposed to check this! */
1201 /* let's use the general instruction creator and pass NULL for OPB */
1202 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1205 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1206 int op, ir_value *a, ir_value *b, int outype)
1211 out = ir_value_out(self->owner, label, store_value, outype);
1215 instr = ir_instr_new(self, op);
1217 ir_value_delete(out);
1221 if (!ir_instr_op(instr, 0, out, true) ||
1222 !ir_instr_op(instr, 1, a, false) ||
1223 !ir_instr_op(instr, 2, b, false) )
1228 if (!ir_block_instr_add(self, instr))
1233 ir_instr_delete(instr);
1234 ir_value_delete(out);
1238 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1240 /* Support for various pointer types todo if so desired */
1241 if (ent->vtype != TYPE_ENTITY)
1244 if (field->vtype != TYPE_FIELD)
1247 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1250 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1253 if (ent->vtype != TYPE_ENTITY)
1256 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1257 if (field->vtype != TYPE_FIELD)
1262 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1263 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1264 case TYPE_STRING: op = INSTR_LOAD_S; break;
1265 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1266 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1268 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1269 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1275 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1278 ir_value* ir_block_create_add(ir_block *self,
1280 ir_value *left, ir_value *right)
1283 int l = left->vtype;
1284 int r = right->vtype;
1303 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1305 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1311 return ir_block_create_binop(self, label, op, left, right);
1314 ir_value* ir_block_create_sub(ir_block *self,
1316 ir_value *left, ir_value *right)
1319 int l = left->vtype;
1320 int r = right->vtype;
1340 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1342 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1348 return ir_block_create_binop(self, label, op, left, right);
1351 ir_value* ir_block_create_mul(ir_block *self,
1353 ir_value *left, ir_value *right)
1356 int l = left->vtype;
1357 int r = right->vtype;
1376 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1378 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1381 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1383 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1385 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1387 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1393 return ir_block_create_binop(self, label, op, left, right);
1396 ir_value* ir_block_create_div(ir_block *self,
1398 ir_value *left, ir_value *right)
1401 int l = left->vtype;
1402 int r = right->vtype;
1419 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1421 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1423 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1429 return ir_block_create_binop(self, label, op, left, right);
1432 /* PHI resolving breaks the SSA, and must thus be the last
1433 * step before life-range calculation.
1436 static bool ir_block_naive_phi(ir_block *self);
1437 bool ir_function_naive_phi(ir_function *self)
1441 for (i = 0; i < self->blocks_count; ++i)
1443 if (!ir_block_naive_phi(self->blocks[i]))
1449 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1454 /* create a store */
1455 if (!ir_block_create_store(block, old, what))
1458 /* we now move it up */
1459 instr = block->instr[block->instr_count-1];
1460 for (i = block->instr_count; i > iid; --i)
1461 block->instr[i] = block->instr[i-1];
1462 block->instr[i] = instr;
1467 static bool ir_block_naive_phi(ir_block *self)
1470 /* FIXME: optionally, create_phi can add the phis
1471 * to a list so we don't need to loop through blocks
1472 * - anyway: "don't optimize YET"
1474 for (i = 0; i < self->instr_count; ++i)
1476 ir_instr *instr = self->instr[i];
1477 if (instr->opcode != VINSTR_PHI)
1480 if (!ir_block_instr_remove(self, i))
1482 --i; /* NOTE: i+1 below */
1484 for (p = 0; p < instr->phi_count; ++p)
1486 ir_value *v = instr->phi[p].value;
1487 for (w = 0; w < v->writes_count; ++w) {
1490 if (!v->writes[w]->_ops[0])
1493 /* When the write was to a global, we have to emit a mov */
1494 old = v->writes[w]->_ops[0];
1496 /* The original instruction now writes to the PHI target local */
1497 if (v->writes[w]->_ops[0] == v)
1498 v->writes[w]->_ops[0] = instr->_ops[0];
1500 if (old->store != store_value && old->store != store_local && old->store != store_param)
1502 /* If it originally wrote to a global we need to store the value
1505 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1507 if (i+1 < self->instr_count)
1508 instr = self->instr[i+1];
1511 /* In case I forget and access instr later, it'll be NULL
1512 * when it's a problem, to make sure we crash, rather than accessing
1518 /* If it didn't, we can replace all reads by the phi target now. */
1520 for (r = 0; r < old->reads_count; ++r)
1523 ir_instr *ri = old->reads[r];
1524 for (op = 0; op < ri->phi_count; ++op) {
1525 if (ri->phi[op].value == old)
1526 ri->phi[op].value = v;
1528 for (op = 0; op < 3; ++op) {
1529 if (ri->_ops[op] == old)
1536 ir_instr_delete(instr);
1541 /***********************************************************************
1542 *IR Temp allocation code
1543 * Propagating value life ranges by walking through the function backwards
1544 * until no more changes are made.
1545 * In theory this should happen once more than once for every nested loop
1547 * Though this implementation might run an additional time for if nests.
1556 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1558 /* Enumerate instructions used by value's life-ranges
1560 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1564 for (i = 0; i < self->instr_count; ++i)
1566 self->instr[i]->eid = eid++;
1571 /* Enumerate blocks and instructions.
1572 * The block-enumeration is unordered!
1573 * We do not really use the block enumreation, however
1574 * the instruction enumeration is important for life-ranges.
1576 void ir_function_enumerate(ir_function *self)
1579 size_t instruction_id = 0;
1580 for (i = 0; i < self->blocks_count; ++i)
1582 self->blocks[i]->eid = i;
1583 self->blocks[i]->run_id = 0;
1584 ir_block_enumerate(self->blocks[i], &instruction_id);
1588 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1589 bool ir_function_calculate_liferanges(ir_function *self)
1597 for (i = 0; i != self->blocks_count; ++i)
1599 if (self->blocks[i]->is_return)
1601 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1609 /* Local-value allocator
1610 * After finishing creating the liferange of all values used in a function
1611 * we can allocate their global-positions.
1612 * This is the counterpart to register-allocation in register machines.
1615 MEM_VECTOR_MAKE(ir_value*, locals);
1616 MEM_VECTOR_MAKE(size_t, sizes);
1617 MEM_VECTOR_MAKE(size_t, positions);
1618 } function_allocator;
1619 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1620 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1621 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1623 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1626 size_t vsize = type_sizeof[var->vtype];
1628 slot = ir_value_var("reg", store_global, var->vtype);
1632 if (!ir_value_life_merge_into(slot, var))
1635 if (!function_allocator_locals_add(alloc, slot))
1638 if (!function_allocator_sizes_add(alloc, vsize))
1644 ir_value_delete(slot);
1648 bool ir_function_allocate_locals(ir_function *self)
1657 function_allocator alloc;
1659 if (!self->locals_count)
1662 MEM_VECTOR_INIT(&alloc, locals);
1663 MEM_VECTOR_INIT(&alloc, sizes);
1664 MEM_VECTOR_INIT(&alloc, positions);
1666 for (i = 0; i < self->locals_count; ++i)
1668 if (!function_allocator_alloc(&alloc, self->locals[i]))
1672 /* Allocate a slot for any value that still exists */
1673 for (i = 0; i < self->values_count; ++i)
1675 v = self->values[i];
1680 for (a = 0; a < alloc.locals_count; ++a)
1682 slot = alloc.locals[a];
1684 if (ir_values_overlap(v, slot))
1687 if (!ir_value_life_merge_into(slot, v))
1690 /* adjust size for this slot */
1691 if (alloc.sizes[a] < type_sizeof[v->vtype])
1692 alloc.sizes[a] = type_sizeof[v->vtype];
1694 self->values[i]->code.local = a;
1697 if (a >= alloc.locals_count) {
1698 self->values[i]->code.local = alloc.locals_count;
1699 if (!function_allocator_alloc(&alloc, v))
1704 /* Adjust slot positions based on sizes */
1705 if (!function_allocator_positions_add(&alloc, 0))
1708 if (alloc.sizes_count)
1709 pos = alloc.positions[0] + alloc.sizes[0];
1712 for (i = 1; i < alloc.sizes_count; ++i)
1714 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1715 if (!function_allocator_positions_add(&alloc, pos))
1719 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1721 /* Take over the actual slot positions */
1722 for (i = 0; i < self->values_count; ++i)
1723 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1730 for (i = 0; i < alloc.locals_count; ++i)
1731 ir_value_delete(alloc.locals[i]);
1732 MEM_VECTOR_CLEAR(&alloc, locals);
1733 MEM_VECTOR_CLEAR(&alloc, sizes);
1734 MEM_VECTOR_CLEAR(&alloc, positions);
1738 /* Get information about which operand
1739 * is read from, or written to.
1741 static void ir_op_read_write(int op, size_t *read, size_t *write)
1768 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1771 bool changed = false;
1773 for (i = 0; i != self->living_count; ++i)
1775 tempbool = ir_value_life_merge(self->living[i], eid);
1778 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1780 changed = changed || tempbool;
1785 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1788 /* values which have been read in a previous iteration are now
1789 * in the "living" array even if the previous block doesn't use them.
1790 * So we have to remove whatever does not exist in the previous block.
1791 * They will be re-added on-read, but the liferange merge won't cause
1794 for (i = 0; i < self->living_count; ++i)
1796 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1797 if (!ir_block_living_remove(self, i))
1803 /* Whatever the previous block still has in its living set
1804 * must now be added to ours as well.
1806 for (i = 0; i < prev->living_count; ++i)
1808 if (ir_block_living_find(self, prev->living[i], NULL))
1810 if (!ir_block_living_add(self, prev->living[i]))
1813 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1819 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1825 /* bitmasks which operands are read from or written to */
1827 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1829 new_reads_t new_reads;
1831 char dbg_ind[16] = { '#', '0' };
1834 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1835 MEM_VECTOR_INIT(&new_reads, v);
1840 if (!ir_block_life_prop_previous(self, prev, changed))
1844 i = self->instr_count;
1847 instr = self->instr[i];
1849 /* PHI operands are always read operands */
1850 for (p = 0; p < instr->phi_count; ++p)
1852 value = instr->phi[p].value;
1853 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1854 if (!ir_block_living_find(self, value, NULL) &&
1855 !ir_block_living_add(self, value))
1860 if (!new_reads_t_v_find(&new_reads, value, NULL))
1862 if (!new_reads_t_v_add(&new_reads, value))
1868 /* See which operands are read and write operands */
1869 ir_op_read_write(instr->opcode, &read, &write);
1871 /* Go through the 3 main operands */
1872 for (o = 0; o < 3; ++o)
1874 if (!instr->_ops[o]) /* no such operand */
1877 value = instr->_ops[o];
1879 /* We only care about locals */
1880 /* we also calculate parameter liferanges so that locals
1881 * can take up parameter slots */
1882 if (value->store != store_value &&
1883 value->store != store_local &&
1884 value->store != store_param)
1890 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1891 if (!ir_block_living_find(self, value, NULL) &&
1892 !ir_block_living_add(self, value))
1897 /* fprintf(stderr, "read: %s\n", value->_name); */
1898 if (!new_reads_t_v_find(&new_reads, value, NULL))
1900 if (!new_reads_t_v_add(&new_reads, value))
1906 /* write operands */
1907 /* When we write to a local, we consider it "dead" for the
1908 * remaining upper part of the function, since in SSA a value
1909 * can only be written once (== created)
1914 bool in_living = ir_block_living_find(self, value, &idx);
1915 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1917 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1918 if (!in_living && !in_reads)
1923 /* If the value isn't alive it hasn't been read before... */
1924 /* TODO: See if the warning can be emitted during parsing or AST processing
1925 * otherwise have warning printed here.
1926 * IF printing a warning here: include filecontext_t,
1927 * and make sure it's only printed once
1928 * since this function is run multiple times.
1930 /* For now: debug info: */
1931 fprintf(stderr, "Value only written %s\n", value->name);
1932 tempbool = ir_value_life_merge(value, instr->eid);
1933 *changed = *changed || tempbool;
1935 ir_instr_dump(instr, dbg_ind, printf);
1939 /* since 'living' won't contain it
1940 * anymore, merge the value, since
1943 tempbool = ir_value_life_merge(value, instr->eid);
1946 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1948 *changed = *changed || tempbool;
1950 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1951 if (!ir_block_living_remove(self, idx))
1956 if (!new_reads_t_v_remove(&new_reads, readidx))
1964 tempbool = ir_block_living_add_instr(self, instr->eid);
1965 /*fprintf(stderr, "living added values\n");*/
1966 *changed = *changed || tempbool;
1968 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1970 for (rd = 0; rd < new_reads.v_count; ++rd)
1972 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1973 if (!ir_block_living_add(self, new_reads.v[rd]))
1976 if (!i && !self->entries_count) {
1978 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1981 MEM_VECTOR_CLEAR(&new_reads, v);
1985 if (self->run_id == self->owner->run_id)
1988 self->run_id = self->owner->run_id;
1990 for (i = 0; i < self->entries_count; ++i)
1992 ir_block *entry = self->entries[i];
1993 ir_block_life_propagate(entry, self, changed);
1998 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1999 MEM_VECTOR_CLEAR(&new_reads, v);
2004 /***********************************************************************
2007 * Since the IR has the convention of putting 'write' operands
2008 * at the beginning, we have to rotate the operands of instructions
2009 * properly in order to generate valid QCVM code.
2011 * Having destinations at a fixed position is more convenient. In QC
2012 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2013 * read from from OPA, and store to OPB rather than OPC. Which is
2014 * partially the reason why the implementation of these instructions
2015 * in darkplaces has been delayed for so long.
2017 * Breaking conventions is annoying...
2019 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2021 static bool gen_global_field(ir_value *global)
2023 if (global->isconst)
2025 ir_value *fld = global->constval.vpointer;
2027 printf("Invalid field constant with no field: %s\n", global->name);
2031 /* Now, in this case, a relocation would be impossible to code
2032 * since it looks like this:
2033 * .vector v = origin; <- parse error, wtf is 'origin'?
2036 * But we will need a general relocation support later anyway
2037 * for functions... might as well support that here.
2039 if (!fld->code.globaladdr) {
2040 printf("FIXME: Relocation support\n");
2044 /* copy the field's value */
2045 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2049 prog_section_field fld;
2051 fld.name = global->code.name;
2052 fld.offset = code_fields_elements;
2053 fld.type = global->fieldtype;
2055 if (fld.type == TYPE_VOID) {
2056 printf("Field is missing a type: %s\n", global->name);
2060 if (code_fields_add(fld) < 0)
2063 global->code.globaladdr = code_globals_add(fld.offset);
2065 if (global->code.globaladdr < 0)
2070 static bool gen_global_pointer(ir_value *global)
2072 if (global->isconst)
2074 ir_value *target = global->constval.vpointer;
2076 printf("Invalid pointer constant: %s\n", global->name);
2077 /* NULL pointers are pointing to the NULL constant, which also
2078 * sits at address 0, but still has an ir_value for itself.
2083 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2084 * void() foo; <- proto
2085 * void() *fooptr = &foo;
2086 * void() foo = { code }
2088 if (!target->code.globaladdr) {
2089 /* FIXME: Check for the constant nullptr ir_value!
2090 * because then code.globaladdr being 0 is valid.
2092 printf("FIXME: Relocation support\n");
2096 global->code.globaladdr = code_globals_add(target->code.globaladdr);
2100 global->code.globaladdr = code_globals_add(0);
2102 if (global->code.globaladdr < 0)
2107 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2109 prog_section_statement stmt;
2118 block->generated = true;
2119 block->code_start = code_statements_elements;
2120 for (i = 0; i < block->instr_count; ++i)
2122 instr = block->instr[i];
2124 if (instr->opcode == VINSTR_PHI) {
2125 printf("cannot generate virtual instruction (phi)\n");
2129 if (instr->opcode == VINSTR_JUMP) {
2130 target = instr->bops[0];
2131 /* for uncoditional jumps, if the target hasn't been generated
2132 * yet, we generate them right here.
2134 if (!target->generated) {
2139 /* otherwise we generate a jump instruction */
2140 stmt.opcode = INSTR_GOTO;
2141 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2144 if (code_statements_add(stmt) < 0)
2147 /* no further instructions can be in this block */
2151 if (instr->opcode == VINSTR_COND) {
2152 ontrue = instr->bops[0];
2153 onfalse = instr->bops[1];
2154 /* TODO: have the AST signal which block should
2155 * come first: eg. optimize IFs without ELSE...
2158 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2162 if (ontrue->generated) {
2163 stmt.opcode = INSTR_IF;
2164 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2165 if (code_statements_add(stmt) < 0)
2168 if (onfalse->generated) {
2169 stmt.opcode = INSTR_IFNOT;
2170 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2171 if (code_statements_add(stmt) < 0)
2174 if (!ontrue->generated) {
2175 if (onfalse->generated) {
2180 if (!onfalse->generated) {
2181 if (ontrue->generated) {
2186 /* neither ontrue nor onfalse exist */
2187 stmt.opcode = INSTR_IFNOT;
2188 stidx = code_statements_elements;
2189 if (code_statements_add(stmt) < 0)
2191 /* on false we jump, so add ontrue-path */
2192 if (!gen_blocks_recursive(func, ontrue))
2194 /* fixup the jump address */
2195 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2196 /* generate onfalse path */
2197 if (onfalse->generated) {
2198 /* fixup the jump address */
2199 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2200 /* may have been generated in the previous recursive call */
2201 stmt.opcode = INSTR_GOTO;
2202 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2205 return (code_statements_add(stmt) >= 0);
2207 /* if not, generate now */
2212 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2213 /* Trivial call translation:
2214 * copy all params to OFS_PARM*
2215 * if the output's storetype is not store_return,
2216 * add append a STORE instruction!
2218 * NOTES on how to do it better without much trouble:
2219 * -) The liferanges!
2220 * Simply check the liferange of all parameters for
2221 * other CALLs. For each param with no CALL in its
2222 * liferange, we can store it in an OFS_PARM at
2223 * generation already. This would even include later
2224 * reuse.... probably... :)
2229 for (p = 0; p < instr->params_count; ++p)
2231 ir_value *param = instr->params[p];
2233 stmt.opcode = INSTR_STORE_F;
2236 stmt.opcode = type_store_instr[param->vtype];
2237 stmt.o1.u1 = param->code.globaladdr;
2238 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2239 if (code_statements_add(stmt) < 0)
2242 stmt.opcode = INSTR_CALL0 + instr->params_count;
2243 if (stmt.opcode > INSTR_CALL8)
2244 stmt.opcode = INSTR_CALL8;
2245 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2248 if (code_statements_add(stmt) < 0)
2251 retvalue = instr->_ops[0];
2252 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2254 /* not to be kept in OFS_RETURN */
2255 stmt.opcode = type_store_instr[retvalue->vtype];
2256 stmt.o1.u1 = OFS_RETURN;
2257 stmt.o2.u1 = retvalue->code.globaladdr;
2259 if (code_statements_add(stmt) < 0)
2265 if (instr->opcode == INSTR_STATE) {
2266 printf("TODO: state instruction\n");
2270 stmt.opcode = instr->opcode;
2275 /* This is the general order of operands */
2277 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2280 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2283 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2285 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2287 stmt.o1.u1 = stmt.o3.u1;
2290 else if (stmt.opcode >= INSTR_STORE_F &&
2291 stmt.opcode <= INSTR_STORE_FNC)
2293 /* 2-operand instructions with A -> B */
2294 stmt.o2.u1 = stmt.o3.u1;
2298 if (code_statements_add(stmt) < 0)
2304 static bool gen_function_code(ir_function *self)
2307 prog_section_statement stmt;
2309 /* Starting from entry point, we generate blocks "as they come"
2310 * for now. Dead blocks will not be translated obviously.
2312 if (!self->blocks_count) {
2313 printf("Function '%s' declared without body.\n", self->name);
2317 block = self->blocks[0];
2318 if (block->generated)
2321 if (!gen_blocks_recursive(self, block)) {
2322 printf("failed to generate blocks for '%s'\n", self->name);
2326 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2327 stmt.opcode = AINSTR_END;
2331 if (code_statements_add(stmt) < 0)
2336 static bool gen_global_function(ir_builder *ir, ir_value *global)
2338 prog_section_function fun;
2342 size_t local_var_end;
2344 if (!global->isconst || (!global->constval.vfunc))
2346 printf("Invalid state of function-global: not constant: %s\n", global->name);
2350 irfun = global->constval.vfunc;
2352 fun.name = global->code.name;
2353 fun.file = code_cachedstring(global->context.file);
2354 fun.profile = 0; /* always 0 */
2355 fun.nargs = irfun->params_count;
2357 for (i = 0;i < 8; ++i) {
2361 fun.argsize[i] = type_sizeof[irfun->params[i]];
2364 fun.firstlocal = code_globals_elements;
2365 fun.locals = irfun->allocated_locals + irfun->locals_count;
2368 for (i = 0; i < irfun->locals_count; ++i) {
2369 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2370 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2374 if (irfun->locals_count) {
2375 ir_value *last = irfun->locals[irfun->locals_count-1];
2376 local_var_end = last->code.globaladdr;
2377 local_var_end += type_sizeof[last->vtype];
2379 for (i = 0; i < irfun->values_count; ++i)
2381 /* generate code.globaladdr for ssa values */
2382 ir_value *v = irfun->values[i];
2383 v->code.globaladdr = local_var_end + v->code.local;
2385 for (i = 0; i < irfun->locals_count; ++i) {
2386 /* fill the locals with zeros */
2387 code_globals_add(0);
2391 fun.entry = irfun->builtin;
2393 fun.entry = code_statements_elements;
2394 if (!gen_function_code(irfun)) {
2395 printf("Failed to generate code for function %s\n", irfun->name);
2400 return (code_functions_add(fun) >= 0);
2403 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2407 prog_section_def def;
2409 def.type = global->vtype;
2410 def.offset = code_globals_elements;
2411 def.name = global->code.name = code_genstring(global->name);
2413 switch (global->vtype)
2416 if (code_defs_add(def) < 0)
2418 return gen_global_pointer(global);
2420 if (code_defs_add(def) < 0)
2422 return gen_global_field(global);
2427 if (code_defs_add(def) < 0)
2430 if (global->isconst) {
2431 iptr = (int32_t*)&global->constval.vfloat;
2432 global->code.globaladdr = code_globals_add(*iptr);
2434 global->code.globaladdr = code_globals_add(0);
2436 return global->code.globaladdr >= 0;
2440 if (code_defs_add(def) < 0)
2442 if (global->isconst)
2443 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2445 global->code.globaladdr = code_globals_add(0);
2446 return global->code.globaladdr >= 0;
2451 if (code_defs_add(def) < 0)
2454 if (global->isconst) {
2455 iptr = (int32_t*)&global->constval.vvec;
2456 global->code.globaladdr = code_globals_add(iptr[0]);
2457 if (global->code.globaladdr < 0)
2459 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2461 if (code_globals_add(iptr[d]) < 0)
2465 global->code.globaladdr = code_globals_add(0);
2466 if (global->code.globaladdr < 0)
2468 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2470 if (code_globals_add(0) < 0)
2474 return global->code.globaladdr >= 0;
2477 if (code_defs_add(def) < 0)
2479 global->code.globaladdr = code_globals_elements;
2480 code_globals_add(code_functions_elements);
2481 return gen_global_function(self, global);
2483 /* assume biggest type */
2484 global->code.globaladdr = code_globals_add(0);
2485 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2486 code_globals_add(0);
2489 /* refuse to create 'void' type or any other fancy business. */
2490 printf("Invalid type for global variable %s\n", global->name);
2495 bool ir_builder_generate(ir_builder *self, const char *filename)
2501 for (i = 0; i < self->globals_count; ++i)
2503 if (!ir_builder_gen_global(self, self->globals[i])) {
2508 printf("writing '%s'...\n", filename);
2509 return code_write(filename);
2512 /***********************************************************************
2513 *IR DEBUG Dump functions...
2516 #define IND_BUFSZ 1024
2518 const char *qc_opname(int op)
2520 if (op < 0) return "<INVALID>";
2521 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2522 return asm_instr[op].m;
2524 case VINSTR_PHI: return "PHI";
2525 case VINSTR_JUMP: return "JUMP";
2526 case VINSTR_COND: return "COND";
2527 default: return "<UNK>";
2531 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2534 char indent[IND_BUFSZ];
2538 oprintf("module %s\n", b->name);
2539 for (i = 0; i < b->globals_count; ++i)
2542 if (b->globals[i]->isconst)
2543 oprintf("%s = ", b->globals[i]->name);
2544 ir_value_dump(b->globals[i], oprintf);
2547 for (i = 0; i < b->functions_count; ++i)
2548 ir_function_dump(b->functions[i], indent, oprintf);
2549 oprintf("endmodule %s\n", b->name);
2552 void ir_function_dump(ir_function *f, char *ind,
2553 int (*oprintf)(const char*, ...))
2556 if (f->builtin != 0) {
2557 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2560 oprintf("%sfunction %s\n", ind, f->name);
2561 strncat(ind, "\t", IND_BUFSZ);
2562 if (f->locals_count)
2564 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2565 for (i = 0; i < f->locals_count; ++i) {
2566 oprintf("%s\t", ind);
2567 ir_value_dump(f->locals[i], oprintf);
2571 if (f->blocks_count)
2573 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2574 for (i = 0; i < f->blocks_count; ++i) {
2575 if (f->blocks[i]->run_id != f->run_id) {
2576 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2578 ir_block_dump(f->blocks[i], ind, oprintf);
2582 ind[strlen(ind)-1] = 0;
2583 oprintf("%sendfunction %s\n", ind, f->name);
2586 void ir_block_dump(ir_block* b, char *ind,
2587 int (*oprintf)(const char*, ...))
2590 oprintf("%s:%s\n", ind, b->label);
2591 strncat(ind, "\t", IND_BUFSZ);
2593 for (i = 0; i < b->instr_count; ++i)
2594 ir_instr_dump(b->instr[i], ind, oprintf);
2595 ind[strlen(ind)-1] = 0;
2598 void dump_phi(ir_instr *in, char *ind,
2599 int (*oprintf)(const char*, ...))
2602 oprintf("%s <- phi ", in->_ops[0]->name);
2603 for (i = 0; i < in->phi_count; ++i)
2605 oprintf("([%s] : %s) ", in->phi[i].from->label,
2606 in->phi[i].value->name);
2611 void ir_instr_dump(ir_instr *in, char *ind,
2612 int (*oprintf)(const char*, ...))
2615 const char *comma = NULL;
2617 oprintf("%s (%i) ", ind, (int)in->eid);
2619 if (in->opcode == VINSTR_PHI) {
2620 dump_phi(in, ind, oprintf);
2624 strncat(ind, "\t", IND_BUFSZ);
2626 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2627 ir_value_dump(in->_ops[0], oprintf);
2628 if (in->_ops[1] || in->_ops[2])
2631 oprintf("%s\t", qc_opname(in->opcode));
2632 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2633 ir_value_dump(in->_ops[0], oprintf);
2638 for (i = 1; i != 3; ++i) {
2642 ir_value_dump(in->_ops[i], oprintf);
2650 oprintf("[%s]", in->bops[0]->label);
2654 oprintf("%s[%s]", comma, in->bops[1]->label);
2656 ind[strlen(ind)-1] = 0;
2659 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2667 oprintf("%g", v->constval.vfloat);
2670 oprintf("'%g %g %g'",
2673 v->constval.vvec.z);
2676 oprintf("(entity)");
2679 oprintf("\"%s\"", v->constval.vstring);
2683 oprintf("%i", v->constval.vint);
2688 v->constval.vpointer->name);
2692 oprintf("%s", v->name);
2696 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2699 oprintf("Life of %s:\n", self->name);
2700 for (i = 0; i < self->life_count; ++i)
2702 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);