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 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
139 int lvl = LVL_WARNING;
141 if (!OPTS_WARN(warntype))
148 vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
154 /***********************************************************************
158 ir_builder* ir_builder_new(const char *modulename)
162 self = (ir_builder*)mem_a(sizeof(*self));
166 MEM_VECTOR_INIT(self, functions);
167 MEM_VECTOR_INIT(self, globals);
168 MEM_VECTOR_INIT(self, fields);
170 if (!ir_builder_set_name(self, modulename)) {
175 /* globals which always exist */
177 /* for now we give it a vector size */
178 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
183 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
184 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
185 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
187 void ir_builder_delete(ir_builder* self)
190 mem_d((void*)self->name);
191 for (i = 0; i != self->functions_count; ++i) {
192 ir_function_delete(self->functions[i]);
194 MEM_VECTOR_CLEAR(self, functions);
195 for (i = 0; i != self->globals_count; ++i) {
196 ir_value_delete(self->globals[i]);
198 MEM_VECTOR_CLEAR(self, globals);
199 for (i = 0; i != self->fields_count; ++i) {
200 ir_value_delete(self->fields[i]);
202 MEM_VECTOR_CLEAR(self, fields);
206 bool ir_builder_set_name(ir_builder *self, const char *name)
209 mem_d((void*)self->name);
210 self->name = util_strdup(name);
214 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
217 for (i = 0; i < self->functions_count; ++i) {
218 if (!strcmp(name, self->functions[i]->name))
219 return self->functions[i];
224 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
226 ir_function *fn = ir_builder_get_function(self, name);
231 fn = ir_function_new(self, outtype);
232 if (!ir_function_set_name(fn, name) ||
233 !ir_builder_functions_add(self, fn) )
235 ir_function_delete(fn);
239 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
241 ir_function_delete(fn);
245 fn->value->isconst = true;
246 fn->value->outtype = outtype;
247 fn->value->constval.vfunc = fn;
248 fn->value->context = fn->context;
253 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
256 for (i = 0; i < self->globals_count; ++i) {
257 if (!strcmp(self->globals[i]->name, name))
258 return self->globals[i];
263 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
267 if (name && name[0] != '#')
269 ve = ir_builder_get_global(self, name);
275 ve = ir_value_var(name, store_global, vtype);
276 if (!ir_builder_globals_add(self, ve)) {
283 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
286 for (i = 0; i < self->fields_count; ++i) {
287 if (!strcmp(self->fields[i]->name, name))
288 return self->fields[i];
294 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
296 ir_value *ve = ir_builder_get_field(self, name);
301 ve = ir_value_var(name, store_global, TYPE_FIELD);
302 ve->fieldtype = vtype;
303 if (!ir_builder_fields_add(self, ve)) {
310 /***********************************************************************
314 bool ir_function_naive_phi(ir_function*);
315 void ir_function_enumerate(ir_function*);
316 bool ir_function_calculate_liferanges(ir_function*);
317 bool ir_function_allocate_locals(ir_function*);
319 ir_function* ir_function_new(ir_builder* owner, int outtype)
322 self = (ir_function*)mem_a(sizeof(*self));
327 memset(self, 0, sizeof(*self));
330 if (!ir_function_set_name(self, "<@unnamed>")) {
335 self->context.file = "<@no context>";
336 self->context.line = 0;
337 self->outtype = outtype;
340 MEM_VECTOR_INIT(self, params);
341 MEM_VECTOR_INIT(self, blocks);
342 MEM_VECTOR_INIT(self, values);
343 MEM_VECTOR_INIT(self, locals);
345 self->code_function_def = -1;
346 self->allocated_locals = 0;
351 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
352 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
353 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
354 MEM_VEC_FUNCTIONS(ir_function, int, params)
356 bool ir_function_set_name(ir_function *self, const char *name)
359 mem_d((void*)self->name);
360 self->name = util_strdup(name);
364 void ir_function_delete(ir_function *self)
367 mem_d((void*)self->name);
369 for (i = 0; i != self->blocks_count; ++i)
370 ir_block_delete(self->blocks[i]);
371 MEM_VECTOR_CLEAR(self, blocks);
373 MEM_VECTOR_CLEAR(self, params);
375 for (i = 0; i != self->values_count; ++i)
376 ir_value_delete(self->values[i]);
377 MEM_VECTOR_CLEAR(self, values);
379 for (i = 0; i != self->locals_count; ++i)
380 ir_value_delete(self->locals[i]);
381 MEM_VECTOR_CLEAR(self, locals);
383 /* self->value is deleted by the builder */
388 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
390 return ir_function_values_add(self, v);
393 ir_block* ir_function_create_block(ir_function *self, const char *label)
395 ir_block* bn = ir_block_new(self, label);
396 memcpy(&bn->context, &self->context, sizeof(self->context));
397 if (!ir_function_blocks_add(self, bn)) {
404 bool ir_function_finalize(ir_function *self)
409 if (!ir_function_naive_phi(self))
412 ir_function_enumerate(self);
414 if (!ir_function_calculate_liferanges(self))
417 if (!ir_function_allocate_locals(self))
422 ir_value* ir_function_get_local(ir_function *self, const char *name)
425 for (i = 0; i < self->locals_count; ++i) {
426 if (!strcmp(self->locals[i]->name, name))
427 return self->locals[i];
432 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
434 ir_value *ve = ir_function_get_local(self, name);
440 self->locals_count &&
441 self->locals[self->locals_count-1]->store != store_param) {
442 irerror(self->context, "cannot add parameters after adding locals");
446 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
447 if (!ir_function_locals_add(self, ve)) {
454 /***********************************************************************
458 ir_block* ir_block_new(ir_function* owner, const char *name)
461 self = (ir_block*)mem_a(sizeof(*self));
465 memset(self, 0, sizeof(*self));
468 if (!ir_block_set_label(self, name)) {
473 self->context.file = "<@no context>";
474 self->context.line = 0;
476 MEM_VECTOR_INIT(self, instr);
477 MEM_VECTOR_INIT(self, entries);
478 MEM_VECTOR_INIT(self, exits);
481 self->is_return = false;
483 MEM_VECTOR_INIT(self, living);
485 self->generated = false;
489 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
490 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
491 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
492 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
494 void ir_block_delete(ir_block* self)
498 for (i = 0; i != self->instr_count; ++i)
499 ir_instr_delete(self->instr[i]);
500 MEM_VECTOR_CLEAR(self, instr);
501 MEM_VECTOR_CLEAR(self, entries);
502 MEM_VECTOR_CLEAR(self, exits);
503 MEM_VECTOR_CLEAR(self, living);
507 bool ir_block_set_label(ir_block *self, const char *name)
510 mem_d((void*)self->label);
511 self->label = util_strdup(name);
512 return !!self->label;
515 /***********************************************************************
519 ir_instr* ir_instr_new(ir_block* owner, int op)
522 self = (ir_instr*)mem_a(sizeof(*self));
527 self->context.file = "<@no context>";
528 self->context.line = 0;
530 self->_ops[0] = NULL;
531 self->_ops[1] = NULL;
532 self->_ops[2] = NULL;
533 self->bops[0] = NULL;
534 self->bops[1] = NULL;
535 MEM_VECTOR_INIT(self, phi);
536 MEM_VECTOR_INIT(self, params);
541 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
542 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
544 void ir_instr_delete(ir_instr *self)
547 /* The following calls can only delete from
548 * vectors, we still want to delete this instruction
549 * so ignore the return value. Since with the warn_unused_result attribute
550 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
551 * I have to improvise here and use if(foo());
553 for (i = 0; i < self->phi_count; ++i) {
555 if (ir_value_writes_find(self->phi[i].value, self, &idx))
556 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
557 if (ir_value_reads_find(self->phi[i].value, self, &idx))
558 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
560 MEM_VECTOR_CLEAR(self, phi);
561 for (i = 0; i < self->params_count; ++i) {
563 if (ir_value_writes_find(self->params[i], self, &idx))
564 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
565 if (ir_value_reads_find(self->params[i], self, &idx))
566 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
568 MEM_VECTOR_CLEAR(self, params);
569 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
570 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
571 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
575 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
577 if (self->_ops[op]) {
579 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
581 if (!ir_value_writes_remove(self->_ops[op], idx))
584 else if (ir_value_reads_find(self->_ops[op], self, &idx))
586 if (!ir_value_reads_remove(self->_ops[op], idx))
592 if (!ir_value_writes_add(v, self))
595 if (!ir_value_reads_add(v, self))
603 /***********************************************************************
607 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
609 self->code.globaladdr = gaddr;
610 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
611 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
612 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
615 int32_t ir_value_code_addr(const ir_value *self)
617 if (self->store == store_return)
618 return OFS_RETURN + self->code.addroffset;
619 return self->code.globaladdr + self->code.addroffset;
622 ir_value* ir_value_var(const char *name, int storetype, int vtype)
625 self = (ir_value*)mem_a(sizeof(*self));
627 self->fieldtype = TYPE_VOID;
628 self->outtype = TYPE_VOID;
629 self->store = storetype;
630 MEM_VECTOR_INIT(self, reads);
631 MEM_VECTOR_INIT(self, writes);
632 self->isconst = false;
633 self->context.file = "<@no context>";
634 self->context.line = 0;
636 ir_value_set_name(self, name);
638 memset(&self->constval, 0, sizeof(self->constval));
639 memset(&self->code, 0, sizeof(self->code));
641 self->members[0] = NULL;
642 self->members[1] = NULL;
643 self->members[2] = NULL;
645 MEM_VECTOR_INIT(self, life);
649 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
655 if (self->members[member])
656 return self->members[member];
658 if (self->vtype == TYPE_VECTOR)
660 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
663 m->context = self->context;
665 self->members[member] = m;
666 m->code.addroffset = member;
668 else if (self->vtype == TYPE_FIELD)
670 if (self->fieldtype != TYPE_VECTOR)
672 m = ir_value_var(self->name, self->store, TYPE_FIELD);
675 m->fieldtype = TYPE_FLOAT;
676 m->context = self->context;
678 self->members[member] = m;
679 m->code.addroffset = member;
683 irerror(self->context, "invalid member access on %s", self->name);
690 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
691 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
692 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
694 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
696 ir_value *v = ir_value_var(name, storetype, vtype);
699 if (!ir_function_collect_value(owner, v))
707 void ir_value_delete(ir_value* self)
711 mem_d((void*)self->name);
714 if (self->vtype == TYPE_STRING)
715 mem_d((void*)self->constval.vstring);
717 for (i = 0; i < 3; ++i) {
718 if (self->members[i])
719 ir_value_delete(self->members[i]);
721 MEM_VECTOR_CLEAR(self, reads);
722 MEM_VECTOR_CLEAR(self, writes);
723 MEM_VECTOR_CLEAR(self, life);
727 void ir_value_set_name(ir_value *self, const char *name)
730 mem_d((void*)self->name);
731 self->name = util_strdup(name);
734 bool ir_value_set_float(ir_value *self, float f)
736 if (self->vtype != TYPE_FLOAT)
738 self->constval.vfloat = f;
739 self->isconst = true;
743 bool ir_value_set_func(ir_value *self, int f)
745 if (self->vtype != TYPE_FUNCTION)
747 self->constval.vint = f;
748 self->isconst = true;
752 bool ir_value_set_vector(ir_value *self, vector v)
754 if (self->vtype != TYPE_VECTOR)
756 self->constval.vvec = v;
757 self->isconst = true;
761 bool ir_value_set_field(ir_value *self, ir_value *fld)
763 if (self->vtype != TYPE_FIELD)
765 self->constval.vpointer = fld;
766 self->isconst = true;
770 static char *ir_strdup(const char *str)
773 /* actually dup empty strings */
774 char *out = mem_a(1);
778 return util_strdup(str);
781 bool ir_value_set_string(ir_value *self, const char *str)
783 if (self->vtype != TYPE_STRING)
785 self->constval.vstring = ir_strdup(str);
786 self->isconst = true;
791 bool ir_value_set_int(ir_value *self, int i)
793 if (self->vtype != TYPE_INTEGER)
795 self->constval.vint = i;
796 self->isconst = true;
801 bool ir_value_lives(ir_value *self, size_t at)
804 for (i = 0; i < self->life_count; ++i)
806 ir_life_entry_t *life = &self->life[i];
807 if (life->start <= at && at <= life->end)
809 if (life->start > at) /* since it's ordered */
815 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
818 if (!ir_value_life_add(self, e)) /* naive... */
820 for (k = self->life_count-1; k > idx; --k)
821 self->life[k] = self->life[k-1];
826 bool ir_value_life_merge(ir_value *self, size_t s)
829 ir_life_entry_t *life = NULL;
830 ir_life_entry_t *before = NULL;
831 ir_life_entry_t new_entry;
833 /* Find the first range >= s */
834 for (i = 0; i < self->life_count; ++i)
837 life = &self->life[i];
841 /* nothing found? append */
842 if (i == self->life_count) {
844 if (life && life->end+1 == s)
846 /* previous life range can be merged in */
850 if (life && life->end >= s)
853 if (!ir_value_life_add(self, e))
854 return false; /* failing */
860 if (before->end + 1 == s &&
861 life->start - 1 == s)
864 before->end = life->end;
865 if (!ir_value_life_remove(self, i))
866 return false; /* failing */
869 if (before->end + 1 == s)
875 /* already contained */
876 if (before->end >= s)
880 if (life->start - 1 == s)
885 /* insert a new entry */
886 new_entry.start = new_entry.end = s;
887 return ir_value_life_insert(self, i, new_entry);
890 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
894 if (!other->life_count)
897 if (!self->life_count) {
898 for (i = 0; i < other->life_count; ++i) {
899 if (!ir_value_life_add(self, other->life[i]))
906 for (i = 0; i < other->life_count; ++i)
908 const ir_life_entry_t *life = &other->life[i];
911 ir_life_entry_t *entry = &self->life[myi];
913 if (life->end+1 < entry->start)
915 /* adding an interval before entry */
916 if (!ir_value_life_insert(self, myi, *life))
922 if (life->start < entry->start &&
923 life->end >= entry->start)
925 /* starts earlier and overlaps */
926 entry->start = life->start;
929 if (life->end > entry->end &&
930 life->start-1 <= entry->end)
932 /* ends later and overlaps */
933 entry->end = life->end;
936 /* see if our change combines it with the next ranges */
937 while (myi+1 < self->life_count &&
938 entry->end+1 >= self->life[1+myi].start)
940 /* overlaps with (myi+1) */
941 if (entry->end < self->life[1+myi].end)
942 entry->end = self->life[1+myi].end;
943 if (!ir_value_life_remove(self, myi+1))
945 entry = &self->life[myi];
948 /* see if we're after the entry */
949 if (life->start > entry->end)
952 /* append if we're at the end */
953 if (myi >= self->life_count) {
954 if (!ir_value_life_add(self, *life))
958 /* otherweise check the next range */
967 bool ir_values_overlap(const ir_value *a, const ir_value *b)
969 /* For any life entry in A see if it overlaps with
970 * any life entry in B.
971 * Note that the life entries are orderes, so we can make a
972 * more efficient algorithm there than naively translating the
976 ir_life_entry_t *la, *lb, *enda, *endb;
978 /* first of all, if either has no life range, they cannot clash */
979 if (!a->life_count || !b->life_count)
984 enda = la + a->life_count;
985 endb = lb + b->life_count;
988 /* check if the entries overlap, for that,
989 * both must start before the other one ends.
991 if (la->start < lb->end &&
997 /* entries are ordered
998 * one entry is earlier than the other
999 * that earlier entry will be moved forward
1001 if (la->start < lb->start)
1003 /* order: A B, move A forward
1004 * check if we hit the end with A
1009 else /* if (lb->start < la->start) actually <= */
1011 /* order: B A, move B forward
1012 * check if we hit the end with B
1021 /***********************************************************************
1025 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1027 ir_instr *in = ir_instr_new(self, op);
1031 if (target->store == store_value &&
1032 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1034 irerror(self->context, "cannot store to an SSA value");
1035 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1036 irerror(self->context, "instruction: %s", asm_instr[op].m);
1040 if (!ir_instr_op(in, 0, target, true) ||
1041 !ir_instr_op(in, 1, what, false) ||
1042 !ir_block_instr_add(self, in) )
1049 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1053 if (target->vtype == TYPE_VARIANT)
1054 vtype = what->vtype;
1056 vtype = target->vtype;
1059 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1060 op = INSTR_CONV_ITOF;
1061 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1062 op = INSTR_CONV_FTOI;
1064 op = type_store_instr[vtype];
1066 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1067 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1071 return ir_block_create_store_op(self, op, target, what);
1074 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1079 if (target->vtype != TYPE_POINTER)
1082 /* storing using pointer - target is a pointer, type must be
1083 * inferred from source
1085 vtype = what->vtype;
1087 op = type_storep_instr[vtype];
1088 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1089 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1090 op = INSTR_STOREP_V;
1093 return ir_block_create_store_op(self, op, target, what);
1096 bool ir_block_create_return(ir_block *self, ir_value *v)
1100 irerror(self->context, "block already ended (%s)", self->label);
1104 self->is_return = true;
1105 in = ir_instr_new(self, INSTR_RETURN);
1109 if (v && !ir_instr_op(in, 0, v, false))
1112 if (!ir_block_instr_add(self, in))
1117 bool ir_block_create_if(ir_block *self, ir_value *v,
1118 ir_block *ontrue, ir_block *onfalse)
1122 irerror(self->context, "block already ended (%s)", self->label);
1126 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1127 in = ir_instr_new(self, VINSTR_COND);
1131 if (!ir_instr_op(in, 0, v, false)) {
1132 ir_instr_delete(in);
1136 in->bops[0] = ontrue;
1137 in->bops[1] = onfalse;
1139 if (!ir_block_instr_add(self, in))
1142 if (!ir_block_exits_add(self, ontrue) ||
1143 !ir_block_exits_add(self, onfalse) ||
1144 !ir_block_entries_add(ontrue, self) ||
1145 !ir_block_entries_add(onfalse, self) )
1152 bool ir_block_create_jump(ir_block *self, ir_block *to)
1156 irerror(self->context, "block already ended (%s)", self->label);
1160 in = ir_instr_new(self, VINSTR_JUMP);
1165 if (!ir_block_instr_add(self, in))
1168 if (!ir_block_exits_add(self, to) ||
1169 !ir_block_entries_add(to, self) )
1176 bool ir_block_create_goto(ir_block *self, ir_block *to)
1180 irerror(self->context, "block already ended (%s)", self->label);
1184 in = ir_instr_new(self, INSTR_GOTO);
1189 if (!ir_block_instr_add(self, in))
1192 if (!ir_block_exits_add(self, to) ||
1193 !ir_block_entries_add(to, self) )
1200 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1204 in = ir_instr_new(self, VINSTR_PHI);
1207 out = ir_value_out(self->owner, label, store_value, ot);
1209 ir_instr_delete(in);
1212 if (!ir_instr_op(in, 0, out, true)) {
1213 ir_instr_delete(in);
1214 ir_value_delete(out);
1217 if (!ir_block_instr_add(self, in)) {
1218 ir_instr_delete(in);
1219 ir_value_delete(out);
1225 ir_value* ir_phi_value(ir_instr *self)
1227 return self->_ops[0];
1230 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1234 if (!ir_block_entries_find(self->owner, b, NULL)) {
1235 /* Must not be possible to cause this, otherwise the AST
1236 * is doing something wrong.
1238 irerror(self->context, "Invalid entry block for PHI");
1244 if (!ir_value_reads_add(v, self))
1246 return ir_instr_phi_add(self, pe);
1249 /* call related code */
1250 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1254 in = ir_instr_new(self, INSTR_CALL0);
1257 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1259 ir_instr_delete(in);
1262 if (!ir_instr_op(in, 0, out, true) ||
1263 !ir_instr_op(in, 1, func, false) ||
1264 !ir_block_instr_add(self, in))
1266 ir_instr_delete(in);
1267 ir_value_delete(out);
1273 ir_value* ir_call_value(ir_instr *self)
1275 return self->_ops[0];
1278 bool ir_call_param(ir_instr* self, ir_value *v)
1280 if (!ir_instr_params_add(self, v))
1282 if (!ir_value_reads_add(v, self)) {
1283 if (!ir_instr_params_remove(self, self->params_count-1))
1284 GMQCC_SUPPRESS_EMPTY_BODY;
1290 /* binary op related code */
1292 ir_value* ir_block_create_binop(ir_block *self,
1293 const char *label, int opcode,
1294 ir_value *left, ir_value *right)
1316 case INSTR_SUB_S: /* -- offset of string as float */
1321 case INSTR_BITOR_IF:
1322 case INSTR_BITOR_FI:
1323 case INSTR_BITAND_FI:
1324 case INSTR_BITAND_IF:
1339 case INSTR_BITAND_I:
1342 case INSTR_RSHIFT_I:
1343 case INSTR_LSHIFT_I:
1365 /* boolean operations result in floats */
1366 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1368 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1371 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1376 if (ot == TYPE_VOID) {
1377 /* The AST or parser were supposed to check this! */
1381 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1384 ir_value* ir_block_create_unary(ir_block *self,
1385 const char *label, int opcode,
1388 int ot = TYPE_FLOAT;
1400 /* QC doesn't have other unary operations. We expect extensions to fill
1401 * the above list, otherwise we assume out-type = in-type, eg for an
1405 ot = operand->vtype;
1408 if (ot == TYPE_VOID) {
1409 /* The AST or parser were supposed to check this! */
1413 /* let's use the general instruction creator and pass NULL for OPB */
1414 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1417 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1418 int op, ir_value *a, ir_value *b, int outype)
1423 out = ir_value_out(self->owner, label, store_value, outype);
1427 instr = ir_instr_new(self, op);
1429 ir_value_delete(out);
1433 if (!ir_instr_op(instr, 0, out, true) ||
1434 !ir_instr_op(instr, 1, a, false) ||
1435 !ir_instr_op(instr, 2, b, false) )
1440 if (!ir_block_instr_add(self, instr))
1445 ir_instr_delete(instr);
1446 ir_value_delete(out);
1450 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1454 /* Support for various pointer types todo if so desired */
1455 if (ent->vtype != TYPE_ENTITY)
1458 if (field->vtype != TYPE_FIELD)
1461 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1462 v->fieldtype = field->fieldtype;
1466 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1469 if (ent->vtype != TYPE_ENTITY)
1472 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1473 if (field->vtype != TYPE_FIELD)
1478 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1479 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1480 case TYPE_STRING: op = INSTR_LOAD_S; break;
1481 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1482 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1483 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1485 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1486 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1492 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1495 ir_value* ir_block_create_add(ir_block *self,
1497 ir_value *left, ir_value *right)
1500 int l = left->vtype;
1501 int r = right->vtype;
1520 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1522 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1528 return ir_block_create_binop(self, label, op, left, right);
1531 ir_value* ir_block_create_sub(ir_block *self,
1533 ir_value *left, ir_value *right)
1536 int l = left->vtype;
1537 int r = right->vtype;
1557 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1559 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1565 return ir_block_create_binop(self, label, op, left, right);
1568 ir_value* ir_block_create_mul(ir_block *self,
1570 ir_value *left, ir_value *right)
1573 int l = left->vtype;
1574 int r = right->vtype;
1593 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1595 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1598 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1600 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1602 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1604 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1610 return ir_block_create_binop(self, label, op, left, right);
1613 ir_value* ir_block_create_div(ir_block *self,
1615 ir_value *left, ir_value *right)
1618 int l = left->vtype;
1619 int r = right->vtype;
1636 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1638 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1640 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1646 return ir_block_create_binop(self, label, op, left, right);
1649 /* PHI resolving breaks the SSA, and must thus be the last
1650 * step before life-range calculation.
1653 static bool ir_block_naive_phi(ir_block *self);
1654 bool ir_function_naive_phi(ir_function *self)
1658 for (i = 0; i < self->blocks_count; ++i)
1660 if (!ir_block_naive_phi(self->blocks[i]))
1666 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1671 /* create a store */
1672 if (!ir_block_create_store(block, old, what))
1675 /* we now move it up */
1676 instr = block->instr[block->instr_count-1];
1677 for (i = block->instr_count; i > iid; --i)
1678 block->instr[i] = block->instr[i-1];
1679 block->instr[i] = instr;
1684 static bool ir_block_naive_phi(ir_block *self)
1687 /* FIXME: optionally, create_phi can add the phis
1688 * to a list so we don't need to loop through blocks
1689 * - anyway: "don't optimize YET"
1691 for (i = 0; i < self->instr_count; ++i)
1693 ir_instr *instr = self->instr[i];
1694 if (instr->opcode != VINSTR_PHI)
1697 if (!ir_block_instr_remove(self, i))
1699 --i; /* NOTE: i+1 below */
1701 for (p = 0; p < instr->phi_count; ++p)
1703 ir_value *v = instr->phi[p].value;
1704 for (w = 0; w < v->writes_count; ++w) {
1707 if (!v->writes[w]->_ops[0])
1710 /* When the write was to a global, we have to emit a mov */
1711 old = v->writes[w]->_ops[0];
1713 /* The original instruction now writes to the PHI target local */
1714 if (v->writes[w]->_ops[0] == v)
1715 v->writes[w]->_ops[0] = instr->_ops[0];
1717 if (old->store != store_value && old->store != store_local && old->store != store_param)
1719 /* If it originally wrote to a global we need to store the value
1722 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1724 if (i+1 < self->instr_count)
1725 instr = self->instr[i+1];
1728 /* In case I forget and access instr later, it'll be NULL
1729 * when it's a problem, to make sure we crash, rather than accessing
1735 /* If it didn't, we can replace all reads by the phi target now. */
1737 for (r = 0; r < old->reads_count; ++r)
1740 ir_instr *ri = old->reads[r];
1741 for (op = 0; op < ri->phi_count; ++op) {
1742 if (ri->phi[op].value == old)
1743 ri->phi[op].value = v;
1745 for (op = 0; op < 3; ++op) {
1746 if (ri->_ops[op] == old)
1753 ir_instr_delete(instr);
1758 /***********************************************************************
1759 *IR Temp allocation code
1760 * Propagating value life ranges by walking through the function backwards
1761 * until no more changes are made.
1762 * In theory this should happen once more than once for every nested loop
1764 * Though this implementation might run an additional time for if nests.
1773 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1775 /* Enumerate instructions used by value's life-ranges
1777 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1781 for (i = 0; i < self->instr_count; ++i)
1783 self->instr[i]->eid = eid++;
1788 /* Enumerate blocks and instructions.
1789 * The block-enumeration is unordered!
1790 * We do not really use the block enumreation, however
1791 * the instruction enumeration is important for life-ranges.
1793 void ir_function_enumerate(ir_function *self)
1796 size_t instruction_id = 0;
1797 for (i = 0; i < self->blocks_count; ++i)
1799 self->blocks[i]->eid = i;
1800 self->blocks[i]->run_id = 0;
1801 ir_block_enumerate(self->blocks[i], &instruction_id);
1805 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1806 bool ir_function_calculate_liferanges(ir_function *self)
1814 for (i = 0; i != self->blocks_count; ++i)
1816 if (self->blocks[i]->is_return)
1818 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1823 if (self->blocks_count) {
1824 ir_block *block = self->blocks[0];
1825 for (i = 0; i < block->living_count; ++i) {
1826 ir_value *v = block->living[i];
1827 if (v->name[0] == '#' || v->name[0] == '%')
1829 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1830 "variable `%s` may be used uninitialized in this function", v->name))
1839 /* Local-value allocator
1840 * After finishing creating the liferange of all values used in a function
1841 * we can allocate their global-positions.
1842 * This is the counterpart to register-allocation in register machines.
1845 MEM_VECTOR_MAKE(ir_value*, locals);
1846 MEM_VECTOR_MAKE(size_t, sizes);
1847 MEM_VECTOR_MAKE(size_t, positions);
1848 } function_allocator;
1849 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1850 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1851 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1853 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1856 size_t vsize = type_sizeof[var->vtype];
1858 slot = ir_value_var("reg", store_global, var->vtype);
1862 if (!ir_value_life_merge_into(slot, var))
1865 if (!function_allocator_locals_add(alloc, slot))
1868 if (!function_allocator_sizes_add(alloc, vsize))
1874 ir_value_delete(slot);
1878 bool ir_function_allocate_locals(ir_function *self)
1887 function_allocator alloc;
1889 if (!self->locals_count && !self->values_count)
1892 MEM_VECTOR_INIT(&alloc, locals);
1893 MEM_VECTOR_INIT(&alloc, sizes);
1894 MEM_VECTOR_INIT(&alloc, positions);
1896 for (i = 0; i < self->locals_count; ++i)
1898 if (!function_allocator_alloc(&alloc, self->locals[i]))
1902 /* Allocate a slot for any value that still exists */
1903 for (i = 0; i < self->values_count; ++i)
1905 v = self->values[i];
1910 for (a = 0; a < alloc.locals_count; ++a)
1912 slot = alloc.locals[a];
1914 if (ir_values_overlap(v, slot))
1917 if (!ir_value_life_merge_into(slot, v))
1920 /* adjust size for this slot */
1921 if (alloc.sizes[a] < type_sizeof[v->vtype])
1922 alloc.sizes[a] = type_sizeof[v->vtype];
1924 self->values[i]->code.local = a;
1927 if (a >= alloc.locals_count) {
1928 self->values[i]->code.local = alloc.locals_count;
1929 if (!function_allocator_alloc(&alloc, v))
1938 /* Adjust slot positions based on sizes */
1939 if (!function_allocator_positions_add(&alloc, 0))
1942 if (alloc.sizes_count)
1943 pos = alloc.positions[0] + alloc.sizes[0];
1946 for (i = 1; i < alloc.sizes_count; ++i)
1948 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1949 if (!function_allocator_positions_add(&alloc, pos))
1953 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1955 /* Take over the actual slot positions */
1956 for (i = 0; i < self->values_count; ++i) {
1957 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1965 for (i = 0; i < alloc.locals_count; ++i)
1966 ir_value_delete(alloc.locals[i]);
1967 MEM_VECTOR_CLEAR(&alloc, locals);
1968 MEM_VECTOR_CLEAR(&alloc, sizes);
1969 MEM_VECTOR_CLEAR(&alloc, positions);
1973 /* Get information about which operand
1974 * is read from, or written to.
1976 static void ir_op_read_write(int op, size_t *read, size_t *write)
1996 case INSTR_STOREP_F:
1997 case INSTR_STOREP_V:
1998 case INSTR_STOREP_S:
1999 case INSTR_STOREP_ENT:
2000 case INSTR_STOREP_FLD:
2001 case INSTR_STOREP_FNC:
2012 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2015 bool changed = false;
2017 for (i = 0; i != self->living_count; ++i)
2019 tempbool = ir_value_life_merge(self->living[i], eid);
2022 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2024 changed = changed || tempbool;
2029 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2032 /* values which have been read in a previous iteration are now
2033 * in the "living" array even if the previous block doesn't use them.
2034 * So we have to remove whatever does not exist in the previous block.
2035 * They will be re-added on-read, but the liferange merge won't cause
2038 for (i = 0; i < self->living_count; ++i)
2040 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2041 if (!ir_block_living_remove(self, i))
2047 /* Whatever the previous block still has in its living set
2048 * must now be added to ours as well.
2050 for (i = 0; i < prev->living_count; ++i)
2052 if (ir_block_living_find(self, prev->living[i], NULL))
2054 if (!ir_block_living_add(self, prev->living[i]))
2057 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2063 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2069 /* bitmasks which operands are read from or written to */
2071 char dbg_ind[16] = { '#', '0' };
2076 if (!ir_block_life_prop_previous(self, prev, changed))
2080 i = self->instr_count;
2083 instr = self->instr[i];
2085 /* PHI operands are always read operands */
2086 for (p = 0; p < instr->phi_count; ++p)
2088 value = instr->phi[p].value;
2089 if (!ir_block_living_find(self, value, NULL) &&
2090 !ir_block_living_add(self, value))
2096 /* call params are read operands too */
2097 for (p = 0; p < instr->params_count; ++p)
2099 value = instr->params[p];
2100 if (!ir_block_living_find(self, value, NULL) &&
2101 !ir_block_living_add(self, value))
2107 /* See which operands are read and write operands */
2108 ir_op_read_write(instr->opcode, &read, &write);
2110 /* Go through the 3 main operands */
2111 for (o = 0; o < 3; ++o)
2113 if (!instr->_ops[o]) /* no such operand */
2116 value = instr->_ops[o];
2118 /* We only care about locals */
2119 /* we also calculate parameter liferanges so that locals
2120 * can take up parameter slots */
2121 if (value->store != store_value &&
2122 value->store != store_local &&
2123 value->store != store_param)
2129 if (!ir_block_living_find(self, value, NULL) &&
2130 !ir_block_living_add(self, value))
2136 /* write operands */
2137 /* When we write to a local, we consider it "dead" for the
2138 * remaining upper part of the function, since in SSA a value
2139 * can only be written once (== created)
2144 bool in_living = ir_block_living_find(self, value, &idx);
2147 /* If the value isn't alive it hasn't been read before... */
2148 /* TODO: See if the warning can be emitted during parsing or AST processing
2149 * otherwise have warning printed here.
2150 * IF printing a warning here: include filecontext_t,
2151 * and make sure it's only printed once
2152 * since this function is run multiple times.
2154 /* For now: debug info: */
2155 /* fprintf(stderr, "Value only written %s\n", value->name); */
2156 tempbool = ir_value_life_merge(value, instr->eid);
2157 *changed = *changed || tempbool;
2159 ir_instr_dump(instr, dbg_ind, printf);
2163 /* since 'living' won't contain it
2164 * anymore, merge the value, since
2167 tempbool = ir_value_life_merge(value, instr->eid);
2170 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2172 *changed = *changed || tempbool;
2174 if (!ir_block_living_remove(self, idx))
2180 tempbool = ir_block_living_add_instr(self, instr->eid);
2181 /*fprintf(stderr, "living added values\n");*/
2182 *changed = *changed || tempbool;
2186 if (self->run_id == self->owner->run_id)
2189 self->run_id = self->owner->run_id;
2191 for (i = 0; i < self->entries_count; ++i)
2193 ir_block *entry = self->entries[i];
2194 ir_block_life_propagate(entry, self, changed);
2200 /***********************************************************************
2203 * Since the IR has the convention of putting 'write' operands
2204 * at the beginning, we have to rotate the operands of instructions
2205 * properly in order to generate valid QCVM code.
2207 * Having destinations at a fixed position is more convenient. In QC
2208 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2209 * read from from OPA, and store to OPB rather than OPC. Which is
2210 * partially the reason why the implementation of these instructions
2211 * in darkplaces has been delayed for so long.
2213 * Breaking conventions is annoying...
2215 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2217 static bool gen_global_field(ir_value *global)
2219 if (global->isconst)
2221 ir_value *fld = global->constval.vpointer;
2223 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2227 /* Now, in this case, a relocation would be impossible to code
2228 * since it looks like this:
2229 * .vector v = origin; <- parse error, wtf is 'origin'?
2232 * But we will need a general relocation support later anyway
2233 * for functions... might as well support that here.
2235 if (!fld->code.globaladdr) {
2236 irerror(global->context, "FIXME: Relocation support");
2240 /* copy the field's value */
2241 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2242 if (global->fieldtype == TYPE_VECTOR) {
2243 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2244 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2249 ir_value_code_setaddr(global, code_globals_add(0));
2250 if (global->fieldtype == TYPE_VECTOR) {
2251 code_globals_add(0);
2252 code_globals_add(0);
2255 if (global->code.globaladdr < 0)
2260 static bool gen_global_pointer(ir_value *global)
2262 if (global->isconst)
2264 ir_value *target = global->constval.vpointer;
2266 irerror(global->context, "Invalid pointer constant: %s", global->name);
2267 /* NULL pointers are pointing to the NULL constant, which also
2268 * sits at address 0, but still has an ir_value for itself.
2273 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2274 * void() foo; <- proto
2275 * void() *fooptr = &foo;
2276 * void() foo = { code }
2278 if (!target->code.globaladdr) {
2279 /* FIXME: Check for the constant nullptr ir_value!
2280 * because then code.globaladdr being 0 is valid.
2282 irerror(global->context, "FIXME: Relocation support");
2286 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2290 ir_value_code_setaddr(global, code_globals_add(0));
2292 if (global->code.globaladdr < 0)
2297 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2299 prog_section_statement stmt;
2308 block->generated = true;
2309 block->code_start = code_statements_elements;
2310 for (i = 0; i < block->instr_count; ++i)
2312 instr = block->instr[i];
2314 if (instr->opcode == VINSTR_PHI) {
2315 irerror(block->context, "cannot generate virtual instruction (phi)");
2319 if (instr->opcode == VINSTR_JUMP) {
2320 target = instr->bops[0];
2321 /* for uncoditional jumps, if the target hasn't been generated
2322 * yet, we generate them right here.
2324 if (!target->generated) {
2329 /* otherwise we generate a jump instruction */
2330 stmt.opcode = INSTR_GOTO;
2331 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2334 if (code_statements_add(stmt) < 0)
2337 /* no further instructions can be in this block */
2341 if (instr->opcode == VINSTR_COND) {
2342 ontrue = instr->bops[0];
2343 onfalse = instr->bops[1];
2344 /* TODO: have the AST signal which block should
2345 * come first: eg. optimize IFs without ELSE...
2348 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2352 if (ontrue->generated) {
2353 stmt.opcode = INSTR_IF;
2354 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2355 if (code_statements_add(stmt) < 0)
2358 if (onfalse->generated) {
2359 stmt.opcode = INSTR_IFNOT;
2360 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2361 if (code_statements_add(stmt) < 0)
2364 if (!ontrue->generated) {
2365 if (onfalse->generated) {
2370 if (!onfalse->generated) {
2371 if (ontrue->generated) {
2376 /* neither ontrue nor onfalse exist */
2377 stmt.opcode = INSTR_IFNOT;
2378 stidx = code_statements_elements;
2379 if (code_statements_add(stmt) < 0)
2381 /* on false we jump, so add ontrue-path */
2382 if (!gen_blocks_recursive(func, ontrue))
2384 /* fixup the jump address */
2385 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2386 /* generate onfalse path */
2387 if (onfalse->generated) {
2388 /* fixup the jump address */
2389 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2390 /* may have been generated in the previous recursive call */
2391 stmt.opcode = INSTR_GOTO;
2392 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2395 return (code_statements_add(stmt) >= 0);
2397 /* if not, generate now */
2402 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2403 /* Trivial call translation:
2404 * copy all params to OFS_PARM*
2405 * if the output's storetype is not store_return,
2406 * add append a STORE instruction!
2408 * NOTES on how to do it better without much trouble:
2409 * -) The liferanges!
2410 * Simply check the liferange of all parameters for
2411 * other CALLs. For each param with no CALL in its
2412 * liferange, we can store it in an OFS_PARM at
2413 * generation already. This would even include later
2414 * reuse.... probably... :)
2419 for (p = 0; p < instr->params_count; ++p)
2421 ir_value *param = instr->params[p];
2423 stmt.opcode = INSTR_STORE_F;
2426 stmt.opcode = type_store_instr[param->vtype];
2427 stmt.o1.u1 = ir_value_code_addr(param);
2428 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2429 if (code_statements_add(stmt) < 0)
2432 stmt.opcode = INSTR_CALL0 + instr->params_count;
2433 if (stmt.opcode > INSTR_CALL8)
2434 stmt.opcode = INSTR_CALL8;
2435 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2438 if (code_statements_add(stmt) < 0)
2441 retvalue = instr->_ops[0];
2442 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2444 /* not to be kept in OFS_RETURN */
2445 stmt.opcode = type_store_instr[retvalue->vtype];
2446 stmt.o1.u1 = OFS_RETURN;
2447 stmt.o2.u1 = ir_value_code_addr(retvalue);
2449 if (code_statements_add(stmt) < 0)
2455 if (instr->opcode == INSTR_STATE) {
2456 irerror(block->context, "TODO: state instruction");
2460 stmt.opcode = instr->opcode;
2465 /* This is the general order of operands */
2467 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2470 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2473 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2475 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2477 stmt.o1.u1 = stmt.o3.u1;
2480 else if ((stmt.opcode >= INSTR_STORE_F &&
2481 stmt.opcode <= INSTR_STORE_FNC) ||
2482 (stmt.opcode >= INSTR_STOREP_F &&
2483 stmt.opcode <= INSTR_STOREP_FNC))
2485 /* 2-operand instructions with A -> B */
2486 stmt.o2.u1 = stmt.o3.u1;
2490 if (code_statements_add(stmt) < 0)
2496 static bool gen_function_code(ir_function *self)
2499 prog_section_statement stmt;
2501 /* Starting from entry point, we generate blocks "as they come"
2502 * for now. Dead blocks will not be translated obviously.
2504 if (!self->blocks_count) {
2505 irerror(self->context, "Function '%s' declared without body.", self->name);
2509 block = self->blocks[0];
2510 if (block->generated)
2513 if (!gen_blocks_recursive(self, block)) {
2514 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2518 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2519 stmt.opcode = AINSTR_END;
2523 if (code_statements_add(stmt) < 0)
2528 static bool gen_global_function(ir_builder *ir, ir_value *global)
2530 prog_section_function fun;
2534 size_t local_var_end;
2536 if (!global->isconst || (!global->constval.vfunc))
2538 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2542 irfun = global->constval.vfunc;
2544 fun.name = global->code.name;
2545 fun.file = code_cachedstring(global->context.file);
2546 fun.profile = 0; /* always 0 */
2547 fun.nargs = irfun->params_count;
2549 for (i = 0;i < 8; ++i) {
2553 fun.argsize[i] = type_sizeof[irfun->params[i]];
2556 fun.firstlocal = code_globals_elements;
2557 fun.locals = irfun->allocated_locals + irfun->locals_count;
2559 local_var_end = fun.firstlocal;
2560 for (i = 0; i < irfun->locals_count; ++i) {
2561 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2562 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2566 if (irfun->locals_count) {
2567 ir_value *last = irfun->locals[irfun->locals_count-1];
2568 local_var_end = last->code.globaladdr;
2569 local_var_end += type_sizeof[last->vtype];
2571 for (i = 0; i < irfun->values_count; ++i)
2573 /* generate code.globaladdr for ssa values */
2574 ir_value *v = irfun->values[i];
2575 ir_value_code_setaddr(v, local_var_end + v->code.local);
2577 for (i = 0; i < irfun->allocated_locals; ++i) {
2578 /* fill the locals with zeros */
2579 code_globals_add(0);
2583 fun.entry = irfun->builtin;
2585 irfun->code_function_def = code_functions_elements;
2586 fun.entry = code_statements_elements;
2589 return (code_functions_add(fun) >= 0);
2592 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2594 prog_section_function *fundef;
2597 irfun = global->constval.vfunc;
2601 if (irfun->code_function_def < 0) {
2602 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2605 fundef = &code_functions_data[irfun->code_function_def];
2607 fundef->entry = code_statements_elements;
2608 if (!gen_function_code(irfun)) {
2609 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2615 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2619 prog_section_def def;
2621 def.type = global->vtype;
2622 def.offset = code_globals_elements;
2623 def.name = global->code.name = code_genstring(global->name);
2625 switch (global->vtype)
2628 if (code_defs_add(def) < 0)
2630 return gen_global_pointer(global);
2632 if (code_defs_add(def) < 0)
2634 return gen_global_field(global);
2639 if (code_defs_add(def) < 0)
2642 if (global->isconst) {
2643 iptr = (int32_t*)&global->constval.vfloat;
2644 ir_value_code_setaddr(global, code_globals_add(*iptr));
2646 ir_value_code_setaddr(global, code_globals_add(0));
2648 return global->code.globaladdr >= 0;
2652 if (code_defs_add(def) < 0)
2654 if (global->isconst)
2655 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2657 ir_value_code_setaddr(global, code_globals_add(0));
2658 return global->code.globaladdr >= 0;
2663 if (code_defs_add(def) < 0)
2666 if (global->isconst) {
2667 iptr = (int32_t*)&global->constval.vvec;
2668 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2669 if (global->code.globaladdr < 0)
2671 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2673 if (code_globals_add(iptr[d]) < 0)
2677 ir_value_code_setaddr(global, code_globals_add(0));
2678 if (global->code.globaladdr < 0)
2680 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2682 if (code_globals_add(0) < 0)
2686 return global->code.globaladdr >= 0;
2689 if (code_defs_add(def) < 0)
2691 ir_value_code_setaddr(global, code_globals_elements);
2692 code_globals_add(code_functions_elements);
2693 return gen_global_function(self, global);
2695 /* assume biggest type */
2696 ir_value_code_setaddr(global, code_globals_add(0));
2697 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2698 code_globals_add(0);
2701 /* refuse to create 'void' type or any other fancy business. */
2702 irerror(global->context, "Invalid type for global variable `%s`: %s",
2703 global->name, type_name[global->vtype]);
2708 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2710 prog_section_def def;
2711 prog_section_field fld;
2713 def.type = field->vtype;
2714 def.offset = code_globals_elements;
2716 /* create a global named the same as the field */
2717 if (opts_standard == COMPILER_GMQCC) {
2718 /* in our standard, the global gets a dot prefix */
2719 size_t len = strlen(field->name);
2722 /* we really don't want to have to allocate this, and 1024
2723 * bytes is more than enough for a variable/field name
2725 if (len+2 >= sizeof(name)) {
2726 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2731 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2734 def.name = code_genstring(name);
2735 fld.name = def.name + 1; /* we reuse that string table entry */
2737 /* in plain QC, there cannot be a global with the same name,
2738 * and so we also name the global the same.
2739 * FIXME: fteqcc should create a global as well
2740 * check if it actually uses the same name. Probably does
2742 def.name = code_genstring(field->name);
2743 fld.name = def.name;
2746 field->code.name = def.name;
2748 if (code_defs_add(def) < 0)
2751 fld.type = field->fieldtype;
2753 if (fld.type == TYPE_VOID) {
2754 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2758 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2760 if (code_fields_add(fld) < 0)
2763 ir_value_code_setaddr(field, code_globals_elements);
2764 if (!code_globals_add(fld.offset))
2766 if (fld.type == TYPE_VECTOR) {
2767 if (!code_globals_add(fld.offset+1))
2769 if (!code_globals_add(fld.offset+2))
2773 return field->code.globaladdr >= 0;
2776 bool ir_builder_generate(ir_builder *self, const char *filename)
2782 for (i = 0; i < self->fields_count; ++i)
2784 if (!ir_builder_gen_field(self, self->fields[i])) {
2789 for (i = 0; i < self->globals_count; ++i)
2791 if (!ir_builder_gen_global(self, self->globals[i])) {
2796 /* generate function code */
2797 for (i = 0; i < self->globals_count; ++i)
2799 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2800 if (!gen_global_function_code(self, self->globals[i])) {
2806 printf("writing '%s'...\n", filename);
2807 return code_write(filename);
2810 /***********************************************************************
2811 *IR DEBUG Dump functions...
2814 #define IND_BUFSZ 1024
2817 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2819 # define strncat strncat
2822 const char *qc_opname(int op)
2824 if (op < 0) return "<INVALID>";
2825 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2826 return asm_instr[op].m;
2828 case VINSTR_PHI: return "PHI";
2829 case VINSTR_JUMP: return "JUMP";
2830 case VINSTR_COND: return "COND";
2831 default: return "<UNK>";
2835 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2838 char indent[IND_BUFSZ];
2842 oprintf("module %s\n", b->name);
2843 for (i = 0; i < b->globals_count; ++i)
2846 if (b->globals[i]->isconst)
2847 oprintf("%s = ", b->globals[i]->name);
2848 ir_value_dump(b->globals[i], oprintf);
2851 for (i = 0; i < b->functions_count; ++i)
2852 ir_function_dump(b->functions[i], indent, oprintf);
2853 oprintf("endmodule %s\n", b->name);
2856 void ir_function_dump(ir_function *f, char *ind,
2857 int (*oprintf)(const char*, ...))
2860 if (f->builtin != 0) {
2861 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2864 oprintf("%sfunction %s\n", ind, f->name);
2865 strncat(ind, "\t", IND_BUFSZ);
2866 if (f->locals_count)
2868 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2869 for (i = 0; i < f->locals_count; ++i) {
2870 oprintf("%s\t", ind);
2871 ir_value_dump(f->locals[i], oprintf);
2875 if (f->blocks_count)
2877 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2878 for (i = 0; i < f->blocks_count; ++i) {
2879 if (f->blocks[i]->run_id != f->run_id) {
2880 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2882 ir_block_dump(f->blocks[i], ind, oprintf);
2886 ind[strlen(ind)-1] = 0;
2887 oprintf("%sendfunction %s\n", ind, f->name);
2890 void ir_block_dump(ir_block* b, char *ind,
2891 int (*oprintf)(const char*, ...))
2894 oprintf("%s:%s\n", ind, b->label);
2895 strncat(ind, "\t", IND_BUFSZ);
2897 for (i = 0; i < b->instr_count; ++i)
2898 ir_instr_dump(b->instr[i], ind, oprintf);
2899 ind[strlen(ind)-1] = 0;
2902 void dump_phi(ir_instr *in, char *ind,
2903 int (*oprintf)(const char*, ...))
2906 oprintf("%s <- phi ", in->_ops[0]->name);
2907 for (i = 0; i < in->phi_count; ++i)
2909 oprintf("([%s] : %s) ", in->phi[i].from->label,
2910 in->phi[i].value->name);
2915 void ir_instr_dump(ir_instr *in, char *ind,
2916 int (*oprintf)(const char*, ...))
2919 const char *comma = NULL;
2921 oprintf("%s (%i) ", ind, (int)in->eid);
2923 if (in->opcode == VINSTR_PHI) {
2924 dump_phi(in, ind, oprintf);
2928 strncat(ind, "\t", IND_BUFSZ);
2930 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2931 ir_value_dump(in->_ops[0], oprintf);
2932 if (in->_ops[1] || in->_ops[2])
2935 if (in->opcode == INSTR_CALL0) {
2936 oprintf("CALL%i\t", in->params_count);
2938 oprintf("%s\t", qc_opname(in->opcode));
2940 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2941 ir_value_dump(in->_ops[0], oprintf);
2946 for (i = 1; i != 3; ++i) {
2950 ir_value_dump(in->_ops[i], oprintf);
2958 oprintf("[%s]", in->bops[0]->label);
2962 oprintf("%s[%s]", comma, in->bops[1]->label);
2964 ind[strlen(ind)-1] = 0;
2967 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2976 oprintf("(function)");
2979 oprintf("%g", v->constval.vfloat);
2982 oprintf("'%g %g %g'",
2985 v->constval.vvec.z);
2988 oprintf("(entity)");
2991 oprintf("\"%s\"", v->constval.vstring);
2995 oprintf("%i", v->constval.vint);
3000 v->constval.vpointer->name);
3004 oprintf("%s", v->name);
3008 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
3011 oprintf("Life of %s:\n", self->name);
3012 for (i = 0; i < self->life_count; ++i)
3014 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);