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);
169 MEM_VECTOR_INIT(self, filenames);
170 MEM_VECTOR_INIT(self, filestrings);
171 self->str_immediate = 0;
173 if (!ir_builder_set_name(self, modulename)) {
181 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
182 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
183 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
184 MEM_VEC_FUNCTIONS(ir_builder, const char*, filenames)
185 MEM_VEC_FUNCTIONS(ir_builder, qcint, filestrings)
187 void ir_builder_delete(ir_builder* self)
190 mem_d((void*)self->name);
191 for (i = 0; i != self->functions_count; ++i) {
192 ir_function_delete(self->functions[i]);
194 MEM_VECTOR_CLEAR(self, functions);
195 for (i = 0; i != self->globals_count; ++i) {
196 ir_value_delete(self->globals[i]);
198 MEM_VECTOR_CLEAR(self, globals);
199 for (i = 0; i != self->fields_count; ++i) {
200 ir_value_delete(self->fields[i]);
202 MEM_VECTOR_CLEAR(self, fields);
203 MEM_VECTOR_CLEAR(self, filenames);
204 MEM_VECTOR_CLEAR(self, filestrings);
208 bool ir_builder_set_name(ir_builder *self, const char *name)
211 mem_d((void*)self->name);
212 self->name = util_strdup(name);
216 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
219 for (i = 0; i < self->functions_count; ++i) {
220 if (!strcmp(name, self->functions[i]->name))
221 return self->functions[i];
226 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
228 ir_function *fn = ir_builder_get_function(self, name);
233 fn = ir_function_new(self, outtype);
234 if (!ir_function_set_name(fn, name) ||
235 !ir_builder_functions_add(self, fn) )
237 ir_function_delete(fn);
241 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
243 ir_function_delete(fn);
247 fn->value->isconst = true;
248 fn->value->outtype = outtype;
249 fn->value->constval.vfunc = fn;
250 fn->value->context = fn->context;
255 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
258 for (i = 0; i < self->globals_count; ++i) {
259 if (!strcmp(self->globals[i]->name, name))
260 return self->globals[i];
265 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
269 if (name && name[0] != '#')
271 ve = ir_builder_get_global(self, name);
277 ve = ir_value_var(name, store_global, vtype);
278 if (!ir_builder_globals_add(self, ve)) {
285 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
288 for (i = 0; i < self->fields_count; ++i) {
289 if (!strcmp(self->fields[i]->name, name))
290 return self->fields[i];
296 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
298 ir_value *ve = ir_builder_get_field(self, name);
303 ve = ir_value_var(name, store_global, TYPE_FIELD);
304 ve->fieldtype = vtype;
305 if (!ir_builder_fields_add(self, ve)) {
312 /***********************************************************************
316 bool ir_function_naive_phi(ir_function*);
317 void ir_function_enumerate(ir_function*);
318 bool ir_function_calculate_liferanges(ir_function*);
319 bool ir_function_allocate_locals(ir_function*);
321 ir_function* ir_function_new(ir_builder* owner, int outtype)
324 self = (ir_function*)mem_a(sizeof(*self));
329 memset(self, 0, sizeof(*self));
332 if (!ir_function_set_name(self, "<@unnamed>")) {
337 self->context.file = "<@no context>";
338 self->context.line = 0;
339 self->outtype = outtype;
342 MEM_VECTOR_INIT(self, params);
343 MEM_VECTOR_INIT(self, blocks);
344 MEM_VECTOR_INIT(self, values);
345 MEM_VECTOR_INIT(self, locals);
347 self->code_function_def = -1;
348 self->allocated_locals = 0;
353 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
354 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
355 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
356 MEM_VEC_FUNCTIONS(ir_function, int, params)
358 bool ir_function_set_name(ir_function *self, const char *name)
361 mem_d((void*)self->name);
362 self->name = util_strdup(name);
366 void ir_function_delete(ir_function *self)
369 mem_d((void*)self->name);
371 for (i = 0; i != self->blocks_count; ++i)
372 ir_block_delete(self->blocks[i]);
373 MEM_VECTOR_CLEAR(self, blocks);
375 MEM_VECTOR_CLEAR(self, params);
377 for (i = 0; i != self->values_count; ++i)
378 ir_value_delete(self->values[i]);
379 MEM_VECTOR_CLEAR(self, values);
381 for (i = 0; i != self->locals_count; ++i)
382 ir_value_delete(self->locals[i]);
383 MEM_VECTOR_CLEAR(self, locals);
385 /* self->value is deleted by the builder */
390 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
392 return ir_function_values_add(self, v);
395 ir_block* ir_function_create_block(ir_function *self, const char *label)
397 ir_block* bn = ir_block_new(self, label);
398 memcpy(&bn->context, &self->context, sizeof(self->context));
399 if (!ir_function_blocks_add(self, bn)) {
406 bool ir_function_finalize(ir_function *self)
411 if (!ir_function_naive_phi(self))
414 ir_function_enumerate(self);
416 if (!ir_function_calculate_liferanges(self))
419 if (!ir_function_allocate_locals(self))
424 ir_value* ir_function_get_local(ir_function *self, const char *name)
427 for (i = 0; i < self->locals_count; ++i) {
428 if (!strcmp(self->locals[i]->name, name))
429 return self->locals[i];
434 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
439 if (ir_function_get_local(self, name))
444 self->locals_count &&
445 self->locals[self->locals_count-1]->store != store_param) {
446 irerror(self->context, "cannot add parameters after adding locals");
450 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
451 if (!ir_function_locals_add(self, ve)) {
458 /***********************************************************************
462 ir_block* ir_block_new(ir_function* owner, const char *name)
465 self = (ir_block*)mem_a(sizeof(*self));
469 memset(self, 0, sizeof(*self));
472 if (name && !ir_block_set_label(self, name)) {
477 self->context.file = "<@no context>";
478 self->context.line = 0;
480 MEM_VECTOR_INIT(self, instr);
481 MEM_VECTOR_INIT(self, entries);
482 MEM_VECTOR_INIT(self, exits);
485 self->is_return = false;
487 MEM_VECTOR_INIT(self, living);
489 self->generated = false;
493 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
494 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
495 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
496 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
498 void ir_block_delete(ir_block* self)
501 if (self->label) mem_d(self->label);
502 for (i = 0; i != self->instr_count; ++i)
503 ir_instr_delete(self->instr[i]);
504 MEM_VECTOR_CLEAR(self, instr);
505 MEM_VECTOR_CLEAR(self, entries);
506 MEM_VECTOR_CLEAR(self, exits);
507 MEM_VECTOR_CLEAR(self, living);
511 bool ir_block_set_label(ir_block *self, const char *name)
514 mem_d((void*)self->label);
515 self->label = util_strdup(name);
516 return !!self->label;
519 /***********************************************************************
523 ir_instr* ir_instr_new(ir_block* owner, int op)
526 self = (ir_instr*)mem_a(sizeof(*self));
531 self->context.file = "<@no context>";
532 self->context.line = 0;
534 self->_ops[0] = NULL;
535 self->_ops[1] = NULL;
536 self->_ops[2] = NULL;
537 self->bops[0] = NULL;
538 self->bops[1] = NULL;
539 MEM_VECTOR_INIT(self, phi);
540 MEM_VECTOR_INIT(self, params);
545 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
546 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
548 void ir_instr_delete(ir_instr *self)
551 /* The following calls can only delete from
552 * vectors, we still want to delete this instruction
553 * so ignore the return value. Since with the warn_unused_result attribute
554 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
555 * I have to improvise here and use if(foo());
557 for (i = 0; i < self->phi_count; ++i) {
559 if (ir_value_writes_find(self->phi[i].value, self, &idx))
560 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
561 if (ir_value_reads_find(self->phi[i].value, self, &idx))
562 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
564 MEM_VECTOR_CLEAR(self, phi);
565 for (i = 0; i < self->params_count; ++i) {
567 if (ir_value_writes_find(self->params[i], self, &idx))
568 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
569 if (ir_value_reads_find(self->params[i], self, &idx))
570 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
572 MEM_VECTOR_CLEAR(self, params);
573 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
574 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
575 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
579 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
581 if (self->_ops[op]) {
583 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
585 if (!ir_value_writes_remove(self->_ops[op], idx))
588 else if (ir_value_reads_find(self->_ops[op], self, &idx))
590 if (!ir_value_reads_remove(self->_ops[op], idx))
596 if (!ir_value_writes_add(v, self))
599 if (!ir_value_reads_add(v, self))
607 /***********************************************************************
611 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
613 self->code.globaladdr = gaddr;
614 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
615 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
616 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
619 int32_t ir_value_code_addr(const ir_value *self)
621 if (self->store == store_return)
622 return OFS_RETURN + self->code.addroffset;
623 return self->code.globaladdr + self->code.addroffset;
626 ir_value* ir_value_var(const char *name, int storetype, int vtype)
629 self = (ir_value*)mem_a(sizeof(*self));
631 self->fieldtype = TYPE_VOID;
632 self->outtype = TYPE_VOID;
633 self->store = storetype;
634 MEM_VECTOR_INIT(self, reads);
635 MEM_VECTOR_INIT(self, writes);
636 self->isconst = false;
637 self->context.file = "<@no context>";
638 self->context.line = 0;
640 if (name && !ir_value_set_name(self, name)) {
641 irerror(self->context, "out of memory");
646 memset(&self->constval, 0, sizeof(self->constval));
647 memset(&self->code, 0, sizeof(self->code));
649 self->members[0] = NULL;
650 self->members[1] = NULL;
651 self->members[2] = NULL;
652 self->memberof = NULL;
654 MEM_VECTOR_INIT(self, life);
658 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
664 if (self->members[member])
665 return self->members[member];
667 if (self->vtype == TYPE_VECTOR)
669 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
672 m->context = self->context;
674 self->members[member] = m;
675 m->code.addroffset = member;
677 else if (self->vtype == TYPE_FIELD)
679 if (self->fieldtype != TYPE_VECTOR)
681 m = ir_value_var(self->name, self->store, TYPE_FIELD);
684 m->fieldtype = TYPE_FLOAT;
685 m->context = self->context;
687 self->members[member] = m;
688 m->code.addroffset = member;
692 irerror(self->context, "invalid member access on %s", self->name);
700 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
701 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
702 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
704 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
706 ir_value *v = ir_value_var(name, storetype, vtype);
709 if (!ir_function_collect_value(owner, v))
717 void ir_value_delete(ir_value* self)
721 mem_d((void*)self->name);
724 if (self->vtype == TYPE_STRING)
725 mem_d((void*)self->constval.vstring);
727 for (i = 0; i < 3; ++i) {
728 if (self->members[i])
729 ir_value_delete(self->members[i]);
731 MEM_VECTOR_CLEAR(self, reads);
732 MEM_VECTOR_CLEAR(self, writes);
733 MEM_VECTOR_CLEAR(self, life);
737 bool ir_value_set_name(ir_value *self, const char *name)
740 mem_d((void*)self->name);
741 self->name = util_strdup(name);
745 bool ir_value_set_float(ir_value *self, float f)
747 if (self->vtype != TYPE_FLOAT)
749 self->constval.vfloat = f;
750 self->isconst = true;
754 bool ir_value_set_func(ir_value *self, int f)
756 if (self->vtype != TYPE_FUNCTION)
758 self->constval.vint = f;
759 self->isconst = true;
763 bool ir_value_set_vector(ir_value *self, vector v)
765 if (self->vtype != TYPE_VECTOR)
767 self->constval.vvec = v;
768 self->isconst = true;
772 bool ir_value_set_field(ir_value *self, ir_value *fld)
774 if (self->vtype != TYPE_FIELD)
776 self->constval.vpointer = fld;
777 self->isconst = true;
781 static char *ir_strdup(const char *str)
784 /* actually dup empty strings */
785 char *out = mem_a(1);
789 return util_strdup(str);
792 bool ir_value_set_string(ir_value *self, const char *str)
794 if (self->vtype != TYPE_STRING)
796 self->constval.vstring = ir_strdup(str);
797 self->isconst = true;
802 bool ir_value_set_int(ir_value *self, int i)
804 if (self->vtype != TYPE_INTEGER)
806 self->constval.vint = i;
807 self->isconst = true;
812 bool ir_value_lives(ir_value *self, size_t at)
815 for (i = 0; i < self->life_count; ++i)
817 ir_life_entry_t *life = &self->life[i];
818 if (life->start <= at && at <= life->end)
820 if (life->start > at) /* since it's ordered */
826 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
829 if (!ir_value_life_add(self, e)) /* naive... */
831 for (k = self->life_count-1; k > idx; --k)
832 self->life[k] = self->life[k-1];
837 bool ir_value_life_merge(ir_value *self, size_t s)
840 ir_life_entry_t *life = NULL;
841 ir_life_entry_t *before = NULL;
842 ir_life_entry_t new_entry;
844 /* Find the first range >= s */
845 for (i = 0; i < self->life_count; ++i)
848 life = &self->life[i];
852 /* nothing found? append */
853 if (i == self->life_count) {
855 if (life && life->end+1 == s)
857 /* previous life range can be merged in */
861 if (life && life->end >= s)
864 if (!ir_value_life_add(self, e))
865 return false; /* failing */
871 if (before->end + 1 == s &&
872 life->start - 1 == s)
875 before->end = life->end;
876 if (!ir_value_life_remove(self, i))
877 return false; /* failing */
880 if (before->end + 1 == s)
886 /* already contained */
887 if (before->end >= s)
891 if (life->start - 1 == s)
896 /* insert a new entry */
897 new_entry.start = new_entry.end = s;
898 return ir_value_life_insert(self, i, new_entry);
901 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
905 if (!other->life_count)
908 if (!self->life_count) {
909 for (i = 0; i < other->life_count; ++i) {
910 if (!ir_value_life_add(self, other->life[i]))
917 for (i = 0; i < other->life_count; ++i)
919 const ir_life_entry_t *life = &other->life[i];
922 ir_life_entry_t *entry = &self->life[myi];
924 if (life->end+1 < entry->start)
926 /* adding an interval before entry */
927 if (!ir_value_life_insert(self, myi, *life))
933 if (life->start < entry->start &&
934 life->end+1 >= entry->start)
936 /* starts earlier and overlaps */
937 entry->start = life->start;
940 if (life->end > entry->end &&
941 life->start <= entry->end+1)
943 /* ends later and overlaps */
944 entry->end = life->end;
947 /* see if our change combines it with the next ranges */
948 while (myi+1 < self->life_count &&
949 entry->end+1 >= self->life[1+myi].start)
951 /* overlaps with (myi+1) */
952 if (entry->end < self->life[1+myi].end)
953 entry->end = self->life[1+myi].end;
954 if (!ir_value_life_remove(self, myi+1))
956 entry = &self->life[myi];
959 /* see if we're after the entry */
960 if (life->start > entry->end)
963 /* append if we're at the end */
964 if (myi >= self->life_count) {
965 if (!ir_value_life_add(self, *life))
969 /* otherweise check the next range */
978 bool ir_values_overlap(const ir_value *a, const ir_value *b)
980 /* For any life entry in A see if it overlaps with
981 * any life entry in B.
982 * Note that the life entries are orderes, so we can make a
983 * more efficient algorithm there than naively translating the
987 ir_life_entry_t *la, *lb, *enda, *endb;
989 /* first of all, if either has no life range, they cannot clash */
990 if (!a->life_count || !b->life_count)
995 enda = la + a->life_count;
996 endb = lb + b->life_count;
999 /* check if the entries overlap, for that,
1000 * both must start before the other one ends.
1002 if (la->start < lb->end &&
1003 lb->start < la->end)
1008 /* entries are ordered
1009 * one entry is earlier than the other
1010 * that earlier entry will be moved forward
1012 if (la->start < lb->start)
1014 /* order: A B, move A forward
1015 * check if we hit the end with A
1020 else /* if (lb->start < la->start) actually <= */
1022 /* order: B A, move B forward
1023 * check if we hit the end with B
1032 /***********************************************************************
1036 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1038 ir_instr *in = ir_instr_new(self, op);
1042 if (target->store == store_value &&
1043 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1045 irerror(self->context, "cannot store to an SSA value");
1046 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1047 irerror(self->context, "instruction: %s", asm_instr[op].m);
1051 if (!ir_instr_op(in, 0, target, true) ||
1052 !ir_instr_op(in, 1, what, false) ||
1053 !ir_block_instr_add(self, in) )
1060 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1064 if (target->vtype == TYPE_VARIANT)
1065 vtype = what->vtype;
1067 vtype = target->vtype;
1070 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1071 op = INSTR_CONV_ITOF;
1072 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1073 op = INSTR_CONV_FTOI;
1075 op = type_store_instr[vtype];
1077 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1078 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1082 return ir_block_create_store_op(self, op, target, what);
1085 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1090 if (target->vtype != TYPE_POINTER)
1093 /* storing using pointer - target is a pointer, type must be
1094 * inferred from source
1096 vtype = what->vtype;
1098 op = type_storep_instr[vtype];
1099 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1100 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1101 op = INSTR_STOREP_V;
1104 return ir_block_create_store_op(self, op, target, what);
1107 bool ir_block_create_return(ir_block *self, ir_value *v)
1111 irerror(self->context, "block already ended (%s)", self->label);
1115 self->is_return = true;
1116 in = ir_instr_new(self, INSTR_RETURN);
1120 if (v && !ir_instr_op(in, 0, v, false))
1123 if (!ir_block_instr_add(self, in))
1128 bool ir_block_create_if(ir_block *self, ir_value *v,
1129 ir_block *ontrue, ir_block *onfalse)
1133 irerror(self->context, "block already ended (%s)", self->label);
1137 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1138 in = ir_instr_new(self, VINSTR_COND);
1142 if (!ir_instr_op(in, 0, v, false)) {
1143 ir_instr_delete(in);
1147 in->bops[0] = ontrue;
1148 in->bops[1] = onfalse;
1150 if (!ir_block_instr_add(self, in))
1153 if (!ir_block_exits_add(self, ontrue) ||
1154 !ir_block_exits_add(self, onfalse) ||
1155 !ir_block_entries_add(ontrue, self) ||
1156 !ir_block_entries_add(onfalse, self) )
1163 bool ir_block_create_jump(ir_block *self, ir_block *to)
1167 irerror(self->context, "block already ended (%s)", self->label);
1171 in = ir_instr_new(self, VINSTR_JUMP);
1176 if (!ir_block_instr_add(self, in))
1179 if (!ir_block_exits_add(self, to) ||
1180 !ir_block_entries_add(to, self) )
1187 bool ir_block_create_goto(ir_block *self, ir_block *to)
1191 irerror(self->context, "block already ended (%s)", self->label);
1195 in = ir_instr_new(self, INSTR_GOTO);
1200 if (!ir_block_instr_add(self, in))
1203 if (!ir_block_exits_add(self, to) ||
1204 !ir_block_entries_add(to, self) )
1211 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1215 in = ir_instr_new(self, VINSTR_PHI);
1218 out = ir_value_out(self->owner, label, store_value, ot);
1220 ir_instr_delete(in);
1223 if (!ir_instr_op(in, 0, out, true)) {
1224 ir_instr_delete(in);
1225 ir_value_delete(out);
1228 if (!ir_block_instr_add(self, in)) {
1229 ir_instr_delete(in);
1230 ir_value_delete(out);
1236 ir_value* ir_phi_value(ir_instr *self)
1238 return self->_ops[0];
1241 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1245 if (!ir_block_entries_find(self->owner, b, NULL)) {
1246 /* Must not be possible to cause this, otherwise the AST
1247 * is doing something wrong.
1249 irerror(self->context, "Invalid entry block for PHI");
1255 if (!ir_value_reads_add(v, self))
1257 return ir_instr_phi_add(self, pe);
1260 /* call related code */
1261 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1265 in = ir_instr_new(self, INSTR_CALL0);
1268 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1270 ir_instr_delete(in);
1273 if (!ir_instr_op(in, 0, out, true) ||
1274 !ir_instr_op(in, 1, func, false) ||
1275 !ir_block_instr_add(self, in))
1277 ir_instr_delete(in);
1278 ir_value_delete(out);
1284 ir_value* ir_call_value(ir_instr *self)
1286 return self->_ops[0];
1289 bool ir_call_param(ir_instr* self, ir_value *v)
1291 if (!ir_instr_params_add(self, v))
1293 if (!ir_value_reads_add(v, self)) {
1294 if (!ir_instr_params_remove(self, self->params_count-1))
1295 GMQCC_SUPPRESS_EMPTY_BODY;
1301 /* binary op related code */
1303 ir_value* ir_block_create_binop(ir_block *self,
1304 const char *label, int opcode,
1305 ir_value *left, ir_value *right)
1327 case INSTR_SUB_S: /* -- offset of string as float */
1332 case INSTR_BITOR_IF:
1333 case INSTR_BITOR_FI:
1334 case INSTR_BITAND_FI:
1335 case INSTR_BITAND_IF:
1350 case INSTR_BITAND_I:
1353 case INSTR_RSHIFT_I:
1354 case INSTR_LSHIFT_I:
1376 /* boolean operations result in floats */
1377 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1379 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1382 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1387 if (ot == TYPE_VOID) {
1388 /* The AST or parser were supposed to check this! */
1392 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1395 ir_value* ir_block_create_unary(ir_block *self,
1396 const char *label, int opcode,
1399 int ot = TYPE_FLOAT;
1411 /* QC doesn't have other unary operations. We expect extensions to fill
1412 * the above list, otherwise we assume out-type = in-type, eg for an
1416 ot = operand->vtype;
1419 if (ot == TYPE_VOID) {
1420 /* The AST or parser were supposed to check this! */
1424 /* let's use the general instruction creator and pass NULL for OPB */
1425 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1428 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1429 int op, ir_value *a, ir_value *b, int outype)
1434 out = ir_value_out(self->owner, label, store_value, outype);
1438 instr = ir_instr_new(self, op);
1440 ir_value_delete(out);
1444 if (!ir_instr_op(instr, 0, out, true) ||
1445 !ir_instr_op(instr, 1, a, false) ||
1446 !ir_instr_op(instr, 2, b, false) )
1451 if (!ir_block_instr_add(self, instr))
1456 ir_instr_delete(instr);
1457 ir_value_delete(out);
1461 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1465 /* Support for various pointer types todo if so desired */
1466 if (ent->vtype != TYPE_ENTITY)
1469 if (field->vtype != TYPE_FIELD)
1472 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1473 v->fieldtype = field->fieldtype;
1477 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1480 if (ent->vtype != TYPE_ENTITY)
1483 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1484 if (field->vtype != TYPE_FIELD)
1489 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1490 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1491 case TYPE_STRING: op = INSTR_LOAD_S; break;
1492 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1493 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1494 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1496 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1497 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1503 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1506 ir_value* ir_block_create_add(ir_block *self,
1508 ir_value *left, ir_value *right)
1511 int l = left->vtype;
1512 int r = right->vtype;
1531 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1533 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1539 return ir_block_create_binop(self, label, op, left, right);
1542 ir_value* ir_block_create_sub(ir_block *self,
1544 ir_value *left, ir_value *right)
1547 int l = left->vtype;
1548 int r = right->vtype;
1568 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1570 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1576 return ir_block_create_binop(self, label, op, left, right);
1579 ir_value* ir_block_create_mul(ir_block *self,
1581 ir_value *left, ir_value *right)
1584 int l = left->vtype;
1585 int r = right->vtype;
1604 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1606 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1609 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1611 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1613 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1615 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1621 return ir_block_create_binop(self, label, op, left, right);
1624 ir_value* ir_block_create_div(ir_block *self,
1626 ir_value *left, ir_value *right)
1629 int l = left->vtype;
1630 int r = right->vtype;
1647 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1649 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1651 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1657 return ir_block_create_binop(self, label, op, left, right);
1660 /* PHI resolving breaks the SSA, and must thus be the last
1661 * step before life-range calculation.
1664 static bool ir_block_naive_phi(ir_block *self);
1665 bool ir_function_naive_phi(ir_function *self)
1669 for (i = 0; i < self->blocks_count; ++i)
1671 if (!ir_block_naive_phi(self->blocks[i]))
1677 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1682 /* create a store */
1683 if (!ir_block_create_store(block, old, what))
1686 /* we now move it up */
1687 instr = block->instr[block->instr_count-1];
1688 for (i = block->instr_count; i > iid; --i)
1689 block->instr[i] = block->instr[i-1];
1690 block->instr[i] = instr;
1695 static bool ir_block_naive_phi(ir_block *self)
1698 /* FIXME: optionally, create_phi can add the phis
1699 * to a list so we don't need to loop through blocks
1700 * - anyway: "don't optimize YET"
1702 for (i = 0; i < self->instr_count; ++i)
1704 ir_instr *instr = self->instr[i];
1705 if (instr->opcode != VINSTR_PHI)
1708 if (!ir_block_instr_remove(self, i))
1710 --i; /* NOTE: i+1 below */
1712 for (p = 0; p < instr->phi_count; ++p)
1714 ir_value *v = instr->phi[p].value;
1715 for (w = 0; w < v->writes_count; ++w) {
1718 if (!v->writes[w]->_ops[0])
1721 /* When the write was to a global, we have to emit a mov */
1722 old = v->writes[w]->_ops[0];
1724 /* The original instruction now writes to the PHI target local */
1725 if (v->writes[w]->_ops[0] == v)
1726 v->writes[w]->_ops[0] = instr->_ops[0];
1728 if (old->store != store_value && old->store != store_local && old->store != store_param)
1730 /* If it originally wrote to a global we need to store the value
1733 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1735 if (i+1 < self->instr_count)
1736 instr = self->instr[i+1];
1739 /* In case I forget and access instr later, it'll be NULL
1740 * when it's a problem, to make sure we crash, rather than accessing
1746 /* If it didn't, we can replace all reads by the phi target now. */
1748 for (r = 0; r < old->reads_count; ++r)
1751 ir_instr *ri = old->reads[r];
1752 for (op = 0; op < ri->phi_count; ++op) {
1753 if (ri->phi[op].value == old)
1754 ri->phi[op].value = v;
1756 for (op = 0; op < 3; ++op) {
1757 if (ri->_ops[op] == old)
1764 ir_instr_delete(instr);
1769 /***********************************************************************
1770 *IR Temp allocation code
1771 * Propagating value life ranges by walking through the function backwards
1772 * until no more changes are made.
1773 * In theory this should happen once more than once for every nested loop
1775 * Though this implementation might run an additional time for if nests.
1784 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1786 /* Enumerate instructions used by value's life-ranges
1788 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1792 for (i = 0; i < self->instr_count; ++i)
1794 self->instr[i]->eid = eid++;
1799 /* Enumerate blocks and instructions.
1800 * The block-enumeration is unordered!
1801 * We do not really use the block enumreation, however
1802 * the instruction enumeration is important for life-ranges.
1804 void ir_function_enumerate(ir_function *self)
1807 size_t instruction_id = 0;
1808 for (i = 0; i < self->blocks_count; ++i)
1810 self->blocks[i]->eid = i;
1811 self->blocks[i]->run_id = 0;
1812 ir_block_enumerate(self->blocks[i], &instruction_id);
1816 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1817 bool ir_function_calculate_liferanges(ir_function *self)
1825 for (i = 0; i != self->blocks_count; ++i)
1827 if (self->blocks[i]->is_return)
1829 self->blocks[i]->living_count = 0;
1830 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1835 if (self->blocks_count) {
1836 ir_block *block = self->blocks[0];
1837 for (i = 0; i < block->living_count; ++i) {
1838 ir_value *v = block->living[i];
1839 if (v->memberof || v->store != store_local)
1841 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1842 "variable `%s` may be used uninitialized in this function", v->name))
1851 /* Local-value allocator
1852 * After finishing creating the liferange of all values used in a function
1853 * we can allocate their global-positions.
1854 * This is the counterpart to register-allocation in register machines.
1857 MEM_VECTOR_MAKE(ir_value*, locals);
1858 MEM_VECTOR_MAKE(size_t, sizes);
1859 MEM_VECTOR_MAKE(size_t, positions);
1860 } function_allocator;
1861 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1862 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1863 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1865 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1868 size_t vsize = type_sizeof[var->vtype];
1870 slot = ir_value_var("reg", store_global, var->vtype);
1874 if (!ir_value_life_merge_into(slot, var))
1877 if (!function_allocator_locals_add(alloc, slot))
1880 if (!function_allocator_sizes_add(alloc, vsize))
1886 ir_value_delete(slot);
1890 bool ir_function_allocate_locals(ir_function *self)
1899 function_allocator alloc;
1901 if (!self->locals_count && !self->values_count)
1904 MEM_VECTOR_INIT(&alloc, locals);
1905 MEM_VECTOR_INIT(&alloc, sizes);
1906 MEM_VECTOR_INIT(&alloc, positions);
1908 for (i = 0; i < self->locals_count; ++i)
1910 if (!function_allocator_alloc(&alloc, self->locals[i]))
1914 /* Allocate a slot for any value that still exists */
1915 for (i = 0; i < self->values_count; ++i)
1917 v = self->values[i];
1922 for (a = 0; a < alloc.locals_count; ++a)
1924 slot = alloc.locals[a];
1926 if (ir_values_overlap(v, slot))
1929 if (!ir_value_life_merge_into(slot, v))
1932 /* adjust size for this slot */
1933 if (alloc.sizes[a] < type_sizeof[v->vtype])
1934 alloc.sizes[a] = type_sizeof[v->vtype];
1936 self->values[i]->code.local = a;
1939 if (a >= alloc.locals_count) {
1940 self->values[i]->code.local = alloc.locals_count;
1941 if (!function_allocator_alloc(&alloc, v))
1950 /* Adjust slot positions based on sizes */
1951 if (!function_allocator_positions_add(&alloc, 0))
1954 if (alloc.sizes_count)
1955 pos = alloc.positions[0] + alloc.sizes[0];
1958 for (i = 1; i < alloc.sizes_count; ++i)
1960 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1961 if (!function_allocator_positions_add(&alloc, pos))
1965 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1967 /* Take over the actual slot positions */
1968 for (i = 0; i < self->values_count; ++i) {
1969 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1977 for (i = 0; i < alloc.locals_count; ++i)
1978 ir_value_delete(alloc.locals[i]);
1979 MEM_VECTOR_CLEAR(&alloc, locals);
1980 MEM_VECTOR_CLEAR(&alloc, sizes);
1981 MEM_VECTOR_CLEAR(&alloc, positions);
1985 /* Get information about which operand
1986 * is read from, or written to.
1988 static void ir_op_read_write(int op, size_t *read, size_t *write)
2008 case INSTR_STOREP_F:
2009 case INSTR_STOREP_V:
2010 case INSTR_STOREP_S:
2011 case INSTR_STOREP_ENT:
2012 case INSTR_STOREP_FLD:
2013 case INSTR_STOREP_FNC:
2024 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2027 bool changed = false;
2029 for (i = 0; i != self->living_count; ++i)
2031 tempbool = ir_value_life_merge(self->living[i], eid);
2034 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2036 changed = changed || tempbool;
2041 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2044 /* values which have been read in a previous iteration are now
2045 * in the "living" array even if the previous block doesn't use them.
2046 * So we have to remove whatever does not exist in the previous block.
2047 * They will be re-added on-read, but the liferange merge won't cause
2050 for (i = 0; i < self->living_count; ++i)
2052 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2053 if (!ir_block_living_remove(self, i))
2059 /* Whatever the previous block still has in its living set
2060 * must now be added to ours as well.
2062 for (i = 0; i < prev->living_count; ++i)
2064 if (ir_block_living_find(self, prev->living[i], NULL))
2066 if (!ir_block_living_add(self, prev->living[i]))
2069 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2075 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2081 /* bitmasks which operands are read from or written to */
2083 char dbg_ind[16] = { '#', '0' };
2088 if (!ir_block_life_prop_previous(self, prev, changed))
2092 i = self->instr_count;
2095 instr = self->instr[i];
2097 /* PHI operands are always read operands */
2098 for (p = 0; p < instr->phi_count; ++p)
2100 value = instr->phi[p].value;
2101 if (value->memberof)
2102 value = value->memberof;
2103 if (!ir_block_living_find(self, value, NULL) &&
2104 !ir_block_living_add(self, value))
2110 /* call params are read operands too */
2111 for (p = 0; p < instr->params_count; ++p)
2113 value = instr->params[p];
2114 if (value->memberof)
2115 value = value->memberof;
2116 if (!ir_block_living_find(self, value, NULL) &&
2117 !ir_block_living_add(self, value))
2123 /* See which operands are read and write operands */
2124 ir_op_read_write(instr->opcode, &read, &write);
2126 if (instr->opcode == INSTR_MUL_VF)
2128 /* the float source will get an additional lifetime */
2129 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2130 *changed = *changed || tempbool;
2132 else if (instr->opcode == INSTR_MUL_FV)
2134 /* the float source will get an additional lifetime */
2135 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2136 *changed = *changed || tempbool;
2139 /* Go through the 3 main operands */
2140 for (o = 0; o < 3; ++o)
2142 if (!instr->_ops[o]) /* no such operand */
2145 value = instr->_ops[o];
2146 if (value->memberof)
2147 value = value->memberof;
2149 /* We only care about locals */
2150 /* we also calculate parameter liferanges so that locals
2151 * can take up parameter slots */
2152 if (value->store != store_value &&
2153 value->store != store_local &&
2154 value->store != store_param)
2160 if (!ir_block_living_find(self, value, NULL) &&
2161 !ir_block_living_add(self, value))
2167 /* write operands */
2168 /* When we write to a local, we consider it "dead" for the
2169 * remaining upper part of the function, since in SSA a value
2170 * can only be written once (== created)
2175 bool in_living = ir_block_living_find(self, value, &idx);
2178 /* If the value isn't alive it hasn't been read before... */
2179 /* TODO: See if the warning can be emitted during parsing or AST processing
2180 * otherwise have warning printed here.
2181 * IF printing a warning here: include filecontext_t,
2182 * and make sure it's only printed once
2183 * since this function is run multiple times.
2185 /* For now: debug info: */
2186 /* fprintf(stderr, "Value only written %s\n", value->name); */
2187 tempbool = ir_value_life_merge(value, instr->eid);
2188 *changed = *changed || tempbool;
2190 ir_instr_dump(instr, dbg_ind, printf);
2194 /* since 'living' won't contain it
2195 * anymore, merge the value, since
2198 tempbool = ir_value_life_merge(value, instr->eid);
2201 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2203 *changed = *changed || tempbool;
2205 if (!ir_block_living_remove(self, idx))
2211 tempbool = ir_block_living_add_instr(self, instr->eid);
2212 /*fprintf(stderr, "living added values\n");*/
2213 *changed = *changed || tempbool;
2217 if (self->run_id == self->owner->run_id)
2220 self->run_id = self->owner->run_id;
2222 for (i = 0; i < self->entries_count; ++i)
2224 ir_block *entry = self->entries[i];
2225 ir_block_life_propagate(entry, self, changed);
2231 /***********************************************************************
2234 * Since the IR has the convention of putting 'write' operands
2235 * at the beginning, we have to rotate the operands of instructions
2236 * properly in order to generate valid QCVM code.
2238 * Having destinations at a fixed position is more convenient. In QC
2239 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2240 * read from from OPA, and store to OPB rather than OPC. Which is
2241 * partially the reason why the implementation of these instructions
2242 * in darkplaces has been delayed for so long.
2244 * Breaking conventions is annoying...
2246 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2248 static bool gen_global_field(ir_value *global)
2250 if (global->isconst)
2252 ir_value *fld = global->constval.vpointer;
2254 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2258 /* Now, in this case, a relocation would be impossible to code
2259 * since it looks like this:
2260 * .vector v = origin; <- parse error, wtf is 'origin'?
2263 * But we will need a general relocation support later anyway
2264 * for functions... might as well support that here.
2266 if (!fld->code.globaladdr) {
2267 irerror(global->context, "FIXME: Relocation support");
2271 /* copy the field's value */
2272 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2273 if (global->fieldtype == TYPE_VECTOR) {
2274 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2275 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2280 ir_value_code_setaddr(global, code_globals_add(0));
2281 if (global->fieldtype == TYPE_VECTOR) {
2282 code_globals_add(0);
2283 code_globals_add(0);
2286 if (global->code.globaladdr < 0)
2291 static bool gen_global_pointer(ir_value *global)
2293 if (global->isconst)
2295 ir_value *target = global->constval.vpointer;
2297 irerror(global->context, "Invalid pointer constant: %s", global->name);
2298 /* NULL pointers are pointing to the NULL constant, which also
2299 * sits at address 0, but still has an ir_value for itself.
2304 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2305 * void() foo; <- proto
2306 * void() *fooptr = &foo;
2307 * void() foo = { code }
2309 if (!target->code.globaladdr) {
2310 /* FIXME: Check for the constant nullptr ir_value!
2311 * because then code.globaladdr being 0 is valid.
2313 irerror(global->context, "FIXME: Relocation support");
2317 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2321 ir_value_code_setaddr(global, code_globals_add(0));
2323 if (global->code.globaladdr < 0)
2328 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2330 prog_section_statement stmt;
2339 block->generated = true;
2340 block->code_start = code_statements_elements;
2341 for (i = 0; i < block->instr_count; ++i)
2343 instr = block->instr[i];
2345 if (instr->opcode == VINSTR_PHI) {
2346 irerror(block->context, "cannot generate virtual instruction (phi)");
2350 if (instr->opcode == VINSTR_JUMP) {
2351 target = instr->bops[0];
2352 /* for uncoditional jumps, if the target hasn't been generated
2353 * yet, we generate them right here.
2355 if (!target->generated) {
2360 /* otherwise we generate a jump instruction */
2361 stmt.opcode = INSTR_GOTO;
2362 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2365 if (code_statements_add(stmt) < 0)
2368 /* no further instructions can be in this block */
2372 if (instr->opcode == VINSTR_COND) {
2373 ontrue = instr->bops[0];
2374 onfalse = instr->bops[1];
2375 /* TODO: have the AST signal which block should
2376 * come first: eg. optimize IFs without ELSE...
2379 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2383 if (ontrue->generated) {
2384 stmt.opcode = INSTR_IF;
2385 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2386 if (code_statements_add(stmt) < 0)
2389 if (onfalse->generated) {
2390 stmt.opcode = INSTR_IFNOT;
2391 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2392 if (code_statements_add(stmt) < 0)
2395 if (!ontrue->generated) {
2396 if (onfalse->generated) {
2401 if (!onfalse->generated) {
2402 if (ontrue->generated) {
2407 /* neither ontrue nor onfalse exist */
2408 stmt.opcode = INSTR_IFNOT;
2409 stidx = code_statements_elements;
2410 if (code_statements_add(stmt) < 0)
2412 /* on false we jump, so add ontrue-path */
2413 if (!gen_blocks_recursive(func, ontrue))
2415 /* fixup the jump address */
2416 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2417 /* generate onfalse path */
2418 if (onfalse->generated) {
2419 /* fixup the jump address */
2420 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2421 /* may have been generated in the previous recursive call */
2422 stmt.opcode = INSTR_GOTO;
2423 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2426 return (code_statements_add(stmt) >= 0);
2428 /* if not, generate now */
2433 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2434 /* Trivial call translation:
2435 * copy all params to OFS_PARM*
2436 * if the output's storetype is not store_return,
2437 * add append a STORE instruction!
2439 * NOTES on how to do it better without much trouble:
2440 * -) The liferanges!
2441 * Simply check the liferange of all parameters for
2442 * other CALLs. For each param with no CALL in its
2443 * liferange, we can store it in an OFS_PARM at
2444 * generation already. This would even include later
2445 * reuse.... probably... :)
2450 for (p = 0; p < instr->params_count; ++p)
2452 ir_value *param = instr->params[p];
2454 stmt.opcode = INSTR_STORE_F;
2457 stmt.opcode = type_store_instr[param->vtype];
2458 stmt.o1.u1 = ir_value_code_addr(param);
2459 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2460 if (code_statements_add(stmt) < 0)
2463 stmt.opcode = INSTR_CALL0 + instr->params_count;
2464 if (stmt.opcode > INSTR_CALL8)
2465 stmt.opcode = INSTR_CALL8;
2466 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2469 if (code_statements_add(stmt) < 0)
2472 retvalue = instr->_ops[0];
2473 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2475 /* not to be kept in OFS_RETURN */
2476 stmt.opcode = type_store_instr[retvalue->vtype];
2477 stmt.o1.u1 = OFS_RETURN;
2478 stmt.o2.u1 = ir_value_code_addr(retvalue);
2480 if (code_statements_add(stmt) < 0)
2486 if (instr->opcode == INSTR_STATE) {
2487 irerror(block->context, "TODO: state instruction");
2491 stmt.opcode = instr->opcode;
2496 /* This is the general order of operands */
2498 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2501 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2504 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2506 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2508 stmt.o1.u1 = stmt.o3.u1;
2511 else if ((stmt.opcode >= INSTR_STORE_F &&
2512 stmt.opcode <= INSTR_STORE_FNC) ||
2513 (stmt.opcode >= INSTR_STOREP_F &&
2514 stmt.opcode <= INSTR_STOREP_FNC))
2516 /* 2-operand instructions with A -> B */
2517 stmt.o2.u1 = stmt.o3.u1;
2521 if (code_statements_add(stmt) < 0)
2527 static bool gen_function_code(ir_function *self)
2530 prog_section_statement stmt;
2532 /* Starting from entry point, we generate blocks "as they come"
2533 * for now. Dead blocks will not be translated obviously.
2535 if (!self->blocks_count) {
2536 irerror(self->context, "Function '%s' declared without body.", self->name);
2540 block = self->blocks[0];
2541 if (block->generated)
2544 if (!gen_blocks_recursive(self, block)) {
2545 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2549 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2550 stmt.opcode = AINSTR_END;
2554 if (code_statements_add(stmt) < 0)
2559 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2561 /* NOTE: filename pointers are copied, we never strdup them,
2562 * thus we can use pointer-comparison to find the string.
2567 for (i = 0; i < ir->filenames_count; ++i) {
2568 if (ir->filenames[i] == filename)
2569 return ir->filestrings[i];
2572 str = code_genstring(filename);
2573 if (!ir_builder_filenames_add(ir, filename))
2575 if (!ir_builder_filestrings_add(ir, str))
2576 ir->filenames_count--;
2580 static bool gen_global_function(ir_builder *ir, ir_value *global)
2582 prog_section_function fun;
2586 size_t local_var_end;
2588 if (!global->isconst || (!global->constval.vfunc))
2590 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2594 irfun = global->constval.vfunc;
2596 fun.name = global->code.name;
2597 fun.file = ir_builder_filestring(ir, global->context.file);
2598 fun.profile = 0; /* always 0 */
2599 fun.nargs = irfun->params_count;
2601 for (i = 0;i < 8; ++i) {
2605 fun.argsize[i] = type_sizeof[irfun->params[i]];
2608 fun.firstlocal = code_globals_elements;
2610 local_var_end = fun.firstlocal;
2611 for (i = 0; i < irfun->locals_count; ++i) {
2612 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2613 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2617 if (irfun->locals_count) {
2618 ir_value *last = irfun->locals[irfun->locals_count-1];
2619 local_var_end = last->code.globaladdr;
2620 local_var_end += type_sizeof[last->vtype];
2622 for (i = 0; i < irfun->values_count; ++i)
2624 /* generate code.globaladdr for ssa values */
2625 ir_value *v = irfun->values[i];
2626 ir_value_code_setaddr(v, local_var_end + v->code.local);
2628 for (i = 0; i < irfun->allocated_locals; ++i) {
2629 /* fill the locals with zeros */
2630 code_globals_add(0);
2633 fun.locals = code_globals_elements - fun.firstlocal;
2636 fun.entry = irfun->builtin;
2638 irfun->code_function_def = code_functions_elements;
2639 fun.entry = code_statements_elements;
2642 return (code_functions_add(fun) >= 0);
2645 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2647 prog_section_function *fundef;
2650 irfun = global->constval.vfunc;
2652 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2653 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2654 /* this was a function pointer, don't generate code for those */
2661 if (irfun->code_function_def < 0) {
2662 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2665 fundef = &code_functions_data[irfun->code_function_def];
2667 fundef->entry = code_statements_elements;
2668 if (!gen_function_code(irfun)) {
2669 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2675 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
2679 prog_section_def def;
2681 def.type = global->vtype;
2682 def.offset = code_globals_elements;
2685 if (global->name[0] == '#') {
2686 if (!self->str_immediate)
2687 self->str_immediate = code_genstring("IMMEDIATE");
2688 def.name = global->code.name = self->str_immediate;
2691 def.name = global->code.name = code_genstring(global->name);
2696 switch (global->vtype)
2699 if (!strcmp(global->name, "end_sys_globals")) {
2700 /* TODO: remember this point... all the defs before this one
2701 * should be checksummed and added to progdefs.h when we generate it.
2704 else if (!strcmp(global->name, "end_sys_fields")) {
2705 /* TODO: same as above but for entity-fields rather than globsl
2709 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
2711 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
2712 * the system fields actually go? Though the engine knows this anyway...
2713 * Maybe this could be an -foption
2714 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
2716 ir_value_code_setaddr(global, code_globals_add(0));
2718 if (code_defs_add(def) < 0)
2722 if (code_defs_add(def) < 0)
2724 return gen_global_pointer(global);
2726 if (code_defs_add(def) < 0)
2728 return gen_global_field(global);
2733 if (global->isconst) {
2734 iptr = (int32_t*)&global->constval.vfloat;
2735 ir_value_code_setaddr(global, code_globals_add(*iptr));
2737 ir_value_code_setaddr(global, code_globals_add(0));
2739 def.type |= DEF_SAVEGLOBAL;
2741 if (code_defs_add(def) < 0)
2744 return global->code.globaladdr >= 0;
2748 if (global->isconst)
2749 ir_value_code_setaddr(global, code_globals_add(code_genstring(global->constval.vstring)));
2751 ir_value_code_setaddr(global, code_globals_add(0));
2753 def.type |= DEF_SAVEGLOBAL;
2755 if (code_defs_add(def) < 0)
2757 return global->code.globaladdr >= 0;
2762 if (global->isconst) {
2763 iptr = (int32_t*)&global->constval.vvec;
2764 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2765 if (global->code.globaladdr < 0)
2767 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2769 if (code_globals_add(iptr[d]) < 0)
2773 ir_value_code_setaddr(global, code_globals_add(0));
2774 if (global->code.globaladdr < 0)
2776 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2778 if (code_globals_add(0) < 0)
2782 def.type |= DEF_SAVEGLOBAL;
2785 if (code_defs_add(def) < 0)
2787 return global->code.globaladdr >= 0;
2790 if (!global->isconst) {
2791 ir_value_code_setaddr(global, code_globals_add(0));
2792 if (global->code.globaladdr < 0)
2795 ir_value_code_setaddr(global, code_globals_elements);
2796 code_globals_add(code_functions_elements);
2797 if (!gen_global_function(self, global))
2800 def.type |= DEF_SAVEGLOBAL;
2802 if (code_defs_add(def) < 0)
2806 /* assume biggest type */
2807 ir_value_code_setaddr(global, code_globals_add(0));
2808 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2809 code_globals_add(0);
2812 /* refuse to create 'void' type or any other fancy business. */
2813 irerror(global->context, "Invalid type for global variable `%s`: %s",
2814 global->name, type_name[global->vtype]);
2819 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2821 prog_section_def def;
2822 prog_section_field fld;
2824 def.type = field->vtype;
2825 def.offset = code_globals_elements;
2827 /* create a global named the same as the field */
2828 if (opts_standard == COMPILER_GMQCC) {
2829 /* in our standard, the global gets a dot prefix */
2830 size_t len = strlen(field->name);
2833 /* we really don't want to have to allocate this, and 1024
2834 * bytes is more than enough for a variable/field name
2836 if (len+2 >= sizeof(name)) {
2837 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2842 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2845 def.name = code_genstring(name);
2846 fld.name = def.name + 1; /* we reuse that string table entry */
2848 /* in plain QC, there cannot be a global with the same name,
2849 * and so we also name the global the same.
2850 * FIXME: fteqcc should create a global as well
2851 * check if it actually uses the same name. Probably does
2853 def.name = code_genstring(field->name);
2854 fld.name = def.name;
2857 field->code.name = def.name;
2859 if (code_defs_add(def) < 0)
2862 fld.type = field->fieldtype;
2864 if (fld.type == TYPE_VOID) {
2865 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2869 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2871 if (code_fields_add(fld) < 0)
2874 ir_value_code_setaddr(field, code_globals_elements);
2875 if (!code_globals_add(fld.offset))
2877 if (fld.type == TYPE_VECTOR) {
2878 if (!code_globals_add(fld.offset+1))
2880 if (!code_globals_add(fld.offset+2))
2884 return field->code.globaladdr >= 0;
2887 bool ir_builder_generate(ir_builder *self, const char *filename)
2889 prog_section_statement stmt;
2894 for (i = 0; i < self->globals_count; ++i)
2896 if (!ir_builder_gen_global(self, self->globals[i], false)) {
2901 for (i = 0; i < self->fields_count; ++i)
2903 if (!ir_builder_gen_field(self, self->fields[i])) {
2908 /* generate function code */
2909 for (i = 0; i < self->globals_count; ++i)
2911 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2912 if (!gen_global_function_code(self, self->globals[i])) {
2918 /* DP errors if the last instruction is not an INSTR_DONE
2919 * and for debugging purposes we add an additional AINSTR_END
2920 * to the end of functions, so here it goes:
2922 stmt.opcode = INSTR_DONE;
2926 if (code_statements_add(stmt) < 0)
2929 printf("writing '%s'...\n", filename);
2930 return code_write(filename);
2933 /***********************************************************************
2934 *IR DEBUG Dump functions...
2937 #define IND_BUFSZ 1024
2940 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2942 # define strncat strncat
2945 const char *qc_opname(int op)
2947 if (op < 0) return "<INVALID>";
2948 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2949 return asm_instr[op].m;
2951 case VINSTR_PHI: return "PHI";
2952 case VINSTR_JUMP: return "JUMP";
2953 case VINSTR_COND: return "COND";
2954 default: return "<UNK>";
2958 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2961 char indent[IND_BUFSZ];
2965 oprintf("module %s\n", b->name);
2966 for (i = 0; i < b->globals_count; ++i)
2969 if (b->globals[i]->isconst)
2970 oprintf("%s = ", b->globals[i]->name);
2971 ir_value_dump(b->globals[i], oprintf);
2974 for (i = 0; i < b->functions_count; ++i)
2975 ir_function_dump(b->functions[i], indent, oprintf);
2976 oprintf("endmodule %s\n", b->name);
2979 void ir_function_dump(ir_function *f, char *ind,
2980 int (*oprintf)(const char*, ...))
2983 if (f->builtin != 0) {
2984 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2987 oprintf("%sfunction %s\n", ind, f->name);
2988 strncat(ind, "\t", IND_BUFSZ);
2989 if (f->locals_count)
2991 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2992 for (i = 0; i < f->locals_count; ++i) {
2993 oprintf("%s\t", ind);
2994 ir_value_dump(f->locals[i], oprintf);
2998 oprintf("%sliferanges:\n", ind);
2999 for (i = 0; i < f->locals_count; ++i) {
3001 ir_value *v = f->locals[i];
3002 oprintf("%s\t%s: unique ", ind, v->name);
3003 for (l = 0; l < v->life_count; ++l) {
3004 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3008 for (i = 0; i < f->values_count; ++i) {
3010 ir_value *v = f->values[i];
3011 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3012 for (l = 0; l < v->life_count; ++l) {
3013 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3017 if (f->blocks_count)
3019 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3020 for (i = 0; i < f->blocks_count; ++i) {
3021 if (f->blocks[i]->run_id != f->run_id) {
3022 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3024 ir_block_dump(f->blocks[i], ind, oprintf);
3028 ind[strlen(ind)-1] = 0;
3029 oprintf("%sendfunction %s\n", ind, f->name);
3032 void ir_block_dump(ir_block* b, char *ind,
3033 int (*oprintf)(const char*, ...))
3036 oprintf("%s:%s\n", ind, b->label);
3037 strncat(ind, "\t", IND_BUFSZ);
3039 for (i = 0; i < b->instr_count; ++i)
3040 ir_instr_dump(b->instr[i], ind, oprintf);
3041 ind[strlen(ind)-1] = 0;
3044 void dump_phi(ir_instr *in, char *ind,
3045 int (*oprintf)(const char*, ...))
3048 oprintf("%s <- phi ", in->_ops[0]->name);
3049 for (i = 0; i < in->phi_count; ++i)
3051 oprintf("([%s] : %s) ", in->phi[i].from->label,
3052 in->phi[i].value->name);
3057 void ir_instr_dump(ir_instr *in, char *ind,
3058 int (*oprintf)(const char*, ...))
3061 const char *comma = NULL;
3063 oprintf("%s (%i) ", ind, (int)in->eid);
3065 if (in->opcode == VINSTR_PHI) {
3066 dump_phi(in, ind, oprintf);
3070 strncat(ind, "\t", IND_BUFSZ);
3072 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3073 ir_value_dump(in->_ops[0], oprintf);
3074 if (in->_ops[1] || in->_ops[2])
3077 if (in->opcode == INSTR_CALL0) {
3078 oprintf("CALL%i\t", in->params_count);
3080 oprintf("%s\t", qc_opname(in->opcode));
3082 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3083 ir_value_dump(in->_ops[0], oprintf);
3088 for (i = 1; i != 3; ++i) {
3092 ir_value_dump(in->_ops[i], oprintf);
3100 oprintf("[%s]", in->bops[0]->label);
3104 oprintf("%s[%s]", comma, in->bops[1]->label);
3105 if (in->params_count) {
3106 oprintf("\tparams: ");
3107 for (i = 0; i != in->params_count; ++i) {
3108 oprintf("%s, ", in->params[i]->name);
3112 ind[strlen(ind)-1] = 0;
3115 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3124 oprintf("fn:%s", v->name);
3127 oprintf("%g", v->constval.vfloat);
3130 oprintf("'%g %g %g'",
3133 v->constval.vvec.z);
3136 oprintf("(entity)");
3139 oprintf("\"%s\"", v->constval.vstring);
3143 oprintf("%i", v->constval.vint);
3148 v->constval.vpointer->name);
3152 oprintf("%s", v->name);
3156 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3159 oprintf("Life of %12s:", self->name);
3160 for (i = 0; i < self->life_count; ++i)
3162 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);