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 GMQCC_WARN 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) ||
616 (op >= VINSTR_BITAND_V && op <= VINSTR_NEG_V) );
619 static bool ir_function_pass_peephole(ir_function *self)
623 for (b = 0; b < vec_size(self->blocks); ++b) {
625 ir_block *block = self->blocks[b];
627 for (i = 0; i < vec_size(block->instr); ++i) {
629 inst = block->instr[i];
632 (inst->opcode >= INSTR_STORE_F &&
633 inst->opcode <= INSTR_STORE_FNC))
641 oper = block->instr[i-1];
642 if (!instr_is_operation(oper->opcode))
645 /* Don't change semantics of MUL_VF in engines where these may not alias. */
646 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
647 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
649 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
653 value = oper->_ops[0];
655 /* only do it for SSA values */
656 if (value->store != store_value)
659 /* don't optimize out the temp if it's used later again */
660 if (vec_size(value->reads) != 1)
663 /* The very next store must use this value */
664 if (value->reads[0] != store)
667 /* And of course the store must _read_ from it, so it's in
669 if (store->_ops[1] != value)
672 ++opts_optimizationcount[OPTIM_PEEPHOLE];
673 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
675 vec_remove(block->instr, i, 1);
676 ir_instr_delete(store);
678 else if (inst->opcode == VINSTR_COND)
680 /* COND on a value resulting from a NOT could
681 * remove the NOT and swap its operands
688 value = inst->_ops[0];
690 if (value->store != store_value ||
691 vec_size(value->reads) != 1 ||
692 value->reads[0] != inst)
697 inot = value->writes[0];
698 if (inot->_ops[0] != value ||
699 inot->opcode < INSTR_NOT_F ||
700 inot->opcode > INSTR_NOT_FNC ||
701 inot->opcode == INSTR_NOT_V || /* can't do these */
702 inot->opcode == INSTR_NOT_S)
708 ++opts_optimizationcount[OPTIM_PEEPHOLE];
710 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
713 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
714 if (tmp->instr[inotid] == inot)
717 if (inotid >= vec_size(tmp->instr)) {
718 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
721 vec_remove(tmp->instr, inotid, 1);
722 ir_instr_delete(inot);
723 /* swap ontrue/onfalse */
725 inst->bops[0] = inst->bops[1];
736 static bool ir_function_pass_tailrecursion(ir_function *self)
740 for (b = 0; b < vec_size(self->blocks); ++b) {
742 ir_instr *ret, *call, *store = NULL;
743 ir_block *block = self->blocks[b];
745 if (!block->final || vec_size(block->instr) < 2)
748 ret = block->instr[vec_size(block->instr)-1];
749 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
752 call = block->instr[vec_size(block->instr)-2];
753 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
754 /* account for the unoptimized
756 * STORE %return, %tmp
760 if (vec_size(block->instr) < 3)
764 call = block->instr[vec_size(block->instr)-3];
767 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
771 /* optimize out the STORE */
773 ret->_ops[0] == store->_ops[0] &&
774 store->_ops[1] == call->_ops[0])
776 ++opts_optimizationcount[OPTIM_PEEPHOLE];
777 call->_ops[0] = store->_ops[0];
778 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
779 ir_instr_delete(store);
788 funcval = call->_ops[1];
791 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
794 /* now we have a CALL and a RET, check if it's a tailcall */
795 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
798 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
799 vec_shrinkby(block->instr, 2);
801 block->final = false; /* open it back up */
803 /* emite parameter-stores */
804 for (p = 0; p < vec_size(call->params); ++p) {
805 /* assert(call->params_count <= self->locals_count); */
806 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
807 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
811 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
812 irerror(call->context, "failed to create tailcall jump");
816 ir_instr_delete(call);
817 ir_instr_delete(ret);
823 bool ir_function_finalize(ir_function *self)
830 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
831 if (!ir_function_pass_peephole(self)) {
832 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
837 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
838 if (!ir_function_pass_tailrecursion(self)) {
839 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
844 if (!ir_function_naive_phi(self)) {
845 irerror(self->context, "internal error: ir_function_naive_phi failed");
849 for (i = 0; i < vec_size(self->locals); ++i) {
850 ir_value *v = self->locals[i];
851 if (v->vtype == TYPE_VECTOR ||
852 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
854 ir_value_vector_member(v, 0);
855 ir_value_vector_member(v, 1);
856 ir_value_vector_member(v, 2);
859 for (i = 0; i < vec_size(self->values); ++i) {
860 ir_value *v = self->values[i];
861 if (v->vtype == TYPE_VECTOR ||
862 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
864 ir_value_vector_member(v, 0);
865 ir_value_vector_member(v, 1);
866 ir_value_vector_member(v, 2);
870 ir_function_enumerate(self);
872 if (!ir_function_calculate_liferanges(self))
874 if (!ir_function_allocate_locals(self))
879 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
884 vec_size(self->locals) &&
885 self->locals[vec_size(self->locals)-1]->store != store_param) {
886 irerror(self->context, "cannot add parameters after adding locals");
890 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
893 vec_push(self->locals, ve);
897 /***********************************************************************
901 ir_block* ir_block_new(ir_function* owner, const char *name)
904 self = (ir_block*)mem_a(sizeof(*self));
908 memset(self, 0, sizeof(*self));
911 if (name && !ir_block_set_label(self, name)) {
916 self->context.file = "<@no context>";
917 self->context.line = 0;
921 self->entries = NULL;
925 self->is_return = false;
929 self->generated = false;
934 static void ir_block_delete_quick(ir_block* self)
937 if (self->label) mem_d(self->label);
938 for (i = 0; i != vec_size(self->instr); ++i)
939 ir_instr_delete_quick(self->instr[i]);
940 vec_free(self->instr);
941 vec_free(self->entries);
942 vec_free(self->exits);
943 vec_free(self->living);
947 void ir_block_delete(ir_block* self)
950 if (self->label) mem_d(self->label);
951 for (i = 0; i != vec_size(self->instr); ++i)
952 ir_instr_delete(self->instr[i]);
953 vec_free(self->instr);
954 vec_free(self->entries);
955 vec_free(self->exits);
956 vec_free(self->living);
960 bool ir_block_set_label(ir_block *self, const char *name)
963 mem_d((void*)self->label);
964 self->label = util_strdup(name);
965 return !!self->label;
968 /***********************************************************************
972 static ir_instr* ir_instr_new(lex_ctx_t ctx, ir_block* owner, int op)
975 self = (ir_instr*)mem_a(sizeof(*self));
982 self->_ops[0] = NULL;
983 self->_ops[1] = NULL;
984 self->_ops[2] = NULL;
985 self->bops[0] = NULL;
986 self->bops[1] = NULL;
997 static void ir_instr_delete_quick(ir_instr *self)
1000 vec_free(self->params);
1004 static void ir_instr_delete(ir_instr *self)
1007 /* The following calls can only delete from
1008 * vectors, we still want to delete this instruction
1009 * so ignore the return value. Since with the warn_unused_result attribute
1010 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
1011 * I have to improvise here and use if(foo());
1013 for (i = 0; i < vec_size(self->phi); ++i) {
1015 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
1016 vec_remove(self->phi[i].value->writes, idx, 1);
1017 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
1018 vec_remove(self->phi[i].value->reads, idx, 1);
1020 vec_free(self->phi);
1021 for (i = 0; i < vec_size(self->params); ++i) {
1023 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
1024 vec_remove(self->params[i]->writes, idx, 1);
1025 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
1026 vec_remove(self->params[i]->reads, idx, 1);
1028 vec_free(self->params);
1029 (void)!ir_instr_op(self, 0, NULL, false);
1030 (void)!ir_instr_op(self, 1, NULL, false);
1031 (void)!ir_instr_op(self, 2, NULL, false);
1035 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
1037 if (v && v->vtype == TYPE_NOEXPR) {
1038 irerror(self->context, "tried to use a NOEXPR value");
1042 if (self->_ops[op]) {
1044 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1045 vec_remove(self->_ops[op]->writes, idx, 1);
1046 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1047 vec_remove(self->_ops[op]->reads, idx, 1);
1051 vec_push(v->writes, self);
1053 vec_push(v->reads, self);
1059 /***********************************************************************
1063 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1065 self->code.globaladdr = gaddr;
1066 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1067 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1068 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1071 static int32_t ir_value_code_addr(const ir_value *self)
1073 if (self->store == store_return)
1074 return OFS_RETURN + self->code.addroffset;
1075 return self->code.globaladdr + self->code.addroffset;
1078 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1081 self = (ir_value*)mem_a(sizeof(*self));
1082 self->vtype = vtype;
1083 self->fieldtype = TYPE_VOID;
1084 self->outtype = TYPE_VOID;
1085 self->store = storetype;
1089 self->writes = NULL;
1091 self->cvq = CV_NONE;
1092 self->hasvalue = false;
1093 self->context.file = "<@no context>";
1094 self->context.line = 0;
1096 if (name && !ir_value_set_name(self, name)) {
1097 irerror(self->context, "out of memory");
1102 memset(&self->constval, 0, sizeof(self->constval));
1103 memset(&self->code, 0, sizeof(self->code));
1105 self->members[0] = NULL;
1106 self->members[1] = NULL;
1107 self->members[2] = NULL;
1108 self->memberof = NULL;
1110 self->unique_life = false;
1111 self->locked = false;
1112 self->callparam = false;
1118 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1126 if (self->members[member])
1127 return self->members[member];
1130 len = strlen(self->name);
1131 name = (char*)mem_a(len + 3);
1132 memcpy(name, self->name, len);
1134 name[len+1] = 'x' + member;
1140 if (self->vtype == TYPE_VECTOR)
1142 m = ir_value_var(name, self->store, TYPE_FLOAT);
1147 m->context = self->context;
1149 self->members[member] = m;
1150 m->code.addroffset = member;
1152 else if (self->vtype == TYPE_FIELD)
1154 if (self->fieldtype != TYPE_VECTOR)
1156 m = ir_value_var(name, self->store, TYPE_FIELD);
1161 m->fieldtype = TYPE_FLOAT;
1162 m->context = self->context;
1164 self->members[member] = m;
1165 m->code.addroffset = member;
1169 irerror(self->context, "invalid member access on %s", self->name);
1177 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1179 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1180 return type_sizeof_[TYPE_VECTOR];
1181 return type_sizeof_[self->vtype];
1184 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1186 ir_value *v = ir_value_var(name, storetype, vtype);
1189 ir_function_collect_value(owner, v);
1193 void ir_value_delete(ir_value* self)
1197 mem_d((void*)self->name);
1200 if (self->vtype == TYPE_STRING)
1201 mem_d((void*)self->constval.vstring);
1203 for (i = 0; i < 3; ++i) {
1204 if (self->members[i])
1205 ir_value_delete(self->members[i]);
1207 vec_free(self->reads);
1208 vec_free(self->writes);
1209 vec_free(self->life);
1213 bool ir_value_set_name(ir_value *self, const char *name)
1216 mem_d((void*)self->name);
1217 self->name = util_strdup(name);
1218 return !!self->name;
1221 bool ir_value_set_float(ir_value *self, float f)
1223 if (self->vtype != TYPE_FLOAT)
1225 self->constval.vfloat = f;
1226 self->hasvalue = true;
1230 bool ir_value_set_func(ir_value *self, int f)
1232 if (self->vtype != TYPE_FUNCTION)
1234 self->constval.vint = f;
1235 self->hasvalue = true;
1239 bool ir_value_set_vector(ir_value *self, vec3_t v)
1241 if (self->vtype != TYPE_VECTOR)
1243 self->constval.vvec = v;
1244 self->hasvalue = true;
1248 bool ir_value_set_field(ir_value *self, ir_value *fld)
1250 if (self->vtype != TYPE_FIELD)
1252 self->constval.vpointer = fld;
1253 self->hasvalue = true;
1257 bool ir_value_set_string(ir_value *self, const char *str)
1259 if (self->vtype != TYPE_STRING)
1261 self->constval.vstring = util_strdupe(str);
1262 self->hasvalue = true;
1267 bool ir_value_set_int(ir_value *self, int i)
1269 if (self->vtype != TYPE_INTEGER)
1271 self->constval.vint = i;
1272 self->hasvalue = true;
1277 bool ir_value_lives(ir_value *self, size_t at)
1280 for (i = 0; i < vec_size(self->life); ++i)
1282 ir_life_entry_t *life = &self->life[i];
1283 if (life->start <= at && at <= life->end)
1285 if (life->start > at) /* since it's ordered */
1291 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1294 vec_push(self->life, e);
1295 for (k = vec_size(self->life)-1; k > idx; --k)
1296 self->life[k] = self->life[k-1];
1297 self->life[idx] = e;
1301 static bool ir_value_life_merge(ir_value *self, size_t s)
1304 const size_t vs = vec_size(self->life);
1305 ir_life_entry_t *life = NULL;
1306 ir_life_entry_t *before = NULL;
1307 ir_life_entry_t new_entry;
1309 /* Find the first range >= s */
1310 for (i = 0; i < vs; ++i)
1313 life = &self->life[i];
1314 if (life->start > s)
1317 /* nothing found? append */
1320 if (life && life->end+1 == s)
1322 /* previous life range can be merged in */
1326 if (life && life->end >= s)
1328 e.start = e.end = s;
1329 vec_push(self->life, e);
1335 if (before->end + 1 == s &&
1336 life->start - 1 == s)
1339 before->end = life->end;
1340 vec_remove(self->life, i, 1);
1343 if (before->end + 1 == s)
1349 /* already contained */
1350 if (before->end >= s)
1354 if (life->start - 1 == s)
1359 /* insert a new entry */
1360 new_entry.start = new_entry.end = s;
1361 return ir_value_life_insert(self, i, new_entry);
1364 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1368 if (!vec_size(other->life))
1371 if (!vec_size(self->life)) {
1372 size_t count = vec_size(other->life);
1373 ir_life_entry_t *life = vec_add(self->life, count);
1374 memcpy(life, other->life, count * sizeof(*life));
1379 for (i = 0; i < vec_size(other->life); ++i)
1381 const ir_life_entry_t *life = &other->life[i];
1384 ir_life_entry_t *entry = &self->life[myi];
1386 if (life->end+1 < entry->start)
1388 /* adding an interval before entry */
1389 if (!ir_value_life_insert(self, myi, *life))
1395 if (life->start < entry->start &&
1396 life->end+1 >= entry->start)
1398 /* starts earlier and overlaps */
1399 entry->start = life->start;
1402 if (life->end > entry->end &&
1403 life->start <= entry->end+1)
1405 /* ends later and overlaps */
1406 entry->end = life->end;
1409 /* see if our change combines it with the next ranges */
1410 while (myi+1 < vec_size(self->life) &&
1411 entry->end+1 >= self->life[1+myi].start)
1413 /* overlaps with (myi+1) */
1414 if (entry->end < self->life[1+myi].end)
1415 entry->end = self->life[1+myi].end;
1416 vec_remove(self->life, myi+1, 1);
1417 entry = &self->life[myi];
1420 /* see if we're after the entry */
1421 if (life->start > entry->end)
1424 /* append if we're at the end */
1425 if (myi >= vec_size(self->life)) {
1426 vec_push(self->life, *life);
1429 /* otherweise check the next range */
1438 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1440 /* For any life entry in A see if it overlaps with
1441 * any life entry in B.
1442 * Note that the life entries are orderes, so we can make a
1443 * more efficient algorithm there than naively translating the
1447 ir_life_entry_t *la, *lb, *enda, *endb;
1449 /* first of all, if either has no life range, they cannot clash */
1450 if (!vec_size(a->life) || !vec_size(b->life))
1455 enda = la + vec_size(a->life);
1456 endb = lb + vec_size(b->life);
1459 /* check if the entries overlap, for that,
1460 * both must start before the other one ends.
1462 if (la->start < lb->end &&
1463 lb->start < la->end)
1468 /* entries are ordered
1469 * one entry is earlier than the other
1470 * that earlier entry will be moved forward
1472 if (la->start < lb->start)
1474 /* order: A B, move A forward
1475 * check if we hit the end with A
1480 else /* if (lb->start < la->start) actually <= */
1482 /* order: B A, move B forward
1483 * check if we hit the end with B
1492 /***********************************************************************
1496 static bool ir_check_unreachable(ir_block *self)
1498 /* The IR should never have to deal with unreachable code */
1499 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1501 irerror(self->context, "unreachable statement (%s)", self->label);
1505 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1508 if (!ir_check_unreachable(self))
1511 if (target->store == store_value &&
1512 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1514 irerror(self->context, "cannot store to an SSA value");
1515 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1516 irerror(self->context, "instruction: %s", util_instr_str[op]);
1520 in = ir_instr_new(ctx, self, op);
1524 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1525 !ir_instr_op(in, 1, what, false))
1527 ir_instr_delete(in);
1530 vec_push(self->instr, in);
1534 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1538 if (target->vtype == TYPE_VARIANT)
1539 vtype = what->vtype;
1541 vtype = target->vtype;
1544 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1545 op = INSTR_CONV_ITOF;
1546 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1547 op = INSTR_CONV_FTOI;
1549 op = type_store_instr[vtype];
1551 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1552 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1556 return ir_block_create_store_op(self, ctx, op, target, what);
1559 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1564 if (target->vtype != TYPE_POINTER)
1567 /* storing using pointer - target is a pointer, type must be
1568 * inferred from source
1570 vtype = what->vtype;
1572 op = type_storep_instr[vtype];
1573 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1574 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1575 op = INSTR_STOREP_V;
1578 return ir_block_create_store_op(self, ctx, op, target, what);
1581 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1584 if (!ir_check_unreachable(self))
1589 /* can eliminate the return instructions for accumulation */
1590 if (self->owner->flags & IR_FLAG_ACCUMULATE)
1593 self->is_return = true;
1594 in = ir_instr_new(ctx, self, INSTR_RETURN);
1598 if (v && !ir_instr_op(in, 0, v, false)) {
1599 ir_instr_delete(in);
1603 vec_push(self->instr, in);
1607 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1608 ir_block *ontrue, ir_block *onfalse)
1611 if (!ir_check_unreachable(self))
1614 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1615 in = ir_instr_new(ctx, self, VINSTR_COND);
1619 if (!ir_instr_op(in, 0, v, false)) {
1620 ir_instr_delete(in);
1624 in->bops[0] = ontrue;
1625 in->bops[1] = onfalse;
1627 vec_push(self->instr, in);
1629 vec_push(self->exits, ontrue);
1630 vec_push(self->exits, onfalse);
1631 vec_push(ontrue->entries, self);
1632 vec_push(onfalse->entries, self);
1636 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1639 if (!ir_check_unreachable(self))
1642 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1647 vec_push(self->instr, in);
1649 vec_push(self->exits, to);
1650 vec_push(to->entries, self);
1654 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1656 self->owner->flags |= IR_FLAG_HAS_GOTO;
1657 return ir_block_create_jump(self, ctx, to);
1660 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, int ot)
1664 if (!ir_check_unreachable(self))
1666 in = ir_instr_new(ctx, self, VINSTR_PHI);
1669 out = ir_value_out(self->owner, label, store_value, ot);
1671 ir_instr_delete(in);
1674 if (!ir_instr_op(in, 0, out, true)) {
1675 ir_instr_delete(in);
1676 ir_value_delete(out);
1679 vec_push(self->instr, in);
1683 ir_value* ir_phi_value(ir_instr *self)
1685 return self->_ops[0];
1688 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1692 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1693 /* Must not be possible to cause this, otherwise the AST
1694 * is doing something wrong.
1696 irerror(self->context, "Invalid entry block for PHI");
1702 vec_push(v->reads, self);
1703 vec_push(self->phi, pe);
1706 /* call related code */
1707 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1711 if (!ir_check_unreachable(self))
1713 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1718 self->is_return = true;
1720 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1722 ir_instr_delete(in);
1725 if (!ir_instr_op(in, 0, out, true) ||
1726 !ir_instr_op(in, 1, func, false))
1728 ir_instr_delete(in);
1729 ir_value_delete(out);
1732 vec_push(self->instr, in);
1735 if (!ir_block_create_return(self, ctx, NULL)) {
1736 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1737 ir_instr_delete(in);
1745 ir_value* ir_call_value(ir_instr *self)
1747 return self->_ops[0];
1750 void ir_call_param(ir_instr* self, ir_value *v)
1752 vec_push(self->params, v);
1753 vec_push(v->reads, self);
1756 /* binary op related code */
1758 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1759 const char *label, int opcode,
1760 ir_value *left, ir_value *right)
1783 case INSTR_SUB_S: /* -- offset of string as float */
1788 case INSTR_BITOR_IF:
1789 case INSTR_BITOR_FI:
1790 case INSTR_BITAND_FI:
1791 case INSTR_BITAND_IF:
1806 case INSTR_BITAND_I:
1809 case INSTR_RSHIFT_I:
1810 case INSTR_LSHIFT_I:
1818 case VINSTR_BITAND_V:
1819 case VINSTR_BITOR_V:
1820 case VINSTR_BITXOR_V:
1821 case VINSTR_BITAND_VF:
1822 case VINSTR_BITOR_VF:
1823 case VINSTR_BITXOR_VF:
1838 * after the following default case, the value of opcode can never
1839 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1843 /* boolean operations result in floats */
1846 * opcode >= 10 takes true branch opcode is at least 10
1847 * opcode <= 23 takes false branch opcode is at least 24
1849 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1853 * At condition "opcode <= 23", the value of "opcode" must be
1855 * At condition "opcode <= 23", the value of "opcode" cannot be
1856 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1857 * The condition "opcode <= 23" cannot be true.
1859 * Thus ot=2 (TYPE_FLOAT) can never be true
1862 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1864 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1869 if (ot == TYPE_VOID) {
1870 /* The AST or parser were supposed to check this! */
1874 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1877 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1878 const char *label, int opcode,
1881 int ot = TYPE_FLOAT;
1887 case INSTR_NOT_FNC: /*
1888 case INSTR_NOT_I: */
1893 * Negation for virtual instructions is emulated with 0-value. Thankfully
1894 * the operand for 0 already exists so we just source it from here.
1897 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_F, NULL, operand, ot);
1899 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_V, NULL, operand, ot);
1902 ot = operand->vtype;
1905 if (ot == TYPE_VOID) {
1906 /* The AST or parser were supposed to check this! */
1910 /* let's use the general instruction creator and pass NULL for OPB */
1911 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1914 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1915 int op, ir_value *a, ir_value *b, int outype)
1920 out = ir_value_out(self->owner, label, store_value, outype);
1924 instr = ir_instr_new(ctx, self, op);
1926 ir_value_delete(out);
1930 if (!ir_instr_op(instr, 0, out, true) ||
1931 !ir_instr_op(instr, 1, a, false) ||
1932 !ir_instr_op(instr, 2, b, false) )
1937 vec_push(self->instr, instr);
1941 ir_instr_delete(instr);
1942 ir_value_delete(out);
1946 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1950 /* Support for various pointer types todo if so desired */
1951 if (ent->vtype != TYPE_ENTITY)
1954 if (field->vtype != TYPE_FIELD)
1957 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1958 v->fieldtype = field->fieldtype;
1962 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)
1965 if (ent->vtype != TYPE_ENTITY)
1968 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1969 if (field->vtype != TYPE_FIELD)
1974 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1975 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1976 case TYPE_STRING: op = INSTR_LOAD_S; break;
1977 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1978 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1979 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1981 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1982 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1985 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1989 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1992 /* PHI resolving breaks the SSA, and must thus be the last
1993 * step before life-range calculation.
1996 static bool ir_block_naive_phi(ir_block *self);
1997 bool ir_function_naive_phi(ir_function *self)
2001 for (i = 0; i < vec_size(self->blocks); ++i)
2003 if (!ir_block_naive_phi(self->blocks[i]))
2009 static bool ir_block_naive_phi(ir_block *self)
2011 size_t i, p; /*, w;*/
2012 /* FIXME: optionally, create_phi can add the phis
2013 * to a list so we don't need to loop through blocks
2014 * - anyway: "don't optimize YET"
2016 for (i = 0; i < vec_size(self->instr); ++i)
2018 ir_instr *instr = self->instr[i];
2019 if (instr->opcode != VINSTR_PHI)
2022 vec_remove(self->instr, i, 1);
2023 --i; /* NOTE: i+1 below */
2025 for (p = 0; p < vec_size(instr->phi); ++p)
2027 ir_value *v = instr->phi[p].value;
2028 ir_block *b = instr->phi[p].from;
2030 if (v->store == store_value &&
2031 vec_size(v->reads) == 1 &&
2032 vec_size(v->writes) == 1)
2034 /* replace the value */
2035 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2040 /* force a move instruction */
2041 ir_instr *prevjump = vec_last(b->instr);
2044 instr->_ops[0]->store = store_global;
2045 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2047 instr->_ops[0]->store = store_value;
2048 vec_push(b->instr, prevjump);
2052 ir_instr_delete(instr);
2057 /***********************************************************************
2058 *IR Temp allocation code
2059 * Propagating value life ranges by walking through the function backwards
2060 * until no more changes are made.
2061 * In theory this should happen once more than once for every nested loop
2063 * Though this implementation might run an additional time for if nests.
2066 /* Enumerate instructions used by value's life-ranges
2068 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2072 for (i = 0; i < vec_size(self->instr); ++i)
2074 self->instr[i]->eid = eid++;
2079 /* Enumerate blocks and instructions.
2080 * The block-enumeration is unordered!
2081 * We do not really use the block enumreation, however
2082 * the instruction enumeration is important for life-ranges.
2084 void ir_function_enumerate(ir_function *self)
2087 size_t instruction_id = 0;
2088 for (i = 0; i < vec_size(self->blocks); ++i)
2090 /* each block now gets an additional "entry" instruction id
2091 * we can use to avoid point-life issues
2093 self->blocks[i]->entry_id = instruction_id;
2096 self->blocks[i]->eid = i;
2097 ir_block_enumerate(self->blocks[i], &instruction_id);
2101 /* Local-value allocator
2102 * After finishing creating the liferange of all values used in a function
2103 * we can allocate their global-positions.
2104 * This is the counterpart to register-allocation in register machines.
2111 } function_allocator;
2113 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2116 size_t vsize = ir_value_sizeof(var);
2118 var->code.local = vec_size(alloc->locals);
2120 slot = ir_value_var("reg", store_global, var->vtype);
2124 if (!ir_value_life_merge_into(slot, var))
2127 vec_push(alloc->locals, slot);
2128 vec_push(alloc->sizes, vsize);
2129 vec_push(alloc->unique, var->unique_life);
2134 ir_value_delete(slot);
2138 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2144 return function_allocator_alloc(alloc, v);
2146 for (a = 0; a < vec_size(alloc->locals); ++a)
2148 /* if it's reserved for a unique liferange: skip */
2149 if (alloc->unique[a])
2152 slot = alloc->locals[a];
2154 /* never resize parameters
2155 * will be required later when overlapping temps + locals
2157 if (a < vec_size(self->params) &&
2158 alloc->sizes[a] < ir_value_sizeof(v))
2163 if (ir_values_overlap(v, slot))
2166 if (!ir_value_life_merge_into(slot, v))
2169 /* adjust size for this slot */
2170 if (alloc->sizes[a] < ir_value_sizeof(v))
2171 alloc->sizes[a] = ir_value_sizeof(v);
2176 if (a >= vec_size(alloc->locals)) {
2177 if (!function_allocator_alloc(alloc, v))
2183 bool ir_function_allocate_locals(ir_function *self)
2188 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2192 function_allocator lockalloc, globalloc;
2194 if (!vec_size(self->locals) && !vec_size(self->values))
2197 globalloc.locals = NULL;
2198 globalloc.sizes = NULL;
2199 globalloc.positions = NULL;
2200 globalloc.unique = NULL;
2201 lockalloc.locals = NULL;
2202 lockalloc.sizes = NULL;
2203 lockalloc.positions = NULL;
2204 lockalloc.unique = NULL;
2206 for (i = 0; i < vec_size(self->locals); ++i)
2208 v = self->locals[i];
2209 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2211 v->unique_life = true;
2213 else if (i >= vec_size(self->params))
2216 v->locked = true; /* lock parameters locals */
2217 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2220 for (; i < vec_size(self->locals); ++i)
2222 v = self->locals[i];
2223 if (!vec_size(v->life))
2225 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2229 /* Allocate a slot for any value that still exists */
2230 for (i = 0; i < vec_size(self->values); ++i)
2232 v = self->values[i];
2234 if (!vec_size(v->life))
2237 /* CALL optimization:
2238 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2239 * and it's not "locked", write it to the OFS_PARM directly.
2241 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2242 if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2243 (v->reads[0]->opcode == VINSTR_NRCALL ||
2244 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2249 ir_instr *call = v->reads[0];
2250 if (!vec_ir_value_find(call->params, v, ¶m)) {
2251 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2254 ++opts_optimizationcount[OPTIM_CALL_STORES];
2255 v->callparam = true;
2257 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2259 size_t nprotos = vec_size(self->owner->extparam_protos);
2262 if (nprotos > param)
2263 ep = self->owner->extparam_protos[param];
2266 ep = ir_gen_extparam_proto(self->owner);
2267 while (++nprotos <= param)
2268 ep = ir_gen_extparam_proto(self->owner);
2270 ir_instr_op(v->writes[0], 0, ep, true);
2271 call->params[param+8] = ep;
2275 if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2277 v->store = store_return;
2278 if (v->members[0]) v->members[0]->store = store_return;
2279 if (v->members[1]) v->members[1]->store = store_return;
2280 if (v->members[2]) v->members[2]->store = store_return;
2281 ++opts_optimizationcount[OPTIM_CALL_STORES];
2286 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2290 if (!lockalloc.sizes && !globalloc.sizes) {
2293 vec_push(lockalloc.positions, 0);
2294 vec_push(globalloc.positions, 0);
2296 /* Adjust slot positions based on sizes */
2297 if (lockalloc.sizes) {
2298 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2299 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2301 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2302 vec_push(lockalloc.positions, pos);
2304 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2306 if (globalloc.sizes) {
2307 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2308 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2310 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2311 vec_push(globalloc.positions, pos);
2313 self->globaltemps = pos + vec_last(globalloc.sizes);
2316 /* Locals need to know their new position */
2317 for (i = 0; i < vec_size(self->locals); ++i) {
2318 v = self->locals[i];
2319 if (v->locked || !opt_gt)
2320 v->code.local = lockalloc.positions[v->code.local];
2322 v->code.local = globalloc.positions[v->code.local];
2324 /* Take over the actual slot positions on values */
2325 for (i = 0; i < vec_size(self->values); ++i) {
2326 v = self->values[i];
2327 if (v->locked || !opt_gt)
2328 v->code.local = lockalloc.positions[v->code.local];
2330 v->code.local = globalloc.positions[v->code.local];
2338 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2339 ir_value_delete(lockalloc.locals[i]);
2340 for (i = 0; i < vec_size(globalloc.locals); ++i)
2341 ir_value_delete(globalloc.locals[i]);
2342 vec_free(globalloc.unique);
2343 vec_free(globalloc.locals);
2344 vec_free(globalloc.sizes);
2345 vec_free(globalloc.positions);
2346 vec_free(lockalloc.unique);
2347 vec_free(lockalloc.locals);
2348 vec_free(lockalloc.sizes);
2349 vec_free(lockalloc.positions);
2353 /* Get information about which operand
2354 * is read from, or written to.
2356 static void ir_op_read_write(int op, size_t *read, size_t *write)
2376 case INSTR_STOREP_F:
2377 case INSTR_STOREP_V:
2378 case INSTR_STOREP_S:
2379 case INSTR_STOREP_ENT:
2380 case INSTR_STOREP_FLD:
2381 case INSTR_STOREP_FNC:
2392 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2395 const size_t vs = vec_size(self->living);
2396 bool changed = false;
2397 for (i = 0; i != vs; ++i)
2399 if (ir_value_life_merge(self->living[i], eid))
2405 static bool ir_block_living_lock(ir_block *self)
2408 bool changed = false;
2409 for (i = 0; i != vec_size(self->living); ++i)
2411 if (!self->living[i]->locked) {
2412 self->living[i]->locked = true;
2419 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2423 size_t i, o, p, mem, cnt;
2424 /* bitmasks which operands are read from or written to */
2431 vec_free(self->living);
2433 p = vec_size(self->exits);
2434 for (i = 0; i < p; ++i) {
2435 ir_block *prev = self->exits[i];
2436 cnt = vec_size(prev->living);
2437 for (o = 0; o < cnt; ++o) {
2438 if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2439 vec_push(self->living, prev->living[o]);
2443 i = vec_size(self->instr);
2446 instr = self->instr[i];
2448 /* See which operands are read and write operands */
2449 ir_op_read_write(instr->opcode, &read, &write);
2451 /* Go through the 3 main operands
2452 * writes first, then reads
2454 for (o = 0; o < 3; ++o)
2456 if (!instr->_ops[o]) /* no such operand */
2459 value = instr->_ops[o];
2461 /* We only care about locals */
2462 /* we also calculate parameter liferanges so that locals
2463 * can take up parameter slots */
2464 if (value->store != store_value &&
2465 value->store != store_local &&
2466 value->store != store_param)
2469 /* write operands */
2470 /* When we write to a local, we consider it "dead" for the
2471 * remaining upper part of the function, since in SSA a value
2472 * can only be written once (== created)
2477 bool in_living = vec_ir_value_find(self->living, value, &idx);
2480 /* If the value isn't alive it hasn't been read before... */
2481 /* TODO: See if the warning can be emitted during parsing or AST processing
2482 * otherwise have warning printed here.
2483 * IF printing a warning here: include filecontext_t,
2484 * and make sure it's only printed once
2485 * since this function is run multiple times.
2487 /* con_err( "Value only written %s\n", value->name); */
2488 if (ir_value_life_merge(value, instr->eid))
2491 /* since 'living' won't contain it
2492 * anymore, merge the value, since
2495 if (ir_value_life_merge(value, instr->eid))
2498 vec_remove(self->living, idx, 1);
2500 /* Removing a vector removes all members */
2501 for (mem = 0; mem < 3; ++mem) {
2502 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2503 if (ir_value_life_merge(value->members[mem], instr->eid))
2505 vec_remove(self->living, idx, 1);
2508 /* Removing the last member removes the vector */
2509 if (value->memberof) {
2510 value = value->memberof;
2511 for (mem = 0; mem < 3; ++mem) {
2512 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2515 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2516 if (ir_value_life_merge(value, instr->eid))
2518 vec_remove(self->living, idx, 1);
2524 /* These operations need a special case as they can break when using
2525 * same source and destination operand otherwise, as the engine may
2526 * read the source multiple times. */
2527 if (instr->opcode == INSTR_MUL_VF ||
2528 instr->opcode == VINSTR_BITAND_VF ||
2529 instr->opcode == VINSTR_BITOR_VF ||
2530 instr->opcode == VINSTR_BITXOR ||
2531 instr->opcode == VINSTR_BITXOR_VF ||
2532 instr->opcode == VINSTR_BITXOR_V ||
2533 instr->opcode == VINSTR_CROSS)
2535 value = instr->_ops[2];
2536 /* the float source will get an additional lifetime */
2537 if (ir_value_life_merge(value, instr->eid+1))
2539 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2543 if (instr->opcode == INSTR_MUL_FV ||
2544 instr->opcode == INSTR_LOAD_V ||
2545 instr->opcode == VINSTR_BITXOR ||
2546 instr->opcode == VINSTR_BITXOR_VF ||
2547 instr->opcode == VINSTR_BITXOR_V ||
2548 instr->opcode == VINSTR_CROSS)
2550 value = instr->_ops[1];
2551 /* the float source will get an additional lifetime */
2552 if (ir_value_life_merge(value, instr->eid+1))
2554 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2558 for (o = 0; o < 3; ++o)
2560 if (!instr->_ops[o]) /* no such operand */
2563 value = instr->_ops[o];
2565 /* We only care about locals */
2566 /* we also calculate parameter liferanges so that locals
2567 * can take up parameter slots */
2568 if (value->store != store_value &&
2569 value->store != store_local &&
2570 value->store != store_param)
2576 if (!vec_ir_value_find(self->living, value, NULL))
2577 vec_push(self->living, value);
2578 /* reading adds the full vector */
2579 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2580 vec_push(self->living, value->memberof);
2581 for (mem = 0; mem < 3; ++mem) {
2582 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2583 vec_push(self->living, value->members[mem]);
2587 /* PHI operands are always read operands */
2588 for (p = 0; p < vec_size(instr->phi); ++p)
2590 value = instr->phi[p].value;
2591 if (!vec_ir_value_find(self->living, value, NULL))
2592 vec_push(self->living, value);
2593 /* reading adds the full vector */
2594 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2595 vec_push(self->living, value->memberof);
2596 for (mem = 0; mem < 3; ++mem) {
2597 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2598 vec_push(self->living, value->members[mem]);
2602 /* on a call, all these values must be "locked" */
2603 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2604 if (ir_block_living_lock(self))
2607 /* call params are read operands too */
2608 for (p = 0; p < vec_size(instr->params); ++p)
2610 value = instr->params[p];
2611 if (!vec_ir_value_find(self->living, value, NULL))
2612 vec_push(self->living, value);
2613 /* reading adds the full vector */
2614 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2615 vec_push(self->living, value->memberof);
2616 for (mem = 0; mem < 3; ++mem) {
2617 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2618 vec_push(self->living, value->members[mem]);
2623 if (ir_block_living_add_instr(self, instr->eid))
2626 /* the "entry" instruction ID */
2627 if (ir_block_living_add_instr(self, self->entry_id))
2633 bool ir_function_calculate_liferanges(ir_function *self)
2638 /* parameters live at 0 */
2639 for (i = 0; i < vec_size(self->params); ++i)
2640 if (!ir_value_life_merge(self->locals[i], 0))
2641 compile_error(self->context, "internal error: failed value-life merging");
2646 i = vec_size(self->blocks);
2648 ir_block_life_propagate(self->blocks[i], &changed);
2652 if (vec_size(self->blocks)) {
2653 ir_block *block = self->blocks[0];
2654 for (i = 0; i < vec_size(block->living); ++i) {
2655 ir_value *v = block->living[i];
2656 if (v->store != store_local)
2658 if (v->vtype == TYPE_VECTOR)
2660 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2661 /* find the instruction reading from it */
2662 for (s = 0; s < vec_size(v->reads); ++s) {
2663 if (v->reads[s]->eid == v->life[0].end)
2666 if (s < vec_size(v->reads)) {
2667 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2668 "variable `%s` may be used uninitialized in this function\n"
2671 v->reads[s]->context.file, v->reads[s]->context.line)
2679 ir_value *vec = v->memberof;
2680 for (s = 0; s < vec_size(vec->reads); ++s) {
2681 if (vec->reads[s]->eid == v->life[0].end)
2684 if (s < vec_size(vec->reads)) {
2685 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2686 "variable `%s` may be used uninitialized in this function\n"
2689 vec->reads[s]->context.file, vec->reads[s]->context.line)
2697 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2698 "variable `%s` may be used uninitialized in this function", v->name))
2707 /***********************************************************************
2710 * Since the IR has the convention of putting 'write' operands
2711 * at the beginning, we have to rotate the operands of instructions
2712 * properly in order to generate valid QCVM code.
2714 * Having destinations at a fixed position is more convenient. In QC
2715 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2716 * read from from OPA, and store to OPB rather than OPC. Which is
2717 * partially the reason why the implementation of these instructions
2718 * in darkplaces has been delayed for so long.
2720 * Breaking conventions is annoying...
2722 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2724 static bool gen_global_field(code_t *code, ir_value *global)
2726 if (global->hasvalue)
2728 ir_value *fld = global->constval.vpointer;
2730 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2734 /* copy the field's value */
2735 ir_value_code_setaddr(global, vec_size(code->globals));
2736 vec_push(code->globals, fld->code.fieldaddr);
2737 if (global->fieldtype == TYPE_VECTOR) {
2738 vec_push(code->globals, fld->code.fieldaddr+1);
2739 vec_push(code->globals, fld->code.fieldaddr+2);
2744 ir_value_code_setaddr(global, vec_size(code->globals));
2745 vec_push(code->globals, 0);
2746 if (global->fieldtype == TYPE_VECTOR) {
2747 vec_push(code->globals, 0);
2748 vec_push(code->globals, 0);
2751 if (global->code.globaladdr < 0)
2756 static bool gen_global_pointer(code_t *code, ir_value *global)
2758 if (global->hasvalue)
2760 ir_value *target = global->constval.vpointer;
2762 irerror(global->context, "Invalid pointer constant: %s", global->name);
2763 /* NULL pointers are pointing to the NULL constant, which also
2764 * sits at address 0, but still has an ir_value for itself.
2769 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2770 * void() foo; <- proto
2771 * void() *fooptr = &foo;
2772 * void() foo = { code }
2774 if (!target->code.globaladdr) {
2775 /* FIXME: Check for the constant nullptr ir_value!
2776 * because then code.globaladdr being 0 is valid.
2778 irerror(global->context, "FIXME: Relocation support");
2782 ir_value_code_setaddr(global, vec_size(code->globals));
2783 vec_push(code->globals, target->code.globaladdr);
2787 ir_value_code_setaddr(global, vec_size(code->globals));
2788 vec_push(code->globals, 0);
2790 if (global->code.globaladdr < 0)
2795 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2797 prog_section_statement_t stmt;
2806 block->generated = true;
2807 block->code_start = vec_size(code->statements);
2808 for (i = 0; i < vec_size(block->instr); ++i)
2810 instr = block->instr[i];
2812 if (instr->opcode == VINSTR_PHI) {
2813 irerror(block->context, "cannot generate virtual instruction (phi)");
2817 if (instr->opcode == VINSTR_JUMP) {
2818 target = instr->bops[0];
2819 /* for uncoditional jumps, if the target hasn't been generated
2820 * yet, we generate them right here.
2822 if (!target->generated)
2823 return gen_blocks_recursive(code, func, target);
2825 /* otherwise we generate a jump instruction */
2826 stmt.opcode = INSTR_GOTO;
2827 stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2830 if (stmt.o1.s1 != 1)
2831 code_push_statement(code, &stmt, instr->context);
2833 /* no further instructions can be in this block */
2837 if (instr->opcode == VINSTR_BITXOR) {
2838 stmt.opcode = INSTR_BITOR;
2839 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2840 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2841 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2842 code_push_statement(code, &stmt, instr->context);
2843 stmt.opcode = INSTR_BITAND;
2844 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2845 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2846 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2847 code_push_statement(code, &stmt, instr->context);
2848 stmt.opcode = INSTR_SUB_F;
2849 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2850 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2851 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2852 code_push_statement(code, &stmt, instr->context);
2854 /* instruction generated */
2858 if (instr->opcode == VINSTR_BITAND_V) {
2859 stmt.opcode = INSTR_BITAND;
2860 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2861 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2862 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2863 code_push_statement(code, &stmt, instr->context);
2867 code_push_statement(code, &stmt, instr->context);
2871 code_push_statement(code, &stmt, instr->context);
2873 /* instruction generated */
2877 if (instr->opcode == VINSTR_BITOR_V) {
2878 stmt.opcode = INSTR_BITOR;
2879 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2880 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2881 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2882 code_push_statement(code, &stmt, instr->context);
2886 code_push_statement(code, &stmt, instr->context);
2890 code_push_statement(code, &stmt, instr->context);
2892 /* instruction generated */
2896 if (instr->opcode == VINSTR_BITXOR_V) {
2897 for (j = 0; j < 3; ++j) {
2898 stmt.opcode = INSTR_BITOR;
2899 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2900 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2901 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2902 code_push_statement(code, &stmt, instr->context);
2903 stmt.opcode = INSTR_BITAND;
2904 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2905 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2906 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2907 code_push_statement(code, &stmt, instr->context);
2909 stmt.opcode = INSTR_SUB_V;
2910 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2911 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2912 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2913 code_push_statement(code, &stmt, instr->context);
2915 /* instruction generated */
2919 if (instr->opcode == VINSTR_BITAND_VF) {
2920 stmt.opcode = INSTR_BITAND;
2921 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2922 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2923 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2924 code_push_statement(code, &stmt, instr->context);
2927 code_push_statement(code, &stmt, instr->context);
2930 code_push_statement(code, &stmt, instr->context);
2932 /* instruction generated */
2936 if (instr->opcode == VINSTR_BITOR_VF) {
2937 stmt.opcode = INSTR_BITOR;
2938 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2939 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2940 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2941 code_push_statement(code, &stmt, instr->context);
2944 code_push_statement(code, &stmt, instr->context);
2947 code_push_statement(code, &stmt, instr->context);
2949 /* instruction generated */
2953 if (instr->opcode == VINSTR_BITXOR_VF) {
2954 for (j = 0; j < 3; ++j) {
2955 stmt.opcode = INSTR_BITOR;
2956 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2957 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2958 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2959 code_push_statement(code, &stmt, instr->context);
2960 stmt.opcode = INSTR_BITAND;
2961 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2962 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2963 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2964 code_push_statement(code, &stmt, instr->context);
2966 stmt.opcode = INSTR_SUB_V;
2967 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2968 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2969 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2970 code_push_statement(code, &stmt, instr->context);
2972 /* instruction generated */
2976 if (instr->opcode == VINSTR_CROSS) {
2977 stmt.opcode = INSTR_MUL_F;
2978 for (j = 0; j < 3; ++j) {
2979 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 1) % 3;
2980 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 2) % 3;
2981 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2982 code_push_statement(code, &stmt, instr->context);
2983 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 2) % 3;
2984 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 1) % 3;
2985 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2986 code_push_statement(code, &stmt, instr->context);
2988 stmt.opcode = INSTR_SUB_V;
2989 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2990 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2991 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2992 code_push_statement(code, &stmt, instr->context);
2994 /* instruction generated */
2998 if (instr->opcode == VINSTR_COND) {
2999 ontrue = instr->bops[0];
3000 onfalse = instr->bops[1];
3001 /* TODO: have the AST signal which block should
3002 * come first: eg. optimize IFs without ELSE...
3005 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
3009 if (ontrue->generated) {
3010 stmt.opcode = INSTR_IF;
3011 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
3012 if (stmt.o2.s1 != 1)
3013 code_push_statement(code, &stmt, instr->context);
3015 if (onfalse->generated) {
3016 stmt.opcode = INSTR_IFNOT;
3017 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
3018 if (stmt.o2.s1 != 1)
3019 code_push_statement(code, &stmt, instr->context);
3021 if (!ontrue->generated) {
3022 if (onfalse->generated)
3023 return gen_blocks_recursive(code, func, ontrue);
3025 if (!onfalse->generated) {
3026 if (ontrue->generated)
3027 return gen_blocks_recursive(code, func, onfalse);
3029 /* neither ontrue nor onfalse exist */
3030 stmt.opcode = INSTR_IFNOT;
3031 if (!instr->likely) {
3032 /* Honor the likelyhood hint */
3033 ir_block *tmp = onfalse;
3034 stmt.opcode = INSTR_IF;
3038 stidx = vec_size(code->statements);
3039 code_push_statement(code, &stmt, instr->context);
3040 /* on false we jump, so add ontrue-path */
3041 if (!gen_blocks_recursive(code, func, ontrue))
3043 /* fixup the jump address */
3044 code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
3045 /* generate onfalse path */
3046 if (onfalse->generated) {
3047 /* fixup the jump address */
3048 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
3049 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
3050 code->statements[stidx] = code->statements[stidx+1];
3051 if (code->statements[stidx].o1.s1 < 0)
3052 code->statements[stidx].o1.s1++;
3053 code_pop_statement(code);
3055 stmt.opcode = vec_last(code->statements).opcode;
3056 if (stmt.opcode == INSTR_GOTO ||
3057 stmt.opcode == INSTR_IF ||
3058 stmt.opcode == INSTR_IFNOT ||
3059 stmt.opcode == INSTR_RETURN ||
3060 stmt.opcode == INSTR_DONE)
3062 /* no use jumping from here */
3065 /* may have been generated in the previous recursive call */
3066 stmt.opcode = INSTR_GOTO;
3067 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
3070 if (stmt.o1.s1 != 1)
3071 code_push_statement(code, &stmt, instr->context);
3074 else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
3075 code->statements[stidx] = code->statements[stidx+1];
3076 if (code->statements[stidx].o1.s1 < 0)
3077 code->statements[stidx].o1.s1++;
3078 code_pop_statement(code);
3080 /* if not, generate now */
3081 return gen_blocks_recursive(code, func, onfalse);
3084 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
3085 || instr->opcode == VINSTR_NRCALL)
3090 first = vec_size(instr->params);
3093 for (p = 0; p < first; ++p)
3095 ir_value *param = instr->params[p];
3096 if (param->callparam)
3099 stmt.opcode = INSTR_STORE_F;
3102 if (param->vtype == TYPE_FIELD)
3103 stmt.opcode = field_store_instr[param->fieldtype];
3104 else if (param->vtype == TYPE_NIL)
3105 stmt.opcode = INSTR_STORE_V;
3107 stmt.opcode = type_store_instr[param->vtype];
3108 stmt.o1.u1 = ir_value_code_addr(param);
3109 stmt.o2.u1 = OFS_PARM0 + 3 * p;
3110 code_push_statement(code, &stmt, instr->context);
3112 /* Now handle extparams */
3113 first = vec_size(instr->params);
3114 for (; p < first; ++p)
3116 ir_builder *ir = func->owner;
3117 ir_value *param = instr->params[p];
3118 ir_value *targetparam;
3120 if (param->callparam)
3123 if (p-8 >= vec_size(ir->extparams))
3124 ir_gen_extparam(ir);
3126 targetparam = ir->extparams[p-8];
3128 stmt.opcode = INSTR_STORE_F;
3131 if (param->vtype == TYPE_FIELD)
3132 stmt.opcode = field_store_instr[param->fieldtype];
3133 else if (param->vtype == TYPE_NIL)
3134 stmt.opcode = INSTR_STORE_V;
3136 stmt.opcode = type_store_instr[param->vtype];
3137 stmt.o1.u1 = ir_value_code_addr(param);
3138 stmt.o2.u1 = ir_value_code_addr(targetparam);
3139 code_push_statement(code, &stmt, instr->context);
3142 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
3143 if (stmt.opcode > INSTR_CALL8)
3144 stmt.opcode = INSTR_CALL8;
3145 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
3148 code_push_statement(code, &stmt, instr->context);
3150 retvalue = instr->_ops[0];
3151 if (retvalue && retvalue->store != store_return &&
3152 (retvalue->store == store_global || vec_size(retvalue->life)))
3154 /* not to be kept in OFS_RETURN */
3155 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
3156 stmt.opcode = field_store_instr[retvalue->fieldtype];
3158 stmt.opcode = type_store_instr[retvalue->vtype];
3159 stmt.o1.u1 = OFS_RETURN;
3160 stmt.o2.u1 = ir_value_code_addr(retvalue);
3162 code_push_statement(code, &stmt, instr->context);
3167 if (instr->opcode == INSTR_STATE) {
3168 irerror(block->context, "TODO: state instruction");
3172 stmt.opcode = instr->opcode;
3177 /* This is the general order of operands */
3179 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
3182 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
3185 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
3187 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
3189 stmt.o1.u1 = stmt.o3.u1;
3192 else if ((stmt.opcode >= INSTR_STORE_F &&
3193 stmt.opcode <= INSTR_STORE_FNC) ||
3194 (stmt.opcode >= INSTR_STOREP_F &&
3195 stmt.opcode <= INSTR_STOREP_FNC))
3197 /* 2-operand instructions with A -> B */
3198 stmt.o2.u1 = stmt.o3.u1;
3201 /* tiny optimization, don't output
3204 if (stmt.o2.u1 == stmt.o1.u1 &&
3205 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
3207 ++opts_optimizationcount[OPTIM_PEEPHOLE];
3211 code_push_statement(code, &stmt, instr->context);
3216 static bool gen_function_code(code_t *code, ir_function *self)
3219 prog_section_statement_t stmt, *retst;
3221 /* Starting from entry point, we generate blocks "as they come"
3222 * for now. Dead blocks will not be translated obviously.
3224 if (!vec_size(self->blocks)) {
3225 irerror(self->context, "Function '%s' declared without body.", self->name);
3229 block = self->blocks[0];
3230 if (block->generated)
3233 if (!gen_blocks_recursive(code, self, block)) {
3234 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3238 /* code_write and qcvm -disasm need to know that the function ends here */
3239 retst = &vec_last(code->statements);
3240 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3241 self->outtype == TYPE_VOID &&
3242 retst->opcode == INSTR_RETURN &&
3243 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3245 retst->opcode = INSTR_DONE;
3246 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3250 stmt.opcode = INSTR_DONE;
3254 last.line = vec_last(code->linenums);
3255 last.column = vec_last(code->columnnums);
3257 code_push_statement(code, &stmt, last);
3262 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3264 /* NOTE: filename pointers are copied, we never strdup them,
3265 * thus we can use pointer-comparison to find the string.
3270 for (i = 0; i < vec_size(ir->filenames); ++i) {
3271 if (ir->filenames[i] == filename)
3272 return ir->filestrings[i];
3275 str = code_genstring(ir->code, filename);
3276 vec_push(ir->filenames, filename);
3277 vec_push(ir->filestrings, str);
3281 static bool gen_global_function(ir_builder *ir, ir_value *global)
3283 prog_section_function_t fun;
3288 if (!global->hasvalue || (!global->constval.vfunc))
3290 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3294 irfun = global->constval.vfunc;
3296 fun.name = global->code.name;
3297 fun.file = ir_builder_filestring(ir, global->context.file);
3298 fun.profile = 0; /* always 0 */
3299 fun.nargs = vec_size(irfun->params);
3303 for (i = 0;i < 8; ++i) {
3304 if ((int32_t)i >= fun.nargs)
3307 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3311 fun.locals = irfun->allocated_locals;
3314 fun.entry = irfun->builtin+1;
3316 irfun->code_function_def = vec_size(ir->code->functions);
3317 fun.entry = vec_size(ir->code->statements);
3320 vec_push(ir->code->functions, fun);
3324 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3329 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3330 global = ir_value_var(name, store_global, TYPE_VECTOR);
3332 vec_push(ir->extparam_protos, global);
3336 static void ir_gen_extparam(ir_builder *ir)
3338 prog_section_def_t def;
3341 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3342 global = ir_gen_extparam_proto(ir);
3344 global = ir->extparam_protos[vec_size(ir->extparams)];
3346 def.name = code_genstring(ir->code, global->name);
3347 def.type = TYPE_VECTOR;
3348 def.offset = vec_size(ir->code->globals);
3350 vec_push(ir->code->defs, def);
3352 ir_value_code_setaddr(global, def.offset);
3354 vec_push(ir->code->globals, 0);
3355 vec_push(ir->code->globals, 0);
3356 vec_push(ir->code->globals, 0);
3358 vec_push(ir->extparams, global);
3361 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3363 size_t i, ext, numparams;
3365 ir_builder *ir = self->owner;
3367 prog_section_statement_t stmt;
3369 numparams = vec_size(self->params);
3373 stmt.opcode = INSTR_STORE_F;
3375 for (i = 8; i < numparams; ++i) {
3377 if (ext >= vec_size(ir->extparams))
3378 ir_gen_extparam(ir);
3380 ep = ir->extparams[ext];
3382 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3383 if (self->locals[i]->vtype == TYPE_FIELD &&
3384 self->locals[i]->fieldtype == TYPE_VECTOR)
3386 stmt.opcode = INSTR_STORE_V;
3388 stmt.o1.u1 = ir_value_code_addr(ep);
3389 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3390 code_push_statement(code, &stmt, self->context);
3396 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3398 size_t i, ext, numparams, maxparams;
3400 ir_builder *ir = self->owner;
3402 prog_section_statement_t stmt;
3404 numparams = vec_size(self->params);
3408 stmt.opcode = INSTR_STORE_V;
3410 maxparams = numparams + self->max_varargs;
3411 for (i = numparams; i < maxparams; ++i) {
3413 stmt.o1.u1 = OFS_PARM0 + 3*i;
3414 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3415 code_push_statement(code, &stmt, self->context);
3419 while (ext >= vec_size(ir->extparams))
3420 ir_gen_extparam(ir);
3422 ep = ir->extparams[ext];
3424 stmt.o1.u1 = ir_value_code_addr(ep);
3425 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3426 code_push_statement(code, &stmt, self->context);
3432 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3434 prog_section_function_t *def;
3437 uint32_t firstlocal, firstglobal;
3439 irfun = global->constval.vfunc;
3440 def = ir->code->functions + irfun->code_function_def;
3442 if (OPTS_OPTION_BOOL(OPTION_G) ||
3443 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3444 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3446 firstlocal = def->firstlocal = vec_size(ir->code->globals);
3448 firstlocal = def->firstlocal = ir->first_common_local;
3449 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3452 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3454 for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3455 vec_push(ir->code->globals, 0);
3456 for (i = 0; i < vec_size(irfun->locals); ++i) {
3457 ir_value *v = irfun->locals[i];
3458 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3459 ir_value_code_setaddr(v, firstlocal + v->code.local);
3460 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3461 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3466 ir_value_code_setaddr(v, firstglobal + v->code.local);
3468 for (i = 0; i < vec_size(irfun->values); ++i)
3470 ir_value *v = irfun->values[i];
3474 ir_value_code_setaddr(v, firstlocal + v->code.local);
3476 ir_value_code_setaddr(v, firstglobal + v->code.local);
3481 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3483 prog_section_function_t *fundef;
3488 irfun = global->constval.vfunc;
3490 if (global->cvq == CV_NONE) {
3491 if (irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3492 "function `%s` has no body and in QC implicitly becomes a function-pointer",
3495 /* Not bailing out just now. If this happens a lot you don't want to have
3496 * to rerun gmqcc for each such function.
3502 /* this was a function pointer, don't generate code for those */
3510 * If there is no definition and the thing is eraseable, we can ignore
3511 * outputting the function to begin with.
3513 if (global->flags & IR_FLAG_ERASEABLE && irfun->code_function_def < 0) {
3517 if (irfun->code_function_def < 0) {
3518 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3521 fundef = &ir->code->functions[irfun->code_function_def];
3523 fundef->entry = vec_size(ir->code->statements);
3524 if (!gen_function_locals(ir, global)) {
3525 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3528 if (!gen_function_extparam_copy(ir->code, irfun)) {
3529 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3532 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3533 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3536 if (!gen_function_code(ir->code, irfun)) {
3537 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3543 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3548 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3551 def.type = TYPE_FLOAT;
3555 component = (char*)mem_a(len+3);
3556 memcpy(component, name, len);
3558 component[len-0] = 0;
3559 component[len-2] = '_';
3561 component[len-1] = 'x';
3563 for (i = 0; i < 3; ++i) {
3564 def.name = code_genstring(code, component);
3565 vec_push(code->defs, def);
3573 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3578 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3581 fld.type = TYPE_FLOAT;
3585 component = (char*)mem_a(len+3);
3586 memcpy(component, name, len);
3588 component[len-0] = 0;
3589 component[len-2] = '_';
3591 component[len-1] = 'x';
3593 for (i = 0; i < 3; ++i) {
3594 fld.name = code_genstring(code, component);
3595 vec_push(code->fields, fld);
3603 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3607 prog_section_def_t def;
3608 bool pushdef = opts.optimizeoff;
3610 def.type = global->vtype;
3611 def.offset = vec_size(self->code->globals);
3613 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3618 * if we're eraseable and the function isn't referenced ignore outputting
3621 if (global->flags & IR_FLAG_ERASEABLE && vec_size(global->reads) == 0) {
3625 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3626 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3627 (global->name[0] == '#' || global->cvq == CV_CONST))
3633 if (global->name[0] == '#') {
3634 if (!self->str_immediate)
3635 self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3636 def.name = global->code.name = self->str_immediate;
3639 def.name = global->code.name = code_genstring(self->code, global->name);
3644 def.offset = ir_value_code_addr(global);
3645 vec_push(self->code->defs, def);
3646 if (global->vtype == TYPE_VECTOR)
3647 gen_vector_defs(self->code, def, global->name);
3648 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3649 gen_vector_defs(self->code, def, global->name);
3656 switch (global->vtype)
3659 if (!strcmp(global->name, "end_sys_globals")) {
3660 /* TODO: remember this point... all the defs before this one
3661 * should be checksummed and added to progdefs.h when we generate it.
3664 else if (!strcmp(global->name, "end_sys_fields")) {
3665 /* TODO: same as above but for entity-fields rather than globsl
3668 else if(irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3671 /* Not bailing out */
3674 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3675 * the system fields actually go? Though the engine knows this anyway...
3676 * Maybe this could be an -foption
3677 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3679 ir_value_code_setaddr(global, vec_size(self->code->globals));
3680 vec_push(self->code->globals, 0);
3682 if (pushdef) vec_push(self->code->defs, def);
3685 if (pushdef) vec_push(self->code->defs, def);
3686 return gen_global_pointer(self->code, global);
3689 vec_push(self->code->defs, def);
3690 if (global->fieldtype == TYPE_VECTOR)
3691 gen_vector_defs(self->code, def, global->name);
3693 return gen_global_field(self->code, global);
3698 ir_value_code_setaddr(global, vec_size(self->code->globals));
3699 if (global->hasvalue) {
3700 iptr = (int32_t*)&global->constval.ivec[0];
3701 vec_push(self->code->globals, *iptr);
3703 vec_push(self->code->globals, 0);
3705 if (!islocal && global->cvq != CV_CONST)
3706 def.type |= DEF_SAVEGLOBAL;
3707 if (pushdef) vec_push(self->code->defs, def);
3709 return global->code.globaladdr >= 0;
3713 ir_value_code_setaddr(global, vec_size(self->code->globals));
3714 if (global->hasvalue) {
3715 uint32_t load = code_genstring(self->code, global->constval.vstring);
3716 vec_push(self->code->globals, load);
3718 vec_push(self->code->globals, 0);
3720 if (!islocal && global->cvq != CV_CONST)
3721 def.type |= DEF_SAVEGLOBAL;
3722 if (pushdef) vec_push(self->code->defs, def);
3723 return global->code.globaladdr >= 0;
3728 ir_value_code_setaddr(global, vec_size(self->code->globals));
3729 if (global->hasvalue) {
3730 iptr = (int32_t*)&global->constval.ivec[0];
3731 vec_push(self->code->globals, iptr[0]);
3732 if (global->code.globaladdr < 0)
3734 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3735 vec_push(self->code->globals, iptr[d]);
3738 vec_push(self->code->globals, 0);
3739 if (global->code.globaladdr < 0)
3741 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3742 vec_push(self->code->globals, 0);
3745 if (!islocal && global->cvq != CV_CONST)
3746 def.type |= DEF_SAVEGLOBAL;
3749 vec_push(self->code->defs, def);
3750 def.type &= ~DEF_SAVEGLOBAL;
3751 gen_vector_defs(self->code, def, global->name);
3753 return global->code.globaladdr >= 0;
3756 ir_value_code_setaddr(global, vec_size(self->code->globals));
3757 if (!global->hasvalue) {
3758 vec_push(self->code->globals, 0);
3759 if (global->code.globaladdr < 0)
3762 vec_push(self->code->globals, vec_size(self->code->functions));
3763 if (!gen_global_function(self, global))
3766 if (!islocal && global->cvq != CV_CONST)
3767 def.type |= DEF_SAVEGLOBAL;
3768 if (pushdef) vec_push(self->code->defs, def);
3771 /* assume biggest type */
3772 ir_value_code_setaddr(global, vec_size(self->code->globals));
3773 vec_push(self->code->globals, 0);
3774 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3775 vec_push(self->code->globals, 0);
3778 /* refuse to create 'void' type or any other fancy business. */
3779 irerror(global->context, "Invalid type for global variable `%s`: %s",
3780 global->name, type_name[global->vtype]);
3785 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3787 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3790 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3792 prog_section_def_t def;
3793 prog_section_field_t fld;
3797 def.type = (uint16_t)field->vtype;
3798 def.offset = (uint16_t)vec_size(self->code->globals);
3800 /* create a global named the same as the field */
3801 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3802 /* in our standard, the global gets a dot prefix */
3803 size_t len = strlen(field->name);
3806 /* we really don't want to have to allocate this, and 1024
3807 * bytes is more than enough for a variable/field name
3809 if (len+2 >= sizeof(name)) {
3810 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3815 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3818 def.name = code_genstring(self->code, name);
3819 fld.name = def.name + 1; /* we reuse that string table entry */
3821 /* in plain QC, there cannot be a global with the same name,
3822 * and so we also name the global the same.
3823 * FIXME: fteqcc should create a global as well
3824 * check if it actually uses the same name. Probably does
3826 def.name = code_genstring(self->code, field->name);
3827 fld.name = def.name;
3830 field->code.name = def.name;
3832 vec_push(self->code->defs, def);
3834 fld.type = field->fieldtype;
3836 if (fld.type == TYPE_VOID) {
3837 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3841 fld.offset = field->code.fieldaddr;
3843 vec_push(self->code->fields, fld);
3845 ir_value_code_setaddr(field, vec_size(self->code->globals));
3846 vec_push(self->code->globals, fld.offset);
3847 if (fld.type == TYPE_VECTOR) {
3848 vec_push(self->code->globals, fld.offset+1);
3849 vec_push(self->code->globals, fld.offset+2);
3852 if (field->fieldtype == TYPE_VECTOR) {
3853 gen_vector_defs (self->code, def, field->name);
3854 gen_vector_fields(self->code, fld, field->name);
3857 return field->code.globaladdr >= 0;
3860 bool ir_builder_generate(ir_builder *self, const char *filename)
3862 prog_section_statement_t stmt;
3864 char *lnofile = NULL;
3866 for (i = 0; i < vec_size(self->fields); ++i)
3868 ir_builder_prepare_field(self->code, self->fields[i]);
3871 for (i = 0; i < vec_size(self->globals); ++i)
3873 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3876 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3877 ir_function *func = self->globals[i]->constval.vfunc;
3878 if (func && self->max_locals < func->allocated_locals &&
3879 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3881 self->max_locals = func->allocated_locals;
3883 if (func && self->max_globaltemps < func->globaltemps)
3884 self->max_globaltemps = func->globaltemps;
3888 for (i = 0; i < vec_size(self->fields); ++i)
3890 if (!ir_builder_gen_field(self, self->fields[i])) {
3896 ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
3897 vec_push(self->code->globals, 0);
3898 vec_push(self->code->globals, 0);
3899 vec_push(self->code->globals, 0);
3901 /* generate virtual-instruction temps */
3902 for (i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
3903 ir_value_code_setaddr(self->vinstr_temp[i], vec_size(self->code->globals));
3904 vec_push(self->code->globals, 0);
3905 vec_push(self->code->globals, 0);
3906 vec_push(self->code->globals, 0);
3909 /* generate global temps */
3910 self->first_common_globaltemp = vec_size(self->code->globals);
3911 for (i = 0; i < self->max_globaltemps; ++i) {
3912 vec_push(self->code->globals, 0);
3914 /* generate common locals */
3915 self->first_common_local = vec_size(self->code->globals);
3916 for (i = 0; i < self->max_locals; ++i) {
3917 vec_push(self->code->globals, 0);
3920 /* generate function code */
3921 for (i = 0; i < vec_size(self->globals); ++i)
3923 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3924 if (!gen_global_function_code(self, self->globals[i])) {
3930 if (vec_size(self->code->globals) >= 65536) {
3931 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3935 /* DP errors if the last instruction is not an INSTR_DONE. */
3936 if (vec_last(self->code->statements).opcode != INSTR_DONE)
3940 stmt.opcode = INSTR_DONE;
3944 last.line = vec_last(self->code->linenums);
3945 last.column = vec_last(self->code->columnnums);
3947 code_push_statement(self->code, &stmt, last);
3950 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3953 if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
3954 con_err("Linecounter wrong: %lu != %lu\n",
3955 (unsigned long)vec_size(self->code->statements),
3956 (unsigned long)vec_size(self->code->linenums));
3957 } else if (OPTS_FLAG(LNO)) {
3959 size_t filelen = strlen(filename);
3961 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3962 dot = strrchr(lnofile, '.');
3966 vec_shrinkto(lnofile, dot - lnofile);
3968 memcpy(vec_add(lnofile, 5), ".lno", 5);
3971 if (!code_write(self->code, filename, lnofile)) {
3980 /***********************************************************************
3981 *IR DEBUG Dump functions...
3984 #define IND_BUFSZ 1024
3986 static const char *qc_opname(int op)
3988 if (op < 0) return "<INVALID>";
3989 if (op < VINSTR_END)
3990 return util_instr_str[op];
3992 case VINSTR_END: return "END";
3993 case VINSTR_PHI: return "PHI";
3994 case VINSTR_JUMP: return "JUMP";
3995 case VINSTR_COND: return "COND";
3996 case VINSTR_BITXOR: return "BITXOR";
3997 case VINSTR_BITAND_V: return "BITAND_V";
3998 case VINSTR_BITOR_V: return "BITOR_V";
3999 case VINSTR_BITXOR_V: return "BITXOR_V";
4000 case VINSTR_BITAND_VF: return "BITAND_VF";
4001 case VINSTR_BITOR_VF: return "BITOR_VF";
4002 case VINSTR_BITXOR_VF: return "BITXOR_VF";
4003 case VINSTR_CROSS: return "CROSS";
4004 case VINSTR_NEG_F: return "NEG_F";
4005 case VINSTR_NEG_V: return "NEG_V";
4006 default: return "<UNK>";
4010 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
4013 char indent[IND_BUFSZ];
4017 oprintf("module %s\n", b->name);
4018 for (i = 0; i < vec_size(b->globals); ++i)
4021 if (b->globals[i]->hasvalue)
4022 oprintf("%s = ", b->globals[i]->name);
4023 ir_value_dump(b->globals[i], oprintf);
4026 for (i = 0; i < vec_size(b->functions); ++i)
4027 ir_function_dump(b->functions[i], indent, oprintf);
4028 oprintf("endmodule %s\n", b->name);
4031 static const char *storenames[] = {
4032 "[global]", "[local]", "[param]", "[value]", "[return]"
4035 void ir_function_dump(ir_function *f, char *ind,
4036 int (*oprintf)(const char*, ...))
4039 if (f->builtin != 0) {
4040 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
4043 oprintf("%sfunction %s\n", ind, f->name);
4044 util_strncat(ind, "\t", IND_BUFSZ-1);
4045 if (vec_size(f->locals))
4047 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
4048 for (i = 0; i < vec_size(f->locals); ++i) {
4049 oprintf("%s\t", ind);
4050 ir_value_dump(f->locals[i], oprintf);
4054 oprintf("%sliferanges:\n", ind);
4055 for (i = 0; i < vec_size(f->locals); ++i) {
4056 const char *attr = "";
4058 ir_value *v = f->locals[i];
4059 if (v->unique_life && v->locked)
4060 attr = "unique,locked ";
4061 else if (v->unique_life)
4065 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
4066 storenames[v->store],
4067 attr, (v->callparam ? "callparam " : ""),
4068 (int)v->code.local);
4071 for (l = 0; l < vec_size(v->life); ++l) {
4072 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
4075 for (m = 0; m < 3; ++m) {
4076 ir_value *vm = v->members[m];
4079 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
4080 for (l = 0; l < vec_size(vm->life); ++l) {
4081 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4086 for (i = 0; i < vec_size(f->values); ++i) {
4087 const char *attr = "";
4089 ir_value *v = f->values[i];
4090 if (v->unique_life && v->locked)
4091 attr = "unique,locked ";
4092 else if (v->unique_life)
4096 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
4097 storenames[v->store],
4098 attr, (v->callparam ? "callparam " : ""),
4099 (int)v->code.local);
4102 for (l = 0; l < vec_size(v->life); ++l) {
4103 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
4106 for (m = 0; m < 3; ++m) {
4107 ir_value *vm = v->members[m];
4110 if (vm->unique_life && vm->locked)
4111 attr = "unique,locked ";
4112 else if (vm->unique_life)
4114 else if (vm->locked)
4116 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
4117 for (l = 0; l < vec_size(vm->life); ++l) {
4118 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4123 if (vec_size(f->blocks))
4125 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
4126 for (i = 0; i < vec_size(f->blocks); ++i) {
4127 ir_block_dump(f->blocks[i], ind, oprintf);
4131 ind[strlen(ind)-1] = 0;
4132 oprintf("%sendfunction %s\n", ind, f->name);
4135 void ir_block_dump(ir_block* b, char *ind,
4136 int (*oprintf)(const char*, ...))
4139 oprintf("%s:%s\n", ind, b->label);
4140 util_strncat(ind, "\t", IND_BUFSZ-1);
4142 if (b->instr && b->instr[0])
4143 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
4144 for (i = 0; i < vec_size(b->instr); ++i)
4145 ir_instr_dump(b->instr[i], ind, oprintf);
4146 ind[strlen(ind)-1] = 0;
4149 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
4152 oprintf("%s <- phi ", in->_ops[0]->name);
4153 for (i = 0; i < vec_size(in->phi); ++i)
4155 oprintf("([%s] : %s) ", in->phi[i].from->label,
4156 in->phi[i].value->name);
4161 void ir_instr_dump(ir_instr *in, char *ind,
4162 int (*oprintf)(const char*, ...))
4165 const char *comma = NULL;
4167 oprintf("%s (%i) ", ind, (int)in->eid);
4169 if (in->opcode == VINSTR_PHI) {
4170 dump_phi(in, oprintf);
4174 util_strncat(ind, "\t", IND_BUFSZ-1);
4176 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
4177 ir_value_dump(in->_ops[0], oprintf);
4178 if (in->_ops[1] || in->_ops[2])
4181 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
4182 oprintf("CALL%i\t", vec_size(in->params));
4184 oprintf("%s\t", qc_opname(in->opcode));
4186 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
4187 ir_value_dump(in->_ops[0], oprintf);
4192 for (i = 1; i != 3; ++i) {
4196 ir_value_dump(in->_ops[i], oprintf);
4204 oprintf("[%s]", in->bops[0]->label);
4208 oprintf("%s[%s]", comma, in->bops[1]->label);
4209 if (vec_size(in->params)) {
4210 oprintf("\tparams: ");
4211 for (i = 0; i != vec_size(in->params); ++i) {
4212 oprintf("%s, ", in->params[i]->name);
4216 ind[strlen(ind)-1] = 0;
4219 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
4222 for (; *str; ++str) {
4224 case '\n': oprintf("\\n"); break;
4225 case '\r': oprintf("\\r"); break;
4226 case '\t': oprintf("\\t"); break;
4227 case '\v': oprintf("\\v"); break;
4228 case '\f': oprintf("\\f"); break;
4229 case '\b': oprintf("\\b"); break;
4230 case '\a': oprintf("\\a"); break;
4231 case '\\': oprintf("\\\\"); break;
4232 case '"': oprintf("\\\""); break;
4233 default: oprintf("%c", *str); break;
4239 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4248 oprintf("fn:%s", v->name);
4251 oprintf("%g", v->constval.vfloat);
4254 oprintf("'%g %g %g'",
4257 v->constval.vvec.z);
4260 oprintf("(entity)");
4263 ir_value_dump_string(v->constval.vstring, oprintf);
4267 oprintf("%i", v->constval.vint);
4272 v->constval.vpointer->name);
4276 oprintf("%s", v->name);
4280 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4283 oprintf("Life of %12s:", self->name);
4284 for (i = 0; i < vec_size(self->life); ++i)
4286 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);