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, 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, 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 ctx, const char *msg, ...)
247 con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
251 static bool irwarning(lex_ctx 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)
316 self = (ir_builder*)mem_a(sizeof(*self));
320 self->functions = NULL;
321 self->globals = NULL;
323 self->filenames = NULL;
324 self->filestrings = NULL;
325 self->htglobals = util_htnew(IR_HT_SIZE);
326 self->htfields = util_htnew(IR_HT_SIZE);
327 self->htfunctions = util_htnew(IR_HT_SIZE);
329 self->extparams = NULL;
330 self->extparam_protos = NULL;
332 self->first_common_globaltemp = 0;
333 self->max_globaltemps = 0;
334 self->first_common_local = 0;
335 self->max_locals = 0;
337 self->str_immediate = 0;
339 if (!ir_builder_set_name(self, modulename)) {
344 self->nil = ir_value_var("nil", store_value, TYPE_NIL);
345 self->nil->cvq = CV_CONST;
347 self->reserved_va_count = NULL;
348 self->code = code_init();
353 void ir_builder_delete(ir_builder* self)
356 util_htdel(self->htglobals);
357 util_htdel(self->htfields);
358 util_htdel(self->htfunctions);
359 mem_d((void*)self->name);
360 for (i = 0; i != vec_size(self->functions); ++i) {
361 ir_function_delete_quick(self->functions[i]);
363 vec_free(self->functions);
364 for (i = 0; i != vec_size(self->extparams); ++i) {
365 ir_value_delete(self->extparams[i]);
367 vec_free(self->extparams);
368 vec_free(self->extparam_protos);
369 for (i = 0; i != vec_size(self->globals); ++i) {
370 ir_value_delete(self->globals[i]);
372 vec_free(self->globals);
373 for (i = 0; i != vec_size(self->fields); ++i) {
374 ir_value_delete(self->fields[i]);
376 ir_value_delete(self->nil);
377 vec_free(self->fields);
378 vec_free(self->filenames);
379 vec_free(self->filestrings);
381 code_cleanup(self->code);
385 bool ir_builder_set_name(ir_builder *self, const char *name)
388 mem_d((void*)self->name);
389 self->name = util_strdup(name);
393 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
395 return (ir_function*)util_htget(self->htfunctions, name);
398 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
400 ir_function *fn = ir_builder_get_function(self, name);
405 fn = ir_function_new(self, outtype);
406 if (!ir_function_set_name(fn, name))
408 ir_function_delete(fn);
411 vec_push(self->functions, fn);
412 util_htset(self->htfunctions, name, fn);
414 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
416 ir_function_delete(fn);
420 fn->value->hasvalue = true;
421 fn->value->outtype = outtype;
422 fn->value->constval.vfunc = fn;
423 fn->value->context = fn->context;
428 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
430 return (ir_value*)util_htget(self->htglobals, name);
433 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
437 if (name && name[0] != '#')
439 ve = ir_builder_get_global(self, name);
445 ve = ir_value_var(name, store_global, vtype);
446 vec_push(self->globals, ve);
447 util_htset(self->htglobals, name, ve);
451 ir_value* ir_builder_get_va_count(ir_builder *self)
453 if (self->reserved_va_count)
454 return self->reserved_va_count;
455 return (self->reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
458 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
460 return (ir_value*)util_htget(self->htfields, name);
464 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
466 ir_value *ve = ir_builder_get_field(self, name);
471 ve = ir_value_var(name, store_global, TYPE_FIELD);
472 ve->fieldtype = vtype;
473 vec_push(self->fields, ve);
474 util_htset(self->htfields, name, ve);
478 /***********************************************************************
482 static bool ir_function_naive_phi(ir_function*);
483 static void ir_function_enumerate(ir_function*);
484 static bool ir_function_calculate_liferanges(ir_function*);
485 static bool ir_function_allocate_locals(ir_function*);
487 ir_function* ir_function_new(ir_builder* owner, int outtype)
490 self = (ir_function*)mem_a(sizeof(*self));
495 memset(self, 0, sizeof(*self));
498 if (!ir_function_set_name(self, "<@unnamed>")) {
505 self->context.file = "<@no context>";
506 self->context.line = 0;
507 self->outtype = outtype;
516 self->max_varargs = 0;
518 self->code_function_def = -1;
519 self->allocated_locals = 0;
520 self->globaltemps = 0;
526 bool ir_function_set_name(ir_function *self, const char *name)
529 mem_d((void*)self->name);
530 self->name = util_strdup(name);
534 static void ir_function_delete_quick(ir_function *self)
537 mem_d((void*)self->name);
539 for (i = 0; i != vec_size(self->blocks); ++i)
540 ir_block_delete_quick(self->blocks[i]);
541 vec_free(self->blocks);
543 vec_free(self->params);
545 for (i = 0; i != vec_size(self->values); ++i)
546 ir_value_delete(self->values[i]);
547 vec_free(self->values);
549 for (i = 0; i != vec_size(self->locals); ++i)
550 ir_value_delete(self->locals[i]);
551 vec_free(self->locals);
553 /* self->value is deleted by the builder */
558 void ir_function_delete(ir_function *self)
561 mem_d((void*)self->name);
563 for (i = 0; i != vec_size(self->blocks); ++i)
564 ir_block_delete(self->blocks[i]);
565 vec_free(self->blocks);
567 vec_free(self->params);
569 for (i = 0; i != vec_size(self->values); ++i)
570 ir_value_delete(self->values[i]);
571 vec_free(self->values);
573 for (i = 0; i != vec_size(self->locals); ++i)
574 ir_value_delete(self->locals[i]);
575 vec_free(self->locals);
577 /* self->value is deleted by the builder */
582 static void ir_function_collect_value(ir_function *self, ir_value *v)
584 vec_push(self->values, v);
587 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
589 ir_block* bn = ir_block_new(self, label);
591 vec_push(self->blocks, bn);
595 static bool instr_is_operation(uint16_t op)
597 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
598 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
599 (op == INSTR_ADDRESS) ||
600 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
601 (op >= INSTR_AND && op <= INSTR_BITOR) ||
602 (op >= INSTR_CALL0 && op <= INSTR_CALL8) );
605 static bool ir_function_pass_peephole(ir_function *self)
609 for (b = 0; b < vec_size(self->blocks); ++b) {
611 ir_block *block = self->blocks[b];
613 for (i = 0; i < vec_size(block->instr); ++i) {
615 inst = block->instr[i];
618 (inst->opcode >= INSTR_STORE_F &&
619 inst->opcode <= INSTR_STORE_FNC))
627 oper = block->instr[i-1];
628 if (!instr_is_operation(oper->opcode))
631 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
632 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
634 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
638 value = oper->_ops[0];
640 /* only do it for SSA values */
641 if (value->store != store_value)
644 /* don't optimize out the temp if it's used later again */
645 if (vec_size(value->reads) != 1)
648 /* The very next store must use this value */
649 if (value->reads[0] != store)
652 /* And of course the store must _read_ from it, so it's in
654 if (store->_ops[1] != value)
657 ++opts_optimizationcount[OPTIM_PEEPHOLE];
658 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
660 vec_remove(block->instr, i, 1);
661 ir_instr_delete(store);
663 else if (inst->opcode == VINSTR_COND)
665 /* COND on a value resulting from a NOT could
666 * remove the NOT and swap its operands
673 value = inst->_ops[0];
675 if (value->store != store_value ||
676 vec_size(value->reads) != 1 ||
677 value->reads[0] != inst)
682 inot = value->writes[0];
683 if (inot->_ops[0] != value ||
684 inot->opcode < INSTR_NOT_F ||
685 inot->opcode > INSTR_NOT_FNC ||
686 inot->opcode == INSTR_NOT_V || /* can't do these */
687 inot->opcode == INSTR_NOT_S)
693 ++opts_optimizationcount[OPTIM_PEEPHOLE];
695 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
698 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
699 if (tmp->instr[inotid] == inot)
702 if (inotid >= vec_size(tmp->instr)) {
703 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
706 vec_remove(tmp->instr, inotid, 1);
707 ir_instr_delete(inot);
708 /* swap ontrue/onfalse */
710 inst->bops[0] = inst->bops[1];
721 static bool ir_function_pass_tailrecursion(ir_function *self)
725 for (b = 0; b < vec_size(self->blocks); ++b) {
727 ir_instr *ret, *call, *store = NULL;
728 ir_block *block = self->blocks[b];
730 if (!block->final || vec_size(block->instr) < 2)
733 ret = block->instr[vec_size(block->instr)-1];
734 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
737 call = block->instr[vec_size(block->instr)-2];
738 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
739 /* account for the unoptimized
741 * STORE %return, %tmp
745 if (vec_size(block->instr) < 3)
749 call = block->instr[vec_size(block->instr)-3];
752 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
756 /* optimize out the STORE */
758 ret->_ops[0] == store->_ops[0] &&
759 store->_ops[1] == call->_ops[0])
761 ++opts_optimizationcount[OPTIM_PEEPHOLE];
762 call->_ops[0] = store->_ops[0];
763 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
764 ir_instr_delete(store);
773 funcval = call->_ops[1];
776 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
779 /* now we have a CALL and a RET, check if it's a tailcall */
780 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
783 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
784 vec_shrinkby(block->instr, 2);
786 block->final = false; /* open it back up */
788 /* emite parameter-stores */
789 for (p = 0; p < vec_size(call->params); ++p) {
790 /* assert(call->params_count <= self->locals_count); */
791 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
792 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
796 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
797 irerror(call->context, "failed to create tailcall jump");
801 ir_instr_delete(call);
802 ir_instr_delete(ret);
808 bool ir_function_finalize(ir_function *self)
815 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
816 if (!ir_function_pass_peephole(self)) {
817 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
822 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
823 if (!ir_function_pass_tailrecursion(self)) {
824 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
829 if (!ir_function_naive_phi(self)) {
830 irerror(self->context, "internal error: ir_function_naive_phi failed");
834 for (i = 0; i < vec_size(self->locals); ++i) {
835 ir_value *v = self->locals[i];
836 if (v->vtype == TYPE_VECTOR ||
837 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
839 ir_value_vector_member(v, 0);
840 ir_value_vector_member(v, 1);
841 ir_value_vector_member(v, 2);
844 for (i = 0; i < vec_size(self->values); ++i) {
845 ir_value *v = self->values[i];
846 if (v->vtype == TYPE_VECTOR ||
847 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
849 ir_value_vector_member(v, 0);
850 ir_value_vector_member(v, 1);
851 ir_value_vector_member(v, 2);
855 ir_function_enumerate(self);
857 if (!ir_function_calculate_liferanges(self))
859 if (!ir_function_allocate_locals(self))
864 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
869 vec_size(self->locals) &&
870 self->locals[vec_size(self->locals)-1]->store != store_param) {
871 irerror(self->context, "cannot add parameters after adding locals");
875 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
878 vec_push(self->locals, ve);
882 /***********************************************************************
886 ir_block* ir_block_new(ir_function* owner, const char *name)
889 self = (ir_block*)mem_a(sizeof(*self));
893 memset(self, 0, sizeof(*self));
896 if (name && !ir_block_set_label(self, name)) {
901 self->context.file = "<@no context>";
902 self->context.line = 0;
906 self->entries = NULL;
910 self->is_return = false;
914 self->generated = false;
919 static void ir_block_delete_quick(ir_block* self)
922 if (self->label) mem_d(self->label);
923 for (i = 0; i != vec_size(self->instr); ++i)
924 ir_instr_delete_quick(self->instr[i]);
925 vec_free(self->instr);
926 vec_free(self->entries);
927 vec_free(self->exits);
928 vec_free(self->living);
932 void ir_block_delete(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(self->instr[i]);
938 vec_free(self->instr);
939 vec_free(self->entries);
940 vec_free(self->exits);
941 vec_free(self->living);
945 bool ir_block_set_label(ir_block *self, const char *name)
948 mem_d((void*)self->label);
949 self->label = util_strdup(name);
950 return !!self->label;
953 /***********************************************************************
957 static ir_instr* ir_instr_new(lex_ctx ctx, ir_block* owner, int op)
960 self = (ir_instr*)mem_a(sizeof(*self));
967 self->_ops[0] = NULL;
968 self->_ops[1] = NULL;
969 self->_ops[2] = NULL;
970 self->bops[0] = NULL;
971 self->bops[1] = NULL;
982 static void ir_instr_delete_quick(ir_instr *self)
985 vec_free(self->params);
989 static void ir_instr_delete(ir_instr *self)
992 /* The following calls can only delete from
993 * vectors, we still want to delete this instruction
994 * so ignore the return value. Since with the warn_unused_result attribute
995 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
996 * I have to improvise here and use if(foo());
998 for (i = 0; i < vec_size(self->phi); ++i) {
1000 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
1001 vec_remove(self->phi[i].value->writes, idx, 1);
1002 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
1003 vec_remove(self->phi[i].value->reads, idx, 1);
1005 vec_free(self->phi);
1006 for (i = 0; i < vec_size(self->params); ++i) {
1008 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
1009 vec_remove(self->params[i]->writes, idx, 1);
1010 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
1011 vec_remove(self->params[i]->reads, idx, 1);
1013 vec_free(self->params);
1014 (void)!ir_instr_op(self, 0, NULL, false);
1015 (void)!ir_instr_op(self, 1, NULL, false);
1016 (void)!ir_instr_op(self, 2, NULL, false);
1020 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
1022 if (self->_ops[op]) {
1024 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1025 vec_remove(self->_ops[op]->writes, idx, 1);
1026 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1027 vec_remove(self->_ops[op]->reads, idx, 1);
1031 vec_push(v->writes, self);
1033 vec_push(v->reads, self);
1039 /***********************************************************************
1043 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1045 self->code.globaladdr = gaddr;
1046 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1047 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1048 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1051 static int32_t ir_value_code_addr(const ir_value *self)
1053 if (self->store == store_return)
1054 return OFS_RETURN + self->code.addroffset;
1055 return self->code.globaladdr + self->code.addroffset;
1058 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1061 self = (ir_value*)mem_a(sizeof(*self));
1062 self->vtype = vtype;
1063 self->fieldtype = TYPE_VOID;
1064 self->outtype = TYPE_VOID;
1065 self->store = storetype;
1069 self->writes = NULL;
1071 self->cvq = CV_NONE;
1072 self->hasvalue = false;
1073 self->context.file = "<@no context>";
1074 self->context.line = 0;
1076 if (name && !ir_value_set_name(self, name)) {
1077 irerror(self->context, "out of memory");
1082 memset(&self->constval, 0, sizeof(self->constval));
1083 memset(&self->code, 0, sizeof(self->code));
1085 self->members[0] = NULL;
1086 self->members[1] = NULL;
1087 self->members[2] = NULL;
1088 self->memberof = NULL;
1090 self->unique_life = false;
1091 self->locked = false;
1092 self->callparam = false;
1098 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1106 if (self->members[member])
1107 return self->members[member];
1110 len = strlen(self->name);
1111 name = (char*)mem_a(len + 3);
1112 memcpy(name, self->name, len);
1114 name[len+1] = 'x' + member;
1120 if (self->vtype == TYPE_VECTOR)
1122 m = ir_value_var(name, self->store, TYPE_FLOAT);
1127 m->context = self->context;
1129 self->members[member] = m;
1130 m->code.addroffset = member;
1132 else if (self->vtype == TYPE_FIELD)
1134 if (self->fieldtype != TYPE_VECTOR)
1136 m = ir_value_var(name, self->store, TYPE_FIELD);
1141 m->fieldtype = TYPE_FLOAT;
1142 m->context = self->context;
1144 self->members[member] = m;
1145 m->code.addroffset = member;
1149 irerror(self->context, "invalid member access on %s", self->name);
1157 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1159 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1160 return type_sizeof_[TYPE_VECTOR];
1161 return type_sizeof_[self->vtype];
1164 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1166 ir_value *v = ir_value_var(name, storetype, vtype);
1169 ir_function_collect_value(owner, v);
1173 void ir_value_delete(ir_value* self)
1177 mem_d((void*)self->name);
1180 if (self->vtype == TYPE_STRING)
1181 mem_d((void*)self->constval.vstring);
1183 for (i = 0; i < 3; ++i) {
1184 if (self->members[i])
1185 ir_value_delete(self->members[i]);
1187 vec_free(self->reads);
1188 vec_free(self->writes);
1189 vec_free(self->life);
1193 bool ir_value_set_name(ir_value *self, const char *name)
1196 mem_d((void*)self->name);
1197 self->name = util_strdup(name);
1198 return !!self->name;
1201 bool ir_value_set_float(ir_value *self, float f)
1203 if (self->vtype != TYPE_FLOAT)
1205 self->constval.vfloat = f;
1206 self->hasvalue = true;
1210 bool ir_value_set_func(ir_value *self, int f)
1212 if (self->vtype != TYPE_FUNCTION)
1214 self->constval.vint = f;
1215 self->hasvalue = true;
1219 bool ir_value_set_vector(ir_value *self, vector v)
1221 if (self->vtype != TYPE_VECTOR)
1223 self->constval.vvec = v;
1224 self->hasvalue = true;
1228 bool ir_value_set_field(ir_value *self, ir_value *fld)
1230 if (self->vtype != TYPE_FIELD)
1232 self->constval.vpointer = fld;
1233 self->hasvalue = true;
1237 bool ir_value_set_string(ir_value *self, const char *str)
1239 if (self->vtype != TYPE_STRING)
1241 self->constval.vstring = util_strdupe(str);
1242 self->hasvalue = true;
1247 bool ir_value_set_int(ir_value *self, int i)
1249 if (self->vtype != TYPE_INTEGER)
1251 self->constval.vint = i;
1252 self->hasvalue = true;
1257 bool ir_value_lives(ir_value *self, size_t at)
1260 for (i = 0; i < vec_size(self->life); ++i)
1262 ir_life_entry_t *life = &self->life[i];
1263 if (life->start <= at && at <= life->end)
1265 if (life->start > at) /* since it's ordered */
1271 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1274 vec_push(self->life, e);
1275 for (k = vec_size(self->life)-1; k > idx; --k)
1276 self->life[k] = self->life[k-1];
1277 self->life[idx] = e;
1281 static bool ir_value_life_merge(ir_value *self, size_t s)
1284 const size_t vs = vec_size(self->life);
1285 ir_life_entry_t *life = NULL;
1286 ir_life_entry_t *before = NULL;
1287 ir_life_entry_t new_entry;
1289 /* Find the first range >= s */
1290 for (i = 0; i < vs; ++i)
1293 life = &self->life[i];
1294 if (life->start > s)
1297 /* nothing found? append */
1300 if (life && life->end+1 == s)
1302 /* previous life range can be merged in */
1306 if (life && life->end >= s)
1308 e.start = e.end = s;
1309 vec_push(self->life, e);
1315 if (before->end + 1 == s &&
1316 life->start - 1 == s)
1319 before->end = life->end;
1320 vec_remove(self->life, i, 1);
1323 if (before->end + 1 == s)
1329 /* already contained */
1330 if (before->end >= s)
1334 if (life->start - 1 == s)
1339 /* insert a new entry */
1340 new_entry.start = new_entry.end = s;
1341 return ir_value_life_insert(self, i, new_entry);
1344 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1348 if (!vec_size(other->life))
1351 if (!vec_size(self->life)) {
1352 size_t count = vec_size(other->life);
1353 ir_life_entry_t *life = vec_add(self->life, count);
1354 memcpy(life, other->life, count * sizeof(*life));
1359 for (i = 0; i < vec_size(other->life); ++i)
1361 const ir_life_entry_t *life = &other->life[i];
1364 ir_life_entry_t *entry = &self->life[myi];
1366 if (life->end+1 < entry->start)
1368 /* adding an interval before entry */
1369 if (!ir_value_life_insert(self, myi, *life))
1375 if (life->start < entry->start &&
1376 life->end+1 >= entry->start)
1378 /* starts earlier and overlaps */
1379 entry->start = life->start;
1382 if (life->end > entry->end &&
1383 life->start <= entry->end+1)
1385 /* ends later and overlaps */
1386 entry->end = life->end;
1389 /* see if our change combines it with the next ranges */
1390 while (myi+1 < vec_size(self->life) &&
1391 entry->end+1 >= self->life[1+myi].start)
1393 /* overlaps with (myi+1) */
1394 if (entry->end < self->life[1+myi].end)
1395 entry->end = self->life[1+myi].end;
1396 vec_remove(self->life, myi+1, 1);
1397 entry = &self->life[myi];
1400 /* see if we're after the entry */
1401 if (life->start > entry->end)
1404 /* append if we're at the end */
1405 if (myi >= vec_size(self->life)) {
1406 vec_push(self->life, *life);
1409 /* otherweise check the next range */
1418 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1420 /* For any life entry in A see if it overlaps with
1421 * any life entry in B.
1422 * Note that the life entries are orderes, so we can make a
1423 * more efficient algorithm there than naively translating the
1427 ir_life_entry_t *la, *lb, *enda, *endb;
1429 /* first of all, if either has no life range, they cannot clash */
1430 if (!vec_size(a->life) || !vec_size(b->life))
1435 enda = la + vec_size(a->life);
1436 endb = lb + vec_size(b->life);
1439 /* check if the entries overlap, for that,
1440 * both must start before the other one ends.
1442 if (la->start < lb->end &&
1443 lb->start < la->end)
1448 /* entries are ordered
1449 * one entry is earlier than the other
1450 * that earlier entry will be moved forward
1452 if (la->start < lb->start)
1454 /* order: A B, move A forward
1455 * check if we hit the end with A
1460 else /* if (lb->start < la->start) actually <= */
1462 /* order: B A, move B forward
1463 * check if we hit the end with B
1472 /***********************************************************************
1476 static bool ir_check_unreachable(ir_block *self)
1478 /* The IR should never have to deal with unreachable code */
1479 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1481 irerror(self->context, "unreachable statement (%s)", self->label);
1485 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1488 if (!ir_check_unreachable(self))
1491 if (target->store == store_value &&
1492 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1494 irerror(self->context, "cannot store to an SSA value");
1495 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1496 irerror(self->context, "instruction: %s", asm_instr[op].m);
1500 in = ir_instr_new(ctx, self, op);
1504 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1505 !ir_instr_op(in, 1, what, false))
1507 ir_instr_delete(in);
1510 vec_push(self->instr, in);
1514 static bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1518 if (target->vtype == TYPE_VARIANT)
1519 vtype = what->vtype;
1521 vtype = target->vtype;
1524 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1525 op = INSTR_CONV_ITOF;
1526 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1527 op = INSTR_CONV_FTOI;
1529 op = type_store_instr[vtype];
1531 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1532 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1536 return ir_block_create_store_op(self, ctx, op, target, what);
1539 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1544 if (target->vtype != TYPE_POINTER)
1547 /* storing using pointer - target is a pointer, type must be
1548 * inferred from source
1550 vtype = what->vtype;
1552 op = type_storep_instr[vtype];
1553 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1554 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1555 op = INSTR_STOREP_V;
1558 return ir_block_create_store_op(self, ctx, op, target, what);
1561 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1564 if (!ir_check_unreachable(self))
1567 self->is_return = true;
1568 in = ir_instr_new(ctx, self, INSTR_RETURN);
1572 if (v && !ir_instr_op(in, 0, v, false)) {
1573 ir_instr_delete(in);
1577 vec_push(self->instr, in);
1581 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1582 ir_block *ontrue, ir_block *onfalse)
1585 if (!ir_check_unreachable(self))
1588 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1589 in = ir_instr_new(ctx, self, VINSTR_COND);
1593 if (!ir_instr_op(in, 0, v, false)) {
1594 ir_instr_delete(in);
1598 in->bops[0] = ontrue;
1599 in->bops[1] = onfalse;
1601 vec_push(self->instr, in);
1603 vec_push(self->exits, ontrue);
1604 vec_push(self->exits, onfalse);
1605 vec_push(ontrue->entries, self);
1606 vec_push(onfalse->entries, self);
1610 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1613 if (!ir_check_unreachable(self))
1616 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1621 vec_push(self->instr, in);
1623 vec_push(self->exits, to);
1624 vec_push(to->entries, self);
1628 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1630 self->owner->flags |= IR_FLAG_HAS_GOTO;
1631 return ir_block_create_jump(self, ctx, to);
1634 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1638 if (!ir_check_unreachable(self))
1640 in = ir_instr_new(ctx, self, VINSTR_PHI);
1643 out = ir_value_out(self->owner, label, store_value, ot);
1645 ir_instr_delete(in);
1648 if (!ir_instr_op(in, 0, out, true)) {
1649 ir_instr_delete(in);
1650 ir_value_delete(out);
1653 vec_push(self->instr, in);
1657 ir_value* ir_phi_value(ir_instr *self)
1659 return self->_ops[0];
1662 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1666 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1667 /* Must not be possible to cause this, otherwise the AST
1668 * is doing something wrong.
1670 irerror(self->context, "Invalid entry block for PHI");
1676 vec_push(v->reads, self);
1677 vec_push(self->phi, pe);
1680 /* call related code */
1681 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func, bool noreturn)
1685 if (!ir_check_unreachable(self))
1687 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1692 self->is_return = true;
1694 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1696 ir_instr_delete(in);
1699 if (!ir_instr_op(in, 0, out, true) ||
1700 !ir_instr_op(in, 1, func, false))
1702 ir_instr_delete(in);
1703 ir_value_delete(out);
1706 vec_push(self->instr, in);
1709 if (!ir_block_create_return(self, ctx, NULL)) {
1710 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1711 ir_instr_delete(in);
1719 ir_value* ir_call_value(ir_instr *self)
1721 return self->_ops[0];
1724 void ir_call_param(ir_instr* self, ir_value *v)
1726 vec_push(self->params, v);
1727 vec_push(v->reads, self);
1730 /* binary op related code */
1732 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1733 const char *label, int opcode,
1734 ir_value *left, ir_value *right)
1756 case INSTR_SUB_S: /* -- offset of string as float */
1761 case INSTR_BITOR_IF:
1762 case INSTR_BITOR_FI:
1763 case INSTR_BITAND_FI:
1764 case INSTR_BITAND_IF:
1779 case INSTR_BITAND_I:
1782 case INSTR_RSHIFT_I:
1783 case INSTR_LSHIFT_I:
1805 /* boolean operations result in floats */
1806 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1808 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1811 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1816 if (ot == TYPE_VOID) {
1817 /* The AST or parser were supposed to check this! */
1821 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1824 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1825 const char *label, int opcode,
1828 int ot = TYPE_FLOAT;
1840 /* QC doesn't have other unary operations. We expect extensions to fill
1841 * the above list, otherwise we assume out-type = in-type, eg for an
1845 ot = operand->vtype;
1848 if (ot == TYPE_VOID) {
1849 /* The AST or parser were supposed to check this! */
1853 /* let's use the general instruction creator and pass NULL for OPB */
1854 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1857 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1858 int op, ir_value *a, ir_value *b, int outype)
1863 out = ir_value_out(self->owner, label, store_value, outype);
1867 instr = ir_instr_new(ctx, self, op);
1869 ir_value_delete(out);
1873 if (!ir_instr_op(instr, 0, out, true) ||
1874 !ir_instr_op(instr, 1, a, false) ||
1875 !ir_instr_op(instr, 2, b, false) )
1880 vec_push(self->instr, instr);
1884 ir_instr_delete(instr);
1885 ir_value_delete(out);
1889 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1893 /* Support for various pointer types todo if so desired */
1894 if (ent->vtype != TYPE_ENTITY)
1897 if (field->vtype != TYPE_FIELD)
1900 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1901 v->fieldtype = field->fieldtype;
1905 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field, int outype)
1908 if (ent->vtype != TYPE_ENTITY)
1911 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1912 if (field->vtype != TYPE_FIELD)
1917 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1918 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1919 case TYPE_STRING: op = INSTR_LOAD_S; break;
1920 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1921 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1922 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1924 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1925 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1928 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1932 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1935 /* PHI resolving breaks the SSA, and must thus be the last
1936 * step before life-range calculation.
1939 static bool ir_block_naive_phi(ir_block *self);
1940 bool ir_function_naive_phi(ir_function *self)
1944 for (i = 0; i < vec_size(self->blocks); ++i)
1946 if (!ir_block_naive_phi(self->blocks[i]))
1952 static bool ir_block_naive_phi(ir_block *self)
1954 size_t i, p; /*, w;*/
1955 /* FIXME: optionally, create_phi can add the phis
1956 * to a list so we don't need to loop through blocks
1957 * - anyway: "don't optimize YET"
1959 for (i = 0; i < vec_size(self->instr); ++i)
1961 ir_instr *instr = self->instr[i];
1962 if (instr->opcode != VINSTR_PHI)
1965 vec_remove(self->instr, i, 1);
1966 --i; /* NOTE: i+1 below */
1968 for (p = 0; p < vec_size(instr->phi); ++p)
1970 ir_value *v = instr->phi[p].value;
1971 ir_block *b = instr->phi[p].from;
1973 if (v->store == store_value &&
1974 vec_size(v->reads) == 1 &&
1975 vec_size(v->writes) == 1)
1977 /* replace the value */
1978 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1983 /* force a move instruction */
1984 ir_instr *prevjump = vec_last(b->instr);
1987 instr->_ops[0]->store = store_global;
1988 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
1990 instr->_ops[0]->store = store_value;
1991 vec_push(b->instr, prevjump);
1995 ir_instr_delete(instr);
2000 /***********************************************************************
2001 *IR Temp allocation code
2002 * Propagating value life ranges by walking through the function backwards
2003 * until no more changes are made.
2004 * In theory this should happen once more than once for every nested loop
2006 * Though this implementation might run an additional time for if nests.
2009 /* Enumerate instructions used by value's life-ranges
2011 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2015 for (i = 0; i < vec_size(self->instr); ++i)
2017 self->instr[i]->eid = eid++;
2022 /* Enumerate blocks and instructions.
2023 * The block-enumeration is unordered!
2024 * We do not really use the block enumreation, however
2025 * the instruction enumeration is important for life-ranges.
2027 void ir_function_enumerate(ir_function *self)
2030 size_t instruction_id = 0;
2031 for (i = 0; i < vec_size(self->blocks); ++i)
2033 /* each block now gets an additional "entry" instruction id
2034 * we can use to avoid point-life issues
2036 self->blocks[i]->entry_id = instruction_id;
2039 self->blocks[i]->eid = i;
2040 ir_block_enumerate(self->blocks[i], &instruction_id);
2044 /* Local-value allocator
2045 * After finishing creating the liferange of all values used in a function
2046 * we can allocate their global-positions.
2047 * This is the counterpart to register-allocation in register machines.
2054 } function_allocator;
2056 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2059 size_t vsize = ir_value_sizeof(var);
2061 var->code.local = vec_size(alloc->locals);
2063 slot = ir_value_var("reg", store_global, var->vtype);
2067 if (!ir_value_life_merge_into(slot, var))
2070 vec_push(alloc->locals, slot);
2071 vec_push(alloc->sizes, vsize);
2072 vec_push(alloc->unique, var->unique_life);
2077 ir_value_delete(slot);
2081 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2087 return function_allocator_alloc(alloc, v);
2089 for (a = 0; a < vec_size(alloc->locals); ++a)
2091 /* if it's reserved for a unique liferange: skip */
2092 if (alloc->unique[a])
2095 slot = alloc->locals[a];
2097 /* never resize parameters
2098 * will be required later when overlapping temps + locals
2100 if (a < vec_size(self->params) &&
2101 alloc->sizes[a] < ir_value_sizeof(v))
2106 if (ir_values_overlap(v, slot))
2109 if (!ir_value_life_merge_into(slot, v))
2112 /* adjust size for this slot */
2113 if (alloc->sizes[a] < ir_value_sizeof(v))
2114 alloc->sizes[a] = ir_value_sizeof(v);
2119 if (a >= vec_size(alloc->locals)) {
2120 if (!function_allocator_alloc(alloc, v))
2126 bool ir_function_allocate_locals(ir_function *self)
2131 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2135 function_allocator lockalloc, globalloc;
2137 if (!vec_size(self->locals) && !vec_size(self->values))
2140 globalloc.locals = NULL;
2141 globalloc.sizes = NULL;
2142 globalloc.positions = NULL;
2143 globalloc.unique = NULL;
2144 lockalloc.locals = NULL;
2145 lockalloc.sizes = NULL;
2146 lockalloc.positions = NULL;
2147 lockalloc.unique = NULL;
2149 for (i = 0; i < vec_size(self->locals); ++i)
2151 v = self->locals[i];
2152 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2154 v->unique_life = true;
2156 else if (i >= vec_size(self->params))
2159 v->locked = true; /* lock parameters locals */
2160 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2163 for (; i < vec_size(self->locals); ++i)
2165 v = self->locals[i];
2166 if (!vec_size(v->life))
2168 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2172 /* Allocate a slot for any value that still exists */
2173 for (i = 0; i < vec_size(self->values); ++i)
2175 v = self->values[i];
2177 if (!vec_size(v->life))
2180 /* CALL optimization:
2181 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2182 * and it's not "locked", write it to the OFS_PARM directly.
2184 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2185 if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2186 (v->reads[0]->opcode == VINSTR_NRCALL ||
2187 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2192 ir_instr *call = v->reads[0];
2193 if (!vec_ir_value_find(call->params, v, ¶m)) {
2194 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2197 ++opts_optimizationcount[OPTIM_CALL_STORES];
2198 v->callparam = true;
2200 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2202 size_t nprotos = vec_size(self->owner->extparam_protos);
2205 if (nprotos > param)
2206 ep = self->owner->extparam_protos[param];
2209 ep = ir_gen_extparam_proto(self->owner);
2210 while (++nprotos <= param)
2211 ep = ir_gen_extparam_proto(self->owner);
2213 ir_instr_op(v->writes[0], 0, ep, true);
2214 call->params[param+8] = ep;
2218 if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2220 v->store = store_return;
2221 if (v->members[0]) v->members[0]->store = store_return;
2222 if (v->members[1]) v->members[1]->store = store_return;
2223 if (v->members[2]) v->members[2]->store = store_return;
2224 ++opts_optimizationcount[OPTIM_CALL_STORES];
2229 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2233 if (!lockalloc.sizes && !globalloc.sizes) {
2236 vec_push(lockalloc.positions, 0);
2237 vec_push(globalloc.positions, 0);
2239 /* Adjust slot positions based on sizes */
2240 if (lockalloc.sizes) {
2241 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2242 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2244 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2245 vec_push(lockalloc.positions, pos);
2247 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2249 if (globalloc.sizes) {
2250 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2251 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2253 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2254 vec_push(globalloc.positions, pos);
2256 self->globaltemps = pos + vec_last(globalloc.sizes);
2259 /* Locals need to know their new position */
2260 for (i = 0; i < vec_size(self->locals); ++i) {
2261 v = self->locals[i];
2262 if (v->locked || !opt_gt)
2263 v->code.local = lockalloc.positions[v->code.local];
2265 v->code.local = globalloc.positions[v->code.local];
2267 /* Take over the actual slot positions on values */
2268 for (i = 0; i < vec_size(self->values); ++i) {
2269 v = self->values[i];
2270 if (v->locked || !opt_gt)
2271 v->code.local = lockalloc.positions[v->code.local];
2273 v->code.local = globalloc.positions[v->code.local];
2281 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2282 ir_value_delete(lockalloc.locals[i]);
2283 for (i = 0; i < vec_size(globalloc.locals); ++i)
2284 ir_value_delete(globalloc.locals[i]);
2285 vec_free(globalloc.unique);
2286 vec_free(globalloc.locals);
2287 vec_free(globalloc.sizes);
2288 vec_free(globalloc.positions);
2289 vec_free(lockalloc.unique);
2290 vec_free(lockalloc.locals);
2291 vec_free(lockalloc.sizes);
2292 vec_free(lockalloc.positions);
2296 /* Get information about which operand
2297 * is read from, or written to.
2299 static void ir_op_read_write(int op, size_t *read, size_t *write)
2319 case INSTR_STOREP_F:
2320 case INSTR_STOREP_V:
2321 case INSTR_STOREP_S:
2322 case INSTR_STOREP_ENT:
2323 case INSTR_STOREP_FLD:
2324 case INSTR_STOREP_FNC:
2335 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2338 const size_t vs = vec_size(self->living);
2339 bool changed = false;
2340 for (i = 0; i != vs; ++i)
2342 if (ir_value_life_merge(self->living[i], eid))
2348 static bool ir_block_living_lock(ir_block *self)
2351 bool changed = false;
2352 for (i = 0; i != vec_size(self->living); ++i)
2354 if (!self->living[i]->locked) {
2355 self->living[i]->locked = true;
2362 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2366 size_t i, o, p, mem, cnt;
2367 /* bitmasks which operands are read from or written to */
2374 vec_free(self->living);
2376 p = vec_size(self->exits);
2377 for (i = 0; i < p; ++i) {
2378 ir_block *prev = self->exits[i];
2379 cnt = vec_size(prev->living);
2380 for (o = 0; o < cnt; ++o) {
2381 if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2382 vec_push(self->living, prev->living[o]);
2386 i = vec_size(self->instr);
2389 instr = self->instr[i];
2391 /* See which operands are read and write operands */
2392 ir_op_read_write(instr->opcode, &read, &write);
2394 /* Go through the 3 main operands
2395 * writes first, then reads
2397 for (o = 0; o < 3; ++o)
2399 if (!instr->_ops[o]) /* no such operand */
2402 value = instr->_ops[o];
2404 /* We only care about locals */
2405 /* we also calculate parameter liferanges so that locals
2406 * can take up parameter slots */
2407 if (value->store != store_value &&
2408 value->store != store_local &&
2409 value->store != store_param)
2412 /* write operands */
2413 /* When we write to a local, we consider it "dead" for the
2414 * remaining upper part of the function, since in SSA a value
2415 * can only be written once (== created)
2420 bool in_living = vec_ir_value_find(self->living, value, &idx);
2423 /* If the value isn't alive it hasn't been read before... */
2424 /* TODO: See if the warning can be emitted during parsing or AST processing
2425 * otherwise have warning printed here.
2426 * IF printing a warning here: include filecontext_t,
2427 * and make sure it's only printed once
2428 * since this function is run multiple times.
2430 /* con_err( "Value only written %s\n", value->name); */
2431 if (ir_value_life_merge(value, instr->eid))
2434 /* since 'living' won't contain it
2435 * anymore, merge the value, since
2438 if (ir_value_life_merge(value, instr->eid))
2441 vec_remove(self->living, idx, 1);
2443 /* Removing a vector removes all members */
2444 for (mem = 0; mem < 3; ++mem) {
2445 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2446 if (ir_value_life_merge(value->members[mem], instr->eid))
2448 vec_remove(self->living, idx, 1);
2451 /* Removing the last member removes the vector */
2452 if (value->memberof) {
2453 value = value->memberof;
2454 for (mem = 0; mem < 3; ++mem) {
2455 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2458 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2459 if (ir_value_life_merge(value, instr->eid))
2461 vec_remove(self->living, idx, 1);
2467 if (instr->opcode == INSTR_MUL_VF)
2469 value = instr->_ops[2];
2470 /* the float source will get an additional lifetime */
2471 if (ir_value_life_merge(value, instr->eid+1))
2473 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2476 else if (instr->opcode == INSTR_MUL_FV || instr->opcode == INSTR_LOAD_V)
2478 value = instr->_ops[1];
2479 /* the float source will get an additional lifetime */
2480 if (ir_value_life_merge(value, instr->eid+1))
2482 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2486 for (o = 0; o < 3; ++o)
2488 if (!instr->_ops[o]) /* no such operand */
2491 value = instr->_ops[o];
2493 /* We only care about locals */
2494 /* we also calculate parameter liferanges so that locals
2495 * can take up parameter slots */
2496 if (value->store != store_value &&
2497 value->store != store_local &&
2498 value->store != store_param)
2504 if (!vec_ir_value_find(self->living, value, NULL))
2505 vec_push(self->living, value);
2506 /* reading adds the full vector */
2507 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2508 vec_push(self->living, value->memberof);
2509 for (mem = 0; mem < 3; ++mem) {
2510 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2511 vec_push(self->living, value->members[mem]);
2515 /* PHI operands are always read operands */
2516 for (p = 0; p < vec_size(instr->phi); ++p)
2518 value = instr->phi[p].value;
2519 if (!vec_ir_value_find(self->living, value, NULL))
2520 vec_push(self->living, value);
2521 /* reading adds the full vector */
2522 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2523 vec_push(self->living, value->memberof);
2524 for (mem = 0; mem < 3; ++mem) {
2525 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2526 vec_push(self->living, value->members[mem]);
2530 /* on a call, all these values must be "locked" */
2531 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2532 if (ir_block_living_lock(self))
2535 /* call params are read operands too */
2536 for (p = 0; p < vec_size(instr->params); ++p)
2538 value = instr->params[p];
2539 if (!vec_ir_value_find(self->living, value, NULL))
2540 vec_push(self->living, value);
2541 /* reading adds the full vector */
2542 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2543 vec_push(self->living, value->memberof);
2544 for (mem = 0; mem < 3; ++mem) {
2545 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2546 vec_push(self->living, value->members[mem]);
2551 if (ir_block_living_add_instr(self, instr->eid))
2554 /* the "entry" instruction ID */
2555 if (ir_block_living_add_instr(self, self->entry_id))
2561 bool ir_function_calculate_liferanges(ir_function *self)
2566 /* parameters live at 0 */
2567 for (i = 0; i < vec_size(self->params); ++i)
2568 ir_value_life_merge(self->locals[i], 0);
2573 i = vec_size(self->blocks);
2575 ir_block_life_propagate(self->blocks[i], &changed);
2579 if (vec_size(self->blocks)) {
2580 ir_block *block = self->blocks[0];
2581 for (i = 0; i < vec_size(block->living); ++i) {
2582 ir_value *v = block->living[i];
2583 if (v->store != store_local)
2585 if (v->vtype == TYPE_VECTOR)
2587 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2588 /* find the instruction reading from it */
2589 for (s = 0; s < vec_size(v->reads); ++s) {
2590 if (v->reads[s]->eid == v->life[0].end)
2593 if (s < vec_size(v->reads)) {
2594 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2595 "variable `%s` may be used uninitialized in this function\n"
2598 v->reads[s]->context.file, v->reads[s]->context.line)
2606 ir_value *vec = v->memberof;
2607 for (s = 0; s < vec_size(vec->reads); ++s) {
2608 if (vec->reads[s]->eid == v->life[0].end)
2611 if (s < vec_size(vec->reads)) {
2612 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2613 "variable `%s` may be used uninitialized in this function\n"
2616 vec->reads[s]->context.file, vec->reads[s]->context.line)
2624 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2625 "variable `%s` may be used uninitialized in this function", v->name))
2634 /***********************************************************************
2637 * Since the IR has the convention of putting 'write' operands
2638 * at the beginning, we have to rotate the operands of instructions
2639 * properly in order to generate valid QCVM code.
2641 * Having destinations at a fixed position is more convenient. In QC
2642 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2643 * read from from OPA, and store to OPB rather than OPC. Which is
2644 * partially the reason why the implementation of these instructions
2645 * in darkplaces has been delayed for so long.
2647 * Breaking conventions is annoying...
2649 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2651 static bool gen_global_field(code_t *code, ir_value *global)
2653 if (global->hasvalue)
2655 ir_value *fld = global->constval.vpointer;
2657 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2661 /* copy the field's value */
2662 ir_value_code_setaddr(global, vec_size(code->globals));
2663 vec_push(code->globals, fld->code.fieldaddr);
2664 if (global->fieldtype == TYPE_VECTOR) {
2665 vec_push(code->globals, fld->code.fieldaddr+1);
2666 vec_push(code->globals, fld->code.fieldaddr+2);
2671 ir_value_code_setaddr(global, vec_size(code->globals));
2672 vec_push(code->globals, 0);
2673 if (global->fieldtype == TYPE_VECTOR) {
2674 vec_push(code->globals, 0);
2675 vec_push(code->globals, 0);
2678 if (global->code.globaladdr < 0)
2683 static bool gen_global_pointer(code_t *code, ir_value *global)
2685 if (global->hasvalue)
2687 ir_value *target = global->constval.vpointer;
2689 irerror(global->context, "Invalid pointer constant: %s", global->name);
2690 /* NULL pointers are pointing to the NULL constant, which also
2691 * sits at address 0, but still has an ir_value for itself.
2696 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2697 * void() foo; <- proto
2698 * void() *fooptr = &foo;
2699 * void() foo = { code }
2701 if (!target->code.globaladdr) {
2702 /* FIXME: Check for the constant nullptr ir_value!
2703 * because then code.globaladdr being 0 is valid.
2705 irerror(global->context, "FIXME: Relocation support");
2709 ir_value_code_setaddr(global, vec_size(code->globals));
2710 vec_push(code->globals, target->code.globaladdr);
2714 ir_value_code_setaddr(global, vec_size(code->globals));
2715 vec_push(code->globals, 0);
2717 if (global->code.globaladdr < 0)
2722 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2724 prog_section_statement stmt;
2732 block->generated = true;
2733 block->code_start = vec_size(code->statements);
2734 for (i = 0; i < vec_size(block->instr); ++i)
2736 instr = block->instr[i];
2738 if (instr->opcode == VINSTR_PHI) {
2739 irerror(block->context, "cannot generate virtual instruction (phi)");
2743 if (instr->opcode == VINSTR_JUMP) {
2744 target = instr->bops[0];
2745 /* for uncoditional jumps, if the target hasn't been generated
2746 * yet, we generate them right here.
2748 if (!target->generated)
2749 return gen_blocks_recursive(code, func, target);
2751 /* otherwise we generate a jump instruction */
2752 stmt.opcode = INSTR_GOTO;
2753 stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2756 if (stmt.o1.s1 != 1)
2757 code_push_statement(code, &stmt, instr->context.line);
2759 /* no further instructions can be in this block */
2763 if (instr->opcode == VINSTR_COND) {
2764 ontrue = instr->bops[0];
2765 onfalse = instr->bops[1];
2766 /* TODO: have the AST signal which block should
2767 * come first: eg. optimize IFs without ELSE...
2770 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2774 if (ontrue->generated) {
2775 stmt.opcode = INSTR_IF;
2776 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
2777 if (stmt.o2.s1 != 1)
2778 code_push_statement(code, &stmt, instr->context.line);
2780 if (onfalse->generated) {
2781 stmt.opcode = INSTR_IFNOT;
2782 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
2783 if (stmt.o2.s1 != 1)
2784 code_push_statement(code, &stmt, instr->context.line);
2786 if (!ontrue->generated) {
2787 if (onfalse->generated)
2788 return gen_blocks_recursive(code, func, ontrue);
2790 if (!onfalse->generated) {
2791 if (ontrue->generated)
2792 return gen_blocks_recursive(code, func, onfalse);
2794 /* neither ontrue nor onfalse exist */
2795 stmt.opcode = INSTR_IFNOT;
2796 if (!instr->likely) {
2797 /* Honor the likelyhood hint */
2798 ir_block *tmp = onfalse;
2799 stmt.opcode = INSTR_IF;
2803 stidx = vec_size(code->statements);
2804 code_push_statement(code, &stmt, instr->context.line);
2805 /* on false we jump, so add ontrue-path */
2806 if (!gen_blocks_recursive(code, func, ontrue))
2808 /* fixup the jump address */
2809 code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
2810 /* generate onfalse path */
2811 if (onfalse->generated) {
2812 /* fixup the jump address */
2813 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2814 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2815 code->statements[stidx] = code->statements[stidx+1];
2816 if (code->statements[stidx].o1.s1 < 0)
2817 code->statements[stidx].o1.s1++;
2818 code_pop_statement(code);
2820 stmt.opcode = vec_last(code->statements).opcode;
2821 if (stmt.opcode == INSTR_GOTO ||
2822 stmt.opcode == INSTR_IF ||
2823 stmt.opcode == INSTR_IFNOT ||
2824 stmt.opcode == INSTR_RETURN ||
2825 stmt.opcode == INSTR_DONE)
2827 /* no use jumping from here */
2830 /* may have been generated in the previous recursive call */
2831 stmt.opcode = INSTR_GOTO;
2832 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
2835 if (stmt.o1.s1 != 1)
2836 code_push_statement(code, &stmt, instr->context.line);
2839 else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2840 code->statements[stidx] = code->statements[stidx+1];
2841 if (code->statements[stidx].o1.s1 < 0)
2842 code->statements[stidx].o1.s1++;
2843 code_pop_statement(code);
2845 /* if not, generate now */
2846 return gen_blocks_recursive(code, func, onfalse);
2849 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2850 || instr->opcode == VINSTR_NRCALL)
2855 first = vec_size(instr->params);
2858 for (p = 0; p < first; ++p)
2860 ir_value *param = instr->params[p];
2861 if (param->callparam)
2864 stmt.opcode = INSTR_STORE_F;
2867 if (param->vtype == TYPE_FIELD)
2868 stmt.opcode = field_store_instr[param->fieldtype];
2869 else if (param->vtype == TYPE_NIL)
2870 stmt.opcode = INSTR_STORE_V;
2872 stmt.opcode = type_store_instr[param->vtype];
2873 stmt.o1.u1 = ir_value_code_addr(param);
2874 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2875 code_push_statement(code, &stmt, instr->context.line);
2877 /* Now handle extparams */
2878 first = vec_size(instr->params);
2879 for (; p < first; ++p)
2881 ir_builder *ir = func->owner;
2882 ir_value *param = instr->params[p];
2883 ir_value *targetparam;
2885 if (param->callparam)
2888 if (p-8 >= vec_size(ir->extparams))
2889 ir_gen_extparam(ir);
2891 targetparam = ir->extparams[p-8];
2893 stmt.opcode = INSTR_STORE_F;
2896 if (param->vtype == TYPE_FIELD)
2897 stmt.opcode = field_store_instr[param->fieldtype];
2898 else if (param->vtype == TYPE_NIL)
2899 stmt.opcode = INSTR_STORE_V;
2901 stmt.opcode = type_store_instr[param->vtype];
2902 stmt.o1.u1 = ir_value_code_addr(param);
2903 stmt.o2.u1 = ir_value_code_addr(targetparam);
2904 code_push_statement(code, &stmt, instr->context.line);
2907 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2908 if (stmt.opcode > INSTR_CALL8)
2909 stmt.opcode = INSTR_CALL8;
2910 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2913 code_push_statement(code, &stmt, instr->context.line);
2915 retvalue = instr->_ops[0];
2916 if (retvalue && retvalue->store != store_return &&
2917 (retvalue->store == store_global || vec_size(retvalue->life)))
2919 /* not to be kept in OFS_RETURN */
2920 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2921 stmt.opcode = field_store_instr[retvalue->fieldtype];
2923 stmt.opcode = type_store_instr[retvalue->vtype];
2924 stmt.o1.u1 = OFS_RETURN;
2925 stmt.o2.u1 = ir_value_code_addr(retvalue);
2927 code_push_statement(code, &stmt, instr->context.line);
2932 if (instr->opcode == INSTR_STATE) {
2933 irerror(block->context, "TODO: state instruction");
2937 stmt.opcode = instr->opcode;
2942 /* This is the general order of operands */
2944 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2947 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2950 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2952 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2954 stmt.o1.u1 = stmt.o3.u1;
2957 else if ((stmt.opcode >= INSTR_STORE_F &&
2958 stmt.opcode <= INSTR_STORE_FNC) ||
2959 (stmt.opcode >= INSTR_STOREP_F &&
2960 stmt.opcode <= INSTR_STOREP_FNC))
2962 /* 2-operand instructions with A -> B */
2963 stmt.o2.u1 = stmt.o3.u1;
2966 /* tiny optimization, don't output
2969 if (stmt.o2.u1 == stmt.o1.u1 &&
2970 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2972 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2977 code_push_statement(code, &stmt, instr->context.line);
2982 static bool gen_function_code(code_t *code, ir_function *self)
2985 prog_section_statement stmt, *retst;
2987 /* Starting from entry point, we generate blocks "as they come"
2988 * for now. Dead blocks will not be translated obviously.
2990 if (!vec_size(self->blocks)) {
2991 irerror(self->context, "Function '%s' declared without body.", self->name);
2995 block = self->blocks[0];
2996 if (block->generated)
2999 if (!gen_blocks_recursive(code, self, block)) {
3000 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3004 /* code_write and qcvm -disasm need to know that the function ends here */
3005 retst = &vec_last(code->statements);
3006 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3007 self->outtype == TYPE_VOID &&
3008 retst->opcode == INSTR_RETURN &&
3009 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3011 retst->opcode = INSTR_DONE;
3012 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3014 stmt.opcode = INSTR_DONE;
3018 code_push_statement(code, &stmt, vec_last(code->linenums));
3023 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
3025 /* NOTE: filename pointers are copied, we never strdup them,
3026 * thus we can use pointer-comparison to find the string.
3031 for (i = 0; i < vec_size(ir->filenames); ++i) {
3032 if (ir->filenames[i] == filename)
3033 return ir->filestrings[i];
3036 str = code_genstring(ir->code, filename);
3037 vec_push(ir->filenames, filename);
3038 vec_push(ir->filestrings, str);
3042 static bool gen_global_function(ir_builder *ir, ir_value *global)
3044 prog_section_function fun;
3049 if (!global->hasvalue || (!global->constval.vfunc))
3051 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3055 irfun = global->constval.vfunc;
3057 fun.name = global->code.name;
3058 fun.file = ir_builder_filestring(ir, global->context.file);
3059 fun.profile = 0; /* always 0 */
3060 fun.nargs = vec_size(irfun->params);
3064 for (i = 0;i < 8; ++i) {
3065 if ((int32_t)i >= fun.nargs)
3068 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3072 fun.locals = irfun->allocated_locals;
3075 fun.entry = irfun->builtin+1;
3077 irfun->code_function_def = vec_size(ir->code->functions);
3078 fun.entry = vec_size(ir->code->statements);
3081 vec_push(ir->code->functions, fun);
3085 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3090 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3091 global = ir_value_var(name, store_global, TYPE_VECTOR);
3093 vec_push(ir->extparam_protos, global);
3097 static void ir_gen_extparam(ir_builder *ir)
3099 prog_section_def def;
3102 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3103 global = ir_gen_extparam_proto(ir);
3105 global = ir->extparam_protos[vec_size(ir->extparams)];
3107 def.name = code_genstring(ir->code, global->name);
3108 def.type = TYPE_VECTOR;
3109 def.offset = vec_size(ir->code->globals);
3111 vec_push(ir->code->defs, def);
3113 ir_value_code_setaddr(global, def.offset);
3115 vec_push(ir->code->globals, 0);
3116 vec_push(ir->code->globals, 0);
3117 vec_push(ir->code->globals, 0);
3119 vec_push(ir->extparams, global);
3122 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3124 size_t i, ext, numparams;
3126 ir_builder *ir = self->owner;
3128 prog_section_statement stmt;
3130 numparams = vec_size(self->params);
3134 stmt.opcode = INSTR_STORE_F;
3136 for (i = 8; i < numparams; ++i) {
3138 if (ext >= vec_size(ir->extparams))
3139 ir_gen_extparam(ir);
3141 ep = ir->extparams[ext];
3143 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3144 if (self->locals[i]->vtype == TYPE_FIELD &&
3145 self->locals[i]->fieldtype == TYPE_VECTOR)
3147 stmt.opcode = INSTR_STORE_V;
3149 stmt.o1.u1 = ir_value_code_addr(ep);
3150 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3151 code_push_statement(code, &stmt, self->context.line);
3157 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3159 size_t i, ext, numparams, maxparams;
3161 ir_builder *ir = self->owner;
3163 prog_section_statement stmt;
3165 numparams = vec_size(self->params);
3169 stmt.opcode = INSTR_STORE_V;
3171 maxparams = numparams + self->max_varargs;
3172 for (i = numparams; i < maxparams; ++i) {
3174 stmt.o1.u1 = OFS_PARM0 + 3*i;
3175 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3176 code_push_statement(code, &stmt, self->context.line);
3180 while (ext >= vec_size(ir->extparams))
3181 ir_gen_extparam(ir);
3183 ep = ir->extparams[ext];
3185 stmt.o1.u1 = ir_value_code_addr(ep);
3186 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3187 code_push_statement(code, &stmt, self->context.line);
3193 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3195 prog_section_function *def;
3198 uint32_t firstlocal, firstglobal;
3200 irfun = global->constval.vfunc;
3201 def = ir->code->functions + irfun->code_function_def;
3203 if (OPTS_OPTION_BOOL(OPTION_G) ||
3204 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3205 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3207 firstlocal = def->firstlocal = vec_size(ir->code->globals);
3209 firstlocal = def->firstlocal = ir->first_common_local;
3210 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3213 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3215 for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3216 vec_push(ir->code->globals, 0);
3217 for (i = 0; i < vec_size(irfun->locals); ++i) {
3218 ir_value *v = irfun->locals[i];
3219 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3220 ir_value_code_setaddr(v, firstlocal + v->code.local);
3221 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3222 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3227 ir_value_code_setaddr(v, firstglobal + v->code.local);
3229 for (i = 0; i < vec_size(irfun->values); ++i)
3231 ir_value *v = irfun->values[i];
3235 ir_value_code_setaddr(v, firstlocal + v->code.local);
3237 ir_value_code_setaddr(v, firstglobal + v->code.local);
3242 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3244 prog_section_function *fundef;
3249 irfun = global->constval.vfunc;
3251 if (global->cvq == CV_NONE) {
3252 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3253 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3255 /* this was a function pointer, don't generate code for those */
3262 if (irfun->code_function_def < 0) {
3263 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3266 fundef = &ir->code->functions[irfun->code_function_def];
3268 fundef->entry = vec_size(ir->code->statements);
3269 if (!gen_function_locals(ir, global)) {
3270 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3273 if (!gen_function_extparam_copy(ir->code, irfun)) {
3274 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3277 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3278 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3281 if (!gen_function_code(ir->code, irfun)) {
3282 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3288 static void gen_vector_defs(code_t *code, prog_section_def def, const char *name)
3293 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3296 def.type = TYPE_FLOAT;
3300 component = (char*)mem_a(len+3);
3301 memcpy(component, name, len);
3303 component[len-0] = 0;
3304 component[len-2] = '_';
3306 component[len-1] = 'x';
3308 for (i = 0; i < 3; ++i) {
3309 def.name = code_genstring(code, component);
3310 vec_push(code->defs, def);
3318 static void gen_vector_fields(code_t *code, prog_section_field fld, const char *name)
3323 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3326 fld.type = TYPE_FLOAT;
3330 component = (char*)mem_a(len+3);
3331 memcpy(component, name, len);
3333 component[len-0] = 0;
3334 component[len-2] = '_';
3336 component[len-1] = 'x';
3338 for (i = 0; i < 3; ++i) {
3339 fld.name = code_genstring(code, component);
3340 vec_push(code->fields, fld);
3348 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3352 prog_section_def def;
3353 bool pushdef = opts.optimizeoff;
3355 def.type = global->vtype;
3356 def.offset = vec_size(self->code->globals);
3358 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3362 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3363 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3364 (global->name[0] == '#' || global->cvq == CV_CONST))
3369 if (pushdef && global->name) {
3370 if (global->name[0] == '#') {
3371 if (!self->str_immediate)
3372 self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3373 def.name = global->code.name = self->str_immediate;
3376 def.name = global->code.name = code_genstring(self->code, global->name);
3381 def.offset = ir_value_code_addr(global);
3382 vec_push(self->code->defs, def);
3383 if (global->vtype == TYPE_VECTOR)
3384 gen_vector_defs(self->code, def, global->name);
3385 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3386 gen_vector_defs(self->code, def, global->name);
3393 switch (global->vtype)
3396 if (!strcmp(global->name, "end_sys_globals")) {
3397 /* TODO: remember this point... all the defs before this one
3398 * should be checksummed and added to progdefs.h when we generate it.
3401 else if (!strcmp(global->name, "end_sys_fields")) {
3402 /* TODO: same as above but for entity-fields rather than globsl
3406 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3408 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3409 * the system fields actually go? Though the engine knows this anyway...
3410 * Maybe this could be an -foption
3411 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3413 ir_value_code_setaddr(global, vec_size(self->code->globals));
3414 vec_push(self->code->globals, 0);
3416 if (pushdef) vec_push(self->code->defs, def);
3419 if (pushdef) vec_push(self->code->defs, def);
3420 return gen_global_pointer(self->code, global);
3423 vec_push(self->code->defs, def);
3424 if (global->fieldtype == TYPE_VECTOR)
3425 gen_vector_defs(self->code, def, global->name);
3427 return gen_global_field(self->code, global);
3432 ir_value_code_setaddr(global, vec_size(self->code->globals));
3433 if (global->hasvalue) {
3434 iptr = (int32_t*)&global->constval.ivec[0];
3435 vec_push(self->code->globals, *iptr);
3437 vec_push(self->code->globals, 0);
3439 if (!islocal && global->cvq != CV_CONST)
3440 def.type |= DEF_SAVEGLOBAL;
3441 if (pushdef) vec_push(self->code->defs, def);
3443 return global->code.globaladdr >= 0;
3447 ir_value_code_setaddr(global, vec_size(self->code->globals));
3448 if (global->hasvalue) {
3449 uint32_t load = code_genstring(self->code, global->constval.vstring);
3450 vec_push(self->code->globals, load);
3452 vec_push(self->code->globals, 0);
3454 if (!islocal && global->cvq != CV_CONST)
3455 def.type |= DEF_SAVEGLOBAL;
3456 if (pushdef) vec_push(self->code->defs, def);
3457 return global->code.globaladdr >= 0;
3462 ir_value_code_setaddr(global, vec_size(self->code->globals));
3463 if (global->hasvalue) {
3464 iptr = (int32_t*)&global->constval.ivec[0];
3465 vec_push(self->code->globals, iptr[0]);
3466 if (global->code.globaladdr < 0)
3468 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3469 vec_push(self->code->globals, iptr[d]);
3472 vec_push(self->code->globals, 0);
3473 if (global->code.globaladdr < 0)
3475 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3476 vec_push(self->code->globals, 0);
3479 if (!islocal && global->cvq != CV_CONST)
3480 def.type |= DEF_SAVEGLOBAL;
3483 vec_push(self->code->defs, def);
3484 def.type &= ~DEF_SAVEGLOBAL;
3485 gen_vector_defs(self->code, def, global->name);
3487 return global->code.globaladdr >= 0;
3490 ir_value_code_setaddr(global, vec_size(self->code->globals));
3491 if (!global->hasvalue) {
3492 vec_push(self->code->globals, 0);
3493 if (global->code.globaladdr < 0)
3496 vec_push(self->code->globals, vec_size(self->code->functions));
3497 if (!gen_global_function(self, global))
3500 if (!islocal && global->cvq != CV_CONST)
3501 def.type |= DEF_SAVEGLOBAL;
3502 if (pushdef) vec_push(self->code->defs, def);
3505 /* assume biggest type */
3506 ir_value_code_setaddr(global, vec_size(self->code->globals));
3507 vec_push(self->code->globals, 0);
3508 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3509 vec_push(self->code->globals, 0);
3512 /* refuse to create 'void' type or any other fancy business. */
3513 irerror(global->context, "Invalid type for global variable `%s`: %s",
3514 global->name, type_name[global->vtype]);
3519 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3521 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3524 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3526 prog_section_def def;
3527 prog_section_field fld;
3531 def.type = (uint16_t)field->vtype;
3532 def.offset = (uint16_t)vec_size(self->code->globals);
3534 /* create a global named the same as the field */
3535 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3536 /* in our standard, the global gets a dot prefix */
3537 size_t len = strlen(field->name);
3540 /* we really don't want to have to allocate this, and 1024
3541 * bytes is more than enough for a variable/field name
3543 if (len+2 >= sizeof(name)) {
3544 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3549 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3552 def.name = code_genstring(self->code, name);
3553 fld.name = def.name + 1; /* we reuse that string table entry */
3555 /* in plain QC, there cannot be a global with the same name,
3556 * and so we also name the global the same.
3557 * FIXME: fteqcc should create a global as well
3558 * check if it actually uses the same name. Probably does
3560 def.name = code_genstring(self->code, field->name);
3561 fld.name = def.name;
3564 field->code.name = def.name;
3566 vec_push(self->code->defs, def);
3568 fld.type = field->fieldtype;
3570 if (fld.type == TYPE_VOID) {
3571 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3575 fld.offset = field->code.fieldaddr;
3577 vec_push(self->code->fields, fld);
3579 ir_value_code_setaddr(field, vec_size(self->code->globals));
3580 vec_push(self->code->globals, fld.offset);
3581 if (fld.type == TYPE_VECTOR) {
3582 vec_push(self->code->globals, fld.offset+1);
3583 vec_push(self->code->globals, fld.offset+2);
3586 if (field->fieldtype == TYPE_VECTOR) {
3587 gen_vector_defs (self->code, def, field->name);
3588 gen_vector_fields(self->code, fld, field->name);
3591 return field->code.globaladdr >= 0;
3594 bool ir_builder_generate(ir_builder *self, const char *filename)
3596 prog_section_statement stmt;
3598 char *lnofile = NULL;
3600 for (i = 0; i < vec_size(self->fields); ++i)
3602 ir_builder_prepare_field(self->code, self->fields[i]);
3605 for (i = 0; i < vec_size(self->globals); ++i)
3607 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3610 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3611 ir_function *func = self->globals[i]->constval.vfunc;
3612 if (func && self->max_locals < func->allocated_locals &&
3613 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3615 self->max_locals = func->allocated_locals;
3617 if (func && self->max_globaltemps < func->globaltemps)
3618 self->max_globaltemps = func->globaltemps;
3622 for (i = 0; i < vec_size(self->fields); ++i)
3624 if (!ir_builder_gen_field(self, self->fields[i])) {
3630 ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
3631 vec_push(self->code->globals, 0);
3632 vec_push(self->code->globals, 0);
3633 vec_push(self->code->globals, 0);
3635 /* generate global temps */
3636 self->first_common_globaltemp = vec_size(self->code->globals);
3637 for (i = 0; i < self->max_globaltemps; ++i) {
3638 vec_push(self->code->globals, 0);
3640 /* generate common locals */
3641 self->first_common_local = vec_size(self->code->globals);
3642 for (i = 0; i < self->max_locals; ++i) {
3643 vec_push(self->code->globals, 0);
3646 /* generate function code */
3647 for (i = 0; i < vec_size(self->globals); ++i)
3649 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3650 if (!gen_global_function_code(self, self->globals[i])) {
3656 if (vec_size(self->code->globals) >= 65536) {
3657 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3661 /* DP errors if the last instruction is not an INSTR_DONE. */
3662 if (vec_last(self->code->statements).opcode != INSTR_DONE)
3664 stmt.opcode = INSTR_DONE;
3668 code_push_statement(self->code, &stmt, vec_last(self->code->linenums));
3671 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3674 if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
3675 con_err("Linecounter wrong: %lu != %lu\n",
3676 (unsigned long)vec_size(self->code->statements),
3677 (unsigned long)vec_size(self->code->linenums));
3678 } else if (OPTS_FLAG(LNO)) {
3680 size_t filelen = strlen(filename);
3682 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3683 dot = strrchr(lnofile, '.');
3687 vec_shrinkto(lnofile, dot - lnofile);
3689 memcpy(vec_add(lnofile, 5), ".lno", 5);
3692 if (!OPTS_OPTION_BOOL(OPTION_QUIET)) {
3694 con_out("writing '%s' and '%s'...\n", filename, lnofile);
3696 con_out("writing '%s'\n", filename);
3698 if (!code_write(self->code, filename, lnofile)) {
3706 /***********************************************************************
3707 *IR DEBUG Dump functions...
3710 #define IND_BUFSZ 1024
3713 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3716 static const char *qc_opname(int op)
3718 if (op < 0) return "<INVALID>";
3719 if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3720 return asm_instr[op].m;
3722 case VINSTR_PHI: return "PHI";
3723 case VINSTR_JUMP: return "JUMP";
3724 case VINSTR_COND: return "COND";
3725 default: return "<UNK>";
3729 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3732 char indent[IND_BUFSZ];
3736 oprintf("module %s\n", b->name);
3737 for (i = 0; i < vec_size(b->globals); ++i)
3740 if (b->globals[i]->hasvalue)
3741 oprintf("%s = ", b->globals[i]->name);
3742 ir_value_dump(b->globals[i], oprintf);
3745 for (i = 0; i < vec_size(b->functions); ++i)
3746 ir_function_dump(b->functions[i], indent, oprintf);
3747 oprintf("endmodule %s\n", b->name);
3750 static const char *storenames[] = {
3751 "[global]", "[local]", "[param]", "[value]", "[return]"
3754 void ir_function_dump(ir_function *f, char *ind,
3755 int (*oprintf)(const char*, ...))
3758 if (f->builtin != 0) {
3759 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3762 oprintf("%sfunction %s\n", ind, f->name);
3763 strncat(ind, "\t", IND_BUFSZ);
3764 if (vec_size(f->locals))
3766 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3767 for (i = 0; i < vec_size(f->locals); ++i) {
3768 oprintf("%s\t", ind);
3769 ir_value_dump(f->locals[i], oprintf);
3773 oprintf("%sliferanges:\n", ind);
3774 for (i = 0; i < vec_size(f->locals); ++i) {
3775 const char *attr = "";
3777 ir_value *v = f->locals[i];
3778 if (v->unique_life && v->locked)
3779 attr = "unique,locked ";
3780 else if (v->unique_life)
3784 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3785 storenames[v->store],
3786 attr, (v->callparam ? "callparam " : ""),
3787 (int)v->code.local);
3790 for (l = 0; l < vec_size(v->life); ++l) {
3791 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3794 for (m = 0; m < 3; ++m) {
3795 ir_value *vm = v->members[m];
3798 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
3799 for (l = 0; l < vec_size(vm->life); ++l) {
3800 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3805 for (i = 0; i < vec_size(f->values); ++i) {
3806 const char *attr = "";
3808 ir_value *v = f->values[i];
3809 if (v->unique_life && v->locked)
3810 attr = "unique,locked ";
3811 else if (v->unique_life)
3815 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3816 storenames[v->store],
3817 attr, (v->callparam ? "callparam " : ""),
3818 (int)v->code.local);
3821 for (l = 0; l < vec_size(v->life); ++l) {
3822 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3825 for (m = 0; m < 3; ++m) {
3826 ir_value *vm = v->members[m];
3829 if (vm->unique_life && vm->locked)
3830 attr = "unique,locked ";
3831 else if (vm->unique_life)
3833 else if (vm->locked)
3835 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (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 if (vec_size(f->blocks))
3844 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
3845 for (i = 0; i < vec_size(f->blocks); ++i) {
3846 ir_block_dump(f->blocks[i], ind, oprintf);
3850 ind[strlen(ind)-1] = 0;
3851 oprintf("%sendfunction %s\n", ind, f->name);
3854 void ir_block_dump(ir_block* b, char *ind,
3855 int (*oprintf)(const char*, ...))
3858 oprintf("%s:%s\n", ind, b->label);
3859 strncat(ind, "\t", IND_BUFSZ);
3861 if (b->instr && b->instr[0])
3862 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
3863 for (i = 0; i < vec_size(b->instr); ++i)
3864 ir_instr_dump(b->instr[i], ind, oprintf);
3865 ind[strlen(ind)-1] = 0;
3868 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3871 oprintf("%s <- phi ", in->_ops[0]->name);
3872 for (i = 0; i < vec_size(in->phi); ++i)
3874 oprintf("([%s] : %s) ", in->phi[i].from->label,
3875 in->phi[i].value->name);
3880 void ir_instr_dump(ir_instr *in, char *ind,
3881 int (*oprintf)(const char*, ...))
3884 const char *comma = NULL;
3886 oprintf("%s (%i) ", ind, (int)in->eid);
3888 if (in->opcode == VINSTR_PHI) {
3889 dump_phi(in, oprintf);
3893 strncat(ind, "\t", IND_BUFSZ);
3895 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3896 ir_value_dump(in->_ops[0], oprintf);
3897 if (in->_ops[1] || in->_ops[2])
3900 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3901 oprintf("CALL%i\t", vec_size(in->params));
3903 oprintf("%s\t", qc_opname(in->opcode));
3905 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3906 ir_value_dump(in->_ops[0], oprintf);
3911 for (i = 1; i != 3; ++i) {
3915 ir_value_dump(in->_ops[i], oprintf);
3923 oprintf("[%s]", in->bops[0]->label);
3927 oprintf("%s[%s]", comma, in->bops[1]->label);
3928 if (vec_size(in->params)) {
3929 oprintf("\tparams: ");
3930 for (i = 0; i != vec_size(in->params); ++i) {
3931 oprintf("%s, ", in->params[i]->name);
3935 ind[strlen(ind)-1] = 0;
3938 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3941 for (; *str; ++str) {
3943 case '\n': oprintf("\\n"); break;
3944 case '\r': oprintf("\\r"); break;
3945 case '\t': oprintf("\\t"); break;
3946 case '\v': oprintf("\\v"); break;
3947 case '\f': oprintf("\\f"); break;
3948 case '\b': oprintf("\\b"); break;
3949 case '\a': oprintf("\\a"); break;
3950 case '\\': oprintf("\\\\"); break;
3951 case '"': oprintf("\\\""); break;
3952 default: oprintf("%c", *str); break;
3958 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3967 oprintf("fn:%s", v->name);
3970 oprintf("%g", v->constval.vfloat);
3973 oprintf("'%g %g %g'",
3976 v->constval.vvec.z);
3979 oprintf("(entity)");
3982 ir_value_dump_string(v->constval.vstring, oprintf);
3986 oprintf("%i", v->constval.vint);
3991 v->constval.vpointer->name);
3995 oprintf("%s", v->name);
3999 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4002 oprintf("Life of %12s:", self->name);
4003 for (i = 0; i < vec_size(self->life); ++i)
4005 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);