2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 /***********************************************************************
31 * Type sizes used at multiple points in the IR codegen
34 const char *type_name[TYPE_COUNT] = {
53 static size_t type_sizeof_[TYPE_COUNT] = {
60 1, /* TYPE_FUNCTION */
71 const uint16_t type_store_instr[TYPE_COUNT] = {
72 INSTR_STORE_F, /* should use I when having integer support */
79 INSTR_STORE_ENT, /* should use I */
81 INSTR_STORE_I, /* integer type */
86 INSTR_STORE_V, /* variant, should never be accessed */
88 VINSTR_END, /* struct */
89 VINSTR_END, /* union */
90 VINSTR_END, /* array */
92 VINSTR_END, /* noexpr */
95 const uint16_t field_store_instr[TYPE_COUNT] = {
105 INSTR_STORE_FLD, /* integer type */
110 INSTR_STORE_V, /* variant, should never be accessed */
112 VINSTR_END, /* struct */
113 VINSTR_END, /* union */
114 VINSTR_END, /* array */
115 VINSTR_END, /* nil */
116 VINSTR_END, /* noexpr */
119 const uint16_t type_storep_instr[TYPE_COUNT] = {
120 INSTR_STOREP_F, /* should use I when having integer support */
127 INSTR_STOREP_ENT, /* should use I */
129 INSTR_STOREP_ENT, /* integer type */
134 INSTR_STOREP_V, /* variant, should never be accessed */
136 VINSTR_END, /* struct */
137 VINSTR_END, /* union */
138 VINSTR_END, /* array */
139 VINSTR_END, /* nil */
140 VINSTR_END, /* noexpr */
143 const uint16_t type_eq_instr[TYPE_COUNT] = {
144 INSTR_EQ_F, /* should use I when having integer support */
149 INSTR_EQ_E, /* FLD has no comparison */
151 INSTR_EQ_E, /* should use I */
158 INSTR_EQ_V, /* variant, should never be accessed */
160 VINSTR_END, /* struct */
161 VINSTR_END, /* union */
162 VINSTR_END, /* array */
163 VINSTR_END, /* nil */
164 VINSTR_END, /* noexpr */
167 const uint16_t type_ne_instr[TYPE_COUNT] = {
168 INSTR_NE_F, /* should use I when having integer support */
173 INSTR_NE_E, /* FLD has no comparison */
175 INSTR_NE_E, /* should use I */
182 INSTR_NE_V, /* variant, should never be accessed */
184 VINSTR_END, /* struct */
185 VINSTR_END, /* union */
186 VINSTR_END, /* array */
187 VINSTR_END, /* nil */
188 VINSTR_END, /* noexpr */
191 const uint16_t type_not_instr[TYPE_COUNT] = {
192 INSTR_NOT_F, /* should use I when having integer support */
193 VINSTR_END, /* not to be used, depends on string related -f flags */
199 INSTR_NOT_ENT, /* should use I */
201 INSTR_NOT_I, /* integer type */
206 INSTR_NOT_V, /* variant, should never be accessed */
208 VINSTR_END, /* struct */
209 VINSTR_END, /* union */
210 VINSTR_END, /* array */
211 VINSTR_END, /* nil */
212 VINSTR_END, /* noexpr */
216 static ir_value* ir_value_var(const char *name, int st, int vtype);
217 static bool ir_value_set_name(ir_value*, const char *name);
218 static void ir_value_dump(ir_value*, int (*oprintf)(const char*,...));
220 static ir_value* ir_gen_extparam_proto(ir_builder *ir);
221 static void ir_gen_extparam (ir_builder *ir);
223 static bool ir_builder_set_name(ir_builder *self, const char *name);
225 static ir_function* ir_function_new(struct ir_builder_s *owner, int returntype);
226 static bool ir_function_set_name(ir_function*, const char *name);
227 static void ir_function_delete(ir_function*);
228 static void ir_function_dump(ir_function*, char *ind, int (*oprintf)(const char*,...));
230 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t, const char *label,
231 int op, ir_value *a, ir_value *b, int outype);
232 static void ir_block_delete(ir_block*);
233 static ir_block* ir_block_new(struct ir_function_s *owner, const char *label);
234 static bool GMQCC_WARN ir_block_create_store(ir_block*, lex_ctx_t, ir_value *target, ir_value *what);
235 static bool ir_block_set_label(ir_block*, const char *label);
236 static void ir_block_dump(ir_block*, char *ind, int (*oprintf)(const char*,...));
238 static bool ir_instr_op(ir_instr*, int op, ir_value *value, bool writing);
239 static void ir_instr_delete(ir_instr*);
240 static void ir_instr_dump(ir_instr* in, char *ind, int (*oprintf)(const char*,...));
241 /* error functions */
243 static void irerror(lex_ctx_t ctx, const char *msg, ...)
247 con_cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
251 static bool irwarning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
256 r = vcompile_warning(ctx, warntype, fmt, ap);
261 /***********************************************************************
262 * Vector utility functions
265 static bool GMQCC_WARN vec_ir_value_find(ir_value **vec, const ir_value *what, size_t *idx)
268 size_t len = vec_size(vec);
269 for (i = 0; i < len; ++i) {
270 if (vec[i] == what) {
278 static bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
281 size_t len = vec_size(vec);
282 for (i = 0; i < len; ++i) {
283 if (vec[i] == what) {
291 static bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
294 size_t len = vec_size(vec);
295 for (i = 0; i < len; ++i) {
296 if (vec[i] == what) {
304 /***********************************************************************
308 static void ir_block_delete_quick(ir_block* self);
309 static void ir_instr_delete_quick(ir_instr *self);
310 static void ir_function_delete_quick(ir_function *self);
312 ir_builder* ir_builder_new(const char *modulename)
317 self = (ir_builder*)mem_a(sizeof(*self));
321 self->functions = NULL;
322 self->globals = NULL;
324 self->filenames = NULL;
325 self->filestrings = NULL;
326 self->htglobals = util_htnew(IR_HT_SIZE);
327 self->htfields = util_htnew(IR_HT_SIZE);
328 self->htfunctions = util_htnew(IR_HT_SIZE);
330 self->extparams = NULL;
331 self->extparam_protos = NULL;
333 self->first_common_globaltemp = 0;
334 self->max_globaltemps = 0;
335 self->first_common_local = 0;
336 self->max_locals = 0;
338 self->str_immediate = 0;
340 if (!ir_builder_set_name(self, modulename)) {
345 self->nil = ir_value_var("nil", store_value, TYPE_NIL);
346 self->nil->cvq = CV_CONST;
348 for (i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
349 /* we write to them, but they're not supposed to be used outside the IR, so
350 * let's not allow the generation of ir_instrs which use these.
351 * So it's a constant noexpr.
353 self->vinstr_temp[i] = ir_value_var("vinstr_temp", store_value, TYPE_NOEXPR);
354 self->vinstr_temp[i]->cvq = CV_CONST;
357 self->reserved_va_count = NULL;
358 self->code = code_init();
363 void ir_builder_delete(ir_builder* self)
366 util_htdel(self->htglobals);
367 util_htdel(self->htfields);
368 util_htdel(self->htfunctions);
369 mem_d((void*)self->name);
370 for (i = 0; i != vec_size(self->functions); ++i) {
371 ir_function_delete_quick(self->functions[i]);
373 vec_free(self->functions);
374 for (i = 0; i != vec_size(self->extparams); ++i) {
375 ir_value_delete(self->extparams[i]);
377 vec_free(self->extparams);
378 vec_free(self->extparam_protos);
379 for (i = 0; i != vec_size(self->globals); ++i) {
380 ir_value_delete(self->globals[i]);
382 vec_free(self->globals);
383 for (i = 0; i != vec_size(self->fields); ++i) {
384 ir_value_delete(self->fields[i]);
386 ir_value_delete(self->nil);
387 for (i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
388 ir_value_delete(self->vinstr_temp[i]);
390 vec_free(self->fields);
391 vec_free(self->filenames);
392 vec_free(self->filestrings);
394 code_cleanup(self->code);
398 bool ir_builder_set_name(ir_builder *self, const char *name)
401 mem_d((void*)self->name);
402 self->name = util_strdup(name);
406 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
408 return (ir_function*)util_htget(self->htfunctions, name);
411 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
413 ir_function *fn = ir_builder_get_function(self, name);
418 fn = ir_function_new(self, outtype);
419 if (!ir_function_set_name(fn, name))
421 ir_function_delete(fn);
424 vec_push(self->functions, fn);
425 util_htset(self->htfunctions, name, fn);
427 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
429 ir_function_delete(fn);
433 fn->value->hasvalue = true;
434 fn->value->outtype = outtype;
435 fn->value->constval.vfunc = fn;
436 fn->value->context = fn->context;
441 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
443 return (ir_value*)util_htget(self->htglobals, name);
446 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
452 ve = ir_builder_get_global(self, name);
458 ve = ir_value_var(name, store_global, vtype);
459 vec_push(self->globals, ve);
460 util_htset(self->htglobals, name, ve);
464 ir_value* ir_builder_get_va_count(ir_builder *self)
466 if (self->reserved_va_count)
467 return self->reserved_va_count;
468 return (self->reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
471 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
473 return (ir_value*)util_htget(self->htfields, name);
477 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
479 ir_value *ve = ir_builder_get_field(self, name);
484 ve = ir_value_var(name, store_global, TYPE_FIELD);
485 ve->fieldtype = vtype;
486 vec_push(self->fields, ve);
487 util_htset(self->htfields, name, ve);
491 /***********************************************************************
495 static bool ir_function_naive_phi(ir_function*);
496 static void ir_function_enumerate(ir_function*);
497 static bool ir_function_calculate_liferanges(ir_function*);
498 static bool ir_function_allocate_locals(ir_function*);
500 ir_function* ir_function_new(ir_builder* owner, int outtype)
503 self = (ir_function*)mem_a(sizeof(*self));
508 memset(self, 0, sizeof(*self));
511 if (!ir_function_set_name(self, "<@unnamed>")) {
518 self->context.file = "<@no context>";
519 self->context.line = 0;
520 self->outtype = outtype;
529 self->max_varargs = 0;
531 self->code_function_def = -1;
532 self->allocated_locals = 0;
533 self->globaltemps = 0;
539 bool ir_function_set_name(ir_function *self, const char *name)
542 mem_d((void*)self->name);
543 self->name = util_strdup(name);
547 static void ir_function_delete_quick(ir_function *self)
550 mem_d((void*)self->name);
552 for (i = 0; i != vec_size(self->blocks); ++i)
553 ir_block_delete_quick(self->blocks[i]);
554 vec_free(self->blocks);
556 vec_free(self->params);
558 for (i = 0; i != vec_size(self->values); ++i)
559 ir_value_delete(self->values[i]);
560 vec_free(self->values);
562 for (i = 0; i != vec_size(self->locals); ++i)
563 ir_value_delete(self->locals[i]);
564 vec_free(self->locals);
566 /* self->value is deleted by the builder */
571 void ir_function_delete(ir_function *self)
574 mem_d((void*)self->name);
576 for (i = 0; i != vec_size(self->blocks); ++i)
577 ir_block_delete(self->blocks[i]);
578 vec_free(self->blocks);
580 vec_free(self->params);
582 for (i = 0; i != vec_size(self->values); ++i)
583 ir_value_delete(self->values[i]);
584 vec_free(self->values);
586 for (i = 0; i != vec_size(self->locals); ++i)
587 ir_value_delete(self->locals[i]);
588 vec_free(self->locals);
590 /* self->value is deleted by the builder */
595 static void ir_function_collect_value(ir_function *self, ir_value *v)
597 vec_push(self->values, v);
600 ir_block* ir_function_create_block(lex_ctx_t ctx, ir_function *self, const char *label)
602 ir_block* bn = ir_block_new(self, label);
604 vec_push(self->blocks, bn);
608 static bool instr_is_operation(uint16_t op)
610 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
611 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
612 (op == INSTR_ADDRESS) ||
613 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
614 (op >= INSTR_AND && op <= INSTR_BITOR) ||
615 (op >= INSTR_CALL0 && op <= INSTR_CALL8) );
618 static bool ir_function_pass_peephole(ir_function *self)
622 for (b = 0; b < vec_size(self->blocks); ++b) {
624 ir_block *block = self->blocks[b];
626 for (i = 0; i < vec_size(block->instr); ++i) {
628 inst = block->instr[i];
631 (inst->opcode >= INSTR_STORE_F &&
632 inst->opcode <= INSTR_STORE_FNC))
640 oper = block->instr[i-1];
641 if (!instr_is_operation(oper->opcode))
644 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
645 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
647 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
651 value = oper->_ops[0];
653 /* only do it for SSA values */
654 if (value->store != store_value)
657 /* don't optimize out the temp if it's used later again */
658 if (vec_size(value->reads) != 1)
661 /* The very next store must use this value */
662 if (value->reads[0] != store)
665 /* And of course the store must _read_ from it, so it's in
667 if (store->_ops[1] != value)
670 ++opts_optimizationcount[OPTIM_PEEPHOLE];
671 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
673 vec_remove(block->instr, i, 1);
674 ir_instr_delete(store);
676 else if (inst->opcode == VINSTR_COND)
678 /* COND on a value resulting from a NOT could
679 * remove the NOT and swap its operands
686 value = inst->_ops[0];
688 if (value->store != store_value ||
689 vec_size(value->reads) != 1 ||
690 value->reads[0] != inst)
695 inot = value->writes[0];
696 if (inot->_ops[0] != value ||
697 inot->opcode < INSTR_NOT_F ||
698 inot->opcode > INSTR_NOT_FNC ||
699 inot->opcode == INSTR_NOT_V || /* can't do these */
700 inot->opcode == INSTR_NOT_S)
706 ++opts_optimizationcount[OPTIM_PEEPHOLE];
708 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
711 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
712 if (tmp->instr[inotid] == inot)
715 if (inotid >= vec_size(tmp->instr)) {
716 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
719 vec_remove(tmp->instr, inotid, 1);
720 ir_instr_delete(inot);
721 /* swap ontrue/onfalse */
723 inst->bops[0] = inst->bops[1];
734 static bool ir_function_pass_tailrecursion(ir_function *self)
738 for (b = 0; b < vec_size(self->blocks); ++b) {
740 ir_instr *ret, *call, *store = NULL;
741 ir_block *block = self->blocks[b];
743 if (!block->final || vec_size(block->instr) < 2)
746 ret = block->instr[vec_size(block->instr)-1];
747 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
750 call = block->instr[vec_size(block->instr)-2];
751 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
752 /* account for the unoptimized
754 * STORE %return, %tmp
758 if (vec_size(block->instr) < 3)
762 call = block->instr[vec_size(block->instr)-3];
765 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
769 /* optimize out the STORE */
771 ret->_ops[0] == store->_ops[0] &&
772 store->_ops[1] == call->_ops[0])
774 ++opts_optimizationcount[OPTIM_PEEPHOLE];
775 call->_ops[0] = store->_ops[0];
776 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
777 ir_instr_delete(store);
786 funcval = call->_ops[1];
789 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
792 /* now we have a CALL and a RET, check if it's a tailcall */
793 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
796 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
797 vec_shrinkby(block->instr, 2);
799 block->final = false; /* open it back up */
801 /* emite parameter-stores */
802 for (p = 0; p < vec_size(call->params); ++p) {
803 /* assert(call->params_count <= self->locals_count); */
804 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
805 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
809 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
810 irerror(call->context, "failed to create tailcall jump");
814 ir_instr_delete(call);
815 ir_instr_delete(ret);
821 bool ir_function_finalize(ir_function *self)
828 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
829 if (!ir_function_pass_peephole(self)) {
830 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
835 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
836 if (!ir_function_pass_tailrecursion(self)) {
837 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
842 if (!ir_function_naive_phi(self)) {
843 irerror(self->context, "internal error: ir_function_naive_phi failed");
847 for (i = 0; i < vec_size(self->locals); ++i) {
848 ir_value *v = self->locals[i];
849 if (v->vtype == TYPE_VECTOR ||
850 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
852 ir_value_vector_member(v, 0);
853 ir_value_vector_member(v, 1);
854 ir_value_vector_member(v, 2);
857 for (i = 0; i < vec_size(self->values); ++i) {
858 ir_value *v = self->values[i];
859 if (v->vtype == TYPE_VECTOR ||
860 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
862 ir_value_vector_member(v, 0);
863 ir_value_vector_member(v, 1);
864 ir_value_vector_member(v, 2);
868 ir_function_enumerate(self);
870 if (!ir_function_calculate_liferanges(self))
872 if (!ir_function_allocate_locals(self))
877 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
882 vec_size(self->locals) &&
883 self->locals[vec_size(self->locals)-1]->store != store_param) {
884 irerror(self->context, "cannot add parameters after adding locals");
888 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
891 vec_push(self->locals, ve);
895 /***********************************************************************
899 ir_block* ir_block_new(ir_function* owner, const char *name)
902 self = (ir_block*)mem_a(sizeof(*self));
906 memset(self, 0, sizeof(*self));
909 if (name && !ir_block_set_label(self, name)) {
914 self->context.file = "<@no context>";
915 self->context.line = 0;
919 self->entries = NULL;
923 self->is_return = false;
927 self->generated = false;
932 static void ir_block_delete_quick(ir_block* self)
935 if (self->label) mem_d(self->label);
936 for (i = 0; i != vec_size(self->instr); ++i)
937 ir_instr_delete_quick(self->instr[i]);
938 vec_free(self->instr);
939 vec_free(self->entries);
940 vec_free(self->exits);
941 vec_free(self->living);
945 void ir_block_delete(ir_block* self)
948 if (self->label) mem_d(self->label);
949 for (i = 0; i != vec_size(self->instr); ++i)
950 ir_instr_delete(self->instr[i]);
951 vec_free(self->instr);
952 vec_free(self->entries);
953 vec_free(self->exits);
954 vec_free(self->living);
958 bool ir_block_set_label(ir_block *self, const char *name)
961 mem_d((void*)self->label);
962 self->label = util_strdup(name);
963 return !!self->label;
966 /***********************************************************************
970 static ir_instr* ir_instr_new(lex_ctx_t ctx, ir_block* owner, int op)
973 self = (ir_instr*)mem_a(sizeof(*self));
980 self->_ops[0] = NULL;
981 self->_ops[1] = NULL;
982 self->_ops[2] = NULL;
983 self->bops[0] = NULL;
984 self->bops[1] = NULL;
995 static void ir_instr_delete_quick(ir_instr *self)
998 vec_free(self->params);
1002 static void ir_instr_delete(ir_instr *self)
1005 /* The following calls can only delete from
1006 * vectors, we still want to delete this instruction
1007 * so ignore the return value. Since with the warn_unused_result attribute
1008 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
1009 * I have to improvise here and use if(foo());
1011 for (i = 0; i < vec_size(self->phi); ++i) {
1013 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
1014 vec_remove(self->phi[i].value->writes, idx, 1);
1015 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
1016 vec_remove(self->phi[i].value->reads, idx, 1);
1018 vec_free(self->phi);
1019 for (i = 0; i < vec_size(self->params); ++i) {
1021 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
1022 vec_remove(self->params[i]->writes, idx, 1);
1023 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
1024 vec_remove(self->params[i]->reads, idx, 1);
1026 vec_free(self->params);
1027 (void)!ir_instr_op(self, 0, NULL, false);
1028 (void)!ir_instr_op(self, 1, NULL, false);
1029 (void)!ir_instr_op(self, 2, NULL, false);
1033 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
1035 if (v && v->vtype == TYPE_NOEXPR) {
1036 irerror(self->context, "tried to use a NOEXPR value");
1040 if (self->_ops[op]) {
1042 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1043 vec_remove(self->_ops[op]->writes, idx, 1);
1044 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1045 vec_remove(self->_ops[op]->reads, idx, 1);
1049 vec_push(v->writes, self);
1051 vec_push(v->reads, self);
1057 /***********************************************************************
1061 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1063 self->code.globaladdr = gaddr;
1064 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1065 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1066 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1069 static int32_t ir_value_code_addr(const ir_value *self)
1071 if (self->store == store_return)
1072 return OFS_RETURN + self->code.addroffset;
1073 return self->code.globaladdr + self->code.addroffset;
1076 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1079 self = (ir_value*)mem_a(sizeof(*self));
1080 self->vtype = vtype;
1081 self->fieldtype = TYPE_VOID;
1082 self->outtype = TYPE_VOID;
1083 self->store = storetype;
1087 self->writes = NULL;
1089 self->cvq = CV_NONE;
1090 self->hasvalue = false;
1091 self->context.file = "<@no context>";
1092 self->context.line = 0;
1094 if (name && !ir_value_set_name(self, name)) {
1095 irerror(self->context, "out of memory");
1100 memset(&self->constval, 0, sizeof(self->constval));
1101 memset(&self->code, 0, sizeof(self->code));
1103 self->members[0] = NULL;
1104 self->members[1] = NULL;
1105 self->members[2] = NULL;
1106 self->memberof = NULL;
1108 self->unique_life = false;
1109 self->locked = false;
1110 self->callparam = false;
1116 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1124 if (self->members[member])
1125 return self->members[member];
1128 len = strlen(self->name);
1129 name = (char*)mem_a(len + 3);
1130 memcpy(name, self->name, len);
1132 name[len+1] = 'x' + member;
1138 if (self->vtype == TYPE_VECTOR)
1140 m = ir_value_var(name, self->store, TYPE_FLOAT);
1145 m->context = self->context;
1147 self->members[member] = m;
1148 m->code.addroffset = member;
1150 else if (self->vtype == TYPE_FIELD)
1152 if (self->fieldtype != TYPE_VECTOR)
1154 m = ir_value_var(name, self->store, TYPE_FIELD);
1159 m->fieldtype = TYPE_FLOAT;
1160 m->context = self->context;
1162 self->members[member] = m;
1163 m->code.addroffset = member;
1167 irerror(self->context, "invalid member access on %s", self->name);
1175 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1177 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1178 return type_sizeof_[TYPE_VECTOR];
1179 return type_sizeof_[self->vtype];
1182 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1184 ir_value *v = ir_value_var(name, storetype, vtype);
1187 ir_function_collect_value(owner, v);
1191 void ir_value_delete(ir_value* self)
1195 mem_d((void*)self->name);
1198 if (self->vtype == TYPE_STRING)
1199 mem_d((void*)self->constval.vstring);
1201 for (i = 0; i < 3; ++i) {
1202 if (self->members[i])
1203 ir_value_delete(self->members[i]);
1205 vec_free(self->reads);
1206 vec_free(self->writes);
1207 vec_free(self->life);
1211 bool ir_value_set_name(ir_value *self, const char *name)
1214 mem_d((void*)self->name);
1215 self->name = util_strdup(name);
1216 return !!self->name;
1219 bool ir_value_set_float(ir_value *self, float f)
1221 if (self->vtype != TYPE_FLOAT)
1223 self->constval.vfloat = f;
1224 self->hasvalue = true;
1228 bool ir_value_set_func(ir_value *self, int f)
1230 if (self->vtype != TYPE_FUNCTION)
1232 self->constval.vint = f;
1233 self->hasvalue = true;
1237 bool ir_value_set_vector(ir_value *self, vec3_t v)
1239 if (self->vtype != TYPE_VECTOR)
1241 self->constval.vvec = v;
1242 self->hasvalue = true;
1246 bool ir_value_set_field(ir_value *self, ir_value *fld)
1248 if (self->vtype != TYPE_FIELD)
1250 self->constval.vpointer = fld;
1251 self->hasvalue = true;
1255 bool ir_value_set_string(ir_value *self, const char *str)
1257 if (self->vtype != TYPE_STRING)
1259 self->constval.vstring = util_strdupe(str);
1260 self->hasvalue = true;
1265 bool ir_value_set_int(ir_value *self, int i)
1267 if (self->vtype != TYPE_INTEGER)
1269 self->constval.vint = i;
1270 self->hasvalue = true;
1275 bool ir_value_lives(ir_value *self, size_t at)
1278 for (i = 0; i < vec_size(self->life); ++i)
1280 ir_life_entry_t *life = &self->life[i];
1281 if (life->start <= at && at <= life->end)
1283 if (life->start > at) /* since it's ordered */
1289 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1292 vec_push(self->life, e);
1293 for (k = vec_size(self->life)-1; k > idx; --k)
1294 self->life[k] = self->life[k-1];
1295 self->life[idx] = e;
1299 static bool ir_value_life_merge(ir_value *self, size_t s)
1302 const size_t vs = vec_size(self->life);
1303 ir_life_entry_t *life = NULL;
1304 ir_life_entry_t *before = NULL;
1305 ir_life_entry_t new_entry;
1307 /* Find the first range >= s */
1308 for (i = 0; i < vs; ++i)
1311 life = &self->life[i];
1312 if (life->start > s)
1315 /* nothing found? append */
1318 if (life && life->end+1 == s)
1320 /* previous life range can be merged in */
1324 if (life && life->end >= s)
1326 e.start = e.end = s;
1327 vec_push(self->life, e);
1333 if (before->end + 1 == s &&
1334 life->start - 1 == s)
1337 before->end = life->end;
1338 vec_remove(self->life, i, 1);
1341 if (before->end + 1 == s)
1347 /* already contained */
1348 if (before->end >= s)
1352 if (life->start - 1 == s)
1357 /* insert a new entry */
1358 new_entry.start = new_entry.end = s;
1359 return ir_value_life_insert(self, i, new_entry);
1362 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1366 if (!vec_size(other->life))
1369 if (!vec_size(self->life)) {
1370 size_t count = vec_size(other->life);
1371 ir_life_entry_t *life = vec_add(self->life, count);
1372 memcpy(life, other->life, count * sizeof(*life));
1377 for (i = 0; i < vec_size(other->life); ++i)
1379 const ir_life_entry_t *life = &other->life[i];
1382 ir_life_entry_t *entry = &self->life[myi];
1384 if (life->end+1 < entry->start)
1386 /* adding an interval before entry */
1387 if (!ir_value_life_insert(self, myi, *life))
1393 if (life->start < entry->start &&
1394 life->end+1 >= entry->start)
1396 /* starts earlier and overlaps */
1397 entry->start = life->start;
1400 if (life->end > entry->end &&
1401 life->start <= entry->end+1)
1403 /* ends later and overlaps */
1404 entry->end = life->end;
1407 /* see if our change combines it with the next ranges */
1408 while (myi+1 < vec_size(self->life) &&
1409 entry->end+1 >= self->life[1+myi].start)
1411 /* overlaps with (myi+1) */
1412 if (entry->end < self->life[1+myi].end)
1413 entry->end = self->life[1+myi].end;
1414 vec_remove(self->life, myi+1, 1);
1415 entry = &self->life[myi];
1418 /* see if we're after the entry */
1419 if (life->start > entry->end)
1422 /* append if we're at the end */
1423 if (myi >= vec_size(self->life)) {
1424 vec_push(self->life, *life);
1427 /* otherweise check the next range */
1436 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1438 /* For any life entry in A see if it overlaps with
1439 * any life entry in B.
1440 * Note that the life entries are orderes, so we can make a
1441 * more efficient algorithm there than naively translating the
1445 ir_life_entry_t *la, *lb, *enda, *endb;
1447 /* first of all, if either has no life range, they cannot clash */
1448 if (!vec_size(a->life) || !vec_size(b->life))
1453 enda = la + vec_size(a->life);
1454 endb = lb + vec_size(b->life);
1457 /* check if the entries overlap, for that,
1458 * both must start before the other one ends.
1460 if (la->start < lb->end &&
1461 lb->start < la->end)
1466 /* entries are ordered
1467 * one entry is earlier than the other
1468 * that earlier entry will be moved forward
1470 if (la->start < lb->start)
1472 /* order: A B, move A forward
1473 * check if we hit the end with A
1478 else /* if (lb->start < la->start) actually <= */
1480 /* order: B A, move B forward
1481 * check if we hit the end with B
1490 /***********************************************************************
1494 static bool ir_check_unreachable(ir_block *self)
1496 /* The IR should never have to deal with unreachable code */
1497 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1499 irerror(self->context, "unreachable statement (%s)", self->label);
1503 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1506 if (!ir_check_unreachable(self))
1509 if (target->store == store_value &&
1510 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1512 irerror(self->context, "cannot store to an SSA value");
1513 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1514 irerror(self->context, "instruction: %s", util_instr_str[op]);
1518 in = ir_instr_new(ctx, self, op);
1522 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1523 !ir_instr_op(in, 1, what, false))
1525 ir_instr_delete(in);
1528 vec_push(self->instr, in);
1532 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1536 if (target->vtype == TYPE_VARIANT)
1537 vtype = what->vtype;
1539 vtype = target->vtype;
1542 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1543 op = INSTR_CONV_ITOF;
1544 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1545 op = INSTR_CONV_FTOI;
1547 op = type_store_instr[vtype];
1549 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1550 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1554 return ir_block_create_store_op(self, ctx, op, target, what);
1557 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1562 if (target->vtype != TYPE_POINTER)
1565 /* storing using pointer - target is a pointer, type must be
1566 * inferred from source
1568 vtype = what->vtype;
1570 op = type_storep_instr[vtype];
1571 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1572 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1573 op = INSTR_STOREP_V;
1576 return ir_block_create_store_op(self, ctx, op, target, what);
1579 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1582 if (!ir_check_unreachable(self))
1585 self->is_return = true;
1586 in = ir_instr_new(ctx, self, INSTR_RETURN);
1590 if (v && !ir_instr_op(in, 0, v, false)) {
1591 ir_instr_delete(in);
1595 vec_push(self->instr, in);
1599 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1600 ir_block *ontrue, ir_block *onfalse)
1603 if (!ir_check_unreachable(self))
1606 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1607 in = ir_instr_new(ctx, self, VINSTR_COND);
1611 if (!ir_instr_op(in, 0, v, false)) {
1612 ir_instr_delete(in);
1616 in->bops[0] = ontrue;
1617 in->bops[1] = onfalse;
1619 vec_push(self->instr, in);
1621 vec_push(self->exits, ontrue);
1622 vec_push(self->exits, onfalse);
1623 vec_push(ontrue->entries, self);
1624 vec_push(onfalse->entries, self);
1628 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1631 if (!ir_check_unreachable(self))
1634 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1639 vec_push(self->instr, in);
1641 vec_push(self->exits, to);
1642 vec_push(to->entries, self);
1646 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1648 self->owner->flags |= IR_FLAG_HAS_GOTO;
1649 return ir_block_create_jump(self, ctx, to);
1652 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, int ot)
1656 if (!ir_check_unreachable(self))
1658 in = ir_instr_new(ctx, self, VINSTR_PHI);
1661 out = ir_value_out(self->owner, label, store_value, ot);
1663 ir_instr_delete(in);
1666 if (!ir_instr_op(in, 0, out, true)) {
1667 ir_instr_delete(in);
1668 ir_value_delete(out);
1671 vec_push(self->instr, in);
1675 ir_value* ir_phi_value(ir_instr *self)
1677 return self->_ops[0];
1680 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1684 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1685 /* Must not be possible to cause this, otherwise the AST
1686 * is doing something wrong.
1688 irerror(self->context, "Invalid entry block for PHI");
1694 vec_push(v->reads, self);
1695 vec_push(self->phi, pe);
1698 /* call related code */
1699 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1703 if (!ir_check_unreachable(self))
1705 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1710 self->is_return = true;
1712 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1714 ir_instr_delete(in);
1717 if (!ir_instr_op(in, 0, out, true) ||
1718 !ir_instr_op(in, 1, func, false))
1720 ir_instr_delete(in);
1721 ir_value_delete(out);
1724 vec_push(self->instr, in);
1727 if (!ir_block_create_return(self, ctx, NULL)) {
1728 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1729 ir_instr_delete(in);
1737 ir_value* ir_call_value(ir_instr *self)
1739 return self->_ops[0];
1742 void ir_call_param(ir_instr* self, ir_value *v)
1744 vec_push(self->params, v);
1745 vec_push(v->reads, self);
1748 /* binary op related code */
1750 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1751 const char *label, int opcode,
1752 ir_value *left, ir_value *right)
1774 case INSTR_SUB_S: /* -- offset of string as float */
1779 case INSTR_BITOR_IF:
1780 case INSTR_BITOR_FI:
1781 case INSTR_BITAND_FI:
1782 case INSTR_BITAND_IF:
1797 case INSTR_BITAND_I:
1800 case INSTR_RSHIFT_I:
1801 case INSTR_LSHIFT_I:
1822 * after the following default case, the value of opcode can never
1823 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1827 /* boolean operations result in floats */
1830 * opcode >= 10 takes true branch opcode is at least 10
1831 * opcode <= 23 takes false branch opcode is at least 24
1833 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1837 * At condition "opcode <= 23", the value of "opcode" must be
1839 * At condition "opcode <= 23", the value of "opcode" cannot be
1840 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1841 * The condition "opcode <= 23" cannot be true.
1843 * Thus ot=2 (TYPE_FLOAT) can never be true
1846 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1848 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1853 if (ot == TYPE_VOID) {
1854 /* The AST or parser were supposed to check this! */
1858 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1861 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1862 const char *label, int opcode,
1865 int ot = TYPE_FLOAT;
1877 /* QC doesn't have other unary operations. We expect extensions to fill
1878 * the above list, otherwise we assume out-type = in-type, eg for an
1882 ot = operand->vtype;
1885 if (ot == TYPE_VOID) {
1886 /* The AST or parser were supposed to check this! */
1890 /* let's use the general instruction creator and pass NULL for OPB */
1891 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1894 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1895 int op, ir_value *a, ir_value *b, int outype)
1900 out = ir_value_out(self->owner, label, store_value, outype);
1904 instr = ir_instr_new(ctx, self, op);
1906 ir_value_delete(out);
1910 if (!ir_instr_op(instr, 0, out, true) ||
1911 !ir_instr_op(instr, 1, a, false) ||
1912 !ir_instr_op(instr, 2, b, false) )
1917 vec_push(self->instr, instr);
1921 ir_instr_delete(instr);
1922 ir_value_delete(out);
1926 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1930 /* Support for various pointer types todo if so desired */
1931 if (ent->vtype != TYPE_ENTITY)
1934 if (field->vtype != TYPE_FIELD)
1937 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1938 v->fieldtype = field->fieldtype;
1942 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field, int outype)
1945 if (ent->vtype != TYPE_ENTITY)
1948 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1949 if (field->vtype != TYPE_FIELD)
1954 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1955 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1956 case TYPE_STRING: op = INSTR_LOAD_S; break;
1957 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1958 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1959 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1961 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1962 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1965 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1969 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1972 /* PHI resolving breaks the SSA, and must thus be the last
1973 * step before life-range calculation.
1976 static bool ir_block_naive_phi(ir_block *self);
1977 bool ir_function_naive_phi(ir_function *self)
1981 for (i = 0; i < vec_size(self->blocks); ++i)
1983 if (!ir_block_naive_phi(self->blocks[i]))
1989 static bool ir_block_naive_phi(ir_block *self)
1991 size_t i, p; /*, w;*/
1992 /* FIXME: optionally, create_phi can add the phis
1993 * to a list so we don't need to loop through blocks
1994 * - anyway: "don't optimize YET"
1996 for (i = 0; i < vec_size(self->instr); ++i)
1998 ir_instr *instr = self->instr[i];
1999 if (instr->opcode != VINSTR_PHI)
2002 vec_remove(self->instr, i, 1);
2003 --i; /* NOTE: i+1 below */
2005 for (p = 0; p < vec_size(instr->phi); ++p)
2007 ir_value *v = instr->phi[p].value;
2008 ir_block *b = instr->phi[p].from;
2010 if (v->store == store_value &&
2011 vec_size(v->reads) == 1 &&
2012 vec_size(v->writes) == 1)
2014 /* replace the value */
2015 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2020 /* force a move instruction */
2021 ir_instr *prevjump = vec_last(b->instr);
2024 instr->_ops[0]->store = store_global;
2025 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2027 instr->_ops[0]->store = store_value;
2028 vec_push(b->instr, prevjump);
2032 ir_instr_delete(instr);
2037 /***********************************************************************
2038 *IR Temp allocation code
2039 * Propagating value life ranges by walking through the function backwards
2040 * until no more changes are made.
2041 * In theory this should happen once more than once for every nested loop
2043 * Though this implementation might run an additional time for if nests.
2046 /* Enumerate instructions used by value's life-ranges
2048 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2052 for (i = 0; i < vec_size(self->instr); ++i)
2054 self->instr[i]->eid = eid++;
2059 /* Enumerate blocks and instructions.
2060 * The block-enumeration is unordered!
2061 * We do not really use the block enumreation, however
2062 * the instruction enumeration is important for life-ranges.
2064 void ir_function_enumerate(ir_function *self)
2067 size_t instruction_id = 0;
2068 for (i = 0; i < vec_size(self->blocks); ++i)
2070 /* each block now gets an additional "entry" instruction id
2071 * we can use to avoid point-life issues
2073 self->blocks[i]->entry_id = instruction_id;
2076 self->blocks[i]->eid = i;
2077 ir_block_enumerate(self->blocks[i], &instruction_id);
2081 /* Local-value allocator
2082 * After finishing creating the liferange of all values used in a function
2083 * we can allocate their global-positions.
2084 * This is the counterpart to register-allocation in register machines.
2091 } function_allocator;
2093 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2096 size_t vsize = ir_value_sizeof(var);
2098 var->code.local = vec_size(alloc->locals);
2100 slot = ir_value_var("reg", store_global, var->vtype);
2104 if (!ir_value_life_merge_into(slot, var))
2107 vec_push(alloc->locals, slot);
2108 vec_push(alloc->sizes, vsize);
2109 vec_push(alloc->unique, var->unique_life);
2114 ir_value_delete(slot);
2118 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2124 return function_allocator_alloc(alloc, v);
2126 for (a = 0; a < vec_size(alloc->locals); ++a)
2128 /* if it's reserved for a unique liferange: skip */
2129 if (alloc->unique[a])
2132 slot = alloc->locals[a];
2134 /* never resize parameters
2135 * will be required later when overlapping temps + locals
2137 if (a < vec_size(self->params) &&
2138 alloc->sizes[a] < ir_value_sizeof(v))
2143 if (ir_values_overlap(v, slot))
2146 if (!ir_value_life_merge_into(slot, v))
2149 /* adjust size for this slot */
2150 if (alloc->sizes[a] < ir_value_sizeof(v))
2151 alloc->sizes[a] = ir_value_sizeof(v);
2156 if (a >= vec_size(alloc->locals)) {
2157 if (!function_allocator_alloc(alloc, v))
2163 bool ir_function_allocate_locals(ir_function *self)
2168 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2172 function_allocator lockalloc, globalloc;
2174 if (!vec_size(self->locals) && !vec_size(self->values))
2177 globalloc.locals = NULL;
2178 globalloc.sizes = NULL;
2179 globalloc.positions = NULL;
2180 globalloc.unique = NULL;
2181 lockalloc.locals = NULL;
2182 lockalloc.sizes = NULL;
2183 lockalloc.positions = NULL;
2184 lockalloc.unique = NULL;
2186 for (i = 0; i < vec_size(self->locals); ++i)
2188 v = self->locals[i];
2189 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2191 v->unique_life = true;
2193 else if (i >= vec_size(self->params))
2196 v->locked = true; /* lock parameters locals */
2197 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2200 for (; i < vec_size(self->locals); ++i)
2202 v = self->locals[i];
2203 if (!vec_size(v->life))
2205 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2209 /* Allocate a slot for any value that still exists */
2210 for (i = 0; i < vec_size(self->values); ++i)
2212 v = self->values[i];
2214 if (!vec_size(v->life))
2217 /* CALL optimization:
2218 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2219 * and it's not "locked", write it to the OFS_PARM directly.
2221 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2222 if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2223 (v->reads[0]->opcode == VINSTR_NRCALL ||
2224 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2229 ir_instr *call = v->reads[0];
2230 if (!vec_ir_value_find(call->params, v, ¶m)) {
2231 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2234 ++opts_optimizationcount[OPTIM_CALL_STORES];
2235 v->callparam = true;
2237 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2239 size_t nprotos = vec_size(self->owner->extparam_protos);
2242 if (nprotos > param)
2243 ep = self->owner->extparam_protos[param];
2246 ep = ir_gen_extparam_proto(self->owner);
2247 while (++nprotos <= param)
2248 ep = ir_gen_extparam_proto(self->owner);
2250 ir_instr_op(v->writes[0], 0, ep, true);
2251 call->params[param+8] = ep;
2255 if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2257 v->store = store_return;
2258 if (v->members[0]) v->members[0]->store = store_return;
2259 if (v->members[1]) v->members[1]->store = store_return;
2260 if (v->members[2]) v->members[2]->store = store_return;
2261 ++opts_optimizationcount[OPTIM_CALL_STORES];
2266 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2270 if (!lockalloc.sizes && !globalloc.sizes) {
2273 vec_push(lockalloc.positions, 0);
2274 vec_push(globalloc.positions, 0);
2276 /* Adjust slot positions based on sizes */
2277 if (lockalloc.sizes) {
2278 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2279 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2281 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2282 vec_push(lockalloc.positions, pos);
2284 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2286 if (globalloc.sizes) {
2287 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2288 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2290 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2291 vec_push(globalloc.positions, pos);
2293 self->globaltemps = pos + vec_last(globalloc.sizes);
2296 /* Locals need to know their new position */
2297 for (i = 0; i < vec_size(self->locals); ++i) {
2298 v = self->locals[i];
2299 if (v->locked || !opt_gt)
2300 v->code.local = lockalloc.positions[v->code.local];
2302 v->code.local = globalloc.positions[v->code.local];
2304 /* Take over the actual slot positions on values */
2305 for (i = 0; i < vec_size(self->values); ++i) {
2306 v = self->values[i];
2307 if (v->locked || !opt_gt)
2308 v->code.local = lockalloc.positions[v->code.local];
2310 v->code.local = globalloc.positions[v->code.local];
2318 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2319 ir_value_delete(lockalloc.locals[i]);
2320 for (i = 0; i < vec_size(globalloc.locals); ++i)
2321 ir_value_delete(globalloc.locals[i]);
2322 vec_free(globalloc.unique);
2323 vec_free(globalloc.locals);
2324 vec_free(globalloc.sizes);
2325 vec_free(globalloc.positions);
2326 vec_free(lockalloc.unique);
2327 vec_free(lockalloc.locals);
2328 vec_free(lockalloc.sizes);
2329 vec_free(lockalloc.positions);
2333 /* Get information about which operand
2334 * is read from, or written to.
2336 static void ir_op_read_write(int op, size_t *read, size_t *write)
2356 case INSTR_STOREP_F:
2357 case INSTR_STOREP_V:
2358 case INSTR_STOREP_S:
2359 case INSTR_STOREP_ENT:
2360 case INSTR_STOREP_FLD:
2361 case INSTR_STOREP_FNC:
2372 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2375 const size_t vs = vec_size(self->living);
2376 bool changed = false;
2377 for (i = 0; i != vs; ++i)
2379 if (ir_value_life_merge(self->living[i], eid))
2385 static bool ir_block_living_lock(ir_block *self)
2388 bool changed = false;
2389 for (i = 0; i != vec_size(self->living); ++i)
2391 if (!self->living[i]->locked) {
2392 self->living[i]->locked = true;
2399 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2403 size_t i, o, p, mem, cnt;
2404 /* bitmasks which operands are read from or written to */
2411 vec_free(self->living);
2413 p = vec_size(self->exits);
2414 for (i = 0; i < p; ++i) {
2415 ir_block *prev = self->exits[i];
2416 cnt = vec_size(prev->living);
2417 for (o = 0; o < cnt; ++o) {
2418 if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2419 vec_push(self->living, prev->living[o]);
2423 i = vec_size(self->instr);
2426 instr = self->instr[i];
2428 /* See which operands are read and write operands */
2429 ir_op_read_write(instr->opcode, &read, &write);
2431 /* Go through the 3 main operands
2432 * writes first, then reads
2434 for (o = 0; o < 3; ++o)
2436 if (!instr->_ops[o]) /* no such operand */
2439 value = instr->_ops[o];
2441 /* We only care about locals */
2442 /* we also calculate parameter liferanges so that locals
2443 * can take up parameter slots */
2444 if (value->store != store_value &&
2445 value->store != store_local &&
2446 value->store != store_param)
2449 /* write operands */
2450 /* When we write to a local, we consider it "dead" for the
2451 * remaining upper part of the function, since in SSA a value
2452 * can only be written once (== created)
2457 bool in_living = vec_ir_value_find(self->living, value, &idx);
2460 /* If the value isn't alive it hasn't been read before... */
2461 /* TODO: See if the warning can be emitted during parsing or AST processing
2462 * otherwise have warning printed here.
2463 * IF printing a warning here: include filecontext_t,
2464 * and make sure it's only printed once
2465 * since this function is run multiple times.
2467 /* con_err( "Value only written %s\n", value->name); */
2468 if (ir_value_life_merge(value, instr->eid))
2471 /* since 'living' won't contain it
2472 * anymore, merge the value, since
2475 if (ir_value_life_merge(value, instr->eid))
2478 vec_remove(self->living, idx, 1);
2480 /* Removing a vector removes all members */
2481 for (mem = 0; mem < 3; ++mem) {
2482 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2483 if (ir_value_life_merge(value->members[mem], instr->eid))
2485 vec_remove(self->living, idx, 1);
2488 /* Removing the last member removes the vector */
2489 if (value->memberof) {
2490 value = value->memberof;
2491 for (mem = 0; mem < 3; ++mem) {
2492 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2495 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2496 if (ir_value_life_merge(value, instr->eid))
2498 vec_remove(self->living, idx, 1);
2504 if (instr->opcode == INSTR_MUL_VF)
2506 value = instr->_ops[2];
2507 /* the float source will get an additional lifetime */
2508 if (ir_value_life_merge(value, instr->eid+1))
2510 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2513 else if (instr->opcode == INSTR_MUL_FV || instr->opcode == INSTR_LOAD_V)
2515 value = instr->_ops[1];
2516 /* the float source will get an additional lifetime */
2517 if (ir_value_life_merge(value, instr->eid+1))
2519 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2523 for (o = 0; o < 3; ++o)
2525 if (!instr->_ops[o]) /* no such operand */
2528 value = instr->_ops[o];
2530 /* We only care about locals */
2531 /* we also calculate parameter liferanges so that locals
2532 * can take up parameter slots */
2533 if (value->store != store_value &&
2534 value->store != store_local &&
2535 value->store != store_param)
2541 if (!vec_ir_value_find(self->living, value, NULL))
2542 vec_push(self->living, value);
2543 /* reading adds the full vector */
2544 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2545 vec_push(self->living, value->memberof);
2546 for (mem = 0; mem < 3; ++mem) {
2547 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2548 vec_push(self->living, value->members[mem]);
2552 /* PHI operands are always read operands */
2553 for (p = 0; p < vec_size(instr->phi); ++p)
2555 value = instr->phi[p].value;
2556 if (!vec_ir_value_find(self->living, value, NULL))
2557 vec_push(self->living, value);
2558 /* reading adds the full vector */
2559 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2560 vec_push(self->living, value->memberof);
2561 for (mem = 0; mem < 3; ++mem) {
2562 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2563 vec_push(self->living, value->members[mem]);
2567 /* on a call, all these values must be "locked" */
2568 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2569 if (ir_block_living_lock(self))
2572 /* call params are read operands too */
2573 for (p = 0; p < vec_size(instr->params); ++p)
2575 value = instr->params[p];
2576 if (!vec_ir_value_find(self->living, value, NULL))
2577 vec_push(self->living, value);
2578 /* reading adds the full vector */
2579 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2580 vec_push(self->living, value->memberof);
2581 for (mem = 0; mem < 3; ++mem) {
2582 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2583 vec_push(self->living, value->members[mem]);
2588 if (ir_block_living_add_instr(self, instr->eid))
2591 /* the "entry" instruction ID */
2592 if (ir_block_living_add_instr(self, self->entry_id))
2598 bool ir_function_calculate_liferanges(ir_function *self)
2603 /* parameters live at 0 */
2604 for (i = 0; i < vec_size(self->params); ++i)
2605 if (!ir_value_life_merge(self->locals[i], 0))
2606 compile_error(self->context, "internal error: failed value-life merging");
2611 i = vec_size(self->blocks);
2613 ir_block_life_propagate(self->blocks[i], &changed);
2617 if (vec_size(self->blocks)) {
2618 ir_block *block = self->blocks[0];
2619 for (i = 0; i < vec_size(block->living); ++i) {
2620 ir_value *v = block->living[i];
2621 if (v->store != store_local)
2623 if (v->vtype == TYPE_VECTOR)
2625 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2626 /* find the instruction reading from it */
2627 for (s = 0; s < vec_size(v->reads); ++s) {
2628 if (v->reads[s]->eid == v->life[0].end)
2631 if (s < vec_size(v->reads)) {
2632 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2633 "variable `%s` may be used uninitialized in this function\n"
2636 v->reads[s]->context.file, v->reads[s]->context.line)
2644 ir_value *vec = v->memberof;
2645 for (s = 0; s < vec_size(vec->reads); ++s) {
2646 if (vec->reads[s]->eid == v->life[0].end)
2649 if (s < vec_size(vec->reads)) {
2650 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2651 "variable `%s` may be used uninitialized in this function\n"
2654 vec->reads[s]->context.file, vec->reads[s]->context.line)
2662 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2663 "variable `%s` may be used uninitialized in this function", v->name))
2672 /***********************************************************************
2675 * Since the IR has the convention of putting 'write' operands
2676 * at the beginning, we have to rotate the operands of instructions
2677 * properly in order to generate valid QCVM code.
2679 * Having destinations at a fixed position is more convenient. In QC
2680 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2681 * read from from OPA, and store to OPB rather than OPC. Which is
2682 * partially the reason why the implementation of these instructions
2683 * in darkplaces has been delayed for so long.
2685 * Breaking conventions is annoying...
2687 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2689 static bool gen_global_field(code_t *code, ir_value *global)
2691 if (global->hasvalue)
2693 ir_value *fld = global->constval.vpointer;
2695 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2699 /* copy the field's value */
2700 ir_value_code_setaddr(global, vec_size(code->globals));
2701 vec_push(code->globals, fld->code.fieldaddr);
2702 if (global->fieldtype == TYPE_VECTOR) {
2703 vec_push(code->globals, fld->code.fieldaddr+1);
2704 vec_push(code->globals, fld->code.fieldaddr+2);
2709 ir_value_code_setaddr(global, vec_size(code->globals));
2710 vec_push(code->globals, 0);
2711 if (global->fieldtype == TYPE_VECTOR) {
2712 vec_push(code->globals, 0);
2713 vec_push(code->globals, 0);
2716 if (global->code.globaladdr < 0)
2721 static bool gen_global_pointer(code_t *code, ir_value *global)
2723 if (global->hasvalue)
2725 ir_value *target = global->constval.vpointer;
2727 irerror(global->context, "Invalid pointer constant: %s", global->name);
2728 /* NULL pointers are pointing to the NULL constant, which also
2729 * sits at address 0, but still has an ir_value for itself.
2734 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2735 * void() foo; <- proto
2736 * void() *fooptr = &foo;
2737 * void() foo = { code }
2739 if (!target->code.globaladdr) {
2740 /* FIXME: Check for the constant nullptr ir_value!
2741 * because then code.globaladdr being 0 is valid.
2743 irerror(global->context, "FIXME: Relocation support");
2747 ir_value_code_setaddr(global, vec_size(code->globals));
2748 vec_push(code->globals, target->code.globaladdr);
2752 ir_value_code_setaddr(global, vec_size(code->globals));
2753 vec_push(code->globals, 0);
2755 if (global->code.globaladdr < 0)
2760 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2762 prog_section_statement_t stmt;
2770 block->generated = true;
2771 block->code_start = vec_size(code->statements);
2772 for (i = 0; i < vec_size(block->instr); ++i)
2774 instr = block->instr[i];
2776 if (instr->opcode == VINSTR_PHI) {
2777 irerror(block->context, "cannot generate virtual instruction (phi)");
2781 if (instr->opcode == VINSTR_JUMP) {
2782 target = instr->bops[0];
2783 /* for uncoditional jumps, if the target hasn't been generated
2784 * yet, we generate them right here.
2786 if (!target->generated)
2787 return gen_blocks_recursive(code, func, target);
2789 /* otherwise we generate a jump instruction */
2790 stmt.opcode = INSTR_GOTO;
2791 stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2794 if (stmt.o1.s1 != 1)
2795 code_push_statement(code, &stmt, instr->context.line);
2797 /* no further instructions can be in this block */
2801 if (instr->opcode == VINSTR_COND) {
2802 ontrue = instr->bops[0];
2803 onfalse = instr->bops[1];
2804 /* TODO: have the AST signal which block should
2805 * come first: eg. optimize IFs without ELSE...
2808 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2812 if (ontrue->generated) {
2813 stmt.opcode = INSTR_IF;
2814 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
2815 if (stmt.o2.s1 != 1)
2816 code_push_statement(code, &stmt, instr->context.line);
2818 if (onfalse->generated) {
2819 stmt.opcode = INSTR_IFNOT;
2820 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
2821 if (stmt.o2.s1 != 1)
2822 code_push_statement(code, &stmt, instr->context.line);
2824 if (!ontrue->generated) {
2825 if (onfalse->generated)
2826 return gen_blocks_recursive(code, func, ontrue);
2828 if (!onfalse->generated) {
2829 if (ontrue->generated)
2830 return gen_blocks_recursive(code, func, onfalse);
2832 /* neither ontrue nor onfalse exist */
2833 stmt.opcode = INSTR_IFNOT;
2834 if (!instr->likely) {
2835 /* Honor the likelyhood hint */
2836 ir_block *tmp = onfalse;
2837 stmt.opcode = INSTR_IF;
2841 stidx = vec_size(code->statements);
2842 code_push_statement(code, &stmt, instr->context.line);
2843 /* on false we jump, so add ontrue-path */
2844 if (!gen_blocks_recursive(code, func, ontrue))
2846 /* fixup the jump address */
2847 code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
2848 /* generate onfalse path */
2849 if (onfalse->generated) {
2850 /* fixup the jump address */
2851 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2852 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2853 code->statements[stidx] = code->statements[stidx+1];
2854 if (code->statements[stidx].o1.s1 < 0)
2855 code->statements[stidx].o1.s1++;
2856 code_pop_statement(code);
2858 stmt.opcode = vec_last(code->statements).opcode;
2859 if (stmt.opcode == INSTR_GOTO ||
2860 stmt.opcode == INSTR_IF ||
2861 stmt.opcode == INSTR_IFNOT ||
2862 stmt.opcode == INSTR_RETURN ||
2863 stmt.opcode == INSTR_DONE)
2865 /* no use jumping from here */
2868 /* may have been generated in the previous recursive call */
2869 stmt.opcode = INSTR_GOTO;
2870 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
2873 if (stmt.o1.s1 != 1)
2874 code_push_statement(code, &stmt, instr->context.line);
2877 else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2878 code->statements[stidx] = code->statements[stidx+1];
2879 if (code->statements[stidx].o1.s1 < 0)
2880 code->statements[stidx].o1.s1++;
2881 code_pop_statement(code);
2883 /* if not, generate now */
2884 return gen_blocks_recursive(code, func, onfalse);
2887 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2888 || instr->opcode == VINSTR_NRCALL)
2893 first = vec_size(instr->params);
2896 for (p = 0; p < first; ++p)
2898 ir_value *param = instr->params[p];
2899 if (param->callparam)
2902 stmt.opcode = INSTR_STORE_F;
2905 if (param->vtype == TYPE_FIELD)
2906 stmt.opcode = field_store_instr[param->fieldtype];
2907 else if (param->vtype == TYPE_NIL)
2908 stmt.opcode = INSTR_STORE_V;
2910 stmt.opcode = type_store_instr[param->vtype];
2911 stmt.o1.u1 = ir_value_code_addr(param);
2912 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2913 code_push_statement(code, &stmt, instr->context.line);
2915 /* Now handle extparams */
2916 first = vec_size(instr->params);
2917 for (; p < first; ++p)
2919 ir_builder *ir = func->owner;
2920 ir_value *param = instr->params[p];
2921 ir_value *targetparam;
2923 if (param->callparam)
2926 if (p-8 >= vec_size(ir->extparams))
2927 ir_gen_extparam(ir);
2929 targetparam = ir->extparams[p-8];
2931 stmt.opcode = INSTR_STORE_F;
2934 if (param->vtype == TYPE_FIELD)
2935 stmt.opcode = field_store_instr[param->fieldtype];
2936 else if (param->vtype == TYPE_NIL)
2937 stmt.opcode = INSTR_STORE_V;
2939 stmt.opcode = type_store_instr[param->vtype];
2940 stmt.o1.u1 = ir_value_code_addr(param);
2941 stmt.o2.u1 = ir_value_code_addr(targetparam);
2942 code_push_statement(code, &stmt, instr->context.line);
2945 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2946 if (stmt.opcode > INSTR_CALL8)
2947 stmt.opcode = INSTR_CALL8;
2948 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2951 code_push_statement(code, &stmt, instr->context.line);
2953 retvalue = instr->_ops[0];
2954 if (retvalue && retvalue->store != store_return &&
2955 (retvalue->store == store_global || vec_size(retvalue->life)))
2957 /* not to be kept in OFS_RETURN */
2958 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2959 stmt.opcode = field_store_instr[retvalue->fieldtype];
2961 stmt.opcode = type_store_instr[retvalue->vtype];
2962 stmt.o1.u1 = OFS_RETURN;
2963 stmt.o2.u1 = ir_value_code_addr(retvalue);
2965 code_push_statement(code, &stmt, instr->context.line);
2970 if (instr->opcode == INSTR_STATE) {
2971 irerror(block->context, "TODO: state instruction");
2975 stmt.opcode = instr->opcode;
2980 /* This is the general order of operands */
2982 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2985 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2988 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2990 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2992 stmt.o1.u1 = stmt.o3.u1;
2995 else if ((stmt.opcode >= INSTR_STORE_F &&
2996 stmt.opcode <= INSTR_STORE_FNC) ||
2997 (stmt.opcode >= INSTR_STOREP_F &&
2998 stmt.opcode <= INSTR_STOREP_FNC))
3000 /* 2-operand instructions with A -> B */
3001 stmt.o2.u1 = stmt.o3.u1;
3004 /* tiny optimization, don't output
3007 if (stmt.o2.u1 == stmt.o1.u1 &&
3008 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
3010 ++opts_optimizationcount[OPTIM_PEEPHOLE];
3015 code_push_statement(code, &stmt, instr->context.line);
3020 static bool gen_function_code(code_t *code, ir_function *self)
3023 prog_section_statement_t stmt, *retst;
3025 /* Starting from entry point, we generate blocks "as they come"
3026 * for now. Dead blocks will not be translated obviously.
3028 if (!vec_size(self->blocks)) {
3029 irerror(self->context, "Function '%s' declared without body.", self->name);
3033 block = self->blocks[0];
3034 if (block->generated)
3037 if (!gen_blocks_recursive(code, self, block)) {
3038 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3042 /* code_write and qcvm -disasm need to know that the function ends here */
3043 retst = &vec_last(code->statements);
3044 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3045 self->outtype == TYPE_VOID &&
3046 retst->opcode == INSTR_RETURN &&
3047 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3049 retst->opcode = INSTR_DONE;
3050 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3052 stmt.opcode = INSTR_DONE;
3056 code_push_statement(code, &stmt, vec_last(code->linenums));
3061 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3063 /* NOTE: filename pointers are copied, we never strdup them,
3064 * thus we can use pointer-comparison to find the string.
3069 for (i = 0; i < vec_size(ir->filenames); ++i) {
3070 if (ir->filenames[i] == filename)
3071 return ir->filestrings[i];
3074 str = code_genstring(ir->code, filename);
3075 vec_push(ir->filenames, filename);
3076 vec_push(ir->filestrings, str);
3080 static bool gen_global_function(ir_builder *ir, ir_value *global)
3082 prog_section_function_t fun;
3087 if (!global->hasvalue || (!global->constval.vfunc))
3089 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3093 irfun = global->constval.vfunc;
3095 fun.name = global->code.name;
3096 fun.file = ir_builder_filestring(ir, global->context.file);
3097 fun.profile = 0; /* always 0 */
3098 fun.nargs = vec_size(irfun->params);
3102 for (i = 0;i < 8; ++i) {
3103 if ((int32_t)i >= fun.nargs)
3106 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3110 fun.locals = irfun->allocated_locals;
3113 fun.entry = irfun->builtin+1;
3115 irfun->code_function_def = vec_size(ir->code->functions);
3116 fun.entry = vec_size(ir->code->statements);
3119 vec_push(ir->code->functions, fun);
3123 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3128 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3129 global = ir_value_var(name, store_global, TYPE_VECTOR);
3131 vec_push(ir->extparam_protos, global);
3135 static void ir_gen_extparam(ir_builder *ir)
3137 prog_section_def_t def;
3140 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3141 global = ir_gen_extparam_proto(ir);
3143 global = ir->extparam_protos[vec_size(ir->extparams)];
3145 def.name = code_genstring(ir->code, global->name);
3146 def.type = TYPE_VECTOR;
3147 def.offset = vec_size(ir->code->globals);
3149 vec_push(ir->code->defs, def);
3151 ir_value_code_setaddr(global, def.offset);
3153 vec_push(ir->code->globals, 0);
3154 vec_push(ir->code->globals, 0);
3155 vec_push(ir->code->globals, 0);
3157 vec_push(ir->extparams, global);
3160 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3162 size_t i, ext, numparams;
3164 ir_builder *ir = self->owner;
3166 prog_section_statement_t stmt;
3168 numparams = vec_size(self->params);
3172 stmt.opcode = INSTR_STORE_F;
3174 for (i = 8; i < numparams; ++i) {
3176 if (ext >= vec_size(ir->extparams))
3177 ir_gen_extparam(ir);
3179 ep = ir->extparams[ext];
3181 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3182 if (self->locals[i]->vtype == TYPE_FIELD &&
3183 self->locals[i]->fieldtype == TYPE_VECTOR)
3185 stmt.opcode = INSTR_STORE_V;
3187 stmt.o1.u1 = ir_value_code_addr(ep);
3188 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3189 code_push_statement(code, &stmt, self->context.line);
3195 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3197 size_t i, ext, numparams, maxparams;
3199 ir_builder *ir = self->owner;
3201 prog_section_statement_t stmt;
3203 numparams = vec_size(self->params);
3207 stmt.opcode = INSTR_STORE_V;
3209 maxparams = numparams + self->max_varargs;
3210 for (i = numparams; i < maxparams; ++i) {
3212 stmt.o1.u1 = OFS_PARM0 + 3*i;
3213 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3214 code_push_statement(code, &stmt, self->context.line);
3218 while (ext >= vec_size(ir->extparams))
3219 ir_gen_extparam(ir);
3221 ep = ir->extparams[ext];
3223 stmt.o1.u1 = ir_value_code_addr(ep);
3224 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3225 code_push_statement(code, &stmt, self->context.line);
3231 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3233 prog_section_function_t *def;
3236 uint32_t firstlocal, firstglobal;
3238 irfun = global->constval.vfunc;
3239 def = ir->code->functions + irfun->code_function_def;
3241 if (OPTS_OPTION_BOOL(OPTION_G) ||
3242 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3243 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3245 firstlocal = def->firstlocal = vec_size(ir->code->globals);
3247 firstlocal = def->firstlocal = ir->first_common_local;
3248 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3251 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3253 for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3254 vec_push(ir->code->globals, 0);
3255 for (i = 0; i < vec_size(irfun->locals); ++i) {
3256 ir_value *v = irfun->locals[i];
3257 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3258 ir_value_code_setaddr(v, firstlocal + v->code.local);
3259 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3260 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3265 ir_value_code_setaddr(v, firstglobal + v->code.local);
3267 for (i = 0; i < vec_size(irfun->values); ++i)
3269 ir_value *v = irfun->values[i];
3273 ir_value_code_setaddr(v, firstlocal + v->code.local);
3275 ir_value_code_setaddr(v, firstglobal + v->code.local);
3280 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3282 prog_section_function_t *fundef;
3287 irfun = global->constval.vfunc;
3289 if (global->cvq == CV_NONE) {
3290 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3291 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3293 /* this was a function pointer, don't generate code for those */
3300 if (irfun->code_function_def < 0) {
3301 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3304 fundef = &ir->code->functions[irfun->code_function_def];
3306 fundef->entry = vec_size(ir->code->statements);
3307 if (!gen_function_locals(ir, global)) {
3308 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3311 if (!gen_function_extparam_copy(ir->code, irfun)) {
3312 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3315 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3316 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3319 if (!gen_function_code(ir->code, irfun)) {
3320 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3326 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3331 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3334 def.type = TYPE_FLOAT;
3338 component = (char*)mem_a(len+3);
3339 memcpy(component, name, len);
3341 component[len-0] = 0;
3342 component[len-2] = '_';
3344 component[len-1] = 'x';
3346 for (i = 0; i < 3; ++i) {
3347 def.name = code_genstring(code, component);
3348 vec_push(code->defs, def);
3356 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3361 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3364 fld.type = TYPE_FLOAT;
3368 component = (char*)mem_a(len+3);
3369 memcpy(component, name, len);
3371 component[len-0] = 0;
3372 component[len-2] = '_';
3374 component[len-1] = 'x';
3376 for (i = 0; i < 3; ++i) {
3377 fld.name = code_genstring(code, component);
3378 vec_push(code->fields, fld);
3386 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3390 prog_section_def_t def;
3391 bool pushdef = opts.optimizeoff;
3393 def.type = global->vtype;
3394 def.offset = vec_size(self->code->globals);
3396 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3400 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3401 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3402 (global->name[0] == '#' || global->cvq == CV_CONST))
3408 if (global->name[0] == '#') {
3409 if (!self->str_immediate)
3410 self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3411 def.name = global->code.name = self->str_immediate;
3414 def.name = global->code.name = code_genstring(self->code, global->name);
3419 def.offset = ir_value_code_addr(global);
3420 vec_push(self->code->defs, def);
3421 if (global->vtype == TYPE_VECTOR)
3422 gen_vector_defs(self->code, def, global->name);
3423 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3424 gen_vector_defs(self->code, def, global->name);
3431 switch (global->vtype)
3434 if (!strcmp(global->name, "end_sys_globals")) {
3435 /* TODO: remember this point... all the defs before this one
3436 * should be checksummed and added to progdefs.h when we generate it.
3439 else if (!strcmp(global->name, "end_sys_fields")) {
3440 /* TODO: same as above but for entity-fields rather than globsl
3444 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3446 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3447 * the system fields actually go? Though the engine knows this anyway...
3448 * Maybe this could be an -foption
3449 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3451 ir_value_code_setaddr(global, vec_size(self->code->globals));
3452 vec_push(self->code->globals, 0);
3454 if (pushdef) vec_push(self->code->defs, def);
3457 if (pushdef) vec_push(self->code->defs, def);
3458 return gen_global_pointer(self->code, global);
3461 vec_push(self->code->defs, def);
3462 if (global->fieldtype == TYPE_VECTOR)
3463 gen_vector_defs(self->code, def, global->name);
3465 return gen_global_field(self->code, global);
3470 ir_value_code_setaddr(global, vec_size(self->code->globals));
3471 if (global->hasvalue) {
3472 iptr = (int32_t*)&global->constval.ivec[0];
3473 vec_push(self->code->globals, *iptr);
3475 vec_push(self->code->globals, 0);
3477 if (!islocal && global->cvq != CV_CONST)
3478 def.type |= DEF_SAVEGLOBAL;
3479 if (pushdef) vec_push(self->code->defs, def);
3481 return global->code.globaladdr >= 0;
3485 ir_value_code_setaddr(global, vec_size(self->code->globals));
3486 if (global->hasvalue) {
3487 uint32_t load = code_genstring(self->code, global->constval.vstring);
3488 vec_push(self->code->globals, load);
3490 vec_push(self->code->globals, 0);
3492 if (!islocal && global->cvq != CV_CONST)
3493 def.type |= DEF_SAVEGLOBAL;
3494 if (pushdef) vec_push(self->code->defs, def);
3495 return global->code.globaladdr >= 0;
3500 ir_value_code_setaddr(global, vec_size(self->code->globals));
3501 if (global->hasvalue) {
3502 iptr = (int32_t*)&global->constval.ivec[0];
3503 vec_push(self->code->globals, iptr[0]);
3504 if (global->code.globaladdr < 0)
3506 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3507 vec_push(self->code->globals, iptr[d]);
3510 vec_push(self->code->globals, 0);
3511 if (global->code.globaladdr < 0)
3513 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3514 vec_push(self->code->globals, 0);
3517 if (!islocal && global->cvq != CV_CONST)
3518 def.type |= DEF_SAVEGLOBAL;
3521 vec_push(self->code->defs, def);
3522 def.type &= ~DEF_SAVEGLOBAL;
3523 gen_vector_defs(self->code, def, global->name);
3525 return global->code.globaladdr >= 0;
3528 ir_value_code_setaddr(global, vec_size(self->code->globals));
3529 if (!global->hasvalue) {
3530 vec_push(self->code->globals, 0);
3531 if (global->code.globaladdr < 0)
3534 vec_push(self->code->globals, vec_size(self->code->functions));
3535 if (!gen_global_function(self, global))
3538 if (!islocal && global->cvq != CV_CONST)
3539 def.type |= DEF_SAVEGLOBAL;
3540 if (pushdef) vec_push(self->code->defs, def);
3543 /* assume biggest type */
3544 ir_value_code_setaddr(global, vec_size(self->code->globals));
3545 vec_push(self->code->globals, 0);
3546 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3547 vec_push(self->code->globals, 0);
3550 /* refuse to create 'void' type or any other fancy business. */
3551 irerror(global->context, "Invalid type for global variable `%s`: %s",
3552 global->name, type_name[global->vtype]);
3557 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3559 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3562 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3564 prog_section_def_t def;
3565 prog_section_field_t fld;
3569 def.type = (uint16_t)field->vtype;
3570 def.offset = (uint16_t)vec_size(self->code->globals);
3572 /* create a global named the same as the field */
3573 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3574 /* in our standard, the global gets a dot prefix */
3575 size_t len = strlen(field->name);
3578 /* we really don't want to have to allocate this, and 1024
3579 * bytes is more than enough for a variable/field name
3581 if (len+2 >= sizeof(name)) {
3582 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3587 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3590 def.name = code_genstring(self->code, name);
3591 fld.name = def.name + 1; /* we reuse that string table entry */
3593 /* in plain QC, there cannot be a global with the same name,
3594 * and so we also name the global the same.
3595 * FIXME: fteqcc should create a global as well
3596 * check if it actually uses the same name. Probably does
3598 def.name = code_genstring(self->code, field->name);
3599 fld.name = def.name;
3602 field->code.name = def.name;
3604 vec_push(self->code->defs, def);
3606 fld.type = field->fieldtype;
3608 if (fld.type == TYPE_VOID) {
3609 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3613 fld.offset = field->code.fieldaddr;
3615 vec_push(self->code->fields, fld);
3617 ir_value_code_setaddr(field, vec_size(self->code->globals));
3618 vec_push(self->code->globals, fld.offset);
3619 if (fld.type == TYPE_VECTOR) {
3620 vec_push(self->code->globals, fld.offset+1);
3621 vec_push(self->code->globals, fld.offset+2);
3624 if (field->fieldtype == TYPE_VECTOR) {
3625 gen_vector_defs (self->code, def, field->name);
3626 gen_vector_fields(self->code, fld, field->name);
3629 return field->code.globaladdr >= 0;
3632 bool ir_builder_generate(ir_builder *self, const char *filename)
3634 prog_section_statement_t stmt;
3636 char *lnofile = NULL;
3638 for (i = 0; i < vec_size(self->fields); ++i)
3640 ir_builder_prepare_field(self->code, self->fields[i]);
3643 for (i = 0; i < vec_size(self->globals); ++i)
3645 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3648 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3649 ir_function *func = self->globals[i]->constval.vfunc;
3650 if (func && self->max_locals < func->allocated_locals &&
3651 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3653 self->max_locals = func->allocated_locals;
3655 if (func && self->max_globaltemps < func->globaltemps)
3656 self->max_globaltemps = func->globaltemps;
3660 for (i = 0; i < vec_size(self->fields); ++i)
3662 if (!ir_builder_gen_field(self, self->fields[i])) {
3668 ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
3669 vec_push(self->code->globals, 0);
3670 vec_push(self->code->globals, 0);
3671 vec_push(self->code->globals, 0);
3673 /* generate virtual-instruction temps */
3674 for (i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
3675 ir_value_code_setaddr(self->vinstr_temp[i], vec_size(self->code->globals));
3676 vec_push(self->code->globals, 0);
3677 vec_push(self->code->globals, 0);
3678 vec_push(self->code->globals, 0);
3681 /* generate global temps */
3682 self->first_common_globaltemp = vec_size(self->code->globals);
3683 for (i = 0; i < self->max_globaltemps; ++i) {
3684 vec_push(self->code->globals, 0);
3686 /* generate common locals */
3687 self->first_common_local = vec_size(self->code->globals);
3688 for (i = 0; i < self->max_locals; ++i) {
3689 vec_push(self->code->globals, 0);
3692 /* generate function code */
3693 for (i = 0; i < vec_size(self->globals); ++i)
3695 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3696 if (!gen_global_function_code(self, self->globals[i])) {
3702 if (vec_size(self->code->globals) >= 65536) {
3703 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3707 /* DP errors if the last instruction is not an INSTR_DONE. */
3708 if (vec_last(self->code->statements).opcode != INSTR_DONE)
3710 stmt.opcode = INSTR_DONE;
3714 code_push_statement(self->code, &stmt, vec_last(self->code->linenums));
3717 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3720 if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
3721 con_err("Linecounter wrong: %lu != %lu\n",
3722 (unsigned long)vec_size(self->code->statements),
3723 (unsigned long)vec_size(self->code->linenums));
3724 } else if (OPTS_FLAG(LNO)) {
3726 size_t filelen = strlen(filename);
3728 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3729 dot = strrchr(lnofile, '.');
3733 vec_shrinkto(lnofile, dot - lnofile);
3735 memcpy(vec_add(lnofile, 5), ".lno", 5);
3738 if (!code_write(self->code, filename, lnofile)) {
3747 /***********************************************************************
3748 *IR DEBUG Dump functions...
3751 #define IND_BUFSZ 1024
3754 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3757 static const char *qc_opname(int op)
3759 if (op < 0) return "<INVALID>";
3760 if (op < VINSTR_END)
3761 return util_instr_str[op];
3763 case VINSTR_END: return "END";
3764 case VINSTR_PHI: return "PHI";
3765 case VINSTR_JUMP: return "JUMP";
3766 case VINSTR_COND: return "COND";
3767 default: return "<UNK>";
3771 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3774 char indent[IND_BUFSZ];
3778 oprintf("module %s\n", b->name);
3779 for (i = 0; i < vec_size(b->globals); ++i)
3782 if (b->globals[i]->hasvalue)
3783 oprintf("%s = ", b->globals[i]->name);
3784 ir_value_dump(b->globals[i], oprintf);
3787 for (i = 0; i < vec_size(b->functions); ++i)
3788 ir_function_dump(b->functions[i], indent, oprintf);
3789 oprintf("endmodule %s\n", b->name);
3792 static const char *storenames[] = {
3793 "[global]", "[local]", "[param]", "[value]", "[return]"
3796 void ir_function_dump(ir_function *f, char *ind,
3797 int (*oprintf)(const char*, ...))
3800 if (f->builtin != 0) {
3801 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3804 oprintf("%sfunction %s\n", ind, f->name);
3805 strncat(ind, "\t", IND_BUFSZ-1);
3806 if (vec_size(f->locals))
3808 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3809 for (i = 0; i < vec_size(f->locals); ++i) {
3810 oprintf("%s\t", ind);
3811 ir_value_dump(f->locals[i], oprintf);
3815 oprintf("%sliferanges:\n", ind);
3816 for (i = 0; i < vec_size(f->locals); ++i) {
3817 const char *attr = "";
3819 ir_value *v = f->locals[i];
3820 if (v->unique_life && v->locked)
3821 attr = "unique,locked ";
3822 else if (v->unique_life)
3826 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3827 storenames[v->store],
3828 attr, (v->callparam ? "callparam " : ""),
3829 (int)v->code.local);
3832 for (l = 0; l < vec_size(v->life); ++l) {
3833 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3836 for (m = 0; m < 3; ++m) {
3837 ir_value *vm = v->members[m];
3840 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
3841 for (l = 0; l < vec_size(vm->life); ++l) {
3842 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3847 for (i = 0; i < vec_size(f->values); ++i) {
3848 const char *attr = "";
3850 ir_value *v = f->values[i];
3851 if (v->unique_life && v->locked)
3852 attr = "unique,locked ";
3853 else if (v->unique_life)
3857 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3858 storenames[v->store],
3859 attr, (v->callparam ? "callparam " : ""),
3860 (int)v->code.local);
3863 for (l = 0; l < vec_size(v->life); ++l) {
3864 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3867 for (m = 0; m < 3; ++m) {
3868 ir_value *vm = v->members[m];
3871 if (vm->unique_life && vm->locked)
3872 attr = "unique,locked ";
3873 else if (vm->unique_life)
3875 else if (vm->locked)
3877 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
3878 for (l = 0; l < vec_size(vm->life); ++l) {
3879 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3884 if (vec_size(f->blocks))
3886 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
3887 for (i = 0; i < vec_size(f->blocks); ++i) {
3888 ir_block_dump(f->blocks[i], ind, oprintf);
3892 ind[strlen(ind)-1] = 0;
3893 oprintf("%sendfunction %s\n", ind, f->name);
3896 void ir_block_dump(ir_block* b, char *ind,
3897 int (*oprintf)(const char*, ...))
3900 oprintf("%s:%s\n", ind, b->label);
3901 strncat(ind, "\t", IND_BUFSZ-1);
3903 if (b->instr && b->instr[0])
3904 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
3905 for (i = 0; i < vec_size(b->instr); ++i)
3906 ir_instr_dump(b->instr[i], ind, oprintf);
3907 ind[strlen(ind)-1] = 0;
3910 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3913 oprintf("%s <- phi ", in->_ops[0]->name);
3914 for (i = 0; i < vec_size(in->phi); ++i)
3916 oprintf("([%s] : %s) ", in->phi[i].from->label,
3917 in->phi[i].value->name);
3922 void ir_instr_dump(ir_instr *in, char *ind,
3923 int (*oprintf)(const char*, ...))
3926 const char *comma = NULL;
3928 oprintf("%s (%i) ", ind, (int)in->eid);
3930 if (in->opcode == VINSTR_PHI) {
3931 dump_phi(in, oprintf);
3935 strncat(ind, "\t", IND_BUFSZ-1);
3937 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3938 ir_value_dump(in->_ops[0], oprintf);
3939 if (in->_ops[1] || in->_ops[2])
3942 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3943 oprintf("CALL%i\t", vec_size(in->params));
3945 oprintf("%s\t", qc_opname(in->opcode));
3947 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3948 ir_value_dump(in->_ops[0], oprintf);
3953 for (i = 1; i != 3; ++i) {
3957 ir_value_dump(in->_ops[i], oprintf);
3965 oprintf("[%s]", in->bops[0]->label);
3969 oprintf("%s[%s]", comma, in->bops[1]->label);
3970 if (vec_size(in->params)) {
3971 oprintf("\tparams: ");
3972 for (i = 0; i != vec_size(in->params); ++i) {
3973 oprintf("%s, ", in->params[i]->name);
3977 ind[strlen(ind)-1] = 0;
3980 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3983 for (; *str; ++str) {
3985 case '\n': oprintf("\\n"); break;
3986 case '\r': oprintf("\\r"); break;
3987 case '\t': oprintf("\\t"); break;
3988 case '\v': oprintf("\\v"); break;
3989 case '\f': oprintf("\\f"); break;
3990 case '\b': oprintf("\\b"); break;
3991 case '\a': oprintf("\\a"); break;
3992 case '\\': oprintf("\\\\"); break;
3993 case '"': oprintf("\\\""); break;
3994 default: oprintf("%c", *str); break;
4000 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4009 oprintf("fn:%s", v->name);
4012 oprintf("%g", v->constval.vfloat);
4015 oprintf("'%g %g %g'",
4018 v->constval.vvec.z);
4021 oprintf("(entity)");
4024 ir_value_dump_string(v->constval.vstring, oprintf);
4028 oprintf("%i", v->constval.vint);
4033 v->constval.vpointer->name);
4037 oprintf("%s", v->name);
4041 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4044 oprintf("Life of %12s:", self->name);
4045 for (i = 0; i < vec_size(self->life); ++i)
4047 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);