7 /***********************************************************************
8 * Type sizes used at multiple points in the IR codegen
11 const char *type_name[TYPE_COUNT] = {
30 static size_t type_sizeof_[TYPE_COUNT] = {
37 1, /* TYPE_FUNCTION */
48 const uint16_t type_store_instr[TYPE_COUNT] = {
49 INSTR_STORE_F, /* should use I when having integer support */
56 INSTR_STORE_ENT, /* should use I */
58 INSTR_STORE_I, /* integer type */
63 INSTR_STORE_V, /* variant, should never be accessed */
65 VINSTR_END, /* struct */
66 VINSTR_END, /* union */
67 VINSTR_END, /* array */
69 VINSTR_END, /* noexpr */
72 const uint16_t field_store_instr[TYPE_COUNT] = {
82 INSTR_STORE_FLD, /* integer type */
87 INSTR_STORE_V, /* variant, should never be accessed */
89 VINSTR_END, /* struct */
90 VINSTR_END, /* union */
91 VINSTR_END, /* array */
93 VINSTR_END, /* noexpr */
96 const uint16_t type_storep_instr[TYPE_COUNT] = {
97 INSTR_STOREP_F, /* should use I when having integer support */
104 INSTR_STOREP_ENT, /* should use I */
106 INSTR_STOREP_ENT, /* integer type */
111 INSTR_STOREP_V, /* variant, should never be accessed */
113 VINSTR_END, /* struct */
114 VINSTR_END, /* union */
115 VINSTR_END, /* array */
116 VINSTR_END, /* nil */
117 VINSTR_END, /* noexpr */
120 const uint16_t type_eq_instr[TYPE_COUNT] = {
121 INSTR_EQ_F, /* should use I when having integer support */
126 INSTR_EQ_E, /* FLD has no comparison */
128 INSTR_EQ_E, /* should use I */
135 INSTR_EQ_V, /* variant, should never be accessed */
137 VINSTR_END, /* struct */
138 VINSTR_END, /* union */
139 VINSTR_END, /* array */
140 VINSTR_END, /* nil */
141 VINSTR_END, /* noexpr */
144 const uint16_t type_ne_instr[TYPE_COUNT] = {
145 INSTR_NE_F, /* should use I when having integer support */
150 INSTR_NE_E, /* FLD has no comparison */
152 INSTR_NE_E, /* should use I */
159 INSTR_NE_V, /* variant, should never be accessed */
161 VINSTR_END, /* struct */
162 VINSTR_END, /* union */
163 VINSTR_END, /* array */
164 VINSTR_END, /* nil */
165 VINSTR_END, /* noexpr */
168 const uint16_t type_not_instr[TYPE_COUNT] = {
169 INSTR_NOT_F, /* should use I when having integer support */
170 VINSTR_END, /* not to be used, depends on string related -f flags */
176 INSTR_NOT_ENT, /* should use I */
178 INSTR_NOT_I, /* integer type */
183 INSTR_NOT_V, /* variant, should never be accessed */
185 VINSTR_END, /* struct */
186 VINSTR_END, /* union */
187 VINSTR_END, /* array */
188 VINSTR_END, /* nil */
189 VINSTR_END, /* noexpr */
193 static ir_value* ir_value_var(const char *name, int st, int vtype);
194 static bool ir_value_set_name(ir_value*, const char *name);
195 static void ir_value_dump(ir_value*, int (*oprintf)(const char*,...));
197 static ir_value* ir_gen_extparam_proto(ir_builder *ir);
198 static void ir_gen_extparam (ir_builder *ir);
200 static bool ir_builder_set_name(ir_builder *self, const char *name);
202 static ir_function* ir_function_new(ir_builder *owner, int returntype);
203 static bool ir_function_set_name(ir_function*, const char *name);
204 static void ir_function_delete(ir_function*);
205 static void ir_function_dump(ir_function*, char *ind, int (*oprintf)(const char*,...));
207 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t, const char *label,
208 int op, ir_value *a, ir_value *b, int outype);
209 static void ir_block_delete(ir_block*);
210 static ir_block* ir_block_new(ir_function *owner, const char *label);
211 static bool GMQCC_WARN ir_block_create_store(ir_block*, lex_ctx_t, ir_value *target, ir_value *what);
212 static bool ir_block_set_label(ir_block*, const char *label);
213 static void ir_block_dump(ir_block*, char *ind, int (*oprintf)(const char*,...));
215 static bool ir_instr_op(ir_instr*, int op, ir_value *value, bool writing);
216 static void ir_instr_delete(ir_instr*);
217 static void ir_instr_dump(ir_instr* in, char *ind, int (*oprintf)(const char*,...));
218 /* error functions */
220 static void irerror(lex_ctx_t ctx, const char *msg, ...)
224 con_cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
228 static bool GMQCC_WARN irwarning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
233 r = vcompile_warning(ctx, warntype, fmt, ap);
238 /***********************************************************************
239 * Vector utility functions
242 static bool GMQCC_WARN vec_ir_value_find(std::vector<ir_value *> &vec, const ir_value *what, size_t *idx)
244 for (auto &it : vec) {
248 *idx = &it - &vec[0];
254 static bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
257 size_t len = vec_size(vec);
258 for (i = 0; i < len; ++i) {
259 if (vec[i] == what) {
267 static bool GMQCC_WARN vec_ir_instr_find(std::vector<ir_instr *> &vec, ir_instr *what, size_t *idx)
269 for (auto &it : vec) {
273 *idx = &it - &vec[0];
279 /***********************************************************************
283 static void ir_block_delete_quick(ir_block* self);
284 static void ir_instr_delete_quick(ir_instr *self);
285 static void ir_function_delete_quick(ir_function *self);
287 ir_builder* ir_builder_new(const char *modulename)
292 self = (ir_builder*)mem_a(sizeof(*self));
296 self->functions = nullptr;
297 self->globals = nullptr;
298 self->fields = nullptr;
299 self->filenames = nullptr;
300 self->filestrings = nullptr;
301 self->htglobals = util_htnew(IR_HT_SIZE);
302 self->htfields = util_htnew(IR_HT_SIZE);
303 self->htfunctions = util_htnew(IR_HT_SIZE);
305 self->extparams = nullptr;
306 self->extparam_protos = nullptr;
308 self->first_common_globaltemp = 0;
309 self->max_globaltemps = 0;
310 self->first_common_local = 0;
311 self->max_locals = 0;
313 self->str_immediate = 0;
314 self->name = nullptr;
315 if (!ir_builder_set_name(self, modulename)) {
320 self->nil = ir_value_var("nil", store_value, TYPE_NIL);
321 self->nil->cvq = CV_CONST;
323 for (i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
324 /* we write to them, but they're not supposed to be used outside the IR, so
325 * let's not allow the generation of ir_instrs which use these.
326 * So it's a constant noexpr.
328 self->vinstr_temp[i] = ir_value_var("vinstr_temp", store_value, TYPE_NOEXPR);
329 self->vinstr_temp[i]->cvq = CV_CONST;
332 self->reserved_va_count = nullptr;
333 self->coverage_func = nullptr;
335 self->code = code_init();
340 void ir_builder_delete(ir_builder* self)
343 util_htdel(self->htglobals);
344 util_htdel(self->htfields);
345 util_htdel(self->htfunctions);
346 mem_d((void*)self->name);
347 for (i = 0; i != vec_size(self->functions); ++i) {
348 ir_function_delete_quick(self->functions[i]);
350 vec_free(self->functions);
351 for (i = 0; i != vec_size(self->extparams); ++i) {
352 ir_value_delete(self->extparams[i]);
354 vec_free(self->extparams);
355 vec_free(self->extparam_protos);
356 for (i = 0; i != vec_size(self->globals); ++i) {
357 ir_value_delete(self->globals[i]);
359 vec_free(self->globals);
360 for (i = 0; i != vec_size(self->fields); ++i) {
361 ir_value_delete(self->fields[i]);
363 ir_value_delete(self->nil);
364 for (i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
365 ir_value_delete(self->vinstr_temp[i]);
367 vec_free(self->fields);
368 vec_free(self->filenames);
369 vec_free(self->filestrings);
371 code_cleanup(self->code);
375 bool ir_builder_set_name(ir_builder *self, const char *name)
378 mem_d((void*)self->name);
379 self->name = util_strdup(name);
383 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
385 return (ir_function*)util_htget(self->htfunctions, name);
388 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
390 ir_function *fn = ir_builder_get_function(self, name);
395 fn = ir_function_new(self, outtype);
396 if (!ir_function_set_name(fn, name))
398 ir_function_delete(fn);
401 vec_push(self->functions, fn);
402 util_htset(self->htfunctions, name, fn);
404 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
406 ir_function_delete(fn);
410 fn->value->hasvalue = true;
411 fn->value->outtype = outtype;
412 fn->value->constval.vfunc = fn;
413 fn->value->context = fn->context;
418 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
420 return (ir_value*)util_htget(self->htglobals, name);
423 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
429 ve = ir_builder_get_global(self, name);
435 ve = ir_value_var(name, store_global, vtype);
436 vec_push(self->globals, ve);
437 util_htset(self->htglobals, name, ve);
441 ir_value* ir_builder_get_va_count(ir_builder *self)
443 if (self->reserved_va_count)
444 return self->reserved_va_count;
445 return (self->reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
448 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
450 return (ir_value*)util_htget(self->htfields, name);
454 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
456 ir_value *ve = ir_builder_get_field(self, name);
461 ve = ir_value_var(name, store_global, TYPE_FIELD);
462 ve->fieldtype = vtype;
463 vec_push(self->fields, ve);
464 util_htset(self->htfields, name, ve);
468 /***********************************************************************
472 static bool ir_function_naive_phi(ir_function*);
473 static void ir_function_enumerate(ir_function*);
474 static bool ir_function_calculate_liferanges(ir_function*);
475 static bool ir_function_allocate_locals(ir_function*);
477 ir_function* ir_function_new(ir_builder* owner, int outtype)
480 self = (ir_function*)mem_a(sizeof(*self));
485 memset(self, 0, sizeof(*self));
487 self->name = nullptr;
488 if (!ir_function_set_name(self, "<@unnamed>")) {
495 self->context.file = "<@no context>";
496 self->context.line = 0;
497 self->outtype = outtype;
498 self->value = nullptr;
501 self->params = nullptr;
502 self->blocks = nullptr;
503 self->values = nullptr;
504 self->locals = nullptr;
506 self->max_varargs = 0;
508 self->code_function_def = -1;
509 self->allocated_locals = 0;
510 self->globaltemps = 0;
516 bool ir_function_set_name(ir_function *self, const char *name)
519 mem_d((void*)self->name);
520 self->name = util_strdup(name);
524 static void ir_function_delete_quick(ir_function *self)
527 mem_d((void*)self->name);
529 for (i = 0; i != vec_size(self->blocks); ++i)
530 ir_block_delete_quick(self->blocks[i]);
531 vec_free(self->blocks);
533 vec_free(self->params);
535 for (i = 0; i != vec_size(self->values); ++i)
536 ir_value_delete(self->values[i]);
537 vec_free(self->values);
539 for (i = 0; i != vec_size(self->locals); ++i)
540 ir_value_delete(self->locals[i]);
541 vec_free(self->locals);
543 /* self->value is deleted by the builder */
548 void ir_function_delete(ir_function *self)
551 mem_d((void*)self->name);
553 for (i = 0; i != vec_size(self->blocks); ++i)
554 ir_block_delete(self->blocks[i]);
555 vec_free(self->blocks);
557 vec_free(self->params);
559 for (i = 0; i != vec_size(self->values); ++i)
560 ir_value_delete(self->values[i]);
561 vec_free(self->values);
563 for (i = 0; i != vec_size(self->locals); ++i)
564 ir_value_delete(self->locals[i]);
565 vec_free(self->locals);
567 /* self->value is deleted by the builder */
572 static void ir_function_collect_value(ir_function *self, ir_value *v)
574 vec_push(self->values, v);
577 ir_block* ir_function_create_block(lex_ctx_t ctx, ir_function *self, const char *label)
579 ir_block* bn = ir_block_new(self, label);
581 vec_push(self->blocks, bn);
583 if ((self->flags & IR_FLAG_BLOCK_COVERAGE) && self->owner->coverage_func)
584 (void)ir_block_create_call(bn, ctx, nullptr, self->owner->coverage_func, false);
589 static bool instr_is_operation(uint16_t op)
591 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
592 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
593 (op == INSTR_ADDRESS) ||
594 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
595 (op >= INSTR_AND && op <= INSTR_BITOR) ||
596 (op >= INSTR_CALL0 && op <= INSTR_CALL8) ||
597 (op >= VINSTR_BITAND_V && op <= VINSTR_NEG_V) );
600 static bool ir_function_pass_peephole(ir_function *self)
604 for (b = 0; b < vec_size(self->blocks); ++b) {
606 ir_block *block = self->blocks[b];
608 for (i = 0; i < vec_size(block->instr); ++i) {
610 inst = block->instr[i];
613 (inst->opcode >= INSTR_STORE_F &&
614 inst->opcode <= INSTR_STORE_FNC))
622 oper = block->instr[i-1];
623 if (!instr_is_operation(oper->opcode))
626 /* Don't change semantics of MUL_VF in engines where these may not alias. */
627 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
628 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
630 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
634 value = oper->_ops[0];
636 /* only do it for SSA values */
637 if (value->store != store_value)
640 /* don't optimize out the temp if it's used later again */
641 if (value->reads.size() != 1)
644 /* The very next store must use this value */
645 if (value->reads[0] != store)
648 /* And of course the store must _read_ from it, so it's in
650 if (store->_ops[1] != value)
653 ++opts_optimizationcount[OPTIM_PEEPHOLE];
654 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
656 vec_remove(block->instr, i, 1);
657 ir_instr_delete(store);
659 else if (inst->opcode == VINSTR_COND)
661 /* COND on a value resulting from a NOT could
662 * remove the NOT and swap its operands
669 value = inst->_ops[0];
671 if (value->store != store_value || value->reads.size() != 1 || value->reads[0] != inst)
674 inot = value->writes[0];
675 if (inot->_ops[0] != value ||
676 inot->opcode < INSTR_NOT_F ||
677 inot->opcode > INSTR_NOT_FNC ||
678 inot->opcode == INSTR_NOT_V || /* can't do these */
679 inot->opcode == INSTR_NOT_S)
685 ++opts_optimizationcount[OPTIM_PEEPHOLE];
687 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
690 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
691 if (tmp->instr[inotid] == inot)
694 if (inotid >= vec_size(tmp->instr)) {
695 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
698 vec_remove(tmp->instr, inotid, 1);
699 ir_instr_delete(inot);
700 /* swap ontrue/onfalse */
702 inst->bops[0] = inst->bops[1];
713 static bool ir_function_pass_tailrecursion(ir_function *self)
717 for (b = 0; b < vec_size(self->blocks); ++b) {
719 ir_instr *ret, *call, *store = nullptr;
720 ir_block *block = self->blocks[b];
722 if (!block->final || vec_size(block->instr) < 2)
725 ret = block->instr[vec_size(block->instr)-1];
726 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
729 call = block->instr[vec_size(block->instr)-2];
730 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
731 /* account for the unoptimized
733 * STORE %return, %tmp
737 if (vec_size(block->instr) < 3)
741 call = block->instr[vec_size(block->instr)-3];
744 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
748 /* optimize out the STORE */
750 ret->_ops[0] == store->_ops[0] &&
751 store->_ops[1] == call->_ops[0])
753 ++opts_optimizationcount[OPTIM_PEEPHOLE];
754 call->_ops[0] = store->_ops[0];
755 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
756 ir_instr_delete(store);
765 funcval = call->_ops[1];
768 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
771 /* now we have a CALL and a RET, check if it's a tailcall */
772 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
775 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
776 vec_shrinkby(block->instr, 2);
778 block->final = false; /* open it back up */
780 /* emite parameter-stores */
781 for (p = 0; p < call->params.size(); ++p) {
782 /* assert(call->params_count <= self->locals_count); */
783 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
784 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
788 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
789 irerror(call->context, "failed to create tailcall jump");
793 ir_instr_delete(call);
794 ir_instr_delete(ret);
800 bool ir_function_finalize(ir_function *self)
807 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
808 if (!ir_function_pass_peephole(self)) {
809 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
814 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
815 if (!ir_function_pass_tailrecursion(self)) {
816 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
821 if (!ir_function_naive_phi(self)) {
822 irerror(self->context, "internal error: ir_function_naive_phi failed");
826 for (i = 0; i < vec_size(self->locals); ++i) {
827 ir_value *v = self->locals[i];
828 if (v->vtype == TYPE_VECTOR ||
829 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
831 ir_value_vector_member(v, 0);
832 ir_value_vector_member(v, 1);
833 ir_value_vector_member(v, 2);
836 for (i = 0; i < vec_size(self->values); ++i) {
837 ir_value *v = self->values[i];
838 if (v->vtype == TYPE_VECTOR ||
839 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
841 ir_value_vector_member(v, 0);
842 ir_value_vector_member(v, 1);
843 ir_value_vector_member(v, 2);
847 ir_function_enumerate(self);
849 if (!ir_function_calculate_liferanges(self))
851 if (!ir_function_allocate_locals(self))
856 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
861 vec_size(self->locals) &&
862 self->locals[vec_size(self->locals)-1]->store != store_param) {
863 irerror(self->context, "cannot add parameters after adding locals");
867 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
870 vec_push(self->locals, ve);
874 /***********************************************************************
878 ir_block* ir_block_new(ir_function* owner, const char *name)
880 ir_block *self = new ir_block;
881 memset(self, 0, sizeof(*self));
883 self->label = nullptr;
884 if (name && !ir_block_set_label(self, name)) {
889 self->context.file = "<@no context>";
890 self->context.line = 0;
893 self->instr = nullptr;
894 self->entries = nullptr;
895 self->exits = nullptr;
898 self->is_return = false;
899 self->generated = false;
904 static void ir_block_delete_quick(ir_block* self)
907 if (self->label) mem_d(self->label);
908 for (i = 0; i != vec_size(self->instr); ++i)
909 ir_instr_delete_quick(self->instr[i]);
910 vec_free(self->instr);
911 vec_free(self->entries);
912 vec_free(self->exits);
916 void ir_block_delete(ir_block* self)
919 if (self->label) mem_d(self->label);
920 for (i = 0; i != vec_size(self->instr); ++i)
921 ir_instr_delete(self->instr[i]);
922 vec_free(self->instr);
923 vec_free(self->entries);
924 vec_free(self->exits);
928 bool ir_block_set_label(ir_block *self, const char *name)
931 mem_d((void*)self->label);
932 self->label = util_strdup(name);
933 return !!self->label;
936 /***********************************************************************
940 static ir_instr* ir_instr_new(lex_ctx_t ctx, ir_block* owner, int op)
942 ir_instr *self = new ir_instr;
946 self->_ops[0] = nullptr;
947 self->_ops[1] = nullptr;
948 self->_ops[2] = nullptr;
949 self->bops[0] = nullptr;
950 self->bops[1] = nullptr;
956 static void ir_instr_delete_quick(ir_instr *self)
961 static void ir_instr_delete(ir_instr *self)
963 /* The following calls can only delete from
964 * vectors, we still want to delete this instruction
965 * so ignore the return value. Since with the warn_unused_result attribute
966 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
967 * I have to improvise here and use if(foo());
969 for (auto &it : self->phi) {
971 if (vec_ir_instr_find(it.value->writes, self, &idx))
972 it.value->writes.erase(it.value->writes.begin() + idx);
973 if (vec_ir_instr_find(it.value->reads, self, &idx))
974 it.value->reads.erase(it.value->reads.begin() + idx);
976 for (auto &it : self->params) {
978 if (vec_ir_instr_find(it->writes, self, &idx))
979 it->writes.erase(it->writes.begin() + idx);
980 if (vec_ir_instr_find(it->reads, self, &idx))
981 it->reads.erase(it->reads.begin() + idx);
983 (void)!ir_instr_op(self, 0, nullptr, false);
984 (void)!ir_instr_op(self, 1, nullptr, false);
985 (void)!ir_instr_op(self, 2, nullptr, false);
989 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
991 if (v && v->vtype == TYPE_NOEXPR) {
992 irerror(self->context, "tried to use a NOEXPR value");
996 if (self->_ops[op]) {
998 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
999 self->_ops[op]->writes.erase(self->_ops[op]->writes.begin() + idx);
1000 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1001 self->_ops[op]->reads.erase(self->_ops[op]->reads.begin() + idx);
1005 v->writes.push_back(self);
1007 v->reads.push_back(self);
1013 /***********************************************************************
1017 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1019 self->code.globaladdr = gaddr;
1020 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1021 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1022 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1025 static int32_t ir_value_code_addr(const ir_value *self)
1027 if (self->store == store_return)
1028 return OFS_RETURN + self->code.addroffset;
1029 return self->code.globaladdr + self->code.addroffset;
1032 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1035 self = (ir_value*)mem_a(sizeof(*self));
1036 new (self) ir_value();
1037 self->vtype = vtype;
1038 self->fieldtype = TYPE_VOID;
1039 self->outtype = TYPE_VOID;
1040 self->store = storetype;
1043 self->cvq = CV_NONE;
1044 self->hasvalue = false;
1045 self->context.file = "<@no context>";
1046 self->context.line = 0;
1047 self->name = nullptr;
1048 if (name && !ir_value_set_name(self, name)) {
1049 irerror(self->context, "out of memory");
1054 memset(&self->constval, 0, sizeof(self->constval));
1055 memset(&self->code, 0, sizeof(self->code));
1057 self->members[0] = nullptr;
1058 self->members[1] = nullptr;
1059 self->members[2] = nullptr;
1060 self->memberof = nullptr;
1062 self->unique_life = false;
1063 self->locked = false;
1064 self->callparam = false;
1066 self->life = nullptr;
1070 /* helper function */
1071 static ir_value* ir_builder_imm_float(ir_builder *self, float value, bool add_to_list) {
1072 ir_value *v = ir_value_var("#IMMEDIATE", store_global, TYPE_FLOAT);
1073 v->flags |= IR_FLAG_ERASABLE;
1076 v->constval.vfloat = value;
1078 vec_push(self->globals, v);
1080 vec_push(self->const_floats, v);
1084 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1092 if (self->members[member])
1093 return self->members[member];
1096 len = strlen(self->name);
1097 name = (char*)mem_a(len + 3);
1098 memcpy(name, self->name, len);
1100 name[len+1] = 'x' + member;
1106 if (self->vtype == TYPE_VECTOR)
1108 m = ir_value_var(name, self->store, TYPE_FLOAT);
1113 m->context = self->context;
1115 self->members[member] = m;
1116 m->code.addroffset = member;
1118 else if (self->vtype == TYPE_FIELD)
1120 if (self->fieldtype != TYPE_VECTOR)
1122 m = ir_value_var(name, self->store, TYPE_FIELD);
1127 m->fieldtype = TYPE_FLOAT;
1128 m->context = self->context;
1130 self->members[member] = m;
1131 m->code.addroffset = member;
1135 irerror(self->context, "invalid member access on %s", self->name);
1143 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1145 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1146 return type_sizeof_[TYPE_VECTOR];
1147 return type_sizeof_[self->vtype];
1150 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1152 ir_value *v = ir_value_var(name, storetype, vtype);
1155 ir_function_collect_value(owner, v);
1159 void ir_value_delete(ir_value* self)
1163 mem_d((void*)self->name);
1166 if (self->vtype == TYPE_STRING)
1167 mem_d((void*)self->constval.vstring);
1169 if (!(self->flags & IR_FLAG_SPLIT_VECTOR)) {
1170 for (i = 0; i < 3; ++i) {
1171 if (self->members[i])
1172 ir_value_delete(self->members[i]);
1175 vec_free(self->life);
1179 bool ir_value_set_name(ir_value *self, const char *name)
1182 mem_d((void*)self->name);
1183 self->name = util_strdup(name);
1184 return !!self->name;
1187 bool ir_value_set_float(ir_value *self, float f)
1189 if (self->vtype != TYPE_FLOAT)
1191 self->constval.vfloat = f;
1192 self->hasvalue = true;
1196 bool ir_value_set_func(ir_value *self, int f)
1198 if (self->vtype != TYPE_FUNCTION)
1200 self->constval.vint = f;
1201 self->hasvalue = true;
1205 bool ir_value_set_vector(ir_value *self, vec3_t v)
1207 if (self->vtype != TYPE_VECTOR)
1209 self->constval.vvec = v;
1210 self->hasvalue = true;
1214 bool ir_value_set_field(ir_value *self, ir_value *fld)
1216 if (self->vtype != TYPE_FIELD)
1218 self->constval.vpointer = fld;
1219 self->hasvalue = true;
1223 bool ir_value_set_string(ir_value *self, const char *str)
1225 if (self->vtype != TYPE_STRING)
1227 self->constval.vstring = util_strdupe(str);
1228 self->hasvalue = true;
1233 bool ir_value_set_int(ir_value *self, int i)
1235 if (self->vtype != TYPE_INTEGER)
1237 self->constval.vint = i;
1238 self->hasvalue = true;
1243 bool ir_value_lives(ir_value *self, size_t at)
1246 for (i = 0; i < vec_size(self->life); ++i)
1248 ir_life_entry_t *life = &self->life[i];
1249 if (life->start <= at && at <= life->end)
1251 if (life->start > at) /* since it's ordered */
1257 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1260 vec_push(self->life, e);
1261 for (k = vec_size(self->life)-1; k > idx; --k)
1262 self->life[k] = self->life[k-1];
1263 self->life[idx] = e;
1267 static bool ir_value_life_merge(ir_value *self, size_t s)
1270 const size_t vs = vec_size(self->life);
1271 ir_life_entry_t *life = nullptr;
1272 ir_life_entry_t *before = nullptr;
1273 ir_life_entry_t new_entry;
1275 /* Find the first range >= s */
1276 for (i = 0; i < vs; ++i)
1279 life = &self->life[i];
1280 if (life->start > s)
1283 /* nothing found? append */
1286 if (life && life->end+1 == s)
1288 /* previous life range can be merged in */
1292 if (life && life->end >= s)
1294 e.start = e.end = s;
1295 vec_push(self->life, e);
1301 if (before->end + 1 == s &&
1302 life->start - 1 == s)
1305 before->end = life->end;
1306 vec_remove(self->life, i, 1);
1309 if (before->end + 1 == s)
1315 /* already contained */
1316 if (before->end >= s)
1320 if (life->start - 1 == s)
1325 /* insert a new entry */
1326 new_entry.start = new_entry.end = s;
1327 return ir_value_life_insert(self, i, new_entry);
1330 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1334 if (!vec_size(other->life))
1337 if (!vec_size(self->life)) {
1338 size_t count = vec_size(other->life);
1339 ir_life_entry_t *life = vec_add(self->life, count);
1340 memcpy(life, other->life, count * sizeof(*life));
1345 for (i = 0; i < vec_size(other->life); ++i)
1347 const ir_life_entry_t *life = &other->life[i];
1350 ir_life_entry_t *entry = &self->life[myi];
1352 if (life->end+1 < entry->start)
1354 /* adding an interval before entry */
1355 if (!ir_value_life_insert(self, myi, *life))
1361 if (life->start < entry->start &&
1362 life->end+1 >= entry->start)
1364 /* starts earlier and overlaps */
1365 entry->start = life->start;
1368 if (life->end > entry->end &&
1369 life->start <= entry->end+1)
1371 /* ends later and overlaps */
1372 entry->end = life->end;
1375 /* see if our change combines it with the next ranges */
1376 while (myi+1 < vec_size(self->life) &&
1377 entry->end+1 >= self->life[1+myi].start)
1379 /* overlaps with (myi+1) */
1380 if (entry->end < self->life[1+myi].end)
1381 entry->end = self->life[1+myi].end;
1382 vec_remove(self->life, myi+1, 1);
1383 entry = &self->life[myi];
1386 /* see if we're after the entry */
1387 if (life->start > entry->end)
1390 /* append if we're at the end */
1391 if (myi >= vec_size(self->life)) {
1392 vec_push(self->life, *life);
1395 /* otherweise check the next range */
1404 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1406 /* For any life entry in A see if it overlaps with
1407 * any life entry in B.
1408 * Note that the life entries are orderes, so we can make a
1409 * more efficient algorithm there than naively translating the
1413 ir_life_entry_t *la, *lb, *enda, *endb;
1415 /* first of all, if either has no life range, they cannot clash */
1416 if (!vec_size(a->life) || !vec_size(b->life))
1421 enda = la + vec_size(a->life);
1422 endb = lb + vec_size(b->life);
1425 /* check if the entries overlap, for that,
1426 * both must start before the other one ends.
1428 if (la->start < lb->end &&
1429 lb->start < la->end)
1434 /* entries are ordered
1435 * one entry is earlier than the other
1436 * that earlier entry will be moved forward
1438 if (la->start < lb->start)
1440 /* order: A B, move A forward
1441 * check if we hit the end with A
1446 else /* if (lb->start < la->start) actually <= */
1448 /* order: B A, move B forward
1449 * check if we hit the end with B
1458 /***********************************************************************
1462 static bool ir_check_unreachable(ir_block *self)
1464 /* The IR should never have to deal with unreachable code */
1465 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1467 irerror(self->context, "unreachable statement (%s)", self->label);
1471 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1474 if (!ir_check_unreachable(self))
1477 if (target->store == store_value &&
1478 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1480 irerror(self->context, "cannot store to an SSA value");
1481 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1482 irerror(self->context, "instruction: %s", util_instr_str[op]);
1486 in = ir_instr_new(ctx, self, op);
1490 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1491 !ir_instr_op(in, 1, what, false))
1493 ir_instr_delete(in);
1496 vec_push(self->instr, in);
1500 bool ir_block_create_state_op(ir_block *self, lex_ctx_t ctx, ir_value *frame, ir_value *think)
1503 if (!ir_check_unreachable(self))
1506 in = ir_instr_new(ctx, self, INSTR_STATE);
1510 if (!ir_instr_op(in, 0, frame, false) ||
1511 !ir_instr_op(in, 1, think, false))
1513 ir_instr_delete(in);
1516 vec_push(self->instr, in);
1520 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1524 if (target->vtype == TYPE_VARIANT)
1525 vtype = what->vtype;
1527 vtype = target->vtype;
1530 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1531 op = INSTR_CONV_ITOF;
1532 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1533 op = INSTR_CONV_FTOI;
1535 op = type_store_instr[vtype];
1537 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1538 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1542 return ir_block_create_store_op(self, ctx, op, target, what);
1545 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1550 if (target->vtype != TYPE_POINTER)
1553 /* storing using pointer - target is a pointer, type must be
1554 * inferred from source
1556 vtype = what->vtype;
1558 op = type_storep_instr[vtype];
1559 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1560 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1561 op = INSTR_STOREP_V;
1564 return ir_block_create_store_op(self, ctx, op, target, what);
1567 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1570 if (!ir_check_unreachable(self))
1575 self->is_return = true;
1576 in = ir_instr_new(ctx, self, INSTR_RETURN);
1580 if (v && !ir_instr_op(in, 0, v, false)) {
1581 ir_instr_delete(in);
1585 vec_push(self->instr, in);
1589 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1590 ir_block *ontrue, ir_block *onfalse)
1593 if (!ir_check_unreachable(self))
1596 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1597 in = ir_instr_new(ctx, self, VINSTR_COND);
1601 if (!ir_instr_op(in, 0, v, false)) {
1602 ir_instr_delete(in);
1606 in->bops[0] = ontrue;
1607 in->bops[1] = onfalse;
1609 vec_push(self->instr, in);
1611 vec_push(self->exits, ontrue);
1612 vec_push(self->exits, onfalse);
1613 vec_push(ontrue->entries, self);
1614 vec_push(onfalse->entries, self);
1618 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1621 if (!ir_check_unreachable(self))
1624 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1629 vec_push(self->instr, in);
1631 vec_push(self->exits, to);
1632 vec_push(to->entries, self);
1636 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1638 self->owner->flags |= IR_FLAG_HAS_GOTO;
1639 return ir_block_create_jump(self, ctx, to);
1642 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, int ot)
1646 if (!ir_check_unreachable(self))
1648 in = ir_instr_new(ctx, self, VINSTR_PHI);
1651 out = ir_value_out(self->owner, label, store_value, ot);
1653 ir_instr_delete(in);
1656 if (!ir_instr_op(in, 0, out, true)) {
1657 ir_instr_delete(in);
1658 ir_value_delete(out);
1661 vec_push(self->instr, in);
1665 ir_value* ir_phi_value(ir_instr *self)
1667 return self->_ops[0];
1670 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1674 if (!vec_ir_block_find(self->owner->entries, b, nullptr)) {
1675 /* Must not be possible to cause this, otherwise the AST
1676 * is doing something wrong.
1678 irerror(self->context, "Invalid entry block for PHI");
1684 v->reads.push_back(self);
1685 self->phi.push_back(pe);
1688 /* call related code */
1689 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1693 if (!ir_check_unreachable(self))
1695 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1700 self->is_return = true;
1702 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1704 ir_instr_delete(in);
1707 if (!ir_instr_op(in, 0, out, true) ||
1708 !ir_instr_op(in, 1, func, false))
1710 ir_instr_delete(in);
1711 ir_value_delete(out);
1714 vec_push(self->instr, in);
1717 if (!ir_block_create_return(self, ctx, nullptr)) {
1718 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1719 ir_instr_delete(in);
1727 ir_value* ir_call_value(ir_instr *self)
1729 return self->_ops[0];
1732 void ir_call_param(ir_instr* self, ir_value *v)
1734 self->params.push_back(v);
1735 v->reads.push_back(self);
1738 /* binary op related code */
1740 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1741 const char *label, int opcode,
1742 ir_value *left, ir_value *right)
1765 case INSTR_SUB_S: /* -- offset of string as float */
1770 case INSTR_BITOR_IF:
1771 case INSTR_BITOR_FI:
1772 case INSTR_BITAND_FI:
1773 case INSTR_BITAND_IF:
1788 case INSTR_BITAND_I:
1791 case INSTR_RSHIFT_I:
1792 case INSTR_LSHIFT_I:
1800 case VINSTR_BITAND_V:
1801 case VINSTR_BITOR_V:
1802 case VINSTR_BITXOR_V:
1803 case VINSTR_BITAND_VF:
1804 case VINSTR_BITOR_VF:
1805 case VINSTR_BITXOR_VF:
1820 * after the following default case, the value of opcode can never
1821 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1825 /* boolean operations result in floats */
1828 * opcode >= 10 takes true branch opcode is at least 10
1829 * opcode <= 23 takes false branch opcode is at least 24
1831 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1835 * At condition "opcode <= 23", the value of "opcode" must be
1837 * At condition "opcode <= 23", the value of "opcode" cannot be
1838 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1839 * The condition "opcode <= 23" cannot be true.
1841 * Thus ot=2 (TYPE_FLOAT) can never be true
1844 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1846 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1851 if (ot == TYPE_VOID) {
1852 /* The AST or parser were supposed to check this! */
1856 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1859 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1860 const char *label, int opcode,
1863 int ot = TYPE_FLOAT;
1869 case INSTR_NOT_FNC: /*
1870 case INSTR_NOT_I: */
1875 * Negation for virtual instructions is emulated with 0-value. Thankfully
1876 * the operand for 0 already exists so we just source it from here.
1879 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_F, nullptr, operand, ot);
1881 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_V, nullptr, operand, TYPE_VECTOR);
1884 ot = operand->vtype;
1887 if (ot == TYPE_VOID) {
1888 /* The AST or parser were supposed to check this! */
1892 /* let's use the general instruction creator and pass nullptr for OPB */
1893 return ir_block_create_general_instr(self, ctx, label, opcode, operand, nullptr, ot);
1896 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1897 int op, ir_value *a, ir_value *b, int outype)
1902 out = ir_value_out(self->owner, label, store_value, outype);
1906 instr = ir_instr_new(ctx, self, op);
1908 ir_value_delete(out);
1912 if (!ir_instr_op(instr, 0, out, true) ||
1913 !ir_instr_op(instr, 1, a, false) ||
1914 !ir_instr_op(instr, 2, b, false) )
1919 vec_push(self->instr, instr);
1923 ir_instr_delete(instr);
1924 ir_value_delete(out);
1928 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1932 /* Support for various pointer types todo if so desired */
1933 if (ent->vtype != TYPE_ENTITY)
1936 if (field->vtype != TYPE_FIELD)
1939 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1940 v->fieldtype = field->fieldtype;
1944 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)
1947 if (ent->vtype != TYPE_ENTITY)
1950 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1951 if (field->vtype != TYPE_FIELD)
1956 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1957 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1958 case TYPE_STRING: op = INSTR_LOAD_S; break;
1959 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1960 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1961 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1963 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1964 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1967 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1971 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1974 /* PHI resolving breaks the SSA, and must thus be the last
1975 * step before life-range calculation.
1978 static bool ir_block_naive_phi(ir_block *self);
1979 bool ir_function_naive_phi(ir_function *self)
1983 for (i = 0; i < vec_size(self->blocks); ++i)
1985 if (!ir_block_naive_phi(self->blocks[i]))
1991 static bool ir_block_naive_phi(ir_block *self)
1994 /* FIXME: optionally, create_phi can add the phis
1995 * to a list so we don't need to loop through blocks
1996 * - anyway: "don't optimize YET"
1998 for (i = 0; i < vec_size(self->instr); ++i)
2000 ir_instr *instr = self->instr[i];
2001 if (instr->opcode != VINSTR_PHI)
2004 vec_remove(self->instr, i, 1);
2005 --i; /* NOTE: i+1 below */
2007 for (auto &it : instr->phi) {
2008 ir_value *v = it.value;
2009 ir_block *b = it.from;
2010 if (v->store == store_value && v->reads.size() == 1 && v->writes.size() == 1) {
2011 /* replace the value */
2012 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2015 /* force a move instruction */
2016 ir_instr *prevjump = vec_last(b->instr);
2019 instr->_ops[0]->store = store_global;
2020 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2022 instr->_ops[0]->store = store_value;
2023 vec_push(b->instr, prevjump);
2027 ir_instr_delete(instr);
2032 /***********************************************************************
2033 *IR Temp allocation code
2034 * Propagating value life ranges by walking through the function backwards
2035 * until no more changes are made.
2036 * In theory this should happen once more than once for every nested loop
2038 * Though this implementation might run an additional time for if nests.
2041 /* Enumerate instructions used by value's life-ranges
2043 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2047 for (i = 0; i < vec_size(self->instr); ++i)
2049 self->instr[i]->eid = eid++;
2054 /* Enumerate blocks and instructions.
2055 * The block-enumeration is unordered!
2056 * We do not really use the block enumreation, however
2057 * the instruction enumeration is important for life-ranges.
2059 void ir_function_enumerate(ir_function *self)
2062 size_t instruction_id = 0;
2063 for (i = 0; i < vec_size(self->blocks); ++i)
2065 /* each block now gets an additional "entry" instruction id
2066 * we can use to avoid point-life issues
2068 self->blocks[i]->entry_id = instruction_id;
2071 self->blocks[i]->eid = i;
2072 ir_block_enumerate(self->blocks[i], &instruction_id);
2076 /* Local-value allocator
2077 * After finishing creating the liferange of all values used in a function
2078 * we can allocate their global-positions.
2079 * This is the counterpart to register-allocation in register machines.
2081 struct function_allocator {
2088 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2091 size_t vsize = ir_value_sizeof(var);
2093 var->code.local = vec_size(alloc->locals);
2095 slot = ir_value_var("reg", store_global, var->vtype);
2099 if (!ir_value_life_merge_into(slot, var))
2102 vec_push(alloc->locals, slot);
2103 vec_push(alloc->sizes, vsize);
2104 vec_push(alloc->unique, var->unique_life);
2109 ir_value_delete(slot);
2113 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2119 return function_allocator_alloc(alloc, v);
2121 for (a = 0; a < vec_size(alloc->locals); ++a)
2123 /* if it's reserved for a unique liferange: skip */
2124 if (alloc->unique[a])
2127 slot = alloc->locals[a];
2129 /* never resize parameters
2130 * will be required later when overlapping temps + locals
2132 if (a < vec_size(self->params) &&
2133 alloc->sizes[a] < ir_value_sizeof(v))
2138 if (ir_values_overlap(v, slot))
2141 if (!ir_value_life_merge_into(slot, v))
2144 /* adjust size for this slot */
2145 if (alloc->sizes[a] < ir_value_sizeof(v))
2146 alloc->sizes[a] = ir_value_sizeof(v);
2151 if (a >= vec_size(alloc->locals)) {
2152 if (!function_allocator_alloc(alloc, v))
2158 bool ir_function_allocate_locals(ir_function *self)
2163 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2167 function_allocator lockalloc, globalloc;
2169 if (!vec_size(self->locals) && !vec_size(self->values))
2172 globalloc.locals = nullptr;
2173 globalloc.sizes = nullptr;
2174 globalloc.positions = nullptr;
2175 globalloc.unique = nullptr;
2176 lockalloc.locals = nullptr;
2177 lockalloc.sizes = nullptr;
2178 lockalloc.positions = nullptr;
2179 lockalloc.unique = nullptr;
2181 for (i = 0; i < vec_size(self->locals); ++i)
2183 v = self->locals[i];
2184 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2186 v->unique_life = true;
2188 else if (i >= vec_size(self->params))
2191 v->locked = true; /* lock parameters locals */
2192 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2195 for (; i < vec_size(self->locals); ++i)
2197 v = self->locals[i];
2198 if (!vec_size(v->life))
2200 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2204 /* Allocate a slot for any value that still exists */
2205 for (i = 0; i < vec_size(self->values); ++i)
2207 v = self->values[i];
2209 if (!vec_size(v->life))
2212 /* CALL optimization:
2213 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2214 * and it's not "locked", write it to the OFS_PARM directly.
2216 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2217 if (v->reads.size() == 1 && v->writes.size() == 1 &&
2218 (v->reads[0]->opcode == VINSTR_NRCALL ||
2219 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2224 ir_instr *call = v->reads[0];
2225 if (!vec_ir_value_find(call->params, v, ¶m)) {
2226 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2229 ++opts_optimizationcount[OPTIM_CALL_STORES];
2230 v->callparam = true;
2232 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2234 size_t nprotos = vec_size(self->owner->extparam_protos);
2237 if (nprotos > param)
2238 ep = self->owner->extparam_protos[param];
2241 ep = ir_gen_extparam_proto(self->owner);
2242 while (++nprotos <= param)
2243 ep = ir_gen_extparam_proto(self->owner);
2245 ir_instr_op(v->writes[0], 0, ep, true);
2246 call->params[param+8] = ep;
2250 if (v->writes.size() == 1 && v->writes[0]->opcode == INSTR_CALL0) {
2251 v->store = store_return;
2252 if (v->members[0]) v->members[0]->store = store_return;
2253 if (v->members[1]) v->members[1]->store = store_return;
2254 if (v->members[2]) v->members[2]->store = store_return;
2255 ++opts_optimizationcount[OPTIM_CALL_STORES];
2260 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2264 if (!lockalloc.sizes && !globalloc.sizes) {
2267 vec_push(lockalloc.positions, 0);
2268 vec_push(globalloc.positions, 0);
2270 /* Adjust slot positions based on sizes */
2271 if (lockalloc.sizes) {
2272 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2273 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2275 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2276 vec_push(lockalloc.positions, pos);
2278 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2280 if (globalloc.sizes) {
2281 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2282 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2284 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2285 vec_push(globalloc.positions, pos);
2287 self->globaltemps = pos + vec_last(globalloc.sizes);
2290 /* Locals need to know their new position */
2291 for (i = 0; i < vec_size(self->locals); ++i) {
2292 v = self->locals[i];
2293 if (v->locked || !opt_gt)
2294 v->code.local = lockalloc.positions[v->code.local];
2296 v->code.local = globalloc.positions[v->code.local];
2298 /* Take over the actual slot positions on values */
2299 for (i = 0; i < vec_size(self->values); ++i) {
2300 v = self->values[i];
2301 if (v->locked || !opt_gt)
2302 v->code.local = lockalloc.positions[v->code.local];
2304 v->code.local = globalloc.positions[v->code.local];
2312 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2313 ir_value_delete(lockalloc.locals[i]);
2314 for (i = 0; i < vec_size(globalloc.locals); ++i)
2315 ir_value_delete(globalloc.locals[i]);
2316 vec_free(globalloc.unique);
2317 vec_free(globalloc.locals);
2318 vec_free(globalloc.sizes);
2319 vec_free(globalloc.positions);
2320 vec_free(lockalloc.unique);
2321 vec_free(lockalloc.locals);
2322 vec_free(lockalloc.sizes);
2323 vec_free(lockalloc.positions);
2327 /* Get information about which operand
2328 * is read from, or written to.
2330 static void ir_op_read_write(int op, size_t *read, size_t *write)
2350 case INSTR_STOREP_F:
2351 case INSTR_STOREP_V:
2352 case INSTR_STOREP_S:
2353 case INSTR_STOREP_ENT:
2354 case INSTR_STOREP_FLD:
2355 case INSTR_STOREP_FNC:
2366 static bool ir_block_living_add_instr(ir_block *self, size_t eid) {
2367 bool changed = false;
2368 for (auto &it : self->living)
2369 if (ir_value_life_merge(it, eid))
2374 static bool ir_block_living_lock(ir_block *self) {
2375 bool changed = false;
2376 for (auto &it : self->living) {
2385 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2389 size_t i, o, p, mem;
2390 /* bitmasks which operands are read from or written to */
2397 self->living.clear();
2399 p = vec_size(self->exits);
2400 for (i = 0; i < p; ++i) {
2401 ir_block *prev = self->exits[i];
2402 for (auto &it : prev->living)
2403 if (!vec_ir_value_find(self->living, it, nullptr))
2404 self->living.push_back(it);
2407 i = vec_size(self->instr);
2410 instr = self->instr[i];
2412 /* See which operands are read and write operands */
2413 ir_op_read_write(instr->opcode, &read, &write);
2415 /* Go through the 3 main operands
2416 * writes first, then reads
2418 for (o = 0; o < 3; ++o)
2420 if (!instr->_ops[o]) /* no such operand */
2423 value = instr->_ops[o];
2425 /* We only care about locals */
2426 /* we also calculate parameter liferanges so that locals
2427 * can take up parameter slots */
2428 if (value->store != store_value &&
2429 value->store != store_local &&
2430 value->store != store_param)
2433 /* write operands */
2434 /* When we write to a local, we consider it "dead" for the
2435 * remaining upper part of the function, since in SSA a value
2436 * can only be written once (== created)
2441 bool in_living = vec_ir_value_find(self->living, value, &idx);
2444 /* If the value isn't alive it hasn't been read before... */
2445 /* TODO: See if the warning can be emitted during parsing or AST processing
2446 * otherwise have warning printed here.
2447 * IF printing a warning here: include filecontext_t,
2448 * and make sure it's only printed once
2449 * since this function is run multiple times.
2451 /* con_err( "Value only written %s\n", value->name); */
2452 if (ir_value_life_merge(value, instr->eid))
2455 /* since 'living' won't contain it
2456 * anymore, merge the value, since
2459 if (ir_value_life_merge(value, instr->eid))
2462 self->living.erase(self->living.begin() + idx);
2464 /* Removing a vector removes all members */
2465 for (mem = 0; mem < 3; ++mem) {
2466 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2467 if (ir_value_life_merge(value->members[mem], instr->eid))
2469 self->living.erase(self->living.begin() + idx);
2472 /* Removing the last member removes the vector */
2473 if (value->memberof) {
2474 value = value->memberof;
2475 for (mem = 0; mem < 3; ++mem) {
2476 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], nullptr))
2479 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2480 if (ir_value_life_merge(value, instr->eid))
2482 self->living.erase(self->living.begin() + idx);
2488 /* These operations need a special case as they can break when using
2489 * same source and destination operand otherwise, as the engine may
2490 * read the source multiple times. */
2491 if (instr->opcode == INSTR_MUL_VF ||
2492 instr->opcode == VINSTR_BITAND_VF ||
2493 instr->opcode == VINSTR_BITOR_VF ||
2494 instr->opcode == VINSTR_BITXOR ||
2495 instr->opcode == VINSTR_BITXOR_VF ||
2496 instr->opcode == VINSTR_BITXOR_V ||
2497 instr->opcode == VINSTR_CROSS)
2499 value = instr->_ops[2];
2500 /* the float source will get an additional lifetime */
2501 if (ir_value_life_merge(value, instr->eid+1))
2503 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2507 if (instr->opcode == INSTR_MUL_FV ||
2508 instr->opcode == INSTR_LOAD_V ||
2509 instr->opcode == VINSTR_BITXOR ||
2510 instr->opcode == VINSTR_BITXOR_VF ||
2511 instr->opcode == VINSTR_BITXOR_V ||
2512 instr->opcode == VINSTR_CROSS)
2514 value = instr->_ops[1];
2515 /* the float source will get an additional lifetime */
2516 if (ir_value_life_merge(value, instr->eid+1))
2518 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2522 for (o = 0; o < 3; ++o)
2524 if (!instr->_ops[o]) /* no such operand */
2527 value = instr->_ops[o];
2529 /* We only care about locals */
2530 /* we also calculate parameter liferanges so that locals
2531 * can take up parameter slots */
2532 if (value->store != store_value &&
2533 value->store != store_local &&
2534 value->store != store_param)
2540 if (!vec_ir_value_find(self->living, value, nullptr))
2541 self->living.push_back(value);
2542 /* reading adds the full vector */
2543 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, nullptr))
2544 self->living.push_back(value->memberof);
2545 for (mem = 0; mem < 3; ++mem) {
2546 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], nullptr))
2547 self->living.push_back(value->members[mem]);
2551 /* PHI operands are always read operands */
2552 for (auto &it : instr->phi) {
2554 if (!vec_ir_value_find(self->living, value, nullptr))
2555 self->living.push_back(value);
2556 /* reading adds the full vector */
2557 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, nullptr))
2558 self->living.push_back(value->memberof);
2559 for (mem = 0; mem < 3; ++mem) {
2560 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], nullptr))
2561 self->living.push_back(value->members[mem]);
2565 /* on a call, all these values must be "locked" */
2566 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2567 if (ir_block_living_lock(self))
2570 /* call params are read operands too */
2571 for (auto &it : instr->params) {
2573 if (!vec_ir_value_find(self->living, value, nullptr))
2574 self->living.push_back(value);
2575 /* reading adds the full vector */
2576 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, nullptr))
2577 self->living.push_back(value->memberof);
2578 for (mem = 0; mem < 3; ++mem) {
2579 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], nullptr))
2580 self->living.push_back(value->members[mem]);
2585 if (ir_block_living_add_instr(self, instr->eid))
2588 /* the "entry" instruction ID */
2589 if (ir_block_living_add_instr(self, self->entry_id))
2595 bool ir_function_calculate_liferanges(ir_function *self)
2600 /* parameters live at 0 */
2601 for (i = 0; i < vec_size(self->params); ++i)
2602 if (!ir_value_life_merge(self->locals[i], 0))
2603 compile_error(self->context, "internal error: failed value-life merging");
2608 i = vec_size(self->blocks);
2610 ir_block_life_propagate(self->blocks[i], &changed);
2614 if (vec_size(self->blocks)) {
2615 ir_block *block = self->blocks[0];
2616 for (auto &it : block->living) {
2618 if (v->store != store_local)
2620 if (v->vtype == TYPE_VECTOR)
2622 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2623 /* find the instruction reading from it */
2624 for (s = 0; s < v->reads.size(); ++s) {
2625 if (v->reads[s]->eid == v->life[0].end)
2628 if (s < v->reads.size()) {
2629 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2630 "variable `%s` may be used uninitialized in this function\n"
2633 v->reads[s]->context.file, v->reads[s]->context.line)
2641 ir_value *vec = v->memberof;
2642 for (s = 0; s < vec->reads.size(); ++s) {
2643 if (vec->reads[s]->eid == v->life[0].end)
2646 if (s < vec->reads.size()) {
2647 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2648 "variable `%s` may be used uninitialized in this function\n"
2651 vec->reads[s]->context.file, vec->reads[s]->context.line)
2659 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2660 "variable `%s` may be used uninitialized in this function", v->name))
2669 /***********************************************************************
2672 * Since the IR has the convention of putting 'write' operands
2673 * at the beginning, we have to rotate the operands of instructions
2674 * properly in order to generate valid QCVM code.
2676 * Having destinations at a fixed position is more convenient. In QC
2677 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2678 * read from from OPA, and store to OPB rather than OPC. Which is
2679 * partially the reason why the implementation of these instructions
2680 * in darkplaces has been delayed for so long.
2682 * Breaking conventions is annoying...
2684 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2686 static bool gen_global_field(code_t *code, ir_value *global)
2688 if (global->hasvalue)
2690 ir_value *fld = global->constval.vpointer;
2692 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2696 /* copy the field's value */
2697 ir_value_code_setaddr(global, code->globals.size());
2698 code->globals.push_back(fld->code.fieldaddr);
2699 if (global->fieldtype == TYPE_VECTOR) {
2700 code->globals.push_back(fld->code.fieldaddr+1);
2701 code->globals.push_back(fld->code.fieldaddr+2);
2706 ir_value_code_setaddr(global, code->globals.size());
2707 code->globals.push_back(0);
2708 if (global->fieldtype == TYPE_VECTOR) {
2709 code->globals.push_back(0);
2710 code->globals.push_back(0);
2713 if (global->code.globaladdr < 0)
2718 static bool gen_global_pointer(code_t *code, ir_value *global)
2720 if (global->hasvalue)
2722 ir_value *target = global->constval.vpointer;
2724 irerror(global->context, "Invalid pointer constant: %s", global->name);
2725 /* nullptr pointers are pointing to the nullptr constant, which also
2726 * sits at address 0, but still has an ir_value for itself.
2731 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2732 * void() foo; <- proto
2733 * void() *fooptr = &foo;
2734 * void() foo = { code }
2736 if (!target->code.globaladdr) {
2737 /* FIXME: Check for the constant nullptr ir_value!
2738 * because then code.globaladdr being 0 is valid.
2740 irerror(global->context, "FIXME: Relocation support");
2744 ir_value_code_setaddr(global, code->globals.size());
2745 code->globals.push_back(target->code.globaladdr);
2749 ir_value_code_setaddr(global, code->globals.size());
2750 code->globals.push_back(0);
2752 if (global->code.globaladdr < 0)
2757 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2759 prog_section_statement_t stmt;
2768 block->generated = true;
2769 block->code_start = code->statements.size();
2770 for (i = 0; i < vec_size(block->instr); ++i)
2772 instr = block->instr[i];
2774 if (instr->opcode == VINSTR_PHI) {
2775 irerror(block->context, "cannot generate virtual instruction (phi)");
2779 if (instr->opcode == VINSTR_JUMP) {
2780 target = instr->bops[0];
2781 /* for uncoditional jumps, if the target hasn't been generated
2782 * yet, we generate them right here.
2784 if (!target->generated)
2785 return gen_blocks_recursive(code, func, target);
2787 /* otherwise we generate a jump instruction */
2788 stmt.opcode = INSTR_GOTO;
2789 stmt.o1.s1 = target->code_start - code->statements.size();
2792 if (stmt.o1.s1 != 1)
2793 code_push_statement(code, &stmt, instr->context);
2795 /* no further instructions can be in this block */
2799 if (instr->opcode == VINSTR_BITXOR) {
2800 stmt.opcode = INSTR_BITOR;
2801 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2802 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2803 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2804 code_push_statement(code, &stmt, instr->context);
2805 stmt.opcode = INSTR_BITAND;
2806 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2807 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2808 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2809 code_push_statement(code, &stmt, instr->context);
2810 stmt.opcode = INSTR_SUB_F;
2811 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2812 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2813 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2814 code_push_statement(code, &stmt, instr->context);
2816 /* instruction generated */
2820 if (instr->opcode == VINSTR_BITAND_V) {
2821 stmt.opcode = INSTR_BITAND;
2822 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2823 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2824 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2825 code_push_statement(code, &stmt, instr->context);
2829 code_push_statement(code, &stmt, instr->context);
2833 code_push_statement(code, &stmt, instr->context);
2835 /* instruction generated */
2839 if (instr->opcode == VINSTR_BITOR_V) {
2840 stmt.opcode = INSTR_BITOR;
2841 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2842 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2843 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2844 code_push_statement(code, &stmt, instr->context);
2848 code_push_statement(code, &stmt, instr->context);
2852 code_push_statement(code, &stmt, instr->context);
2854 /* instruction generated */
2858 if (instr->opcode == VINSTR_BITXOR_V) {
2859 for (j = 0; j < 3; ++j) {
2860 stmt.opcode = INSTR_BITOR;
2861 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2862 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2863 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2864 code_push_statement(code, &stmt, instr->context);
2865 stmt.opcode = INSTR_BITAND;
2866 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2867 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2868 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2869 code_push_statement(code, &stmt, instr->context);
2871 stmt.opcode = INSTR_SUB_V;
2872 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2873 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2874 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2875 code_push_statement(code, &stmt, instr->context);
2877 /* instruction generated */
2881 if (instr->opcode == VINSTR_BITAND_VF) {
2882 stmt.opcode = INSTR_BITAND;
2883 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2884 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2885 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2886 code_push_statement(code, &stmt, instr->context);
2889 code_push_statement(code, &stmt, instr->context);
2892 code_push_statement(code, &stmt, instr->context);
2894 /* instruction generated */
2898 if (instr->opcode == VINSTR_BITOR_VF) {
2899 stmt.opcode = INSTR_BITOR;
2900 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2901 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2902 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2903 code_push_statement(code, &stmt, instr->context);
2906 code_push_statement(code, &stmt, instr->context);
2909 code_push_statement(code, &stmt, instr->context);
2911 /* instruction generated */
2915 if (instr->opcode == VINSTR_BITXOR_VF) {
2916 for (j = 0; j < 3; ++j) {
2917 stmt.opcode = INSTR_BITOR;
2918 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2919 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2920 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2921 code_push_statement(code, &stmt, instr->context);
2922 stmt.opcode = INSTR_BITAND;
2923 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2924 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2925 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2926 code_push_statement(code, &stmt, instr->context);
2928 stmt.opcode = INSTR_SUB_V;
2929 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2930 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2931 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2932 code_push_statement(code, &stmt, instr->context);
2934 /* instruction generated */
2938 if (instr->opcode == VINSTR_CROSS) {
2939 stmt.opcode = INSTR_MUL_F;
2940 for (j = 0; j < 3; ++j) {
2941 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 1) % 3;
2942 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 2) % 3;
2943 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2944 code_push_statement(code, &stmt, instr->context);
2945 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 2) % 3;
2946 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 1) % 3;
2947 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2948 code_push_statement(code, &stmt, instr->context);
2950 stmt.opcode = INSTR_SUB_V;
2951 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2952 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2953 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2954 code_push_statement(code, &stmt, instr->context);
2956 /* instruction generated */
2960 if (instr->opcode == VINSTR_COND) {
2961 ontrue = instr->bops[0];
2962 onfalse = instr->bops[1];
2963 /* TODO: have the AST signal which block should
2964 * come first: eg. optimize IFs without ELSE...
2967 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2971 if (ontrue->generated) {
2972 stmt.opcode = INSTR_IF;
2973 stmt.o2.s1 = ontrue->code_start - code->statements.size();
2974 if (stmt.o2.s1 != 1)
2975 code_push_statement(code, &stmt, instr->context);
2977 if (onfalse->generated) {
2978 stmt.opcode = INSTR_IFNOT;
2979 stmt.o2.s1 = onfalse->code_start - code->statements.size();
2980 if (stmt.o2.s1 != 1)
2981 code_push_statement(code, &stmt, instr->context);
2983 if (!ontrue->generated) {
2984 if (onfalse->generated)
2985 return gen_blocks_recursive(code, func, ontrue);
2987 if (!onfalse->generated) {
2988 if (ontrue->generated)
2989 return gen_blocks_recursive(code, func, onfalse);
2991 /* neither ontrue nor onfalse exist */
2992 stmt.opcode = INSTR_IFNOT;
2993 if (!instr->likely) {
2994 /* Honor the likelyhood hint */
2995 ir_block *tmp = onfalse;
2996 stmt.opcode = INSTR_IF;
3000 stidx = code->statements.size();
3001 code_push_statement(code, &stmt, instr->context);
3002 /* on false we jump, so add ontrue-path */
3003 if (!gen_blocks_recursive(code, func, ontrue))
3005 /* fixup the jump address */
3006 code->statements[stidx].o2.s1 = code->statements.size() - stidx;
3007 /* generate onfalse path */
3008 if (onfalse->generated) {
3009 /* fixup the jump address */
3010 code->statements[stidx].o2.s1 = onfalse->code_start - stidx;
3011 if (stidx+2 == code->statements.size() && code->statements[stidx].o2.s1 == 1) {
3012 code->statements[stidx] = code->statements[stidx+1];
3013 if (code->statements[stidx].o1.s1 < 0)
3014 code->statements[stidx].o1.s1++;
3015 code_pop_statement(code);
3017 stmt.opcode = code->statements.back().opcode;
3018 if (stmt.opcode == INSTR_GOTO ||
3019 stmt.opcode == INSTR_IF ||
3020 stmt.opcode == INSTR_IFNOT ||
3021 stmt.opcode == INSTR_RETURN ||
3022 stmt.opcode == INSTR_DONE)
3024 /* no use jumping from here */
3027 /* may have been generated in the previous recursive call */
3028 stmt.opcode = INSTR_GOTO;
3029 stmt.o1.s1 = onfalse->code_start - code->statements.size();
3032 if (stmt.o1.s1 != 1)
3033 code_push_statement(code, &stmt, instr->context);
3036 else if (stidx+2 == code->statements.size() && code->statements[stidx].o2.s1 == 1) {
3037 code->statements[stidx] = code->statements[stidx+1];
3038 if (code->statements[stidx].o1.s1 < 0)
3039 code->statements[stidx].o1.s1++;
3040 code_pop_statement(code);
3042 /* if not, generate now */
3043 return gen_blocks_recursive(code, func, onfalse);
3046 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
3047 || instr->opcode == VINSTR_NRCALL)
3052 first = instr->params.size();
3055 for (p = 0; p < first; ++p)
3057 ir_value *param = instr->params[p];
3058 if (param->callparam)
3061 stmt.opcode = INSTR_STORE_F;
3064 if (param->vtype == TYPE_FIELD)
3065 stmt.opcode = field_store_instr[param->fieldtype];
3066 else if (param->vtype == TYPE_NIL)
3067 stmt.opcode = INSTR_STORE_V;
3069 stmt.opcode = type_store_instr[param->vtype];
3070 stmt.o1.u1 = ir_value_code_addr(param);
3071 stmt.o2.u1 = OFS_PARM0 + 3 * p;
3073 if (param->vtype == TYPE_VECTOR && (param->flags & IR_FLAG_SPLIT_VECTOR)) {
3074 /* fetch 3 separate floats */
3075 stmt.opcode = INSTR_STORE_F;
3076 stmt.o1.u1 = ir_value_code_addr(param->members[0]);
3077 code_push_statement(code, &stmt, instr->context);
3079 stmt.o1.u1 = ir_value_code_addr(param->members[1]);
3080 code_push_statement(code, &stmt, instr->context);
3082 stmt.o1.u1 = ir_value_code_addr(param->members[2]);
3083 code_push_statement(code, &stmt, instr->context);
3086 code_push_statement(code, &stmt, instr->context);
3088 /* Now handle extparams */
3089 first = instr->params.size();
3090 for (; p < first; ++p)
3092 ir_builder *ir = func->owner;
3093 ir_value *param = instr->params[p];
3094 ir_value *targetparam;
3096 if (param->callparam)
3099 if (p-8 >= vec_size(ir->extparams))
3100 ir_gen_extparam(ir);
3102 targetparam = ir->extparams[p-8];
3104 stmt.opcode = INSTR_STORE_F;
3107 if (param->vtype == TYPE_FIELD)
3108 stmt.opcode = field_store_instr[param->fieldtype];
3109 else if (param->vtype == TYPE_NIL)
3110 stmt.opcode = INSTR_STORE_V;
3112 stmt.opcode = type_store_instr[param->vtype];
3113 stmt.o1.u1 = ir_value_code_addr(param);
3114 stmt.o2.u1 = ir_value_code_addr(targetparam);
3115 if (param->vtype == TYPE_VECTOR && (param->flags & IR_FLAG_SPLIT_VECTOR)) {
3116 /* fetch 3 separate floats */
3117 stmt.opcode = INSTR_STORE_F;
3118 stmt.o1.u1 = ir_value_code_addr(param->members[0]);
3119 code_push_statement(code, &stmt, instr->context);
3121 stmt.o1.u1 = ir_value_code_addr(param->members[1]);
3122 code_push_statement(code, &stmt, instr->context);
3124 stmt.o1.u1 = ir_value_code_addr(param->members[2]);
3125 code_push_statement(code, &stmt, instr->context);
3128 code_push_statement(code, &stmt, instr->context);
3131 stmt.opcode = INSTR_CALL0 + instr->params.size();
3132 if (stmt.opcode > INSTR_CALL8)
3133 stmt.opcode = INSTR_CALL8;
3134 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
3137 code_push_statement(code, &stmt, instr->context);
3139 retvalue = instr->_ops[0];
3140 if (retvalue && retvalue->store != store_return &&
3141 (retvalue->store == store_global || vec_size(retvalue->life)))
3143 /* not to be kept in OFS_RETURN */
3144 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
3145 stmt.opcode = field_store_instr[retvalue->fieldtype];
3147 stmt.opcode = type_store_instr[retvalue->vtype];
3148 stmt.o1.u1 = OFS_RETURN;
3149 stmt.o2.u1 = ir_value_code_addr(retvalue);
3151 code_push_statement(code, &stmt, instr->context);
3156 if (instr->opcode == INSTR_STATE) {
3157 stmt.opcode = instr->opcode;
3159 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
3161 stmt.o2.u1 = ir_value_code_addr(instr->_ops[1]);
3163 code_push_statement(code, &stmt, instr->context);
3167 stmt.opcode = instr->opcode;
3172 /* This is the general order of operands */
3174 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
3177 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
3180 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
3182 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
3184 stmt.o1.u1 = stmt.o3.u1;
3187 else if ((stmt.opcode >= INSTR_STORE_F &&
3188 stmt.opcode <= INSTR_STORE_FNC) ||
3189 (stmt.opcode >= INSTR_STOREP_F &&
3190 stmt.opcode <= INSTR_STOREP_FNC))
3192 /* 2-operand instructions with A -> B */
3193 stmt.o2.u1 = stmt.o3.u1;
3196 /* tiny optimization, don't output
3199 if (stmt.o2.u1 == stmt.o1.u1 &&
3200 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
3202 ++opts_optimizationcount[OPTIM_PEEPHOLE];
3206 code_push_statement(code, &stmt, instr->context);
3211 static bool gen_function_code(code_t *code, ir_function *self)
3214 prog_section_statement_t stmt, *retst;
3216 /* Starting from entry point, we generate blocks "as they come"
3217 * for now. Dead blocks will not be translated obviously.
3219 if (!vec_size(self->blocks)) {
3220 irerror(self->context, "Function '%s' declared without body.", self->name);
3224 block = self->blocks[0];
3225 if (block->generated)
3228 if (!gen_blocks_recursive(code, self, block)) {
3229 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3233 /* code_write and qcvm -disasm need to know that the function ends here */
3234 retst = &code->statements.back();
3235 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3236 self->outtype == TYPE_VOID &&
3237 retst->opcode == INSTR_RETURN &&
3238 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3240 retst->opcode = INSTR_DONE;
3241 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3245 stmt.opcode = INSTR_DONE;
3249 last.line = code->linenums.back();
3250 last.column = code->columnnums.back();
3252 code_push_statement(code, &stmt, last);
3257 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3259 /* NOTE: filename pointers are copied, we never strdup them,
3260 * thus we can use pointer-comparison to find the string.
3265 for (i = 0; i < vec_size(ir->filenames); ++i) {
3266 if (ir->filenames[i] == filename)
3267 return ir->filestrings[i];
3270 str = code_genstring(ir->code, filename);
3271 vec_push(ir->filenames, filename);
3272 vec_push(ir->filestrings, str);
3276 static bool gen_global_function(ir_builder *ir, ir_value *global)
3278 prog_section_function_t fun;
3283 if (!global->hasvalue || (!global->constval.vfunc)) {
3284 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3288 irfun = global->constval.vfunc;
3289 fun.name = global->code.name;
3290 fun.file = ir_builder_filestring(ir, global->context.file);
3291 fun.profile = 0; /* always 0 */
3292 fun.nargs = vec_size(irfun->params);
3296 for (i = 0; i < 8; ++i) {
3297 if ((int32_t)i >= fun.nargs)
3300 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3304 fun.locals = irfun->allocated_locals;
3307 fun.entry = irfun->builtin+1;
3309 irfun->code_function_def = ir->code->functions.size();
3310 fun.entry = ir->code->statements.size();
3313 ir->code->functions.push_back(fun);
3317 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3322 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3323 global = ir_value_var(name, store_global, TYPE_VECTOR);
3325 vec_push(ir->extparam_protos, global);
3329 static void ir_gen_extparam(ir_builder *ir)
3331 prog_section_def_t def;
3334 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3335 global = ir_gen_extparam_proto(ir);
3337 global = ir->extparam_protos[vec_size(ir->extparams)];
3339 def.name = code_genstring(ir->code, global->name);
3340 def.type = TYPE_VECTOR;
3341 def.offset = ir->code->globals.size();
3343 ir->code->defs.push_back(def);
3345 ir_value_code_setaddr(global, def.offset);
3347 ir->code->globals.push_back(0);
3348 ir->code->globals.push_back(0);
3349 ir->code->globals.push_back(0);
3351 vec_push(ir->extparams, global);
3354 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3356 size_t i, ext, numparams;
3358 ir_builder *ir = self->owner;
3360 prog_section_statement_t stmt;
3362 numparams = vec_size(self->params);
3366 stmt.opcode = INSTR_STORE_F;
3368 for (i = 8; i < numparams; ++i) {
3370 if (ext >= vec_size(ir->extparams))
3371 ir_gen_extparam(ir);
3373 ep = ir->extparams[ext];
3375 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3376 if (self->locals[i]->vtype == TYPE_FIELD &&
3377 self->locals[i]->fieldtype == TYPE_VECTOR)
3379 stmt.opcode = INSTR_STORE_V;
3381 stmt.o1.u1 = ir_value_code_addr(ep);
3382 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3383 code_push_statement(code, &stmt, self->context);
3389 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3391 size_t i, ext, numparams, maxparams;
3393 ir_builder *ir = self->owner;
3395 prog_section_statement_t stmt;
3397 numparams = vec_size(self->params);
3401 stmt.opcode = INSTR_STORE_V;
3403 maxparams = numparams + self->max_varargs;
3404 for (i = numparams; i < maxparams; ++i) {
3406 stmt.o1.u1 = OFS_PARM0 + 3*i;
3407 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3408 code_push_statement(code, &stmt, self->context);
3412 while (ext >= vec_size(ir->extparams))
3413 ir_gen_extparam(ir);
3415 ep = ir->extparams[ext];
3417 stmt.o1.u1 = ir_value_code_addr(ep);
3418 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3419 code_push_statement(code, &stmt, self->context);
3425 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3427 prog_section_function_t *def;
3430 uint32_t firstlocal, firstglobal;
3432 irfun = global->constval.vfunc;
3433 def = &ir->code->functions[0] + irfun->code_function_def;
3435 if (OPTS_OPTION_BOOL(OPTION_G) ||
3436 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3437 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3439 firstlocal = def->firstlocal = ir->code->globals.size();
3441 firstlocal = def->firstlocal = ir->first_common_local;
3442 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3445 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3447 for (i = ir->code->globals.size(); i < firstlocal + irfun->allocated_locals; ++i)
3448 ir->code->globals.push_back(0);
3449 for (i = 0; i < vec_size(irfun->locals); ++i) {
3450 ir_value *v = irfun->locals[i];
3451 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3452 ir_value_code_setaddr(v, firstlocal + v->code.local);
3453 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3454 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3459 ir_value_code_setaddr(v, firstglobal + v->code.local);
3461 for (i = 0; i < vec_size(irfun->values); ++i)
3463 ir_value *v = irfun->values[i];
3467 ir_value_code_setaddr(v, firstlocal + v->code.local);
3469 ir_value_code_setaddr(v, firstglobal + v->code.local);
3474 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3476 prog_section_function_t *fundef;
3481 irfun = global->constval.vfunc;
3483 if (global->cvq == CV_NONE) {
3484 if (irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3485 "function `%s` has no body and in QC implicitly becomes a function-pointer",
3488 /* Not bailing out just now. If this happens a lot you don't want to have
3489 * to rerun gmqcc for each such function.
3495 /* this was a function pointer, don't generate code for those */
3503 * If there is no definition and the thing is eraseable, we can ignore
3504 * outputting the function to begin with.
3506 if (global->flags & IR_FLAG_ERASABLE && irfun->code_function_def < 0) {
3510 if (irfun->code_function_def < 0) {
3511 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3514 fundef = &ir->code->functions[irfun->code_function_def];
3516 fundef->entry = ir->code->statements.size();
3517 if (!gen_function_locals(ir, global)) {
3518 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3521 if (!gen_function_extparam_copy(ir->code, irfun)) {
3522 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3525 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3526 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3529 if (!gen_function_code(ir->code, irfun)) {
3530 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3536 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3541 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3544 def.type = TYPE_FLOAT;
3548 component = (char*)mem_a(len+3);
3549 memcpy(component, name, len);
3551 component[len-0] = 0;
3552 component[len-2] = '_';
3554 component[len-1] = 'x';
3556 for (i = 0; i < 3; ++i) {
3557 def.name = code_genstring(code, component);
3558 code->defs.push_back(def);
3566 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3571 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3574 fld.type = TYPE_FLOAT;
3578 component = (char*)mem_a(len+3);
3579 memcpy(component, name, len);
3581 component[len-0] = 0;
3582 component[len-2] = '_';
3584 component[len-1] = 'x';
3586 for (i = 0; i < 3; ++i) {
3587 fld.name = code_genstring(code, component);
3588 code->fields.push_back(fld);
3596 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3600 prog_section_def_t def;
3601 bool pushdef = opts.optimizeoff;
3603 /* we don't generate split-vectors */
3604 if (global->vtype == TYPE_VECTOR && (global->flags & IR_FLAG_SPLIT_VECTOR))
3607 def.type = global->vtype;
3608 def.offset = self->code->globals.size();
3610 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3615 * if we're eraseable and the function isn't referenced ignore outputting
3618 if (global->flags & IR_FLAG_ERASABLE && global->reads.empty()) {
3622 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3623 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3624 (global->name[0] == '#' || global->cvq == CV_CONST))
3630 if (global->name[0] == '#') {
3631 if (!self->str_immediate)
3632 self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3633 def.name = global->code.name = self->str_immediate;
3636 def.name = global->code.name = code_genstring(self->code, global->name);
3641 def.offset = ir_value_code_addr(global);
3642 self->code->defs.push_back(def);
3643 if (global->vtype == TYPE_VECTOR)
3644 gen_vector_defs(self->code, def, global->name);
3645 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3646 gen_vector_defs(self->code, def, global->name);
3653 switch (global->vtype)
3656 if (!strcmp(global->name, "end_sys_globals")) {
3657 /* TODO: remember this point... all the defs before this one
3658 * should be checksummed and added to progdefs.h when we generate it.
3661 else if (!strcmp(global->name, "end_sys_fields")) {
3662 /* TODO: same as above but for entity-fields rather than globsl
3665 else if(irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3668 /* Not bailing out */
3671 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3672 * the system fields actually go? Though the engine knows this anyway...
3673 * Maybe this could be an -foption
3674 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3676 ir_value_code_setaddr(global, self->code->globals.size());
3677 self->code->globals.push_back(0);
3679 if (pushdef) self->code->defs.push_back(def);
3682 if (pushdef) self->code->defs.push_back(def);
3683 return gen_global_pointer(self->code, global);
3686 self->code->defs.push_back(def);
3687 if (global->fieldtype == TYPE_VECTOR)
3688 gen_vector_defs(self->code, def, global->name);
3690 return gen_global_field(self->code, global);
3695 ir_value_code_setaddr(global, self->code->globals.size());
3696 if (global->hasvalue) {
3697 iptr = (int32_t*)&global->constval.ivec[0];
3698 self->code->globals.push_back(*iptr);
3700 self->code->globals.push_back(0);
3702 if (!islocal && global->cvq != CV_CONST)
3703 def.type |= DEF_SAVEGLOBAL;
3704 if (pushdef) self->code->defs.push_back(def);
3706 return global->code.globaladdr >= 0;
3710 ir_value_code_setaddr(global, self->code->globals.size());
3711 if (global->hasvalue) {
3712 uint32_t load = code_genstring(self->code, global->constval.vstring);
3713 self->code->globals.push_back(load);
3715 self->code->globals.push_back(0);
3717 if (!islocal && global->cvq != CV_CONST)
3718 def.type |= DEF_SAVEGLOBAL;
3719 if (pushdef) self->code->defs.push_back(def);
3720 return global->code.globaladdr >= 0;
3725 ir_value_code_setaddr(global, self->code->globals.size());
3726 if (global->hasvalue) {
3727 iptr = (int32_t*)&global->constval.ivec[0];
3728 self->code->globals.push_back(iptr[0]);
3729 if (global->code.globaladdr < 0)
3731 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3732 self->code->globals.push_back(iptr[d]);
3735 self->code->globals.push_back(0);
3736 if (global->code.globaladdr < 0)
3738 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3739 self->code->globals.push_back(0);
3742 if (!islocal && global->cvq != CV_CONST)
3743 def.type |= DEF_SAVEGLOBAL;
3746 self->code->defs.push_back(def);
3747 def.type &= ~DEF_SAVEGLOBAL;
3748 gen_vector_defs(self->code, def, global->name);
3750 return global->code.globaladdr >= 0;
3753 ir_value_code_setaddr(global, self->code->globals.size());
3754 if (!global->hasvalue) {
3755 self->code->globals.push_back(0);
3756 if (global->code.globaladdr < 0)
3759 self->code->globals.push_back(self->code->functions.size());
3760 if (!gen_global_function(self, global))
3763 if (!islocal && global->cvq != CV_CONST)
3764 def.type |= DEF_SAVEGLOBAL;
3765 if (pushdef) self->code->defs.push_back(def);
3768 /* assume biggest type */
3769 ir_value_code_setaddr(global, self->code->globals.size());
3770 self->code->globals.push_back(0);
3771 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3772 self->code->globals.push_back(0);
3775 /* refuse to create 'void' type or any other fancy business. */
3776 irerror(global->context, "Invalid type for global variable `%s`: %s",
3777 global->name, type_name[global->vtype]);
3782 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3784 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3787 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3789 prog_section_def_t def;
3790 prog_section_field_t fld;
3794 def.type = (uint16_t)field->vtype;
3795 def.offset = (uint16_t)self->code->globals.size();
3797 /* create a global named the same as the field */
3798 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3799 /* in our standard, the global gets a dot prefix */
3800 size_t len = strlen(field->name);
3803 /* we really don't want to have to allocate this, and 1024
3804 * bytes is more than enough for a variable/field name
3806 if (len+2 >= sizeof(name)) {
3807 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3812 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3815 def.name = code_genstring(self->code, name);
3816 fld.name = def.name + 1; /* we reuse that string table entry */
3818 /* in plain QC, there cannot be a global with the same name,
3819 * and so we also name the global the same.
3820 * FIXME: fteqcc should create a global as well
3821 * check if it actually uses the same name. Probably does
3823 def.name = code_genstring(self->code, field->name);
3824 fld.name = def.name;
3827 field->code.name = def.name;
3829 self->code->defs.push_back(def);
3831 fld.type = field->fieldtype;
3833 if (fld.type == TYPE_VOID) {
3834 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3838 fld.offset = field->code.fieldaddr;
3840 self->code->fields.push_back(fld);
3842 ir_value_code_setaddr(field, self->code->globals.size());
3843 self->code->globals.push_back(fld.offset);
3844 if (fld.type == TYPE_VECTOR) {
3845 self->code->globals.push_back(fld.offset+1);
3846 self->code->globals.push_back(fld.offset+2);
3849 if (field->fieldtype == TYPE_VECTOR) {
3850 gen_vector_defs (self->code, def, field->name);
3851 gen_vector_fields(self->code, fld, field->name);
3854 return field->code.globaladdr >= 0;
3857 static void ir_builder_collect_reusables(ir_builder *builder) {
3859 ir_value **reusables = nullptr;
3860 for (i = 0; i < vec_size(builder->globals); ++i) {
3861 ir_value *value = builder->globals[i];
3862 if (value->vtype != TYPE_FLOAT || !value->hasvalue)
3864 if (value->cvq == CV_CONST || (value->name && value->name[0] == '#')) {
3865 vec_push(reusables, value);
3868 builder->const_floats = reusables;
3871 static void ir_builder_split_vector(ir_builder *self, ir_value *vec) {
3873 ir_value* found[3] = { nullptr, nullptr, nullptr };
3875 /* must not be written to */
3876 if (vec->writes.size())
3878 /* must not be trying to access individual members */
3879 if (vec->members[0] || vec->members[1] || vec->members[2])
3881 /* should be actually used otherwise it won't be generated anyway */
3882 count = vec->reads.size();
3886 /* may only be used directly as function parameters, so if we find some other instruction cancel */
3887 for (i = 0; i != count; ++i) {
3888 /* we only split vectors if they're used directly as parameter to a call only! */
3889 ir_instr *user = vec->reads[i];
3890 if ((user->opcode < INSTR_CALL0 || user->opcode > INSTR_CALL8) && user->opcode != VINSTR_NRCALL)
3894 vec->flags |= IR_FLAG_SPLIT_VECTOR;
3896 /* find existing floats making up the split */
3897 count = vec_size(self->const_floats);
3898 for (i = 0; i != count; ++i) {
3899 ir_value *c = self->const_floats[i];
3900 if (!found[0] && c->constval.vfloat == vec->constval.vvec.x)
3902 if (!found[1] && c->constval.vfloat == vec->constval.vvec.y)
3904 if (!found[2] && c->constval.vfloat == vec->constval.vvec.z)
3906 if (found[0] && found[1] && found[2])
3910 /* generate floats for not yet found components */
3912 found[0] = ir_builder_imm_float(self, vec->constval.vvec.x, true);
3914 if (vec->constval.vvec.y == vec->constval.vvec.x)
3915 found[1] = found[0];
3917 found[1] = ir_builder_imm_float(self, vec->constval.vvec.y, true);
3920 if (vec->constval.vvec.z == vec->constval.vvec.x)
3921 found[2] = found[0];
3922 else if (vec->constval.vvec.z == vec->constval.vvec.y)
3923 found[2] = found[1];
3925 found[2] = ir_builder_imm_float(self, vec->constval.vvec.z, true);
3928 /* the .members array should be safe to use here. */
3929 vec->members[0] = found[0];
3930 vec->members[1] = found[1];
3931 vec->members[2] = found[2];
3933 /* register the readers for these floats */
3934 count = vec->reads.size();
3935 for (i = 0; i != count; ++i) {
3936 found[0]->reads.push_back(vec->reads[i]);
3937 found[1]->reads.push_back(vec->reads[i]);
3938 found[2]->reads.push_back(vec->reads[i]);
3942 static void ir_builder_split_vectors(ir_builder *self) {
3943 size_t i, count = vec_size(self->globals);
3944 for (i = 0; i != count; ++i) {
3945 ir_value *v = self->globals[i];
3946 if (v->vtype != TYPE_VECTOR || !v->name || v->name[0] != '#')
3948 ir_builder_split_vector(self, self->globals[i]);
3952 bool ir_builder_generate(ir_builder *self, const char *filename)
3954 prog_section_statement_t stmt;
3956 char *lnofile = nullptr;
3958 if (OPTS_FLAG(SPLIT_VECTOR_PARAMETERS)) {
3959 ir_builder_collect_reusables(self);
3960 if (vec_size(self->const_floats) > 0)
3961 ir_builder_split_vectors(self);
3964 for (i = 0; i < vec_size(self->fields); ++i)
3966 ir_builder_prepare_field(self->code, self->fields[i]);
3969 for (i = 0; i < vec_size(self->globals); ++i)
3971 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3974 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3975 ir_function *func = self->globals[i]->constval.vfunc;
3976 if (func && self->max_locals < func->allocated_locals &&
3977 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3979 self->max_locals = func->allocated_locals;
3981 if (func && self->max_globaltemps < func->globaltemps)
3982 self->max_globaltemps = func->globaltemps;
3986 for (i = 0; i < vec_size(self->fields); ++i)
3988 if (!ir_builder_gen_field(self, self->fields[i])) {
3994 ir_value_code_setaddr(self->nil, self->code->globals.size());
3995 self->code->globals.push_back(0);
3996 self->code->globals.push_back(0);
3997 self->code->globals.push_back(0);
3999 /* generate virtual-instruction temps */
4000 for (i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
4001 ir_value_code_setaddr(self->vinstr_temp[i], self->code->globals.size());
4002 self->code->globals.push_back(0);
4003 self->code->globals.push_back(0);
4004 self->code->globals.push_back(0);
4007 /* generate global temps */
4008 self->first_common_globaltemp = self->code->globals.size();
4009 for (i = 0; i < self->max_globaltemps; ++i) {
4010 self->code->globals.push_back(0);
4012 /* generate common locals */
4013 self->first_common_local = self->code->globals.size();
4014 for (i = 0; i < self->max_locals; ++i) {
4015 self->code->globals.push_back(0);
4018 /* generate function code */
4019 for (i = 0; i < vec_size(self->globals); ++i)
4021 if (self->globals[i]->vtype == TYPE_FUNCTION) {
4022 if (!gen_global_function_code(self, self->globals[i])) {
4028 if (self->code->globals.size() >= 65536) {
4029 irerror(vec_last(self->globals)->context,
4030 "This progs file would require more globals than the metadata can handle (%zu). Bailing out.",
4031 self->code->globals.size());
4035 /* DP errors if the last instruction is not an INSTR_DONE. */
4036 if (self->code->statements.back().opcode != INSTR_DONE)
4040 stmt.opcode = INSTR_DONE;
4044 last.line = self->code->linenums.back();
4045 last.column = self->code->columnnums.back();
4047 code_push_statement(self->code, &stmt, last);
4050 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
4053 if (self->code->statements.size() != self->code->linenums.size()) {
4054 con_err("Linecounter wrong: %lu != %lu\n",
4055 self->code->statements.size(),
4056 self->code->linenums.size());
4057 } else if (OPTS_FLAG(LNO)) {
4059 size_t filelen = strlen(filename);
4061 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
4062 dot = strrchr(lnofile, '.');
4066 vec_shrinkto(lnofile, dot - lnofile);
4068 memcpy(vec_add(lnofile, 5), ".lno", 5);
4071 if (!code_write(self->code, filename, lnofile)) {
4080 /***********************************************************************
4081 *IR DEBUG Dump functions...
4084 #define IND_BUFSZ 1024
4086 static const char *qc_opname(int op)
4088 if (op < 0) return "<INVALID>";
4089 if (op < VINSTR_END)
4090 return util_instr_str[op];
4092 case VINSTR_END: return "END";
4093 case VINSTR_PHI: return "PHI";
4094 case VINSTR_JUMP: return "JUMP";
4095 case VINSTR_COND: return "COND";
4096 case VINSTR_BITXOR: return "BITXOR";
4097 case VINSTR_BITAND_V: return "BITAND_V";
4098 case VINSTR_BITOR_V: return "BITOR_V";
4099 case VINSTR_BITXOR_V: return "BITXOR_V";
4100 case VINSTR_BITAND_VF: return "BITAND_VF";
4101 case VINSTR_BITOR_VF: return "BITOR_VF";
4102 case VINSTR_BITXOR_VF: return "BITXOR_VF";
4103 case VINSTR_CROSS: return "CROSS";
4104 case VINSTR_NEG_F: return "NEG_F";
4105 case VINSTR_NEG_V: return "NEG_V";
4106 default: return "<UNK>";
4110 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
4113 char indent[IND_BUFSZ];
4117 oprintf("module %s\n", b->name);
4118 for (i = 0; i < vec_size(b->globals); ++i)
4121 if (b->globals[i]->hasvalue)
4122 oprintf("%s = ", b->globals[i]->name);
4123 ir_value_dump(b->globals[i], oprintf);
4126 for (i = 0; i < vec_size(b->functions); ++i)
4127 ir_function_dump(b->functions[i], indent, oprintf);
4128 oprintf("endmodule %s\n", b->name);
4131 static const char *storenames[] = {
4132 "[global]", "[local]", "[param]", "[value]", "[return]"
4135 void ir_function_dump(ir_function *f, char *ind,
4136 int (*oprintf)(const char*, ...))
4139 if (f->builtin != 0) {
4140 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
4143 oprintf("%sfunction %s\n", ind, f->name);
4144 util_strncat(ind, "\t", IND_BUFSZ-1);
4145 if (vec_size(f->locals))
4147 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
4148 for (i = 0; i < vec_size(f->locals); ++i) {
4149 oprintf("%s\t", ind);
4150 ir_value_dump(f->locals[i], oprintf);
4154 oprintf("%sliferanges:\n", ind);
4155 for (i = 0; i < vec_size(f->locals); ++i) {
4156 const char *attr = "";
4158 ir_value *v = f->locals[i];
4159 if (v->unique_life && v->locked)
4160 attr = "unique,locked ";
4161 else if (v->unique_life)
4165 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
4166 storenames[v->store],
4167 attr, (v->callparam ? "callparam " : ""),
4168 (int)v->code.local);
4171 for (l = 0; l < vec_size(v->life); ++l) {
4172 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
4175 for (m = 0; m < 3; ++m) {
4176 ir_value *vm = v->members[m];
4179 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
4180 for (l = 0; l < vec_size(vm->life); ++l) {
4181 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4186 for (i = 0; i < vec_size(f->values); ++i) {
4187 const char *attr = "";
4189 ir_value *v = f->values[i];
4190 if (v->unique_life && v->locked)
4191 attr = "unique,locked ";
4192 else if (v->unique_life)
4196 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
4197 storenames[v->store],
4198 attr, (v->callparam ? "callparam " : ""),
4199 (int)v->code.local);
4202 for (l = 0; l < vec_size(v->life); ++l) {
4203 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
4206 for (m = 0; m < 3; ++m) {
4207 ir_value *vm = v->members[m];
4210 if (vm->unique_life && vm->locked)
4211 attr = "unique,locked ";
4212 else if (vm->unique_life)
4214 else if (vm->locked)
4216 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
4217 for (l = 0; l < vec_size(vm->life); ++l) {
4218 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4223 if (vec_size(f->blocks))
4225 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
4226 for (i = 0; i < vec_size(f->blocks); ++i) {
4227 ir_block_dump(f->blocks[i], ind, oprintf);
4231 ind[strlen(ind)-1] = 0;
4232 oprintf("%sendfunction %s\n", ind, f->name);
4235 void ir_block_dump(ir_block* b, char *ind,
4236 int (*oprintf)(const char*, ...))
4239 oprintf("%s:%s\n", ind, b->label);
4240 util_strncat(ind, "\t", IND_BUFSZ-1);
4242 if (b->instr && b->instr[0])
4243 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
4244 for (i = 0; i < vec_size(b->instr); ++i)
4245 ir_instr_dump(b->instr[i], ind, oprintf);
4246 ind[strlen(ind)-1] = 0;
4249 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
4251 oprintf("%s <- phi ", in->_ops[0]->name);
4252 for (auto &it : in->phi) {
4253 oprintf("([%s] : %s) ", it.from->label,
4259 void ir_instr_dump(ir_instr *in, char *ind,
4260 int (*oprintf)(const char*, ...))
4263 const char *comma = nullptr;
4265 oprintf("%s (%i) ", ind, (int)in->eid);
4267 if (in->opcode == VINSTR_PHI) {
4268 dump_phi(in, oprintf);
4272 util_strncat(ind, "\t", IND_BUFSZ-1);
4274 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
4275 ir_value_dump(in->_ops[0], oprintf);
4276 if (in->_ops[1] || in->_ops[2])
4279 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
4280 oprintf("CALL%i\t", in->params.size());
4282 oprintf("%s\t", qc_opname(in->opcode));
4284 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
4285 ir_value_dump(in->_ops[0], oprintf);
4290 for (i = 1; i != 3; ++i) {
4294 ir_value_dump(in->_ops[i], oprintf);
4302 oprintf("[%s]", in->bops[0]->label);
4306 oprintf("%s[%s]", comma, in->bops[1]->label);
4307 if (in->params.size()) {
4308 oprintf("\tparams: ");
4309 for (auto &it : in->params)
4310 oprintf("%s, ", it->name);
4313 ind[strlen(ind)-1] = 0;
4316 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
4319 for (; *str; ++str) {
4321 case '\n': oprintf("\\n"); break;
4322 case '\r': oprintf("\\r"); break;
4323 case '\t': oprintf("\\t"); break;
4324 case '\v': oprintf("\\v"); break;
4325 case '\f': oprintf("\\f"); break;
4326 case '\b': oprintf("\\b"); break;
4327 case '\a': oprintf("\\a"); break;
4328 case '\\': oprintf("\\\\"); break;
4329 case '"': oprintf("\\\""); break;
4330 default: oprintf("%c", *str); break;
4336 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4345 oprintf("fn:%s", v->name);
4348 oprintf("%g", v->constval.vfloat);
4351 oprintf("'%g %g %g'",
4354 v->constval.vvec.z);
4357 oprintf("(entity)");
4360 ir_value_dump_string(v->constval.vstring, oprintf);
4364 oprintf("%i", v->constval.vint);
4369 v->constval.vpointer->name);
4373 oprintf("%s", v->name);
4377 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4380 oprintf("Life of %12s:", self->name);
4381 for (i = 0; i < vec_size(self->life); ++i)
4383 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);