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] = {
48 size_t type_sizeof[TYPE_COUNT] = {
55 1, /* TYPE_FUNCTION */
64 uint16_t type_store_instr[TYPE_COUNT] = {
65 INSTR_STORE_F, /* should use I when having integer support */
72 INSTR_STORE_ENT, /* should use I */
74 INSTR_STORE_I, /* integer type */
79 INSTR_STORE_V, /* variant, should never be accessed */
81 AINSTR_END, /* struct */
82 AINSTR_END, /* union */
83 AINSTR_END, /* array */
86 uint16_t field_store_instr[TYPE_COUNT] = {
96 INSTR_STORE_FLD, /* integer type */
101 INSTR_STORE_V, /* variant, should never be accessed */
103 AINSTR_END, /* struct */
104 AINSTR_END, /* union */
105 AINSTR_END, /* array */
108 uint16_t type_storep_instr[TYPE_COUNT] = {
109 INSTR_STOREP_F, /* should use I when having integer support */
116 INSTR_STOREP_ENT, /* should use I */
118 INSTR_STOREP_ENT, /* integer type */
123 INSTR_STOREP_V, /* variant, should never be accessed */
125 AINSTR_END, /* struct */
126 AINSTR_END, /* union */
127 AINSTR_END, /* array */
130 uint16_t type_eq_instr[TYPE_COUNT] = {
131 INSTR_EQ_F, /* should use I when having integer support */
136 INSTR_EQ_E, /* FLD has no comparison */
138 INSTR_EQ_E, /* should use I */
145 INSTR_EQ_V, /* variant, should never be accessed */
147 AINSTR_END, /* struct */
148 AINSTR_END, /* union */
149 AINSTR_END, /* array */
152 uint16_t type_ne_instr[TYPE_COUNT] = {
153 INSTR_NE_F, /* should use I when having integer support */
158 INSTR_NE_E, /* FLD has no comparison */
160 INSTR_NE_E, /* should use I */
167 INSTR_NE_V, /* variant, should never be accessed */
169 AINSTR_END, /* struct */
170 AINSTR_END, /* union */
171 AINSTR_END, /* array */
174 uint16_t type_not_instr[TYPE_COUNT] = {
175 INSTR_NOT_F, /* should use I when having integer support */
182 INSTR_NOT_ENT, /* should use I */
184 INSTR_NOT_I, /* integer type */
189 INSTR_NOT_V, /* variant, should never be accessed */
191 AINSTR_END, /* struct */
192 AINSTR_END, /* union */
193 AINSTR_END, /* array */
197 static void ir_gen_extparam(ir_builder *ir);
199 /* error functions */
201 static void irerror(lex_ctx ctx, const char *msg, ...)
205 con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
209 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
214 r = vcompile_warning(ctx, warntype, fmt, ap);
219 /***********************************************************************
220 * Vector utility functions
223 bool GMQCC_WARN vec_ir_value_find(ir_value **vec, ir_value *what, size_t *idx)
226 size_t len = vec_size(vec);
227 for (i = 0; i < len; ++i) {
228 if (vec[i] == what) {
236 bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
239 size_t len = vec_size(vec);
240 for (i = 0; i < len; ++i) {
241 if (vec[i] == what) {
249 bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
252 size_t len = vec_size(vec);
253 for (i = 0; i < len; ++i) {
254 if (vec[i] == what) {
262 /***********************************************************************
266 static void ir_block_delete_quick(ir_block* self);
267 static void ir_instr_delete_quick(ir_instr *self);
268 static void ir_function_delete_quick(ir_function *self);
270 ir_builder* ir_builder_new(const char *modulename)
274 self = (ir_builder*)mem_a(sizeof(*self));
278 self->functions = NULL;
279 self->globals = NULL;
281 self->extparams = NULL;
282 self->filenames = NULL;
283 self->filestrings = NULL;
284 self->htglobals = util_htnew(IR_HT_SIZE);
285 self->htfields = util_htnew(IR_HT_SIZE);
286 self->htfunctions = util_htnew(IR_HT_SIZE);
288 self->str_immediate = 0;
290 if (!ir_builder_set_name(self, modulename)) {
298 void ir_builder_delete(ir_builder* self)
301 util_htdel(self->htglobals);
302 util_htdel(self->htfields);
303 util_htdel(self->htfunctions);
304 mem_d((void*)self->name);
305 for (i = 0; i != vec_size(self->functions); ++i) {
306 ir_function_delete_quick(self->functions[i]);
308 vec_free(self->functions);
309 for (i = 0; i != vec_size(self->extparams); ++i) {
310 ir_value_delete(self->extparams[i]);
312 vec_free(self->extparams);
313 for (i = 0; i != vec_size(self->globals); ++i) {
314 ir_value_delete(self->globals[i]);
316 vec_free(self->globals);
317 for (i = 0; i != vec_size(self->fields); ++i) {
318 ir_value_delete(self->fields[i]);
320 vec_free(self->fields);
321 vec_free(self->filenames);
322 vec_free(self->filestrings);
326 bool ir_builder_set_name(ir_builder *self, const char *name)
329 mem_d((void*)self->name);
330 self->name = util_strdup(name);
334 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
336 return (ir_function*)util_htget(self->htfunctions, name);
339 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
341 ir_function *fn = ir_builder_get_function(self, name);
346 fn = ir_function_new(self, outtype);
347 if (!ir_function_set_name(fn, name))
349 ir_function_delete(fn);
352 vec_push(self->functions, fn);
353 util_htset(self->htfunctions, name, fn);
355 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
357 ir_function_delete(fn);
361 fn->value->hasvalue = true;
362 fn->value->outtype = outtype;
363 fn->value->constval.vfunc = fn;
364 fn->value->context = fn->context;
369 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
371 return (ir_value*)util_htget(self->htglobals, name);
374 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
378 if (name && name[0] != '#')
380 ve = ir_builder_get_global(self, name);
386 ve = ir_value_var(name, store_global, vtype);
387 vec_push(self->globals, ve);
388 util_htset(self->htglobals, name, ve);
392 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
394 return (ir_value*)util_htget(self->htfields, name);
398 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
400 ir_value *ve = ir_builder_get_field(self, name);
405 ve = ir_value_var(name, store_global, TYPE_FIELD);
406 ve->fieldtype = vtype;
407 vec_push(self->fields, ve);
408 util_htset(self->htfields, name, ve);
412 /***********************************************************************
416 bool ir_function_naive_phi(ir_function*);
417 void ir_function_enumerate(ir_function*);
418 bool ir_function_calculate_liferanges(ir_function*);
419 bool ir_function_allocate_locals(ir_function*);
421 ir_function* ir_function_new(ir_builder* owner, int outtype)
424 self = (ir_function*)mem_a(sizeof(*self));
429 memset(self, 0, sizeof(*self));
432 if (!ir_function_set_name(self, "<@unnamed>")) {
437 self->context.file = "<@no context>";
438 self->context.line = 0;
439 self->outtype = outtype;
448 self->code_function_def = -1;
449 self->allocated_locals = 0;
455 bool ir_function_set_name(ir_function *self, const char *name)
458 mem_d((void*)self->name);
459 self->name = util_strdup(name);
463 static void ir_function_delete_quick(ir_function *self)
466 mem_d((void*)self->name);
468 for (i = 0; i != vec_size(self->blocks); ++i)
469 ir_block_delete_quick(self->blocks[i]);
470 vec_free(self->blocks);
472 vec_free(self->params);
474 for (i = 0; i != vec_size(self->values); ++i)
475 ir_value_delete(self->values[i]);
476 vec_free(self->values);
478 for (i = 0; i != vec_size(self->locals); ++i)
479 ir_value_delete(self->locals[i]);
480 vec_free(self->locals);
482 /* self->value is deleted by the builder */
487 void ir_function_delete(ir_function *self)
490 mem_d((void*)self->name);
492 for (i = 0; i != vec_size(self->blocks); ++i)
493 ir_block_delete(self->blocks[i]);
494 vec_free(self->blocks);
496 vec_free(self->params);
498 for (i = 0; i != vec_size(self->values); ++i)
499 ir_value_delete(self->values[i]);
500 vec_free(self->values);
502 for (i = 0; i != vec_size(self->locals); ++i)
503 ir_value_delete(self->locals[i]);
504 vec_free(self->locals);
506 /* self->value is deleted by the builder */
511 void ir_function_collect_value(ir_function *self, ir_value *v)
513 vec_push(self->values, v);
516 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
518 ir_block* bn = ir_block_new(self, label);
520 vec_push(self->blocks, bn);
524 static bool instr_is_operation(uint16_t op)
526 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
527 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
528 (op == INSTR_ADDRESS) ||
529 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
530 (op >= INSTR_AND && op <= INSTR_BITOR) );
533 bool ir_function_pass_peephole(ir_function *self)
537 for (b = 0; b < vec_size(self->blocks); ++b) {
539 ir_block *block = self->blocks[b];
541 for (i = 0; i < vec_size(block->instr); ++i) {
543 inst = block->instr[i];
546 (inst->opcode >= INSTR_STORE_F &&
547 inst->opcode <= INSTR_STORE_FNC))
555 oper = block->instr[i-1];
556 if (!instr_is_operation(oper->opcode))
559 value = oper->_ops[0];
561 /* only do it for SSA values */
562 if (value->store != store_value)
565 /* don't optimize out the temp if it's used later again */
566 if (vec_size(value->reads) != 1)
569 /* The very next store must use this value */
570 if (value->reads[0] != store)
573 /* And of course the store must _read_ from it, so it's in
575 if (store->_ops[1] != value)
578 ++opts_optimizationcount[OPTIM_PEEPHOLE];
579 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
581 vec_remove(block->instr, i, 1);
582 ir_instr_delete(store);
584 else if (inst->opcode == VINSTR_COND)
586 /* COND on a value resulting from a NOT could
587 * remove the NOT and swap its operands
594 value = inst->_ops[0];
596 if (value->store != store_value ||
597 vec_size(value->reads) != 1 ||
598 value->reads[0] != inst)
603 inot = value->writes[0];
604 if (inot->_ops[0] != value ||
605 inot->opcode < INSTR_NOT_F ||
606 inot->opcode > INSTR_NOT_FNC ||
607 inot->opcode == INSTR_NOT_V) /* can't do this one */
613 ++opts_optimizationcount[OPTIM_PEEPHOLE];
615 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
618 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
619 if (tmp->instr[inotid] == inot)
622 if (inotid >= vec_size(tmp->instr)) {
623 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
626 vec_remove(tmp->instr, inotid, 1);
627 ir_instr_delete(inot);
628 /* swap ontrue/onfalse */
630 inst->bops[0] = inst->bops[1];
641 bool ir_function_pass_tailcall(ir_function *self)
645 for (b = 0; b < vec_size(self->blocks); ++b) {
647 ir_instr *ret, *call, *store = NULL;
648 ir_block *block = self->blocks[b];
650 if (!block->final || vec_size(block->instr) < 2)
653 ret = block->instr[vec_size(block->instr)-1];
654 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
657 call = block->instr[vec_size(block->instr)-2];
658 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
659 /* account for the unoptimized
661 * STORE %return, %tmp
665 if (vec_size(block->instr) < 3)
669 call = block->instr[vec_size(block->instr)-3];
672 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
676 /* optimize out the STORE */
678 ret->_ops[0] == store->_ops[0] &&
679 store->_ops[1] == call->_ops[0])
681 ++opts_optimizationcount[OPTIM_PEEPHOLE];
682 call->_ops[0] = store->_ops[0];
683 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
684 ir_instr_delete(store);
693 funcval = call->_ops[1];
696 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
699 /* now we have a CALL and a RET, check if it's a tailcall */
700 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
703 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
704 vec_shrinkby(block->instr, 2);
706 block->final = false; /* open it back up */
708 /* emite parameter-stores */
709 for (p = 0; p < vec_size(call->params); ++p) {
710 /* assert(call->params_count <= self->locals_count); */
711 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
712 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
716 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
717 irerror(call->context, "failed to create tailcall jump");
721 ir_instr_delete(call);
722 ir_instr_delete(ret);
728 bool ir_function_finalize(ir_function *self)
733 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
734 if (!ir_function_pass_peephole(self)) {
735 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
740 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
741 if (!ir_function_pass_tailcall(self)) {
742 irerror(self->context, "tailcall optimization pass broke something in `%s`", self->name);
747 if (!ir_function_naive_phi(self))
750 ir_function_enumerate(self);
752 if (!ir_function_calculate_liferanges(self))
754 if (!ir_function_allocate_locals(self))
759 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
764 vec_size(self->locals) &&
765 self->locals[vec_size(self->locals)-1]->store != store_param) {
766 irerror(self->context, "cannot add parameters after adding locals");
770 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
771 vec_push(self->locals, ve);
775 /***********************************************************************
779 ir_block* ir_block_new(ir_function* owner, const char *name)
782 self = (ir_block*)mem_a(sizeof(*self));
786 memset(self, 0, sizeof(*self));
789 if (name && !ir_block_set_label(self, name)) {
794 self->context.file = "<@no context>";
795 self->context.line = 0;
799 self->entries = NULL;
803 self->is_return = false;
808 self->generated = false;
813 static void ir_block_delete_quick(ir_block* self)
816 if (self->label) mem_d(self->label);
817 for (i = 0; i != vec_size(self->instr); ++i)
818 ir_instr_delete_quick(self->instr[i]);
819 vec_free(self->instr);
820 vec_free(self->entries);
821 vec_free(self->exits);
822 vec_free(self->living);
826 void ir_block_delete(ir_block* self)
829 if (self->label) mem_d(self->label);
830 for (i = 0; i != vec_size(self->instr); ++i)
831 ir_instr_delete(self->instr[i]);
832 vec_free(self->instr);
833 vec_free(self->entries);
834 vec_free(self->exits);
835 vec_free(self->living);
839 bool ir_block_set_label(ir_block *self, const char *name)
842 mem_d((void*)self->label);
843 self->label = util_strdup(name);
844 return !!self->label;
847 /***********************************************************************
851 ir_instr* ir_instr_new(lex_ctx ctx, ir_block* owner, int op)
854 self = (ir_instr*)mem_a(sizeof(*self));
861 self->_ops[0] = NULL;
862 self->_ops[1] = NULL;
863 self->_ops[2] = NULL;
864 self->bops[0] = NULL;
865 self->bops[1] = NULL;
876 static void ir_instr_delete_quick(ir_instr *self)
879 vec_free(self->params);
883 void ir_instr_delete(ir_instr *self)
886 /* The following calls can only delete from
887 * vectors, we still want to delete this instruction
888 * so ignore the return value. Since with the warn_unused_result attribute
889 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
890 * I have to improvise here and use if(foo());
892 for (i = 0; i < vec_size(self->phi); ++i) {
894 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
895 vec_remove(self->phi[i].value->writes, idx, 1);
896 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
897 vec_remove(self->phi[i].value->reads, idx, 1);
900 for (i = 0; i < vec_size(self->params); ++i) {
902 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
903 vec_remove(self->params[i]->writes, idx, 1);
904 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
905 vec_remove(self->params[i]->reads, idx, 1);
907 vec_free(self->params);
908 (void)!ir_instr_op(self, 0, NULL, false);
909 (void)!ir_instr_op(self, 1, NULL, false);
910 (void)!ir_instr_op(self, 2, NULL, false);
914 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
916 if (self->_ops[op]) {
918 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
919 vec_remove(self->_ops[op]->writes, idx, 1);
920 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
921 vec_remove(self->_ops[op]->reads, idx, 1);
925 vec_push(v->writes, self);
927 vec_push(v->reads, self);
933 /***********************************************************************
937 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
939 self->code.globaladdr = gaddr;
940 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
941 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
942 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
945 int32_t ir_value_code_addr(const ir_value *self)
947 if (self->store == store_return)
948 return OFS_RETURN + self->code.addroffset;
949 return self->code.globaladdr + self->code.addroffset;
952 ir_value* ir_value_var(const char *name, int storetype, int vtype)
955 self = (ir_value*)mem_a(sizeof(*self));
957 self->fieldtype = TYPE_VOID;
958 self->outtype = TYPE_VOID;
959 self->store = storetype;
965 self->hasvalue = false;
966 self->context.file = "<@no context>";
967 self->context.line = 0;
969 if (name && !ir_value_set_name(self, name)) {
970 irerror(self->context, "out of memory");
975 memset(&self->constval, 0, sizeof(self->constval));
976 memset(&self->code, 0, sizeof(self->code));
978 self->members[0] = NULL;
979 self->members[1] = NULL;
980 self->members[2] = NULL;
981 self->memberof = NULL;
983 self->unique_life = false;
989 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
995 if (self->members[member])
996 return self->members[member];
998 if (self->vtype == TYPE_VECTOR)
1000 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
1003 m->context = self->context;
1005 self->members[member] = m;
1006 m->code.addroffset = member;
1008 else if (self->vtype == TYPE_FIELD)
1010 if (self->fieldtype != TYPE_VECTOR)
1012 m = ir_value_var(self->name, self->store, TYPE_FIELD);
1015 m->fieldtype = TYPE_FLOAT;
1016 m->context = self->context;
1018 self->members[member] = m;
1019 m->code.addroffset = member;
1023 irerror(self->context, "invalid member access on %s", self->name);
1031 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1033 ir_value *v = ir_value_var(name, storetype, vtype);
1036 ir_function_collect_value(owner, v);
1040 void ir_value_delete(ir_value* self)
1044 mem_d((void*)self->name);
1047 if (self->vtype == TYPE_STRING)
1048 mem_d((void*)self->constval.vstring);
1050 for (i = 0; i < 3; ++i) {
1051 if (self->members[i])
1052 ir_value_delete(self->members[i]);
1054 vec_free(self->reads);
1055 vec_free(self->writes);
1056 vec_free(self->life);
1060 bool ir_value_set_name(ir_value *self, const char *name)
1063 mem_d((void*)self->name);
1064 self->name = util_strdup(name);
1065 return !!self->name;
1068 bool ir_value_set_float(ir_value *self, float f)
1070 if (self->vtype != TYPE_FLOAT)
1072 self->constval.vfloat = f;
1073 self->hasvalue = true;
1077 bool ir_value_set_func(ir_value *self, int f)
1079 if (self->vtype != TYPE_FUNCTION)
1081 self->constval.vint = f;
1082 self->hasvalue = true;
1086 bool ir_value_set_vector(ir_value *self, vector v)
1088 if (self->vtype != TYPE_VECTOR)
1090 self->constval.vvec = v;
1091 self->hasvalue = true;
1095 bool ir_value_set_field(ir_value *self, ir_value *fld)
1097 if (self->vtype != TYPE_FIELD)
1099 self->constval.vpointer = fld;
1100 self->hasvalue = true;
1104 static char *ir_strdup(const char *str)
1107 /* actually dup empty strings */
1108 char *out = mem_a(1);
1112 return util_strdup(str);
1115 bool ir_value_set_string(ir_value *self, const char *str)
1117 if (self->vtype != TYPE_STRING)
1119 self->constval.vstring = ir_strdup(str);
1120 self->hasvalue = true;
1125 bool ir_value_set_int(ir_value *self, int i)
1127 if (self->vtype != TYPE_INTEGER)
1129 self->constval.vint = i;
1130 self->hasvalue = true;
1135 bool ir_value_lives(ir_value *self, size_t at)
1138 for (i = 0; i < vec_size(self->life); ++i)
1140 ir_life_entry_t *life = &self->life[i];
1141 if (life->start <= at && at <= life->end)
1143 if (life->start > at) /* since it's ordered */
1149 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1152 vec_push(self->life, e);
1153 for (k = vec_size(self->life)-1; k > idx; --k)
1154 self->life[k] = self->life[k-1];
1155 self->life[idx] = e;
1159 bool ir_value_life_merge(ir_value *self, size_t s)
1162 ir_life_entry_t *life = NULL;
1163 ir_life_entry_t *before = NULL;
1164 ir_life_entry_t new_entry;
1166 /* Find the first range >= s */
1167 for (i = 0; i < vec_size(self->life); ++i)
1170 life = &self->life[i];
1171 if (life->start > s)
1174 /* nothing found? append */
1175 if (i == vec_size(self->life)) {
1177 if (life && life->end+1 == s)
1179 /* previous life range can be merged in */
1183 if (life && life->end >= s)
1185 e.start = e.end = s;
1186 vec_push(self->life, e);
1192 if (before->end + 1 == s &&
1193 life->start - 1 == s)
1196 before->end = life->end;
1197 vec_remove(self->life, i, 1);
1200 if (before->end + 1 == s)
1206 /* already contained */
1207 if (before->end >= s)
1211 if (life->start - 1 == s)
1216 /* insert a new entry */
1217 new_entry.start = new_entry.end = s;
1218 return ir_value_life_insert(self, i, new_entry);
1221 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1225 if (!vec_size(other->life))
1228 if (!vec_size(self->life)) {
1229 size_t count = vec_size(other->life);
1230 ir_life_entry_t *life = vec_add(self->life, count);
1231 memcpy(life, other->life, count * sizeof(*life));
1236 for (i = 0; i < vec_size(other->life); ++i)
1238 const ir_life_entry_t *life = &other->life[i];
1241 ir_life_entry_t *entry = &self->life[myi];
1243 if (life->end+1 < entry->start)
1245 /* adding an interval before entry */
1246 if (!ir_value_life_insert(self, myi, *life))
1252 if (life->start < entry->start &&
1253 life->end+1 >= entry->start)
1255 /* starts earlier and overlaps */
1256 entry->start = life->start;
1259 if (life->end > entry->end &&
1260 life->start <= entry->end+1)
1262 /* ends later and overlaps */
1263 entry->end = life->end;
1266 /* see if our change combines it with the next ranges */
1267 while (myi+1 < vec_size(self->life) &&
1268 entry->end+1 >= self->life[1+myi].start)
1270 /* overlaps with (myi+1) */
1271 if (entry->end < self->life[1+myi].end)
1272 entry->end = self->life[1+myi].end;
1273 vec_remove(self->life, myi+1, 1);
1274 entry = &self->life[myi];
1277 /* see if we're after the entry */
1278 if (life->start > entry->end)
1281 /* append if we're at the end */
1282 if (myi >= vec_size(self->life)) {
1283 vec_push(self->life, *life);
1286 /* otherweise check the next range */
1295 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1297 /* For any life entry in A see if it overlaps with
1298 * any life entry in B.
1299 * Note that the life entries are orderes, so we can make a
1300 * more efficient algorithm there than naively translating the
1304 ir_life_entry_t *la, *lb, *enda, *endb;
1306 /* first of all, if either has no life range, they cannot clash */
1307 if (!vec_size(a->life) || !vec_size(b->life))
1312 enda = la + vec_size(a->life);
1313 endb = lb + vec_size(b->life);
1316 /* check if the entries overlap, for that,
1317 * both must start before the other one ends.
1319 if (la->start < lb->end &&
1320 lb->start < la->end)
1325 /* entries are ordered
1326 * one entry is earlier than the other
1327 * that earlier entry will be moved forward
1329 if (la->start < lb->start)
1331 /* order: A B, move A forward
1332 * check if we hit the end with A
1337 else /* if (lb->start < la->start) actually <= */
1339 /* order: B A, move B forward
1340 * check if we hit the end with B
1349 /***********************************************************************
1353 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1357 irerror(self->context, "unreachable statement (%s)", self->label);
1360 in = ir_instr_new(ctx, self, op);
1364 if (target->store == store_value &&
1365 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1367 irerror(self->context, "cannot store to an SSA value");
1368 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1369 irerror(self->context, "instruction: %s", asm_instr[op].m);
1373 if (!ir_instr_op(in, 0, target, true) ||
1374 !ir_instr_op(in, 1, what, false))
1378 vec_push(self->instr, in);
1382 bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1386 if (target->vtype == TYPE_VARIANT)
1387 vtype = what->vtype;
1389 vtype = target->vtype;
1392 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1393 op = INSTR_CONV_ITOF;
1394 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1395 op = INSTR_CONV_FTOI;
1397 op = type_store_instr[vtype];
1399 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1400 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1404 return ir_block_create_store_op(self, ctx, op, target, what);
1407 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1412 if (target->vtype != TYPE_POINTER)
1415 /* storing using pointer - target is a pointer, type must be
1416 * inferred from source
1418 vtype = what->vtype;
1420 op = type_storep_instr[vtype];
1421 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1422 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1423 op = INSTR_STOREP_V;
1426 return ir_block_create_store_op(self, ctx, op, target, what);
1429 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1433 irerror(self->context, "unreachable statement (%s)", self->label);
1437 self->is_return = true;
1438 in = ir_instr_new(ctx, self, INSTR_RETURN);
1442 if (v && !ir_instr_op(in, 0, v, false))
1445 vec_push(self->instr, in);
1449 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1450 ir_block *ontrue, ir_block *onfalse)
1454 irerror(self->context, "unreachable statement (%s)", self->label);
1458 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1459 in = ir_instr_new(ctx, self, VINSTR_COND);
1463 if (!ir_instr_op(in, 0, v, false)) {
1464 ir_instr_delete(in);
1468 in->bops[0] = ontrue;
1469 in->bops[1] = onfalse;
1471 vec_push(self->instr, in);
1473 vec_push(self->exits, ontrue);
1474 vec_push(self->exits, onfalse);
1475 vec_push(ontrue->entries, self);
1476 vec_push(onfalse->entries, self);
1480 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1484 irerror(self->context, "unreachable statement (%s)", self->label);
1488 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1493 vec_push(self->instr, in);
1495 vec_push(self->exits, to);
1496 vec_push(to->entries, self);
1500 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1504 irerror(self->context, "unreachable statement (%s)", self->label);
1508 in = ir_instr_new(ctx, self, INSTR_GOTO);
1513 vec_push(self->instr, in);
1515 vec_push(self->exits, to);
1516 vec_push(to->entries, self);
1520 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1524 in = ir_instr_new(ctx, self, VINSTR_PHI);
1527 out = ir_value_out(self->owner, label, store_value, ot);
1529 ir_instr_delete(in);
1532 if (!ir_instr_op(in, 0, out, true)) {
1533 ir_instr_delete(in);
1534 ir_value_delete(out);
1537 vec_push(self->instr, in);
1541 ir_value* ir_phi_value(ir_instr *self)
1543 return self->_ops[0];
1546 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1550 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1551 /* Must not be possible to cause this, otherwise the AST
1552 * is doing something wrong.
1554 irerror(self->context, "Invalid entry block for PHI");
1560 vec_push(v->reads, self);
1561 vec_push(self->phi, pe);
1564 /* call related code */
1565 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func)
1569 in = ir_instr_new(ctx, self, INSTR_CALL0);
1572 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1574 ir_instr_delete(in);
1577 if (!ir_instr_op(in, 0, out, true) ||
1578 !ir_instr_op(in, 1, func, false))
1580 ir_instr_delete(in);
1581 ir_value_delete(out);
1584 vec_push(self->instr, in);
1588 ir_value* ir_call_value(ir_instr *self)
1590 return self->_ops[0];
1593 void ir_call_param(ir_instr* self, ir_value *v)
1595 vec_push(self->params, v);
1596 vec_push(v->reads, self);
1599 /* binary op related code */
1601 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1602 const char *label, int opcode,
1603 ir_value *left, ir_value *right)
1625 case INSTR_SUB_S: /* -- offset of string as float */
1630 case INSTR_BITOR_IF:
1631 case INSTR_BITOR_FI:
1632 case INSTR_BITAND_FI:
1633 case INSTR_BITAND_IF:
1648 case INSTR_BITAND_I:
1651 case INSTR_RSHIFT_I:
1652 case INSTR_LSHIFT_I:
1674 /* boolean operations result in floats */
1675 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1677 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1680 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1685 if (ot == TYPE_VOID) {
1686 /* The AST or parser were supposed to check this! */
1690 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1693 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1694 const char *label, int opcode,
1697 int ot = TYPE_FLOAT;
1709 /* QC doesn't have other unary operations. We expect extensions to fill
1710 * the above list, otherwise we assume out-type = in-type, eg for an
1714 ot = operand->vtype;
1717 if (ot == TYPE_VOID) {
1718 /* The AST or parser were supposed to check this! */
1722 /* let's use the general instruction creator and pass NULL for OPB */
1723 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1726 ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1727 int op, ir_value *a, ir_value *b, int outype)
1732 out = ir_value_out(self->owner, label, store_value, outype);
1736 instr = ir_instr_new(ctx, self, op);
1738 ir_value_delete(out);
1742 if (!ir_instr_op(instr, 0, out, true) ||
1743 !ir_instr_op(instr, 1, a, false) ||
1744 !ir_instr_op(instr, 2, b, false) )
1749 vec_push(self->instr, instr);
1753 ir_instr_delete(instr);
1754 ir_value_delete(out);
1758 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1762 /* Support for various pointer types todo if so desired */
1763 if (ent->vtype != TYPE_ENTITY)
1766 if (field->vtype != TYPE_FIELD)
1769 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1770 v->fieldtype = field->fieldtype;
1774 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field, int outype)
1777 if (ent->vtype != TYPE_ENTITY)
1780 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1781 if (field->vtype != TYPE_FIELD)
1786 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1787 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1788 case TYPE_STRING: op = INSTR_LOAD_S; break;
1789 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1790 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1791 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1793 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1794 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1797 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1801 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1804 ir_value* ir_block_create_add(ir_block *self, lex_ctx ctx,
1806 ir_value *left, ir_value *right)
1809 int l = left->vtype;
1810 int r = right->vtype;
1814 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1830 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1832 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1837 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1841 return ir_block_create_binop(self, ctx, label, op, left, right);
1844 ir_value* ir_block_create_sub(ir_block *self, lex_ctx ctx,
1846 ir_value *left, ir_value *right)
1849 int l = left->vtype;
1850 int r = right->vtype;
1855 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1871 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1873 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1878 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1882 return ir_block_create_binop(self, ctx, label, op, left, right);
1885 ir_value* ir_block_create_mul(ir_block *self, lex_ctx ctx,
1887 ir_value *left, ir_value *right)
1890 int l = left->vtype;
1891 int r = right->vtype;
1896 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1911 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1913 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1916 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1918 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1920 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1922 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1926 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1930 return ir_block_create_binop(self, ctx, label, op, left, right);
1933 ir_value* ir_block_create_div(ir_block *self, lex_ctx ctx,
1935 ir_value *left, ir_value *right)
1938 int l = left->vtype;
1939 int r = right->vtype;
1944 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1957 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1959 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1961 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1966 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1970 return ir_block_create_binop(self, ctx, label, op, left, right);
1973 /* PHI resolving breaks the SSA, and must thus be the last
1974 * step before life-range calculation.
1977 static bool ir_block_naive_phi(ir_block *self);
1978 bool ir_function_naive_phi(ir_function *self)
1982 for (i = 0; i < vec_size(self->blocks); ++i)
1984 if (!ir_block_naive_phi(self->blocks[i]))
1991 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1996 /* create a store */
1997 if (!ir_block_create_store(block, old, what))
2000 /* we now move it up */
2001 instr = vec_last(block->instr);
2002 for (i = vec_size(block->instr)-1; i > iid; --i)
2003 block->instr[i] = block->instr[i-1];
2004 block->instr[i] = instr;
2010 static bool ir_block_naive_phi(ir_block *self)
2012 size_t i, p; /*, w;*/
2013 /* FIXME: optionally, create_phi can add the phis
2014 * to a list so we don't need to loop through blocks
2015 * - anyway: "don't optimize YET"
2017 for (i = 0; i < vec_size(self->instr); ++i)
2019 ir_instr *instr = self->instr[i];
2020 if (instr->opcode != VINSTR_PHI)
2023 vec_remove(self->instr, i, 1);
2024 --i; /* NOTE: i+1 below */
2026 for (p = 0; p < vec_size(instr->phi); ++p)
2028 ir_value *v = instr->phi[p].value;
2029 ir_block *b = instr->phi[p].from;
2031 if (v->store == store_value &&
2032 vec_size(v->reads) == 1 &&
2033 vec_size(v->writes) == 1)
2035 /* replace the value */
2036 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2041 /* force a move instruction */
2042 ir_instr *prevjump = vec_last(b->instr);
2045 instr->_ops[0]->store = store_global;
2046 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2048 instr->_ops[0]->store = store_value;
2049 vec_push(b->instr, prevjump);
2054 ir_value *v = instr->phi[p].value;
2055 for (w = 0; w < vec_size(v->writes); ++w) {
2058 if (!v->writes[w]->_ops[0])
2061 /* When the write was to a global, we have to emit a mov */
2062 old = v->writes[w]->_ops[0];
2064 /* The original instruction now writes to the PHI target local */
2065 if (v->writes[w]->_ops[0] == v)
2066 v->writes[w]->_ops[0] = instr->_ops[0];
2068 if (old->store != store_value && old->store != store_local && old->store != store_param)
2070 /* If it originally wrote to a global we need to store the value
2073 if (!ir_naive_phi_emit_store(self, i+1, old, v))
2075 if (i+1 < vec_size(self->instr))
2076 instr = self->instr[i+1];
2079 /* In case I forget and access instr later, it'll be NULL
2080 * when it's a problem, to make sure we crash, rather than accessing
2086 /* If it didn't, we can replace all reads by the phi target now. */
2088 for (r = 0; r < vec_size(old->reads); ++r)
2091 ir_instr *ri = old->reads[r];
2092 for (op = 0; op < vec_size(ri->phi); ++op) {
2093 if (ri->phi[op].value == old)
2094 ri->phi[op].value = v;
2096 for (op = 0; op < 3; ++op) {
2097 if (ri->_ops[op] == old)
2105 ir_instr_delete(instr);
2110 /***********************************************************************
2111 *IR Temp allocation code
2112 * Propagating value life ranges by walking through the function backwards
2113 * until no more changes are made.
2114 * In theory this should happen once more than once for every nested loop
2116 * Though this implementation might run an additional time for if nests.
2119 /* Enumerate instructions used by value's life-ranges
2121 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2125 for (i = 0; i < vec_size(self->instr); ++i)
2127 self->instr[i]->eid = eid++;
2132 /* Enumerate blocks and instructions.
2133 * The block-enumeration is unordered!
2134 * We do not really use the block enumreation, however
2135 * the instruction enumeration is important for life-ranges.
2137 void ir_function_enumerate(ir_function *self)
2140 size_t instruction_id = 0;
2141 for (i = 0; i < vec_size(self->blocks); ++i)
2143 self->blocks[i]->eid = i;
2144 self->blocks[i]->run_id = 0;
2145 ir_block_enumerate(self->blocks[i], &instruction_id);
2149 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
2150 bool ir_function_calculate_liferanges(ir_function *self)
2158 for (i = 0; i != vec_size(self->blocks); ++i)
2160 if (self->blocks[i]->is_return)
2162 vec_free(self->blocks[i]->living);
2163 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
2168 if (vec_size(self->blocks)) {
2169 ir_block *block = self->blocks[0];
2170 for (i = 0; i < vec_size(block->living); ++i) {
2171 ir_value *v = block->living[i];
2172 if (v->memberof || v->store != store_local)
2174 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2175 "variable `%s` may be used uninitialized in this function", v->name))
2184 /* Local-value allocator
2185 * After finishing creating the liferange of all values used in a function
2186 * we can allocate their global-positions.
2187 * This is the counterpart to register-allocation in register machines.
2194 } function_allocator;
2196 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
2199 size_t vsize = type_sizeof[var->vtype];
2201 slot = ir_value_var("reg", store_global, var->vtype);
2205 if (!ir_value_life_merge_into(slot, var))
2208 vec_push(alloc->locals, slot);
2209 vec_push(alloc->sizes, vsize);
2210 vec_push(alloc->unique, var->unique_life);
2215 ir_value_delete(slot);
2219 bool ir_function_allocate_locals(ir_function *self)
2228 function_allocator alloc;
2230 if (!vec_size(self->locals) && !vec_size(self->values))
2233 alloc.locals = NULL;
2235 alloc.positions = NULL;
2236 alloc.unique = NULL;
2238 for (i = 0; i < vec_size(self->locals); ++i)
2240 if (!OPTS_OPTIMIZATION(OPTIM_LOCALTEMPS))
2241 self->locals[i]->unique_life = true;
2242 if (!function_allocator_alloc(&alloc, self->locals[i]))
2246 /* Allocate a slot for any value that still exists */
2247 for (i = 0; i < vec_size(self->values); ++i)
2249 v = self->values[i];
2251 if (!vec_size(v->life))
2254 for (a = 0; a < vec_size(alloc.locals); ++a)
2256 /* if it's reserved for a unique liferange: skip */
2257 if (alloc.unique[a])
2260 slot = alloc.locals[a];
2262 /* never resize parameters
2263 * will be required later when overlapping temps + locals
2265 if (a < vec_size(self->params) &&
2266 alloc.sizes[a] < type_sizeof[v->vtype])
2271 if (ir_values_overlap(v, slot))
2274 if (!ir_value_life_merge_into(slot, v))
2277 /* adjust size for this slot */
2278 if (alloc.sizes[a] < type_sizeof[v->vtype])
2279 alloc.sizes[a] = type_sizeof[v->vtype];
2281 self->values[i]->code.local = a;
2284 if (a >= vec_size(alloc.locals)) {
2285 self->values[i]->code.local = vec_size(alloc.locals);
2286 if (!function_allocator_alloc(&alloc, v))
2295 /* Adjust slot positions based on sizes */
2296 vec_push(alloc.positions, 0);
2298 if (vec_size(alloc.sizes))
2299 pos = alloc.positions[0] + alloc.sizes[0];
2302 for (i = 1; i < vec_size(alloc.sizes); ++i)
2304 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2305 vec_push(alloc.positions, pos);
2308 self->allocated_locals = pos + vec_last(alloc.sizes);
2310 /* Locals need to know their new position */
2311 for (i = 0; i < vec_size(self->locals); ++i) {
2312 self->locals[i]->code.local = alloc.positions[i];
2314 /* Take over the actual slot positions on values */
2315 for (i = 0; i < vec_size(self->values); ++i) {
2316 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2324 for (i = 0; i < vec_size(alloc.locals); ++i)
2325 ir_value_delete(alloc.locals[i]);
2326 vec_free(alloc.locals);
2327 vec_free(alloc.sizes);
2328 vec_free(alloc.positions);
2332 /* Get information about which operand
2333 * is read from, or written to.
2335 static void ir_op_read_write(int op, size_t *read, size_t *write)
2355 case INSTR_STOREP_F:
2356 case INSTR_STOREP_V:
2357 case INSTR_STOREP_S:
2358 case INSTR_STOREP_ENT:
2359 case INSTR_STOREP_FLD:
2360 case INSTR_STOREP_FNC:
2371 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2374 bool changed = false;
2376 for (i = 0; i != vec_size(self->living); ++i)
2378 tempbool = ir_value_life_merge(self->living[i], eid);
2381 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2383 changed = changed || tempbool;
2388 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2394 /* values which have been read in a previous iteration are now
2395 * in the "living" array even if the previous block doesn't use them.
2396 * So we have to remove whatever does not exist in the previous block.
2397 * They will be re-added on-read, but the liferange merge won't cause
2399 for (i = 0; i < vec_size(self->living); ++i)
2401 if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2402 vec_remove(self->living, i, 1);
2408 /* Whatever the previous block still has in its living set
2409 * must now be added to ours as well.
2411 for (i = 0; i < vec_size(prev->living); ++i)
2413 if (vec_ir_value_find(self->living, prev->living[i], NULL))
2415 vec_push(self->living, prev->living[i]);
2417 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2423 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2429 /* bitmasks which operands are read from or written to */
2431 char dbg_ind[16] = { '#', '0' };
2436 if (!ir_block_life_prop_previous(self, prev, changed))
2440 i = vec_size(self->instr);
2443 instr = self->instr[i];
2445 /* PHI operands are always read operands */
2446 for (p = 0; p < vec_size(instr->phi); ++p)
2448 value = instr->phi[p].value;
2449 if (value->memberof)
2450 value = value->memberof;
2451 if (!vec_ir_value_find(self->living, value, NULL))
2452 vec_push(self->living, value);
2455 /* call params are read operands too */
2456 for (p = 0; p < vec_size(instr->params); ++p)
2458 value = instr->params[p];
2459 if (value->memberof)
2460 value = value->memberof;
2461 if (!vec_ir_value_find(self->living, value, NULL))
2462 vec_push(self->living, value);
2465 /* See which operands are read and write operands */
2466 ir_op_read_write(instr->opcode, &read, &write);
2468 if (instr->opcode == INSTR_MUL_VF)
2470 /* the float source will get an additional lifetime */
2471 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2472 *changed = *changed || tempbool;
2474 else if (instr->opcode == INSTR_MUL_FV)
2476 /* the float source will get an additional lifetime */
2477 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2478 *changed = *changed || tempbool;
2481 /* Go through the 3 main operands */
2482 for (o = 0; o < 3; ++o)
2484 if (!instr->_ops[o]) /* no such operand */
2487 value = instr->_ops[o];
2488 if (value->memberof)
2489 value = value->memberof;
2491 /* We only care about locals */
2492 /* we also calculate parameter liferanges so that locals
2493 * can take up parameter slots */
2494 if (value->store != store_value &&
2495 value->store != store_local &&
2496 value->store != store_param)
2502 if (!vec_ir_value_find(self->living, value, NULL))
2503 vec_push(self->living, value);
2506 /* write operands */
2507 /* When we write to a local, we consider it "dead" for the
2508 * remaining upper part of the function, since in SSA a value
2509 * can only be written once (== created)
2514 bool in_living = vec_ir_value_find(self->living, value, &idx);
2517 /* If the value isn't alive it hasn't been read before... */
2518 /* TODO: See if the warning can be emitted during parsing or AST processing
2519 * otherwise have warning printed here.
2520 * IF printing a warning here: include filecontext_t,
2521 * and make sure it's only printed once
2522 * since this function is run multiple times.
2524 /* For now: debug info: */
2525 /* con_err( "Value only written %s\n", value->name); */
2526 tempbool = ir_value_life_merge(value, instr->eid);
2527 *changed = *changed || tempbool;
2529 ir_instr_dump(instr, dbg_ind, printf);
2533 /* since 'living' won't contain it
2534 * anymore, merge the value, since
2537 tempbool = ir_value_life_merge(value, instr->eid);
2540 con_err( "value added id %s %i\n", value->name, (int)instr->eid);
2542 *changed = *changed || tempbool;
2544 vec_remove(self->living, idx, 1);
2549 tempbool = ir_block_living_add_instr(self, instr->eid);
2550 /*con_err( "living added values\n");*/
2551 *changed = *changed || tempbool;
2555 if (self->run_id == self->owner->run_id)
2558 self->run_id = self->owner->run_id;
2560 for (i = 0; i < vec_size(self->entries); ++i)
2562 ir_block *entry = self->entries[i];
2563 ir_block_life_propagate(entry, self, changed);
2569 /***********************************************************************
2572 * Since the IR has the convention of putting 'write' operands
2573 * at the beginning, we have to rotate the operands of instructions
2574 * properly in order to generate valid QCVM code.
2576 * Having destinations at a fixed position is more convenient. In QC
2577 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2578 * read from from OPA, and store to OPB rather than OPC. Which is
2579 * partially the reason why the implementation of these instructions
2580 * in darkplaces has been delayed for so long.
2582 * Breaking conventions is annoying...
2584 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2586 static bool gen_global_field(ir_value *global)
2588 if (global->hasvalue)
2590 ir_value *fld = global->constval.vpointer;
2592 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2596 /* copy the field's value */
2597 ir_value_code_setaddr(global, vec_size(code_globals));
2598 vec_push(code_globals, fld->code.fieldaddr);
2599 if (global->fieldtype == TYPE_VECTOR) {
2600 vec_push(code_globals, fld->code.fieldaddr+1);
2601 vec_push(code_globals, fld->code.fieldaddr+2);
2606 ir_value_code_setaddr(global, vec_size(code_globals));
2607 vec_push(code_globals, 0);
2608 if (global->fieldtype == TYPE_VECTOR) {
2609 vec_push(code_globals, 0);
2610 vec_push(code_globals, 0);
2613 if (global->code.globaladdr < 0)
2618 static bool gen_global_pointer(ir_value *global)
2620 if (global->hasvalue)
2622 ir_value *target = global->constval.vpointer;
2624 irerror(global->context, "Invalid pointer constant: %s", global->name);
2625 /* NULL pointers are pointing to the NULL constant, which also
2626 * sits at address 0, but still has an ir_value for itself.
2631 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2632 * void() foo; <- proto
2633 * void() *fooptr = &foo;
2634 * void() foo = { code }
2636 if (!target->code.globaladdr) {
2637 /* FIXME: Check for the constant nullptr ir_value!
2638 * because then code.globaladdr being 0 is valid.
2640 irerror(global->context, "FIXME: Relocation support");
2644 ir_value_code_setaddr(global, vec_size(code_globals));
2645 vec_push(code_globals, target->code.globaladdr);
2649 ir_value_code_setaddr(global, vec_size(code_globals));
2650 vec_push(code_globals, 0);
2652 if (global->code.globaladdr < 0)
2657 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2659 prog_section_statement stmt;
2668 block->generated = true;
2669 block->code_start = vec_size(code_statements);
2670 for (i = 0; i < vec_size(block->instr); ++i)
2672 instr = block->instr[i];
2674 if (instr->opcode == VINSTR_PHI) {
2675 irerror(block->context, "cannot generate virtual instruction (phi)");
2679 if (instr->opcode == VINSTR_JUMP) {
2680 target = instr->bops[0];
2681 /* for uncoditional jumps, if the target hasn't been generated
2682 * yet, we generate them right here.
2684 if (!target->generated) {
2689 /* otherwise we generate a jump instruction */
2690 stmt.opcode = INSTR_GOTO;
2691 stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2694 if (stmt.o1.s1 != 1)
2695 code_push_statement(&stmt, instr->context.line);
2697 /* no further instructions can be in this block */
2701 if (instr->opcode == VINSTR_COND) {
2702 ontrue = instr->bops[0];
2703 onfalse = instr->bops[1];
2704 /* TODO: have the AST signal which block should
2705 * come first: eg. optimize IFs without ELSE...
2708 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2712 if (ontrue->generated) {
2713 stmt.opcode = INSTR_IF;
2714 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2715 code_push_statement(&stmt, instr->context.line);
2717 if (onfalse->generated) {
2718 stmt.opcode = INSTR_IFNOT;
2719 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2720 code_push_statement(&stmt, instr->context.line);
2722 if (!ontrue->generated) {
2723 if (onfalse->generated) {
2728 if (!onfalse->generated) {
2729 if (ontrue->generated) {
2734 /* neither ontrue nor onfalse exist */
2735 stmt.opcode = INSTR_IFNOT;
2736 if (!instr->likely) {
2737 /* Honor the likelyhood hint */
2738 ir_block *tmp = onfalse;
2739 stmt.opcode = INSTR_IF;
2743 stidx = vec_size(code_statements);
2744 code_push_statement(&stmt, instr->context.line);
2745 /* on false we jump, so add ontrue-path */
2746 if (!gen_blocks_recursive(func, ontrue))
2748 /* fixup the jump address */
2749 code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2750 /* generate onfalse path */
2751 if (onfalse->generated) {
2752 /* fixup the jump address */
2753 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2754 stmt.opcode = vec_last(code_statements).opcode;
2755 if (stmt.opcode == INSTR_GOTO ||
2756 stmt.opcode == INSTR_IF ||
2757 stmt.opcode == INSTR_IFNOT ||
2758 stmt.opcode == INSTR_RETURN ||
2759 stmt.opcode == INSTR_DONE)
2761 /* no use jumping from here */
2764 /* may have been generated in the previous recursive call */
2765 stmt.opcode = INSTR_GOTO;
2766 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2769 if (stmt.o1.s1 != 1)
2770 code_push_statement(&stmt, instr->context.line);
2773 /* if not, generate now */
2778 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2779 /* Trivial call translation:
2780 * copy all params to OFS_PARM*
2781 * if the output's storetype is not store_return,
2782 * add append a STORE instruction!
2784 * NOTES on how to do it better without much trouble:
2785 * -) The liferanges!
2786 * Simply check the liferange of all parameters for
2787 * other CALLs. For each param with no CALL in its
2788 * liferange, we can store it in an OFS_PARM at
2789 * generation already. This would even include later
2790 * reuse.... probably... :)
2795 first = vec_size(instr->params);
2798 for (p = 0; p < first; ++p)
2800 ir_value *param = instr->params[p];
2802 stmt.opcode = INSTR_STORE_F;
2805 if (param->vtype == TYPE_FIELD)
2806 stmt.opcode = field_store_instr[param->fieldtype];
2808 stmt.opcode = type_store_instr[param->vtype];
2809 stmt.o1.u1 = ir_value_code_addr(param);
2810 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2811 code_push_statement(&stmt, instr->context.line);
2813 /* Now handle extparams */
2814 first = vec_size(instr->params);
2815 for (; p < first; ++p)
2817 ir_builder *ir = func->owner;
2818 ir_value *param = instr->params[p];
2819 ir_value *targetparam;
2821 if (p-8 >= vec_size(ir->extparams))
2822 ir_gen_extparam(ir);
2824 targetparam = ir->extparams[p-8];
2826 stmt.opcode = INSTR_STORE_F;
2829 if (param->vtype == TYPE_FIELD)
2830 stmt.opcode = field_store_instr[param->fieldtype];
2832 stmt.opcode = type_store_instr[param->vtype];
2833 stmt.o1.u1 = ir_value_code_addr(param);
2834 stmt.o2.u1 = ir_value_code_addr(targetparam);
2835 code_push_statement(&stmt, instr->context.line);
2838 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2839 if (stmt.opcode > INSTR_CALL8)
2840 stmt.opcode = INSTR_CALL8;
2841 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2844 code_push_statement(&stmt, instr->context.line);
2846 retvalue = instr->_ops[0];
2847 if (retvalue && retvalue->store != store_return && vec_size(retvalue->life))
2849 /* not to be kept in OFS_RETURN */
2850 if (retvalue->vtype == TYPE_FIELD)
2851 stmt.opcode = field_store_instr[retvalue->vtype];
2853 stmt.opcode = type_store_instr[retvalue->vtype];
2854 stmt.o1.u1 = OFS_RETURN;
2855 stmt.o2.u1 = ir_value_code_addr(retvalue);
2857 code_push_statement(&stmt, instr->context.line);
2862 if (instr->opcode == INSTR_STATE) {
2863 irerror(block->context, "TODO: state instruction");
2867 stmt.opcode = instr->opcode;
2872 /* This is the general order of operands */
2874 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2877 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2880 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2882 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2884 stmt.o1.u1 = stmt.o3.u1;
2887 else if ((stmt.opcode >= INSTR_STORE_F &&
2888 stmt.opcode <= INSTR_STORE_FNC) ||
2889 (stmt.opcode >= INSTR_STOREP_F &&
2890 stmt.opcode <= INSTR_STOREP_FNC))
2892 /* 2-operand instructions with A -> B */
2893 stmt.o2.u1 = stmt.o3.u1;
2896 /* tiny optimization, don't output
2899 if (stmt.o2.u1 == stmt.o1.u1 &&
2900 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2902 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2907 code_push_statement(&stmt, instr->context.line);
2912 static bool gen_function_code(ir_function *self)
2915 prog_section_statement stmt;
2917 /* Starting from entry point, we generate blocks "as they come"
2918 * for now. Dead blocks will not be translated obviously.
2920 if (!vec_size(self->blocks)) {
2921 irerror(self->context, "Function '%s' declared without body.", self->name);
2925 block = self->blocks[0];
2926 if (block->generated)
2929 if (!gen_blocks_recursive(self, block)) {
2930 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2934 /* code_write and qcvm -disasm need to know that the function ends here */
2935 stmt.opcode = INSTR_DONE;
2939 code_push_statement(&stmt, vec_last(code_linenums));
2943 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2945 /* NOTE: filename pointers are copied, we never strdup them,
2946 * thus we can use pointer-comparison to find the string.
2951 for (i = 0; i < vec_size(ir->filenames); ++i) {
2952 if (ir->filenames[i] == filename)
2953 return ir->filestrings[i];
2956 str = code_genstring(filename);
2957 vec_push(ir->filenames, filename);
2958 vec_push(ir->filestrings, str);
2962 static bool gen_global_function(ir_builder *ir, ir_value *global)
2964 prog_section_function fun;
2968 #ifndef NEW_ALLOC_STRAT
2969 size_t local_var_end;
2972 if (!global->hasvalue || (!global->constval.vfunc))
2974 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2978 irfun = global->constval.vfunc;
2980 fun.name = global->code.name;
2981 fun.file = ir_builder_filestring(ir, global->context.file);
2982 fun.profile = 0; /* always 0 */
2983 fun.nargs = vec_size(irfun->params);
2987 for (i = 0;i < 8; ++i) {
2988 if ((int32_t)i >= fun.nargs)
2991 fun.argsize[i] = type_sizeof[irfun->params[i]];
2994 fun.firstlocal = vec_size(code_globals);
2996 #ifndef NEW_ALLOC_STRAT
2997 local_var_end = fun.firstlocal;
2998 for (i = 0; i < vec_size(irfun->locals); ++i) {
2999 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3000 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
3004 if (vec_size(irfun->locals)) {
3005 ir_value *last = vec_last(irfun->locals);
3006 local_var_end = last->code.globaladdr;
3007 if (last->vtype == TYPE_FIELD && last->fieldtype == TYPE_VECTOR)
3008 local_var_end += type_sizeof[TYPE_VECTOR];
3010 local_var_end += type_sizeof[last->vtype];
3012 for (i = 0; i < vec_size(irfun->values); ++i)
3014 /* generate code.globaladdr for ssa values */
3015 ir_value *v = irfun->values[i];
3016 ir_value_code_setaddr(v, local_var_end + v->code.local);
3018 for (i = 0; i < irfun->allocated_locals; ++i) {
3019 /* fill the locals with zeros */
3020 vec_push(code_globals, 0);
3023 fun.locals = vec_size(code_globals) - fun.firstlocal;
3025 fun.locals = irfun->allocated_locals;
3026 for (i = 0; i < vec_size(irfun->locals); ++i) {
3027 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3028 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
3031 ir_value_code_setaddr(irfun->locals[i], fun.firstlocal + irfun->locals[i]->code.local);
3033 for (i = vec_size(code_globals) - fun.firstlocal; i < fun.locals; ++i) {
3034 vec_push(code_globals, 0);
3036 for (i = 0; i < vec_size(irfun->values); ++i)
3038 /* generate code.globaladdr for ssa values */
3039 ir_value *v = irfun->values[i];
3040 ir_value_code_setaddr(v, fun.firstlocal + v->code.local);
3045 fun.entry = irfun->builtin+1;
3047 irfun->code_function_def = vec_size(code_functions);
3048 fun.entry = vec_size(code_statements);
3051 vec_push(code_functions, fun);
3055 static void ir_gen_extparam(ir_builder *ir)
3057 prog_section_def def;
3061 snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparams)+8));
3062 global = ir_value_var(name, store_global, TYPE_VECTOR);
3064 def.name = code_genstring(name);
3065 def.type = TYPE_VECTOR;
3066 def.offset = vec_size(code_globals);
3068 vec_push(code_defs, def);
3069 ir_value_code_setaddr(global, def.offset);
3070 vec_push(code_globals, 0);
3071 vec_push(code_globals, 0);
3072 vec_push(code_globals, 0);
3074 vec_push(ir->extparams, global);
3077 static bool gen_function_extparam_copy(ir_function *self)
3079 size_t i, ext, numparams;
3081 ir_builder *ir = self->owner;
3083 prog_section_statement stmt;
3085 numparams = vec_size(self->params);
3089 stmt.opcode = INSTR_STORE_F;
3091 for (i = 8; i < numparams; ++i) {
3093 if (ext >= vec_size(ir->extparams))
3094 ir_gen_extparam(ir);
3096 ep = ir->extparams[ext];
3098 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3099 if (self->locals[i]->vtype == TYPE_FIELD &&
3100 self->locals[i]->fieldtype == TYPE_VECTOR)
3102 stmt.opcode = INSTR_STORE_V;
3104 stmt.o1.u1 = ir_value_code_addr(ep);
3105 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3106 code_push_statement(&stmt, self->context.line);
3112 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3114 prog_section_function *fundef;
3119 irfun = global->constval.vfunc;
3121 if (global->cvq == CV_NONE) {
3122 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3123 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3125 /* this was a function pointer, don't generate code for those */
3132 if (irfun->code_function_def < 0) {
3133 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3136 fundef = &code_functions[irfun->code_function_def];
3138 fundef->entry = vec_size(code_statements);
3139 if (!gen_function_extparam_copy(irfun)) {
3140 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3143 if (!gen_function_code(irfun)) {
3144 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3150 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3154 prog_section_def def;
3156 def.type = global->vtype;
3157 def.offset = vec_size(code_globals);
3160 if (global->name[0] == '#') {
3161 if (!self->str_immediate)
3162 self->str_immediate = code_genstring("IMMEDIATE");
3163 def.name = global->code.name = self->str_immediate;
3166 def.name = global->code.name = code_genstring(global->name);
3171 switch (global->vtype)
3174 if (!strcmp(global->name, "end_sys_globals")) {
3175 /* TODO: remember this point... all the defs before this one
3176 * should be checksummed and added to progdefs.h when we generate it.
3179 else if (!strcmp(global->name, "end_sys_fields")) {
3180 /* TODO: same as above but for entity-fields rather than globsl
3184 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3186 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3187 * the system fields actually go? Though the engine knows this anyway...
3188 * Maybe this could be an -foption
3189 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3191 ir_value_code_setaddr(global, vec_size(code_globals));
3192 vec_push(code_globals, 0);
3194 vec_push(code_defs, def);
3197 vec_push(code_defs, def);
3198 return gen_global_pointer(global);
3200 vec_push(code_defs, def);
3201 return gen_global_field(global);
3206 ir_value_code_setaddr(global, vec_size(code_globals));
3207 if (global->hasvalue) {
3208 iptr = (int32_t*)&global->constval.ivec[0];
3209 vec_push(code_globals, *iptr);
3211 vec_push(code_globals, 0);
3213 if (!islocal && global->cvq != CV_CONST)
3214 def.type |= DEF_SAVEGLOBAL;
3215 vec_push(code_defs, def);
3217 return global->code.globaladdr >= 0;
3221 ir_value_code_setaddr(global, vec_size(code_globals));
3222 if (global->hasvalue) {
3223 vec_push(code_globals, code_genstring(global->constval.vstring));
3225 vec_push(code_globals, 0);
3227 if (!islocal && global->cvq != CV_CONST)
3228 def.type |= DEF_SAVEGLOBAL;
3229 vec_push(code_defs, def);
3230 return global->code.globaladdr >= 0;
3235 ir_value_code_setaddr(global, vec_size(code_globals));
3236 if (global->hasvalue) {
3237 iptr = (int32_t*)&global->constval.ivec[0];
3238 vec_push(code_globals, iptr[0]);
3239 if (global->code.globaladdr < 0)
3241 for (d = 1; d < type_sizeof[global->vtype]; ++d) {
3242 vec_push(code_globals, iptr[d]);
3245 vec_push(code_globals, 0);
3246 if (global->code.globaladdr < 0)
3248 for (d = 1; d < type_sizeof[global->vtype]; ++d) {
3249 vec_push(code_globals, 0);
3252 if (!islocal && global->cvq != CV_CONST)
3253 def.type |= DEF_SAVEGLOBAL;
3255 vec_push(code_defs, def);
3256 return global->code.globaladdr >= 0;
3259 ir_value_code_setaddr(global, vec_size(code_globals));
3260 if (!global->hasvalue) {
3261 vec_push(code_globals, 0);
3262 if (global->code.globaladdr < 0)
3265 vec_push(code_globals, vec_size(code_functions));
3266 if (!gen_global_function(self, global))
3269 if (!islocal && global->cvq != CV_CONST)
3270 def.type |= DEF_SAVEGLOBAL;
3271 vec_push(code_defs, def);
3274 /* assume biggest type */
3275 ir_value_code_setaddr(global, vec_size(code_globals));
3276 vec_push(code_globals, 0);
3277 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
3278 vec_push(code_globals, 0);
3281 /* refuse to create 'void' type or any other fancy business. */
3282 irerror(global->context, "Invalid type for global variable `%s`: %s",
3283 global->name, type_name[global->vtype]);
3288 static void ir_builder_prepare_field(ir_value *field)
3290 field->code.fieldaddr = code_alloc_field(type_sizeof[field->fieldtype]);
3293 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3295 prog_section_def def;
3296 prog_section_field fld;
3300 def.type = (uint16_t)field->vtype;
3301 def.offset = (uint16_t)vec_size(code_globals);
3303 /* create a global named the same as the field */
3304 if (opts.standard == COMPILER_GMQCC) {
3305 /* in our standard, the global gets a dot prefix */
3306 size_t len = strlen(field->name);
3309 /* we really don't want to have to allocate this, and 1024
3310 * bytes is more than enough for a variable/field name
3312 if (len+2 >= sizeof(name)) {
3313 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3318 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3321 def.name = code_genstring(name);
3322 fld.name = def.name + 1; /* we reuse that string table entry */
3324 /* in plain QC, there cannot be a global with the same name,
3325 * and so we also name the global the same.
3326 * FIXME: fteqcc should create a global as well
3327 * check if it actually uses the same name. Probably does
3329 def.name = code_genstring(field->name);
3330 fld.name = def.name;
3333 field->code.name = def.name;
3335 vec_push(code_defs, def);
3337 fld.type = field->fieldtype;
3339 if (fld.type == TYPE_VOID) {
3340 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3344 fld.offset = field->code.fieldaddr;
3346 vec_push(code_fields, fld);
3348 ir_value_code_setaddr(field, vec_size(code_globals));
3349 vec_push(code_globals, fld.offset);
3350 if (fld.type == TYPE_VECTOR) {
3351 vec_push(code_globals, fld.offset+1);
3352 vec_push(code_globals, fld.offset+2);
3355 return field->code.globaladdr >= 0;
3358 bool ir_builder_generate(ir_builder *self, const char *filename)
3360 prog_section_statement stmt;
3362 char *lnofile = NULL;
3366 for (i = 0; i < vec_size(self->fields); ++i)
3368 ir_builder_prepare_field(self->fields[i]);
3371 for (i = 0; i < vec_size(self->globals); ++i)
3373 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3378 for (i = 0; i < vec_size(self->fields); ++i)
3380 if (!ir_builder_gen_field(self, self->fields[i])) {
3385 /* generate function code */
3386 for (i = 0; i < vec_size(self->globals); ++i)
3388 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3389 if (!gen_global_function_code(self, self->globals[i])) {
3395 if (vec_size(code_globals) >= 65536) {
3396 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3400 /* DP errors if the last instruction is not an INSTR_DONE. */
3401 if (vec_last(code_statements).opcode != INSTR_DONE)
3403 stmt.opcode = INSTR_DONE;
3407 code_push_statement(&stmt, vec_last(code_linenums));
3413 if (vec_size(code_statements) != vec_size(code_linenums)) {
3414 con_err("Linecounter wrong: %lu != %lu\n",
3415 (unsigned long)vec_size(code_statements),
3416 (unsigned long)vec_size(code_linenums));
3417 } else if (OPTS_FLAG(LNO)) {
3419 size_t filelen = strlen(filename);
3421 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3422 dot = strrchr(lnofile, '.');
3426 vec_shrinkto(lnofile, dot - lnofile);
3428 memcpy(vec_add(lnofile, 5), ".lno", 5);
3432 con_out("writing '%s' and '%s'...\n", filename, lnofile);
3434 con_out("writing '%s'\n", filename);
3435 if (!code_write(filename, lnofile)) {
3443 /***********************************************************************
3444 *IR DEBUG Dump functions...
3447 #define IND_BUFSZ 1024
3450 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3453 const char *qc_opname(int op)
3455 if (op < 0) return "<INVALID>";
3456 if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3457 return asm_instr[op].m;
3459 case VINSTR_PHI: return "PHI";
3460 case VINSTR_JUMP: return "JUMP";
3461 case VINSTR_COND: return "COND";
3462 default: return "<UNK>";
3466 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3469 char indent[IND_BUFSZ];
3473 oprintf("module %s\n", b->name);
3474 for (i = 0; i < vec_size(b->globals); ++i)
3477 if (b->globals[i]->hasvalue)
3478 oprintf("%s = ", b->globals[i]->name);
3479 ir_value_dump(b->globals[i], oprintf);
3482 for (i = 0; i < vec_size(b->functions); ++i)
3483 ir_function_dump(b->functions[i], indent, oprintf);
3484 oprintf("endmodule %s\n", b->name);
3487 void ir_function_dump(ir_function *f, char *ind,
3488 int (*oprintf)(const char*, ...))
3491 if (f->builtin != 0) {
3492 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3495 oprintf("%sfunction %s\n", ind, f->name);
3496 strncat(ind, "\t", IND_BUFSZ);
3497 if (vec_size(f->locals))
3499 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3500 for (i = 0; i < vec_size(f->locals); ++i) {
3501 oprintf("%s\t", ind);
3502 ir_value_dump(f->locals[i], oprintf);
3506 oprintf("%sliferanges:\n", ind);
3507 for (i = 0; i < vec_size(f->locals); ++i) {
3509 ir_value *v = f->locals[i];
3510 oprintf("%s\t%s: %s@%i ", ind, v->name, (v->unique_life ? "unique " : ""), (int)v->code.local);
3511 for (l = 0; l < vec_size(v->life); ++l) {
3512 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3516 for (i = 0; i < vec_size(f->values); ++i) {
3518 ir_value *v = f->values[i];
3519 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3520 for (l = 0; l < vec_size(v->life); ++l) {
3521 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3525 if (vec_size(f->blocks))
3527 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3528 for (i = 0; i < vec_size(f->blocks); ++i) {
3529 if (f->blocks[i]->run_id != f->run_id) {
3530 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3532 ir_block_dump(f->blocks[i], ind, oprintf);
3536 ind[strlen(ind)-1] = 0;
3537 oprintf("%sendfunction %s\n", ind, f->name);
3540 void ir_block_dump(ir_block* b, char *ind,
3541 int (*oprintf)(const char*, ...))
3544 oprintf("%s:%s\n", ind, b->label);
3545 strncat(ind, "\t", IND_BUFSZ);
3547 for (i = 0; i < vec_size(b->instr); ++i)
3548 ir_instr_dump(b->instr[i], ind, oprintf);
3549 ind[strlen(ind)-1] = 0;
3552 void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3555 oprintf("%s <- phi ", in->_ops[0]->name);
3556 for (i = 0; i < vec_size(in->phi); ++i)
3558 oprintf("([%s] : %s) ", in->phi[i].from->label,
3559 in->phi[i].value->name);
3564 void ir_instr_dump(ir_instr *in, char *ind,
3565 int (*oprintf)(const char*, ...))
3568 const char *comma = NULL;
3570 oprintf("%s (%i) ", ind, (int)in->eid);
3572 if (in->opcode == VINSTR_PHI) {
3573 dump_phi(in, oprintf);
3577 strncat(ind, "\t", IND_BUFSZ);
3579 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3580 ir_value_dump(in->_ops[0], oprintf);
3581 if (in->_ops[1] || in->_ops[2])
3584 if (in->opcode == INSTR_CALL0) {
3585 oprintf("CALL%i\t", vec_size(in->params));
3587 oprintf("%s\t", qc_opname(in->opcode));
3589 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3590 ir_value_dump(in->_ops[0], oprintf);
3595 for (i = 1; i != 3; ++i) {
3599 ir_value_dump(in->_ops[i], oprintf);
3607 oprintf("[%s]", in->bops[0]->label);
3611 oprintf("%s[%s]", comma, in->bops[1]->label);
3612 if (vec_size(in->params)) {
3613 oprintf("\tparams: ");
3614 for (i = 0; i != vec_size(in->params); ++i) {
3615 oprintf("%s, ", in->params[i]->name);
3619 ind[strlen(ind)-1] = 0;
3622 void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3625 for (; *str; ++str) {
3627 case '\n': oprintf("\\n"); break;
3628 case '\r': oprintf("\\r"); break;
3629 case '\t': oprintf("\\t"); break;
3630 case '\v': oprintf("\\v"); break;
3631 case '\f': oprintf("\\f"); break;
3632 case '\b': oprintf("\\b"); break;
3633 case '\a': oprintf("\\a"); break;
3634 case '\\': oprintf("\\\\"); break;
3635 case '"': oprintf("\\\""); break;
3636 default: oprintf("%c", *str); break;
3642 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3651 oprintf("fn:%s", v->name);
3654 oprintf("%g", v->constval.vfloat);
3657 oprintf("'%g %g %g'",
3660 v->constval.vvec.z);
3663 oprintf("(entity)");
3666 ir_value_dump_string(v->constval.vstring, oprintf);
3670 oprintf("%i", v->constval.vint);
3675 v->constval.vpointer->name);
3679 oprintf("%s", v->name);
3683 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3686 oprintf("Life of %12s:", self->name);
3687 for (i = 0; i < vec_size(self->life); ++i)
3689 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);