5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 /***********************************************************************
29 * Type sizes used at multiple points in the IR codegen
32 const char *type_name[TYPE_COUNT] = {
47 size_t type_sizeof[TYPE_COUNT] = {
54 1, /* TYPE_FUNCTION */
62 uint16_t type_store_instr[TYPE_COUNT] = {
63 INSTR_STORE_F, /* should use I when having integer support */
70 INSTR_STORE_ENT, /* should use I */
72 INSTR_STORE_I, /* integer type */
75 INSTR_STORE_V, /* variant, should never be accessed */
78 uint16_t type_storep_instr[TYPE_COUNT] = {
79 INSTR_STOREP_F, /* should use I when having integer support */
86 INSTR_STOREP_ENT, /* should use I */
88 INSTR_STOREP_ENT, /* integer type */
91 INSTR_STOREP_V, /* variant, should never be accessed */
94 uint16_t type_eq_instr[TYPE_COUNT] = {
95 INSTR_EQ_F, /* should use I when having integer support */
100 INSTR_EQ_E, /* FLD has no comparison */
102 INSTR_EQ_E, /* should use I */
107 INSTR_EQ_V, /* variant, should never be accessed */
110 uint16_t type_ne_instr[TYPE_COUNT] = {
111 INSTR_NE_F, /* should use I when having integer support */
116 INSTR_NE_E, /* FLD has no comparison */
118 INSTR_NE_E, /* should use I */
123 INSTR_NE_V, /* variant, should never be accessed */
126 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
128 static void irerror(lex_ctx ctx, const char *msg, ...)
132 cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
136 /***********************************************************************
140 ir_builder* ir_builder_new(const char *modulename)
144 self = (ir_builder*)mem_a(sizeof(*self));
148 MEM_VECTOR_INIT(self, functions);
149 MEM_VECTOR_INIT(self, globals);
150 MEM_VECTOR_INIT(self, fields);
152 if (!ir_builder_set_name(self, modulename)) {
157 /* globals which always exist */
159 /* for now we give it a vector size */
160 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
165 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
166 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
167 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
169 void ir_builder_delete(ir_builder* self)
172 mem_d((void*)self->name);
173 for (i = 0; i != self->functions_count; ++i) {
174 ir_function_delete(self->functions[i]);
176 MEM_VECTOR_CLEAR(self, functions);
177 for (i = 0; i != self->globals_count; ++i) {
178 ir_value_delete(self->globals[i]);
180 MEM_VECTOR_CLEAR(self, globals);
181 for (i = 0; i != self->fields_count; ++i) {
182 ir_value_delete(self->fields[i]);
184 MEM_VECTOR_CLEAR(self, fields);
188 bool ir_builder_set_name(ir_builder *self, const char *name)
191 mem_d((void*)self->name);
192 self->name = util_strdup(name);
196 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
199 for (i = 0; i < self->functions_count; ++i) {
200 if (!strcmp(name, self->functions[i]->name))
201 return self->functions[i];
206 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
208 ir_function *fn = ir_builder_get_function(self, name);
213 fn = ir_function_new(self, outtype);
214 if (!ir_function_set_name(fn, name) ||
215 !ir_builder_functions_add(self, fn) )
217 ir_function_delete(fn);
221 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
223 ir_function_delete(fn);
227 fn->value->isconst = true;
228 fn->value->outtype = outtype;
229 fn->value->constval.vfunc = fn;
230 fn->value->context = fn->context;
235 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
238 for (i = 0; i < self->globals_count; ++i) {
239 if (!strcmp(self->globals[i]->name, name))
240 return self->globals[i];
245 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
249 if (name && name[0] != '#')
251 ve = ir_builder_get_global(self, name);
257 ve = ir_value_var(name, store_global, vtype);
258 if (!ir_builder_globals_add(self, ve)) {
265 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
268 for (i = 0; i < self->fields_count; ++i) {
269 if (!strcmp(self->fields[i]->name, name))
270 return self->fields[i];
276 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
278 ir_value *ve = ir_builder_get_field(self, name);
283 ve = ir_value_var(name, store_global, TYPE_FIELD);
284 ve->fieldtype = vtype;
285 if (!ir_builder_fields_add(self, ve)) {
292 /***********************************************************************
296 bool ir_function_naive_phi(ir_function*);
297 void ir_function_enumerate(ir_function*);
298 bool ir_function_calculate_liferanges(ir_function*);
299 bool ir_function_allocate_locals(ir_function*);
301 ir_function* ir_function_new(ir_builder* owner, int outtype)
304 self = (ir_function*)mem_a(sizeof(*self));
309 memset(self, 0, sizeof(*self));
312 if (!ir_function_set_name(self, "<@unnamed>")) {
317 self->context.file = "<@no context>";
318 self->context.line = 0;
319 self->outtype = outtype;
322 MEM_VECTOR_INIT(self, params);
323 MEM_VECTOR_INIT(self, blocks);
324 MEM_VECTOR_INIT(self, values);
325 MEM_VECTOR_INIT(self, locals);
327 self->code_function_def = -1;
328 self->allocated_locals = 0;
333 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
334 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
335 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
336 MEM_VEC_FUNCTIONS(ir_function, int, params)
338 bool ir_function_set_name(ir_function *self, const char *name)
341 mem_d((void*)self->name);
342 self->name = util_strdup(name);
346 void ir_function_delete(ir_function *self)
349 mem_d((void*)self->name);
351 for (i = 0; i != self->blocks_count; ++i)
352 ir_block_delete(self->blocks[i]);
353 MEM_VECTOR_CLEAR(self, blocks);
355 MEM_VECTOR_CLEAR(self, params);
357 for (i = 0; i != self->values_count; ++i)
358 ir_value_delete(self->values[i]);
359 MEM_VECTOR_CLEAR(self, values);
361 for (i = 0; i != self->locals_count; ++i)
362 ir_value_delete(self->locals[i]);
363 MEM_VECTOR_CLEAR(self, locals);
365 /* self->value is deleted by the builder */
370 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
372 return ir_function_values_add(self, v);
375 ir_block* ir_function_create_block(ir_function *self, const char *label)
377 ir_block* bn = ir_block_new(self, label);
378 memcpy(&bn->context, &self->context, sizeof(self->context));
379 if (!ir_function_blocks_add(self, bn)) {
386 bool ir_function_finalize(ir_function *self)
391 if (!ir_function_naive_phi(self))
394 ir_function_enumerate(self);
396 if (!ir_function_calculate_liferanges(self))
399 if (!ir_function_allocate_locals(self))
404 ir_value* ir_function_get_local(ir_function *self, const char *name)
407 for (i = 0; i < self->locals_count; ++i) {
408 if (!strcmp(self->locals[i]->name, name))
409 return self->locals[i];
414 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
416 ir_value *ve = ir_function_get_local(self, name);
422 self->locals_count &&
423 self->locals[self->locals_count-1]->store != store_param) {
424 irerror(self->context, "cannot add parameters after adding locals\n");
428 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
429 if (!ir_function_locals_add(self, ve)) {
436 /***********************************************************************
440 ir_block* ir_block_new(ir_function* owner, const char *name)
443 self = (ir_block*)mem_a(sizeof(*self));
447 memset(self, 0, sizeof(*self));
450 if (!ir_block_set_label(self, name)) {
455 self->context.file = "<@no context>";
456 self->context.line = 0;
458 MEM_VECTOR_INIT(self, instr);
459 MEM_VECTOR_INIT(self, entries);
460 MEM_VECTOR_INIT(self, exits);
463 self->is_return = false;
465 MEM_VECTOR_INIT(self, living);
467 self->generated = false;
471 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
472 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
473 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
474 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
476 void ir_block_delete(ir_block* self)
480 for (i = 0; i != self->instr_count; ++i)
481 ir_instr_delete(self->instr[i]);
482 MEM_VECTOR_CLEAR(self, instr);
483 MEM_VECTOR_CLEAR(self, entries);
484 MEM_VECTOR_CLEAR(self, exits);
485 MEM_VECTOR_CLEAR(self, living);
489 bool ir_block_set_label(ir_block *self, const char *name)
492 mem_d((void*)self->label);
493 self->label = util_strdup(name);
494 return !!self->label;
497 /***********************************************************************
501 ir_instr* ir_instr_new(ir_block* owner, int op)
504 self = (ir_instr*)mem_a(sizeof(*self));
509 self->context.file = "<@no context>";
510 self->context.line = 0;
512 self->_ops[0] = NULL;
513 self->_ops[1] = NULL;
514 self->_ops[2] = NULL;
515 self->bops[0] = NULL;
516 self->bops[1] = NULL;
517 MEM_VECTOR_INIT(self, phi);
518 MEM_VECTOR_INIT(self, params);
523 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
524 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
526 void ir_instr_delete(ir_instr *self)
529 /* The following calls can only delete from
530 * vectors, we still want to delete this instruction
531 * so ignore the return value. Since with the warn_unused_result attribute
532 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
533 * I have to improvise here and use if(foo());
535 for (i = 0; i < self->phi_count; ++i) {
537 if (ir_value_writes_find(self->phi[i].value, self, &idx))
538 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
539 if (ir_value_reads_find(self->phi[i].value, self, &idx))
540 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
542 MEM_VECTOR_CLEAR(self, phi);
543 for (i = 0; i < self->params_count; ++i) {
545 if (ir_value_writes_find(self->params[i], self, &idx))
546 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
547 if (ir_value_reads_find(self->params[i], self, &idx))
548 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
550 MEM_VECTOR_CLEAR(self, params);
551 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
552 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
553 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
557 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
559 if (self->_ops[op]) {
561 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
563 if (!ir_value_writes_remove(self->_ops[op], idx))
566 else if (ir_value_reads_find(self->_ops[op], self, &idx))
568 if (!ir_value_reads_remove(self->_ops[op], idx))
574 if (!ir_value_writes_add(v, self))
577 if (!ir_value_reads_add(v, self))
585 /***********************************************************************
589 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
591 self->code.globaladdr = gaddr;
592 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
593 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
594 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
597 int32_t ir_value_code_addr(const ir_value *self)
599 if (self->store == store_return)
600 return OFS_RETURN + self->code.addroffset;
601 return self->code.globaladdr + self->code.addroffset;
604 ir_value* ir_value_var(const char *name, int storetype, int vtype)
607 self = (ir_value*)mem_a(sizeof(*self));
609 self->fieldtype = TYPE_VOID;
610 self->outtype = TYPE_VOID;
611 self->store = storetype;
612 MEM_VECTOR_INIT(self, reads);
613 MEM_VECTOR_INIT(self, writes);
614 self->isconst = false;
615 self->context.file = "<@no context>";
616 self->context.line = 0;
618 ir_value_set_name(self, name);
620 memset(&self->constval, 0, sizeof(self->constval));
621 memset(&self->code, 0, sizeof(self->code));
623 self->members[0] = NULL;
624 self->members[1] = NULL;
625 self->members[2] = NULL;
627 MEM_VECTOR_INIT(self, life);
631 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
637 if (self->members[member])
638 return self->members[member];
640 if (self->vtype == TYPE_VECTOR)
642 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
645 m->context = self->context;
647 self->members[member] = m;
648 m->code.addroffset = member;
650 else if (self->vtype == TYPE_FIELD)
652 if (self->fieldtype != TYPE_VECTOR)
654 m = ir_value_var(self->name, self->store, TYPE_FIELD);
657 m->fieldtype = TYPE_FLOAT;
658 m->context = self->context;
660 self->members[member] = m;
661 m->code.addroffset = member;
665 irerror(self->context, "invalid member access on %s\n", self->name);
672 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
673 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
674 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
676 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
678 ir_value *v = ir_value_var(name, storetype, vtype);
681 if (!ir_function_collect_value(owner, v))
689 void ir_value_delete(ir_value* self)
693 mem_d((void*)self->name);
696 if (self->vtype == TYPE_STRING)
697 mem_d((void*)self->constval.vstring);
699 for (i = 0; i < 3; ++i) {
700 if (self->members[i])
701 ir_value_delete(self->members[i]);
703 MEM_VECTOR_CLEAR(self, reads);
704 MEM_VECTOR_CLEAR(self, writes);
705 MEM_VECTOR_CLEAR(self, life);
709 void ir_value_set_name(ir_value *self, const char *name)
712 mem_d((void*)self->name);
713 self->name = util_strdup(name);
716 bool ir_value_set_float(ir_value *self, float f)
718 if (self->vtype != TYPE_FLOAT)
720 self->constval.vfloat = f;
721 self->isconst = true;
725 bool ir_value_set_func(ir_value *self, int f)
727 if (self->vtype != TYPE_FUNCTION)
729 self->constval.vint = f;
730 self->isconst = true;
734 bool ir_value_set_vector(ir_value *self, vector v)
736 if (self->vtype != TYPE_VECTOR)
738 self->constval.vvec = v;
739 self->isconst = true;
743 bool ir_value_set_field(ir_value *self, ir_value *fld)
745 if (self->vtype != TYPE_FIELD)
747 self->constval.vpointer = fld;
748 self->isconst = true;
752 bool ir_value_set_string(ir_value *self, const char *str)
754 if (self->vtype != TYPE_STRING)
756 self->constval.vstring = util_strdup(str);
757 self->isconst = true;
762 bool ir_value_set_int(ir_value *self, int i)
764 if (self->vtype != TYPE_INTEGER)
766 self->constval.vint = i;
767 self->isconst = true;
772 bool ir_value_lives(ir_value *self, size_t at)
775 for (i = 0; i < self->life_count; ++i)
777 ir_life_entry_t *life = &self->life[i];
778 if (life->start <= at && at <= life->end)
780 if (life->start > at) /* since it's ordered */
786 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
789 if (!ir_value_life_add(self, e)) /* naive... */
791 for (k = self->life_count-1; k > idx; --k)
792 self->life[k] = self->life[k-1];
797 bool ir_value_life_merge(ir_value *self, size_t s)
800 ir_life_entry_t *life = NULL;
801 ir_life_entry_t *before = NULL;
802 ir_life_entry_t new_entry;
804 /* Find the first range >= s */
805 for (i = 0; i < self->life_count; ++i)
808 life = &self->life[i];
812 /* nothing found? append */
813 if (i == self->life_count) {
815 if (life && life->end+1 == s)
817 /* previous life range can be merged in */
821 if (life && life->end >= s)
824 if (!ir_value_life_add(self, e))
825 return false; /* failing */
831 if (before->end + 1 == s &&
832 life->start - 1 == s)
835 before->end = life->end;
836 if (!ir_value_life_remove(self, i))
837 return false; /* failing */
840 if (before->end + 1 == s)
846 /* already contained */
847 if (before->end >= s)
851 if (life->start - 1 == s)
856 /* insert a new entry */
857 new_entry.start = new_entry.end = s;
858 return ir_value_life_insert(self, i, new_entry);
861 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
865 if (!other->life_count)
868 if (!self->life_count) {
869 for (i = 0; i < other->life_count; ++i) {
870 if (!ir_value_life_add(self, other->life[i]))
877 for (i = 0; i < other->life_count; ++i)
879 const ir_life_entry_t *life = &other->life[i];
882 ir_life_entry_t *entry = &self->life[myi];
884 if (life->end+1 < entry->start)
886 /* adding an interval before entry */
887 if (!ir_value_life_insert(self, myi, *life))
893 if (life->start < entry->start &&
894 life->end >= entry->start)
896 /* starts earlier and overlaps */
897 entry->start = life->start;
900 if (life->end > entry->end &&
901 life->start-1 <= entry->end)
903 /* ends later and overlaps */
904 entry->end = life->end;
907 /* see if our change combines it with the next ranges */
908 while (myi+1 < self->life_count &&
909 entry->end+1 >= self->life[1+myi].start)
911 /* overlaps with (myi+1) */
912 if (entry->end < self->life[1+myi].end)
913 entry->end = self->life[1+myi].end;
914 if (!ir_value_life_remove(self, myi+1))
916 entry = &self->life[myi];
919 /* see if we're after the entry */
920 if (life->start > entry->end)
923 /* append if we're at the end */
924 if (myi >= self->life_count) {
925 if (!ir_value_life_add(self, *life))
929 /* otherweise check the next range */
938 bool ir_values_overlap(const ir_value *a, const ir_value *b)
940 /* For any life entry in A see if it overlaps with
941 * any life entry in B.
942 * Note that the life entries are orderes, so we can make a
943 * more efficient algorithm there than naively translating the
947 ir_life_entry_t *la, *lb, *enda, *endb;
949 /* first of all, if either has no life range, they cannot clash */
950 if (!a->life_count || !b->life_count)
955 enda = la + a->life_count;
956 endb = lb + b->life_count;
959 /* check if the entries overlap, for that,
960 * both must start before the other one ends.
962 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
963 if (la->start <= lb->end &&
964 lb->start <= la->end)
966 if (la->start < lb->end &&
973 /* entries are ordered
974 * one entry is earlier than the other
975 * that earlier entry will be moved forward
977 if (la->start < lb->start)
979 /* order: A B, move A forward
980 * check if we hit the end with A
985 else /* if (lb->start < la->start) actually <= */
987 /* order: B A, move B forward
988 * check if we hit the end with B
997 /***********************************************************************
1001 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1003 ir_instr *in = ir_instr_new(self, op);
1007 if (target->store == store_value &&
1008 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1010 irerror(self->context, "cannot store to an SSA value\n");
1011 irerror(self->context, "trying to store: %s <- %s\n", target->name, what->name);
1012 irerror(self->context, "instruction: %s\n", asm_instr[op].m);
1016 if (!ir_instr_op(in, 0, target, true) ||
1017 !ir_instr_op(in, 1, what, false) ||
1018 !ir_block_instr_add(self, in) )
1025 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1029 if (target->vtype == TYPE_VARIANT)
1030 vtype = what->vtype;
1032 vtype = target->vtype;
1035 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1036 op = INSTR_CONV_ITOF;
1037 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1038 op = INSTR_CONV_FTOI;
1040 op = type_store_instr[vtype];
1042 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1043 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1047 return ir_block_create_store_op(self, op, target, what);
1050 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1055 if (target->vtype != TYPE_POINTER)
1058 /* storing using pointer - target is a pointer, type must be
1059 * inferred from source
1061 vtype = what->vtype;
1063 op = type_storep_instr[vtype];
1064 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1065 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1066 op = INSTR_STOREP_V;
1069 return ir_block_create_store_op(self, op, target, what);
1072 bool ir_block_create_return(ir_block *self, ir_value *v)
1076 irerror(self->context, "block already ended (%s)\n", self->label);
1080 self->is_return = true;
1081 in = ir_instr_new(self, INSTR_RETURN);
1085 if (v && !ir_instr_op(in, 0, v, false))
1088 if (!ir_block_instr_add(self, in))
1093 bool ir_block_create_if(ir_block *self, ir_value *v,
1094 ir_block *ontrue, ir_block *onfalse)
1098 irerror(self->context, "block already ended (%s)\n", self->label);
1102 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1103 in = ir_instr_new(self, VINSTR_COND);
1107 if (!ir_instr_op(in, 0, v, false)) {
1108 ir_instr_delete(in);
1112 in->bops[0] = ontrue;
1113 in->bops[1] = onfalse;
1115 if (!ir_block_instr_add(self, in))
1118 if (!ir_block_exits_add(self, ontrue) ||
1119 !ir_block_exits_add(self, onfalse) ||
1120 !ir_block_entries_add(ontrue, self) ||
1121 !ir_block_entries_add(onfalse, self) )
1128 bool ir_block_create_jump(ir_block *self, ir_block *to)
1132 irerror(self->context, "block already ended (%s)\n", self->label);
1136 in = ir_instr_new(self, VINSTR_JUMP);
1141 if (!ir_block_instr_add(self, in))
1144 if (!ir_block_exits_add(self, to) ||
1145 !ir_block_entries_add(to, self) )
1152 bool ir_block_create_goto(ir_block *self, ir_block *to)
1156 irerror(self->context, "block already ended (%s)\n", self->label);
1160 in = ir_instr_new(self, INSTR_GOTO);
1165 if (!ir_block_instr_add(self, in))
1168 if (!ir_block_exits_add(self, to) ||
1169 !ir_block_entries_add(to, self) )
1176 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1180 in = ir_instr_new(self, VINSTR_PHI);
1183 out = ir_value_out(self->owner, label, store_value, ot);
1185 ir_instr_delete(in);
1188 if (!ir_instr_op(in, 0, out, true)) {
1189 ir_instr_delete(in);
1190 ir_value_delete(out);
1193 if (!ir_block_instr_add(self, in)) {
1194 ir_instr_delete(in);
1195 ir_value_delete(out);
1201 ir_value* ir_phi_value(ir_instr *self)
1203 return self->_ops[0];
1206 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1210 if (!ir_block_entries_find(self->owner, b, NULL)) {
1211 /* Must not be possible to cause this, otherwise the AST
1212 * is doing something wrong.
1214 irerror(self->context, "Invalid entry block for PHI\n");
1220 if (!ir_value_reads_add(v, self))
1222 return ir_instr_phi_add(self, pe);
1225 /* call related code */
1226 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1230 in = ir_instr_new(self, INSTR_CALL0);
1233 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1235 ir_instr_delete(in);
1238 if (!ir_instr_op(in, 0, out, true) ||
1239 !ir_instr_op(in, 1, func, false) ||
1240 !ir_block_instr_add(self, in))
1242 ir_instr_delete(in);
1243 ir_value_delete(out);
1249 ir_value* ir_call_value(ir_instr *self)
1251 return self->_ops[0];
1254 bool ir_call_param(ir_instr* self, ir_value *v)
1256 if (!ir_instr_params_add(self, v))
1258 if (!ir_value_reads_add(v, self)) {
1259 if (!ir_instr_params_remove(self, self->params_count-1))
1260 GMQCC_SUPPRESS_EMPTY_BODY;
1266 /* binary op related code */
1268 ir_value* ir_block_create_binop(ir_block *self,
1269 const char *label, int opcode,
1270 ir_value *left, ir_value *right)
1292 case INSTR_SUB_S: /* -- offset of string as float */
1297 case INSTR_BITOR_IF:
1298 case INSTR_BITOR_FI:
1299 case INSTR_BITAND_FI:
1300 case INSTR_BITAND_IF:
1315 case INSTR_BITAND_I:
1318 case INSTR_RSHIFT_I:
1319 case INSTR_LSHIFT_I:
1341 /* boolean operations result in floats */
1342 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1344 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1347 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1352 if (ot == TYPE_VOID) {
1353 /* The AST or parser were supposed to check this! */
1357 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1360 ir_value* ir_block_create_unary(ir_block *self,
1361 const char *label, int opcode,
1364 int ot = TYPE_FLOAT;
1376 /* QC doesn't have other unary operations. We expect extensions to fill
1377 * the above list, otherwise we assume out-type = in-type, eg for an
1381 ot = operand->vtype;
1384 if (ot == TYPE_VOID) {
1385 /* The AST or parser were supposed to check this! */
1389 /* let's use the general instruction creator and pass NULL for OPB */
1390 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1393 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1394 int op, ir_value *a, ir_value *b, int outype)
1399 out = ir_value_out(self->owner, label, store_value, outype);
1403 instr = ir_instr_new(self, op);
1405 ir_value_delete(out);
1409 if (!ir_instr_op(instr, 0, out, true) ||
1410 !ir_instr_op(instr, 1, a, false) ||
1411 !ir_instr_op(instr, 2, b, false) )
1416 if (!ir_block_instr_add(self, instr))
1421 ir_instr_delete(instr);
1422 ir_value_delete(out);
1426 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1430 /* Support for various pointer types todo if so desired */
1431 if (ent->vtype != TYPE_ENTITY)
1434 if (field->vtype != TYPE_FIELD)
1437 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1438 v->fieldtype = field->fieldtype;
1442 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1445 if (ent->vtype != TYPE_ENTITY)
1448 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1449 if (field->vtype != TYPE_FIELD)
1454 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1455 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1456 case TYPE_STRING: op = INSTR_LOAD_S; break;
1457 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1458 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1459 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1461 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1462 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1468 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1471 ir_value* ir_block_create_add(ir_block *self,
1473 ir_value *left, ir_value *right)
1476 int l = left->vtype;
1477 int r = right->vtype;
1496 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1498 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1504 return ir_block_create_binop(self, label, op, left, right);
1507 ir_value* ir_block_create_sub(ir_block *self,
1509 ir_value *left, ir_value *right)
1512 int l = left->vtype;
1513 int r = right->vtype;
1533 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1535 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1541 return ir_block_create_binop(self, label, op, left, right);
1544 ir_value* ir_block_create_mul(ir_block *self,
1546 ir_value *left, ir_value *right)
1549 int l = left->vtype;
1550 int r = right->vtype;
1569 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1571 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1574 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1576 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1578 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1580 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1586 return ir_block_create_binop(self, label, op, left, right);
1589 ir_value* ir_block_create_div(ir_block *self,
1591 ir_value *left, ir_value *right)
1594 int l = left->vtype;
1595 int r = right->vtype;
1612 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1614 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1616 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1622 return ir_block_create_binop(self, label, op, left, right);
1625 /* PHI resolving breaks the SSA, and must thus be the last
1626 * step before life-range calculation.
1629 static bool ir_block_naive_phi(ir_block *self);
1630 bool ir_function_naive_phi(ir_function *self)
1634 for (i = 0; i < self->blocks_count; ++i)
1636 if (!ir_block_naive_phi(self->blocks[i]))
1642 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1647 /* create a store */
1648 if (!ir_block_create_store(block, old, what))
1651 /* we now move it up */
1652 instr = block->instr[block->instr_count-1];
1653 for (i = block->instr_count; i > iid; --i)
1654 block->instr[i] = block->instr[i-1];
1655 block->instr[i] = instr;
1660 static bool ir_block_naive_phi(ir_block *self)
1663 /* FIXME: optionally, create_phi can add the phis
1664 * to a list so we don't need to loop through blocks
1665 * - anyway: "don't optimize YET"
1667 for (i = 0; i < self->instr_count; ++i)
1669 ir_instr *instr = self->instr[i];
1670 if (instr->opcode != VINSTR_PHI)
1673 if (!ir_block_instr_remove(self, i))
1675 --i; /* NOTE: i+1 below */
1677 for (p = 0; p < instr->phi_count; ++p)
1679 ir_value *v = instr->phi[p].value;
1680 for (w = 0; w < v->writes_count; ++w) {
1683 if (!v->writes[w]->_ops[0])
1686 /* When the write was to a global, we have to emit a mov */
1687 old = v->writes[w]->_ops[0];
1689 /* The original instruction now writes to the PHI target local */
1690 if (v->writes[w]->_ops[0] == v)
1691 v->writes[w]->_ops[0] = instr->_ops[0];
1693 if (old->store != store_value && old->store != store_local && old->store != store_param)
1695 /* If it originally wrote to a global we need to store the value
1698 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1700 if (i+1 < self->instr_count)
1701 instr = self->instr[i+1];
1704 /* In case I forget and access instr later, it'll be NULL
1705 * when it's a problem, to make sure we crash, rather than accessing
1711 /* If it didn't, we can replace all reads by the phi target now. */
1713 for (r = 0; r < old->reads_count; ++r)
1716 ir_instr *ri = old->reads[r];
1717 for (op = 0; op < ri->phi_count; ++op) {
1718 if (ri->phi[op].value == old)
1719 ri->phi[op].value = v;
1721 for (op = 0; op < 3; ++op) {
1722 if (ri->_ops[op] == old)
1729 ir_instr_delete(instr);
1734 /***********************************************************************
1735 *IR Temp allocation code
1736 * Propagating value life ranges by walking through the function backwards
1737 * until no more changes are made.
1738 * In theory this should happen once more than once for every nested loop
1740 * Though this implementation might run an additional time for if nests.
1749 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1751 /* Enumerate instructions used by value's life-ranges
1753 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1757 for (i = 0; i < self->instr_count; ++i)
1759 self->instr[i]->eid = eid++;
1764 /* Enumerate blocks and instructions.
1765 * The block-enumeration is unordered!
1766 * We do not really use the block enumreation, however
1767 * the instruction enumeration is important for life-ranges.
1769 void ir_function_enumerate(ir_function *self)
1772 size_t instruction_id = 0;
1773 for (i = 0; i < self->blocks_count; ++i)
1775 self->blocks[i]->eid = i;
1776 self->blocks[i]->run_id = 0;
1777 ir_block_enumerate(self->blocks[i], &instruction_id);
1781 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1782 bool ir_function_calculate_liferanges(ir_function *self)
1790 for (i = 0; i != self->blocks_count; ++i)
1792 if (self->blocks[i]->is_return)
1794 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1802 /* Local-value allocator
1803 * After finishing creating the liferange of all values used in a function
1804 * we can allocate their global-positions.
1805 * This is the counterpart to register-allocation in register machines.
1808 MEM_VECTOR_MAKE(ir_value*, locals);
1809 MEM_VECTOR_MAKE(size_t, sizes);
1810 MEM_VECTOR_MAKE(size_t, positions);
1811 } function_allocator;
1812 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1813 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1814 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1816 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1819 size_t vsize = type_sizeof[var->vtype];
1821 slot = ir_value_var("reg", store_global, var->vtype);
1825 if (!ir_value_life_merge_into(slot, var))
1828 if (!function_allocator_locals_add(alloc, slot))
1831 if (!function_allocator_sizes_add(alloc, vsize))
1837 ir_value_delete(slot);
1841 bool ir_function_allocate_locals(ir_function *self)
1850 function_allocator alloc;
1852 if (!self->locals_count && !self->values_count)
1855 MEM_VECTOR_INIT(&alloc, locals);
1856 MEM_VECTOR_INIT(&alloc, sizes);
1857 MEM_VECTOR_INIT(&alloc, positions);
1859 for (i = 0; i < self->locals_count; ++i)
1861 if (!function_allocator_alloc(&alloc, self->locals[i]))
1865 /* Allocate a slot for any value that still exists */
1866 for (i = 0; i < self->values_count; ++i)
1868 v = self->values[i];
1873 for (a = 0; a < alloc.locals_count; ++a)
1875 slot = alloc.locals[a];
1877 if (ir_values_overlap(v, slot))
1880 if (!ir_value_life_merge_into(slot, v))
1883 /* adjust size for this slot */
1884 if (alloc.sizes[a] < type_sizeof[v->vtype])
1885 alloc.sizes[a] = type_sizeof[v->vtype];
1887 self->values[i]->code.local = a;
1890 if (a >= alloc.locals_count) {
1891 self->values[i]->code.local = alloc.locals_count;
1892 if (!function_allocator_alloc(&alloc, v))
1901 /* Adjust slot positions based on sizes */
1902 if (!function_allocator_positions_add(&alloc, 0))
1905 if (alloc.sizes_count)
1906 pos = alloc.positions[0] + alloc.sizes[0];
1909 for (i = 1; i < alloc.sizes_count; ++i)
1911 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1912 if (!function_allocator_positions_add(&alloc, pos))
1916 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1918 /* Take over the actual slot positions */
1919 for (i = 0; i < self->values_count; ++i) {
1920 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1928 for (i = 0; i < alloc.locals_count; ++i)
1929 ir_value_delete(alloc.locals[i]);
1930 MEM_VECTOR_CLEAR(&alloc, locals);
1931 MEM_VECTOR_CLEAR(&alloc, sizes);
1932 MEM_VECTOR_CLEAR(&alloc, positions);
1936 /* Get information about which operand
1937 * is read from, or written to.
1939 static void ir_op_read_write(int op, size_t *read, size_t *write)
1959 case INSTR_STOREP_F:
1960 case INSTR_STOREP_V:
1961 case INSTR_STOREP_S:
1962 case INSTR_STOREP_ENT:
1963 case INSTR_STOREP_FLD:
1964 case INSTR_STOREP_FNC:
1975 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1978 bool changed = false;
1980 for (i = 0; i != self->living_count; ++i)
1982 tempbool = ir_value_life_merge(self->living[i], eid);
1985 irerror(self->context, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1987 changed = changed || tempbool;
1992 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1995 /* values which have been read in a previous iteration are now
1996 * in the "living" array even if the previous block doesn't use them.
1997 * So we have to remove whatever does not exist in the previous block.
1998 * They will be re-added on-read, but the liferange merge won't cause
2001 for (i = 0; i < self->living_count; ++i)
2003 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2004 if (!ir_block_living_remove(self, i))
2010 /* Whatever the previous block still has in its living set
2011 * must now be added to ours as well.
2013 for (i = 0; i < prev->living_count; ++i)
2015 if (ir_block_living_find(self, prev->living[i], NULL))
2017 if (!ir_block_living_add(self, prev->living[i]))
2020 irerror(self->contextt from prev: %s\n", self->label, prev->living[i]->_name);
2026 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2032 /* bitmasks which operands are read from or written to */
2034 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2036 new_reads_t new_reads;
2038 char dbg_ind[16] = { '#', '0' };
2041 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2042 MEM_VECTOR_INIT(&new_reads, v);
2047 if (!ir_block_life_prop_previous(self, prev, changed))
2051 i = self->instr_count;
2054 instr = self->instr[i];
2056 /* PHI operands are always read operands */
2057 for (p = 0; p < instr->phi_count; ++p)
2059 value = instr->phi[p].value;
2060 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2061 if (!ir_block_living_find(self, value, NULL) &&
2062 !ir_block_living_add(self, value))
2067 if (!new_reads_t_v_find(&new_reads, value, NULL))
2069 if (!new_reads_t_v_add(&new_reads, value))
2075 /* call params are read operands too */
2076 for (p = 0; p < instr->params_count; ++p)
2078 value = instr->params[p];
2079 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2080 if (!ir_block_living_find(self, value, NULL) &&
2081 !ir_block_living_add(self, value))
2086 if (!new_reads_t_v_find(&new_reads, value, NULL))
2088 if (!new_reads_t_v_add(&new_reads, value))
2094 /* See which operands are read and write operands */
2095 ir_op_read_write(instr->opcode, &read, &write);
2097 /* Go through the 3 main operands */
2098 for (o = 0; o < 3; ++o)
2100 if (!instr->_ops[o]) /* no such operand */
2103 value = instr->_ops[o];
2105 /* We only care about locals */
2106 /* we also calculate parameter liferanges so that locals
2107 * can take up parameter slots */
2108 if (value->store != store_value &&
2109 value->store != store_local &&
2110 value->store != store_param)
2116 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2117 if (!ir_block_living_find(self, value, NULL) &&
2118 !ir_block_living_add(self, value))
2123 /* fprintf(stderr, "read: %s\n", value->_name); */
2124 if (!new_reads_t_v_find(&new_reads, value, NULL))
2126 if (!new_reads_t_v_add(&new_reads, value))
2132 /* write operands */
2133 /* When we write to a local, we consider it "dead" for the
2134 * remaining upper part of the function, since in SSA a value
2135 * can only be written once (== created)
2140 bool in_living = ir_block_living_find(self, value, &idx);
2141 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2143 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2144 if (!in_living && !in_reads)
2149 /* If the value isn't alive it hasn't been read before... */
2150 /* TODO: See if the warning can be emitted during parsing or AST processing
2151 * otherwise have warning printed here.
2152 * IF printing a warning here: include filecontext_t,
2153 * and make sure it's only printed once
2154 * since this function is run multiple times.
2156 /* For now: debug info: */
2157 /* fprintf(stderr, "Value only written %s\n", value->name); */
2158 tempbool = ir_value_life_merge(value, instr->eid);
2159 *changed = *changed || tempbool;
2161 ir_instr_dump(instr, dbg_ind, printf);
2165 /* since 'living' won't contain it
2166 * anymore, merge the value, since
2169 tempbool = ir_value_life_merge(value, instr->eid);
2172 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2174 *changed = *changed || tempbool;
2176 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2177 if (!ir_block_living_remove(self, idx))
2182 if (!new_reads_t_v_remove(&new_reads, readidx))
2190 tempbool = ir_block_living_add_instr(self, instr->eid);
2191 /*fprintf(stderr, "living added values\n");*/
2192 *changed = *changed || tempbool;
2194 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2196 for (rd = 0; rd < new_reads.v_count; ++rd)
2198 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2199 if (!ir_block_living_add(self, new_reads.v[rd]))
2202 if (!i && !self->entries_count) {
2204 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2207 MEM_VECTOR_CLEAR(&new_reads, v);
2211 if (self->run_id == self->owner->run_id)
2214 self->run_id = self->owner->run_id;
2216 for (i = 0; i < self->entries_count; ++i)
2218 ir_block *entry = self->entries[i];
2219 ir_block_life_propagate(entry, self, changed);
2224 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2225 MEM_VECTOR_CLEAR(&new_reads, v);
2230 /***********************************************************************
2233 * Since the IR has the convention of putting 'write' operands
2234 * at the beginning, we have to rotate the operands of instructions
2235 * properly in order to generate valid QCVM code.
2237 * Having destinations at a fixed position is more convenient. In QC
2238 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2239 * read from from OPA, and store to OPB rather than OPC. Which is
2240 * partially the reason why the implementation of these instructions
2241 * in darkplaces has been delayed for so long.
2243 * Breaking conventions is annoying...
2245 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2247 static bool gen_global_field(ir_value *global)
2249 if (global->isconst)
2251 ir_value *fld = global->constval.vpointer;
2253 irerror(global->context, "Invalid field constant with no field: %s\n", global->name);
2257 /* Now, in this case, a relocation would be impossible to code
2258 * since it looks like this:
2259 * .vector v = origin; <- parse error, wtf is 'origin'?
2262 * But we will need a general relocation support later anyway
2263 * for functions... might as well support that here.
2265 if (!fld->code.globaladdr) {
2266 irerror(global->context, "FIXME: Relocation support\n");
2270 /* copy the field's value */
2271 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2272 if (global->fieldtype == TYPE_VECTOR) {
2273 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2274 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2279 ir_value_code_setaddr(global, code_globals_add(0));
2280 if (global->fieldtype == TYPE_VECTOR) {
2281 code_globals_add(0);
2282 code_globals_add(0);
2285 if (global->code.globaladdr < 0)
2290 static bool gen_global_pointer(ir_value *global)
2292 if (global->isconst)
2294 ir_value *target = global->constval.vpointer;
2296 irerror(global->context, "Invalid pointer constant: %s\n", global->name);
2297 /* NULL pointers are pointing to the NULL constant, which also
2298 * sits at address 0, but still has an ir_value for itself.
2303 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2304 * void() foo; <- proto
2305 * void() *fooptr = &foo;
2306 * void() foo = { code }
2308 if (!target->code.globaladdr) {
2309 /* FIXME: Check for the constant nullptr ir_value!
2310 * because then code.globaladdr being 0 is valid.
2312 irerror(global->context, "FIXME: Relocation support\n");
2316 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2320 ir_value_code_setaddr(global, code_globals_add(0));
2322 if (global->code.globaladdr < 0)
2327 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2329 prog_section_statement stmt;
2338 block->generated = true;
2339 block->code_start = code_statements_elements;
2340 for (i = 0; i < block->instr_count; ++i)
2342 instr = block->instr[i];
2344 if (instr->opcode == VINSTR_PHI) {
2345 irerror(block->context, "cannot generate virtual instruction (phi)\n");
2349 if (instr->opcode == VINSTR_JUMP) {
2350 target = instr->bops[0];
2351 /* for uncoditional jumps, if the target hasn't been generated
2352 * yet, we generate them right here.
2354 if (!target->generated) {
2359 /* otherwise we generate a jump instruction */
2360 stmt.opcode = INSTR_GOTO;
2361 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2364 if (code_statements_add(stmt) < 0)
2367 /* no further instructions can be in this block */
2371 if (instr->opcode == VINSTR_COND) {
2372 ontrue = instr->bops[0];
2373 onfalse = instr->bops[1];
2374 /* TODO: have the AST signal which block should
2375 * come first: eg. optimize IFs without ELSE...
2378 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2382 if (ontrue->generated) {
2383 stmt.opcode = INSTR_IF;
2384 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2385 if (code_statements_add(stmt) < 0)
2388 if (onfalse->generated) {
2389 stmt.opcode = INSTR_IFNOT;
2390 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2391 if (code_statements_add(stmt) < 0)
2394 if (!ontrue->generated) {
2395 if (onfalse->generated) {
2400 if (!onfalse->generated) {
2401 if (ontrue->generated) {
2406 /* neither ontrue nor onfalse exist */
2407 stmt.opcode = INSTR_IFNOT;
2408 stidx = code_statements_elements;
2409 if (code_statements_add(stmt) < 0)
2411 /* on false we jump, so add ontrue-path */
2412 if (!gen_blocks_recursive(func, ontrue))
2414 /* fixup the jump address */
2415 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2416 /* generate onfalse path */
2417 if (onfalse->generated) {
2418 /* fixup the jump address */
2419 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2420 /* may have been generated in the previous recursive call */
2421 stmt.opcode = INSTR_GOTO;
2422 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2425 return (code_statements_add(stmt) >= 0);
2427 /* if not, generate now */
2432 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2433 /* Trivial call translation:
2434 * copy all params to OFS_PARM*
2435 * if the output's storetype is not store_return,
2436 * add append a STORE instruction!
2438 * NOTES on how to do it better without much trouble:
2439 * -) The liferanges!
2440 * Simply check the liferange of all parameters for
2441 * other CALLs. For each param with no CALL in its
2442 * liferange, we can store it in an OFS_PARM at
2443 * generation already. This would even include later
2444 * reuse.... probably... :)
2449 for (p = 0; p < instr->params_count; ++p)
2451 ir_value *param = instr->params[p];
2453 stmt.opcode = INSTR_STORE_F;
2456 stmt.opcode = type_store_instr[param->vtype];
2457 stmt.o1.u1 = ir_value_code_addr(param);
2458 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2459 if (code_statements_add(stmt) < 0)
2462 stmt.opcode = INSTR_CALL0 + instr->params_count;
2463 if (stmt.opcode > INSTR_CALL8)
2464 stmt.opcode = INSTR_CALL8;
2465 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2468 if (code_statements_add(stmt) < 0)
2471 retvalue = instr->_ops[0];
2472 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2474 /* not to be kept in OFS_RETURN */
2475 stmt.opcode = type_store_instr[retvalue->vtype];
2476 stmt.o1.u1 = OFS_RETURN;
2477 stmt.o2.u1 = ir_value_code_addr(retvalue);
2479 if (code_statements_add(stmt) < 0)
2485 if (instr->opcode == INSTR_STATE) {
2486 irerror(block->context, "TODO: state instruction\n");
2490 stmt.opcode = instr->opcode;
2495 /* This is the general order of operands */
2497 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2500 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2503 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2505 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2507 stmt.o1.u1 = stmt.o3.u1;
2510 else if ((stmt.opcode >= INSTR_STORE_F &&
2511 stmt.opcode <= INSTR_STORE_FNC) ||
2512 (stmt.opcode >= INSTR_STOREP_F &&
2513 stmt.opcode <= INSTR_STOREP_FNC))
2515 /* 2-operand instructions with A -> B */
2516 stmt.o2.u1 = stmt.o3.u1;
2520 if (code_statements_add(stmt) < 0)
2526 static bool gen_function_code(ir_function *self)
2529 prog_section_statement stmt;
2531 /* Starting from entry point, we generate blocks "as they come"
2532 * for now. Dead blocks will not be translated obviously.
2534 if (!self->blocks_count) {
2535 irerror(self->context, "Function '%s' declared without body.\n", self->name);
2539 block = self->blocks[0];
2540 if (block->generated)
2543 if (!gen_blocks_recursive(self, block)) {
2544 irerror(self->context, "failed to generate blocks for '%s'\n", self->name);
2548 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2549 stmt.opcode = AINSTR_END;
2553 if (code_statements_add(stmt) < 0)
2558 static bool gen_global_function(ir_builder *ir, ir_value *global)
2560 prog_section_function fun;
2564 size_t local_var_end;
2566 if (!global->isconst || (!global->constval.vfunc))
2568 irerror(global->context, "Invalid state of function-global: not constant: %s\n", global->name);
2572 irfun = global->constval.vfunc;
2574 fun.name = global->code.name;
2575 fun.file = code_cachedstring(global->context.file);
2576 fun.profile = 0; /* always 0 */
2577 fun.nargs = irfun->params_count;
2579 for (i = 0;i < 8; ++i) {
2583 fun.argsize[i] = type_sizeof[irfun->params[i]];
2586 fun.firstlocal = code_globals_elements;
2587 fun.locals = irfun->allocated_locals + irfun->locals_count;
2589 local_var_end = fun.firstlocal;
2590 for (i = 0; i < irfun->locals_count; ++i) {
2591 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2592 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2596 if (irfun->locals_count) {
2597 ir_value *last = irfun->locals[irfun->locals_count-1];
2598 local_var_end = last->code.globaladdr;
2599 local_var_end += type_sizeof[last->vtype];
2601 for (i = 0; i < irfun->values_count; ++i)
2603 /* generate code.globaladdr for ssa values */
2604 ir_value *v = irfun->values[i];
2605 ir_value_code_setaddr(v, local_var_end + v->code.local);
2607 for (i = 0; i < irfun->allocated_locals; ++i) {
2608 /* fill the locals with zeros */
2609 code_globals_add(0);
2613 fun.entry = irfun->builtin;
2615 irfun->code_function_def = code_functions_elements;
2616 fun.entry = code_statements_elements;
2619 return (code_functions_add(fun) >= 0);
2622 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2624 prog_section_function *fundef;
2627 irfun = global->constval.vfunc;
2631 if (irfun->code_function_def < 0) {
2632 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2635 fundef = &code_functions_data[irfun->code_function_def];
2637 fundef->entry = code_statements_elements;
2638 if (!gen_function_code(irfun)) {
2639 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2645 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2649 prog_section_def def;
2651 def.type = global->vtype;
2652 def.offset = code_globals_elements;
2653 def.name = global->code.name = code_genstring(global->name);
2655 switch (global->vtype)
2658 if (code_defs_add(def) < 0)
2660 return gen_global_pointer(global);
2662 if (code_defs_add(def) < 0)
2664 return gen_global_field(global);
2669 if (code_defs_add(def) < 0)
2672 if (global->isconst) {
2673 iptr = (int32_t*)&global->constval.vfloat;
2674 ir_value_code_setaddr(global, code_globals_add(*iptr));
2676 ir_value_code_setaddr(global, code_globals_add(0));
2678 return global->code.globaladdr >= 0;
2682 if (code_defs_add(def) < 0)
2684 if (global->isconst)
2685 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2687 ir_value_code_setaddr(global, code_globals_add(0));
2688 return global->code.globaladdr >= 0;
2693 if (code_defs_add(def) < 0)
2696 if (global->isconst) {
2697 iptr = (int32_t*)&global->constval.vvec;
2698 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2699 if (global->code.globaladdr < 0)
2701 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2703 if (code_globals_add(iptr[d]) < 0)
2707 ir_value_code_setaddr(global, code_globals_add(0));
2708 if (global->code.globaladdr < 0)
2710 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2712 if (code_globals_add(0) < 0)
2716 return global->code.globaladdr >= 0;
2719 if (code_defs_add(def) < 0)
2721 ir_value_code_setaddr(global, code_globals_elements);
2722 code_globals_add(code_functions_elements);
2723 return gen_global_function(self, global);
2725 /* assume biggest type */
2726 ir_value_code_setaddr(global, code_globals_add(0));
2727 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2728 code_globals_add(0);
2731 /* refuse to create 'void' type or any other fancy business. */
2732 irerror(global->context, "Invalid type for global variable %s\n", global->name);
2737 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2739 prog_section_def def;
2740 prog_section_field fld;
2742 def.type = field->vtype;
2743 def.offset = code_globals_elements;
2745 /* create a global named the same as the field */
2746 if (opts_standard == COMPILER_GMQCC) {
2747 /* in our standard, the global gets a dot prefix */
2748 size_t len = strlen(field->name);
2751 /* we really don't want to have to allocate this, and 1024
2752 * bytes is more than enough for a variable/field name
2754 if (len+2 >= sizeof(name)) {
2755 irerror(field->context, "invalid field name size: %u\n", (unsigned int)len);
2760 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2763 def.name = code_genstring(name);
2764 fld.name = def.name + 1; /* we reuse that string table entry */
2766 /* in plain QC, there cannot be a global with the same name,
2767 * and so we also name the global the same.
2768 * FIXME: fteqcc should create a global as well
2769 * check if it actually uses the same name. Probably does
2771 def.name = code_genstring(field->name);
2772 fld.name = def.name;
2775 field->code.name = def.name;
2777 if (code_defs_add(def) < 0)
2780 fld.type = field->fieldtype;
2782 if (fld.type == TYPE_VOID) {
2783 irerror(field->context, "field is missing a type: %s - don't know its size\n", field->name);
2787 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2789 if (code_fields_add(fld) < 0)
2792 ir_value_code_setaddr(field, code_globals_elements);
2793 if (!code_globals_add(fld.offset))
2795 if (fld.type == TYPE_VECTOR) {
2796 if (!code_globals_add(fld.offset+1))
2798 if (!code_globals_add(fld.offset+2))
2802 return field->code.globaladdr >= 0;
2805 bool ir_builder_generate(ir_builder *self, const char *filename)
2811 for (i = 0; i < self->fields_count; ++i)
2813 if (!ir_builder_gen_field(self, self->fields[i])) {
2818 for (i = 0; i < self->globals_count; ++i)
2820 if (!ir_builder_gen_global(self, self->globals[i])) {
2825 /* generate function code */
2826 for (i = 0; i < self->globals_count; ++i)
2828 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2829 if (!gen_global_function_code(self, self->globals[i])) {
2835 printf("writing '%s'...\n", filename);
2836 return code_write(filename);
2839 /***********************************************************************
2840 *IR DEBUG Dump functions...
2843 #define IND_BUFSZ 1024
2846 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2848 # define strncat strncat
2851 const char *qc_opname(int op)
2853 if (op < 0) return "<INVALID>";
2854 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2855 return asm_instr[op].m;
2857 case VINSTR_PHI: return "PHI";
2858 case VINSTR_JUMP: return "JUMP";
2859 case VINSTR_COND: return "COND";
2860 default: return "<UNK>";
2864 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2867 char indent[IND_BUFSZ];
2871 oprintf("module %s\n", b->name);
2872 for (i = 0; i < b->globals_count; ++i)
2875 if (b->globals[i]->isconst)
2876 oprintf("%s = ", b->globals[i]->name);
2877 ir_value_dump(b->globals[i], oprintf);
2880 for (i = 0; i < b->functions_count; ++i)
2881 ir_function_dump(b->functions[i], indent, oprintf);
2882 oprintf("endmodule %s\n", b->name);
2885 void ir_function_dump(ir_function *f, char *ind,
2886 int (*oprintf)(const char*, ...))
2889 if (f->builtin != 0) {
2890 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2893 oprintf("%sfunction %s\n", ind, f->name);
2894 strncat(ind, "\t", IND_BUFSZ);
2895 if (f->locals_count)
2897 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2898 for (i = 0; i < f->locals_count; ++i) {
2899 oprintf("%s\t", ind);
2900 ir_value_dump(f->locals[i], oprintf);
2904 if (f->blocks_count)
2906 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2907 for (i = 0; i < f->blocks_count; ++i) {
2908 if (f->blocks[i]->run_id != f->run_id) {
2909 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2911 ir_block_dump(f->blocks[i], ind, oprintf);
2915 ind[strlen(ind)-1] = 0;
2916 oprintf("%sendfunction %s\n", ind, f->name);
2919 void ir_block_dump(ir_block* b, char *ind,
2920 int (*oprintf)(const char*, ...))
2923 oprintf("%s:%s\n", ind, b->label);
2924 strncat(ind, "\t", IND_BUFSZ);
2926 for (i = 0; i < b->instr_count; ++i)
2927 ir_instr_dump(b->instr[i], ind, oprintf);
2928 ind[strlen(ind)-1] = 0;
2931 void dump_phi(ir_instr *in, char *ind,
2932 int (*oprintf)(const char*, ...))
2935 oprintf("%s <- phi ", in->_ops[0]->name);
2936 for (i = 0; i < in->phi_count; ++i)
2938 oprintf("([%s] : %s) ", in->phi[i].from->label,
2939 in->phi[i].value->name);
2944 void ir_instr_dump(ir_instr *in, char *ind,
2945 int (*oprintf)(const char*, ...))
2948 const char *comma = NULL;
2950 oprintf("%s (%i) ", ind, (int)in->eid);
2952 if (in->opcode == VINSTR_PHI) {
2953 dump_phi(in, ind, oprintf);
2957 strncat(ind, "\t", IND_BUFSZ);
2959 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2960 ir_value_dump(in->_ops[0], oprintf);
2961 if (in->_ops[1] || in->_ops[2])
2964 if (in->opcode == INSTR_CALL0) {
2965 oprintf("CALL%i\t", in->params_count);
2967 oprintf("%s\t", qc_opname(in->opcode));
2969 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2970 ir_value_dump(in->_ops[0], oprintf);
2975 for (i = 1; i != 3; ++i) {
2979 ir_value_dump(in->_ops[i], oprintf);
2987 oprintf("[%s]", in->bops[0]->label);
2991 oprintf("%s[%s]", comma, in->bops[1]->label);
2993 ind[strlen(ind)-1] = 0;
2996 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3005 oprintf("(function)");
3008 oprintf("%g", v->constval.vfloat);
3011 oprintf("'%g %g %g'",
3014 v->constval.vvec.z);
3017 oprintf("(entity)");
3020 oprintf("\"%s\"", v->constval.vstring);
3024 oprintf("%i", v->constval.vint);
3029 v->constval.vpointer->name);
3033 oprintf("%s", v->name);
3037 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
3040 oprintf("Life of %s:\n", self->name);
3041 for (i = 0; i < self->life_count; ++i)
3043 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);