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 (warntype && !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)
432 if (ir_function_get_local(self, name))
437 self->locals_count &&
438 self->locals[self->locals_count-1]->store != store_param) {
439 irerror(self->context, "cannot add parameters after adding locals");
443 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
444 if (!ir_function_locals_add(self, ve)) {
451 /***********************************************************************
455 ir_block* ir_block_new(ir_function* owner, const char *name)
458 self = (ir_block*)mem_a(sizeof(*self));
462 memset(self, 0, sizeof(*self));
465 if (name && !ir_block_set_label(self, name)) {
470 self->context.file = "<@no context>";
471 self->context.line = 0;
473 MEM_VECTOR_INIT(self, instr);
474 MEM_VECTOR_INIT(self, entries);
475 MEM_VECTOR_INIT(self, exits);
478 self->is_return = false;
480 MEM_VECTOR_INIT(self, living);
482 self->generated = false;
486 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
487 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
488 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
489 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
491 void ir_block_delete(ir_block* self)
494 if (self->label) mem_d(self->label);
495 for (i = 0; i != self->instr_count; ++i)
496 ir_instr_delete(self->instr[i]);
497 MEM_VECTOR_CLEAR(self, instr);
498 MEM_VECTOR_CLEAR(self, entries);
499 MEM_VECTOR_CLEAR(self, exits);
500 MEM_VECTOR_CLEAR(self, living);
504 bool ir_block_set_label(ir_block *self, const char *name)
507 mem_d((void*)self->label);
508 self->label = util_strdup(name);
509 return !!self->label;
512 /***********************************************************************
516 ir_instr* ir_instr_new(ir_block* owner, int op)
519 self = (ir_instr*)mem_a(sizeof(*self));
524 self->context.file = "<@no context>";
525 self->context.line = 0;
527 self->_ops[0] = NULL;
528 self->_ops[1] = NULL;
529 self->_ops[2] = NULL;
530 self->bops[0] = NULL;
531 self->bops[1] = NULL;
532 MEM_VECTOR_INIT(self, phi);
533 MEM_VECTOR_INIT(self, params);
538 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
539 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
541 void ir_instr_delete(ir_instr *self)
544 /* The following calls can only delete from
545 * vectors, we still want to delete this instruction
546 * so ignore the return value. Since with the warn_unused_result attribute
547 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
548 * I have to improvise here and use if(foo());
550 for (i = 0; i < self->phi_count; ++i) {
552 if (ir_value_writes_find(self->phi[i].value, self, &idx))
553 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
554 if (ir_value_reads_find(self->phi[i].value, self, &idx))
555 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
557 MEM_VECTOR_CLEAR(self, phi);
558 for (i = 0; i < self->params_count; ++i) {
560 if (ir_value_writes_find(self->params[i], self, &idx))
561 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
562 if (ir_value_reads_find(self->params[i], self, &idx))
563 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
565 MEM_VECTOR_CLEAR(self, params);
566 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
567 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
568 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
572 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
574 if (self->_ops[op]) {
576 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
578 if (!ir_value_writes_remove(self->_ops[op], idx))
581 else if (ir_value_reads_find(self->_ops[op], self, &idx))
583 if (!ir_value_reads_remove(self->_ops[op], idx))
589 if (!ir_value_writes_add(v, self))
592 if (!ir_value_reads_add(v, self))
600 /***********************************************************************
604 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
606 self->code.globaladdr = gaddr;
607 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
608 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
609 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
612 int32_t ir_value_code_addr(const ir_value *self)
614 if (self->store == store_return)
615 return OFS_RETURN + self->code.addroffset;
616 return self->code.globaladdr + self->code.addroffset;
619 ir_value* ir_value_var(const char *name, int storetype, int vtype)
622 self = (ir_value*)mem_a(sizeof(*self));
624 self->fieldtype = TYPE_VOID;
625 self->outtype = TYPE_VOID;
626 self->store = storetype;
627 MEM_VECTOR_INIT(self, reads);
628 MEM_VECTOR_INIT(self, writes);
629 self->isconst = false;
630 self->context.file = "<@no context>";
631 self->context.line = 0;
633 if (name && !ir_value_set_name(self, name)) {
634 irerror(self->context, "out of memory");
639 memset(&self->constval, 0, sizeof(self->constval));
640 memset(&self->code, 0, sizeof(self->code));
642 self->members[0] = NULL;
643 self->members[1] = NULL;
644 self->members[2] = NULL;
645 self->memberof = NULL;
647 MEM_VECTOR_INIT(self, life);
651 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
657 if (self->members[member])
658 return self->members[member];
660 if (self->vtype == TYPE_VECTOR)
662 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
665 m->context = self->context;
667 self->members[member] = m;
668 m->code.addroffset = member;
670 else if (self->vtype == TYPE_FIELD)
672 if (self->fieldtype != TYPE_VECTOR)
674 m = ir_value_var(self->name, self->store, TYPE_FIELD);
677 m->fieldtype = TYPE_FLOAT;
678 m->context = self->context;
680 self->members[member] = m;
681 m->code.addroffset = member;
685 irerror(self->context, "invalid member access on %s", self->name);
693 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
694 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
695 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
697 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
699 ir_value *v = ir_value_var(name, storetype, vtype);
702 if (!ir_function_collect_value(owner, v))
710 void ir_value_delete(ir_value* self)
714 mem_d((void*)self->name);
717 if (self->vtype == TYPE_STRING)
718 mem_d((void*)self->constval.vstring);
720 for (i = 0; i < 3; ++i) {
721 if (self->members[i])
722 ir_value_delete(self->members[i]);
724 MEM_VECTOR_CLEAR(self, reads);
725 MEM_VECTOR_CLEAR(self, writes);
726 MEM_VECTOR_CLEAR(self, life);
730 bool ir_value_set_name(ir_value *self, const char *name)
733 mem_d((void*)self->name);
734 self->name = util_strdup(name);
738 bool ir_value_set_float(ir_value *self, float f)
740 if (self->vtype != TYPE_FLOAT)
742 self->constval.vfloat = f;
743 self->isconst = true;
747 bool ir_value_set_func(ir_value *self, int f)
749 if (self->vtype != TYPE_FUNCTION)
751 self->constval.vint = f;
752 self->isconst = true;
756 bool ir_value_set_vector(ir_value *self, vector v)
758 if (self->vtype != TYPE_VECTOR)
760 self->constval.vvec = v;
761 self->isconst = true;
765 bool ir_value_set_field(ir_value *self, ir_value *fld)
767 if (self->vtype != TYPE_FIELD)
769 self->constval.vpointer = fld;
770 self->isconst = true;
774 static char *ir_strdup(const char *str)
777 /* actually dup empty strings */
778 char *out = mem_a(1);
782 return util_strdup(str);
785 bool ir_value_set_string(ir_value *self, const char *str)
787 if (self->vtype != TYPE_STRING)
789 self->constval.vstring = ir_strdup(str);
790 self->isconst = true;
795 bool ir_value_set_int(ir_value *self, int i)
797 if (self->vtype != TYPE_INTEGER)
799 self->constval.vint = i;
800 self->isconst = true;
805 bool ir_value_lives(ir_value *self, size_t at)
808 for (i = 0; i < self->life_count; ++i)
810 ir_life_entry_t *life = &self->life[i];
811 if (life->start <= at && at <= life->end)
813 if (life->start > at) /* since it's ordered */
819 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
822 if (!ir_value_life_add(self, e)) /* naive... */
824 for (k = self->life_count-1; k > idx; --k)
825 self->life[k] = self->life[k-1];
830 bool ir_value_life_merge(ir_value *self, size_t s)
833 ir_life_entry_t *life = NULL;
834 ir_life_entry_t *before = NULL;
835 ir_life_entry_t new_entry;
837 /* Find the first range >= s */
838 for (i = 0; i < self->life_count; ++i)
841 life = &self->life[i];
845 /* nothing found? append */
846 if (i == self->life_count) {
848 if (life && life->end+1 == s)
850 /* previous life range can be merged in */
854 if (life && life->end >= s)
857 if (!ir_value_life_add(self, e))
858 return false; /* failing */
864 if (before->end + 1 == s &&
865 life->start - 1 == s)
868 before->end = life->end;
869 if (!ir_value_life_remove(self, i))
870 return false; /* failing */
873 if (before->end + 1 == s)
879 /* already contained */
880 if (before->end >= s)
884 if (life->start - 1 == s)
889 /* insert a new entry */
890 new_entry.start = new_entry.end = s;
891 return ir_value_life_insert(self, i, new_entry);
894 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
898 if (!other->life_count)
901 if (!self->life_count) {
902 for (i = 0; i < other->life_count; ++i) {
903 if (!ir_value_life_add(self, other->life[i]))
910 for (i = 0; i < other->life_count; ++i)
912 const ir_life_entry_t *life = &other->life[i];
915 ir_life_entry_t *entry = &self->life[myi];
917 if (life->end+1 < entry->start)
919 /* adding an interval before entry */
920 if (!ir_value_life_insert(self, myi, *life))
926 if (life->start < entry->start &&
927 life->end+1 >= entry->start)
929 /* starts earlier and overlaps */
930 entry->start = life->start;
933 if (life->end > entry->end &&
934 life->start <= entry->end+1)
936 /* ends later and overlaps */
937 entry->end = life->end;
940 /* see if our change combines it with the next ranges */
941 while (myi+1 < self->life_count &&
942 entry->end+1 >= self->life[1+myi].start)
944 /* overlaps with (myi+1) */
945 if (entry->end < self->life[1+myi].end)
946 entry->end = self->life[1+myi].end;
947 if (!ir_value_life_remove(self, myi+1))
949 entry = &self->life[myi];
952 /* see if we're after the entry */
953 if (life->start > entry->end)
956 /* append if we're at the end */
957 if (myi >= self->life_count) {
958 if (!ir_value_life_add(self, *life))
962 /* otherweise check the next range */
971 bool ir_values_overlap(const ir_value *a, const ir_value *b)
973 /* For any life entry in A see if it overlaps with
974 * any life entry in B.
975 * Note that the life entries are orderes, so we can make a
976 * more efficient algorithm there than naively translating the
980 ir_life_entry_t *la, *lb, *enda, *endb;
982 /* first of all, if either has no life range, they cannot clash */
983 if (!a->life_count || !b->life_count)
988 enda = la + a->life_count;
989 endb = lb + b->life_count;
992 /* check if the entries overlap, for that,
993 * both must start before the other one ends.
995 if (la->start < lb->end &&
1001 /* entries are ordered
1002 * one entry is earlier than the other
1003 * that earlier entry will be moved forward
1005 if (la->start < lb->start)
1007 /* order: A B, move A forward
1008 * check if we hit the end with A
1013 else /* if (lb->start < la->start) actually <= */
1015 /* order: B A, move B forward
1016 * check if we hit the end with B
1025 /***********************************************************************
1029 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1031 ir_instr *in = ir_instr_new(self, op);
1035 if (target->store == store_value &&
1036 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1038 irerror(self->context, "cannot store to an SSA value");
1039 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1040 irerror(self->context, "instruction: %s", asm_instr[op].m);
1044 if (!ir_instr_op(in, 0, target, true) ||
1045 !ir_instr_op(in, 1, what, false) ||
1046 !ir_block_instr_add(self, in) )
1053 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1057 if (target->vtype == TYPE_VARIANT)
1058 vtype = what->vtype;
1060 vtype = target->vtype;
1063 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1064 op = INSTR_CONV_ITOF;
1065 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1066 op = INSTR_CONV_FTOI;
1068 op = type_store_instr[vtype];
1070 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1071 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1075 return ir_block_create_store_op(self, op, target, what);
1078 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1083 if (target->vtype != TYPE_POINTER)
1086 /* storing using pointer - target is a pointer, type must be
1087 * inferred from source
1089 vtype = what->vtype;
1091 op = type_storep_instr[vtype];
1092 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1093 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1094 op = INSTR_STOREP_V;
1097 return ir_block_create_store_op(self, op, target, what);
1100 bool ir_block_create_return(ir_block *self, ir_value *v)
1104 irerror(self->context, "block already ended (%s)", self->label);
1108 self->is_return = true;
1109 in = ir_instr_new(self, INSTR_RETURN);
1113 if (v && !ir_instr_op(in, 0, v, false))
1116 if (!ir_block_instr_add(self, in))
1121 bool ir_block_create_if(ir_block *self, ir_value *v,
1122 ir_block *ontrue, ir_block *onfalse)
1126 irerror(self->context, "block already ended (%s)", self->label);
1130 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1131 in = ir_instr_new(self, VINSTR_COND);
1135 if (!ir_instr_op(in, 0, v, false)) {
1136 ir_instr_delete(in);
1140 in->bops[0] = ontrue;
1141 in->bops[1] = onfalse;
1143 if (!ir_block_instr_add(self, in))
1146 if (!ir_block_exits_add(self, ontrue) ||
1147 !ir_block_exits_add(self, onfalse) ||
1148 !ir_block_entries_add(ontrue, self) ||
1149 !ir_block_entries_add(onfalse, self) )
1156 bool ir_block_create_jump(ir_block *self, ir_block *to)
1160 irerror(self->context, "block already ended (%s)", self->label);
1164 in = ir_instr_new(self, VINSTR_JUMP);
1169 if (!ir_block_instr_add(self, in))
1172 if (!ir_block_exits_add(self, to) ||
1173 !ir_block_entries_add(to, self) )
1180 bool ir_block_create_goto(ir_block *self, ir_block *to)
1184 irerror(self->context, "block already ended (%s)", self->label);
1188 in = ir_instr_new(self, INSTR_GOTO);
1193 if (!ir_block_instr_add(self, in))
1196 if (!ir_block_exits_add(self, to) ||
1197 !ir_block_entries_add(to, self) )
1204 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1208 in = ir_instr_new(self, VINSTR_PHI);
1211 out = ir_value_out(self->owner, label, store_value, ot);
1213 ir_instr_delete(in);
1216 if (!ir_instr_op(in, 0, out, true)) {
1217 ir_instr_delete(in);
1218 ir_value_delete(out);
1221 if (!ir_block_instr_add(self, in)) {
1222 ir_instr_delete(in);
1223 ir_value_delete(out);
1229 ir_value* ir_phi_value(ir_instr *self)
1231 return self->_ops[0];
1234 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1238 if (!ir_block_entries_find(self->owner, b, NULL)) {
1239 /* Must not be possible to cause this, otherwise the AST
1240 * is doing something wrong.
1242 irerror(self->context, "Invalid entry block for PHI");
1248 if (!ir_value_reads_add(v, self))
1250 return ir_instr_phi_add(self, pe);
1253 /* call related code */
1254 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1258 in = ir_instr_new(self, INSTR_CALL0);
1261 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1263 ir_instr_delete(in);
1266 if (!ir_instr_op(in, 0, out, true) ||
1267 !ir_instr_op(in, 1, func, false) ||
1268 !ir_block_instr_add(self, in))
1270 ir_instr_delete(in);
1271 ir_value_delete(out);
1277 ir_value* ir_call_value(ir_instr *self)
1279 return self->_ops[0];
1282 bool ir_call_param(ir_instr* self, ir_value *v)
1284 if (!ir_instr_params_add(self, v))
1286 if (!ir_value_reads_add(v, self)) {
1287 if (!ir_instr_params_remove(self, self->params_count-1))
1288 GMQCC_SUPPRESS_EMPTY_BODY;
1294 /* binary op related code */
1296 ir_value* ir_block_create_binop(ir_block *self,
1297 const char *label, int opcode,
1298 ir_value *left, ir_value *right)
1320 case INSTR_SUB_S: /* -- offset of string as float */
1325 case INSTR_BITOR_IF:
1326 case INSTR_BITOR_FI:
1327 case INSTR_BITAND_FI:
1328 case INSTR_BITAND_IF:
1343 case INSTR_BITAND_I:
1346 case INSTR_RSHIFT_I:
1347 case INSTR_LSHIFT_I:
1369 /* boolean operations result in floats */
1370 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1372 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1375 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1380 if (ot == TYPE_VOID) {
1381 /* The AST or parser were supposed to check this! */
1385 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1388 ir_value* ir_block_create_unary(ir_block *self,
1389 const char *label, int opcode,
1392 int ot = TYPE_FLOAT;
1404 /* QC doesn't have other unary operations. We expect extensions to fill
1405 * the above list, otherwise we assume out-type = in-type, eg for an
1409 ot = operand->vtype;
1412 if (ot == TYPE_VOID) {
1413 /* The AST or parser were supposed to check this! */
1417 /* let's use the general instruction creator and pass NULL for OPB */
1418 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1421 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1422 int op, ir_value *a, ir_value *b, int outype)
1427 out = ir_value_out(self->owner, label, store_value, outype);
1431 instr = ir_instr_new(self, op);
1433 ir_value_delete(out);
1437 if (!ir_instr_op(instr, 0, out, true) ||
1438 !ir_instr_op(instr, 1, a, false) ||
1439 !ir_instr_op(instr, 2, b, false) )
1444 if (!ir_block_instr_add(self, instr))
1449 ir_instr_delete(instr);
1450 ir_value_delete(out);
1454 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1458 /* Support for various pointer types todo if so desired */
1459 if (ent->vtype != TYPE_ENTITY)
1462 if (field->vtype != TYPE_FIELD)
1465 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1466 v->fieldtype = field->fieldtype;
1470 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1473 if (ent->vtype != TYPE_ENTITY)
1476 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1477 if (field->vtype != TYPE_FIELD)
1482 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1483 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1484 case TYPE_STRING: op = INSTR_LOAD_S; break;
1485 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1486 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1487 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1489 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1490 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1496 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1499 ir_value* ir_block_create_add(ir_block *self,
1501 ir_value *left, ir_value *right)
1504 int l = left->vtype;
1505 int r = right->vtype;
1524 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1526 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1532 return ir_block_create_binop(self, label, op, left, right);
1535 ir_value* ir_block_create_sub(ir_block *self,
1537 ir_value *left, ir_value *right)
1540 int l = left->vtype;
1541 int r = right->vtype;
1561 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1563 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1569 return ir_block_create_binop(self, label, op, left, right);
1572 ir_value* ir_block_create_mul(ir_block *self,
1574 ir_value *left, ir_value *right)
1577 int l = left->vtype;
1578 int r = right->vtype;
1597 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1599 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1602 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1604 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1606 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1608 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1614 return ir_block_create_binop(self, label, op, left, right);
1617 ir_value* ir_block_create_div(ir_block *self,
1619 ir_value *left, ir_value *right)
1622 int l = left->vtype;
1623 int r = right->vtype;
1640 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1642 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1644 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1650 return ir_block_create_binop(self, label, op, left, right);
1653 /* PHI resolving breaks the SSA, and must thus be the last
1654 * step before life-range calculation.
1657 static bool ir_block_naive_phi(ir_block *self);
1658 bool ir_function_naive_phi(ir_function *self)
1662 for (i = 0; i < self->blocks_count; ++i)
1664 if (!ir_block_naive_phi(self->blocks[i]))
1670 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1675 /* create a store */
1676 if (!ir_block_create_store(block, old, what))
1679 /* we now move it up */
1680 instr = block->instr[block->instr_count-1];
1681 for (i = block->instr_count; i > iid; --i)
1682 block->instr[i] = block->instr[i-1];
1683 block->instr[i] = instr;
1688 static bool ir_block_naive_phi(ir_block *self)
1691 /* FIXME: optionally, create_phi can add the phis
1692 * to a list so we don't need to loop through blocks
1693 * - anyway: "don't optimize YET"
1695 for (i = 0; i < self->instr_count; ++i)
1697 ir_instr *instr = self->instr[i];
1698 if (instr->opcode != VINSTR_PHI)
1701 if (!ir_block_instr_remove(self, i))
1703 --i; /* NOTE: i+1 below */
1705 for (p = 0; p < instr->phi_count; ++p)
1707 ir_value *v = instr->phi[p].value;
1708 for (w = 0; w < v->writes_count; ++w) {
1711 if (!v->writes[w]->_ops[0])
1714 /* When the write was to a global, we have to emit a mov */
1715 old = v->writes[w]->_ops[0];
1717 /* The original instruction now writes to the PHI target local */
1718 if (v->writes[w]->_ops[0] == v)
1719 v->writes[w]->_ops[0] = instr->_ops[0];
1721 if (old->store != store_value && old->store != store_local && old->store != store_param)
1723 /* If it originally wrote to a global we need to store the value
1726 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1728 if (i+1 < self->instr_count)
1729 instr = self->instr[i+1];
1732 /* In case I forget and access instr later, it'll be NULL
1733 * when it's a problem, to make sure we crash, rather than accessing
1739 /* If it didn't, we can replace all reads by the phi target now. */
1741 for (r = 0; r < old->reads_count; ++r)
1744 ir_instr *ri = old->reads[r];
1745 for (op = 0; op < ri->phi_count; ++op) {
1746 if (ri->phi[op].value == old)
1747 ri->phi[op].value = v;
1749 for (op = 0; op < 3; ++op) {
1750 if (ri->_ops[op] == old)
1757 ir_instr_delete(instr);
1762 /***********************************************************************
1763 *IR Temp allocation code
1764 * Propagating value life ranges by walking through the function backwards
1765 * until no more changes are made.
1766 * In theory this should happen once more than once for every nested loop
1768 * Though this implementation might run an additional time for if nests.
1777 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1779 /* Enumerate instructions used by value's life-ranges
1781 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1785 for (i = 0; i < self->instr_count; ++i)
1787 self->instr[i]->eid = eid++;
1792 /* Enumerate blocks and instructions.
1793 * The block-enumeration is unordered!
1794 * We do not really use the block enumreation, however
1795 * the instruction enumeration is important for life-ranges.
1797 void ir_function_enumerate(ir_function *self)
1800 size_t instruction_id = 0;
1801 for (i = 0; i < self->blocks_count; ++i)
1803 self->blocks[i]->eid = i;
1804 self->blocks[i]->run_id = 0;
1805 ir_block_enumerate(self->blocks[i], &instruction_id);
1809 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1810 bool ir_function_calculate_liferanges(ir_function *self)
1818 for (i = 0; i != self->blocks_count; ++i)
1820 if (self->blocks[i]->is_return)
1822 self->blocks[i]->living_count = 0;
1823 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1828 if (self->blocks_count) {
1829 ir_block *block = self->blocks[0];
1830 for (i = 0; i < block->living_count; ++i) {
1831 ir_value *v = block->living[i];
1832 if (v->memberof || v->store != store_local)
1834 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1835 "variable `%s` may be used uninitialized in this function", v->name))
1844 /* Local-value allocator
1845 * After finishing creating the liferange of all values used in a function
1846 * we can allocate their global-positions.
1847 * This is the counterpart to register-allocation in register machines.
1850 MEM_VECTOR_MAKE(ir_value*, locals);
1851 MEM_VECTOR_MAKE(size_t, sizes);
1852 MEM_VECTOR_MAKE(size_t, positions);
1853 } function_allocator;
1854 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1855 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1856 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1858 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1861 size_t vsize = type_sizeof[var->vtype];
1863 slot = ir_value_var("reg", store_global, var->vtype);
1867 if (!ir_value_life_merge_into(slot, var))
1870 if (!function_allocator_locals_add(alloc, slot))
1873 if (!function_allocator_sizes_add(alloc, vsize))
1879 ir_value_delete(slot);
1883 bool ir_function_allocate_locals(ir_function *self)
1892 function_allocator alloc;
1894 if (!self->locals_count && !self->values_count)
1897 MEM_VECTOR_INIT(&alloc, locals);
1898 MEM_VECTOR_INIT(&alloc, sizes);
1899 MEM_VECTOR_INIT(&alloc, positions);
1901 for (i = 0; i < self->locals_count; ++i)
1903 if (!function_allocator_alloc(&alloc, self->locals[i]))
1907 /* Allocate a slot for any value that still exists */
1908 for (i = 0; i < self->values_count; ++i)
1910 v = self->values[i];
1915 for (a = 0; a < alloc.locals_count; ++a)
1917 slot = alloc.locals[a];
1919 if (ir_values_overlap(v, slot))
1922 if (!ir_value_life_merge_into(slot, v))
1925 /* adjust size for this slot */
1926 if (alloc.sizes[a] < type_sizeof[v->vtype])
1927 alloc.sizes[a] = type_sizeof[v->vtype];
1929 self->values[i]->code.local = a;
1932 if (a >= alloc.locals_count) {
1933 self->values[i]->code.local = alloc.locals_count;
1934 if (!function_allocator_alloc(&alloc, v))
1943 /* Adjust slot positions based on sizes */
1944 if (!function_allocator_positions_add(&alloc, 0))
1947 if (alloc.sizes_count)
1948 pos = alloc.positions[0] + alloc.sizes[0];
1951 for (i = 1; i < alloc.sizes_count; ++i)
1953 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1954 if (!function_allocator_positions_add(&alloc, pos))
1958 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1960 /* Take over the actual slot positions */
1961 for (i = 0; i < self->values_count; ++i) {
1962 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1970 for (i = 0; i < alloc.locals_count; ++i)
1971 ir_value_delete(alloc.locals[i]);
1972 MEM_VECTOR_CLEAR(&alloc, locals);
1973 MEM_VECTOR_CLEAR(&alloc, sizes);
1974 MEM_VECTOR_CLEAR(&alloc, positions);
1978 /* Get information about which operand
1979 * is read from, or written to.
1981 static void ir_op_read_write(int op, size_t *read, size_t *write)
2001 case INSTR_STOREP_F:
2002 case INSTR_STOREP_V:
2003 case INSTR_STOREP_S:
2004 case INSTR_STOREP_ENT:
2005 case INSTR_STOREP_FLD:
2006 case INSTR_STOREP_FNC:
2017 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2020 bool changed = false;
2022 for (i = 0; i != self->living_count; ++i)
2024 tempbool = ir_value_life_merge(self->living[i], eid);
2027 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2029 changed = changed || tempbool;
2034 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2037 /* values which have been read in a previous iteration are now
2038 * in the "living" array even if the previous block doesn't use them.
2039 * So we have to remove whatever does not exist in the previous block.
2040 * They will be re-added on-read, but the liferange merge won't cause
2043 for (i = 0; i < self->living_count; ++i)
2045 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2046 if (!ir_block_living_remove(self, i))
2052 /* Whatever the previous block still has in its living set
2053 * must now be added to ours as well.
2055 for (i = 0; i < prev->living_count; ++i)
2057 if (ir_block_living_find(self, prev->living[i], NULL))
2059 if (!ir_block_living_add(self, prev->living[i]))
2062 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2068 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2074 /* bitmasks which operands are read from or written to */
2076 char dbg_ind[16] = { '#', '0' };
2081 if (!ir_block_life_prop_previous(self, prev, changed))
2085 i = self->instr_count;
2088 instr = self->instr[i];
2090 /* PHI operands are always read operands */
2091 for (p = 0; p < instr->phi_count; ++p)
2093 value = instr->phi[p].value;
2094 if (value->memberof)
2095 value = value->memberof;
2096 if (!ir_block_living_find(self, value, NULL) &&
2097 !ir_block_living_add(self, value))
2103 /* call params are read operands too */
2104 for (p = 0; p < instr->params_count; ++p)
2106 value = instr->params[p];
2107 if (value->memberof)
2108 value = value->memberof;
2109 if (!ir_block_living_find(self, value, NULL) &&
2110 !ir_block_living_add(self, value))
2116 /* See which operands are read and write operands */
2117 ir_op_read_write(instr->opcode, &read, &write);
2119 if (instr->opcode == INSTR_MUL_VF)
2121 /* the float source will get an additional lifetime */
2122 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2123 *changed = *changed || tempbool;
2125 else if (instr->opcode == INSTR_MUL_FV)
2127 /* the float source will get an additional lifetime */
2128 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2129 *changed = *changed || tempbool;
2132 /* Go through the 3 main operands */
2133 for (o = 0; o < 3; ++o)
2135 if (!instr->_ops[o]) /* no such operand */
2138 value = instr->_ops[o];
2139 if (value->memberof)
2140 value = value->memberof;
2142 /* We only care about locals */
2143 /* we also calculate parameter liferanges so that locals
2144 * can take up parameter slots */
2145 if (value->store != store_value &&
2146 value->store != store_local &&
2147 value->store != store_param)
2153 if (!ir_block_living_find(self, value, NULL) &&
2154 !ir_block_living_add(self, value))
2160 /* write operands */
2161 /* When we write to a local, we consider it "dead" for the
2162 * remaining upper part of the function, since in SSA a value
2163 * can only be written once (== created)
2168 bool in_living = ir_block_living_find(self, value, &idx);
2171 /* If the value isn't alive it hasn't been read before... */
2172 /* TODO: See if the warning can be emitted during parsing or AST processing
2173 * otherwise have warning printed here.
2174 * IF printing a warning here: include filecontext_t,
2175 * and make sure it's only printed once
2176 * since this function is run multiple times.
2178 /* For now: debug info: */
2179 /* fprintf(stderr, "Value only written %s\n", value->name); */
2180 tempbool = ir_value_life_merge(value, instr->eid);
2181 *changed = *changed || tempbool;
2183 ir_instr_dump(instr, dbg_ind, printf);
2187 /* since 'living' won't contain it
2188 * anymore, merge the value, since
2191 tempbool = ir_value_life_merge(value, instr->eid);
2194 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2196 *changed = *changed || tempbool;
2198 if (!ir_block_living_remove(self, idx))
2204 tempbool = ir_block_living_add_instr(self, instr->eid);
2205 /*fprintf(stderr, "living added values\n");*/
2206 *changed = *changed || tempbool;
2210 if (self->run_id == self->owner->run_id)
2213 self->run_id = self->owner->run_id;
2215 for (i = 0; i < self->entries_count; ++i)
2217 ir_block *entry = self->entries[i];
2218 ir_block_life_propagate(entry, self, changed);
2224 /***********************************************************************
2227 * Since the IR has the convention of putting 'write' operands
2228 * at the beginning, we have to rotate the operands of instructions
2229 * properly in order to generate valid QCVM code.
2231 * Having destinations at a fixed position is more convenient. In QC
2232 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2233 * read from from OPA, and store to OPB rather than OPC. Which is
2234 * partially the reason why the implementation of these instructions
2235 * in darkplaces has been delayed for so long.
2237 * Breaking conventions is annoying...
2239 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2241 static bool gen_global_field(ir_value *global)
2243 if (global->isconst)
2245 ir_value *fld = global->constval.vpointer;
2247 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2251 /* Now, in this case, a relocation would be impossible to code
2252 * since it looks like this:
2253 * .vector v = origin; <- parse error, wtf is 'origin'?
2256 * But we will need a general relocation support later anyway
2257 * for functions... might as well support that here.
2259 if (!fld->code.globaladdr) {
2260 irerror(global->context, "FIXME: Relocation support");
2264 /* copy the field's value */
2265 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2266 if (global->fieldtype == TYPE_VECTOR) {
2267 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2268 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2273 ir_value_code_setaddr(global, code_globals_add(0));
2274 if (global->fieldtype == TYPE_VECTOR) {
2275 code_globals_add(0);
2276 code_globals_add(0);
2279 if (global->code.globaladdr < 0)
2284 static bool gen_global_pointer(ir_value *global)
2286 if (global->isconst)
2288 ir_value *target = global->constval.vpointer;
2290 irerror(global->context, "Invalid pointer constant: %s", global->name);
2291 /* NULL pointers are pointing to the NULL constant, which also
2292 * sits at address 0, but still has an ir_value for itself.
2297 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2298 * void() foo; <- proto
2299 * void() *fooptr = &foo;
2300 * void() foo = { code }
2302 if (!target->code.globaladdr) {
2303 /* FIXME: Check for the constant nullptr ir_value!
2304 * because then code.globaladdr being 0 is valid.
2306 irerror(global->context, "FIXME: Relocation support");
2310 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2314 ir_value_code_setaddr(global, code_globals_add(0));
2316 if (global->code.globaladdr < 0)
2321 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2323 prog_section_statement stmt;
2332 block->generated = true;
2333 block->code_start = code_statements_elements;
2334 for (i = 0; i < block->instr_count; ++i)
2336 instr = block->instr[i];
2338 if (instr->opcode == VINSTR_PHI) {
2339 irerror(block->context, "cannot generate virtual instruction (phi)");
2343 if (instr->opcode == VINSTR_JUMP) {
2344 target = instr->bops[0];
2345 /* for uncoditional jumps, if the target hasn't been generated
2346 * yet, we generate them right here.
2348 if (!target->generated) {
2353 /* otherwise we generate a jump instruction */
2354 stmt.opcode = INSTR_GOTO;
2355 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2358 if (code_statements_add(stmt) < 0)
2361 /* no further instructions can be in this block */
2365 if (instr->opcode == VINSTR_COND) {
2366 ontrue = instr->bops[0];
2367 onfalse = instr->bops[1];
2368 /* TODO: have the AST signal which block should
2369 * come first: eg. optimize IFs without ELSE...
2372 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2376 if (ontrue->generated) {
2377 stmt.opcode = INSTR_IF;
2378 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2379 if (code_statements_add(stmt) < 0)
2382 if (onfalse->generated) {
2383 stmt.opcode = INSTR_IFNOT;
2384 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2385 if (code_statements_add(stmt) < 0)
2388 if (!ontrue->generated) {
2389 if (onfalse->generated) {
2394 if (!onfalse->generated) {
2395 if (ontrue->generated) {
2400 /* neither ontrue nor onfalse exist */
2401 stmt.opcode = INSTR_IFNOT;
2402 stidx = code_statements_elements;
2403 if (code_statements_add(stmt) < 0)
2405 /* on false we jump, so add ontrue-path */
2406 if (!gen_blocks_recursive(func, ontrue))
2408 /* fixup the jump address */
2409 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2410 /* generate onfalse path */
2411 if (onfalse->generated) {
2412 /* fixup the jump address */
2413 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2414 /* may have been generated in the previous recursive call */
2415 stmt.opcode = INSTR_GOTO;
2416 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2419 return (code_statements_add(stmt) >= 0);
2421 /* if not, generate now */
2426 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2427 /* Trivial call translation:
2428 * copy all params to OFS_PARM*
2429 * if the output's storetype is not store_return,
2430 * add append a STORE instruction!
2432 * NOTES on how to do it better without much trouble:
2433 * -) The liferanges!
2434 * Simply check the liferange of all parameters for
2435 * other CALLs. For each param with no CALL in its
2436 * liferange, we can store it in an OFS_PARM at
2437 * generation already. This would even include later
2438 * reuse.... probably... :)
2443 for (p = 0; p < instr->params_count; ++p)
2445 ir_value *param = instr->params[p];
2447 stmt.opcode = INSTR_STORE_F;
2450 stmt.opcode = type_store_instr[param->vtype];
2451 stmt.o1.u1 = ir_value_code_addr(param);
2452 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2453 if (code_statements_add(stmt) < 0)
2456 stmt.opcode = INSTR_CALL0 + instr->params_count;
2457 if (stmt.opcode > INSTR_CALL8)
2458 stmt.opcode = INSTR_CALL8;
2459 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2462 if (code_statements_add(stmt) < 0)
2465 retvalue = instr->_ops[0];
2466 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2468 /* not to be kept in OFS_RETURN */
2469 stmt.opcode = type_store_instr[retvalue->vtype];
2470 stmt.o1.u1 = OFS_RETURN;
2471 stmt.o2.u1 = ir_value_code_addr(retvalue);
2473 if (code_statements_add(stmt) < 0)
2479 if (instr->opcode == INSTR_STATE) {
2480 irerror(block->context, "TODO: state instruction");
2484 stmt.opcode = instr->opcode;
2489 /* This is the general order of operands */
2491 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2494 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2497 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2499 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2501 stmt.o1.u1 = stmt.o3.u1;
2504 else if ((stmt.opcode >= INSTR_STORE_F &&
2505 stmt.opcode <= INSTR_STORE_FNC) ||
2506 (stmt.opcode >= INSTR_STOREP_F &&
2507 stmt.opcode <= INSTR_STOREP_FNC))
2509 /* 2-operand instructions with A -> B */
2510 stmt.o2.u1 = stmt.o3.u1;
2514 if (code_statements_add(stmt) < 0)
2520 static bool gen_function_code(ir_function *self)
2523 prog_section_statement stmt;
2525 /* Starting from entry point, we generate blocks "as they come"
2526 * for now. Dead blocks will not be translated obviously.
2528 if (!self->blocks_count) {
2529 irerror(self->context, "Function '%s' declared without body.", self->name);
2533 block = self->blocks[0];
2534 if (block->generated)
2537 if (!gen_blocks_recursive(self, block)) {
2538 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2542 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2543 stmt.opcode = AINSTR_END;
2547 if (code_statements_add(stmt) < 0)
2552 static bool gen_global_function(ir_builder *ir, ir_value *global)
2554 prog_section_function fun;
2558 size_t local_var_end;
2560 if (!global->isconst || (!global->constval.vfunc))
2562 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2566 irfun = global->constval.vfunc;
2568 fun.name = global->code.name;
2569 fun.file = code_cachedstring(global->context.file);
2570 fun.profile = 0; /* always 0 */
2571 fun.nargs = irfun->params_count;
2573 for (i = 0;i < 8; ++i) {
2577 fun.argsize[i] = type_sizeof[irfun->params[i]];
2580 fun.firstlocal = code_globals_elements;
2582 local_var_end = fun.firstlocal;
2583 for (i = 0; i < irfun->locals_count; ++i) {
2584 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2585 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2589 if (irfun->locals_count) {
2590 ir_value *last = irfun->locals[irfun->locals_count-1];
2591 local_var_end = last->code.globaladdr;
2592 local_var_end += type_sizeof[last->vtype];
2594 for (i = 0; i < irfun->values_count; ++i)
2596 /* generate code.globaladdr for ssa values */
2597 ir_value *v = irfun->values[i];
2598 ir_value_code_setaddr(v, local_var_end + v->code.local);
2600 for (i = 0; i < irfun->allocated_locals; ++i) {
2601 /* fill the locals with zeros */
2602 code_globals_add(0);
2605 fun.locals = code_globals_elements - fun.firstlocal;
2608 fun.entry = irfun->builtin;
2610 irfun->code_function_def = code_functions_elements;
2611 fun.entry = code_statements_elements;
2614 return (code_functions_add(fun) >= 0);
2617 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2619 prog_section_function *fundef;
2622 irfun = global->constval.vfunc;
2624 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2625 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2626 /* this was a function pointer, don't generate code for those */
2633 if (irfun->code_function_def < 0) {
2634 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2637 fundef = &code_functions_data[irfun->code_function_def];
2639 fundef->entry = code_statements_elements;
2640 if (!gen_function_code(irfun)) {
2641 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2647 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
2651 prog_section_def def;
2653 def.type = global->vtype;
2654 def.offset = code_globals_elements;
2655 def.name = global->code.name = code_genstring(global->name);
2657 switch (global->vtype)
2660 if (!strcmp(global->name, "end_sys_globals")) {
2661 /* TODO: remember this point... all the defs before this one
2662 * should be checksummed and added to progdefs.h when we generate it.
2665 else if (!strcmp(global->name, "end_sys_fields")) {
2666 /* TODO: same as above but for entity-fields rather than globsl
2670 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
2672 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
2673 * the system fields actually go? Though the engine knows this anyway...
2674 * Maybe this could be an -foption
2675 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
2677 ir_value_code_setaddr(global, code_globals_add(0));
2679 if (code_defs_add(def) < 0)
2683 if (code_defs_add(def) < 0)
2685 return gen_global_pointer(global);
2687 if (code_defs_add(def) < 0)
2689 return gen_global_field(global);
2694 if (global->isconst) {
2695 iptr = (int32_t*)&global->constval.vfloat;
2696 ir_value_code_setaddr(global, code_globals_add(*iptr));
2698 ir_value_code_setaddr(global, code_globals_add(0));
2700 def.type |= DEF_SAVEGLOBAL;
2702 if (code_defs_add(def) < 0)
2705 return global->code.globaladdr >= 0;
2709 if (global->isconst)
2710 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2712 ir_value_code_setaddr(global, code_globals_add(0));
2714 def.type |= DEF_SAVEGLOBAL;
2716 if (code_defs_add(def) < 0)
2718 return global->code.globaladdr >= 0;
2723 if (global->isconst) {
2724 iptr = (int32_t*)&global->constval.vvec;
2725 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2726 if (global->code.globaladdr < 0)
2728 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2730 if (code_globals_add(iptr[d]) < 0)
2734 ir_value_code_setaddr(global, code_globals_add(0));
2735 if (global->code.globaladdr < 0)
2737 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2739 if (code_globals_add(0) < 0)
2743 def.type |= DEF_SAVEGLOBAL;
2746 if (code_defs_add(def) < 0)
2748 return global->code.globaladdr >= 0;
2751 if (!global->isconst) {
2752 ir_value_code_setaddr(global, code_globals_add(0));
2753 if (global->code.globaladdr < 0)
2756 ir_value_code_setaddr(global, code_globals_elements);
2757 code_globals_add(code_functions_elements);
2758 if (!gen_global_function(self, global))
2761 def.type |= DEF_SAVEGLOBAL;
2763 if (code_defs_add(def) < 0)
2767 /* assume biggest type */
2768 ir_value_code_setaddr(global, code_globals_add(0));
2769 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2770 code_globals_add(0);
2773 /* refuse to create 'void' type or any other fancy business. */
2774 irerror(global->context, "Invalid type for global variable `%s`: %s",
2775 global->name, type_name[global->vtype]);
2780 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2782 prog_section_def def;
2783 prog_section_field fld;
2785 def.type = field->vtype;
2786 def.offset = code_globals_elements;
2788 /* create a global named the same as the field */
2789 if (opts_standard == COMPILER_GMQCC) {
2790 /* in our standard, the global gets a dot prefix */
2791 size_t len = strlen(field->name);
2794 /* we really don't want to have to allocate this, and 1024
2795 * bytes is more than enough for a variable/field name
2797 if (len+2 >= sizeof(name)) {
2798 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2803 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2806 def.name = code_genstring(name);
2807 fld.name = def.name + 1; /* we reuse that string table entry */
2809 /* in plain QC, there cannot be a global with the same name,
2810 * and so we also name the global the same.
2811 * FIXME: fteqcc should create a global as well
2812 * check if it actually uses the same name. Probably does
2814 def.name = code_genstring(field->name);
2815 fld.name = def.name;
2818 field->code.name = def.name;
2820 if (code_defs_add(def) < 0)
2823 fld.type = field->fieldtype;
2825 if (fld.type == TYPE_VOID) {
2826 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2830 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2832 if (code_fields_add(fld) < 0)
2835 ir_value_code_setaddr(field, code_globals_elements);
2836 if (!code_globals_add(fld.offset))
2838 if (fld.type == TYPE_VECTOR) {
2839 if (!code_globals_add(fld.offset+1))
2841 if (!code_globals_add(fld.offset+2))
2845 return field->code.globaladdr >= 0;
2848 bool ir_builder_generate(ir_builder *self, const char *filename)
2850 prog_section_statement stmt;
2855 for (i = 0; i < self->globals_count; ++i)
2857 if (!ir_builder_gen_global(self, self->globals[i], false)) {
2862 for (i = 0; i < self->fields_count; ++i)
2864 if (!ir_builder_gen_field(self, self->fields[i])) {
2869 /* generate function code */
2870 for (i = 0; i < self->globals_count; ++i)
2872 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2873 if (!gen_global_function_code(self, self->globals[i])) {
2879 /* DP errors if the last instruction is not an INSTR_DONE
2880 * and for debugging purposes we add an additional AINSTR_END
2881 * to the end of functions, so here it goes:
2883 stmt.opcode = INSTR_DONE;
2887 if (code_statements_add(stmt) < 0)
2890 printf("writing '%s'...\n", filename);
2891 return code_write(filename);
2894 /***********************************************************************
2895 *IR DEBUG Dump functions...
2898 #define IND_BUFSZ 1024
2901 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2903 # define strncat strncat
2906 const char *qc_opname(int op)
2908 if (op < 0) return "<INVALID>";
2909 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2910 return asm_instr[op].m;
2912 case VINSTR_PHI: return "PHI";
2913 case VINSTR_JUMP: return "JUMP";
2914 case VINSTR_COND: return "COND";
2915 default: return "<UNK>";
2919 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2922 char indent[IND_BUFSZ];
2926 oprintf("module %s\n", b->name);
2927 for (i = 0; i < b->globals_count; ++i)
2930 if (b->globals[i]->isconst)
2931 oprintf("%s = ", b->globals[i]->name);
2932 ir_value_dump(b->globals[i], oprintf);
2935 for (i = 0; i < b->functions_count; ++i)
2936 ir_function_dump(b->functions[i], indent, oprintf);
2937 oprintf("endmodule %s\n", b->name);
2940 void ir_function_dump(ir_function *f, char *ind,
2941 int (*oprintf)(const char*, ...))
2944 if (f->builtin != 0) {
2945 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2948 oprintf("%sfunction %s\n", ind, f->name);
2949 strncat(ind, "\t", IND_BUFSZ);
2950 if (f->locals_count)
2952 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2953 for (i = 0; i < f->locals_count; ++i) {
2954 oprintf("%s\t", ind);
2955 ir_value_dump(f->locals[i], oprintf);
2959 oprintf("%sliferanges:\n", ind);
2960 for (i = 0; i < f->locals_count; ++i) {
2962 ir_value *v = f->locals[i];
2963 oprintf("%s\t%s: unique ", ind, v->name);
2964 for (l = 0; l < v->life_count; ++l) {
2965 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
2969 for (i = 0; i < f->values_count; ++i) {
2971 ir_value *v = f->values[i];
2972 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
2973 for (l = 0; l < v->life_count; ++l) {
2974 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
2978 if (f->blocks_count)
2980 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2981 for (i = 0; i < f->blocks_count; ++i) {
2982 if (f->blocks[i]->run_id != f->run_id) {
2983 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2985 ir_block_dump(f->blocks[i], ind, oprintf);
2989 ind[strlen(ind)-1] = 0;
2990 oprintf("%sendfunction %s\n", ind, f->name);
2993 void ir_block_dump(ir_block* b, char *ind,
2994 int (*oprintf)(const char*, ...))
2997 oprintf("%s:%s\n", ind, b->label);
2998 strncat(ind, "\t", IND_BUFSZ);
3000 for (i = 0; i < b->instr_count; ++i)
3001 ir_instr_dump(b->instr[i], ind, oprintf);
3002 ind[strlen(ind)-1] = 0;
3005 void dump_phi(ir_instr *in, char *ind,
3006 int (*oprintf)(const char*, ...))
3009 oprintf("%s <- phi ", in->_ops[0]->name);
3010 for (i = 0; i < in->phi_count; ++i)
3012 oprintf("([%s] : %s) ", in->phi[i].from->label,
3013 in->phi[i].value->name);
3018 void ir_instr_dump(ir_instr *in, char *ind,
3019 int (*oprintf)(const char*, ...))
3022 const char *comma = NULL;
3024 oprintf("%s (%i) ", ind, (int)in->eid);
3026 if (in->opcode == VINSTR_PHI) {
3027 dump_phi(in, ind, oprintf);
3031 strncat(ind, "\t", IND_BUFSZ);
3033 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3034 ir_value_dump(in->_ops[0], oprintf);
3035 if (in->_ops[1] || in->_ops[2])
3038 if (in->opcode == INSTR_CALL0) {
3039 oprintf("CALL%i\t", in->params_count);
3041 oprintf("%s\t", qc_opname(in->opcode));
3043 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3044 ir_value_dump(in->_ops[0], oprintf);
3049 for (i = 1; i != 3; ++i) {
3053 ir_value_dump(in->_ops[i], oprintf);
3061 oprintf("[%s]", in->bops[0]->label);
3065 oprintf("%s[%s]", comma, in->bops[1]->label);
3066 if (in->params_count) {
3067 oprintf("\tparams: ");
3068 for (i = 0; i != in->params_count; ++i) {
3069 oprintf("%s, ", in->params[i]->name);
3073 ind[strlen(ind)-1] = 0;
3076 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3085 oprintf("fn:%s", v->name);
3088 oprintf("%g", v->constval.vfloat);
3091 oprintf("'%g %g %g'",
3094 v->constval.vvec.z);
3097 oprintf("(entity)");
3100 oprintf("\"%s\"", v->constval.vstring);
3104 oprintf("%i", v->constval.vint);
3109 v->constval.vpointer->name);
3113 oprintf("%s", v->name);
3117 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3120 oprintf("Life of %12s:", self->name);
3121 for (i = 0; i < self->life_count; ++i)
3123 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);