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 const char *type_name[TYPE_COUNT] = {
49 size_t type_sizeof[TYPE_COUNT] = {
56 1, /* TYPE_FUNCTION */
61 4, /* TYPE_QUATERNION */
63 16, /* TYPE_VARIANT */
66 uint16_t type_store_instr[TYPE_COUNT] = {
67 INSTR_STORE_F, /* should use I when having integer support */
74 INSTR_STORE_ENT, /* should use I */
76 INSTR_STORE_I, /* integer type */
81 INSTR_STORE_M, /* variant, should never be accessed */
84 uint16_t type_storep_instr[TYPE_COUNT] = {
85 INSTR_STOREP_F, /* should use I when having integer support */
92 INSTR_STOREP_ENT, /* should use I */
94 INSTR_STOREP_ENT, /* integer type */
99 INSTR_STOREP_M, /* variant, should never be accessed */
102 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
104 /***********************************************************************
108 ir_builder* ir_builder_new(const char *modulename)
112 self = (ir_builder*)mem_a(sizeof(*self));
116 MEM_VECTOR_INIT(self, functions);
117 MEM_VECTOR_INIT(self, globals);
119 if (!ir_builder_set_name(self, modulename)) {
124 /* globals which always exist */
126 /* for now we give it a vector size */
127 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
132 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
133 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
135 void ir_builder_delete(ir_builder* self)
138 mem_d((void*)self->name);
139 for (i = 0; i != self->functions_count; ++i) {
140 ir_function_delete(self->functions[i]);
142 MEM_VECTOR_CLEAR(self, functions);
143 for (i = 0; i != self->globals_count; ++i) {
144 ir_value_delete(self->globals[i]);
146 MEM_VECTOR_CLEAR(self, globals);
150 bool ir_builder_set_name(ir_builder *self, const char *name)
153 mem_d((void*)self->name);
154 self->name = util_strdup(name);
158 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
161 for (i = 0; i < self->functions_count; ++i) {
162 if (!strcmp(name, self->functions[i]->name))
163 return self->functions[i];
168 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
170 ir_function *fn = ir_builder_get_function(self, name);
175 fn = ir_function_new(self, outtype);
176 if (!ir_function_set_name(fn, name) ||
177 !ir_builder_functions_add(self, fn) )
179 ir_function_delete(fn);
183 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
185 ir_function_delete(fn);
189 fn->value->isconst = true;
190 fn->value->outtype = outtype;
191 fn->value->constval.vfunc = fn;
192 fn->value->context = fn->context;
197 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
200 for (i = 0; i < self->globals_count; ++i) {
201 if (!strcmp(self->globals[i]->name, name))
202 return self->globals[i];
207 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
211 if (name && name[0] != '#')
213 ve = ir_builder_get_global(self, name);
219 ve = ir_value_var(name, store_global, vtype);
220 if (!ir_builder_globals_add(self, ve)) {
227 /***********************************************************************
231 bool ir_function_naive_phi(ir_function*);
232 void ir_function_enumerate(ir_function*);
233 bool ir_function_calculate_liferanges(ir_function*);
234 bool ir_function_allocate_locals(ir_function*);
236 ir_function* ir_function_new(ir_builder* owner, int outtype)
239 self = (ir_function*)mem_a(sizeof(*self));
245 if (!ir_function_set_name(self, "<@unnamed>")) {
250 self->context.file = "<@no context>";
251 self->context.line = 0;
252 self->outtype = outtype;
255 MEM_VECTOR_INIT(self, params);
256 MEM_VECTOR_INIT(self, blocks);
257 MEM_VECTOR_INIT(self, values);
258 MEM_VECTOR_INIT(self, locals);
263 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
264 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
265 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
266 MEM_VEC_FUNCTIONS(ir_function, int, params)
268 bool ir_function_set_name(ir_function *self, const char *name)
271 mem_d((void*)self->name);
272 self->name = util_strdup(name);
276 void ir_function_delete(ir_function *self)
279 mem_d((void*)self->name);
281 for (i = 0; i != self->blocks_count; ++i)
282 ir_block_delete(self->blocks[i]);
283 MEM_VECTOR_CLEAR(self, blocks);
285 MEM_VECTOR_CLEAR(self, params);
287 for (i = 0; i != self->values_count; ++i)
288 ir_value_delete(self->values[i]);
289 MEM_VECTOR_CLEAR(self, values);
291 for (i = 0; i != self->locals_count; ++i)
292 ir_value_delete(self->locals[i]);
293 MEM_VECTOR_CLEAR(self, locals);
295 /* self->value is deleted by the builder */
300 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
302 return ir_function_values_add(self, v);
305 ir_block* ir_function_create_block(ir_function *self, const char *label)
307 ir_block* bn = ir_block_new(self, label);
308 memcpy(&bn->context, &self->context, sizeof(self->context));
309 if (!ir_function_blocks_add(self, bn)) {
316 bool ir_function_finalize(ir_function *self)
321 if (!ir_function_naive_phi(self))
324 ir_function_enumerate(self);
326 if (!ir_function_calculate_liferanges(self))
329 if (!ir_function_allocate_locals(self))
334 ir_value* ir_function_get_local(ir_function *self, const char *name)
337 for (i = 0; i < self->locals_count; ++i) {
338 if (!strcmp(self->locals[i]->name, name))
339 return self->locals[i];
344 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
346 ir_value *ve = ir_function_get_local(self, name);
351 ve = ir_value_var(name, store_local, vtype);
352 if (!ir_function_locals_add(self, ve)) {
359 /***********************************************************************
363 ir_block* ir_block_new(ir_function* owner, const char *name)
366 self = (ir_block*)mem_a(sizeof(*self));
370 memset(self, 0, sizeof(*self));
373 if (!ir_block_set_label(self, name)) {
378 self->context.file = "<@no context>";
379 self->context.line = 0;
381 MEM_VECTOR_INIT(self, instr);
382 MEM_VECTOR_INIT(self, entries);
383 MEM_VECTOR_INIT(self, exits);
386 self->is_return = false;
388 MEM_VECTOR_INIT(self, living);
390 self->generated = false;
394 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
395 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
396 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
397 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
399 void ir_block_delete(ir_block* self)
403 for (i = 0; i != self->instr_count; ++i)
404 ir_instr_delete(self->instr[i]);
405 MEM_VECTOR_CLEAR(self, instr);
406 MEM_VECTOR_CLEAR(self, entries);
407 MEM_VECTOR_CLEAR(self, exits);
408 MEM_VECTOR_CLEAR(self, living);
412 bool ir_block_set_label(ir_block *self, const char *name)
415 mem_d((void*)self->label);
416 self->label = util_strdup(name);
417 return !!self->label;
420 /***********************************************************************
424 ir_instr* ir_instr_new(ir_block* owner, int op)
427 self = (ir_instr*)mem_a(sizeof(*self));
432 self->context.file = "<@no context>";
433 self->context.line = 0;
435 self->_ops[0] = NULL;
436 self->_ops[1] = NULL;
437 self->_ops[2] = NULL;
438 self->bops[0] = NULL;
439 self->bops[1] = NULL;
440 MEM_VECTOR_INIT(self, phi);
441 MEM_VECTOR_INIT(self, params);
446 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
447 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
449 void ir_instr_delete(ir_instr *self)
452 /* The following calls can only delete from
453 * vectors, we still want to delete this instruction
454 * so ignore the return value. Since with the warn_unused_result attribute
455 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
456 * I have to improvise here and use if(foo());
458 for (i = 0; i < self->phi_count; ++i) {
460 if (ir_value_writes_find(self->phi[i].value, self, &idx))
461 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
462 if (ir_value_reads_find(self->phi[i].value, self, &idx))
463 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
465 MEM_VECTOR_CLEAR(self, phi);
466 for (i = 0; i < self->params_count; ++i) {
468 if (ir_value_writes_find(self->params[i], self, &idx))
469 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
470 if (ir_value_reads_find(self->params[i], self, &idx))
471 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
473 MEM_VECTOR_CLEAR(self, params);
474 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
475 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
476 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
480 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
482 if (self->_ops[op]) {
484 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
486 if (!ir_value_writes_remove(self->_ops[op], idx))
489 else if (ir_value_reads_find(self->_ops[op], self, &idx))
491 if (!ir_value_reads_remove(self->_ops[op], idx))
497 if (!ir_value_writes_add(v, self))
500 if (!ir_value_reads_add(v, self))
508 /***********************************************************************
512 ir_value* ir_value_var(const char *name, int storetype, int vtype)
515 self = (ir_value*)mem_a(sizeof(*self));
517 self->fieldtype = TYPE_VOID;
518 self->outtype = TYPE_VOID;
519 self->store = storetype;
520 MEM_VECTOR_INIT(self, reads);
521 MEM_VECTOR_INIT(self, writes);
522 self->isconst = false;
523 self->context.file = "<@no context>";
524 self->context.line = 0;
526 ir_value_set_name(self, name);
528 memset(&self->constval, 0, sizeof(self->constval));
529 memset(&self->code, 0, sizeof(self->code));
531 MEM_VECTOR_INIT(self, life);
534 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
535 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
536 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
538 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
540 ir_value *v = ir_value_var(name, storetype, vtype);
543 if (!ir_function_collect_value(owner, v))
551 void ir_value_delete(ir_value* self)
554 mem_d((void*)self->name);
557 if (self->vtype == TYPE_STRING)
558 mem_d((void*)self->constval.vstring);
560 MEM_VECTOR_CLEAR(self, reads);
561 MEM_VECTOR_CLEAR(self, writes);
562 MEM_VECTOR_CLEAR(self, life);
566 void ir_value_set_name(ir_value *self, const char *name)
569 mem_d((void*)self->name);
570 self->name = util_strdup(name);
573 bool ir_value_set_float(ir_value *self, float f)
575 if (self->vtype != TYPE_FLOAT)
577 self->constval.vfloat = f;
578 self->isconst = true;
582 bool ir_value_set_func(ir_value *self, int f)
584 if (self->vtype != TYPE_FUNCTION)
586 self->constval.vint = f;
587 self->isconst = true;
591 bool ir_value_set_vector(ir_value *self, vector v)
593 if (self->vtype != TYPE_VECTOR)
595 self->constval.vvec = v;
596 self->isconst = true;
600 bool ir_value_set_quaternion(ir_value *self, quaternion v)
602 if (self->vtype != TYPE_QUATERNION)
604 memcpy(&self->constval.vquat, v, sizeof(self->constval.vquat));
605 self->isconst = true;
609 bool ir_value_set_matrix(ir_value *self, matrix v)
611 if (self->vtype != TYPE_MATRIX)
613 memcpy(&self->constval.vmat, v, sizeof(self->constval.vmat));
614 self->isconst = true;
618 bool ir_value_set_string(ir_value *self, const char *str)
620 if (self->vtype != TYPE_STRING)
622 self->constval.vstring = util_strdup(str);
623 self->isconst = true;
628 bool ir_value_set_int(ir_value *self, int i)
630 if (self->vtype != TYPE_INTEGER)
632 self->constval.vint = i;
633 self->isconst = true;
638 bool ir_value_lives(ir_value *self, size_t at)
641 for (i = 0; i < self->life_count; ++i)
643 ir_life_entry_t *life = &self->life[i];
644 if (life->start <= at && at <= life->end)
646 if (life->start > at) /* since it's ordered */
652 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
655 if (!ir_value_life_add(self, e)) /* naive... */
657 for (k = self->life_count-1; k > idx; --k)
658 self->life[k] = self->life[k-1];
663 bool ir_value_life_merge(ir_value *self, size_t s)
666 ir_life_entry_t *life = NULL;
667 ir_life_entry_t *before = NULL;
668 ir_life_entry_t new_entry;
670 /* Find the first range >= s */
671 for (i = 0; i < self->life_count; ++i)
674 life = &self->life[i];
678 /* nothing found? append */
679 if (i == self->life_count) {
681 if (life && life->end+1 == s)
683 /* previous life range can be merged in */
687 if (life && life->end >= s)
690 if (!ir_value_life_add(self, e))
691 return false; /* failing */
697 if (before->end + 1 == s &&
698 life->start - 1 == s)
701 before->end = life->end;
702 if (!ir_value_life_remove(self, i))
703 return false; /* failing */
706 if (before->end + 1 == s)
712 /* already contained */
713 if (before->end >= s)
717 if (life->start - 1 == s)
722 /* insert a new entry */
723 new_entry.start = new_entry.end = s;
724 return ir_value_life_insert(self, i, new_entry);
727 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
731 if (!other->life_count)
734 if (!self->life_count) {
735 for (i = 0; i < other->life_count; ++i) {
736 if (!ir_value_life_add(self, other->life[i]))
743 for (i = 0; i < other->life_count; ++i)
745 const ir_life_entry_t *life = &other->life[i];
748 ir_life_entry_t *entry = &self->life[myi];
750 if (life->end+1 < entry->start)
752 /* adding an interval before entry */
753 if (!ir_value_life_insert(self, myi, *life))
759 if (life->start < entry->start &&
760 life->end >= entry->start)
762 /* starts earlier and overlaps */
763 entry->start = life->start;
766 if (life->end > entry->end &&
767 life->start-1 <= entry->end)
769 /* ends later and overlaps */
770 entry->end = life->end;
773 /* see if our change combines it with the next ranges */
774 while (myi+1 < self->life_count &&
775 entry->end+1 >= self->life[1+myi].start)
777 /* overlaps with (myi+1) */
778 if (entry->end < self->life[1+myi].end)
779 entry->end = self->life[1+myi].end;
780 if (!ir_value_life_remove(self, myi+1))
782 entry = &self->life[myi];
785 /* see if we're after the entry */
786 if (life->start > entry->end)
789 /* append if we're at the end */
790 if (myi >= self->life_count) {
791 if (!ir_value_life_add(self, *life))
795 /* otherweise check the next range */
804 bool ir_values_overlap(const ir_value *a, const ir_value *b)
806 /* For any life entry in A see if it overlaps with
807 * any life entry in B.
808 * Note that the life entries are orderes, so we can make a
809 * more efficient algorithm there than naively translating the
813 ir_life_entry_t *la, *lb, *enda, *endb;
815 /* first of all, if either has no life range, they cannot clash */
816 if (!a->life_count || !b->life_count)
821 enda = la + a->life_count;
822 endb = lb + b->life_count;
825 /* check if the entries overlap, for that,
826 * both must start before the other one ends.
828 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
829 if (la->start <= lb->end &&
830 lb->start <= la->end)
832 if (la->start < lb->end &&
839 /* entries are ordered
840 * one entry is earlier than the other
841 * that earlier entry will be moved forward
843 if (la->start < lb->start)
845 /* order: A B, move A forward
846 * check if we hit the end with A
851 else if (lb->start < la->start)
853 /* order: B A, move B forward
854 * check if we hit the end with B
863 /***********************************************************************
867 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
869 if (target->store == store_value) {
870 fprintf(stderr, "cannot store to an SSA value\n");
871 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
874 ir_instr *in = ir_instr_new(self, op);
877 if (!ir_instr_op(in, 0, target, true) ||
878 !ir_instr_op(in, 1, what, false) ||
879 !ir_block_instr_add(self, in) )
887 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
891 if (target->vtype == TYPE_VARIANT)
894 vtype = target->vtype;
897 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
898 op = INSTR_CONV_ITOF;
899 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
900 op = INSTR_CONV_FTOI;
902 op = type_store_instr[vtype];
904 return ir_block_create_store_op(self, op, target, what);
907 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
912 if (target->vtype != TYPE_POINTER)
915 /* storing using pointer - target is a pointer, type must be
916 * inferred from source
920 op = type_storep_instr[vtype];
921 return ir_block_create_store_op(self, op, target, what);
924 bool ir_block_create_return(ir_block *self, ir_value *v)
928 fprintf(stderr, "block already ended (%s)\n", self->label);
932 self->is_return = true;
933 in = ir_instr_new(self, INSTR_RETURN);
937 if (!ir_instr_op(in, 0, v, false) ||
938 !ir_block_instr_add(self, in) )
945 bool ir_block_create_if(ir_block *self, ir_value *v,
946 ir_block *ontrue, ir_block *onfalse)
950 fprintf(stderr, "block already ended (%s)\n", self->label);
954 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
955 in = ir_instr_new(self, VINSTR_COND);
959 if (!ir_instr_op(in, 0, v, false)) {
964 in->bops[0] = ontrue;
965 in->bops[1] = onfalse;
967 if (!ir_block_instr_add(self, in))
970 if (!ir_block_exits_add(self, ontrue) ||
971 !ir_block_exits_add(self, onfalse) ||
972 !ir_block_entries_add(ontrue, self) ||
973 !ir_block_entries_add(onfalse, self) )
980 bool ir_block_create_jump(ir_block *self, ir_block *to)
984 fprintf(stderr, "block already ended (%s)\n", self->label);
988 in = ir_instr_new(self, VINSTR_JUMP);
993 if (!ir_block_instr_add(self, in))
996 if (!ir_block_exits_add(self, to) ||
997 !ir_block_entries_add(to, self) )
1004 bool ir_block_create_goto(ir_block *self, ir_block *to)
1008 fprintf(stderr, "block already ended (%s)\n", self->label);
1012 in = ir_instr_new(self, INSTR_GOTO);
1017 if (!ir_block_instr_add(self, in))
1020 if (!ir_block_exits_add(self, to) ||
1021 !ir_block_entries_add(to, self) )
1028 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1032 in = ir_instr_new(self, VINSTR_PHI);
1035 out = ir_value_out(self->owner, label, store_value, ot);
1037 ir_instr_delete(in);
1040 if (!ir_instr_op(in, 0, out, true)) {
1041 ir_instr_delete(in);
1042 ir_value_delete(out);
1045 if (!ir_block_instr_add(self, in)) {
1046 ir_instr_delete(in);
1047 ir_value_delete(out);
1053 ir_value* ir_phi_value(ir_instr *self)
1055 return self->_ops[0];
1058 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1062 if (!ir_block_entries_find(self->owner, b, NULL)) {
1063 /* Must not be possible to cause this, otherwise the AST
1064 * is doing something wrong.
1066 fprintf(stderr, "Invalid entry block for PHI\n");
1072 if (!ir_value_reads_add(v, self))
1074 return ir_instr_phi_add(self, pe);
1077 /* call related code */
1078 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1082 in = ir_instr_new(self, INSTR_CALL0);
1085 out = ir_value_out(self->owner, label, store_return, func->outtype);
1087 ir_instr_delete(in);
1090 if (!ir_instr_op(in, 0, out, true) ||
1091 !ir_instr_op(in, 1, func, false) ||
1092 !ir_block_instr_add(self, in))
1094 ir_instr_delete(in);
1095 ir_value_delete(out);
1101 ir_value* ir_call_value(ir_instr *self)
1103 return self->_ops[0];
1106 bool ir_call_param(ir_instr* self, ir_value *v)
1108 if (!ir_instr_params_add(self, v))
1110 if (!ir_value_reads_add(v, self)) {
1111 if (!ir_instr_params_remove(self, self->params_count-1))
1112 GMQCC_SUPPRESS_EMPTY_BODY;
1118 /* binary op related code */
1120 ir_value* ir_block_create_binop(ir_block *self,
1121 const char *label, int opcode,
1122 ir_value *left, ir_value *right)
1144 case INSTR_SUB_S: /* -- offset of string as float */
1149 case INSTR_BITOR_IF:
1150 case INSTR_BITOR_FI:
1151 case INSTR_BITAND_FI:
1152 case INSTR_BITAND_IF:
1167 case INSTR_BITAND_I:
1170 case INSTR_RSHIFT_I:
1171 case INSTR_LSHIFT_I:
1192 /* boolean operations result in floats */
1193 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1195 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1198 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1203 if (ot == TYPE_VOID) {
1204 /* The AST or parser were supposed to check this! */
1208 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1211 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1212 int op, ir_value *a, ir_value *b, int outype)
1217 out = ir_value_out(self->owner, label, store_value, outype);
1221 instr = ir_instr_new(self, op);
1223 ir_value_delete(out);
1227 if (!ir_instr_op(instr, 0, out, true) ||
1228 !ir_instr_op(instr, 1, a, false) ||
1229 !ir_instr_op(instr, 2, b, false) )
1234 if (!ir_block_instr_add(self, instr))
1239 ir_instr_delete(instr);
1240 ir_value_delete(out);
1244 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1246 /* Support for various pointer types todo if so desired */
1247 if (ent->vtype != TYPE_ENTITY)
1250 if (field->vtype != TYPE_FIELD)
1253 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1256 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1259 if (ent->vtype != TYPE_ENTITY)
1262 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1263 if (field->vtype != TYPE_FIELD)
1268 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1269 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1270 case TYPE_STRING: op = INSTR_LOAD_S; break;
1271 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1272 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1274 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1275 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1277 case TYPE_QUATERNION: op = INSTR_LOAD_Q; break;
1278 case TYPE_MATRIX: op = INSTR_LOAD_M; break;
1283 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1286 ir_value* ir_block_create_add(ir_block *self,
1288 ir_value *left, ir_value *right)
1291 int l = left->vtype;
1292 int r = right->vtype;
1311 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1313 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1319 return ir_block_create_binop(self, label, op, left, right);
1322 ir_value* ir_block_create_sub(ir_block *self,
1324 ir_value *left, ir_value *right)
1327 int l = left->vtype;
1328 int r = right->vtype;
1348 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1350 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1356 return ir_block_create_binop(self, label, op, left, right);
1359 ir_value* ir_block_create_mul(ir_block *self,
1361 ir_value *left, ir_value *right)
1364 int l = left->vtype;
1365 int r = right->vtype;
1382 case TYPE_QUATERNION:
1390 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1392 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1394 else if ( (l == TYPE_QUATERNION && r == TYPE_FLOAT) )
1396 else if ( (l == TYPE_MATRIX && r == TYPE_FLOAT) )
1399 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1401 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1403 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1405 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1411 return ir_block_create_binop(self, label, op, left, right);
1414 ir_value* ir_block_create_div(ir_block *self,
1416 ir_value *left, ir_value *right)
1419 int l = left->vtype;
1420 int r = right->vtype;
1437 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1439 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1441 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1447 return ir_block_create_binop(self, label, op, left, right);
1450 /* PHI resolving breaks the SSA, and must thus be the last
1451 * step before life-range calculation.
1454 static bool ir_block_naive_phi(ir_block *self);
1455 bool ir_function_naive_phi(ir_function *self)
1459 for (i = 0; i < self->blocks_count; ++i)
1461 if (!ir_block_naive_phi(self->blocks[i]))
1467 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1472 /* create a store */
1473 if (!ir_block_create_store(block, old, what))
1476 /* we now move it up */
1477 instr = block->instr[block->instr_count-1];
1478 for (i = block->instr_count; i > iid; --i)
1479 block->instr[i] = block->instr[i-1];
1480 block->instr[i] = instr;
1485 static bool ir_block_naive_phi(ir_block *self)
1488 /* FIXME: optionally, create_phi can add the phis
1489 * to a list so we don't need to loop through blocks
1490 * - anyway: "don't optimize YET"
1492 for (i = 0; i < self->instr_count; ++i)
1494 ir_instr *instr = self->instr[i];
1495 if (instr->opcode != VINSTR_PHI)
1498 if (!ir_block_instr_remove(self, i))
1500 --i; /* NOTE: i+1 below */
1502 for (p = 0; p < instr->phi_count; ++p)
1504 ir_value *v = instr->phi[p].value;
1505 for (w = 0; w < v->writes_count; ++w) {
1508 if (!v->writes[w]->_ops[0])
1511 /* When the write was to a global, we have to emit a mov */
1512 old = v->writes[w]->_ops[0];
1514 /* The original instruction now writes to the PHI target local */
1515 if (v->writes[w]->_ops[0] == v)
1516 v->writes[w]->_ops[0] = instr->_ops[0];
1518 if (old->store != store_value && old->store != store_local)
1520 /* If it originally wrote to a global we need to store the value
1523 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1525 if (i+1 < self->instr_count)
1526 instr = self->instr[i+1];
1529 /* In case I forget and access instr later, it'll be NULL
1530 * when it's a problem, to make sure we crash, rather than accessing
1536 /* If it didn't, we can replace all reads by the phi target now. */
1538 for (r = 0; r < old->reads_count; ++r)
1541 ir_instr *ri = old->reads[r];
1542 for (op = 0; op < ri->phi_count; ++op) {
1543 if (ri->phi[op].value == old)
1544 ri->phi[op].value = v;
1546 for (op = 0; op < 3; ++op) {
1547 if (ri->_ops[op] == old)
1554 ir_instr_delete(instr);
1559 /***********************************************************************
1560 *IR Temp allocation code
1561 * Propagating value life ranges by walking through the function backwards
1562 * until no more changes are made.
1563 * In theory this should happen once more than once for every nested loop
1565 * Though this implementation might run an additional time for if nests.
1574 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1576 /* Enumerate instructions used by value's life-ranges
1578 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1582 for (i = 0; i < self->instr_count; ++i)
1584 self->instr[i]->eid = eid++;
1589 /* Enumerate blocks and instructions.
1590 * The block-enumeration is unordered!
1591 * We do not really use the block enumreation, however
1592 * the instruction enumeration is important for life-ranges.
1594 void ir_function_enumerate(ir_function *self)
1597 size_t instruction_id = 0;
1598 for (i = 0; i < self->blocks_count; ++i)
1600 self->blocks[i]->eid = i;
1601 self->blocks[i]->run_id = 0;
1602 ir_block_enumerate(self->blocks[i], &instruction_id);
1606 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1607 bool ir_function_calculate_liferanges(ir_function *self)
1615 for (i = 0; i != self->blocks_count; ++i)
1617 if (self->blocks[i]->is_return)
1619 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1627 /* Local-value allocator
1628 * After finishing creating the liferange of all values used in a function
1629 * we can allocate their global-positions.
1630 * This is the counterpart to register-allocation in register machines.
1633 MEM_VECTOR_MAKE(ir_value*, locals);
1634 MEM_VECTOR_MAKE(size_t, sizes);
1635 MEM_VECTOR_MAKE(size_t, positions);
1636 } function_allocator;
1637 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1638 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1639 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1641 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1644 size_t vsize = type_sizeof[var->vtype];
1646 slot = ir_value_var("reg", store_global, var->vtype);
1650 if (!ir_value_life_merge_into(slot, var))
1653 if (!function_allocator_locals_add(alloc, slot))
1656 if (!function_allocator_sizes_add(alloc, vsize))
1662 ir_value_delete(slot);
1666 bool ir_function_allocate_locals(ir_function *self)
1675 function_allocator alloc;
1677 if (!self->locals_count)
1680 MEM_VECTOR_INIT(&alloc, locals);
1681 MEM_VECTOR_INIT(&alloc, sizes);
1682 MEM_VECTOR_INIT(&alloc, positions);
1684 for (i = 0; i < self->locals_count; ++i)
1686 if (!function_allocator_alloc(&alloc, self->locals[i]))
1690 /* Allocate a slot for any value that still exists */
1691 for (i = 0; i < self->values_count; ++i)
1693 v = self->values[i];
1698 for (a = 0; a < alloc.locals_count; ++a)
1700 slot = alloc.locals[a];
1702 if (ir_values_overlap(v, slot))
1705 if (!ir_value_life_merge_into(slot, v))
1708 /* adjust size for this slot */
1709 if (alloc.sizes[a] < type_sizeof[v->vtype])
1710 alloc.sizes[a] = type_sizeof[v->vtype];
1712 self->values[i]->code.local = a;
1715 if (a >= alloc.locals_count) {
1716 self->values[i]->code.local = alloc.locals_count;
1717 if (!function_allocator_alloc(&alloc, v))
1722 /* Adjust slot positions based on sizes */
1723 if (!function_allocator_positions_add(&alloc, 0))
1726 if (alloc.sizes_count)
1727 pos = alloc.positions[0] + alloc.sizes[0];
1730 for (i = 1; i < alloc.sizes_count; ++i)
1732 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1733 if (!function_allocator_positions_add(&alloc, pos))
1737 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1739 /* Take over the actual slot positions */
1740 for (i = 0; i < self->values_count; ++i)
1741 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1748 for (i = 0; i < alloc.locals_count; ++i)
1749 ir_value_delete(alloc.locals[i]);
1750 MEM_VECTOR_CLEAR(&alloc, locals);
1751 MEM_VECTOR_CLEAR(&alloc, sizes);
1752 MEM_VECTOR_CLEAR(&alloc, positions);
1756 /* Get information about which operand
1757 * is read from, or written to.
1759 static void ir_op_read_write(int op, size_t *read, size_t *write)
1786 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1789 bool changed = false;
1791 for (i = 0; i != self->living_count; ++i)
1793 tempbool = ir_value_life_merge(self->living[i], eid);
1796 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1798 changed = changed || tempbool;
1803 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1806 /* values which have been read in a previous iteration are now
1807 * in the "living" array even if the previous block doesn't use them.
1808 * So we have to remove whatever does not exist in the previous block.
1809 * They will be re-added on-read, but the liferange merge won't cause
1812 for (i = 0; i < self->living_count; ++i)
1814 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1815 if (!ir_block_living_remove(self, i))
1821 /* Whatever the previous block still has in its living set
1822 * must now be added to ours as well.
1824 for (i = 0; i < prev->living_count; ++i)
1826 if (ir_block_living_find(self, prev->living[i], NULL))
1828 if (!ir_block_living_add(self, prev->living[i]))
1831 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1837 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1843 /* bitmasks which operands are read from or written to */
1845 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1847 new_reads_t new_reads;
1849 char dbg_ind[16] = { '#', '0' };
1852 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1853 MEM_VECTOR_INIT(&new_reads, v);
1858 if (!ir_block_life_prop_previous(self, prev, changed))
1862 i = self->instr_count;
1865 instr = self->instr[i];
1867 /* PHI operands are always read operands */
1868 for (p = 0; p < instr->phi_count; ++p)
1870 value = instr->phi[p].value;
1871 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1872 if (!ir_block_living_find(self, value, NULL) &&
1873 !ir_block_living_add(self, value))
1878 if (!new_reads_t_v_find(&new_reads, value, NULL))
1880 if (!new_reads_t_v_add(&new_reads, value))
1886 /* See which operands are read and write operands */
1887 ir_op_read_write(instr->opcode, &read, &write);
1889 /* Go through the 3 main operands */
1890 for (o = 0; o < 3; ++o)
1892 if (!instr->_ops[o]) /* no such operand */
1895 value = instr->_ops[o];
1897 /* We only care about locals */
1898 if (value->store != store_value &&
1899 value->store != store_local)
1905 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1906 if (!ir_block_living_find(self, value, NULL) &&
1907 !ir_block_living_add(self, value))
1912 /* fprintf(stderr, "read: %s\n", value->_name); */
1913 if (!new_reads_t_v_find(&new_reads, value, NULL))
1915 if (!new_reads_t_v_add(&new_reads, value))
1921 /* write operands */
1922 /* When we write to a local, we consider it "dead" for the
1923 * remaining upper part of the function, since in SSA a value
1924 * can only be written once (== created)
1929 bool in_living = ir_block_living_find(self, value, &idx);
1930 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1932 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1933 if (!in_living && !in_reads)
1938 /* If the value isn't alive it hasn't been read before... */
1939 /* TODO: See if the warning can be emitted during parsing or AST processing
1940 * otherwise have warning printed here.
1941 * IF printing a warning here: include filecontext_t,
1942 * and make sure it's only printed once
1943 * since this function is run multiple times.
1945 /* For now: debug info: */
1946 fprintf(stderr, "Value only written %s\n", value->name);
1947 tempbool = ir_value_life_merge(value, instr->eid);
1948 *changed = *changed || tempbool;
1950 ir_instr_dump(instr, dbg_ind, printf);
1954 /* since 'living' won't contain it
1955 * anymore, merge the value, since
1958 tempbool = ir_value_life_merge(value, instr->eid);
1961 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1963 *changed = *changed || tempbool;
1965 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1966 if (!ir_block_living_remove(self, idx))
1971 if (!new_reads_t_v_remove(&new_reads, readidx))
1979 tempbool = ir_block_living_add_instr(self, instr->eid);
1980 /*fprintf(stderr, "living added values\n");*/
1981 *changed = *changed || tempbool;
1983 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1985 for (rd = 0; rd < new_reads.v_count; ++rd)
1987 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1988 if (!ir_block_living_add(self, new_reads.v[rd]))
1991 if (!i && !self->entries_count) {
1993 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1996 MEM_VECTOR_CLEAR(&new_reads, v);
2000 if (self->run_id == self->owner->run_id)
2003 self->run_id = self->owner->run_id;
2005 for (i = 0; i < self->entries_count; ++i)
2007 ir_block *entry = self->entries[i];
2008 ir_block_life_propagate(entry, self, changed);
2013 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2014 MEM_VECTOR_CLEAR(&new_reads, v);
2019 /***********************************************************************
2022 * Since the IR has the convention of putting 'write' operands
2023 * at the beginning, we have to rotate the operands of instructions
2024 * properly in order to generate valid QCVM code.
2026 * Having destinations at a fixed position is more convenient. In QC
2027 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2028 * read from from OPA, and store to OPB rather than OPC. Which is
2029 * partially the reason why the implementation of these instructions
2030 * in darkplaces has been delayed for so long.
2032 * Breaking conventions is annoying...
2034 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2036 static bool gen_global_field(ir_value *global)
2038 if (global->isconst)
2040 ir_value *fld = global->constval.vpointer;
2042 printf("Invalid field constant with no field: %s\n", global->name);
2046 /* Now, in this case, a relocation would be impossible to code
2047 * since it looks like this:
2048 * .vector v = origin; <- parse error, wtf is 'origin'?
2051 * But we will need a general relocation support later anyway
2052 * for functions... might as well support that here.
2054 if (!fld->code.globaladdr) {
2055 printf("FIXME: Relocation support\n");
2059 /* copy the field's value */
2060 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2064 prog_section_field fld;
2066 fld.name = global->code.name;
2067 fld.offset = code_fields_elements;
2068 fld.type = global->fieldtype;
2070 if (fld.type == TYPE_VOID) {
2071 printf("Field is missing a type: %s\n", global->name);
2075 if (code_fields_add(fld) < 0)
2078 global->code.globaladdr = code_globals_add(fld.offset);
2080 if (global->code.globaladdr < 0)
2085 static bool gen_global_pointer(ir_value *global)
2087 if (global->isconst)
2089 ir_value *target = global->constval.vpointer;
2091 printf("Invalid pointer constant: %s\n", global->name);
2092 /* NULL pointers are pointing to the NULL constant, which also
2093 * sits at address 0, but still has an ir_value for itself.
2098 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2099 * void() foo; <- proto
2100 * void() *fooptr = &foo;
2101 * void() foo = { code }
2103 if (!target->code.globaladdr) {
2104 /* FIXME: Check for the constant nullptr ir_value!
2105 * because then code.globaladdr being 0 is valid.
2107 printf("FIXME: Relocation support\n");
2111 global->code.globaladdr = code_globals_add(target->code.globaladdr);
2115 global->code.globaladdr = code_globals_add(0);
2117 if (global->code.globaladdr < 0)
2122 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2124 prog_section_statement stmt;
2133 block->generated = true;
2134 block->code_start = code_statements_elements;
2135 for (i = 0; i < block->instr_count; ++i)
2137 instr = block->instr[i];
2139 if (instr->opcode == VINSTR_PHI) {
2140 printf("cannot generate virtual instruction (phi)\n");
2144 if (instr->opcode == VINSTR_JUMP) {
2145 target = instr->bops[0];
2146 /* for uncoditional jumps, if the target hasn't been generated
2147 * yet, we generate them right here.
2149 if (!target->generated) {
2154 /* otherwise we generate a jump instruction */
2155 stmt.opcode = INSTR_GOTO;
2156 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2159 if (code_statements_add(stmt) < 0)
2162 /* no further instructions can be in this block */
2166 if (instr->opcode == VINSTR_COND) {
2167 ontrue = instr->bops[0];
2168 onfalse = instr->bops[1];
2169 /* TODO: have the AST signal which block should
2170 * come first: eg. optimize IFs without ELSE...
2173 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2177 if (ontrue->generated) {
2178 stmt.opcode = INSTR_IF;
2179 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2180 if (code_statements_add(stmt) < 0)
2183 if (onfalse->generated) {
2184 stmt.opcode = INSTR_IFNOT;
2185 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2186 if (code_statements_add(stmt) < 0)
2189 if (!ontrue->generated) {
2190 if (onfalse->generated) {
2195 if (!onfalse->generated) {
2196 if (ontrue->generated) {
2201 /* neither ontrue nor onfalse exist */
2202 stmt.opcode = INSTR_IFNOT;
2203 stidx = code_statements_elements;
2204 if (code_statements_add(stmt) < 0)
2206 /* on false we jump, so add ontrue-path */
2207 if (!gen_blocks_recursive(func, ontrue))
2209 /* fixup the jump address */
2210 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2211 /* generate onfalse path */
2212 if (onfalse->generated) {
2213 /* fixup the jump address */
2214 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2215 /* may have been generated in the previous recursive call */
2216 stmt.opcode = INSTR_GOTO;
2217 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2220 return (code_statements_add(stmt) >= 0);
2222 /* if not, generate now */
2227 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2228 /* Trivial call translation:
2229 * copy all params to OFS_PARM*
2230 * if the output's storetype is not store_return,
2231 * add append a STORE instruction!
2233 * NOTES on how to do it better without much trouble:
2234 * -) The liferanges!
2235 * Simply check the liferange of all parameters for
2236 * other CALLs. For each param with no CALL in its
2237 * liferange, we can store it in an OFS_PARM at
2238 * generation already. This would even include later
2239 * reuse.... probably... :)
2244 for (p = 0; p < instr->params_count; ++p)
2246 ir_value *param = instr->params[p];
2248 stmt.opcode = INSTR_STORE_F;
2251 stmt.opcode = type_store_instr[param->vtype];
2252 stmt.o1.u1 = param->code.globaladdr;
2253 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2254 if (code_statements_add(stmt) < 0)
2257 stmt.opcode = INSTR_CALL0 + instr->params_count;
2258 if (stmt.opcode > INSTR_CALL8)
2259 stmt.opcode = INSTR_CALL8;
2260 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2263 if (code_statements_add(stmt) < 0)
2266 retvalue = instr->_ops[0];
2267 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2269 /* not to be kept in OFS_RETURN */
2270 stmt.opcode = type_store_instr[retvalue->vtype];
2271 stmt.o1.u1 = OFS_RETURN;
2272 stmt.o2.u1 = retvalue->code.globaladdr;
2274 if (code_statements_add(stmt) < 0)
2280 if (instr->opcode == INSTR_STATE) {
2281 printf("TODO: state instruction\n");
2285 stmt.opcode = instr->opcode;
2290 /* This is the general order of operands */
2292 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2295 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2298 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2300 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2302 stmt.o1.u1 = stmt.o3.u1;
2305 else if ((stmt.opcode >= INSTR_STORE_F &&
2306 stmt.opcode <= INSTR_STORE_FNC) ||
2307 (stmt.opcode >= INSTR_NOT_F &&
2308 stmt.opcode <= INSTR_NOT_FNC))
2310 /* 2-operand instructions with A -> B */
2311 stmt.o2.u1 = stmt.o3.u1;
2315 if (code_statements_add(stmt) < 0)
2321 static bool gen_function_code(ir_function *self)
2324 prog_section_statement stmt;
2326 /* Starting from entry point, we generate blocks "as they come"
2327 * for now. Dead blocks will not be translated obviously.
2329 if (!self->blocks_count) {
2330 printf("Function '%s' declared without body.\n", self->name);
2334 block = self->blocks[0];
2335 if (block->generated)
2338 if (!gen_blocks_recursive(self, block)) {
2339 printf("failed to generate blocks for '%s'\n", self->name);
2343 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2344 stmt.opcode = AINSTR_END;
2348 if (code_statements_add(stmt) < 0)
2353 static bool gen_global_function(ir_builder *ir, ir_value *global)
2355 prog_section_function fun;
2359 size_t local_var_end;
2361 if (!global->isconst || (!global->constval.vfunc))
2363 printf("Invalid state of function-global: not constant: %s\n", global->name);
2367 irfun = global->constval.vfunc;
2369 fun.name = global->code.name;
2370 fun.file = code_cachedstring(global->context.file);
2371 fun.profile = 0; /* always 0 */
2372 fun.nargs = irfun->params_count;
2374 for (i = 0;i < 8; ++i) {
2378 fun.argsize[i] = type_sizeof[irfun->params[i]];
2381 fun.firstlocal = code_globals_elements;
2382 fun.locals = irfun->allocated_locals + irfun->locals_count;
2385 for (i = 0; i < irfun->locals_count; ++i) {
2386 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2387 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2391 if (irfun->locals_count) {
2392 ir_value *last = irfun->locals[irfun->locals_count-1];
2393 local_var_end = last->code.globaladdr;
2394 local_var_end += type_sizeof[last->vtype];
2396 for (i = 0; i < irfun->values_count; ++i)
2398 /* generate code.globaladdr for ssa values */
2399 ir_value *v = irfun->values[i];
2400 v->code.globaladdr = local_var_end + v->code.local;
2402 for (i = 0; i < irfun->locals_count; ++i) {
2403 /* fill the locals with zeros */
2404 code_globals_add(0);
2408 fun.entry = irfun->builtin;
2410 fun.entry = code_statements_elements;
2411 if (!gen_function_code(irfun)) {
2412 printf("Failed to generate code for function %s\n", irfun->name);
2417 return (code_functions_add(fun) >= 0);
2420 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2423 prog_section_def def;
2425 def.type = global->vtype;
2426 def.offset = code_globals_elements;
2427 def.name = global->code.name = code_genstring(global->name);
2429 switch (global->vtype)
2432 if (code_defs_add(def) < 0)
2434 return gen_global_pointer(global);
2436 if (code_defs_add(def) < 0)
2438 return gen_global_field(global);
2443 if (code_defs_add(def) < 0)
2446 if (global->isconst) {
2447 iptr = (int32_t*)&global->constval.vfloat;
2448 global->code.globaladdr = code_globals_add(*iptr);
2450 global->code.globaladdr = code_globals_add(0);
2452 return global->code.globaladdr >= 0;
2456 if (code_defs_add(def) < 0)
2458 if (global->isconst)
2459 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2461 global->code.globaladdr = code_globals_add(0);
2462 return global->code.globaladdr >= 0;
2465 case TYPE_QUATERNION:
2469 if (code_defs_add(def) < 0)
2472 if (global->isconst) {
2473 iptr = (int32_t*)&global->constval.vvec;
2474 global->code.globaladdr = code_globals_add(iptr[0]);
2475 if (global->code.globaladdr < 0)
2477 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2479 if (code_globals_add(iptr[d]) < 0)
2483 global->code.globaladdr = code_globals_add(0);
2484 if (global->code.globaladdr < 0)
2486 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2488 if (code_globals_add(0) < 0)
2492 return global->code.globaladdr >= 0;
2495 if (code_defs_add(def) < 0)
2497 global->code.globaladdr = code_globals_elements;
2498 code_globals_add(code_functions_elements);
2499 return gen_global_function(self, global);
2501 /* assume biggest type */
2502 global->code.globaladdr = code_globals_add(0);
2503 code_globals_add(0);
2504 code_globals_add(0);
2507 /* refuse to create 'void' type or any other fancy business. */
2508 printf("Invalid type for global variable %s\n", global->name);
2513 bool ir_builder_generate(ir_builder *self, const char *filename)
2519 for (i = 0; i < self->globals_count; ++i)
2521 if (!ir_builder_gen_global(self, self->globals[i])) {
2526 printf("writing '%s'...\n", filename);
2527 return code_write(filename);
2530 /***********************************************************************
2531 *IR DEBUG Dump functions...
2534 #define IND_BUFSZ 1024
2536 const char *qc_opname(int op)
2538 if (op < 0) return "<INVALID>";
2539 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2540 return asm_instr[op].m;
2542 case VINSTR_PHI: return "PHI";
2543 case VINSTR_JUMP: return "JUMP";
2544 case VINSTR_COND: return "COND";
2545 default: return "<UNK>";
2549 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2552 char indent[IND_BUFSZ];
2556 oprintf("module %s\n", b->name);
2557 for (i = 0; i < b->globals_count; ++i)
2560 if (b->globals[i]->isconst)
2561 oprintf("%s = ", b->globals[i]->name);
2562 ir_value_dump(b->globals[i], oprintf);
2565 for (i = 0; i < b->functions_count; ++i)
2566 ir_function_dump(b->functions[i], indent, oprintf);
2567 oprintf("endmodule %s\n", b->name);
2570 void ir_function_dump(ir_function *f, char *ind,
2571 int (*oprintf)(const char*, ...))
2574 if (f->builtin != 0) {
2575 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2578 oprintf("%sfunction %s\n", ind, f->name);
2579 strncat(ind, "\t", IND_BUFSZ);
2580 if (f->locals_count)
2582 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2583 for (i = 0; i < f->locals_count; ++i) {
2584 oprintf("%s\t", ind);
2585 ir_value_dump(f->locals[i], oprintf);
2589 if (f->blocks_count)
2591 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2592 for (i = 0; i < f->blocks_count; ++i) {
2593 if (f->blocks[i]->run_id != f->run_id) {
2594 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2596 ir_block_dump(f->blocks[i], ind, oprintf);
2600 ind[strlen(ind)-1] = 0;
2601 oprintf("%sendfunction %s\n", ind, f->name);
2604 void ir_block_dump(ir_block* b, char *ind,
2605 int (*oprintf)(const char*, ...))
2608 oprintf("%s:%s\n", ind, b->label);
2609 strncat(ind, "\t", IND_BUFSZ);
2611 for (i = 0; i < b->instr_count; ++i)
2612 ir_instr_dump(b->instr[i], ind, oprintf);
2613 ind[strlen(ind)-1] = 0;
2616 void dump_phi(ir_instr *in, char *ind,
2617 int (*oprintf)(const char*, ...))
2620 oprintf("%s <- phi ", in->_ops[0]->name);
2621 for (i = 0; i < in->phi_count; ++i)
2623 oprintf("([%s] : %s) ", in->phi[i].from->label,
2624 in->phi[i].value->name);
2629 void ir_instr_dump(ir_instr *in, char *ind,
2630 int (*oprintf)(const char*, ...))
2633 const char *comma = NULL;
2635 oprintf("%s (%i) ", ind, (int)in->eid);
2637 if (in->opcode == VINSTR_PHI) {
2638 dump_phi(in, ind, oprintf);
2642 strncat(ind, "\t", IND_BUFSZ);
2644 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2645 ir_value_dump(in->_ops[0], oprintf);
2646 if (in->_ops[1] || in->_ops[2])
2649 oprintf("%s\t", qc_opname(in->opcode));
2650 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2651 ir_value_dump(in->_ops[0], oprintf);
2656 for (i = 1; i != 3; ++i) {
2660 ir_value_dump(in->_ops[i], oprintf);
2668 oprintf("[%s]", in->bops[0]->label);
2672 oprintf("%s[%s]", comma, in->bops[1]->label);
2674 ind[strlen(ind)-1] = 0;
2677 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2686 oprintf("%g", v->constval.vfloat);
2689 oprintf("'%g %g %g'",
2692 v->constval.vvec.z);
2695 oprintf("(entity)");
2698 oprintf("\"%s\"", v->constval.vstring);
2702 oprintf("%i", v->constval.vint);
2707 v->constval.vpointer->name);
2711 oprintf("%s", v->name);
2715 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2718 oprintf("Life of %s:\n", self->name);
2719 for (i = 0; i < self->life_count; ++i)
2721 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);