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)) {
178 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
179 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
180 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
182 void ir_builder_delete(ir_builder* self)
185 mem_d((void*)self->name);
186 for (i = 0; i != self->functions_count; ++i) {
187 ir_function_delete(self->functions[i]);
189 MEM_VECTOR_CLEAR(self, functions);
190 for (i = 0; i != self->globals_count; ++i) {
191 ir_value_delete(self->globals[i]);
193 MEM_VECTOR_CLEAR(self, globals);
194 for (i = 0; i != self->fields_count; ++i) {
195 ir_value_delete(self->fields[i]);
197 MEM_VECTOR_CLEAR(self, fields);
201 bool ir_builder_set_name(ir_builder *self, const char *name)
204 mem_d((void*)self->name);
205 self->name = util_strdup(name);
209 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
212 for (i = 0; i < self->functions_count; ++i) {
213 if (!strcmp(name, self->functions[i]->name))
214 return self->functions[i];
219 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
221 ir_function *fn = ir_builder_get_function(self, name);
226 fn = ir_function_new(self, outtype);
227 if (!ir_function_set_name(fn, name) ||
228 !ir_builder_functions_add(self, fn) )
230 ir_function_delete(fn);
234 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
236 ir_function_delete(fn);
240 fn->value->isconst = true;
241 fn->value->outtype = outtype;
242 fn->value->constval.vfunc = fn;
243 fn->value->context = fn->context;
248 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
251 for (i = 0; i < self->globals_count; ++i) {
252 if (!strcmp(self->globals[i]->name, name))
253 return self->globals[i];
258 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
262 if (name && name[0] != '#')
264 ve = ir_builder_get_global(self, name);
270 ve = ir_value_var(name, store_global, vtype);
271 if (!ir_builder_globals_add(self, ve)) {
278 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
281 for (i = 0; i < self->fields_count; ++i) {
282 if (!strcmp(self->fields[i]->name, name))
283 return self->fields[i];
289 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
291 ir_value *ve = ir_builder_get_field(self, name);
296 ve = ir_value_var(name, store_global, TYPE_FIELD);
297 ve->fieldtype = vtype;
298 if (!ir_builder_fields_add(self, ve)) {
305 /***********************************************************************
309 bool ir_function_naive_phi(ir_function*);
310 void ir_function_enumerate(ir_function*);
311 bool ir_function_calculate_liferanges(ir_function*);
312 bool ir_function_allocate_locals(ir_function*);
314 ir_function* ir_function_new(ir_builder* owner, int outtype)
317 self = (ir_function*)mem_a(sizeof(*self));
322 memset(self, 0, sizeof(*self));
325 if (!ir_function_set_name(self, "<@unnamed>")) {
330 self->context.file = "<@no context>";
331 self->context.line = 0;
332 self->outtype = outtype;
335 MEM_VECTOR_INIT(self, params);
336 MEM_VECTOR_INIT(self, blocks);
337 MEM_VECTOR_INIT(self, values);
338 MEM_VECTOR_INIT(self, locals);
340 self->code_function_def = -1;
341 self->allocated_locals = 0;
346 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
347 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
348 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
349 MEM_VEC_FUNCTIONS(ir_function, int, params)
351 bool ir_function_set_name(ir_function *self, const char *name)
354 mem_d((void*)self->name);
355 self->name = util_strdup(name);
359 void ir_function_delete(ir_function *self)
362 mem_d((void*)self->name);
364 for (i = 0; i != self->blocks_count; ++i)
365 ir_block_delete(self->blocks[i]);
366 MEM_VECTOR_CLEAR(self, blocks);
368 MEM_VECTOR_CLEAR(self, params);
370 for (i = 0; i != self->values_count; ++i)
371 ir_value_delete(self->values[i]);
372 MEM_VECTOR_CLEAR(self, values);
374 for (i = 0; i != self->locals_count; ++i)
375 ir_value_delete(self->locals[i]);
376 MEM_VECTOR_CLEAR(self, locals);
378 /* self->value is deleted by the builder */
383 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
385 return ir_function_values_add(self, v);
388 ir_block* ir_function_create_block(ir_function *self, const char *label)
390 ir_block* bn = ir_block_new(self, label);
391 memcpy(&bn->context, &self->context, sizeof(self->context));
392 if (!ir_function_blocks_add(self, bn)) {
399 bool ir_function_finalize(ir_function *self)
404 if (!ir_function_naive_phi(self))
407 ir_function_enumerate(self);
409 if (!ir_function_calculate_liferanges(self))
412 if (!ir_function_allocate_locals(self))
417 ir_value* ir_function_get_local(ir_function *self, const char *name)
420 for (i = 0; i < self->locals_count; ++i) {
421 if (!strcmp(self->locals[i]->name, name))
422 return self->locals[i];
427 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
429 ir_value *ve = ir_function_get_local(self, name);
435 self->locals_count &&
436 self->locals[self->locals_count-1]->store != store_param) {
437 irerror(self->context, "cannot add parameters after adding locals");
441 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
442 if (!ir_function_locals_add(self, ve)) {
449 /***********************************************************************
453 ir_block* ir_block_new(ir_function* owner, const char *name)
456 self = (ir_block*)mem_a(sizeof(*self));
460 memset(self, 0, sizeof(*self));
463 if (!ir_block_set_label(self, name)) {
468 self->context.file = "<@no context>";
469 self->context.line = 0;
471 MEM_VECTOR_INIT(self, instr);
472 MEM_VECTOR_INIT(self, entries);
473 MEM_VECTOR_INIT(self, exits);
476 self->is_return = false;
478 MEM_VECTOR_INIT(self, living);
480 self->generated = false;
484 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
485 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
486 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
487 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
489 void ir_block_delete(ir_block* self)
493 for (i = 0; i != self->instr_count; ++i)
494 ir_instr_delete(self->instr[i]);
495 MEM_VECTOR_CLEAR(self, instr);
496 MEM_VECTOR_CLEAR(self, entries);
497 MEM_VECTOR_CLEAR(self, exits);
498 MEM_VECTOR_CLEAR(self, living);
502 bool ir_block_set_label(ir_block *self, const char *name)
505 mem_d((void*)self->label);
506 self->label = util_strdup(name);
507 return !!self->label;
510 /***********************************************************************
514 ir_instr* ir_instr_new(ir_block* owner, int op)
517 self = (ir_instr*)mem_a(sizeof(*self));
522 self->context.file = "<@no context>";
523 self->context.line = 0;
525 self->_ops[0] = NULL;
526 self->_ops[1] = NULL;
527 self->_ops[2] = NULL;
528 self->bops[0] = NULL;
529 self->bops[1] = NULL;
530 MEM_VECTOR_INIT(self, phi);
531 MEM_VECTOR_INIT(self, params);
536 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
537 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
539 void ir_instr_delete(ir_instr *self)
542 /* The following calls can only delete from
543 * vectors, we still want to delete this instruction
544 * so ignore the return value. Since with the warn_unused_result attribute
545 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
546 * I have to improvise here and use if(foo());
548 for (i = 0; i < self->phi_count; ++i) {
550 if (ir_value_writes_find(self->phi[i].value, self, &idx))
551 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
552 if (ir_value_reads_find(self->phi[i].value, self, &idx))
553 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
555 MEM_VECTOR_CLEAR(self, phi);
556 for (i = 0; i < self->params_count; ++i) {
558 if (ir_value_writes_find(self->params[i], self, &idx))
559 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
560 if (ir_value_reads_find(self->params[i], self, &idx))
561 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
563 MEM_VECTOR_CLEAR(self, params);
564 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
565 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
566 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
570 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
572 if (self->_ops[op]) {
574 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
576 if (!ir_value_writes_remove(self->_ops[op], idx))
579 else if (ir_value_reads_find(self->_ops[op], self, &idx))
581 if (!ir_value_reads_remove(self->_ops[op], idx))
587 if (!ir_value_writes_add(v, self))
590 if (!ir_value_reads_add(v, self))
598 /***********************************************************************
602 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
604 self->code.globaladdr = gaddr;
605 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
606 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
607 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
610 int32_t ir_value_code_addr(const ir_value *self)
612 if (self->store == store_return)
613 return OFS_RETURN + self->code.addroffset;
614 return self->code.globaladdr + self->code.addroffset;
617 ir_value* ir_value_var(const char *name, int storetype, int vtype)
620 self = (ir_value*)mem_a(sizeof(*self));
622 self->fieldtype = TYPE_VOID;
623 self->outtype = TYPE_VOID;
624 self->store = storetype;
625 MEM_VECTOR_INIT(self, reads);
626 MEM_VECTOR_INIT(self, writes);
627 self->isconst = false;
628 self->context.file = "<@no context>";
629 self->context.line = 0;
631 ir_value_set_name(self, name);
633 memset(&self->constval, 0, sizeof(self->constval));
634 memset(&self->code, 0, sizeof(self->code));
636 self->members[0] = NULL;
637 self->members[1] = NULL;
638 self->members[2] = NULL;
639 self->memberof = NULL;
641 MEM_VECTOR_INIT(self, life);
645 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
651 if (self->members[member])
652 return self->members[member];
654 if (self->vtype == TYPE_VECTOR)
656 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
659 m->context = self->context;
661 self->members[member] = m;
662 m->code.addroffset = member;
664 else if (self->vtype == TYPE_FIELD)
666 if (self->fieldtype != TYPE_VECTOR)
668 m = ir_value_var(self->name, self->store, TYPE_FIELD);
671 m->fieldtype = TYPE_FLOAT;
672 m->context = self->context;
674 self->members[member] = m;
675 m->code.addroffset = member;
679 irerror(self->context, "invalid member access on %s", self->name);
687 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
688 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
689 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
691 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
693 ir_value *v = ir_value_var(name, storetype, vtype);
696 if (!ir_function_collect_value(owner, v))
704 void ir_value_delete(ir_value* self)
708 mem_d((void*)self->name);
711 if (self->vtype == TYPE_STRING)
712 mem_d((void*)self->constval.vstring);
714 for (i = 0; i < 3; ++i) {
715 if (self->members[i])
716 ir_value_delete(self->members[i]);
718 MEM_VECTOR_CLEAR(self, reads);
719 MEM_VECTOR_CLEAR(self, writes);
720 MEM_VECTOR_CLEAR(self, life);
724 void ir_value_set_name(ir_value *self, const char *name)
727 mem_d((void*)self->name);
728 self->name = util_strdup(name);
731 bool ir_value_set_float(ir_value *self, float f)
733 if (self->vtype != TYPE_FLOAT)
735 self->constval.vfloat = f;
736 self->isconst = true;
740 bool ir_value_set_func(ir_value *self, int f)
742 if (self->vtype != TYPE_FUNCTION)
744 self->constval.vint = f;
745 self->isconst = true;
749 bool ir_value_set_vector(ir_value *self, vector v)
751 if (self->vtype != TYPE_VECTOR)
753 self->constval.vvec = v;
754 self->isconst = true;
758 bool ir_value_set_field(ir_value *self, ir_value *fld)
760 if (self->vtype != TYPE_FIELD)
762 self->constval.vpointer = fld;
763 self->isconst = true;
767 static char *ir_strdup(const char *str)
770 /* actually dup empty strings */
771 char *out = mem_a(1);
775 return util_strdup(str);
778 bool ir_value_set_string(ir_value *self, const char *str)
780 if (self->vtype != TYPE_STRING)
782 self->constval.vstring = ir_strdup(str);
783 self->isconst = true;
788 bool ir_value_set_int(ir_value *self, int i)
790 if (self->vtype != TYPE_INTEGER)
792 self->constval.vint = i;
793 self->isconst = true;
798 bool ir_value_lives(ir_value *self, size_t at)
801 for (i = 0; i < self->life_count; ++i)
803 ir_life_entry_t *life = &self->life[i];
804 if (life->start <= at && at <= life->end)
806 if (life->start > at) /* since it's ordered */
812 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
815 if (!ir_value_life_add(self, e)) /* naive... */
817 for (k = self->life_count-1; k > idx; --k)
818 self->life[k] = self->life[k-1];
823 bool ir_value_life_merge(ir_value *self, size_t s)
826 ir_life_entry_t *life = NULL;
827 ir_life_entry_t *before = NULL;
828 ir_life_entry_t new_entry;
830 /* Find the first range >= s */
831 for (i = 0; i < self->life_count; ++i)
834 life = &self->life[i];
838 /* nothing found? append */
839 if (i == self->life_count) {
841 if (life && life->end+1 == s)
843 /* previous life range can be merged in */
847 if (life && life->end >= s)
850 if (!ir_value_life_add(self, e))
851 return false; /* failing */
857 if (before->end + 1 == s &&
858 life->start - 1 == s)
861 before->end = life->end;
862 if (!ir_value_life_remove(self, i))
863 return false; /* failing */
866 if (before->end + 1 == s)
872 /* already contained */
873 if (before->end >= s)
877 if (life->start - 1 == s)
882 /* insert a new entry */
883 new_entry.start = new_entry.end = s;
884 return ir_value_life_insert(self, i, new_entry);
887 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
891 if (!other->life_count)
894 if (!self->life_count) {
895 for (i = 0; i < other->life_count; ++i) {
896 if (!ir_value_life_add(self, other->life[i]))
903 for (i = 0; i < other->life_count; ++i)
905 const ir_life_entry_t *life = &other->life[i];
908 ir_life_entry_t *entry = &self->life[myi];
910 if (life->end+1 < entry->start)
912 /* adding an interval before entry */
913 if (!ir_value_life_insert(self, myi, *life))
919 if (life->start < entry->start &&
920 life->end >= entry->start)
922 /* starts earlier and overlaps */
923 entry->start = life->start;
926 if (life->end > entry->end &&
927 life->start-1 <= entry->end)
929 /* ends later and overlaps */
930 entry->end = life->end;
933 /* see if our change combines it with the next ranges */
934 while (myi+1 < self->life_count &&
935 entry->end+1 >= self->life[1+myi].start)
937 /* overlaps with (myi+1) */
938 if (entry->end < self->life[1+myi].end)
939 entry->end = self->life[1+myi].end;
940 if (!ir_value_life_remove(self, myi+1))
942 entry = &self->life[myi];
945 /* see if we're after the entry */
946 if (life->start > entry->end)
949 /* append if we're at the end */
950 if (myi >= self->life_count) {
951 if (!ir_value_life_add(self, *life))
955 /* otherweise check the next range */
964 bool ir_values_overlap(const ir_value *a, const ir_value *b)
966 /* For any life entry in A see if it overlaps with
967 * any life entry in B.
968 * Note that the life entries are orderes, so we can make a
969 * more efficient algorithm there than naively translating the
973 ir_life_entry_t *la, *lb, *enda, *endb;
975 /* first of all, if either has no life range, they cannot clash */
976 if (!a->life_count || !b->life_count)
981 enda = la + a->life_count;
982 endb = lb + b->life_count;
985 /* check if the entries overlap, for that,
986 * both must start before the other one ends.
988 if (la->start < lb->end &&
994 /* entries are ordered
995 * one entry is earlier than the other
996 * that earlier entry will be moved forward
998 if (la->start < lb->start)
1000 /* order: A B, move A forward
1001 * check if we hit the end with A
1006 else /* if (lb->start < la->start) actually <= */
1008 /* order: B A, move B forward
1009 * check if we hit the end with B
1018 /***********************************************************************
1022 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1024 ir_instr *in = ir_instr_new(self, op);
1028 if (target->store == store_value &&
1029 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1031 irerror(self->context, "cannot store to an SSA value");
1032 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1033 irerror(self->context, "instruction: %s", asm_instr[op].m);
1037 if (!ir_instr_op(in, 0, target, true) ||
1038 !ir_instr_op(in, 1, what, false) ||
1039 !ir_block_instr_add(self, in) )
1046 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1050 if (target->vtype == TYPE_VARIANT)
1051 vtype = what->vtype;
1053 vtype = target->vtype;
1056 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1057 op = INSTR_CONV_ITOF;
1058 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1059 op = INSTR_CONV_FTOI;
1061 op = type_store_instr[vtype];
1063 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1064 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1068 return ir_block_create_store_op(self, op, target, what);
1071 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1076 if (target->vtype != TYPE_POINTER)
1079 /* storing using pointer - target is a pointer, type must be
1080 * inferred from source
1082 vtype = what->vtype;
1084 op = type_storep_instr[vtype];
1085 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1086 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1087 op = INSTR_STOREP_V;
1090 return ir_block_create_store_op(self, op, target, what);
1093 bool ir_block_create_return(ir_block *self, ir_value *v)
1097 irerror(self->context, "block already ended (%s)", self->label);
1101 self->is_return = true;
1102 in = ir_instr_new(self, INSTR_RETURN);
1106 if (v && !ir_instr_op(in, 0, v, false))
1109 if (!ir_block_instr_add(self, in))
1114 bool ir_block_create_if(ir_block *self, ir_value *v,
1115 ir_block *ontrue, ir_block *onfalse)
1119 irerror(self->context, "block already ended (%s)", self->label);
1123 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1124 in = ir_instr_new(self, VINSTR_COND);
1128 if (!ir_instr_op(in, 0, v, false)) {
1129 ir_instr_delete(in);
1133 in->bops[0] = ontrue;
1134 in->bops[1] = onfalse;
1136 if (!ir_block_instr_add(self, in))
1139 if (!ir_block_exits_add(self, ontrue) ||
1140 !ir_block_exits_add(self, onfalse) ||
1141 !ir_block_entries_add(ontrue, self) ||
1142 !ir_block_entries_add(onfalse, self) )
1149 bool ir_block_create_jump(ir_block *self, ir_block *to)
1153 irerror(self->context, "block already ended (%s)", self->label);
1157 in = ir_instr_new(self, VINSTR_JUMP);
1162 if (!ir_block_instr_add(self, in))
1165 if (!ir_block_exits_add(self, to) ||
1166 !ir_block_entries_add(to, self) )
1173 bool ir_block_create_goto(ir_block *self, ir_block *to)
1177 irerror(self->context, "block already ended (%s)", self->label);
1181 in = ir_instr_new(self, INSTR_GOTO);
1186 if (!ir_block_instr_add(self, in))
1189 if (!ir_block_exits_add(self, to) ||
1190 !ir_block_entries_add(to, self) )
1197 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1201 in = ir_instr_new(self, VINSTR_PHI);
1204 out = ir_value_out(self->owner, label, store_value, ot);
1206 ir_instr_delete(in);
1209 if (!ir_instr_op(in, 0, out, true)) {
1210 ir_instr_delete(in);
1211 ir_value_delete(out);
1214 if (!ir_block_instr_add(self, in)) {
1215 ir_instr_delete(in);
1216 ir_value_delete(out);
1222 ir_value* ir_phi_value(ir_instr *self)
1224 return self->_ops[0];
1227 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1231 if (!ir_block_entries_find(self->owner, b, NULL)) {
1232 /* Must not be possible to cause this, otherwise the AST
1233 * is doing something wrong.
1235 irerror(self->context, "Invalid entry block for PHI");
1241 if (!ir_value_reads_add(v, self))
1243 return ir_instr_phi_add(self, pe);
1246 /* call related code */
1247 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1251 in = ir_instr_new(self, INSTR_CALL0);
1254 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1256 ir_instr_delete(in);
1259 if (!ir_instr_op(in, 0, out, true) ||
1260 !ir_instr_op(in, 1, func, false) ||
1261 !ir_block_instr_add(self, in))
1263 ir_instr_delete(in);
1264 ir_value_delete(out);
1270 ir_value* ir_call_value(ir_instr *self)
1272 return self->_ops[0];
1275 bool ir_call_param(ir_instr* self, ir_value *v)
1277 if (!ir_instr_params_add(self, v))
1279 if (!ir_value_reads_add(v, self)) {
1280 if (!ir_instr_params_remove(self, self->params_count-1))
1281 GMQCC_SUPPRESS_EMPTY_BODY;
1287 /* binary op related code */
1289 ir_value* ir_block_create_binop(ir_block *self,
1290 const char *label, int opcode,
1291 ir_value *left, ir_value *right)
1313 case INSTR_SUB_S: /* -- offset of string as float */
1318 case INSTR_BITOR_IF:
1319 case INSTR_BITOR_FI:
1320 case INSTR_BITAND_FI:
1321 case INSTR_BITAND_IF:
1336 case INSTR_BITAND_I:
1339 case INSTR_RSHIFT_I:
1340 case INSTR_LSHIFT_I:
1362 /* boolean operations result in floats */
1363 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1365 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1368 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1373 if (ot == TYPE_VOID) {
1374 /* The AST or parser were supposed to check this! */
1378 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1381 ir_value* ir_block_create_unary(ir_block *self,
1382 const char *label, int opcode,
1385 int ot = TYPE_FLOAT;
1397 /* QC doesn't have other unary operations. We expect extensions to fill
1398 * the above list, otherwise we assume out-type = in-type, eg for an
1402 ot = operand->vtype;
1405 if (ot == TYPE_VOID) {
1406 /* The AST or parser were supposed to check this! */
1410 /* let's use the general instruction creator and pass NULL for OPB */
1411 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1414 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1415 int op, ir_value *a, ir_value *b, int outype)
1420 out = ir_value_out(self->owner, label, store_value, outype);
1424 instr = ir_instr_new(self, op);
1426 ir_value_delete(out);
1430 if (!ir_instr_op(instr, 0, out, true) ||
1431 !ir_instr_op(instr, 1, a, false) ||
1432 !ir_instr_op(instr, 2, b, false) )
1437 if (!ir_block_instr_add(self, instr))
1442 ir_instr_delete(instr);
1443 ir_value_delete(out);
1447 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1451 /* Support for various pointer types todo if so desired */
1452 if (ent->vtype != TYPE_ENTITY)
1455 if (field->vtype != TYPE_FIELD)
1458 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1459 v->fieldtype = field->fieldtype;
1463 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1466 if (ent->vtype != TYPE_ENTITY)
1469 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1470 if (field->vtype != TYPE_FIELD)
1475 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1476 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1477 case TYPE_STRING: op = INSTR_LOAD_S; break;
1478 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1479 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1480 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1482 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1483 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1489 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1492 ir_value* ir_block_create_add(ir_block *self,
1494 ir_value *left, ir_value *right)
1497 int l = left->vtype;
1498 int r = right->vtype;
1517 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1519 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1525 return ir_block_create_binop(self, label, op, left, right);
1528 ir_value* ir_block_create_sub(ir_block *self,
1530 ir_value *left, ir_value *right)
1533 int l = left->vtype;
1534 int r = right->vtype;
1554 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1556 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1562 return ir_block_create_binop(self, label, op, left, right);
1565 ir_value* ir_block_create_mul(ir_block *self,
1567 ir_value *left, ir_value *right)
1570 int l = left->vtype;
1571 int r = right->vtype;
1590 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1592 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1595 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1597 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1599 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1601 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1607 return ir_block_create_binop(self, label, op, left, right);
1610 ir_value* ir_block_create_div(ir_block *self,
1612 ir_value *left, ir_value *right)
1615 int l = left->vtype;
1616 int r = right->vtype;
1633 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1635 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1637 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1643 return ir_block_create_binop(self, label, op, left, right);
1646 /* PHI resolving breaks the SSA, and must thus be the last
1647 * step before life-range calculation.
1650 static bool ir_block_naive_phi(ir_block *self);
1651 bool ir_function_naive_phi(ir_function *self)
1655 for (i = 0; i < self->blocks_count; ++i)
1657 if (!ir_block_naive_phi(self->blocks[i]))
1663 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1668 /* create a store */
1669 if (!ir_block_create_store(block, old, what))
1672 /* we now move it up */
1673 instr = block->instr[block->instr_count-1];
1674 for (i = block->instr_count; i > iid; --i)
1675 block->instr[i] = block->instr[i-1];
1676 block->instr[i] = instr;
1681 static bool ir_block_naive_phi(ir_block *self)
1684 /* FIXME: optionally, create_phi can add the phis
1685 * to a list so we don't need to loop through blocks
1686 * - anyway: "don't optimize YET"
1688 for (i = 0; i < self->instr_count; ++i)
1690 ir_instr *instr = self->instr[i];
1691 if (instr->opcode != VINSTR_PHI)
1694 if (!ir_block_instr_remove(self, i))
1696 --i; /* NOTE: i+1 below */
1698 for (p = 0; p < instr->phi_count; ++p)
1700 ir_value *v = instr->phi[p].value;
1701 for (w = 0; w < v->writes_count; ++w) {
1704 if (!v->writes[w]->_ops[0])
1707 /* When the write was to a global, we have to emit a mov */
1708 old = v->writes[w]->_ops[0];
1710 /* The original instruction now writes to the PHI target local */
1711 if (v->writes[w]->_ops[0] == v)
1712 v->writes[w]->_ops[0] = instr->_ops[0];
1714 if (old->store != store_value && old->store != store_local && old->store != store_param)
1716 /* If it originally wrote to a global we need to store the value
1719 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1721 if (i+1 < self->instr_count)
1722 instr = self->instr[i+1];
1725 /* In case I forget and access instr later, it'll be NULL
1726 * when it's a problem, to make sure we crash, rather than accessing
1732 /* If it didn't, we can replace all reads by the phi target now. */
1734 for (r = 0; r < old->reads_count; ++r)
1737 ir_instr *ri = old->reads[r];
1738 for (op = 0; op < ri->phi_count; ++op) {
1739 if (ri->phi[op].value == old)
1740 ri->phi[op].value = v;
1742 for (op = 0; op < 3; ++op) {
1743 if (ri->_ops[op] == old)
1750 ir_instr_delete(instr);
1755 /***********************************************************************
1756 *IR Temp allocation code
1757 * Propagating value life ranges by walking through the function backwards
1758 * until no more changes are made.
1759 * In theory this should happen once more than once for every nested loop
1761 * Though this implementation might run an additional time for if nests.
1770 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1772 /* Enumerate instructions used by value's life-ranges
1774 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1778 for (i = 0; i < self->instr_count; ++i)
1780 self->instr[i]->eid = eid++;
1785 /* Enumerate blocks and instructions.
1786 * The block-enumeration is unordered!
1787 * We do not really use the block enumreation, however
1788 * the instruction enumeration is important for life-ranges.
1790 void ir_function_enumerate(ir_function *self)
1793 size_t instruction_id = 0;
1794 for (i = 0; i < self->blocks_count; ++i)
1796 self->blocks[i]->eid = i;
1797 self->blocks[i]->run_id = 0;
1798 ir_block_enumerate(self->blocks[i], &instruction_id);
1802 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1803 bool ir_function_calculate_liferanges(ir_function *self)
1811 for (i = 0; i != self->blocks_count; ++i)
1813 if (self->blocks[i]->is_return)
1815 self->blocks[i]->living_count = 0;
1816 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1821 if (self->blocks_count) {
1822 ir_block *block = self->blocks[0];
1823 for (i = 0; i < block->living_count; ++i) {
1824 ir_value *v = block->living[i];
1825 if (v->memberof || v->store != store_local)
1827 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1828 "variable `%s` may be used uninitialized in this function", v->name))
1837 /* Local-value allocator
1838 * After finishing creating the liferange of all values used in a function
1839 * we can allocate their global-positions.
1840 * This is the counterpart to register-allocation in register machines.
1843 MEM_VECTOR_MAKE(ir_value*, locals);
1844 MEM_VECTOR_MAKE(size_t, sizes);
1845 MEM_VECTOR_MAKE(size_t, positions);
1846 } function_allocator;
1847 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1848 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1849 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1851 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1854 size_t vsize = type_sizeof[var->vtype];
1856 slot = ir_value_var("reg", store_global, var->vtype);
1860 if (!ir_value_life_merge_into(slot, var))
1863 if (!function_allocator_locals_add(alloc, slot))
1866 if (!function_allocator_sizes_add(alloc, vsize))
1872 ir_value_delete(slot);
1876 bool ir_function_allocate_locals(ir_function *self)
1885 function_allocator alloc;
1887 if (!self->locals_count && !self->values_count)
1890 MEM_VECTOR_INIT(&alloc, locals);
1891 MEM_VECTOR_INIT(&alloc, sizes);
1892 MEM_VECTOR_INIT(&alloc, positions);
1894 for (i = 0; i < self->locals_count; ++i)
1896 if (!function_allocator_alloc(&alloc, self->locals[i]))
1900 /* Allocate a slot for any value that still exists */
1901 for (i = 0; i < self->values_count; ++i)
1903 v = self->values[i];
1908 for (a = 0; a < alloc.locals_count; ++a)
1910 slot = alloc.locals[a];
1912 if (ir_values_overlap(v, slot))
1915 if (!ir_value_life_merge_into(slot, v))
1918 /* adjust size for this slot */
1919 if (alloc.sizes[a] < type_sizeof[v->vtype])
1920 alloc.sizes[a] = type_sizeof[v->vtype];
1922 self->values[i]->code.local = a;
1925 if (a >= alloc.locals_count) {
1926 self->values[i]->code.local = alloc.locals_count;
1927 if (!function_allocator_alloc(&alloc, v))
1936 /* Adjust slot positions based on sizes */
1937 if (!function_allocator_positions_add(&alloc, 0))
1940 if (alloc.sizes_count)
1941 pos = alloc.positions[0] + alloc.sizes[0];
1944 for (i = 1; i < alloc.sizes_count; ++i)
1946 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1947 if (!function_allocator_positions_add(&alloc, pos))
1951 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1953 /* Take over the actual slot positions */
1954 for (i = 0; i < self->values_count; ++i) {
1955 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1963 for (i = 0; i < alloc.locals_count; ++i)
1964 ir_value_delete(alloc.locals[i]);
1965 MEM_VECTOR_CLEAR(&alloc, locals);
1966 MEM_VECTOR_CLEAR(&alloc, sizes);
1967 MEM_VECTOR_CLEAR(&alloc, positions);
1971 /* Get information about which operand
1972 * is read from, or written to.
1974 static void ir_op_read_write(int op, size_t *read, size_t *write)
1994 case INSTR_STOREP_F:
1995 case INSTR_STOREP_V:
1996 case INSTR_STOREP_S:
1997 case INSTR_STOREP_ENT:
1998 case INSTR_STOREP_FLD:
1999 case INSTR_STOREP_FNC:
2010 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2013 bool changed = false;
2015 for (i = 0; i != self->living_count; ++i)
2017 tempbool = ir_value_life_merge(self->living[i], eid);
2020 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2022 changed = changed || tempbool;
2027 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2030 /* values which have been read in a previous iteration are now
2031 * in the "living" array even if the previous block doesn't use them.
2032 * So we have to remove whatever does not exist in the previous block.
2033 * They will be re-added on-read, but the liferange merge won't cause
2036 for (i = 0; i < self->living_count; ++i)
2038 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2039 if (!ir_block_living_remove(self, i))
2045 /* Whatever the previous block still has in its living set
2046 * must now be added to ours as well.
2048 for (i = 0; i < prev->living_count; ++i)
2050 if (ir_block_living_find(self, prev->living[i], NULL))
2052 if (!ir_block_living_add(self, prev->living[i]))
2055 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2061 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2067 /* bitmasks which operands are read from or written to */
2069 char dbg_ind[16] = { '#', '0' };
2074 if (!ir_block_life_prop_previous(self, prev, changed))
2078 i = self->instr_count;
2081 instr = self->instr[i];
2083 /* PHI operands are always read operands */
2084 for (p = 0; p < instr->phi_count; ++p)
2086 value = instr->phi[p].value;
2087 if (value->memberof)
2088 value = value->memberof;
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 (value->memberof)
2101 value = value->memberof;
2102 if (!ir_block_living_find(self, value, NULL) &&
2103 !ir_block_living_add(self, value))
2109 /* See which operands are read and write operands */
2110 ir_op_read_write(instr->opcode, &read, &write);
2112 /* Go through the 3 main operands */
2113 for (o = 0; o < 3; ++o)
2115 if (!instr->_ops[o]) /* no such operand */
2118 value = instr->_ops[o];
2119 if (value->memberof)
2120 value = value->memberof;
2122 /* We only care about locals */
2123 /* we also calculate parameter liferanges so that locals
2124 * can take up parameter slots */
2125 if (value->store != store_value &&
2126 value->store != store_local &&
2127 value->store != store_param)
2133 if (!ir_block_living_find(self, value, NULL) &&
2134 !ir_block_living_add(self, value))
2140 /* write operands */
2141 /* When we write to a local, we consider it "dead" for the
2142 * remaining upper part of the function, since in SSA a value
2143 * can only be written once (== created)
2148 bool in_living = ir_block_living_find(self, value, &idx);
2151 /* If the value isn't alive it hasn't been read before... */
2152 /* TODO: See if the warning can be emitted during parsing or AST processing
2153 * otherwise have warning printed here.
2154 * IF printing a warning here: include filecontext_t,
2155 * and make sure it's only printed once
2156 * since this function is run multiple times.
2158 /* For now: debug info: */
2159 /* fprintf(stderr, "Value only written %s\n", value->name); */
2160 tempbool = ir_value_life_merge(value, instr->eid);
2161 *changed = *changed || tempbool;
2163 ir_instr_dump(instr, dbg_ind, printf);
2167 /* since 'living' won't contain it
2168 * anymore, merge the value, since
2171 tempbool = ir_value_life_merge(value, instr->eid);
2174 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2176 *changed = *changed || tempbool;
2178 if (!ir_block_living_remove(self, idx))
2184 tempbool = ir_block_living_add_instr(self, instr->eid);
2185 /*fprintf(stderr, "living added values\n");*/
2186 *changed = *changed || tempbool;
2190 if (self->run_id == self->owner->run_id)
2193 self->run_id = self->owner->run_id;
2195 for (i = 0; i < self->entries_count; ++i)
2197 ir_block *entry = self->entries[i];
2198 ir_block_life_propagate(entry, self, changed);
2204 /***********************************************************************
2207 * Since the IR has the convention of putting 'write' operands
2208 * at the beginning, we have to rotate the operands of instructions
2209 * properly in order to generate valid QCVM code.
2211 * Having destinations at a fixed position is more convenient. In QC
2212 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2213 * read from from OPA, and store to OPB rather than OPC. Which is
2214 * partially the reason why the implementation of these instructions
2215 * in darkplaces has been delayed for so long.
2217 * Breaking conventions is annoying...
2219 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2221 static bool gen_global_field(ir_value *global)
2223 if (global->isconst)
2225 ir_value *fld = global->constval.vpointer;
2227 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2231 /* Now, in this case, a relocation would be impossible to code
2232 * since it looks like this:
2233 * .vector v = origin; <- parse error, wtf is 'origin'?
2236 * But we will need a general relocation support later anyway
2237 * for functions... might as well support that here.
2239 if (!fld->code.globaladdr) {
2240 irerror(global->context, "FIXME: Relocation support");
2244 /* copy the field's value */
2245 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2246 if (global->fieldtype == TYPE_VECTOR) {
2247 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2248 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2253 ir_value_code_setaddr(global, code_globals_add(0));
2254 if (global->fieldtype == TYPE_VECTOR) {
2255 code_globals_add(0);
2256 code_globals_add(0);
2259 if (global->code.globaladdr < 0)
2264 static bool gen_global_pointer(ir_value *global)
2266 if (global->isconst)
2268 ir_value *target = global->constval.vpointer;
2270 irerror(global->context, "Invalid pointer constant: %s", global->name);
2271 /* NULL pointers are pointing to the NULL constant, which also
2272 * sits at address 0, but still has an ir_value for itself.
2277 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2278 * void() foo; <- proto
2279 * void() *fooptr = &foo;
2280 * void() foo = { code }
2282 if (!target->code.globaladdr) {
2283 /* FIXME: Check for the constant nullptr ir_value!
2284 * because then code.globaladdr being 0 is valid.
2286 irerror(global->context, "FIXME: Relocation support");
2290 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2294 ir_value_code_setaddr(global, code_globals_add(0));
2296 if (global->code.globaladdr < 0)
2301 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2303 prog_section_statement stmt;
2312 block->generated = true;
2313 block->code_start = code_statements_elements;
2314 for (i = 0; i < block->instr_count; ++i)
2316 instr = block->instr[i];
2318 if (instr->opcode == VINSTR_PHI) {
2319 irerror(block->context, "cannot generate virtual instruction (phi)");
2323 if (instr->opcode == VINSTR_JUMP) {
2324 target = instr->bops[0];
2325 /* for uncoditional jumps, if the target hasn't been generated
2326 * yet, we generate them right here.
2328 if (!target->generated) {
2333 /* otherwise we generate a jump instruction */
2334 stmt.opcode = INSTR_GOTO;
2335 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2338 if (code_statements_add(stmt) < 0)
2341 /* no further instructions can be in this block */
2345 if (instr->opcode == VINSTR_COND) {
2346 ontrue = instr->bops[0];
2347 onfalse = instr->bops[1];
2348 /* TODO: have the AST signal which block should
2349 * come first: eg. optimize IFs without ELSE...
2352 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2356 if (ontrue->generated) {
2357 stmt.opcode = INSTR_IF;
2358 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2359 if (code_statements_add(stmt) < 0)
2362 if (onfalse->generated) {
2363 stmt.opcode = INSTR_IFNOT;
2364 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2365 if (code_statements_add(stmt) < 0)
2368 if (!ontrue->generated) {
2369 if (onfalse->generated) {
2374 if (!onfalse->generated) {
2375 if (ontrue->generated) {
2380 /* neither ontrue nor onfalse exist */
2381 stmt.opcode = INSTR_IFNOT;
2382 stidx = code_statements_elements;
2383 if (code_statements_add(stmt) < 0)
2385 /* on false we jump, so add ontrue-path */
2386 if (!gen_blocks_recursive(func, ontrue))
2388 /* fixup the jump address */
2389 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2390 /* generate onfalse path */
2391 if (onfalse->generated) {
2392 /* fixup the jump address */
2393 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2394 /* may have been generated in the previous recursive call */
2395 stmt.opcode = INSTR_GOTO;
2396 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2399 return (code_statements_add(stmt) >= 0);
2401 /* if not, generate now */
2406 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2407 /* Trivial call translation:
2408 * copy all params to OFS_PARM*
2409 * if the output's storetype is not store_return,
2410 * add append a STORE instruction!
2412 * NOTES on how to do it better without much trouble:
2413 * -) The liferanges!
2414 * Simply check the liferange of all parameters for
2415 * other CALLs. For each param with no CALL in its
2416 * liferange, we can store it in an OFS_PARM at
2417 * generation already. This would even include later
2418 * reuse.... probably... :)
2423 for (p = 0; p < instr->params_count; ++p)
2425 ir_value *param = instr->params[p];
2427 stmt.opcode = INSTR_STORE_F;
2430 stmt.opcode = type_store_instr[param->vtype];
2431 stmt.o1.u1 = ir_value_code_addr(param);
2432 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2433 if (code_statements_add(stmt) < 0)
2436 stmt.opcode = INSTR_CALL0 + instr->params_count;
2437 if (stmt.opcode > INSTR_CALL8)
2438 stmt.opcode = INSTR_CALL8;
2439 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2442 if (code_statements_add(stmt) < 0)
2445 retvalue = instr->_ops[0];
2446 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2448 /* not to be kept in OFS_RETURN */
2449 stmt.opcode = type_store_instr[retvalue->vtype];
2450 stmt.o1.u1 = OFS_RETURN;
2451 stmt.o2.u1 = ir_value_code_addr(retvalue);
2453 if (code_statements_add(stmt) < 0)
2459 if (instr->opcode == INSTR_STATE) {
2460 irerror(block->context, "TODO: state instruction");
2464 stmt.opcode = instr->opcode;
2469 /* This is the general order of operands */
2471 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2474 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2477 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2479 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2481 stmt.o1.u1 = stmt.o3.u1;
2484 else if ((stmt.opcode >= INSTR_STORE_F &&
2485 stmt.opcode <= INSTR_STORE_FNC) ||
2486 (stmt.opcode >= INSTR_STOREP_F &&
2487 stmt.opcode <= INSTR_STOREP_FNC))
2489 /* 2-operand instructions with A -> B */
2490 stmt.o2.u1 = stmt.o3.u1;
2494 if (code_statements_add(stmt) < 0)
2500 static bool gen_function_code(ir_function *self)
2503 prog_section_statement stmt;
2505 /* Starting from entry point, we generate blocks "as they come"
2506 * for now. Dead blocks will not be translated obviously.
2508 if (!self->blocks_count) {
2509 irerror(self->context, "Function '%s' declared without body.", self->name);
2513 block = self->blocks[0];
2514 if (block->generated)
2517 if (!gen_blocks_recursive(self, block)) {
2518 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2522 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2523 stmt.opcode = AINSTR_END;
2527 if (code_statements_add(stmt) < 0)
2532 static bool gen_global_function(ir_builder *ir, ir_value *global)
2534 prog_section_function fun;
2538 size_t local_var_end;
2540 if (!global->isconst || (!global->constval.vfunc))
2542 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2546 irfun = global->constval.vfunc;
2548 fun.name = global->code.name;
2549 fun.file = code_cachedstring(global->context.file);
2550 fun.profile = 0; /* always 0 */
2551 fun.nargs = irfun->params_count;
2553 for (i = 0;i < 8; ++i) {
2557 fun.argsize[i] = type_sizeof[irfun->params[i]];
2560 fun.firstlocal = code_globals_elements;
2561 fun.locals = irfun->allocated_locals + irfun->locals_count;
2563 local_var_end = fun.firstlocal;
2564 for (i = 0; i < irfun->locals_count; ++i) {
2565 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2566 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2570 if (irfun->locals_count) {
2571 ir_value *last = irfun->locals[irfun->locals_count-1];
2572 local_var_end = last->code.globaladdr;
2573 local_var_end += type_sizeof[last->vtype];
2575 for (i = 0; i < irfun->values_count; ++i)
2577 /* generate code.globaladdr for ssa values */
2578 ir_value *v = irfun->values[i];
2579 ir_value_code_setaddr(v, local_var_end + v->code.local);
2581 for (i = 0; i < irfun->allocated_locals; ++i) {
2582 /* fill the locals with zeros */
2583 code_globals_add(0);
2587 fun.entry = irfun->builtin;
2589 irfun->code_function_def = code_functions_elements;
2590 fun.entry = code_statements_elements;
2593 return (code_functions_add(fun) >= 0);
2596 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2598 prog_section_function *fundef;
2601 irfun = global->constval.vfunc;
2603 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2604 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2605 /* this was a function pointer, don't generate code for those */
2612 if (irfun->code_function_def < 0) {
2613 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2616 fundef = &code_functions_data[irfun->code_function_def];
2618 fundef->entry = code_statements_elements;
2619 if (!gen_function_code(irfun)) {
2620 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2626 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2630 prog_section_def def;
2632 def.type = global->vtype;
2633 def.offset = code_globals_elements;
2634 def.name = global->code.name = code_genstring(global->name);
2636 switch (global->vtype)
2639 if (!strcmp(global->name, "end_sys_globals")) {
2640 /* TODO: remember this point... all the defs before this one
2641 * should be checksummed and added to progdefs.h when we generate it.
2644 else if (!strcmp(global->name, "end_sys_fields")) {
2645 /* TODO: same as above but for entity-fields rather than globsl
2649 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
2651 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
2652 * the system fields actually go? Though the engine knows this anyway...
2653 * Maybe this could be an -foption
2655 ir_value_code_setaddr(global, def.offset);
2657 if (code_defs_add(def) < 0)
2661 if (code_defs_add(def) < 0)
2663 return gen_global_pointer(global);
2665 if (code_defs_add(def) < 0)
2667 return gen_global_field(global);
2672 if (code_defs_add(def) < 0)
2675 if (global->isconst) {
2676 iptr = (int32_t*)&global->constval.vfloat;
2677 ir_value_code_setaddr(global, code_globals_add(*iptr));
2679 ir_value_code_setaddr(global, code_globals_add(0));
2681 return global->code.globaladdr >= 0;
2685 if (code_defs_add(def) < 0)
2687 if (global->isconst)
2688 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2690 ir_value_code_setaddr(global, code_globals_add(0));
2691 return global->code.globaladdr >= 0;
2696 if (code_defs_add(def) < 0)
2699 if (global->isconst) {
2700 iptr = (int32_t*)&global->constval.vvec;
2701 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2702 if (global->code.globaladdr < 0)
2704 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2706 if (code_globals_add(iptr[d]) < 0)
2710 ir_value_code_setaddr(global, code_globals_add(0));
2711 if (global->code.globaladdr < 0)
2713 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2715 if (code_globals_add(0) < 0)
2719 return global->code.globaladdr >= 0;
2722 if (code_defs_add(def) < 0)
2724 if (!global->isconst) {
2725 ir_value_code_setaddr(global, code_globals_add(0));
2726 return global->code.globaladdr >= 0;
2728 ir_value_code_setaddr(global, code_globals_elements);
2729 code_globals_add(code_functions_elements);
2730 return gen_global_function(self, global);
2733 /* assume biggest type */
2734 ir_value_code_setaddr(global, code_globals_add(0));
2735 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2736 code_globals_add(0);
2739 /* refuse to create 'void' type or any other fancy business. */
2740 irerror(global->context, "Invalid type for global variable `%s`: %s",
2741 global->name, type_name[global->vtype]);
2746 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2748 prog_section_def def;
2749 prog_section_field fld;
2751 def.type = field->vtype;
2752 def.offset = code_globals_elements;
2754 /* create a global named the same as the field */
2755 if (opts_standard == COMPILER_GMQCC) {
2756 /* in our standard, the global gets a dot prefix */
2757 size_t len = strlen(field->name);
2760 /* we really don't want to have to allocate this, and 1024
2761 * bytes is more than enough for a variable/field name
2763 if (len+2 >= sizeof(name)) {
2764 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2769 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2772 def.name = code_genstring(name);
2773 fld.name = def.name + 1; /* we reuse that string table entry */
2775 /* in plain QC, there cannot be a global with the same name,
2776 * and so we also name the global the same.
2777 * FIXME: fteqcc should create a global as well
2778 * check if it actually uses the same name. Probably does
2780 def.name = code_genstring(field->name);
2781 fld.name = def.name;
2784 field->code.name = def.name;
2786 if (code_defs_add(def) < 0)
2789 fld.type = field->fieldtype;
2791 if (fld.type == TYPE_VOID) {
2792 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2796 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2798 if (code_fields_add(fld) < 0)
2801 ir_value_code_setaddr(field, code_globals_elements);
2802 if (!code_globals_add(fld.offset))
2804 if (fld.type == TYPE_VECTOR) {
2805 if (!code_globals_add(fld.offset+1))
2807 if (!code_globals_add(fld.offset+2))
2811 return field->code.globaladdr >= 0;
2814 bool ir_builder_generate(ir_builder *self, const char *filename)
2816 prog_section_statement stmt;
2821 for (i = 0; i < self->globals_count; ++i)
2823 if (!ir_builder_gen_global(self, self->globals[i])) {
2828 for (i = 0; i < self->fields_count; ++i)
2830 if (!ir_builder_gen_field(self, self->fields[i])) {
2835 /* generate function code */
2836 for (i = 0; i < self->globals_count; ++i)
2838 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2839 if (!gen_global_function_code(self, self->globals[i])) {
2845 /* DP errors if the last instruction is not an INSTR_DONE
2846 * and for debugging purposes we add an additional AINSTR_END
2847 * to the end of functions, so here it goes:
2849 stmt.opcode = INSTR_DONE;
2853 if (code_statements_add(stmt) < 0)
2856 printf("writing '%s'...\n", filename);
2857 return code_write(filename);
2860 /***********************************************************************
2861 *IR DEBUG Dump functions...
2864 #define IND_BUFSZ 1024
2867 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2869 # define strncat strncat
2872 const char *qc_opname(int op)
2874 if (op < 0) return "<INVALID>";
2875 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2876 return asm_instr[op].m;
2878 case VINSTR_PHI: return "PHI";
2879 case VINSTR_JUMP: return "JUMP";
2880 case VINSTR_COND: return "COND";
2881 default: return "<UNK>";
2885 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2888 char indent[IND_BUFSZ];
2892 oprintf("module %s\n", b->name);
2893 for (i = 0; i < b->globals_count; ++i)
2896 if (b->globals[i]->isconst)
2897 oprintf("%s = ", b->globals[i]->name);
2898 ir_value_dump(b->globals[i], oprintf);
2901 for (i = 0; i < b->functions_count; ++i)
2902 ir_function_dump(b->functions[i], indent, oprintf);
2903 oprintf("endmodule %s\n", b->name);
2906 void ir_function_dump(ir_function *f, char *ind,
2907 int (*oprintf)(const char*, ...))
2910 if (f->builtin != 0) {
2911 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2914 oprintf("%sfunction %s\n", ind, f->name);
2915 strncat(ind, "\t", IND_BUFSZ);
2916 if (f->locals_count)
2918 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2919 for (i = 0; i < f->locals_count; ++i) {
2920 oprintf("%s\t", ind);
2921 ir_value_dump(f->locals[i], oprintf);
2925 oprintf("%sliferanges:\n", ind);
2926 for (i = 0; i < f->locals_count; ++i) {
2928 ir_value *v = f->locals[i];
2929 oprintf("%s\t%s: ", ind, v->name);
2930 for (l = 0; l < v->life_count; ++l) {
2931 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
2935 for (i = 0; i < f->values_count; ++i) {
2937 ir_value *v = f->values[i];
2938 oprintf("%s\t%s: (%i)", ind, v->name, (int)v->life_count);
2939 for (l = 0; l < v->life_count; ++l) {
2940 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
2944 if (f->blocks_count)
2946 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2947 for (i = 0; i < f->blocks_count; ++i) {
2948 if (f->blocks[i]->run_id != f->run_id) {
2949 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2951 ir_block_dump(f->blocks[i], ind, oprintf);
2955 ind[strlen(ind)-1] = 0;
2956 oprintf("%sendfunction %s\n", ind, f->name);
2959 void ir_block_dump(ir_block* b, char *ind,
2960 int (*oprintf)(const char*, ...))
2963 oprintf("%s:%s\n", ind, b->label);
2964 strncat(ind, "\t", IND_BUFSZ);
2966 for (i = 0; i < b->instr_count; ++i)
2967 ir_instr_dump(b->instr[i], ind, oprintf);
2968 ind[strlen(ind)-1] = 0;
2971 void dump_phi(ir_instr *in, char *ind,
2972 int (*oprintf)(const char*, ...))
2975 oprintf("%s <- phi ", in->_ops[0]->name);
2976 for (i = 0; i < in->phi_count; ++i)
2978 oprintf("([%s] : %s) ", in->phi[i].from->label,
2979 in->phi[i].value->name);
2984 void ir_instr_dump(ir_instr *in, char *ind,
2985 int (*oprintf)(const char*, ...))
2988 const char *comma = NULL;
2990 oprintf("%s (%i) ", ind, (int)in->eid);
2992 if (in->opcode == VINSTR_PHI) {
2993 dump_phi(in, ind, oprintf);
2997 strncat(ind, "\t", IND_BUFSZ);
2999 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3000 ir_value_dump(in->_ops[0], oprintf);
3001 if (in->_ops[1] || in->_ops[2])
3004 if (in->opcode == INSTR_CALL0) {
3005 oprintf("CALL%i\t", in->params_count);
3007 oprintf("%s\t", qc_opname(in->opcode));
3009 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3010 ir_value_dump(in->_ops[0], oprintf);
3015 for (i = 1; i != 3; ++i) {
3019 ir_value_dump(in->_ops[i], oprintf);
3027 oprintf("[%s]", in->bops[0]->label);
3031 oprintf("%s[%s]", comma, in->bops[1]->label);
3032 if (in->params_count) {
3033 oprintf("\tparams: ");
3034 for (i = 0; i != in->params_count; ++i) {
3035 oprintf("%s, ", in->params[i]->name);
3039 ind[strlen(ind)-1] = 0;
3042 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3051 oprintf("fn:%s", v->name);
3054 oprintf("%g", v->constval.vfloat);
3057 oprintf("'%g %g %g'",
3060 v->constval.vvec.z);
3063 oprintf("(entity)");
3066 oprintf("\"%s\"", v->constval.vstring);
3070 oprintf("%i", v->constval.vint);
3075 v->constval.vpointer->name);
3079 oprintf("%s", v->name);
3083 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
3086 oprintf("Life of %s:\n", self->name);
3087 for (i = 0; i < self->life_count; ++i)
3089 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);