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 (self->_ops[op]) {
1037 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1038 vec_remove(self->_ops[op]->writes, idx, 1);
1039 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1040 vec_remove(self->_ops[op]->reads, idx, 1);
1044 vec_push(v->writes, self);
1046 vec_push(v->reads, self);
1052 /***********************************************************************
1056 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1058 self->code.globaladdr = gaddr;
1059 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1060 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1061 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1064 static int32_t ir_value_code_addr(const ir_value *self)
1066 if (self->store == store_return)
1067 return OFS_RETURN + self->code.addroffset;
1068 return self->code.globaladdr + self->code.addroffset;
1071 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1074 self = (ir_value*)mem_a(sizeof(*self));
1075 self->vtype = vtype;
1076 self->fieldtype = TYPE_VOID;
1077 self->outtype = TYPE_VOID;
1078 self->store = storetype;
1082 self->writes = NULL;
1084 self->cvq = CV_NONE;
1085 self->hasvalue = false;
1086 self->context.file = "<@no context>";
1087 self->context.line = 0;
1089 if (name && !ir_value_set_name(self, name)) {
1090 irerror(self->context, "out of memory");
1095 memset(&self->constval, 0, sizeof(self->constval));
1096 memset(&self->code, 0, sizeof(self->code));
1098 self->members[0] = NULL;
1099 self->members[1] = NULL;
1100 self->members[2] = NULL;
1101 self->memberof = NULL;
1103 self->unique_life = false;
1104 self->locked = false;
1105 self->callparam = false;
1111 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1119 if (self->members[member])
1120 return self->members[member];
1123 len = strlen(self->name);
1124 name = (char*)mem_a(len + 3);
1125 memcpy(name, self->name, len);
1127 name[len+1] = 'x' + member;
1133 if (self->vtype == TYPE_VECTOR)
1135 m = ir_value_var(name, self->store, TYPE_FLOAT);
1140 m->context = self->context;
1142 self->members[member] = m;
1143 m->code.addroffset = member;
1145 else if (self->vtype == TYPE_FIELD)
1147 if (self->fieldtype != TYPE_VECTOR)
1149 m = ir_value_var(name, self->store, TYPE_FIELD);
1154 m->fieldtype = TYPE_FLOAT;
1155 m->context = self->context;
1157 self->members[member] = m;
1158 m->code.addroffset = member;
1162 irerror(self->context, "invalid member access on %s", self->name);
1170 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1172 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1173 return type_sizeof_[TYPE_VECTOR];
1174 return type_sizeof_[self->vtype];
1177 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1179 ir_value *v = ir_value_var(name, storetype, vtype);
1182 ir_function_collect_value(owner, v);
1186 void ir_value_delete(ir_value* self)
1190 mem_d((void*)self->name);
1193 if (self->vtype == TYPE_STRING)
1194 mem_d((void*)self->constval.vstring);
1196 for (i = 0; i < 3; ++i) {
1197 if (self->members[i])
1198 ir_value_delete(self->members[i]);
1200 vec_free(self->reads);
1201 vec_free(self->writes);
1202 vec_free(self->life);
1206 bool ir_value_set_name(ir_value *self, const char *name)
1209 mem_d((void*)self->name);
1210 self->name = util_strdup(name);
1211 return !!self->name;
1214 bool ir_value_set_float(ir_value *self, float f)
1216 if (self->vtype != TYPE_FLOAT)
1218 self->constval.vfloat = f;
1219 self->hasvalue = true;
1223 bool ir_value_set_func(ir_value *self, int f)
1225 if (self->vtype != TYPE_FUNCTION)
1227 self->constval.vint = f;
1228 self->hasvalue = true;
1232 bool ir_value_set_vector(ir_value *self, vec3_t v)
1234 if (self->vtype != TYPE_VECTOR)
1236 self->constval.vvec = v;
1237 self->hasvalue = true;
1241 bool ir_value_set_field(ir_value *self, ir_value *fld)
1243 if (self->vtype != TYPE_FIELD)
1245 self->constval.vpointer = fld;
1246 self->hasvalue = true;
1250 bool ir_value_set_string(ir_value *self, const char *str)
1252 if (self->vtype != TYPE_STRING)
1254 self->constval.vstring = util_strdupe(str);
1255 self->hasvalue = true;
1260 bool ir_value_set_int(ir_value *self, int i)
1262 if (self->vtype != TYPE_INTEGER)
1264 self->constval.vint = i;
1265 self->hasvalue = true;
1270 bool ir_value_lives(ir_value *self, size_t at)
1273 for (i = 0; i < vec_size(self->life); ++i)
1275 ir_life_entry_t *life = &self->life[i];
1276 if (life->start <= at && at <= life->end)
1278 if (life->start > at) /* since it's ordered */
1284 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1287 vec_push(self->life, e);
1288 for (k = vec_size(self->life)-1; k > idx; --k)
1289 self->life[k] = self->life[k-1];
1290 self->life[idx] = e;
1294 static bool ir_value_life_merge(ir_value *self, size_t s)
1297 const size_t vs = vec_size(self->life);
1298 ir_life_entry_t *life = NULL;
1299 ir_life_entry_t *before = NULL;
1300 ir_life_entry_t new_entry;
1302 /* Find the first range >= s */
1303 for (i = 0; i < vs; ++i)
1306 life = &self->life[i];
1307 if (life->start > s)
1310 /* nothing found? append */
1313 if (life && life->end+1 == s)
1315 /* previous life range can be merged in */
1319 if (life && life->end >= s)
1321 e.start = e.end = s;
1322 vec_push(self->life, e);
1328 if (before->end + 1 == s &&
1329 life->start - 1 == s)
1332 before->end = life->end;
1333 vec_remove(self->life, i, 1);
1336 if (before->end + 1 == s)
1342 /* already contained */
1343 if (before->end >= s)
1347 if (life->start - 1 == s)
1352 /* insert a new entry */
1353 new_entry.start = new_entry.end = s;
1354 return ir_value_life_insert(self, i, new_entry);
1357 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1361 if (!vec_size(other->life))
1364 if (!vec_size(self->life)) {
1365 size_t count = vec_size(other->life);
1366 ir_life_entry_t *life = vec_add(self->life, count);
1367 memcpy(life, other->life, count * sizeof(*life));
1372 for (i = 0; i < vec_size(other->life); ++i)
1374 const ir_life_entry_t *life = &other->life[i];
1377 ir_life_entry_t *entry = &self->life[myi];
1379 if (life->end+1 < entry->start)
1381 /* adding an interval before entry */
1382 if (!ir_value_life_insert(self, myi, *life))
1388 if (life->start < entry->start &&
1389 life->end+1 >= entry->start)
1391 /* starts earlier and overlaps */
1392 entry->start = life->start;
1395 if (life->end > entry->end &&
1396 life->start <= entry->end+1)
1398 /* ends later and overlaps */
1399 entry->end = life->end;
1402 /* see if our change combines it with the next ranges */
1403 while (myi+1 < vec_size(self->life) &&
1404 entry->end+1 >= self->life[1+myi].start)
1406 /* overlaps with (myi+1) */
1407 if (entry->end < self->life[1+myi].end)
1408 entry->end = self->life[1+myi].end;
1409 vec_remove(self->life, myi+1, 1);
1410 entry = &self->life[myi];
1413 /* see if we're after the entry */
1414 if (life->start > entry->end)
1417 /* append if we're at the end */
1418 if (myi >= vec_size(self->life)) {
1419 vec_push(self->life, *life);
1422 /* otherweise check the next range */
1431 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1433 /* For any life entry in A see if it overlaps with
1434 * any life entry in B.
1435 * Note that the life entries are orderes, so we can make a
1436 * more efficient algorithm there than naively translating the
1440 ir_life_entry_t *la, *lb, *enda, *endb;
1442 /* first of all, if either has no life range, they cannot clash */
1443 if (!vec_size(a->life) || !vec_size(b->life))
1448 enda = la + vec_size(a->life);
1449 endb = lb + vec_size(b->life);
1452 /* check if the entries overlap, for that,
1453 * both must start before the other one ends.
1455 if (la->start < lb->end &&
1456 lb->start < la->end)
1461 /* entries are ordered
1462 * one entry is earlier than the other
1463 * that earlier entry will be moved forward
1465 if (la->start < lb->start)
1467 /* order: A B, move A forward
1468 * check if we hit the end with A
1473 else /* if (lb->start < la->start) actually <= */
1475 /* order: B A, move B forward
1476 * check if we hit the end with B
1485 /***********************************************************************
1489 static bool ir_check_unreachable(ir_block *self)
1491 /* The IR should never have to deal with unreachable code */
1492 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1494 irerror(self->context, "unreachable statement (%s)", self->label);
1498 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1501 if (!ir_check_unreachable(self))
1504 if (target->store == store_value &&
1505 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1507 irerror(self->context, "cannot store to an SSA value");
1508 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1509 irerror(self->context, "instruction: %s", util_instr_str[op]);
1513 in = ir_instr_new(ctx, self, op);
1517 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1518 !ir_instr_op(in, 1, what, false))
1520 ir_instr_delete(in);
1523 vec_push(self->instr, in);
1527 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1531 if (target->vtype == TYPE_VARIANT)
1532 vtype = what->vtype;
1534 vtype = target->vtype;
1537 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1538 op = INSTR_CONV_ITOF;
1539 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1540 op = INSTR_CONV_FTOI;
1542 op = type_store_instr[vtype];
1544 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1545 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1549 return ir_block_create_store_op(self, ctx, op, target, what);
1552 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1557 if (target->vtype != TYPE_POINTER)
1560 /* storing using pointer - target is a pointer, type must be
1561 * inferred from source
1563 vtype = what->vtype;
1565 op = type_storep_instr[vtype];
1566 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1567 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1568 op = INSTR_STOREP_V;
1571 return ir_block_create_store_op(self, ctx, op, target, what);
1574 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1577 if (!ir_check_unreachable(self))
1580 self->is_return = true;
1581 in = ir_instr_new(ctx, self, INSTR_RETURN);
1585 if (v && !ir_instr_op(in, 0, v, false)) {
1586 ir_instr_delete(in);
1590 vec_push(self->instr, in);
1594 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1595 ir_block *ontrue, ir_block *onfalse)
1598 if (!ir_check_unreachable(self))
1601 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1602 in = ir_instr_new(ctx, self, VINSTR_COND);
1606 if (!ir_instr_op(in, 0, v, false)) {
1607 ir_instr_delete(in);
1611 in->bops[0] = ontrue;
1612 in->bops[1] = onfalse;
1614 vec_push(self->instr, in);
1616 vec_push(self->exits, ontrue);
1617 vec_push(self->exits, onfalse);
1618 vec_push(ontrue->entries, self);
1619 vec_push(onfalse->entries, self);
1623 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1626 if (!ir_check_unreachable(self))
1629 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1634 vec_push(self->instr, in);
1636 vec_push(self->exits, to);
1637 vec_push(to->entries, self);
1641 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1643 self->owner->flags |= IR_FLAG_HAS_GOTO;
1644 return ir_block_create_jump(self, ctx, to);
1647 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, int ot)
1651 if (!ir_check_unreachable(self))
1653 in = ir_instr_new(ctx, self, VINSTR_PHI);
1656 out = ir_value_out(self->owner, label, store_value, ot);
1658 ir_instr_delete(in);
1661 if (!ir_instr_op(in, 0, out, true)) {
1662 ir_instr_delete(in);
1663 ir_value_delete(out);
1666 vec_push(self->instr, in);
1670 ir_value* ir_phi_value(ir_instr *self)
1672 return self->_ops[0];
1675 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1679 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1680 /* Must not be possible to cause this, otherwise the AST
1681 * is doing something wrong.
1683 irerror(self->context, "Invalid entry block for PHI");
1689 vec_push(v->reads, self);
1690 vec_push(self->phi, pe);
1693 /* call related code */
1694 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1698 if (!ir_check_unreachable(self))
1700 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1705 self->is_return = true;
1707 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1709 ir_instr_delete(in);
1712 if (!ir_instr_op(in, 0, out, true) ||
1713 !ir_instr_op(in, 1, func, false))
1715 ir_instr_delete(in);
1716 ir_value_delete(out);
1719 vec_push(self->instr, in);
1722 if (!ir_block_create_return(self, ctx, NULL)) {
1723 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1724 ir_instr_delete(in);
1732 ir_value* ir_call_value(ir_instr *self)
1734 return self->_ops[0];
1737 void ir_call_param(ir_instr* self, ir_value *v)
1739 vec_push(self->params, v);
1740 vec_push(v->reads, self);
1743 /* binary op related code */
1745 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1746 const char *label, int opcode,
1747 ir_value *left, ir_value *right)
1769 case INSTR_SUB_S: /* -- offset of string as float */
1774 case INSTR_BITOR_IF:
1775 case INSTR_BITOR_FI:
1776 case INSTR_BITAND_FI:
1777 case INSTR_BITAND_IF:
1792 case INSTR_BITAND_I:
1795 case INSTR_RSHIFT_I:
1796 case INSTR_LSHIFT_I:
1817 * after the following default case, the value of opcode can never
1818 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1822 /* boolean operations result in floats */
1825 * opcode >= 10 takes true branch opcode is at least 10
1826 * opcode <= 23 takes false branch opcode is at least 24
1828 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1832 * At condition "opcode <= 23", the value of "opcode" must be
1834 * At condition "opcode <= 23", the value of "opcode" cannot be
1835 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1836 * The condition "opcode <= 23" cannot be true.
1838 * Thus ot=2 (TYPE_FLOAT) can never be true
1841 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1843 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1848 if (ot == TYPE_VOID) {
1849 /* The AST or parser were supposed to check this! */
1853 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1856 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1857 const char *label, int opcode,
1860 int ot = TYPE_FLOAT;
1872 /* QC doesn't have other unary operations. We expect extensions to fill
1873 * the above list, otherwise we assume out-type = in-type, eg for an
1877 ot = operand->vtype;
1880 if (ot == TYPE_VOID) {
1881 /* The AST or parser were supposed to check this! */
1885 /* let's use the general instruction creator and pass NULL for OPB */
1886 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1889 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1890 int op, ir_value *a, ir_value *b, int outype)
1895 out = ir_value_out(self->owner, label, store_value, outype);
1899 instr = ir_instr_new(ctx, self, op);
1901 ir_value_delete(out);
1905 if (!ir_instr_op(instr, 0, out, true) ||
1906 !ir_instr_op(instr, 1, a, false) ||
1907 !ir_instr_op(instr, 2, b, false) )
1912 vec_push(self->instr, instr);
1916 ir_instr_delete(instr);
1917 ir_value_delete(out);
1921 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1925 /* Support for various pointer types todo if so desired */
1926 if (ent->vtype != TYPE_ENTITY)
1929 if (field->vtype != TYPE_FIELD)
1932 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1933 v->fieldtype = field->fieldtype;
1937 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)
1940 if (ent->vtype != TYPE_ENTITY)
1943 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1944 if (field->vtype != TYPE_FIELD)
1949 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1950 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1951 case TYPE_STRING: op = INSTR_LOAD_S; break;
1952 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1953 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1954 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1956 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1957 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1960 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1964 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1967 /* PHI resolving breaks the SSA, and must thus be the last
1968 * step before life-range calculation.
1971 static bool ir_block_naive_phi(ir_block *self);
1972 bool ir_function_naive_phi(ir_function *self)
1976 for (i = 0; i < vec_size(self->blocks); ++i)
1978 if (!ir_block_naive_phi(self->blocks[i]))
1984 static bool ir_block_naive_phi(ir_block *self)
1986 size_t i, p; /*, w;*/
1987 /* FIXME: optionally, create_phi can add the phis
1988 * to a list so we don't need to loop through blocks
1989 * - anyway: "don't optimize YET"
1991 for (i = 0; i < vec_size(self->instr); ++i)
1993 ir_instr *instr = self->instr[i];
1994 if (instr->opcode != VINSTR_PHI)
1997 vec_remove(self->instr, i, 1);
1998 --i; /* NOTE: i+1 below */
2000 for (p = 0; p < vec_size(instr->phi); ++p)
2002 ir_value *v = instr->phi[p].value;
2003 ir_block *b = instr->phi[p].from;
2005 if (v->store == store_value &&
2006 vec_size(v->reads) == 1 &&
2007 vec_size(v->writes) == 1)
2009 /* replace the value */
2010 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2015 /* force a move instruction */
2016 ir_instr *prevjump = vec_last(b->instr);
2019 instr->_ops[0]->store = store_global;
2020 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2022 instr->_ops[0]->store = store_value;
2023 vec_push(b->instr, prevjump);
2027 ir_instr_delete(instr);
2032 /***********************************************************************
2033 *IR Temp allocation code
2034 * Propagating value life ranges by walking through the function backwards
2035 * until no more changes are made.
2036 * In theory this should happen once more than once for every nested loop
2038 * Though this implementation might run an additional time for if nests.
2041 /* Enumerate instructions used by value's life-ranges
2043 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2047 for (i = 0; i < vec_size(self->instr); ++i)
2049 self->instr[i]->eid = eid++;
2054 /* Enumerate blocks and instructions.
2055 * The block-enumeration is unordered!
2056 * We do not really use the block enumreation, however
2057 * the instruction enumeration is important for life-ranges.
2059 void ir_function_enumerate(ir_function *self)
2062 size_t instruction_id = 0;
2063 for (i = 0; i < vec_size(self->blocks); ++i)
2065 /* each block now gets an additional "entry" instruction id
2066 * we can use to avoid point-life issues
2068 self->blocks[i]->entry_id = instruction_id;
2071 self->blocks[i]->eid = i;
2072 ir_block_enumerate(self->blocks[i], &instruction_id);
2076 /* Local-value allocator
2077 * After finishing creating the liferange of all values used in a function
2078 * we can allocate their global-positions.
2079 * This is the counterpart to register-allocation in register machines.
2086 } function_allocator;
2088 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2091 size_t vsize = ir_value_sizeof(var);
2093 var->code.local = vec_size(alloc->locals);
2095 slot = ir_value_var("reg", store_global, var->vtype);
2099 if (!ir_value_life_merge_into(slot, var))
2102 vec_push(alloc->locals, slot);
2103 vec_push(alloc->sizes, vsize);
2104 vec_push(alloc->unique, var->unique_life);
2109 ir_value_delete(slot);
2113 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2119 return function_allocator_alloc(alloc, v);
2121 for (a = 0; a < vec_size(alloc->locals); ++a)
2123 /* if it's reserved for a unique liferange: skip */
2124 if (alloc->unique[a])
2127 slot = alloc->locals[a];
2129 /* never resize parameters
2130 * will be required later when overlapping temps + locals
2132 if (a < vec_size(self->params) &&
2133 alloc->sizes[a] < ir_value_sizeof(v))
2138 if (ir_values_overlap(v, slot))
2141 if (!ir_value_life_merge_into(slot, v))
2144 /* adjust size for this slot */
2145 if (alloc->sizes[a] < ir_value_sizeof(v))
2146 alloc->sizes[a] = ir_value_sizeof(v);
2151 if (a >= vec_size(alloc->locals)) {
2152 if (!function_allocator_alloc(alloc, v))
2158 bool ir_function_allocate_locals(ir_function *self)
2163 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2167 function_allocator lockalloc, globalloc;
2169 if (!vec_size(self->locals) && !vec_size(self->values))
2172 globalloc.locals = NULL;
2173 globalloc.sizes = NULL;
2174 globalloc.positions = NULL;
2175 globalloc.unique = NULL;
2176 lockalloc.locals = NULL;
2177 lockalloc.sizes = NULL;
2178 lockalloc.positions = NULL;
2179 lockalloc.unique = NULL;
2181 for (i = 0; i < vec_size(self->locals); ++i)
2183 v = self->locals[i];
2184 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2186 v->unique_life = true;
2188 else if (i >= vec_size(self->params))
2191 v->locked = true; /* lock parameters locals */
2192 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2195 for (; i < vec_size(self->locals); ++i)
2197 v = self->locals[i];
2198 if (!vec_size(v->life))
2200 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2204 /* Allocate a slot for any value that still exists */
2205 for (i = 0; i < vec_size(self->values); ++i)
2207 v = self->values[i];
2209 if (!vec_size(v->life))
2212 /* CALL optimization:
2213 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2214 * and it's not "locked", write it to the OFS_PARM directly.
2216 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2217 if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2218 (v->reads[0]->opcode == VINSTR_NRCALL ||
2219 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2224 ir_instr *call = v->reads[0];
2225 if (!vec_ir_value_find(call->params, v, ¶m)) {
2226 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2229 ++opts_optimizationcount[OPTIM_CALL_STORES];
2230 v->callparam = true;
2232 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2234 size_t nprotos = vec_size(self->owner->extparam_protos);
2237 if (nprotos > param)
2238 ep = self->owner->extparam_protos[param];
2241 ep = ir_gen_extparam_proto(self->owner);
2242 while (++nprotos <= param)
2243 ep = ir_gen_extparam_proto(self->owner);
2245 ir_instr_op(v->writes[0], 0, ep, true);
2246 call->params[param+8] = ep;
2250 if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2252 v->store = store_return;
2253 if (v->members[0]) v->members[0]->store = store_return;
2254 if (v->members[1]) v->members[1]->store = store_return;
2255 if (v->members[2]) v->members[2]->store = store_return;
2256 ++opts_optimizationcount[OPTIM_CALL_STORES];
2261 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2265 if (!lockalloc.sizes && !globalloc.sizes) {
2268 vec_push(lockalloc.positions, 0);
2269 vec_push(globalloc.positions, 0);
2271 /* Adjust slot positions based on sizes */
2272 if (lockalloc.sizes) {
2273 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2274 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2276 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2277 vec_push(lockalloc.positions, pos);
2279 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2281 if (globalloc.sizes) {
2282 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2283 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2285 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2286 vec_push(globalloc.positions, pos);
2288 self->globaltemps = pos + vec_last(globalloc.sizes);
2291 /* Locals need to know their new position */
2292 for (i = 0; i < vec_size(self->locals); ++i) {
2293 v = self->locals[i];
2294 if (v->locked || !opt_gt)
2295 v->code.local = lockalloc.positions[v->code.local];
2297 v->code.local = globalloc.positions[v->code.local];
2299 /* Take over the actual slot positions on values */
2300 for (i = 0; i < vec_size(self->values); ++i) {
2301 v = self->values[i];
2302 if (v->locked || !opt_gt)
2303 v->code.local = lockalloc.positions[v->code.local];
2305 v->code.local = globalloc.positions[v->code.local];
2313 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2314 ir_value_delete(lockalloc.locals[i]);
2315 for (i = 0; i < vec_size(globalloc.locals); ++i)
2316 ir_value_delete(globalloc.locals[i]);
2317 vec_free(globalloc.unique);
2318 vec_free(globalloc.locals);
2319 vec_free(globalloc.sizes);
2320 vec_free(globalloc.positions);
2321 vec_free(lockalloc.unique);
2322 vec_free(lockalloc.locals);
2323 vec_free(lockalloc.sizes);
2324 vec_free(lockalloc.positions);
2328 /* Get information about which operand
2329 * is read from, or written to.
2331 static void ir_op_read_write(int op, size_t *read, size_t *write)
2351 case INSTR_STOREP_F:
2352 case INSTR_STOREP_V:
2353 case INSTR_STOREP_S:
2354 case INSTR_STOREP_ENT:
2355 case INSTR_STOREP_FLD:
2356 case INSTR_STOREP_FNC:
2367 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2370 const size_t vs = vec_size(self->living);
2371 bool changed = false;
2372 for (i = 0; i != vs; ++i)
2374 if (ir_value_life_merge(self->living[i], eid))
2380 static bool ir_block_living_lock(ir_block *self)
2383 bool changed = false;
2384 for (i = 0; i != vec_size(self->living); ++i)
2386 if (!self->living[i]->locked) {
2387 self->living[i]->locked = true;
2394 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2398 size_t i, o, p, mem, cnt;
2399 /* bitmasks which operands are read from or written to */
2406 vec_free(self->living);
2408 p = vec_size(self->exits);
2409 for (i = 0; i < p; ++i) {
2410 ir_block *prev = self->exits[i];
2411 cnt = vec_size(prev->living);
2412 for (o = 0; o < cnt; ++o) {
2413 if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2414 vec_push(self->living, prev->living[o]);
2418 i = vec_size(self->instr);
2421 instr = self->instr[i];
2423 /* See which operands are read and write operands */
2424 ir_op_read_write(instr->opcode, &read, &write);
2426 /* Go through the 3 main operands
2427 * writes first, then reads
2429 for (o = 0; o < 3; ++o)
2431 if (!instr->_ops[o]) /* no such operand */
2434 value = instr->_ops[o];
2436 /* We only care about locals */
2437 /* we also calculate parameter liferanges so that locals
2438 * can take up parameter slots */
2439 if (value->store != store_value &&
2440 value->store != store_local &&
2441 value->store != store_param)
2444 /* write operands */
2445 /* When we write to a local, we consider it "dead" for the
2446 * remaining upper part of the function, since in SSA a value
2447 * can only be written once (== created)
2452 bool in_living = vec_ir_value_find(self->living, value, &idx);
2455 /* If the value isn't alive it hasn't been read before... */
2456 /* TODO: See if the warning can be emitted during parsing or AST processing
2457 * otherwise have warning printed here.
2458 * IF printing a warning here: include filecontext_t,
2459 * and make sure it's only printed once
2460 * since this function is run multiple times.
2462 /* con_err( "Value only written %s\n", value->name); */
2463 if (ir_value_life_merge(value, instr->eid))
2466 /* since 'living' won't contain it
2467 * anymore, merge the value, since
2470 if (ir_value_life_merge(value, instr->eid))
2473 vec_remove(self->living, idx, 1);
2475 /* Removing a vector removes all members */
2476 for (mem = 0; mem < 3; ++mem) {
2477 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2478 if (ir_value_life_merge(value->members[mem], instr->eid))
2480 vec_remove(self->living, idx, 1);
2483 /* Removing the last member removes the vector */
2484 if (value->memberof) {
2485 value = value->memberof;
2486 for (mem = 0; mem < 3; ++mem) {
2487 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2490 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2491 if (ir_value_life_merge(value, instr->eid))
2493 vec_remove(self->living, idx, 1);
2499 if (instr->opcode == INSTR_MUL_VF)
2501 value = instr->_ops[2];
2502 /* the float source will get an additional lifetime */
2503 if (ir_value_life_merge(value, instr->eid+1))
2505 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2508 else if (instr->opcode == INSTR_MUL_FV || instr->opcode == INSTR_LOAD_V)
2510 value = instr->_ops[1];
2511 /* the float source will get an additional lifetime */
2512 if (ir_value_life_merge(value, instr->eid+1))
2514 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2518 for (o = 0; o < 3; ++o)
2520 if (!instr->_ops[o]) /* no such operand */
2523 value = instr->_ops[o];
2525 /* We only care about locals */
2526 /* we also calculate parameter liferanges so that locals
2527 * can take up parameter slots */
2528 if (value->store != store_value &&
2529 value->store != store_local &&
2530 value->store != store_param)
2536 if (!vec_ir_value_find(self->living, value, NULL))
2537 vec_push(self->living, value);
2538 /* reading adds the full vector */
2539 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2540 vec_push(self->living, value->memberof);
2541 for (mem = 0; mem < 3; ++mem) {
2542 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2543 vec_push(self->living, value->members[mem]);
2547 /* PHI operands are always read operands */
2548 for (p = 0; p < vec_size(instr->phi); ++p)
2550 value = instr->phi[p].value;
2551 if (!vec_ir_value_find(self->living, value, NULL))
2552 vec_push(self->living, value);
2553 /* reading adds the full vector */
2554 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2555 vec_push(self->living, value->memberof);
2556 for (mem = 0; mem < 3; ++mem) {
2557 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2558 vec_push(self->living, value->members[mem]);
2562 /* on a call, all these values must be "locked" */
2563 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2564 if (ir_block_living_lock(self))
2567 /* call params are read operands too */
2568 for (p = 0; p < vec_size(instr->params); ++p)
2570 value = instr->params[p];
2571 if (!vec_ir_value_find(self->living, value, NULL))
2572 vec_push(self->living, value);
2573 /* reading adds the full vector */
2574 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2575 vec_push(self->living, value->memberof);
2576 for (mem = 0; mem < 3; ++mem) {
2577 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2578 vec_push(self->living, value->members[mem]);
2583 if (ir_block_living_add_instr(self, instr->eid))
2586 /* the "entry" instruction ID */
2587 if (ir_block_living_add_instr(self, self->entry_id))
2593 bool ir_function_calculate_liferanges(ir_function *self)
2598 /* parameters live at 0 */
2599 for (i = 0; i < vec_size(self->params); ++i)
2600 if (!ir_value_life_merge(self->locals[i], 0))
2601 compile_error(self->context, "internal error: failed value-life merging");
2606 i = vec_size(self->blocks);
2608 ir_block_life_propagate(self->blocks[i], &changed);
2612 if (vec_size(self->blocks)) {
2613 ir_block *block = self->blocks[0];
2614 for (i = 0; i < vec_size(block->living); ++i) {
2615 ir_value *v = block->living[i];
2616 if (v->store != store_local)
2618 if (v->vtype == TYPE_VECTOR)
2620 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2621 /* find the instruction reading from it */
2622 for (s = 0; s < vec_size(v->reads); ++s) {
2623 if (v->reads[s]->eid == v->life[0].end)
2626 if (s < vec_size(v->reads)) {
2627 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2628 "variable `%s` may be used uninitialized in this function\n"
2631 v->reads[s]->context.file, v->reads[s]->context.line)
2639 ir_value *vec = v->memberof;
2640 for (s = 0; s < vec_size(vec->reads); ++s) {
2641 if (vec->reads[s]->eid == v->life[0].end)
2644 if (s < vec_size(vec->reads)) {
2645 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2646 "variable `%s` may be used uninitialized in this function\n"
2649 vec->reads[s]->context.file, vec->reads[s]->context.line)
2657 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2658 "variable `%s` may be used uninitialized in this function", v->name))
2667 /***********************************************************************
2670 * Since the IR has the convention of putting 'write' operands
2671 * at the beginning, we have to rotate the operands of instructions
2672 * properly in order to generate valid QCVM code.
2674 * Having destinations at a fixed position is more convenient. In QC
2675 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2676 * read from from OPA, and store to OPB rather than OPC. Which is
2677 * partially the reason why the implementation of these instructions
2678 * in darkplaces has been delayed for so long.
2680 * Breaking conventions is annoying...
2682 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2684 static bool gen_global_field(code_t *code, ir_value *global)
2686 if (global->hasvalue)
2688 ir_value *fld = global->constval.vpointer;
2690 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2694 /* copy the field's value */
2695 ir_value_code_setaddr(global, vec_size(code->globals));
2696 vec_push(code->globals, fld->code.fieldaddr);
2697 if (global->fieldtype == TYPE_VECTOR) {
2698 vec_push(code->globals, fld->code.fieldaddr+1);
2699 vec_push(code->globals, fld->code.fieldaddr+2);
2704 ir_value_code_setaddr(global, vec_size(code->globals));
2705 vec_push(code->globals, 0);
2706 if (global->fieldtype == TYPE_VECTOR) {
2707 vec_push(code->globals, 0);
2708 vec_push(code->globals, 0);
2711 if (global->code.globaladdr < 0)
2716 static bool gen_global_pointer(code_t *code, ir_value *global)
2718 if (global->hasvalue)
2720 ir_value *target = global->constval.vpointer;
2722 irerror(global->context, "Invalid pointer constant: %s", global->name);
2723 /* NULL pointers are pointing to the NULL constant, which also
2724 * sits at address 0, but still has an ir_value for itself.
2729 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2730 * void() foo; <- proto
2731 * void() *fooptr = &foo;
2732 * void() foo = { code }
2734 if (!target->code.globaladdr) {
2735 /* FIXME: Check for the constant nullptr ir_value!
2736 * because then code.globaladdr being 0 is valid.
2738 irerror(global->context, "FIXME: Relocation support");
2742 ir_value_code_setaddr(global, vec_size(code->globals));
2743 vec_push(code->globals, target->code.globaladdr);
2747 ir_value_code_setaddr(global, vec_size(code->globals));
2748 vec_push(code->globals, 0);
2750 if (global->code.globaladdr < 0)
2755 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2757 prog_section_statement_t stmt;
2765 block->generated = true;
2766 block->code_start = vec_size(code->statements);
2767 for (i = 0; i < vec_size(block->instr); ++i)
2769 instr = block->instr[i];
2771 if (instr->opcode == VINSTR_PHI) {
2772 irerror(block->context, "cannot generate virtual instruction (phi)");
2776 if (instr->opcode == VINSTR_JUMP) {
2777 target = instr->bops[0];
2778 /* for uncoditional jumps, if the target hasn't been generated
2779 * yet, we generate them right here.
2781 if (!target->generated)
2782 return gen_blocks_recursive(code, func, target);
2784 /* otherwise we generate a jump instruction */
2785 stmt.opcode = INSTR_GOTO;
2786 stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2789 if (stmt.o1.s1 != 1)
2790 code_push_statement(code, &stmt, instr->context.line);
2792 /* no further instructions can be in this block */
2796 if (instr->opcode == VINSTR_COND) {
2797 ontrue = instr->bops[0];
2798 onfalse = instr->bops[1];
2799 /* TODO: have the AST signal which block should
2800 * come first: eg. optimize IFs without ELSE...
2803 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2807 if (ontrue->generated) {
2808 stmt.opcode = INSTR_IF;
2809 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
2810 if (stmt.o2.s1 != 1)
2811 code_push_statement(code, &stmt, instr->context.line);
2813 if (onfalse->generated) {
2814 stmt.opcode = INSTR_IFNOT;
2815 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
2816 if (stmt.o2.s1 != 1)
2817 code_push_statement(code, &stmt, instr->context.line);
2819 if (!ontrue->generated) {
2820 if (onfalse->generated)
2821 return gen_blocks_recursive(code, func, ontrue);
2823 if (!onfalse->generated) {
2824 if (ontrue->generated)
2825 return gen_blocks_recursive(code, func, onfalse);
2827 /* neither ontrue nor onfalse exist */
2828 stmt.opcode = INSTR_IFNOT;
2829 if (!instr->likely) {
2830 /* Honor the likelyhood hint */
2831 ir_block *tmp = onfalse;
2832 stmt.opcode = INSTR_IF;
2836 stidx = vec_size(code->statements);
2837 code_push_statement(code, &stmt, instr->context.line);
2838 /* on false we jump, so add ontrue-path */
2839 if (!gen_blocks_recursive(code, func, ontrue))
2841 /* fixup the jump address */
2842 code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
2843 /* generate onfalse path */
2844 if (onfalse->generated) {
2845 /* fixup the jump address */
2846 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2847 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2848 code->statements[stidx] = code->statements[stidx+1];
2849 if (code->statements[stidx].o1.s1 < 0)
2850 code->statements[stidx].o1.s1++;
2851 code_pop_statement(code);
2853 stmt.opcode = vec_last(code->statements).opcode;
2854 if (stmt.opcode == INSTR_GOTO ||
2855 stmt.opcode == INSTR_IF ||
2856 stmt.opcode == INSTR_IFNOT ||
2857 stmt.opcode == INSTR_RETURN ||
2858 stmt.opcode == INSTR_DONE)
2860 /* no use jumping from here */
2863 /* may have been generated in the previous recursive call */
2864 stmt.opcode = INSTR_GOTO;
2865 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
2868 if (stmt.o1.s1 != 1)
2869 code_push_statement(code, &stmt, instr->context.line);
2872 else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2873 code->statements[stidx] = code->statements[stidx+1];
2874 if (code->statements[stidx].o1.s1 < 0)
2875 code->statements[stidx].o1.s1++;
2876 code_pop_statement(code);
2878 /* if not, generate now */
2879 return gen_blocks_recursive(code, func, onfalse);
2882 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2883 || instr->opcode == VINSTR_NRCALL)
2888 first = vec_size(instr->params);
2891 for (p = 0; p < first; ++p)
2893 ir_value *param = instr->params[p];
2894 if (param->callparam)
2897 stmt.opcode = INSTR_STORE_F;
2900 if (param->vtype == TYPE_FIELD)
2901 stmt.opcode = field_store_instr[param->fieldtype];
2902 else if (param->vtype == TYPE_NIL)
2903 stmt.opcode = INSTR_STORE_V;
2905 stmt.opcode = type_store_instr[param->vtype];
2906 stmt.o1.u1 = ir_value_code_addr(param);
2907 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2908 code_push_statement(code, &stmt, instr->context.line);
2910 /* Now handle extparams */
2911 first = vec_size(instr->params);
2912 for (; p < first; ++p)
2914 ir_builder *ir = func->owner;
2915 ir_value *param = instr->params[p];
2916 ir_value *targetparam;
2918 if (param->callparam)
2921 if (p-8 >= vec_size(ir->extparams))
2922 ir_gen_extparam(ir);
2924 targetparam = ir->extparams[p-8];
2926 stmt.opcode = INSTR_STORE_F;
2929 if (param->vtype == TYPE_FIELD)
2930 stmt.opcode = field_store_instr[param->fieldtype];
2931 else if (param->vtype == TYPE_NIL)
2932 stmt.opcode = INSTR_STORE_V;
2934 stmt.opcode = type_store_instr[param->vtype];
2935 stmt.o1.u1 = ir_value_code_addr(param);
2936 stmt.o2.u1 = ir_value_code_addr(targetparam);
2937 code_push_statement(code, &stmt, instr->context.line);
2940 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2941 if (stmt.opcode > INSTR_CALL8)
2942 stmt.opcode = INSTR_CALL8;
2943 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2946 code_push_statement(code, &stmt, instr->context.line);
2948 retvalue = instr->_ops[0];
2949 if (retvalue && retvalue->store != store_return &&
2950 (retvalue->store == store_global || vec_size(retvalue->life)))
2952 /* not to be kept in OFS_RETURN */
2953 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2954 stmt.opcode = field_store_instr[retvalue->fieldtype];
2956 stmt.opcode = type_store_instr[retvalue->vtype];
2957 stmt.o1.u1 = OFS_RETURN;
2958 stmt.o2.u1 = ir_value_code_addr(retvalue);
2960 code_push_statement(code, &stmt, instr->context.line);
2965 if (instr->opcode == INSTR_STATE) {
2966 irerror(block->context, "TODO: state instruction");
2970 stmt.opcode = instr->opcode;
2975 /* This is the general order of operands */
2977 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2980 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2983 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2985 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2987 stmt.o1.u1 = stmt.o3.u1;
2990 else if ((stmt.opcode >= INSTR_STORE_F &&
2991 stmt.opcode <= INSTR_STORE_FNC) ||
2992 (stmt.opcode >= INSTR_STOREP_F &&
2993 stmt.opcode <= INSTR_STOREP_FNC))
2995 /* 2-operand instructions with A -> B */
2996 stmt.o2.u1 = stmt.o3.u1;
2999 /* tiny optimization, don't output
3002 if (stmt.o2.u1 == stmt.o1.u1 &&
3003 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
3005 ++opts_optimizationcount[OPTIM_PEEPHOLE];
3010 code_push_statement(code, &stmt, instr->context.line);
3015 static bool gen_function_code(code_t *code, ir_function *self)
3018 prog_section_statement_t stmt, *retst;
3020 /* Starting from entry point, we generate blocks "as they come"
3021 * for now. Dead blocks will not be translated obviously.
3023 if (!vec_size(self->blocks)) {
3024 irerror(self->context, "Function '%s' declared without body.", self->name);
3028 block = self->blocks[0];
3029 if (block->generated)
3032 if (!gen_blocks_recursive(code, self, block)) {
3033 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3037 /* code_write and qcvm -disasm need to know that the function ends here */
3038 retst = &vec_last(code->statements);
3039 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3040 self->outtype == TYPE_VOID &&
3041 retst->opcode == INSTR_RETURN &&
3042 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3044 retst->opcode = INSTR_DONE;
3045 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3047 stmt.opcode = INSTR_DONE;
3051 code_push_statement(code, &stmt, vec_last(code->linenums));
3056 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3058 /* NOTE: filename pointers are copied, we never strdup them,
3059 * thus we can use pointer-comparison to find the string.
3064 for (i = 0; i < vec_size(ir->filenames); ++i) {
3065 if (ir->filenames[i] == filename)
3066 return ir->filestrings[i];
3069 str = code_genstring(ir->code, filename);
3070 vec_push(ir->filenames, filename);
3071 vec_push(ir->filestrings, str);
3075 static bool gen_global_function(ir_builder *ir, ir_value *global)
3077 prog_section_function_t fun;
3082 if (!global->hasvalue || (!global->constval.vfunc))
3084 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3088 irfun = global->constval.vfunc;
3090 fun.name = global->code.name;
3091 fun.file = ir_builder_filestring(ir, global->context.file);
3092 fun.profile = 0; /* always 0 */
3093 fun.nargs = vec_size(irfun->params);
3097 for (i = 0;i < 8; ++i) {
3098 if ((int32_t)i >= fun.nargs)
3101 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3105 fun.locals = irfun->allocated_locals;
3108 fun.entry = irfun->builtin+1;
3110 irfun->code_function_def = vec_size(ir->code->functions);
3111 fun.entry = vec_size(ir->code->statements);
3114 vec_push(ir->code->functions, fun);
3118 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3123 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3124 global = ir_value_var(name, store_global, TYPE_VECTOR);
3126 vec_push(ir->extparam_protos, global);
3130 static void ir_gen_extparam(ir_builder *ir)
3132 prog_section_def_t def;
3135 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3136 global = ir_gen_extparam_proto(ir);
3138 global = ir->extparam_protos[vec_size(ir->extparams)];
3140 def.name = code_genstring(ir->code, global->name);
3141 def.type = TYPE_VECTOR;
3142 def.offset = vec_size(ir->code->globals);
3144 vec_push(ir->code->defs, def);
3146 ir_value_code_setaddr(global, def.offset);
3148 vec_push(ir->code->globals, 0);
3149 vec_push(ir->code->globals, 0);
3150 vec_push(ir->code->globals, 0);
3152 vec_push(ir->extparams, global);
3155 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3157 size_t i, ext, numparams;
3159 ir_builder *ir = self->owner;
3161 prog_section_statement_t stmt;
3163 numparams = vec_size(self->params);
3167 stmt.opcode = INSTR_STORE_F;
3169 for (i = 8; i < numparams; ++i) {
3171 if (ext >= vec_size(ir->extparams))
3172 ir_gen_extparam(ir);
3174 ep = ir->extparams[ext];
3176 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3177 if (self->locals[i]->vtype == TYPE_FIELD &&
3178 self->locals[i]->fieldtype == TYPE_VECTOR)
3180 stmt.opcode = INSTR_STORE_V;
3182 stmt.o1.u1 = ir_value_code_addr(ep);
3183 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3184 code_push_statement(code, &stmt, self->context.line);
3190 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3192 size_t i, ext, numparams, maxparams;
3194 ir_builder *ir = self->owner;
3196 prog_section_statement_t stmt;
3198 numparams = vec_size(self->params);
3202 stmt.opcode = INSTR_STORE_V;
3204 maxparams = numparams + self->max_varargs;
3205 for (i = numparams; i < maxparams; ++i) {
3207 stmt.o1.u1 = OFS_PARM0 + 3*i;
3208 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3209 code_push_statement(code, &stmt, self->context.line);
3213 while (ext >= vec_size(ir->extparams))
3214 ir_gen_extparam(ir);
3216 ep = ir->extparams[ext];
3218 stmt.o1.u1 = ir_value_code_addr(ep);
3219 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3220 code_push_statement(code, &stmt, self->context.line);
3226 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3228 prog_section_function_t *def;
3231 uint32_t firstlocal, firstglobal;
3233 irfun = global->constval.vfunc;
3234 def = ir->code->functions + irfun->code_function_def;
3236 if (OPTS_OPTION_BOOL(OPTION_G) ||
3237 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3238 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3240 firstlocal = def->firstlocal = vec_size(ir->code->globals);
3242 firstlocal = def->firstlocal = ir->first_common_local;
3243 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3246 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3248 for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3249 vec_push(ir->code->globals, 0);
3250 for (i = 0; i < vec_size(irfun->locals); ++i) {
3251 ir_value *v = irfun->locals[i];
3252 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3253 ir_value_code_setaddr(v, firstlocal + v->code.local);
3254 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3255 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3260 ir_value_code_setaddr(v, firstglobal + v->code.local);
3262 for (i = 0; i < vec_size(irfun->values); ++i)
3264 ir_value *v = irfun->values[i];
3268 ir_value_code_setaddr(v, firstlocal + v->code.local);
3270 ir_value_code_setaddr(v, firstglobal + v->code.local);
3275 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3277 prog_section_function_t *fundef;
3282 irfun = global->constval.vfunc;
3284 if (global->cvq == CV_NONE) {
3285 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3286 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3288 /* this was a function pointer, don't generate code for those */
3295 if (irfun->code_function_def < 0) {
3296 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3299 fundef = &ir->code->functions[irfun->code_function_def];
3301 fundef->entry = vec_size(ir->code->statements);
3302 if (!gen_function_locals(ir, global)) {
3303 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3306 if (!gen_function_extparam_copy(ir->code, irfun)) {
3307 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3310 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3311 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3314 if (!gen_function_code(ir->code, irfun)) {
3315 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3321 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3326 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3329 def.type = TYPE_FLOAT;
3333 component = (char*)mem_a(len+3);
3334 memcpy(component, name, len);
3336 component[len-0] = 0;
3337 component[len-2] = '_';
3339 component[len-1] = 'x';
3341 for (i = 0; i < 3; ++i) {
3342 def.name = code_genstring(code, component);
3343 vec_push(code->defs, def);
3351 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3356 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3359 fld.type = TYPE_FLOAT;
3363 component = (char*)mem_a(len+3);
3364 memcpy(component, name, len);
3366 component[len-0] = 0;
3367 component[len-2] = '_';
3369 component[len-1] = 'x';
3371 for (i = 0; i < 3; ++i) {
3372 fld.name = code_genstring(code, component);
3373 vec_push(code->fields, fld);
3381 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3385 prog_section_def_t def;
3386 bool pushdef = opts.optimizeoff;
3388 def.type = global->vtype;
3389 def.offset = vec_size(self->code->globals);
3391 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3395 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3396 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3397 (global->name[0] == '#' || global->cvq == CV_CONST))
3403 if (global->name[0] == '#') {
3404 if (!self->str_immediate)
3405 self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3406 def.name = global->code.name = self->str_immediate;
3409 def.name = global->code.name = code_genstring(self->code, global->name);
3414 def.offset = ir_value_code_addr(global);
3415 vec_push(self->code->defs, def);
3416 if (global->vtype == TYPE_VECTOR)
3417 gen_vector_defs(self->code, def, global->name);
3418 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3419 gen_vector_defs(self->code, def, global->name);
3426 switch (global->vtype)
3429 if (!strcmp(global->name, "end_sys_globals")) {
3430 /* TODO: remember this point... all the defs before this one
3431 * should be checksummed and added to progdefs.h when we generate it.
3434 else if (!strcmp(global->name, "end_sys_fields")) {
3435 /* TODO: same as above but for entity-fields rather than globsl
3439 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3441 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3442 * the system fields actually go? Though the engine knows this anyway...
3443 * Maybe this could be an -foption
3444 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3446 ir_value_code_setaddr(global, vec_size(self->code->globals));
3447 vec_push(self->code->globals, 0);
3449 if (pushdef) vec_push(self->code->defs, def);
3452 if (pushdef) vec_push(self->code->defs, def);
3453 return gen_global_pointer(self->code, global);
3456 vec_push(self->code->defs, def);
3457 if (global->fieldtype == TYPE_VECTOR)
3458 gen_vector_defs(self->code, def, global->name);
3460 return gen_global_field(self->code, global);
3465 ir_value_code_setaddr(global, vec_size(self->code->globals));
3466 if (global->hasvalue) {
3467 iptr = (int32_t*)&global->constval.ivec[0];
3468 vec_push(self->code->globals, *iptr);
3470 vec_push(self->code->globals, 0);
3472 if (!islocal && global->cvq != CV_CONST)
3473 def.type |= DEF_SAVEGLOBAL;
3474 if (pushdef) vec_push(self->code->defs, def);
3476 return global->code.globaladdr >= 0;
3480 ir_value_code_setaddr(global, vec_size(self->code->globals));
3481 if (global->hasvalue) {
3482 uint32_t load = code_genstring(self->code, global->constval.vstring);
3483 vec_push(self->code->globals, load);
3485 vec_push(self->code->globals, 0);
3487 if (!islocal && global->cvq != CV_CONST)
3488 def.type |= DEF_SAVEGLOBAL;
3489 if (pushdef) vec_push(self->code->defs, def);
3490 return global->code.globaladdr >= 0;
3495 ir_value_code_setaddr(global, vec_size(self->code->globals));
3496 if (global->hasvalue) {
3497 iptr = (int32_t*)&global->constval.ivec[0];
3498 vec_push(self->code->globals, iptr[0]);
3499 if (global->code.globaladdr < 0)
3501 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3502 vec_push(self->code->globals, iptr[d]);
3505 vec_push(self->code->globals, 0);
3506 if (global->code.globaladdr < 0)
3508 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3509 vec_push(self->code->globals, 0);
3512 if (!islocal && global->cvq != CV_CONST)
3513 def.type |= DEF_SAVEGLOBAL;
3516 vec_push(self->code->defs, def);
3517 def.type &= ~DEF_SAVEGLOBAL;
3518 gen_vector_defs(self->code, def, global->name);
3520 return global->code.globaladdr >= 0;
3523 ir_value_code_setaddr(global, vec_size(self->code->globals));
3524 if (!global->hasvalue) {
3525 vec_push(self->code->globals, 0);
3526 if (global->code.globaladdr < 0)
3529 vec_push(self->code->globals, vec_size(self->code->functions));
3530 if (!gen_global_function(self, global))
3533 if (!islocal && global->cvq != CV_CONST)
3534 def.type |= DEF_SAVEGLOBAL;
3535 if (pushdef) vec_push(self->code->defs, def);
3538 /* assume biggest type */
3539 ir_value_code_setaddr(global, vec_size(self->code->globals));
3540 vec_push(self->code->globals, 0);
3541 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3542 vec_push(self->code->globals, 0);
3545 /* refuse to create 'void' type or any other fancy business. */
3546 irerror(global->context, "Invalid type for global variable `%s`: %s",
3547 global->name, type_name[global->vtype]);
3552 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3554 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3557 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3559 prog_section_def_t def;
3560 prog_section_field_t fld;
3564 def.type = (uint16_t)field->vtype;
3565 def.offset = (uint16_t)vec_size(self->code->globals);
3567 /* create a global named the same as the field */
3568 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3569 /* in our standard, the global gets a dot prefix */
3570 size_t len = strlen(field->name);
3573 /* we really don't want to have to allocate this, and 1024
3574 * bytes is more than enough for a variable/field name
3576 if (len+2 >= sizeof(name)) {
3577 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3582 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3585 def.name = code_genstring(self->code, name);
3586 fld.name = def.name + 1; /* we reuse that string table entry */
3588 /* in plain QC, there cannot be a global with the same name,
3589 * and so we also name the global the same.
3590 * FIXME: fteqcc should create a global as well
3591 * check if it actually uses the same name. Probably does
3593 def.name = code_genstring(self->code, field->name);
3594 fld.name = def.name;
3597 field->code.name = def.name;
3599 vec_push(self->code->defs, def);
3601 fld.type = field->fieldtype;
3603 if (fld.type == TYPE_VOID) {
3604 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3608 fld.offset = field->code.fieldaddr;
3610 vec_push(self->code->fields, fld);
3612 ir_value_code_setaddr(field, vec_size(self->code->globals));
3613 vec_push(self->code->globals, fld.offset);
3614 if (fld.type == TYPE_VECTOR) {
3615 vec_push(self->code->globals, fld.offset+1);
3616 vec_push(self->code->globals, fld.offset+2);
3619 if (field->fieldtype == TYPE_VECTOR) {
3620 gen_vector_defs (self->code, def, field->name);
3621 gen_vector_fields(self->code, fld, field->name);
3624 return field->code.globaladdr >= 0;
3627 bool ir_builder_generate(ir_builder *self, const char *filename)
3629 prog_section_statement_t stmt;
3631 char *lnofile = NULL;
3633 for (i = 0; i < vec_size(self->fields); ++i)
3635 ir_builder_prepare_field(self->code, self->fields[i]);
3638 for (i = 0; i < vec_size(self->globals); ++i)
3640 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3643 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3644 ir_function *func = self->globals[i]->constval.vfunc;
3645 if (func && self->max_locals < func->allocated_locals &&
3646 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3648 self->max_locals = func->allocated_locals;
3650 if (func && self->max_globaltemps < func->globaltemps)
3651 self->max_globaltemps = func->globaltemps;
3655 for (i = 0; i < vec_size(self->fields); ++i)
3657 if (!ir_builder_gen_field(self, self->fields[i])) {
3663 ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
3664 vec_push(self->code->globals, 0);
3665 vec_push(self->code->globals, 0);
3666 vec_push(self->code->globals, 0);
3668 /* generate virtual-instruction temps */
3669 for (i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
3670 ir_value_code_setaddr(self->vinstr_temp[i], vec_size(self->code->globals));
3671 vec_push(self->code->globals, 0);
3672 vec_push(self->code->globals, 0);
3673 vec_push(self->code->globals, 0);
3676 /* generate global temps */
3677 self->first_common_globaltemp = vec_size(self->code->globals);
3678 for (i = 0; i < self->max_globaltemps; ++i) {
3679 vec_push(self->code->globals, 0);
3681 /* generate common locals */
3682 self->first_common_local = vec_size(self->code->globals);
3683 for (i = 0; i < self->max_locals; ++i) {
3684 vec_push(self->code->globals, 0);
3687 /* generate function code */
3688 for (i = 0; i < vec_size(self->globals); ++i)
3690 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3691 if (!gen_global_function_code(self, self->globals[i])) {
3697 if (vec_size(self->code->globals) >= 65536) {
3698 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3702 /* DP errors if the last instruction is not an INSTR_DONE. */
3703 if (vec_last(self->code->statements).opcode != INSTR_DONE)
3705 stmt.opcode = INSTR_DONE;
3709 code_push_statement(self->code, &stmt, vec_last(self->code->linenums));
3712 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3715 if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
3716 con_err("Linecounter wrong: %lu != %lu\n",
3717 (unsigned long)vec_size(self->code->statements),
3718 (unsigned long)vec_size(self->code->linenums));
3719 } else if (OPTS_FLAG(LNO)) {
3721 size_t filelen = strlen(filename);
3723 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3724 dot = strrchr(lnofile, '.');
3728 vec_shrinkto(lnofile, dot - lnofile);
3730 memcpy(vec_add(lnofile, 5), ".lno", 5);
3733 if (!code_write(self->code, filename, lnofile)) {
3742 /***********************************************************************
3743 *IR DEBUG Dump functions...
3746 #define IND_BUFSZ 1024
3749 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3752 static const char *qc_opname(int op)
3754 if (op < 0) return "<INVALID>";
3755 if (op < VINSTR_END)
3756 return util_instr_str[op];
3758 case VINSTR_END: return "END";
3759 case VINSTR_PHI: return "PHI";
3760 case VINSTR_JUMP: return "JUMP";
3761 case VINSTR_COND: return "COND";
3762 default: return "<UNK>";
3766 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3769 char indent[IND_BUFSZ];
3773 oprintf("module %s\n", b->name);
3774 for (i = 0; i < vec_size(b->globals); ++i)
3777 if (b->globals[i]->hasvalue)
3778 oprintf("%s = ", b->globals[i]->name);
3779 ir_value_dump(b->globals[i], oprintf);
3782 for (i = 0; i < vec_size(b->functions); ++i)
3783 ir_function_dump(b->functions[i], indent, oprintf);
3784 oprintf("endmodule %s\n", b->name);
3787 static const char *storenames[] = {
3788 "[global]", "[local]", "[param]", "[value]", "[return]"
3791 void ir_function_dump(ir_function *f, char *ind,
3792 int (*oprintf)(const char*, ...))
3795 if (f->builtin != 0) {
3796 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3799 oprintf("%sfunction %s\n", ind, f->name);
3800 strncat(ind, "\t", IND_BUFSZ-1);
3801 if (vec_size(f->locals))
3803 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3804 for (i = 0; i < vec_size(f->locals); ++i) {
3805 oprintf("%s\t", ind);
3806 ir_value_dump(f->locals[i], oprintf);
3810 oprintf("%sliferanges:\n", ind);
3811 for (i = 0; i < vec_size(f->locals); ++i) {
3812 const char *attr = "";
3814 ir_value *v = f->locals[i];
3815 if (v->unique_life && v->locked)
3816 attr = "unique,locked ";
3817 else if (v->unique_life)
3821 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3822 storenames[v->store],
3823 attr, (v->callparam ? "callparam " : ""),
3824 (int)v->code.local);
3827 for (l = 0; l < vec_size(v->life); ++l) {
3828 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3831 for (m = 0; m < 3; ++m) {
3832 ir_value *vm = v->members[m];
3835 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
3836 for (l = 0; l < vec_size(vm->life); ++l) {
3837 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3842 for (i = 0; i < vec_size(f->values); ++i) {
3843 const char *attr = "";
3845 ir_value *v = f->values[i];
3846 if (v->unique_life && v->locked)
3847 attr = "unique,locked ";
3848 else if (v->unique_life)
3852 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3853 storenames[v->store],
3854 attr, (v->callparam ? "callparam " : ""),
3855 (int)v->code.local);
3858 for (l = 0; l < vec_size(v->life); ++l) {
3859 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3862 for (m = 0; m < 3; ++m) {
3863 ir_value *vm = v->members[m];
3866 if (vm->unique_life && vm->locked)
3867 attr = "unique,locked ";
3868 else if (vm->unique_life)
3870 else if (vm->locked)
3872 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
3873 for (l = 0; l < vec_size(vm->life); ++l) {
3874 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3879 if (vec_size(f->blocks))
3881 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
3882 for (i = 0; i < vec_size(f->blocks); ++i) {
3883 ir_block_dump(f->blocks[i], ind, oprintf);
3887 ind[strlen(ind)-1] = 0;
3888 oprintf("%sendfunction %s\n", ind, f->name);
3891 void ir_block_dump(ir_block* b, char *ind,
3892 int (*oprintf)(const char*, ...))
3895 oprintf("%s:%s\n", ind, b->label);
3896 strncat(ind, "\t", IND_BUFSZ-1);
3898 if (b->instr && b->instr[0])
3899 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
3900 for (i = 0; i < vec_size(b->instr); ++i)
3901 ir_instr_dump(b->instr[i], ind, oprintf);
3902 ind[strlen(ind)-1] = 0;
3905 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3908 oprintf("%s <- phi ", in->_ops[0]->name);
3909 for (i = 0; i < vec_size(in->phi); ++i)
3911 oprintf("([%s] : %s) ", in->phi[i].from->label,
3912 in->phi[i].value->name);
3917 void ir_instr_dump(ir_instr *in, char *ind,
3918 int (*oprintf)(const char*, ...))
3921 const char *comma = NULL;
3923 oprintf("%s (%i) ", ind, (int)in->eid);
3925 if (in->opcode == VINSTR_PHI) {
3926 dump_phi(in, oprintf);
3930 strncat(ind, "\t", IND_BUFSZ-1);
3932 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3933 ir_value_dump(in->_ops[0], oprintf);
3934 if (in->_ops[1] || in->_ops[2])
3937 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3938 oprintf("CALL%i\t", vec_size(in->params));
3940 oprintf("%s\t", qc_opname(in->opcode));
3942 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3943 ir_value_dump(in->_ops[0], oprintf);
3948 for (i = 1; i != 3; ++i) {
3952 ir_value_dump(in->_ops[i], oprintf);
3960 oprintf("[%s]", in->bops[0]->label);
3964 oprintf("%s[%s]", comma, in->bops[1]->label);
3965 if (vec_size(in->params)) {
3966 oprintf("\tparams: ");
3967 for (i = 0; i != vec_size(in->params); ++i) {
3968 oprintf("%s, ", in->params[i]->name);
3972 ind[strlen(ind)-1] = 0;
3975 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3978 for (; *str; ++str) {
3980 case '\n': oprintf("\\n"); break;
3981 case '\r': oprintf("\\r"); break;
3982 case '\t': oprintf("\\t"); break;
3983 case '\v': oprintf("\\v"); break;
3984 case '\f': oprintf("\\f"); break;
3985 case '\b': oprintf("\\b"); break;
3986 case '\a': oprintf("\\a"); break;
3987 case '\\': oprintf("\\\\"); break;
3988 case '"': oprintf("\\\""); break;
3989 default: oprintf("%c", *str); break;
3995 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4004 oprintf("fn:%s", v->name);
4007 oprintf("%g", v->constval.vfloat);
4010 oprintf("'%g %g %g'",
4013 v->constval.vvec.z);
4016 oprintf("(entity)");
4019 ir_value_dump_string(v->constval.vstring, oprintf);
4023 oprintf("%i", v->constval.vint);
4028 v->constval.vpointer->name);
4032 oprintf("%s", v->name);
4036 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4039 oprintf("Life of %12s:", self->name);
4040 for (i = 0; i < vec_size(self->life); ++i)
4042 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);