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 field_store_instr[TYPE_COUNT] = {
88 INSTR_STORE_FLD, /* integer type */
91 INSTR_STORE_V, /* variant, should never be accessed */
94 uint16_t type_storep_instr[TYPE_COUNT] = {
95 INSTR_STOREP_F, /* should use I when having integer support */
102 INSTR_STOREP_ENT, /* should use I */
104 INSTR_STOREP_ENT, /* integer type */
107 INSTR_STOREP_V, /* variant, should never be accessed */
110 uint16_t type_eq_instr[TYPE_COUNT] = {
111 INSTR_EQ_F, /* should use I when having integer support */
116 INSTR_EQ_E, /* FLD has no comparison */
118 INSTR_EQ_E, /* should use I */
123 INSTR_EQ_V, /* variant, should never be accessed */
126 uint16_t type_ne_instr[TYPE_COUNT] = {
127 INSTR_NE_F, /* should use I when having integer support */
132 INSTR_NE_E, /* FLD has no comparison */
134 INSTR_NE_E, /* should use I */
139 INSTR_NE_V, /* variant, should never be accessed */
142 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
144 static void irerror(lex_ctx ctx, const char *msg, ...)
148 cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
152 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
155 int lvl = LVL_WARNING;
157 if (warntype && !OPTS_WARN(warntype))
164 vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
170 /***********************************************************************
174 static void ir_block_delete_quick(ir_block* self);
175 static void ir_instr_delete_quick(ir_instr *self);
176 static void ir_function_delete_quick(ir_function *self);
178 ir_builder* ir_builder_new(const char *modulename)
182 self = (ir_builder*)mem_a(sizeof(*self));
186 MEM_VECTOR_INIT(self, functions);
187 MEM_VECTOR_INIT(self, globals);
188 MEM_VECTOR_INIT(self, fields);
189 MEM_VECTOR_INIT(self, filenames);
190 MEM_VECTOR_INIT(self, filestrings);
191 self->str_immediate = 0;
193 if (!ir_builder_set_name(self, modulename)) {
201 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
202 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
203 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
204 MEM_VEC_FUNCTIONS(ir_builder, const char*, filenames)
205 MEM_VEC_FUNCTIONS(ir_builder, qcint, filestrings)
207 void ir_builder_delete(ir_builder* self)
210 mem_d((void*)self->name);
211 for (i = 0; i != self->functions_count; ++i) {
212 ir_function_delete_quick(self->functions[i]);
214 MEM_VECTOR_CLEAR(self, functions);
215 for (i = 0; i != self->globals_count; ++i) {
216 ir_value_delete(self->globals[i]);
218 MEM_VECTOR_CLEAR(self, globals);
219 for (i = 0; i != self->fields_count; ++i) {
220 ir_value_delete(self->fields[i]);
222 MEM_VECTOR_CLEAR(self, fields);
223 MEM_VECTOR_CLEAR(self, filenames);
224 MEM_VECTOR_CLEAR(self, filestrings);
228 bool ir_builder_set_name(ir_builder *self, const char *name)
231 mem_d((void*)self->name);
232 self->name = util_strdup(name);
236 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
239 for (i = 0; i < self->functions_count; ++i) {
240 if (!strcmp(name, self->functions[i]->name))
241 return self->functions[i];
246 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
248 ir_function *fn = ir_builder_get_function(self, name);
253 fn = ir_function_new(self, outtype);
254 if (!ir_function_set_name(fn, name) ||
255 !ir_builder_functions_add(self, fn) )
257 ir_function_delete(fn);
261 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
263 ir_function_delete(fn);
267 fn->value->isconst = true;
268 fn->value->outtype = outtype;
269 fn->value->constval.vfunc = fn;
270 fn->value->context = fn->context;
275 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
278 for (i = 0; i < self->globals_count; ++i) {
279 if (!strcmp(self->globals[i]->name, name))
280 return self->globals[i];
285 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
289 if (name && name[0] != '#')
291 ve = ir_builder_get_global(self, name);
297 ve = ir_value_var(name, store_global, vtype);
298 if (!ir_builder_globals_add(self, ve)) {
305 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
308 for (i = 0; i < self->fields_count; ++i) {
309 if (!strcmp(self->fields[i]->name, name))
310 return self->fields[i];
316 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
318 ir_value *ve = ir_builder_get_field(self, name);
323 ve = ir_value_var(name, store_global, TYPE_FIELD);
324 ve->fieldtype = vtype;
325 if (!ir_builder_fields_add(self, ve)) {
332 /***********************************************************************
336 bool ir_function_naive_phi(ir_function*);
337 void ir_function_enumerate(ir_function*);
338 bool ir_function_calculate_liferanges(ir_function*);
339 bool ir_function_allocate_locals(ir_function*);
341 ir_function* ir_function_new(ir_builder* owner, int outtype)
344 self = (ir_function*)mem_a(sizeof(*self));
349 memset(self, 0, sizeof(*self));
352 if (!ir_function_set_name(self, "<@unnamed>")) {
357 self->context.file = "<@no context>";
358 self->context.line = 0;
359 self->outtype = outtype;
362 MEM_VECTOR_INIT(self, params);
363 MEM_VECTOR_INIT(self, blocks);
364 MEM_VECTOR_INIT(self, values);
365 MEM_VECTOR_INIT(self, locals);
367 self->code_function_def = -1;
368 self->allocated_locals = 0;
373 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
374 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
375 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
376 MEM_VEC_FUNCTIONS(ir_function, int, params)
378 bool ir_function_set_name(ir_function *self, const char *name)
381 mem_d((void*)self->name);
382 self->name = util_strdup(name);
386 static void ir_function_delete_quick(ir_function *self)
389 mem_d((void*)self->name);
391 for (i = 0; i != self->blocks_count; ++i)
392 ir_block_delete_quick(self->blocks[i]);
393 MEM_VECTOR_CLEAR(self, blocks);
395 MEM_VECTOR_CLEAR(self, params);
397 for (i = 0; i != self->values_count; ++i)
398 ir_value_delete(self->values[i]);
399 MEM_VECTOR_CLEAR(self, values);
401 for (i = 0; i != self->locals_count; ++i)
402 ir_value_delete(self->locals[i]);
403 MEM_VECTOR_CLEAR(self, locals);
405 /* self->value is deleted by the builder */
410 void ir_function_delete(ir_function *self)
413 mem_d((void*)self->name);
415 for (i = 0; i != self->blocks_count; ++i)
416 ir_block_delete(self->blocks[i]);
417 MEM_VECTOR_CLEAR(self, blocks);
419 MEM_VECTOR_CLEAR(self, params);
421 for (i = 0; i != self->values_count; ++i)
422 ir_value_delete(self->values[i]);
423 MEM_VECTOR_CLEAR(self, values);
425 for (i = 0; i != self->locals_count; ++i)
426 ir_value_delete(self->locals[i]);
427 MEM_VECTOR_CLEAR(self, locals);
429 /* self->value is deleted by the builder */
434 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
436 return ir_function_values_add(self, v);
439 ir_block* ir_function_create_block(ir_function *self, const char *label)
441 ir_block* bn = ir_block_new(self, label);
442 memcpy(&bn->context, &self->context, sizeof(self->context));
443 if (!ir_function_blocks_add(self, bn)) {
450 bool ir_function_finalize(ir_function *self)
455 if (!ir_function_naive_phi(self))
458 ir_function_enumerate(self);
460 if (!ir_function_calculate_liferanges(self))
463 if (!ir_function_allocate_locals(self))
468 ir_value* ir_function_get_local(ir_function *self, const char *name)
471 for (i = 0; i < self->locals_count; ++i) {
472 if (!strcmp(self->locals[i]->name, name))
473 return self->locals[i];
478 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
483 if (ir_function_get_local(self, name))
488 self->locals_count &&
489 self->locals[self->locals_count-1]->store != store_param) {
490 irerror(self->context, "cannot add parameters after adding locals");
494 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
495 if (!ir_function_locals_add(self, ve)) {
502 /***********************************************************************
506 ir_block* ir_block_new(ir_function* owner, const char *name)
509 self = (ir_block*)mem_a(sizeof(*self));
513 memset(self, 0, sizeof(*self));
516 if (name && !ir_block_set_label(self, name)) {
521 self->context.file = "<@no context>";
522 self->context.line = 0;
524 MEM_VECTOR_INIT(self, instr);
525 MEM_VECTOR_INIT(self, entries);
526 MEM_VECTOR_INIT(self, exits);
529 self->is_return = false;
531 MEM_VECTOR_INIT(self, living);
533 self->generated = false;
537 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
538 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
539 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
540 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
542 static void ir_block_delete_quick(ir_block* self)
545 if (self->label) mem_d(self->label);
546 for (i = 0; i != self->instr_count; ++i)
547 ir_instr_delete_quick(self->instr[i]);
548 MEM_VECTOR_CLEAR(self, instr);
549 MEM_VECTOR_CLEAR(self, entries);
550 MEM_VECTOR_CLEAR(self, exits);
551 MEM_VECTOR_CLEAR(self, living);
555 void ir_block_delete(ir_block* self)
558 if (self->label) mem_d(self->label);
559 for (i = 0; i != self->instr_count; ++i)
560 ir_instr_delete(self->instr[i]);
561 MEM_VECTOR_CLEAR(self, instr);
562 MEM_VECTOR_CLEAR(self, entries);
563 MEM_VECTOR_CLEAR(self, exits);
564 MEM_VECTOR_CLEAR(self, living);
568 bool ir_block_set_label(ir_block *self, const char *name)
571 mem_d((void*)self->label);
572 self->label = util_strdup(name);
573 return !!self->label;
576 /***********************************************************************
580 ir_instr* ir_instr_new(ir_block* owner, int op)
583 self = (ir_instr*)mem_a(sizeof(*self));
588 self->context.file = "<@no context>";
589 self->context.line = 0;
591 self->_ops[0] = NULL;
592 self->_ops[1] = NULL;
593 self->_ops[2] = NULL;
594 self->bops[0] = NULL;
595 self->bops[1] = NULL;
596 MEM_VECTOR_INIT(self, phi);
597 MEM_VECTOR_INIT(self, params);
602 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
603 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
605 static void ir_instr_delete_quick(ir_instr *self)
607 MEM_VECTOR_CLEAR(self, phi);
608 MEM_VECTOR_CLEAR(self, params);
612 void ir_instr_delete(ir_instr *self)
615 /* The following calls can only delete from
616 * vectors, we still want to delete this instruction
617 * so ignore the return value. Since with the warn_unused_result attribute
618 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
619 * I have to improvise here and use if(foo());
621 for (i = 0; i < self->phi_count; ++i) {
623 if (ir_value_writes_find(self->phi[i].value, self, &idx))
624 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
625 if (ir_value_reads_find(self->phi[i].value, self, &idx))
626 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
628 MEM_VECTOR_CLEAR(self, phi);
629 for (i = 0; i < self->params_count; ++i) {
631 if (ir_value_writes_find(self->params[i], self, &idx))
632 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
633 if (ir_value_reads_find(self->params[i], self, &idx))
634 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
636 MEM_VECTOR_CLEAR(self, params);
637 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
638 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
639 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
643 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
645 if (self->_ops[op]) {
647 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
649 if (!ir_value_writes_remove(self->_ops[op], idx))
652 else if (ir_value_reads_find(self->_ops[op], self, &idx))
654 if (!ir_value_reads_remove(self->_ops[op], idx))
660 if (!ir_value_writes_add(v, self))
663 if (!ir_value_reads_add(v, self))
671 /***********************************************************************
675 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
677 self->code.globaladdr = gaddr;
678 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
679 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
680 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
683 int32_t ir_value_code_addr(const ir_value *self)
685 if (self->store == store_return)
686 return OFS_RETURN + self->code.addroffset;
687 return self->code.globaladdr + self->code.addroffset;
690 ir_value* ir_value_var(const char *name, int storetype, int vtype)
693 self = (ir_value*)mem_a(sizeof(*self));
695 self->fieldtype = TYPE_VOID;
696 self->outtype = TYPE_VOID;
697 self->store = storetype;
698 MEM_VECTOR_INIT(self, reads);
699 MEM_VECTOR_INIT(self, writes);
700 self->isconst = false;
701 self->context.file = "<@no context>";
702 self->context.line = 0;
704 if (name && !ir_value_set_name(self, name)) {
705 irerror(self->context, "out of memory");
710 memset(&self->constval, 0, sizeof(self->constval));
711 memset(&self->code, 0, sizeof(self->code));
713 self->members[0] = NULL;
714 self->members[1] = NULL;
715 self->members[2] = NULL;
716 self->memberof = NULL;
718 MEM_VECTOR_INIT(self, life);
722 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
728 if (self->members[member])
729 return self->members[member];
731 if (self->vtype == TYPE_VECTOR)
733 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
736 m->context = self->context;
738 self->members[member] = m;
739 m->code.addroffset = member;
741 else if (self->vtype == TYPE_FIELD)
743 if (self->fieldtype != TYPE_VECTOR)
745 m = ir_value_var(self->name, self->store, TYPE_FIELD);
748 m->fieldtype = TYPE_FLOAT;
749 m->context = self->context;
751 self->members[member] = m;
752 m->code.addroffset = member;
756 irerror(self->context, "invalid member access on %s", self->name);
764 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
765 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
766 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
768 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
770 ir_value *v = ir_value_var(name, storetype, vtype);
773 if (!ir_function_collect_value(owner, v))
781 void ir_value_delete(ir_value* self)
785 mem_d((void*)self->name);
788 if (self->vtype == TYPE_STRING)
789 mem_d((void*)self->constval.vstring);
791 for (i = 0; i < 3; ++i) {
792 if (self->members[i])
793 ir_value_delete(self->members[i]);
795 MEM_VECTOR_CLEAR(self, reads);
796 MEM_VECTOR_CLEAR(self, writes);
797 MEM_VECTOR_CLEAR(self, life);
801 bool ir_value_set_name(ir_value *self, const char *name)
804 mem_d((void*)self->name);
805 self->name = util_strdup(name);
809 bool ir_value_set_float(ir_value *self, float f)
811 if (self->vtype != TYPE_FLOAT)
813 self->constval.vfloat = f;
814 self->isconst = true;
818 bool ir_value_set_func(ir_value *self, int f)
820 if (self->vtype != TYPE_FUNCTION)
822 self->constval.vint = f;
823 self->isconst = true;
827 bool ir_value_set_vector(ir_value *self, vector v)
829 if (self->vtype != TYPE_VECTOR)
831 self->constval.vvec = v;
832 self->isconst = true;
836 bool ir_value_set_field(ir_value *self, ir_value *fld)
838 if (self->vtype != TYPE_FIELD)
840 self->constval.vpointer = fld;
841 self->isconst = true;
845 static char *ir_strdup(const char *str)
848 /* actually dup empty strings */
849 char *out = mem_a(1);
853 return util_strdup(str);
856 bool ir_value_set_string(ir_value *self, const char *str)
858 if (self->vtype != TYPE_STRING)
860 self->constval.vstring = ir_strdup(str);
861 self->isconst = true;
866 bool ir_value_set_int(ir_value *self, int i)
868 if (self->vtype != TYPE_INTEGER)
870 self->constval.vint = i;
871 self->isconst = true;
876 bool ir_value_lives(ir_value *self, size_t at)
879 for (i = 0; i < self->life_count; ++i)
881 ir_life_entry_t *life = &self->life[i];
882 if (life->start <= at && at <= life->end)
884 if (life->start > at) /* since it's ordered */
890 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
893 if (!ir_value_life_add(self, e)) /* naive... */
895 for (k = self->life_count-1; k > idx; --k)
896 self->life[k] = self->life[k-1];
901 bool ir_value_life_merge(ir_value *self, size_t s)
904 ir_life_entry_t *life = NULL;
905 ir_life_entry_t *before = NULL;
906 ir_life_entry_t new_entry;
908 /* Find the first range >= s */
909 for (i = 0; i < self->life_count; ++i)
912 life = &self->life[i];
916 /* nothing found? append */
917 if (i == self->life_count) {
919 if (life && life->end+1 == s)
921 /* previous life range can be merged in */
925 if (life && life->end >= s)
928 if (!ir_value_life_add(self, e))
929 return false; /* failing */
935 if (before->end + 1 == s &&
936 life->start - 1 == s)
939 before->end = life->end;
940 if (!ir_value_life_remove(self, i))
941 return false; /* failing */
944 if (before->end + 1 == s)
950 /* already contained */
951 if (before->end >= s)
955 if (life->start - 1 == s)
960 /* insert a new entry */
961 new_entry.start = new_entry.end = s;
962 return ir_value_life_insert(self, i, new_entry);
965 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
969 if (!other->life_count)
972 if (!self->life_count) {
973 for (i = 0; i < other->life_count; ++i) {
974 if (!ir_value_life_add(self, other->life[i]))
981 for (i = 0; i < other->life_count; ++i)
983 const ir_life_entry_t *life = &other->life[i];
986 ir_life_entry_t *entry = &self->life[myi];
988 if (life->end+1 < entry->start)
990 /* adding an interval before entry */
991 if (!ir_value_life_insert(self, myi, *life))
997 if (life->start < entry->start &&
998 life->end+1 >= entry->start)
1000 /* starts earlier and overlaps */
1001 entry->start = life->start;
1004 if (life->end > entry->end &&
1005 life->start <= entry->end+1)
1007 /* ends later and overlaps */
1008 entry->end = life->end;
1011 /* see if our change combines it with the next ranges */
1012 while (myi+1 < self->life_count &&
1013 entry->end+1 >= self->life[1+myi].start)
1015 /* overlaps with (myi+1) */
1016 if (entry->end < self->life[1+myi].end)
1017 entry->end = self->life[1+myi].end;
1018 if (!ir_value_life_remove(self, myi+1))
1020 entry = &self->life[myi];
1023 /* see if we're after the entry */
1024 if (life->start > entry->end)
1027 /* append if we're at the end */
1028 if (myi >= self->life_count) {
1029 if (!ir_value_life_add(self, *life))
1033 /* otherweise check the next range */
1042 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1044 /* For any life entry in A see if it overlaps with
1045 * any life entry in B.
1046 * Note that the life entries are orderes, so we can make a
1047 * more efficient algorithm there than naively translating the
1051 ir_life_entry_t *la, *lb, *enda, *endb;
1053 /* first of all, if either has no life range, they cannot clash */
1054 if (!a->life_count || !b->life_count)
1059 enda = la + a->life_count;
1060 endb = lb + b->life_count;
1063 /* check if the entries overlap, for that,
1064 * both must start before the other one ends.
1066 if (la->start < lb->end &&
1067 lb->start < la->end)
1072 /* entries are ordered
1073 * one entry is earlier than the other
1074 * that earlier entry will be moved forward
1076 if (la->start < lb->start)
1078 /* order: A B, move A forward
1079 * check if we hit the end with A
1084 else /* if (lb->start < la->start) actually <= */
1086 /* order: B A, move B forward
1087 * check if we hit the end with B
1096 /***********************************************************************
1100 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1102 ir_instr *in = ir_instr_new(self, op);
1106 if (target->store == store_value &&
1107 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1109 irerror(self->context, "cannot store to an SSA value");
1110 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1111 irerror(self->context, "instruction: %s", asm_instr[op].m);
1115 if (!ir_instr_op(in, 0, target, true) ||
1116 !ir_instr_op(in, 1, what, false) ||
1117 !ir_block_instr_add(self, in) )
1124 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1128 if (target->vtype == TYPE_VARIANT)
1129 vtype = what->vtype;
1131 vtype = target->vtype;
1134 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1135 op = INSTR_CONV_ITOF;
1136 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1137 op = INSTR_CONV_FTOI;
1139 op = type_store_instr[vtype];
1141 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1142 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1146 return ir_block_create_store_op(self, op, target, what);
1149 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1154 if (target->vtype != TYPE_POINTER)
1157 /* storing using pointer - target is a pointer, type must be
1158 * inferred from source
1160 vtype = what->vtype;
1162 op = type_storep_instr[vtype];
1163 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1164 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1165 op = INSTR_STOREP_V;
1168 return ir_block_create_store_op(self, op, target, what);
1171 bool ir_block_create_return(ir_block *self, ir_value *v)
1175 irerror(self->context, "block already ended (%s)", self->label);
1179 self->is_return = true;
1180 in = ir_instr_new(self, INSTR_RETURN);
1184 if (v && !ir_instr_op(in, 0, v, false))
1187 if (!ir_block_instr_add(self, in))
1192 bool ir_block_create_if(ir_block *self, ir_value *v,
1193 ir_block *ontrue, ir_block *onfalse)
1197 irerror(self->context, "block already ended (%s)", self->label);
1201 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1202 in = ir_instr_new(self, VINSTR_COND);
1206 if (!ir_instr_op(in, 0, v, false)) {
1207 ir_instr_delete(in);
1211 in->bops[0] = ontrue;
1212 in->bops[1] = onfalse;
1214 if (!ir_block_instr_add(self, in))
1217 if (!ir_block_exits_add(self, ontrue) ||
1218 !ir_block_exits_add(self, onfalse) ||
1219 !ir_block_entries_add(ontrue, self) ||
1220 !ir_block_entries_add(onfalse, self) )
1227 bool ir_block_create_jump(ir_block *self, ir_block *to)
1231 irerror(self->context, "block already ended (%s)", self->label);
1235 in = ir_instr_new(self, VINSTR_JUMP);
1240 if (!ir_block_instr_add(self, in))
1243 if (!ir_block_exits_add(self, to) ||
1244 !ir_block_entries_add(to, self) )
1251 bool ir_block_create_goto(ir_block *self, ir_block *to)
1255 irerror(self->context, "block already ended (%s)", self->label);
1259 in = ir_instr_new(self, INSTR_GOTO);
1264 if (!ir_block_instr_add(self, in))
1267 if (!ir_block_exits_add(self, to) ||
1268 !ir_block_entries_add(to, self) )
1275 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1279 in = ir_instr_new(self, VINSTR_PHI);
1282 out = ir_value_out(self->owner, label, store_value, ot);
1284 ir_instr_delete(in);
1287 if (!ir_instr_op(in, 0, out, true)) {
1288 ir_instr_delete(in);
1289 ir_value_delete(out);
1292 if (!ir_block_instr_add(self, in)) {
1293 ir_instr_delete(in);
1294 ir_value_delete(out);
1300 ir_value* ir_phi_value(ir_instr *self)
1302 return self->_ops[0];
1305 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1309 if (!ir_block_entries_find(self->owner, b, NULL)) {
1310 /* Must not be possible to cause this, otherwise the AST
1311 * is doing something wrong.
1313 irerror(self->context, "Invalid entry block for PHI");
1319 if (!ir_value_reads_add(v, self))
1321 return ir_instr_phi_add(self, pe);
1324 /* call related code */
1325 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1329 in = ir_instr_new(self, INSTR_CALL0);
1332 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1334 ir_instr_delete(in);
1337 if (!ir_instr_op(in, 0, out, true) ||
1338 !ir_instr_op(in, 1, func, false) ||
1339 !ir_block_instr_add(self, in))
1341 ir_instr_delete(in);
1342 ir_value_delete(out);
1348 ir_value* ir_call_value(ir_instr *self)
1350 return self->_ops[0];
1353 bool ir_call_param(ir_instr* self, ir_value *v)
1355 if (!ir_instr_params_add(self, v))
1357 if (!ir_value_reads_add(v, self)) {
1358 if (!ir_instr_params_remove(self, self->params_count-1))
1359 GMQCC_SUPPRESS_EMPTY_BODY;
1365 /* binary op related code */
1367 ir_value* ir_block_create_binop(ir_block *self,
1368 const char *label, int opcode,
1369 ir_value *left, ir_value *right)
1391 case INSTR_SUB_S: /* -- offset of string as float */
1396 case INSTR_BITOR_IF:
1397 case INSTR_BITOR_FI:
1398 case INSTR_BITAND_FI:
1399 case INSTR_BITAND_IF:
1414 case INSTR_BITAND_I:
1417 case INSTR_RSHIFT_I:
1418 case INSTR_LSHIFT_I:
1440 /* boolean operations result in floats */
1441 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1443 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1446 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1451 if (ot == TYPE_VOID) {
1452 /* The AST or parser were supposed to check this! */
1456 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1459 ir_value* ir_block_create_unary(ir_block *self,
1460 const char *label, int opcode,
1463 int ot = TYPE_FLOAT;
1475 /* QC doesn't have other unary operations. We expect extensions to fill
1476 * the above list, otherwise we assume out-type = in-type, eg for an
1480 ot = operand->vtype;
1483 if (ot == TYPE_VOID) {
1484 /* The AST or parser were supposed to check this! */
1488 /* let's use the general instruction creator and pass NULL for OPB */
1489 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1492 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1493 int op, ir_value *a, ir_value *b, int outype)
1498 out = ir_value_out(self->owner, label, store_value, outype);
1502 instr = ir_instr_new(self, op);
1504 ir_value_delete(out);
1508 if (!ir_instr_op(instr, 0, out, true) ||
1509 !ir_instr_op(instr, 1, a, false) ||
1510 !ir_instr_op(instr, 2, b, false) )
1515 if (!ir_block_instr_add(self, instr))
1520 ir_instr_delete(instr);
1521 ir_value_delete(out);
1525 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1529 /* Support for various pointer types todo if so desired */
1530 if (ent->vtype != TYPE_ENTITY)
1533 if (field->vtype != TYPE_FIELD)
1536 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1537 v->fieldtype = field->fieldtype;
1541 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1544 if (ent->vtype != TYPE_ENTITY)
1547 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1548 if (field->vtype != TYPE_FIELD)
1553 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1554 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1555 case TYPE_STRING: op = INSTR_LOAD_S; break;
1556 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1557 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1558 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1560 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1561 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1567 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1570 ir_value* ir_block_create_add(ir_block *self,
1572 ir_value *left, ir_value *right)
1575 int l = left->vtype;
1576 int r = right->vtype;
1595 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1597 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1603 return ir_block_create_binop(self, label, op, left, right);
1606 ir_value* ir_block_create_sub(ir_block *self,
1608 ir_value *left, ir_value *right)
1611 int l = left->vtype;
1612 int r = right->vtype;
1632 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1634 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1640 return ir_block_create_binop(self, label, op, left, right);
1643 ir_value* ir_block_create_mul(ir_block *self,
1645 ir_value *left, ir_value *right)
1648 int l = left->vtype;
1649 int r = right->vtype;
1668 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1670 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1673 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1675 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1677 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1679 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1685 return ir_block_create_binop(self, label, op, left, right);
1688 ir_value* ir_block_create_div(ir_block *self,
1690 ir_value *left, ir_value *right)
1693 int l = left->vtype;
1694 int r = right->vtype;
1711 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1713 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1715 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1721 return ir_block_create_binop(self, label, op, left, right);
1724 /* PHI resolving breaks the SSA, and must thus be the last
1725 * step before life-range calculation.
1728 static bool ir_block_naive_phi(ir_block *self);
1729 bool ir_function_naive_phi(ir_function *self)
1733 for (i = 0; i < self->blocks_count; ++i)
1735 if (!ir_block_naive_phi(self->blocks[i]))
1741 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1746 /* create a store */
1747 if (!ir_block_create_store(block, old, what))
1750 /* we now move it up */
1751 instr = block->instr[block->instr_count-1];
1752 for (i = block->instr_count; i > iid; --i)
1753 block->instr[i] = block->instr[i-1];
1754 block->instr[i] = instr;
1759 static bool ir_block_naive_phi(ir_block *self)
1762 /* FIXME: optionally, create_phi can add the phis
1763 * to a list so we don't need to loop through blocks
1764 * - anyway: "don't optimize YET"
1766 for (i = 0; i < self->instr_count; ++i)
1768 ir_instr *instr = self->instr[i];
1769 if (instr->opcode != VINSTR_PHI)
1772 if (!ir_block_instr_remove(self, i))
1774 --i; /* NOTE: i+1 below */
1776 for (p = 0; p < instr->phi_count; ++p)
1778 ir_value *v = instr->phi[p].value;
1779 for (w = 0; w < v->writes_count; ++w) {
1782 if (!v->writes[w]->_ops[0])
1785 /* When the write was to a global, we have to emit a mov */
1786 old = v->writes[w]->_ops[0];
1788 /* The original instruction now writes to the PHI target local */
1789 if (v->writes[w]->_ops[0] == v)
1790 v->writes[w]->_ops[0] = instr->_ops[0];
1792 if (old->store != store_value && old->store != store_local && old->store != store_param)
1794 /* If it originally wrote to a global we need to store the value
1797 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1799 if (i+1 < self->instr_count)
1800 instr = self->instr[i+1];
1803 /* In case I forget and access instr later, it'll be NULL
1804 * when it's a problem, to make sure we crash, rather than accessing
1810 /* If it didn't, we can replace all reads by the phi target now. */
1812 for (r = 0; r < old->reads_count; ++r)
1815 ir_instr *ri = old->reads[r];
1816 for (op = 0; op < ri->phi_count; ++op) {
1817 if (ri->phi[op].value == old)
1818 ri->phi[op].value = v;
1820 for (op = 0; op < 3; ++op) {
1821 if (ri->_ops[op] == old)
1828 ir_instr_delete(instr);
1833 /***********************************************************************
1834 *IR Temp allocation code
1835 * Propagating value life ranges by walking through the function backwards
1836 * until no more changes are made.
1837 * In theory this should happen once more than once for every nested loop
1839 * Though this implementation might run an additional time for if nests.
1848 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1850 /* Enumerate instructions used by value's life-ranges
1852 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1856 for (i = 0; i < self->instr_count; ++i)
1858 self->instr[i]->eid = eid++;
1863 /* Enumerate blocks and instructions.
1864 * The block-enumeration is unordered!
1865 * We do not really use the block enumreation, however
1866 * the instruction enumeration is important for life-ranges.
1868 void ir_function_enumerate(ir_function *self)
1871 size_t instruction_id = 0;
1872 for (i = 0; i < self->blocks_count; ++i)
1874 self->blocks[i]->eid = i;
1875 self->blocks[i]->run_id = 0;
1876 ir_block_enumerate(self->blocks[i], &instruction_id);
1880 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1881 bool ir_function_calculate_liferanges(ir_function *self)
1889 for (i = 0; i != self->blocks_count; ++i)
1891 if (self->blocks[i]->is_return)
1893 self->blocks[i]->living_count = 0;
1894 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1899 if (self->blocks_count) {
1900 ir_block *block = self->blocks[0];
1901 for (i = 0; i < block->living_count; ++i) {
1902 ir_value *v = block->living[i];
1903 if (v->memberof || v->store != store_local)
1905 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1906 "variable `%s` may be used uninitialized in this function", v->name))
1915 /* Local-value allocator
1916 * After finishing creating the liferange of all values used in a function
1917 * we can allocate their global-positions.
1918 * This is the counterpart to register-allocation in register machines.
1921 MEM_VECTOR_MAKE(ir_value*, locals);
1922 MEM_VECTOR_MAKE(size_t, sizes);
1923 MEM_VECTOR_MAKE(size_t, positions);
1924 } function_allocator;
1925 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1926 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1927 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1929 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1932 size_t vsize = type_sizeof[var->vtype];
1934 slot = ir_value_var("reg", store_global, var->vtype);
1938 if (!ir_value_life_merge_into(slot, var))
1941 if (!function_allocator_locals_add(alloc, slot))
1944 if (!function_allocator_sizes_add(alloc, vsize))
1950 ir_value_delete(slot);
1954 bool ir_function_allocate_locals(ir_function *self)
1963 function_allocator alloc;
1965 if (!self->locals_count && !self->values_count)
1968 MEM_VECTOR_INIT(&alloc, locals);
1969 MEM_VECTOR_INIT(&alloc, sizes);
1970 MEM_VECTOR_INIT(&alloc, positions);
1972 for (i = 0; i < self->locals_count; ++i)
1974 if (!function_allocator_alloc(&alloc, self->locals[i]))
1978 /* Allocate a slot for any value that still exists */
1979 for (i = 0; i < self->values_count; ++i)
1981 v = self->values[i];
1986 for (a = 0; a < alloc.locals_count; ++a)
1988 slot = alloc.locals[a];
1990 if (ir_values_overlap(v, slot))
1993 if (!ir_value_life_merge_into(slot, v))
1996 /* adjust size for this slot */
1997 if (alloc.sizes[a] < type_sizeof[v->vtype])
1998 alloc.sizes[a] = type_sizeof[v->vtype];
2000 self->values[i]->code.local = a;
2003 if (a >= alloc.locals_count) {
2004 self->values[i]->code.local = alloc.locals_count;
2005 if (!function_allocator_alloc(&alloc, v))
2014 /* Adjust slot positions based on sizes */
2015 if (!function_allocator_positions_add(&alloc, 0))
2018 if (alloc.sizes_count)
2019 pos = alloc.positions[0] + alloc.sizes[0];
2022 for (i = 1; i < alloc.sizes_count; ++i)
2024 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2025 if (!function_allocator_positions_add(&alloc, pos))
2029 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
2031 /* Take over the actual slot positions */
2032 for (i = 0; i < self->values_count; ++i) {
2033 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2041 for (i = 0; i < alloc.locals_count; ++i)
2042 ir_value_delete(alloc.locals[i]);
2043 MEM_VECTOR_CLEAR(&alloc, locals);
2044 MEM_VECTOR_CLEAR(&alloc, sizes);
2045 MEM_VECTOR_CLEAR(&alloc, positions);
2049 /* Get information about which operand
2050 * is read from, or written to.
2052 static void ir_op_read_write(int op, size_t *read, size_t *write)
2072 case INSTR_STOREP_F:
2073 case INSTR_STOREP_V:
2074 case INSTR_STOREP_S:
2075 case INSTR_STOREP_ENT:
2076 case INSTR_STOREP_FLD:
2077 case INSTR_STOREP_FNC:
2088 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2091 bool changed = false;
2093 for (i = 0; i != self->living_count; ++i)
2095 tempbool = ir_value_life_merge(self->living[i], eid);
2098 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2100 changed = changed || tempbool;
2105 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2108 /* values which have been read in a previous iteration are now
2109 * in the "living" array even if the previous block doesn't use them.
2110 * So we have to remove whatever does not exist in the previous block.
2111 * They will be re-added on-read, but the liferange merge won't cause
2114 for (i = 0; i < self->living_count; ++i)
2116 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2117 if (!ir_block_living_remove(self, i))
2123 /* Whatever the previous block still has in its living set
2124 * must now be added to ours as well.
2126 for (i = 0; i < prev->living_count; ++i)
2128 if (ir_block_living_find(self, prev->living[i], NULL))
2130 if (!ir_block_living_add(self, prev->living[i]))
2133 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2139 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2145 /* bitmasks which operands are read from or written to */
2147 char dbg_ind[16] = { '#', '0' };
2152 if (!ir_block_life_prop_previous(self, prev, changed))
2156 i = self->instr_count;
2159 instr = self->instr[i];
2161 /* PHI operands are always read operands */
2162 for (p = 0; p < instr->phi_count; ++p)
2164 value = instr->phi[p].value;
2165 if (value->memberof)
2166 value = value->memberof;
2167 if (!ir_block_living_find(self, value, NULL) &&
2168 !ir_block_living_add(self, value))
2174 /* call params are read operands too */
2175 for (p = 0; p < instr->params_count; ++p)
2177 value = instr->params[p];
2178 if (value->memberof)
2179 value = value->memberof;
2180 if (!ir_block_living_find(self, value, NULL) &&
2181 !ir_block_living_add(self, value))
2187 /* See which operands are read and write operands */
2188 ir_op_read_write(instr->opcode, &read, &write);
2190 if (instr->opcode == INSTR_MUL_VF)
2192 /* the float source will get an additional lifetime */
2193 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2194 *changed = *changed || tempbool;
2196 else if (instr->opcode == INSTR_MUL_FV)
2198 /* the float source will get an additional lifetime */
2199 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2200 *changed = *changed || tempbool;
2203 /* Go through the 3 main operands */
2204 for (o = 0; o < 3; ++o)
2206 if (!instr->_ops[o]) /* no such operand */
2209 value = instr->_ops[o];
2210 if (value->memberof)
2211 value = value->memberof;
2213 /* We only care about locals */
2214 /* we also calculate parameter liferanges so that locals
2215 * can take up parameter slots */
2216 if (value->store != store_value &&
2217 value->store != store_local &&
2218 value->store != store_param)
2224 if (!ir_block_living_find(self, value, NULL) &&
2225 !ir_block_living_add(self, value))
2231 /* write operands */
2232 /* When we write to a local, we consider it "dead" for the
2233 * remaining upper part of the function, since in SSA a value
2234 * can only be written once (== created)
2239 bool in_living = ir_block_living_find(self, value, &idx);
2242 /* If the value isn't alive it hasn't been read before... */
2243 /* TODO: See if the warning can be emitted during parsing or AST processing
2244 * otherwise have warning printed here.
2245 * IF printing a warning here: include filecontext_t,
2246 * and make sure it's only printed once
2247 * since this function is run multiple times.
2249 /* For now: debug info: */
2250 /* fprintf(stderr, "Value only written %s\n", value->name); */
2251 tempbool = ir_value_life_merge(value, instr->eid);
2252 *changed = *changed || tempbool;
2254 ir_instr_dump(instr, dbg_ind, printf);
2258 /* since 'living' won't contain it
2259 * anymore, merge the value, since
2262 tempbool = ir_value_life_merge(value, instr->eid);
2265 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2267 *changed = *changed || tempbool;
2269 if (!ir_block_living_remove(self, idx))
2275 tempbool = ir_block_living_add_instr(self, instr->eid);
2276 /*fprintf(stderr, "living added values\n");*/
2277 *changed = *changed || tempbool;
2281 if (self->run_id == self->owner->run_id)
2284 self->run_id = self->owner->run_id;
2286 for (i = 0; i < self->entries_count; ++i)
2288 ir_block *entry = self->entries[i];
2289 ir_block_life_propagate(entry, self, changed);
2295 /***********************************************************************
2298 * Since the IR has the convention of putting 'write' operands
2299 * at the beginning, we have to rotate the operands of instructions
2300 * properly in order to generate valid QCVM code.
2302 * Having destinations at a fixed position is more convenient. In QC
2303 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2304 * read from from OPA, and store to OPB rather than OPC. Which is
2305 * partially the reason why the implementation of these instructions
2306 * in darkplaces has been delayed for so long.
2308 * Breaking conventions is annoying...
2310 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2312 static bool gen_global_field(ir_value *global)
2314 if (global->isconst)
2316 ir_value *fld = global->constval.vpointer;
2318 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2322 /* Now, in this case, a relocation would be impossible to code
2323 * since it looks like this:
2324 * .vector v = origin; <- parse error, wtf is 'origin'?
2327 * But we will need a general relocation support later anyway
2328 * for functions... might as well support that here.
2330 if (!fld->code.globaladdr) {
2331 irerror(global->context, "FIXME: Relocation support");
2335 /* copy the field's value */
2336 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2337 if (global->fieldtype == TYPE_VECTOR) {
2338 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2339 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2344 ir_value_code_setaddr(global, code_globals_add(0));
2345 if (global->fieldtype == TYPE_VECTOR) {
2346 code_globals_add(0);
2347 code_globals_add(0);
2350 if (global->code.globaladdr < 0)
2355 static bool gen_global_pointer(ir_value *global)
2357 if (global->isconst)
2359 ir_value *target = global->constval.vpointer;
2361 irerror(global->context, "Invalid pointer constant: %s", global->name);
2362 /* NULL pointers are pointing to the NULL constant, which also
2363 * sits at address 0, but still has an ir_value for itself.
2368 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2369 * void() foo; <- proto
2370 * void() *fooptr = &foo;
2371 * void() foo = { code }
2373 if (!target->code.globaladdr) {
2374 /* FIXME: Check for the constant nullptr ir_value!
2375 * because then code.globaladdr being 0 is valid.
2377 irerror(global->context, "FIXME: Relocation support");
2381 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2385 ir_value_code_setaddr(global, code_globals_add(0));
2387 if (global->code.globaladdr < 0)
2392 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2394 prog_section_statement stmt;
2403 block->generated = true;
2404 block->code_start = code_statements_elements;
2405 for (i = 0; i < block->instr_count; ++i)
2407 instr = block->instr[i];
2409 if (instr->opcode == VINSTR_PHI) {
2410 irerror(block->context, "cannot generate virtual instruction (phi)");
2414 if (instr->opcode == VINSTR_JUMP) {
2415 target = instr->bops[0];
2416 /* for uncoditional jumps, if the target hasn't been generated
2417 * yet, we generate them right here.
2419 if (!target->generated) {
2424 /* otherwise we generate a jump instruction */
2425 stmt.opcode = INSTR_GOTO;
2426 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2429 if (code_statements_add(stmt) < 0)
2432 /* no further instructions can be in this block */
2436 if (instr->opcode == VINSTR_COND) {
2437 ontrue = instr->bops[0];
2438 onfalse = instr->bops[1];
2439 /* TODO: have the AST signal which block should
2440 * come first: eg. optimize IFs without ELSE...
2443 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2447 if (ontrue->generated) {
2448 stmt.opcode = INSTR_IF;
2449 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2450 if (code_statements_add(stmt) < 0)
2453 if (onfalse->generated) {
2454 stmt.opcode = INSTR_IFNOT;
2455 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2456 if (code_statements_add(stmt) < 0)
2459 if (!ontrue->generated) {
2460 if (onfalse->generated) {
2465 if (!onfalse->generated) {
2466 if (ontrue->generated) {
2471 /* neither ontrue nor onfalse exist */
2472 stmt.opcode = INSTR_IFNOT;
2473 stidx = code_statements_elements;
2474 if (code_statements_add(stmt) < 0)
2476 /* on false we jump, so add ontrue-path */
2477 if (!gen_blocks_recursive(func, ontrue))
2479 /* fixup the jump address */
2480 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2481 /* generate onfalse path */
2482 if (onfalse->generated) {
2483 /* fixup the jump address */
2484 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2485 /* may have been generated in the previous recursive call */
2486 stmt.opcode = INSTR_GOTO;
2487 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2490 return (code_statements_add(stmt) >= 0);
2492 /* if not, generate now */
2497 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2498 /* Trivial call translation:
2499 * copy all params to OFS_PARM*
2500 * if the output's storetype is not store_return,
2501 * add append a STORE instruction!
2503 * NOTES on how to do it better without much trouble:
2504 * -) The liferanges!
2505 * Simply check the liferange of all parameters for
2506 * other CALLs. For each param with no CALL in its
2507 * liferange, we can store it in an OFS_PARM at
2508 * generation already. This would even include later
2509 * reuse.... probably... :)
2514 for (p = 0; p < instr->params_count; ++p)
2516 ir_value *param = instr->params[p];
2518 stmt.opcode = INSTR_STORE_F;
2521 if (param->vtype == TYPE_FIELD)
2522 stmt.opcode = field_store_instr[param->fieldtype];
2524 stmt.opcode = type_store_instr[param->vtype];
2525 stmt.o1.u1 = ir_value_code_addr(param);
2526 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2527 if (code_statements_add(stmt) < 0)
2530 stmt.opcode = INSTR_CALL0 + instr->params_count;
2531 if (stmt.opcode > INSTR_CALL8)
2532 stmt.opcode = INSTR_CALL8;
2533 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2536 if (code_statements_add(stmt) < 0)
2539 retvalue = instr->_ops[0];
2540 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2542 /* not to be kept in OFS_RETURN */
2543 if (retvalue->vtype == TYPE_FIELD)
2544 stmt.opcode = field_store_instr[retvalue->vtype];
2546 stmt.opcode = type_store_instr[retvalue->vtype];
2547 stmt.o1.u1 = OFS_RETURN;
2548 stmt.o2.u1 = ir_value_code_addr(retvalue);
2550 if (code_statements_add(stmt) < 0)
2556 if (instr->opcode == INSTR_STATE) {
2557 irerror(block->context, "TODO: state instruction");
2561 stmt.opcode = instr->opcode;
2566 /* This is the general order of operands */
2568 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2571 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2574 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2576 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2578 stmt.o1.u1 = stmt.o3.u1;
2581 else if ((stmt.opcode >= INSTR_STORE_F &&
2582 stmt.opcode <= INSTR_STORE_FNC) ||
2583 (stmt.opcode >= INSTR_STOREP_F &&
2584 stmt.opcode <= INSTR_STOREP_FNC))
2586 /* 2-operand instructions with A -> B */
2587 stmt.o2.u1 = stmt.o3.u1;
2591 if (code_statements_add(stmt) < 0)
2597 static bool gen_function_code(ir_function *self)
2600 prog_section_statement stmt;
2602 /* Starting from entry point, we generate blocks "as they come"
2603 * for now. Dead blocks will not be translated obviously.
2605 if (!self->blocks_count) {
2606 irerror(self->context, "Function '%s' declared without body.", self->name);
2610 block = self->blocks[0];
2611 if (block->generated)
2614 if (!gen_blocks_recursive(self, block)) {
2615 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2619 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2620 stmt.opcode = AINSTR_END;
2624 if (code_statements_add(stmt) < 0)
2629 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2631 /* NOTE: filename pointers are copied, we never strdup them,
2632 * thus we can use pointer-comparison to find the string.
2637 for (i = 0; i < ir->filenames_count; ++i) {
2638 if (ir->filenames[i] == filename)
2639 return ir->filestrings[i];
2642 str = code_genstring(filename);
2643 if (!ir_builder_filenames_add(ir, filename))
2645 if (!ir_builder_filestrings_add(ir, str))
2646 ir->filenames_count--;
2650 static bool gen_global_function(ir_builder *ir, ir_value *global)
2652 prog_section_function fun;
2656 size_t local_var_end;
2658 if (!global->isconst || (!global->constval.vfunc))
2660 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2664 irfun = global->constval.vfunc;
2666 fun.name = global->code.name;
2667 fun.file = ir_builder_filestring(ir, global->context.file);
2668 fun.profile = 0; /* always 0 */
2669 fun.nargs = irfun->params_count;
2671 for (i = 0;i < 8; ++i) {
2675 fun.argsize[i] = type_sizeof[irfun->params[i]];
2678 fun.firstlocal = code_globals_elements;
2680 local_var_end = fun.firstlocal;
2681 for (i = 0; i < irfun->locals_count; ++i) {
2682 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2683 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2687 if (irfun->locals_count) {
2688 ir_value *last = irfun->locals[irfun->locals_count-1];
2689 local_var_end = last->code.globaladdr;
2690 local_var_end += type_sizeof[last->vtype];
2692 for (i = 0; i < irfun->values_count; ++i)
2694 /* generate code.globaladdr for ssa values */
2695 ir_value *v = irfun->values[i];
2696 ir_value_code_setaddr(v, local_var_end + v->code.local);
2698 for (i = 0; i < irfun->allocated_locals; ++i) {
2699 /* fill the locals with zeros */
2700 code_globals_add(0);
2703 fun.locals = code_globals_elements - fun.firstlocal;
2706 fun.entry = irfun->builtin;
2708 irfun->code_function_def = code_functions_elements;
2709 fun.entry = code_statements_elements;
2712 return (code_functions_add(fun) >= 0);
2715 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2717 prog_section_function *fundef;
2720 irfun = global->constval.vfunc;
2722 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2723 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2724 /* this was a function pointer, don't generate code for those */
2731 if (irfun->code_function_def < 0) {
2732 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2735 fundef = &code_functions_data[irfun->code_function_def];
2737 fundef->entry = code_statements_elements;
2738 if (!gen_function_code(irfun)) {
2739 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2745 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
2749 prog_section_def def;
2751 def.type = global->vtype;
2752 def.offset = code_globals_elements;
2755 if (global->name[0] == '#') {
2756 if (!self->str_immediate)
2757 self->str_immediate = code_genstring("IMMEDIATE");
2758 def.name = global->code.name = self->str_immediate;
2761 def.name = global->code.name = code_genstring(global->name);
2766 switch (global->vtype)
2769 if (!strcmp(global->name, "end_sys_globals")) {
2770 /* TODO: remember this point... all the defs before this one
2771 * should be checksummed and added to progdefs.h when we generate it.
2774 else if (!strcmp(global->name, "end_sys_fields")) {
2775 /* TODO: same as above but for entity-fields rather than globsl
2779 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
2781 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
2782 * the system fields actually go? Though the engine knows this anyway...
2783 * Maybe this could be an -foption
2784 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
2786 ir_value_code_setaddr(global, code_globals_add(0));
2788 if (code_defs_add(def) < 0)
2792 if (code_defs_add(def) < 0)
2794 return gen_global_pointer(global);
2796 if (code_defs_add(def) < 0)
2798 return gen_global_field(global);
2803 if (global->isconst) {
2804 iptr = (int32_t*)&global->constval.ivec[0];
2805 ir_value_code_setaddr(global, code_globals_add(*iptr));
2807 ir_value_code_setaddr(global, code_globals_add(0));
2809 def.type |= DEF_SAVEGLOBAL;
2811 if (code_defs_add(def) < 0)
2814 return global->code.globaladdr >= 0;
2818 if (global->isconst)
2819 ir_value_code_setaddr(global, code_globals_add(code_genstring(global->constval.vstring)));
2821 ir_value_code_setaddr(global, code_globals_add(0));
2823 def.type |= DEF_SAVEGLOBAL;
2825 if (code_defs_add(def) < 0)
2827 return global->code.globaladdr >= 0;
2832 if (global->isconst) {
2833 iptr = (int32_t*)&global->constval.ivec[0];
2834 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2835 if (global->code.globaladdr < 0)
2837 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2839 if (code_globals_add(iptr[d]) < 0)
2843 ir_value_code_setaddr(global, code_globals_add(0));
2844 if (global->code.globaladdr < 0)
2846 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2848 if (code_globals_add(0) < 0)
2852 def.type |= DEF_SAVEGLOBAL;
2855 if (code_defs_add(def) < 0)
2857 return global->code.globaladdr >= 0;
2860 if (!global->isconst) {
2861 ir_value_code_setaddr(global, code_globals_add(0));
2862 if (global->code.globaladdr < 0)
2865 ir_value_code_setaddr(global, code_globals_elements);
2866 code_globals_add(code_functions_elements);
2867 if (!gen_global_function(self, global))
2870 def.type |= DEF_SAVEGLOBAL;
2872 if (code_defs_add(def) < 0)
2876 /* assume biggest type */
2877 ir_value_code_setaddr(global, code_globals_add(0));
2878 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2879 code_globals_add(0);
2882 /* refuse to create 'void' type or any other fancy business. */
2883 irerror(global->context, "Invalid type for global variable `%s`: %s",
2884 global->name, type_name[global->vtype]);
2889 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2891 prog_section_def def;
2892 prog_section_field fld;
2894 def.type = field->vtype;
2895 def.offset = code_globals_elements;
2897 /* create a global named the same as the field */
2898 if (opts_standard == COMPILER_GMQCC) {
2899 /* in our standard, the global gets a dot prefix */
2900 size_t len = strlen(field->name);
2903 /* we really don't want to have to allocate this, and 1024
2904 * bytes is more than enough for a variable/field name
2906 if (len+2 >= sizeof(name)) {
2907 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2912 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2915 def.name = code_genstring(name);
2916 fld.name = def.name + 1; /* we reuse that string table entry */
2918 /* in plain QC, there cannot be a global with the same name,
2919 * and so we also name the global the same.
2920 * FIXME: fteqcc should create a global as well
2921 * check if it actually uses the same name. Probably does
2923 def.name = code_genstring(field->name);
2924 fld.name = def.name;
2927 field->code.name = def.name;
2929 if (code_defs_add(def) < 0)
2932 fld.type = field->fieldtype;
2934 if (fld.type == TYPE_VOID) {
2935 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2939 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2941 if (code_fields_add(fld) < 0)
2944 ir_value_code_setaddr(field, code_globals_elements);
2945 if (!code_globals_add(fld.offset))
2947 if (fld.type == TYPE_VECTOR) {
2948 if (!code_globals_add(fld.offset+1))
2950 if (!code_globals_add(fld.offset+2))
2954 return field->code.globaladdr >= 0;
2957 bool ir_builder_generate(ir_builder *self, const char *filename)
2959 prog_section_statement stmt;
2964 for (i = 0; i < self->globals_count; ++i)
2966 if (!ir_builder_gen_global(self, self->globals[i], false)) {
2971 for (i = 0; i < self->fields_count; ++i)
2973 if (!ir_builder_gen_field(self, self->fields[i])) {
2978 /* generate function code */
2979 for (i = 0; i < self->globals_count; ++i)
2981 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2982 if (!gen_global_function_code(self, self->globals[i])) {
2988 /* DP errors if the last instruction is not an INSTR_DONE
2989 * and for debugging purposes we add an additional AINSTR_END
2990 * to the end of functions, so here it goes:
2992 stmt.opcode = INSTR_DONE;
2996 if (code_statements_add(stmt) < 0)
2999 printf("writing '%s'...\n", filename);
3000 return code_write(filename);
3003 /***********************************************************************
3004 *IR DEBUG Dump functions...
3007 #define IND_BUFSZ 1024
3010 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3013 const char *qc_opname(int op)
3015 if (op < 0) return "<INVALID>";
3016 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3017 return asm_instr[op].m;
3019 case VINSTR_PHI: return "PHI";
3020 case VINSTR_JUMP: return "JUMP";
3021 case VINSTR_COND: return "COND";
3022 default: return "<UNK>";
3026 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3029 char indent[IND_BUFSZ];
3033 oprintf("module %s\n", b->name);
3034 for (i = 0; i < b->globals_count; ++i)
3037 if (b->globals[i]->isconst)
3038 oprintf("%s = ", b->globals[i]->name);
3039 ir_value_dump(b->globals[i], oprintf);
3042 for (i = 0; i < b->functions_count; ++i)
3043 ir_function_dump(b->functions[i], indent, oprintf);
3044 oprintf("endmodule %s\n", b->name);
3047 void ir_function_dump(ir_function *f, char *ind,
3048 int (*oprintf)(const char*, ...))
3051 if (f->builtin != 0) {
3052 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3055 oprintf("%sfunction %s\n", ind, f->name);
3056 strncat(ind, "\t", IND_BUFSZ);
3057 if (f->locals_count)
3059 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
3060 for (i = 0; i < f->locals_count; ++i) {
3061 oprintf("%s\t", ind);
3062 ir_value_dump(f->locals[i], oprintf);
3066 oprintf("%sliferanges:\n", ind);
3067 for (i = 0; i < f->locals_count; ++i) {
3069 ir_value *v = f->locals[i];
3070 oprintf("%s\t%s: unique ", ind, v->name);
3071 for (l = 0; l < v->life_count; ++l) {
3072 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3076 for (i = 0; i < f->values_count; ++i) {
3078 ir_value *v = f->values[i];
3079 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3080 for (l = 0; l < v->life_count; ++l) {
3081 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3085 if (f->blocks_count)
3087 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3088 for (i = 0; i < f->blocks_count; ++i) {
3089 if (f->blocks[i]->run_id != f->run_id) {
3090 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3092 ir_block_dump(f->blocks[i], ind, oprintf);
3096 ind[strlen(ind)-1] = 0;
3097 oprintf("%sendfunction %s\n", ind, f->name);
3100 void ir_block_dump(ir_block* b, char *ind,
3101 int (*oprintf)(const char*, ...))
3104 oprintf("%s:%s\n", ind, b->label);
3105 strncat(ind, "\t", IND_BUFSZ);
3107 for (i = 0; i < b->instr_count; ++i)
3108 ir_instr_dump(b->instr[i], ind, oprintf);
3109 ind[strlen(ind)-1] = 0;
3112 void dump_phi(ir_instr *in, char *ind,
3113 int (*oprintf)(const char*, ...))
3116 oprintf("%s <- phi ", in->_ops[0]->name);
3117 for (i = 0; i < in->phi_count; ++i)
3119 oprintf("([%s] : %s) ", in->phi[i].from->label,
3120 in->phi[i].value->name);
3125 void ir_instr_dump(ir_instr *in, char *ind,
3126 int (*oprintf)(const char*, ...))
3129 const char *comma = NULL;
3131 oprintf("%s (%i) ", ind, (int)in->eid);
3133 if (in->opcode == VINSTR_PHI) {
3134 dump_phi(in, ind, oprintf);
3138 strncat(ind, "\t", IND_BUFSZ);
3140 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3141 ir_value_dump(in->_ops[0], oprintf);
3142 if (in->_ops[1] || in->_ops[2])
3145 if (in->opcode == INSTR_CALL0) {
3146 oprintf("CALL%i\t", in->params_count);
3148 oprintf("%s\t", qc_opname(in->opcode));
3150 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3151 ir_value_dump(in->_ops[0], oprintf);
3156 for (i = 1; i != 3; ++i) {
3160 ir_value_dump(in->_ops[i], oprintf);
3168 oprintf("[%s]", in->bops[0]->label);
3172 oprintf("%s[%s]", comma, in->bops[1]->label);
3173 if (in->params_count) {
3174 oprintf("\tparams: ");
3175 for (i = 0; i != in->params_count; ++i) {
3176 oprintf("%s, ", in->params[i]->name);
3180 ind[strlen(ind)-1] = 0;
3183 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3192 oprintf("fn:%s", v->name);
3195 oprintf("%g", v->constval.vfloat);
3198 oprintf("'%g %g %g'",
3201 v->constval.vvec.z);
3204 oprintf("(entity)");
3207 oprintf("\"%s\"", v->constval.vstring);
3211 oprintf("%i", v->constval.vint);
3216 v->constval.vpointer->name);
3220 oprintf("%s", v->name);
3224 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3227 oprintf("Life of %12s:", self->name);
3228 for (i = 0; i < self->life_count; ++i)
3230 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);