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] = {
47 size_t type_sizeof[TYPE_COUNT] = {
54 1, /* TYPE_FUNCTION */
62 uint16_t type_store_instr[TYPE_COUNT] = {
63 INSTR_STORE_F, /* should use I when having integer support */
70 INSTR_STORE_ENT, /* should use I */
72 INSTR_STORE_I, /* integer type */
75 INSTR_STORE_V, /* variant, should never be accessed */
78 uint16_t type_storep_instr[TYPE_COUNT] = {
79 INSTR_STOREP_F, /* should use I when having integer support */
86 INSTR_STOREP_ENT, /* should use I */
88 INSTR_STOREP_ENT, /* integer type */
91 INSTR_STOREP_V, /* variant, should never be accessed */
94 uint16_t type_eq_instr[TYPE_COUNT] = {
95 INSTR_EQ_F, /* should use I when having integer support */
100 INSTR_EQ_E, /* FLD has no comparison */
102 INSTR_EQ_E, /* should use I */
107 INSTR_EQ_V, /* variant, should never be accessed */
110 uint16_t type_ne_instr[TYPE_COUNT] = {
111 INSTR_NE_F, /* should use I when having integer support */
116 INSTR_NE_E, /* FLD has no comparison */
118 INSTR_NE_E, /* should use I */
123 INSTR_NE_V, /* variant, should never be accessed */
126 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
128 static void irerror(lex_ctx ctx, const char *msg, ...)
132 cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
136 /***********************************************************************
140 ir_builder* ir_builder_new(const char *modulename)
144 self = (ir_builder*)mem_a(sizeof(*self));
148 MEM_VECTOR_INIT(self, functions);
149 MEM_VECTOR_INIT(self, globals);
150 MEM_VECTOR_INIT(self, fields);
152 if (!ir_builder_set_name(self, modulename)) {
157 /* globals which always exist */
159 /* for now we give it a vector size */
160 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
165 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
166 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
167 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
169 void ir_builder_delete(ir_builder* self)
172 mem_d((void*)self->name);
173 for (i = 0; i != self->functions_count; ++i) {
174 ir_function_delete(self->functions[i]);
176 MEM_VECTOR_CLEAR(self, functions);
177 for (i = 0; i != self->globals_count; ++i) {
178 ir_value_delete(self->globals[i]);
180 MEM_VECTOR_CLEAR(self, globals);
181 for (i = 0; i != self->fields_count; ++i) {
182 ir_value_delete(self->fields[i]);
184 MEM_VECTOR_CLEAR(self, fields);
188 bool ir_builder_set_name(ir_builder *self, const char *name)
191 mem_d((void*)self->name);
192 self->name = util_strdup(name);
196 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
199 for (i = 0; i < self->functions_count; ++i) {
200 if (!strcmp(name, self->functions[i]->name))
201 return self->functions[i];
206 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
208 ir_function *fn = ir_builder_get_function(self, name);
213 fn = ir_function_new(self, outtype);
214 if (!ir_function_set_name(fn, name) ||
215 !ir_builder_functions_add(self, fn) )
217 ir_function_delete(fn);
221 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
223 ir_function_delete(fn);
227 fn->value->isconst = true;
228 fn->value->outtype = outtype;
229 fn->value->constval.vfunc = fn;
230 fn->value->context = fn->context;
235 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
238 for (i = 0; i < self->globals_count; ++i) {
239 if (!strcmp(self->globals[i]->name, name))
240 return self->globals[i];
245 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
249 if (name && name[0] != '#')
251 ve = ir_builder_get_global(self, name);
257 ve = ir_value_var(name, store_global, vtype);
258 if (!ir_builder_globals_add(self, ve)) {
265 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
268 for (i = 0; i < self->fields_count; ++i) {
269 if (!strcmp(self->fields[i]->name, name))
270 return self->fields[i];
276 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
278 ir_value *ve = ir_builder_get_field(self, name);
283 ve = ir_value_var(name, store_global, TYPE_FIELD);
284 ve->fieldtype = vtype;
285 if (!ir_builder_fields_add(self, ve)) {
292 /***********************************************************************
296 bool ir_function_naive_phi(ir_function*);
297 void ir_function_enumerate(ir_function*);
298 bool ir_function_calculate_liferanges(ir_function*);
299 bool ir_function_allocate_locals(ir_function*);
301 ir_function* ir_function_new(ir_builder* owner, int outtype)
304 self = (ir_function*)mem_a(sizeof(*self));
310 if (!ir_function_set_name(self, "<@unnamed>")) {
315 self->context.file = "<@no context>";
316 self->context.line = 0;
317 self->outtype = outtype;
320 MEM_VECTOR_INIT(self, params);
321 MEM_VECTOR_INIT(self, blocks);
322 MEM_VECTOR_INIT(self, values);
323 MEM_VECTOR_INIT(self, locals);
325 self->code_function_def = -1;
330 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
331 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
332 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
333 MEM_VEC_FUNCTIONS(ir_function, int, params)
335 bool ir_function_set_name(ir_function *self, const char *name)
338 mem_d((void*)self->name);
339 self->name = util_strdup(name);
343 void ir_function_delete(ir_function *self)
346 mem_d((void*)self->name);
348 for (i = 0; i != self->blocks_count; ++i)
349 ir_block_delete(self->blocks[i]);
350 MEM_VECTOR_CLEAR(self, blocks);
352 MEM_VECTOR_CLEAR(self, params);
354 for (i = 0; i != self->values_count; ++i)
355 ir_value_delete(self->values[i]);
356 MEM_VECTOR_CLEAR(self, values);
358 for (i = 0; i != self->locals_count; ++i)
359 ir_value_delete(self->locals[i]);
360 MEM_VECTOR_CLEAR(self, locals);
362 /* self->value is deleted by the builder */
367 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
369 return ir_function_values_add(self, v);
372 ir_block* ir_function_create_block(ir_function *self, const char *label)
374 ir_block* bn = ir_block_new(self, label);
375 memcpy(&bn->context, &self->context, sizeof(self->context));
376 if (!ir_function_blocks_add(self, bn)) {
383 bool ir_function_finalize(ir_function *self)
388 if (!ir_function_naive_phi(self))
391 ir_function_enumerate(self);
393 if (!ir_function_calculate_liferanges(self))
396 if (!ir_function_allocate_locals(self))
401 ir_value* ir_function_get_local(ir_function *self, const char *name)
404 for (i = 0; i < self->locals_count; ++i) {
405 if (!strcmp(self->locals[i]->name, name))
406 return self->locals[i];
411 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
413 ir_value *ve = ir_function_get_local(self, name);
419 self->locals_count &&
420 self->locals[self->locals_count-1]->store != store_param) {
421 irerror(self->context, "cannot add parameters after adding locals\n");
425 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
426 if (!ir_function_locals_add(self, ve)) {
433 /***********************************************************************
437 ir_block* ir_block_new(ir_function* owner, const char *name)
440 self = (ir_block*)mem_a(sizeof(*self));
444 memset(self, 0, sizeof(*self));
447 if (!ir_block_set_label(self, name)) {
452 self->context.file = "<@no context>";
453 self->context.line = 0;
455 MEM_VECTOR_INIT(self, instr);
456 MEM_VECTOR_INIT(self, entries);
457 MEM_VECTOR_INIT(self, exits);
460 self->is_return = false;
462 MEM_VECTOR_INIT(self, living);
464 self->generated = false;
468 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
469 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
470 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
471 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
473 void ir_block_delete(ir_block* self)
477 for (i = 0; i != self->instr_count; ++i)
478 ir_instr_delete(self->instr[i]);
479 MEM_VECTOR_CLEAR(self, instr);
480 MEM_VECTOR_CLEAR(self, entries);
481 MEM_VECTOR_CLEAR(self, exits);
482 MEM_VECTOR_CLEAR(self, living);
486 bool ir_block_set_label(ir_block *self, const char *name)
489 mem_d((void*)self->label);
490 self->label = util_strdup(name);
491 return !!self->label;
494 /***********************************************************************
498 ir_instr* ir_instr_new(ir_block* owner, int op)
501 self = (ir_instr*)mem_a(sizeof(*self));
506 self->context.file = "<@no context>";
507 self->context.line = 0;
509 self->_ops[0] = NULL;
510 self->_ops[1] = NULL;
511 self->_ops[2] = NULL;
512 self->bops[0] = NULL;
513 self->bops[1] = NULL;
514 MEM_VECTOR_INIT(self, phi);
515 MEM_VECTOR_INIT(self, params);
520 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
521 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
523 void ir_instr_delete(ir_instr *self)
526 /* The following calls can only delete from
527 * vectors, we still want to delete this instruction
528 * so ignore the return value. Since with the warn_unused_result attribute
529 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
530 * I have to improvise here and use if(foo());
532 for (i = 0; i < self->phi_count; ++i) {
534 if (ir_value_writes_find(self->phi[i].value, self, &idx))
535 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
536 if (ir_value_reads_find(self->phi[i].value, self, &idx))
537 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
539 MEM_VECTOR_CLEAR(self, phi);
540 for (i = 0; i < self->params_count; ++i) {
542 if (ir_value_writes_find(self->params[i], self, &idx))
543 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
544 if (ir_value_reads_find(self->params[i], self, &idx))
545 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
547 MEM_VECTOR_CLEAR(self, params);
548 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
549 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
550 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
554 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
556 if (self->_ops[op]) {
558 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
560 if (!ir_value_writes_remove(self->_ops[op], idx))
563 else if (ir_value_reads_find(self->_ops[op], self, &idx))
565 if (!ir_value_reads_remove(self->_ops[op], idx))
571 if (!ir_value_writes_add(v, self))
574 if (!ir_value_reads_add(v, self))
582 /***********************************************************************
586 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
588 self->code.globaladdr = gaddr;
589 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
590 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
591 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
594 int32_t ir_value_code_addr(const ir_value *self)
596 if (self->store == store_return)
597 return OFS_RETURN + self->code.addroffset;
598 return self->code.globaladdr + self->code.addroffset;
601 ir_value* ir_value_var(const char *name, int storetype, int vtype)
604 self = (ir_value*)mem_a(sizeof(*self));
606 self->fieldtype = TYPE_VOID;
607 self->outtype = TYPE_VOID;
608 self->store = storetype;
609 MEM_VECTOR_INIT(self, reads);
610 MEM_VECTOR_INIT(self, writes);
611 self->isconst = false;
612 self->context.file = "<@no context>";
613 self->context.line = 0;
615 ir_value_set_name(self, name);
617 memset(&self->constval, 0, sizeof(self->constval));
618 memset(&self->code, 0, sizeof(self->code));
620 self->members[0] = NULL;
621 self->members[1] = NULL;
622 self->members[2] = NULL;
624 MEM_VECTOR_INIT(self, life);
628 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
634 if (self->members[member])
635 return self->members[member];
637 if (self->vtype == TYPE_VECTOR)
639 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
642 m->context = self->context;
644 self->members[member] = m;
645 m->code.addroffset = member;
647 else if (self->vtype == TYPE_FIELD)
649 if (self->fieldtype != TYPE_VECTOR)
651 m = ir_value_var(self->name, self->store, TYPE_FIELD);
654 m->fieldtype = TYPE_FLOAT;
655 m->context = self->context;
657 self->members[member] = m;
658 m->code.addroffset = member;
662 irerror(self->context, "invalid member access on %s\n", self->name);
669 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
670 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
671 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
673 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
675 ir_value *v = ir_value_var(name, storetype, vtype);
678 if (!ir_function_collect_value(owner, v))
686 void ir_value_delete(ir_value* self)
690 mem_d((void*)self->name);
693 if (self->vtype == TYPE_STRING)
694 mem_d((void*)self->constval.vstring);
696 for (i = 0; i < 3; ++i) {
697 if (self->members[i])
698 ir_value_delete(self->members[i]);
700 MEM_VECTOR_CLEAR(self, reads);
701 MEM_VECTOR_CLEAR(self, writes);
702 MEM_VECTOR_CLEAR(self, life);
706 void ir_value_set_name(ir_value *self, const char *name)
709 mem_d((void*)self->name);
710 self->name = util_strdup(name);
713 bool ir_value_set_float(ir_value *self, float f)
715 if (self->vtype != TYPE_FLOAT)
717 self->constval.vfloat = f;
718 self->isconst = true;
722 bool ir_value_set_func(ir_value *self, int f)
724 if (self->vtype != TYPE_FUNCTION)
726 self->constval.vint = f;
727 self->isconst = true;
731 bool ir_value_set_vector(ir_value *self, vector v)
733 if (self->vtype != TYPE_VECTOR)
735 self->constval.vvec = v;
736 self->isconst = true;
740 bool ir_value_set_field(ir_value *self, ir_value *fld)
742 if (self->vtype != TYPE_FIELD)
744 self->constval.vpointer = fld;
745 self->isconst = true;
749 bool ir_value_set_string(ir_value *self, const char *str)
751 if (self->vtype != TYPE_STRING)
753 self->constval.vstring = util_strdup(str);
754 self->isconst = true;
759 bool ir_value_set_int(ir_value *self, int i)
761 if (self->vtype != TYPE_INTEGER)
763 self->constval.vint = i;
764 self->isconst = true;
769 bool ir_value_lives(ir_value *self, size_t at)
772 for (i = 0; i < self->life_count; ++i)
774 ir_life_entry_t *life = &self->life[i];
775 if (life->start <= at && at <= life->end)
777 if (life->start > at) /* since it's ordered */
783 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
786 if (!ir_value_life_add(self, e)) /* naive... */
788 for (k = self->life_count-1; k > idx; --k)
789 self->life[k] = self->life[k-1];
794 bool ir_value_life_merge(ir_value *self, size_t s)
797 ir_life_entry_t *life = NULL;
798 ir_life_entry_t *before = NULL;
799 ir_life_entry_t new_entry;
801 /* Find the first range >= s */
802 for (i = 0; i < self->life_count; ++i)
805 life = &self->life[i];
809 /* nothing found? append */
810 if (i == self->life_count) {
812 if (life && life->end+1 == s)
814 /* previous life range can be merged in */
818 if (life && life->end >= s)
821 if (!ir_value_life_add(self, e))
822 return false; /* failing */
828 if (before->end + 1 == s &&
829 life->start - 1 == s)
832 before->end = life->end;
833 if (!ir_value_life_remove(self, i))
834 return false; /* failing */
837 if (before->end + 1 == s)
843 /* already contained */
844 if (before->end >= s)
848 if (life->start - 1 == s)
853 /* insert a new entry */
854 new_entry.start = new_entry.end = s;
855 return ir_value_life_insert(self, i, new_entry);
858 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
862 if (!other->life_count)
865 if (!self->life_count) {
866 for (i = 0; i < other->life_count; ++i) {
867 if (!ir_value_life_add(self, other->life[i]))
874 for (i = 0; i < other->life_count; ++i)
876 const ir_life_entry_t *life = &other->life[i];
879 ir_life_entry_t *entry = &self->life[myi];
881 if (life->end+1 < entry->start)
883 /* adding an interval before entry */
884 if (!ir_value_life_insert(self, myi, *life))
890 if (life->start < entry->start &&
891 life->end >= entry->start)
893 /* starts earlier and overlaps */
894 entry->start = life->start;
897 if (life->end > entry->end &&
898 life->start-1 <= entry->end)
900 /* ends later and overlaps */
901 entry->end = life->end;
904 /* see if our change combines it with the next ranges */
905 while (myi+1 < self->life_count &&
906 entry->end+1 >= self->life[1+myi].start)
908 /* overlaps with (myi+1) */
909 if (entry->end < self->life[1+myi].end)
910 entry->end = self->life[1+myi].end;
911 if (!ir_value_life_remove(self, myi+1))
913 entry = &self->life[myi];
916 /* see if we're after the entry */
917 if (life->start > entry->end)
920 /* append if we're at the end */
921 if (myi >= self->life_count) {
922 if (!ir_value_life_add(self, *life))
926 /* otherweise check the next range */
935 bool ir_values_overlap(const ir_value *a, const ir_value *b)
937 /* For any life entry in A see if it overlaps with
938 * any life entry in B.
939 * Note that the life entries are orderes, so we can make a
940 * more efficient algorithm there than naively translating the
944 ir_life_entry_t *la, *lb, *enda, *endb;
946 /* first of all, if either has no life range, they cannot clash */
947 if (!a->life_count || !b->life_count)
952 enda = la + a->life_count;
953 endb = lb + b->life_count;
956 /* check if the entries overlap, for that,
957 * both must start before the other one ends.
959 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
960 if (la->start <= lb->end &&
961 lb->start <= la->end)
963 if (la->start < lb->end &&
970 /* entries are ordered
971 * one entry is earlier than the other
972 * that earlier entry will be moved forward
974 if (la->start < lb->start)
976 /* order: A B, move A forward
977 * check if we hit the end with A
982 else /* if (lb->start < la->start) actually <= */
984 /* order: B A, move B forward
985 * check if we hit the end with B
994 /***********************************************************************
998 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1000 ir_instr *in = ir_instr_new(self, op);
1004 if (target->store == store_value &&
1005 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1007 irerror(self->context, "cannot store to an SSA value\n");
1008 irerror(self->context, "trying to store: %s <- %s\n", target->name, what->name);
1009 irerror(self->context, "instruction: %s\n", asm_instr[op].m);
1013 if (!ir_instr_op(in, 0, target, true) ||
1014 !ir_instr_op(in, 1, what, false) ||
1015 !ir_block_instr_add(self, in) )
1022 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1026 if (target->vtype == TYPE_VARIANT)
1027 vtype = what->vtype;
1029 vtype = target->vtype;
1032 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1033 op = INSTR_CONV_ITOF;
1034 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1035 op = INSTR_CONV_FTOI;
1037 op = type_store_instr[vtype];
1039 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1040 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1044 return ir_block_create_store_op(self, op, target, what);
1047 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1052 if (target->vtype != TYPE_POINTER)
1055 /* storing using pointer - target is a pointer, type must be
1056 * inferred from source
1058 vtype = what->vtype;
1060 op = type_storep_instr[vtype];
1061 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1062 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1063 op = INSTR_STOREP_V;
1066 return ir_block_create_store_op(self, op, target, what);
1069 bool ir_block_create_return(ir_block *self, ir_value *v)
1073 irerror(self->context, "block already ended (%s)\n", self->label);
1077 self->is_return = true;
1078 in = ir_instr_new(self, INSTR_RETURN);
1082 if (v && !ir_instr_op(in, 0, v, false))
1085 if (!ir_block_instr_add(self, in))
1090 bool ir_block_create_if(ir_block *self, ir_value *v,
1091 ir_block *ontrue, ir_block *onfalse)
1095 irerror(self->context, "block already ended (%s)\n", self->label);
1099 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1100 in = ir_instr_new(self, VINSTR_COND);
1104 if (!ir_instr_op(in, 0, v, false)) {
1105 ir_instr_delete(in);
1109 in->bops[0] = ontrue;
1110 in->bops[1] = onfalse;
1112 if (!ir_block_instr_add(self, in))
1115 if (!ir_block_exits_add(self, ontrue) ||
1116 !ir_block_exits_add(self, onfalse) ||
1117 !ir_block_entries_add(ontrue, self) ||
1118 !ir_block_entries_add(onfalse, self) )
1125 bool ir_block_create_jump(ir_block *self, ir_block *to)
1129 irerror(self->context, "block already ended (%s)\n", self->label);
1133 in = ir_instr_new(self, VINSTR_JUMP);
1138 if (!ir_block_instr_add(self, in))
1141 if (!ir_block_exits_add(self, to) ||
1142 !ir_block_entries_add(to, self) )
1149 bool ir_block_create_goto(ir_block *self, ir_block *to)
1153 irerror(self->context, "block already ended (%s)\n", self->label);
1157 in = ir_instr_new(self, INSTR_GOTO);
1162 if (!ir_block_instr_add(self, in))
1165 if (!ir_block_exits_add(self, to) ||
1166 !ir_block_entries_add(to, self) )
1173 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1177 in = ir_instr_new(self, VINSTR_PHI);
1180 out = ir_value_out(self->owner, label, store_value, ot);
1182 ir_instr_delete(in);
1185 if (!ir_instr_op(in, 0, out, true)) {
1186 ir_instr_delete(in);
1187 ir_value_delete(out);
1190 if (!ir_block_instr_add(self, in)) {
1191 ir_instr_delete(in);
1192 ir_value_delete(out);
1198 ir_value* ir_phi_value(ir_instr *self)
1200 return self->_ops[0];
1203 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1207 if (!ir_block_entries_find(self->owner, b, NULL)) {
1208 /* Must not be possible to cause this, otherwise the AST
1209 * is doing something wrong.
1211 irerror(self->context, "Invalid entry block for PHI\n");
1217 if (!ir_value_reads_add(v, self))
1219 return ir_instr_phi_add(self, pe);
1222 /* call related code */
1223 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1227 in = ir_instr_new(self, INSTR_CALL0);
1230 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1232 ir_instr_delete(in);
1235 if (!ir_instr_op(in, 0, out, true) ||
1236 !ir_instr_op(in, 1, func, false) ||
1237 !ir_block_instr_add(self, in))
1239 ir_instr_delete(in);
1240 ir_value_delete(out);
1246 ir_value* ir_call_value(ir_instr *self)
1248 return self->_ops[0];
1251 bool ir_call_param(ir_instr* self, ir_value *v)
1253 if (!ir_instr_params_add(self, v))
1255 if (!ir_value_reads_add(v, self)) {
1256 if (!ir_instr_params_remove(self, self->params_count-1))
1257 GMQCC_SUPPRESS_EMPTY_BODY;
1263 /* binary op related code */
1265 ir_value* ir_block_create_binop(ir_block *self,
1266 const char *label, int opcode,
1267 ir_value *left, ir_value *right)
1289 case INSTR_SUB_S: /* -- offset of string as float */
1294 case INSTR_BITOR_IF:
1295 case INSTR_BITOR_FI:
1296 case INSTR_BITAND_FI:
1297 case INSTR_BITAND_IF:
1312 case INSTR_BITAND_I:
1315 case INSTR_RSHIFT_I:
1316 case INSTR_LSHIFT_I:
1338 /* boolean operations result in floats */
1339 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1341 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1344 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1349 if (ot == TYPE_VOID) {
1350 /* The AST or parser were supposed to check this! */
1354 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1357 ir_value* ir_block_create_unary(ir_block *self,
1358 const char *label, int opcode,
1361 int ot = TYPE_FLOAT;
1373 /* QC doesn't have other unary operations. We expect extensions to fill
1374 * the above list, otherwise we assume out-type = in-type, eg for an
1378 ot = operand->vtype;
1381 if (ot == TYPE_VOID) {
1382 /* The AST or parser were supposed to check this! */
1386 /* let's use the general instruction creator and pass NULL for OPB */
1387 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1390 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1391 int op, ir_value *a, ir_value *b, int outype)
1396 out = ir_value_out(self->owner, label, store_value, outype);
1400 instr = ir_instr_new(self, op);
1402 ir_value_delete(out);
1406 if (!ir_instr_op(instr, 0, out, true) ||
1407 !ir_instr_op(instr, 1, a, false) ||
1408 !ir_instr_op(instr, 2, b, false) )
1413 if (!ir_block_instr_add(self, instr))
1418 ir_instr_delete(instr);
1419 ir_value_delete(out);
1423 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1427 /* Support for various pointer types todo if so desired */
1428 if (ent->vtype != TYPE_ENTITY)
1431 if (field->vtype != TYPE_FIELD)
1434 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1435 v->fieldtype = field->fieldtype;
1439 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1442 if (ent->vtype != TYPE_ENTITY)
1445 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1446 if (field->vtype != TYPE_FIELD)
1451 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1452 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1453 case TYPE_STRING: op = INSTR_LOAD_S; break;
1454 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1455 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1456 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1458 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1459 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1465 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1468 ir_value* ir_block_create_add(ir_block *self,
1470 ir_value *left, ir_value *right)
1473 int l = left->vtype;
1474 int r = right->vtype;
1493 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1495 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1501 return ir_block_create_binop(self, label, op, left, right);
1504 ir_value* ir_block_create_sub(ir_block *self,
1506 ir_value *left, ir_value *right)
1509 int l = left->vtype;
1510 int r = right->vtype;
1530 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1532 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1538 return ir_block_create_binop(self, label, op, left, right);
1541 ir_value* ir_block_create_mul(ir_block *self,
1543 ir_value *left, ir_value *right)
1546 int l = left->vtype;
1547 int r = right->vtype;
1566 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1568 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1571 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1573 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1575 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1577 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1583 return ir_block_create_binop(self, label, op, left, right);
1586 ir_value* ir_block_create_div(ir_block *self,
1588 ir_value *left, ir_value *right)
1591 int l = left->vtype;
1592 int r = right->vtype;
1609 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1611 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1613 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1619 return ir_block_create_binop(self, label, op, left, right);
1622 /* PHI resolving breaks the SSA, and must thus be the last
1623 * step before life-range calculation.
1626 static bool ir_block_naive_phi(ir_block *self);
1627 bool ir_function_naive_phi(ir_function *self)
1631 for (i = 0; i < self->blocks_count; ++i)
1633 if (!ir_block_naive_phi(self->blocks[i]))
1639 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1644 /* create a store */
1645 if (!ir_block_create_store(block, old, what))
1648 /* we now move it up */
1649 instr = block->instr[block->instr_count-1];
1650 for (i = block->instr_count; i > iid; --i)
1651 block->instr[i] = block->instr[i-1];
1652 block->instr[i] = instr;
1657 static bool ir_block_naive_phi(ir_block *self)
1660 /* FIXME: optionally, create_phi can add the phis
1661 * to a list so we don't need to loop through blocks
1662 * - anyway: "don't optimize YET"
1664 for (i = 0; i < self->instr_count; ++i)
1666 ir_instr *instr = self->instr[i];
1667 if (instr->opcode != VINSTR_PHI)
1670 if (!ir_block_instr_remove(self, i))
1672 --i; /* NOTE: i+1 below */
1674 for (p = 0; p < instr->phi_count; ++p)
1676 ir_value *v = instr->phi[p].value;
1677 for (w = 0; w < v->writes_count; ++w) {
1680 if (!v->writes[w]->_ops[0])
1683 /* When the write was to a global, we have to emit a mov */
1684 old = v->writes[w]->_ops[0];
1686 /* The original instruction now writes to the PHI target local */
1687 if (v->writes[w]->_ops[0] == v)
1688 v->writes[w]->_ops[0] = instr->_ops[0];
1690 if (old->store != store_value && old->store != store_local && old->store != store_param)
1692 /* If it originally wrote to a global we need to store the value
1695 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1697 if (i+1 < self->instr_count)
1698 instr = self->instr[i+1];
1701 /* In case I forget and access instr later, it'll be NULL
1702 * when it's a problem, to make sure we crash, rather than accessing
1708 /* If it didn't, we can replace all reads by the phi target now. */
1710 for (r = 0; r < old->reads_count; ++r)
1713 ir_instr *ri = old->reads[r];
1714 for (op = 0; op < ri->phi_count; ++op) {
1715 if (ri->phi[op].value == old)
1716 ri->phi[op].value = v;
1718 for (op = 0; op < 3; ++op) {
1719 if (ri->_ops[op] == old)
1726 ir_instr_delete(instr);
1731 /***********************************************************************
1732 *IR Temp allocation code
1733 * Propagating value life ranges by walking through the function backwards
1734 * until no more changes are made.
1735 * In theory this should happen once more than once for every nested loop
1737 * Though this implementation might run an additional time for if nests.
1746 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1748 /* Enumerate instructions used by value's life-ranges
1750 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1754 for (i = 0; i < self->instr_count; ++i)
1756 self->instr[i]->eid = eid++;
1761 /* Enumerate blocks and instructions.
1762 * The block-enumeration is unordered!
1763 * We do not really use the block enumreation, however
1764 * the instruction enumeration is important for life-ranges.
1766 void ir_function_enumerate(ir_function *self)
1769 size_t instruction_id = 0;
1770 for (i = 0; i < self->blocks_count; ++i)
1772 self->blocks[i]->eid = i;
1773 self->blocks[i]->run_id = 0;
1774 ir_block_enumerate(self->blocks[i], &instruction_id);
1778 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1779 bool ir_function_calculate_liferanges(ir_function *self)
1787 for (i = 0; i != self->blocks_count; ++i)
1789 if (self->blocks[i]->is_return)
1791 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1799 /* Local-value allocator
1800 * After finishing creating the liferange of all values used in a function
1801 * we can allocate their global-positions.
1802 * This is the counterpart to register-allocation in register machines.
1805 MEM_VECTOR_MAKE(ir_value*, locals);
1806 MEM_VECTOR_MAKE(size_t, sizes);
1807 MEM_VECTOR_MAKE(size_t, positions);
1808 } function_allocator;
1809 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1810 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1811 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1813 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1816 size_t vsize = type_sizeof[var->vtype];
1818 slot = ir_value_var("reg", store_global, var->vtype);
1822 if (!ir_value_life_merge_into(slot, var))
1825 if (!function_allocator_locals_add(alloc, slot))
1828 if (!function_allocator_sizes_add(alloc, vsize))
1834 ir_value_delete(slot);
1838 bool ir_function_allocate_locals(ir_function *self)
1847 function_allocator alloc;
1849 if (!self->locals_count && !self->values_count)
1852 MEM_VECTOR_INIT(&alloc, locals);
1853 MEM_VECTOR_INIT(&alloc, sizes);
1854 MEM_VECTOR_INIT(&alloc, positions);
1856 for (i = 0; i < self->locals_count; ++i)
1858 if (!function_allocator_alloc(&alloc, self->locals[i]))
1862 /* Allocate a slot for any value that still exists */
1863 for (i = 0; i < self->values_count; ++i)
1865 v = self->values[i];
1870 for (a = 0; a < alloc.locals_count; ++a)
1872 slot = alloc.locals[a];
1874 if (ir_values_overlap(v, slot))
1877 if (!ir_value_life_merge_into(slot, v))
1880 /* adjust size for this slot */
1881 if (alloc.sizes[a] < type_sizeof[v->vtype])
1882 alloc.sizes[a] = type_sizeof[v->vtype];
1884 self->values[i]->code.local = a;
1887 if (a >= alloc.locals_count) {
1888 self->values[i]->code.local = alloc.locals_count;
1889 if (!function_allocator_alloc(&alloc, v))
1894 /* Adjust slot positions based on sizes */
1895 if (!function_allocator_positions_add(&alloc, 0))
1898 if (alloc.sizes_count)
1899 pos = alloc.positions[0] + alloc.sizes[0];
1902 for (i = 1; i < alloc.sizes_count; ++i)
1904 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1905 if (!function_allocator_positions_add(&alloc, pos))
1909 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1911 /* Take over the actual slot positions */
1912 for (i = 0; i < self->values_count; ++i) {
1913 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1921 for (i = 0; i < alloc.locals_count; ++i)
1922 ir_value_delete(alloc.locals[i]);
1923 MEM_VECTOR_CLEAR(&alloc, locals);
1924 MEM_VECTOR_CLEAR(&alloc, sizes);
1925 MEM_VECTOR_CLEAR(&alloc, positions);
1929 /* Get information about which operand
1930 * is read from, or written to.
1932 static void ir_op_read_write(int op, size_t *read, size_t *write)
1952 case INSTR_STOREP_F:
1953 case INSTR_STOREP_V:
1954 case INSTR_STOREP_S:
1955 case INSTR_STOREP_ENT:
1956 case INSTR_STOREP_FLD:
1957 case INSTR_STOREP_FNC:
1968 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1971 bool changed = false;
1973 for (i = 0; i != self->living_count; ++i)
1975 tempbool = ir_value_life_merge(self->living[i], eid);
1978 irerror(self->context, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1980 changed = changed || tempbool;
1985 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1988 /* values which have been read in a previous iteration are now
1989 * in the "living" array even if the previous block doesn't use them.
1990 * So we have to remove whatever does not exist in the previous block.
1991 * They will be re-added on-read, but the liferange merge won't cause
1994 for (i = 0; i < self->living_count; ++i)
1996 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1997 if (!ir_block_living_remove(self, i))
2003 /* Whatever the previous block still has in its living set
2004 * must now be added to ours as well.
2006 for (i = 0; i < prev->living_count; ++i)
2008 if (ir_block_living_find(self, prev->living[i], NULL))
2010 if (!ir_block_living_add(self, prev->living[i]))
2013 irerror(self->contextt from prev: %s\n", self->label, prev->living[i]->_name);
2019 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2025 /* bitmasks which operands are read from or written to */
2027 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2029 new_reads_t new_reads;
2031 char dbg_ind[16] = { '#', '0' };
2034 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2035 MEM_VECTOR_INIT(&new_reads, v);
2040 if (!ir_block_life_prop_previous(self, prev, changed))
2044 i = self->instr_count;
2047 instr = self->instr[i];
2049 /* PHI operands are always read operands */
2050 for (p = 0; p < instr->phi_count; ++p)
2052 value = instr->phi[p].value;
2053 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2054 if (!ir_block_living_find(self, value, NULL) &&
2055 !ir_block_living_add(self, value))
2060 if (!new_reads_t_v_find(&new_reads, value, NULL))
2062 if (!new_reads_t_v_add(&new_reads, value))
2068 /* call params are read operands too */
2069 for (p = 0; p < instr->params_count; ++p)
2071 value = instr->params[p];
2072 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2073 if (!ir_block_living_find(self, value, NULL) &&
2074 !ir_block_living_add(self, value))
2079 if (!new_reads_t_v_find(&new_reads, value, NULL))
2081 if (!new_reads_t_v_add(&new_reads, value))
2087 /* See which operands are read and write operands */
2088 ir_op_read_write(instr->opcode, &read, &write);
2090 /* Go through the 3 main operands */
2091 for (o = 0; o < 3; ++o)
2093 if (!instr->_ops[o]) /* no such operand */
2096 value = instr->_ops[o];
2098 /* We only care about locals */
2099 /* we also calculate parameter liferanges so that locals
2100 * can take up parameter slots */
2101 if (value->store != store_value &&
2102 value->store != store_local &&
2103 value->store != store_param)
2109 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2110 if (!ir_block_living_find(self, value, NULL) &&
2111 !ir_block_living_add(self, value))
2116 /* fprintf(stderr, "read: %s\n", value->_name); */
2117 if (!new_reads_t_v_find(&new_reads, value, NULL))
2119 if (!new_reads_t_v_add(&new_reads, value))
2125 /* write operands */
2126 /* When we write to a local, we consider it "dead" for the
2127 * remaining upper part of the function, since in SSA a value
2128 * can only be written once (== created)
2133 bool in_living = ir_block_living_find(self, value, &idx);
2134 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2136 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2137 if (!in_living && !in_reads)
2142 /* If the value isn't alive it hasn't been read before... */
2143 /* TODO: See if the warning can be emitted during parsing or AST processing
2144 * otherwise have warning printed here.
2145 * IF printing a warning here: include filecontext_t,
2146 * and make sure it's only printed once
2147 * since this function is run multiple times.
2149 /* For now: debug info: */
2150 /* fprintf(stderr, "Value only written %s\n", value->name); */
2151 tempbool = ir_value_life_merge(value, instr->eid);
2152 *changed = *changed || tempbool;
2154 ir_instr_dump(instr, dbg_ind, printf);
2158 /* since 'living' won't contain it
2159 * anymore, merge the value, since
2162 tempbool = ir_value_life_merge(value, instr->eid);
2165 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2167 *changed = *changed || tempbool;
2169 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2170 if (!ir_block_living_remove(self, idx))
2175 if (!new_reads_t_v_remove(&new_reads, readidx))
2183 tempbool = ir_block_living_add_instr(self, instr->eid);
2184 /*fprintf(stderr, "living added values\n");*/
2185 *changed = *changed || tempbool;
2187 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2189 for (rd = 0; rd < new_reads.v_count; ++rd)
2191 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2192 if (!ir_block_living_add(self, new_reads.v[rd]))
2195 if (!i && !self->entries_count) {
2197 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2200 MEM_VECTOR_CLEAR(&new_reads, v);
2204 if (self->run_id == self->owner->run_id)
2207 self->run_id = self->owner->run_id;
2209 for (i = 0; i < self->entries_count; ++i)
2211 ir_block *entry = self->entries[i];
2212 ir_block_life_propagate(entry, self, changed);
2217 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2218 MEM_VECTOR_CLEAR(&new_reads, v);
2223 /***********************************************************************
2226 * Since the IR has the convention of putting 'write' operands
2227 * at the beginning, we have to rotate the operands of instructions
2228 * properly in order to generate valid QCVM code.
2230 * Having destinations at a fixed position is more convenient. In QC
2231 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2232 * read from from OPA, and store to OPB rather than OPC. Which is
2233 * partially the reason why the implementation of these instructions
2234 * in darkplaces has been delayed for so long.
2236 * Breaking conventions is annoying...
2238 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2240 static bool gen_global_field(ir_value *global)
2242 if (global->isconst)
2244 ir_value *fld = global->constval.vpointer;
2246 irerror(global->context, "Invalid field constant with no field: %s\n", global->name);
2250 /* Now, in this case, a relocation would be impossible to code
2251 * since it looks like this:
2252 * .vector v = origin; <- parse error, wtf is 'origin'?
2255 * But we will need a general relocation support later anyway
2256 * for functions... might as well support that here.
2258 if (!fld->code.globaladdr) {
2259 irerror(global->context, "FIXME: Relocation support\n");
2263 /* copy the field's value */
2264 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2265 if (global->fieldtype == TYPE_VECTOR) {
2266 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2267 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2272 ir_value_code_setaddr(global, code_globals_add(0));
2273 if (global->fieldtype == TYPE_VECTOR) {
2274 code_globals_add(0);
2275 code_globals_add(0);
2278 if (global->code.globaladdr < 0)
2283 static bool gen_global_pointer(ir_value *global)
2285 if (global->isconst)
2287 ir_value *target = global->constval.vpointer;
2289 irerror(global->context, "Invalid pointer constant: %s\n", global->name);
2290 /* NULL pointers are pointing to the NULL constant, which also
2291 * sits at address 0, but still has an ir_value for itself.
2296 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2297 * void() foo; <- proto
2298 * void() *fooptr = &foo;
2299 * void() foo = { code }
2301 if (!target->code.globaladdr) {
2302 /* FIXME: Check for the constant nullptr ir_value!
2303 * because then code.globaladdr being 0 is valid.
2305 irerror(global->context, "FIXME: Relocation support\n");
2309 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2313 ir_value_code_setaddr(global, code_globals_add(0));
2315 if (global->code.globaladdr < 0)
2320 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2322 prog_section_statement stmt;
2331 block->generated = true;
2332 block->code_start = code_statements_elements;
2333 for (i = 0; i < block->instr_count; ++i)
2335 instr = block->instr[i];
2337 if (instr->opcode == VINSTR_PHI) {
2338 irerror(block->context, "cannot generate virtual instruction (phi)\n");
2342 if (instr->opcode == VINSTR_JUMP) {
2343 target = instr->bops[0];
2344 /* for uncoditional jumps, if the target hasn't been generated
2345 * yet, we generate them right here.
2347 if (!target->generated) {
2352 /* otherwise we generate a jump instruction */
2353 stmt.opcode = INSTR_GOTO;
2354 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2357 if (code_statements_add(stmt) < 0)
2360 /* no further instructions can be in this block */
2364 if (instr->opcode == VINSTR_COND) {
2365 ontrue = instr->bops[0];
2366 onfalse = instr->bops[1];
2367 /* TODO: have the AST signal which block should
2368 * come first: eg. optimize IFs without ELSE...
2371 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2375 if (ontrue->generated) {
2376 stmt.opcode = INSTR_IF;
2377 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2378 if (code_statements_add(stmt) < 0)
2381 if (onfalse->generated) {
2382 stmt.opcode = INSTR_IFNOT;
2383 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2384 if (code_statements_add(stmt) < 0)
2387 if (!ontrue->generated) {
2388 if (onfalse->generated) {
2393 if (!onfalse->generated) {
2394 if (ontrue->generated) {
2399 /* neither ontrue nor onfalse exist */
2400 stmt.opcode = INSTR_IFNOT;
2401 stidx = code_statements_elements;
2402 if (code_statements_add(stmt) < 0)
2404 /* on false we jump, so add ontrue-path */
2405 if (!gen_blocks_recursive(func, ontrue))
2407 /* fixup the jump address */
2408 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2409 /* generate onfalse path */
2410 if (onfalse->generated) {
2411 /* fixup the jump address */
2412 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2413 /* may have been generated in the previous recursive call */
2414 stmt.opcode = INSTR_GOTO;
2415 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2418 return (code_statements_add(stmt) >= 0);
2420 /* if not, generate now */
2425 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2426 /* Trivial call translation:
2427 * copy all params to OFS_PARM*
2428 * if the output's storetype is not store_return,
2429 * add append a STORE instruction!
2431 * NOTES on how to do it better without much trouble:
2432 * -) The liferanges!
2433 * Simply check the liferange of all parameters for
2434 * other CALLs. For each param with no CALL in its
2435 * liferange, we can store it in an OFS_PARM at
2436 * generation already. This would even include later
2437 * reuse.... probably... :)
2442 for (p = 0; p < instr->params_count; ++p)
2444 ir_value *param = instr->params[p];
2446 stmt.opcode = INSTR_STORE_F;
2449 stmt.opcode = type_store_instr[param->vtype];
2450 stmt.o1.u1 = ir_value_code_addr(param);
2451 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2452 if (code_statements_add(stmt) < 0)
2455 stmt.opcode = INSTR_CALL0 + instr->params_count;
2456 if (stmt.opcode > INSTR_CALL8)
2457 stmt.opcode = INSTR_CALL8;
2458 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2461 if (code_statements_add(stmt) < 0)
2464 retvalue = instr->_ops[0];
2465 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2467 /* not to be kept in OFS_RETURN */
2468 stmt.opcode = type_store_instr[retvalue->vtype];
2469 stmt.o1.u1 = OFS_RETURN;
2470 stmt.o2.u1 = ir_value_code_addr(retvalue);
2472 if (code_statements_add(stmt) < 0)
2478 if (instr->opcode == INSTR_STATE) {
2479 irerror(block->context, "TODO: state instruction\n");
2483 stmt.opcode = instr->opcode;
2488 /* This is the general order of operands */
2490 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2493 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2496 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2498 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2500 stmt.o1.u1 = stmt.o3.u1;
2503 else if ((stmt.opcode >= INSTR_STORE_F &&
2504 stmt.opcode <= INSTR_STORE_FNC) ||
2505 (stmt.opcode >= INSTR_STOREP_F &&
2506 stmt.opcode <= INSTR_STOREP_FNC))
2508 /* 2-operand instructions with A -> B */
2509 stmt.o2.u1 = stmt.o3.u1;
2513 if (code_statements_add(stmt) < 0)
2519 static bool gen_function_code(ir_function *self)
2522 prog_section_statement stmt;
2524 /* Starting from entry point, we generate blocks "as they come"
2525 * for now. Dead blocks will not be translated obviously.
2527 if (!self->blocks_count) {
2528 irerror(self->context, "Function '%s' declared without body.\n", self->name);
2532 block = self->blocks[0];
2533 if (block->generated)
2536 if (!gen_blocks_recursive(self, block)) {
2537 irerror(self->context, "failed to generate blocks for '%s'\n", self->name);
2541 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2542 stmt.opcode = AINSTR_END;
2546 if (code_statements_add(stmt) < 0)
2551 static bool gen_global_function(ir_builder *ir, ir_value *global)
2553 prog_section_function fun;
2557 size_t local_var_end;
2559 if (!global->isconst || (!global->constval.vfunc))
2561 irerror(global->context, "Invalid state of function-global: not constant: %s\n", global->name);
2565 irfun = global->constval.vfunc;
2567 fun.name = global->code.name;
2568 fun.file = code_cachedstring(global->context.file);
2569 fun.profile = 0; /* always 0 */
2570 fun.nargs = irfun->params_count;
2572 for (i = 0;i < 8; ++i) {
2576 fun.argsize[i] = type_sizeof[irfun->params[i]];
2579 fun.firstlocal = code_globals_elements;
2580 fun.locals = irfun->allocated_locals + irfun->locals_count;
2582 local_var_end = fun.firstlocal;
2583 for (i = 0; i < irfun->locals_count; ++i) {
2584 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2585 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2589 if (irfun->locals_count) {
2590 ir_value *last = irfun->locals[irfun->locals_count-1];
2591 local_var_end = last->code.globaladdr;
2592 local_var_end += type_sizeof[last->vtype];
2594 for (i = 0; i < irfun->values_count; ++i)
2596 /* generate code.globaladdr for ssa values */
2597 ir_value *v = irfun->values[i];
2598 ir_value_code_setaddr(v, local_var_end + v->code.local);
2600 for (i = 0; i < irfun->allocated_locals; ++i) {
2601 /* fill the locals with zeros */
2602 code_globals_add(0);
2606 fun.entry = irfun->builtin;
2608 irfun->code_function_def = code_functions_elements;
2609 fun.entry = code_statements_elements;
2610 /* done in second pass: gen_global_function_code!
2611 if (!gen_function_code(irfun)) {
2612 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2618 return (code_functions_add(fun) >= 0);
2621 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2623 prog_section_function *fundef;
2626 irfun = global->constval.vfunc;
2630 if (irfun->code_function_def < 0) {
2631 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2634 fundef = &code_functions_data[irfun->code_function_def];
2636 fundef->entry = code_statements_elements;
2637 if (!gen_function_code(irfun)) {
2638 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2644 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2648 prog_section_def def;
2650 def.type = global->vtype;
2651 def.offset = code_globals_elements;
2652 def.name = global->code.name = code_genstring(global->name);
2654 switch (global->vtype)
2657 if (code_defs_add(def) < 0)
2659 return gen_global_pointer(global);
2661 if (code_defs_add(def) < 0)
2663 return gen_global_field(global);
2668 if (code_defs_add(def) < 0)
2671 if (global->isconst) {
2672 iptr = (int32_t*)&global->constval.vfloat;
2673 ir_value_code_setaddr(global, code_globals_add(*iptr));
2675 ir_value_code_setaddr(global, code_globals_add(0));
2677 return global->code.globaladdr >= 0;
2681 if (code_defs_add(def) < 0)
2683 if (global->isconst)
2684 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2686 ir_value_code_setaddr(global, code_globals_add(0));
2687 return global->code.globaladdr >= 0;
2692 if (code_defs_add(def) < 0)
2695 if (global->isconst) {
2696 iptr = (int32_t*)&global->constval.vvec;
2697 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2698 if (global->code.globaladdr < 0)
2700 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2702 if (code_globals_add(iptr[d]) < 0)
2706 ir_value_code_setaddr(global, code_globals_add(0));
2707 if (global->code.globaladdr < 0)
2709 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2711 if (code_globals_add(0) < 0)
2715 return global->code.globaladdr >= 0;
2718 if (code_defs_add(def) < 0)
2720 ir_value_code_setaddr(global, code_globals_elements);
2721 code_globals_add(code_functions_elements);
2722 return gen_global_function(self, global);
2724 /* assume biggest type */
2725 ir_value_code_setaddr(global, code_globals_add(0));
2726 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2727 code_globals_add(0);
2730 /* refuse to create 'void' type or any other fancy business. */
2731 irerror(global->context, "Invalid type for global variable %s\n", global->name);
2736 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2738 prog_section_def def;
2739 prog_section_field fld;
2741 def.type = field->vtype;
2742 def.offset = code_globals_elements;
2744 /* create a global named the same as the field */
2745 if (opts_standard == COMPILER_GMQCC) {
2746 /* in our standard, the global gets a dot prefix */
2747 size_t len = strlen(field->name);
2750 /* we really don't want to have to allocate this, and 1024
2751 * bytes is more than enough for a variable/field name
2753 if (len+2 >= sizeof(name)) {
2754 irerror(field->context, "invalid field name size: %u\n", (unsigned int)len);
2759 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2762 def.name = code_genstring(name);
2763 fld.name = def.name + 1; /* we reuse that string table entry */
2765 /* in plain QC, there cannot be a global with the same name,
2766 * and so we also name the global the same.
2767 * FIXME: fteqcc should create a global as well
2768 * check if it actually uses the same name. Probably does
2770 def.name = code_genstring(field->name);
2771 fld.name = def.name;
2774 field->code.name = def.name;
2776 if (code_defs_add(def) < 0)
2779 fld.type = field->fieldtype;
2781 if (fld.type == TYPE_VOID) {
2782 irerror(field->context, "field is missing a type: %s - don't know its size\n", field->name);
2786 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2788 if (code_fields_add(fld) < 0)
2791 ir_value_code_setaddr(field, code_globals_elements);
2792 if (!code_globals_add(fld.offset))
2794 if (fld.type == TYPE_VECTOR) {
2795 if (!code_globals_add(fld.offset+1))
2797 if (!code_globals_add(fld.offset+2))
2801 return field->code.globaladdr >= 0;
2804 bool ir_builder_generate(ir_builder *self, const char *filename)
2810 for (i = 0; i < self->fields_count; ++i)
2812 if (!ir_builder_gen_field(self, self->fields[i])) {
2817 for (i = 0; i < self->globals_count; ++i)
2819 if (!ir_builder_gen_global(self, self->globals[i])) {
2824 /* generate function code */
2825 for (i = 0; i < self->globals_count; ++i)
2827 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2828 if (!gen_global_function_code(self, self->globals[i])) {
2834 printf("writing '%s'...\n", filename);
2835 return code_write(filename);
2838 /***********************************************************************
2839 *IR DEBUG Dump functions...
2842 #define IND_BUFSZ 1024
2845 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2847 # define strncat strncat
2850 const char *qc_opname(int op)
2852 if (op < 0) return "<INVALID>";
2853 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2854 return asm_instr[op].m;
2856 case VINSTR_PHI: return "PHI";
2857 case VINSTR_JUMP: return "JUMP";
2858 case VINSTR_COND: return "COND";
2859 default: return "<UNK>";
2863 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2866 char indent[IND_BUFSZ];
2870 oprintf("module %s\n", b->name);
2871 for (i = 0; i < b->globals_count; ++i)
2874 if (b->globals[i]->isconst)
2875 oprintf("%s = ", b->globals[i]->name);
2876 ir_value_dump(b->globals[i], oprintf);
2879 for (i = 0; i < b->functions_count; ++i)
2880 ir_function_dump(b->functions[i], indent, oprintf);
2881 oprintf("endmodule %s\n", b->name);
2884 void ir_function_dump(ir_function *f, char *ind,
2885 int (*oprintf)(const char*, ...))
2888 if (f->builtin != 0) {
2889 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2892 oprintf("%sfunction %s\n", ind, f->name);
2893 strncat(ind, "\t", IND_BUFSZ);
2894 if (f->locals_count)
2896 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2897 for (i = 0; i < f->locals_count; ++i) {
2898 oprintf("%s\t", ind);
2899 ir_value_dump(f->locals[i], oprintf);
2903 if (f->blocks_count)
2905 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2906 for (i = 0; i < f->blocks_count; ++i) {
2907 if (f->blocks[i]->run_id != f->run_id) {
2908 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2910 ir_block_dump(f->blocks[i], ind, oprintf);
2914 ind[strlen(ind)-1] = 0;
2915 oprintf("%sendfunction %s\n", ind, f->name);
2918 void ir_block_dump(ir_block* b, char *ind,
2919 int (*oprintf)(const char*, ...))
2922 oprintf("%s:%s\n", ind, b->label);
2923 strncat(ind, "\t", IND_BUFSZ);
2925 for (i = 0; i < b->instr_count; ++i)
2926 ir_instr_dump(b->instr[i], ind, oprintf);
2927 ind[strlen(ind)-1] = 0;
2930 void dump_phi(ir_instr *in, char *ind,
2931 int (*oprintf)(const char*, ...))
2934 oprintf("%s <- phi ", in->_ops[0]->name);
2935 for (i = 0; i < in->phi_count; ++i)
2937 oprintf("([%s] : %s) ", in->phi[i].from->label,
2938 in->phi[i].value->name);
2943 void ir_instr_dump(ir_instr *in, char *ind,
2944 int (*oprintf)(const char*, ...))
2947 const char *comma = NULL;
2949 oprintf("%s (%i) ", ind, (int)in->eid);
2951 if (in->opcode == VINSTR_PHI) {
2952 dump_phi(in, ind, oprintf);
2956 strncat(ind, "\t", IND_BUFSZ);
2958 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2959 ir_value_dump(in->_ops[0], oprintf);
2960 if (in->_ops[1] || in->_ops[2])
2963 if (in->opcode == INSTR_CALL0) {
2964 oprintf("CALL%i\t", in->params_count);
2966 oprintf("%s\t", qc_opname(in->opcode));
2968 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2969 ir_value_dump(in->_ops[0], oprintf);
2974 for (i = 1; i != 3; ++i) {
2978 ir_value_dump(in->_ops[i], oprintf);
2986 oprintf("[%s]", in->bops[0]->label);
2990 oprintf("%s[%s]", comma, in->bops[1]->label);
2992 ind[strlen(ind)-1] = 0;
2995 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3004 oprintf("(function)");
3007 oprintf("%g", v->constval.vfloat);
3010 oprintf("'%g %g %g'",
3013 v->constval.vvec.z);
3016 oprintf("(entity)");
3019 oprintf("\"%s\"", v->constval.vstring);
3023 oprintf("%i", v->constval.vint);
3028 v->constval.vpointer->name);
3032 oprintf("%s", v->name);
3036 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
3039 oprintf("Life of %s:\n", self->name);
3040 for (i = 0; i < self->life_count; ++i)
3042 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);