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 void ir_value_dump(ir_value*, int (*oprintf)(const char*,...));
195 static ir_value* ir_gen_extparam_proto(ir_builder *ir);
196 static void ir_gen_extparam (ir_builder *ir);
198 static void ir_function_dump(ir_function*, char *ind, int (*oprintf)(const char*,...));
200 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t, const char *label,
201 int op, ir_value *a, ir_value *b, qc_type outype);
202 static bool GMQCC_WARN ir_block_create_store(ir_block*, lex_ctx_t, ir_value *target, ir_value *what);
203 static void ir_block_dump(ir_block*, char *ind, int (*oprintf)(const char*,...));
205 static bool ir_instr_op(ir_instr*, int op, ir_value *value, bool writing);
206 static void ir_instr_dump(ir_instr* in, char *ind, int (*oprintf)(const char*,...));
207 /* error functions */
209 static void irerror(lex_ctx_t ctx, const char *msg, ...)
213 con_cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
217 static bool GMQCC_WARN irwarning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
222 r = vcompile_warning(ctx, warntype, fmt, ap);
227 /***********************************************************************
228 * Vector utility functions
231 static bool GMQCC_WARN vec_ir_value_find(std::vector<ir_value *> &vec, const ir_value *what, size_t *idx)
233 for (auto &it : vec) {
237 *idx = &it - &vec[0];
243 static bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
246 size_t len = vec_size(vec);
247 for (i = 0; i < len; ++i) {
248 if (vec[i] == what) {
256 static bool GMQCC_WARN vec_ir_instr_find(std::vector<ir_instr *> &vec, ir_instr *what, size_t *idx)
258 for (auto &it : vec) {
262 *idx = &it - &vec[0];
268 /***********************************************************************
272 static void ir_block_delete_quick(ir_block* self);
273 static void ir_instr_delete_quick(ir_instr *self);
274 static void ir_function_delete_quick(ir_function *self);
276 void* ir_builder::operator new(std::size_t bytes)
281 void ir_builder::operator delete(void *ptr)
286 ir_builder::ir_builder(const std::string& modulename)
290 htglobals = util_htnew(IR_HT_SIZE);
291 htfields = util_htnew(IR_HT_SIZE);
292 htfunctions = util_htnew(IR_HT_SIZE);
294 nil = new ir_value("nil", store_value, TYPE_NIL);
297 for (size_t i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
298 /* we write to them, but they're not supposed to be used outside the IR, so
299 * let's not allow the generation of ir_instrs which use these.
300 * So it's a constant noexpr.
302 vinstr_temp[i] = new ir_value("vinstr_temp", store_value, TYPE_NOEXPR);
303 vinstr_temp[i]->cvq = CV_CONST;
307 ir_builder::~ir_builder()
309 util_htdel(htglobals);
310 util_htdel(htfields);
311 util_htdel(htfunctions);
312 for (auto& f : functions)
313 ir_function_delete_quick(f.release());
314 functions.clear(); // delete them now before deleting the rest:
318 for (size_t i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
319 delete vinstr_temp[i];
323 extparam_protos.clear();
326 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
328 return (ir_function*)util_htget(self->htfunctions, name);
331 ir_function* ir_builder_create_function(ir_builder *self, const std::string& name, qc_type outtype)
333 ir_function *fn = ir_builder_get_function(self, name.c_str());
338 fn = new ir_function(self, outtype);
340 self->functions.emplace_back(fn);
341 util_htset(self->htfunctions, name.c_str(), fn);
343 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
349 fn->value->hasvalue = true;
350 fn->value->outtype = outtype;
351 fn->value->constval.vfunc = fn;
352 fn->value->context = fn->context;
357 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
359 return (ir_value*)util_htget(self->htglobals, name);
362 ir_value* ir_builder_create_global(ir_builder *self, const std::string& name, qc_type vtype)
368 ve = ir_builder_get_global(self, name.c_str());
374 ve = new ir_value(std::string(name), store_global, vtype);
375 self->globals.emplace_back(ve);
376 util_htset(self->htglobals, name.c_str(), ve);
380 ir_value* ir_builder_get_va_count(ir_builder *self)
382 if (self->reserved_va_count)
383 return self->reserved_va_count;
384 return (self->reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
387 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
389 return (ir_value*)util_htget(self->htfields, name);
393 ir_value* ir_builder_create_field(ir_builder *self, const std::string& name, qc_type vtype)
395 ir_value *ve = ir_builder_get_field(self, name.c_str());
400 ve = new ir_value(std::string(name), store_global, TYPE_FIELD);
401 ve->fieldtype = vtype;
402 self->fields.emplace_back(ve);
403 util_htset(self->htfields, name.c_str(), ve);
407 /***********************************************************************
411 static bool ir_function_naive_phi(ir_function*);
412 static void ir_function_enumerate(ir_function*);
413 static bool ir_function_calculate_liferanges(ir_function*);
414 static bool ir_function_allocate_locals(ir_function*);
416 void* ir_function::operator new(std::size_t bytes)
421 void ir_function::operator delete(void *ptr)
426 ir_function::ir_function(ir_builder* owner_, qc_type outtype_)
432 context.file = "<@no context>";
437 ir_function::~ir_function()
441 static void ir_function_delete_quick(ir_function *self)
443 for (auto& b : self->blocks)
444 ir_block_delete_quick(b.release());
448 static void ir_function_collect_value(ir_function *self, ir_value *v)
450 self->values.emplace_back(v);
453 ir_block* ir_function_create_block(lex_ctx_t ctx, ir_function *self, const char *label)
455 ir_block* bn = new ir_block(self, label ? std::string(label) : std::string());
457 self->blocks.emplace_back(bn);
459 if ((self->flags & IR_FLAG_BLOCK_COVERAGE) && self->owner->coverage_func)
460 (void)ir_block_create_call(bn, ctx, nullptr, self->owner->coverage_func, false);
465 static bool instr_is_operation(uint16_t op)
467 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
468 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
469 (op == INSTR_ADDRESS) ||
470 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
471 (op >= INSTR_AND && op <= INSTR_BITOR) ||
472 (op >= INSTR_CALL0 && op <= INSTR_CALL8) ||
473 (op >= VINSTR_BITAND_V && op <= VINSTR_NEG_V) );
476 static bool ir_function_pass_peephole(ir_function *self)
478 for (auto& bp : self->blocks) {
479 ir_block *block = bp.get();
480 for (size_t i = 0; i < vec_size(block->instr); ++i) {
482 inst = block->instr[i];
485 (inst->opcode >= INSTR_STORE_F &&
486 inst->opcode <= INSTR_STORE_FNC))
494 oper = block->instr[i-1];
495 if (!instr_is_operation(oper->opcode))
498 /* Don't change semantics of MUL_VF in engines where these may not alias. */
499 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
500 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
502 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
506 value = oper->_ops[0];
508 /* only do it for SSA values */
509 if (value->store != store_value)
512 /* don't optimize out the temp if it's used later again */
513 if (value->reads.size() != 1)
516 /* The very next store must use this value */
517 if (value->reads[0] != store)
520 /* And of course the store must _read_ from it, so it's in
522 if (store->_ops[1] != value)
525 ++opts_optimizationcount[OPTIM_PEEPHOLE];
526 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
528 vec_remove(block->instr, i, 1);
531 else if (inst->opcode == VINSTR_COND)
533 /* COND on a value resulting from a NOT could
534 * remove the NOT and swap its operands
541 value = inst->_ops[0];
543 if (value->store != store_value || value->reads.size() != 1 || value->reads[0] != inst)
546 inot = value->writes[0];
547 if (inot->_ops[0] != value ||
548 inot->opcode < INSTR_NOT_F ||
549 inot->opcode > INSTR_NOT_FNC ||
550 inot->opcode == INSTR_NOT_V || /* can't do these */
551 inot->opcode == INSTR_NOT_S)
557 ++opts_optimizationcount[OPTIM_PEEPHOLE];
559 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
562 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
563 if (tmp->instr[inotid] == inot)
566 if (inotid >= vec_size(tmp->instr)) {
567 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
570 vec_remove(tmp->instr, inotid, 1);
572 /* swap ontrue/onfalse */
574 inst->bops[0] = inst->bops[1];
585 static bool ir_function_pass_tailrecursion(ir_function *self)
589 for (auto& bp : self->blocks) {
590 ir_block *block = bp.get();
593 ir_instr *ret, *call, *store = nullptr;
595 if (!block->final || vec_size(block->instr) < 2)
598 ret = block->instr[vec_size(block->instr)-1];
599 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
602 call = block->instr[vec_size(block->instr)-2];
603 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
604 /* account for the unoptimized
606 * STORE %return, %tmp
610 if (vec_size(block->instr) < 3)
614 call = block->instr[vec_size(block->instr)-3];
617 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
621 /* optimize out the STORE */
623 ret->_ops[0] == store->_ops[0] &&
624 store->_ops[1] == call->_ops[0])
626 ++opts_optimizationcount[OPTIM_PEEPHOLE];
627 call->_ops[0] = store->_ops[0];
628 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
638 funcval = call->_ops[1];
641 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
644 /* now we have a CALL and a RET, check if it's a tailcall */
645 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
648 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
649 vec_shrinkby(block->instr, 2);
651 block->final = false; /* open it back up */
653 /* emite parameter-stores */
654 for (p = 0; p < call->params.size(); ++p) {
655 /* assert(call->params_count <= self->locals_count); */
656 if (!ir_block_create_store(block, call->context, self->locals[p].get(), call->params[p])) {
657 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
661 if (!ir_block_create_jump(block, call->context, self->blocks[0].get())) {
662 irerror(call->context, "failed to create tailcall jump");
673 bool ir_function_finalize(ir_function *self)
678 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
679 if (!ir_function_pass_peephole(self)) {
680 irerror(self->context, "generic optimization pass broke something in `%s`", self->name.c_str());
685 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
686 if (!ir_function_pass_tailrecursion(self)) {
687 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name.c_str());
692 if (!ir_function_naive_phi(self)) {
693 irerror(self->context, "internal error: ir_function_naive_phi failed");
697 for (auto& lp : self->locals) {
698 ir_value *v = lp.get();
699 if (v->vtype == TYPE_VECTOR ||
700 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
702 ir_value_vector_member(v, 0);
703 ir_value_vector_member(v, 1);
704 ir_value_vector_member(v, 2);
707 for (auto& vp : self->values) {
708 ir_value *v = vp.get();
709 if (v->vtype == TYPE_VECTOR ||
710 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
712 ir_value_vector_member(v, 0);
713 ir_value_vector_member(v, 1);
714 ir_value_vector_member(v, 2);
718 ir_function_enumerate(self);
720 if (!ir_function_calculate_liferanges(self))
722 if (!ir_function_allocate_locals(self))
727 ir_value* ir_function_create_local(ir_function *self, const std::string& name, qc_type vtype, bool param)
732 !self->locals.empty() &&
733 self->locals.back()->store != store_param)
735 irerror(self->context, "cannot add parameters after adding locals");
739 ve = new ir_value(std::string(name), (param ? store_param : store_local), vtype);
742 self->locals.emplace_back(ve);
746 /***********************************************************************
750 void* ir_block::operator new(std::size_t bytes) {
754 void ir_block::operator delete(void *data) {
758 ir_block::ir_block(ir_function* owner, const std::string& name)
762 context.file = "<@no context>";
766 ir_block::~ir_block()
768 for (size_t i = 0; i != vec_size(instr); ++i)
775 static void ir_block_delete_quick(ir_block* self)
778 for (i = 0; i != vec_size(self->instr); ++i)
779 ir_instr_delete_quick(self->instr[i]);
780 vec_free(self->instr);
784 /***********************************************************************
788 void* ir_instr::operator new(std::size_t bytes) {
792 void ir_instr::operator delete(void *data) {
796 ir_instr::ir_instr(lex_ctx_t ctx, ir_block* owner_, int op)
803 ir_instr::~ir_instr()
805 // The following calls can only delete from
806 // vectors, we still want to delete this instruction
807 // so ignore the return value. Since with the warn_unused_result attribute
808 // gcc doesn't care about an explicit: (void)foo(); to ignore the result,
809 // I have to improvise here and use if(foo());
810 for (auto &it : phi) {
812 if (vec_ir_instr_find(it.value->writes, this, &idx))
813 it.value->writes.erase(it.value->writes.begin() + idx);
814 if (vec_ir_instr_find(it.value->reads, this, &idx))
815 it.value->reads.erase(it.value->reads.begin() + idx);
817 for (auto &it : params) {
819 if (vec_ir_instr_find(it->writes, this, &idx))
820 it->writes.erase(it->writes.begin() + idx);
821 if (vec_ir_instr_find(it->reads, this, &idx))
822 it->reads.erase(it->reads.begin() + idx);
824 (void)!ir_instr_op(this, 0, nullptr, false);
825 (void)!ir_instr_op(this, 1, nullptr, false);
826 (void)!ir_instr_op(this, 2, nullptr, false);
829 static void ir_instr_delete_quick(ir_instr *self)
832 self->params.clear();
836 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
838 if (v && v->vtype == TYPE_NOEXPR) {
839 irerror(self->context, "tried to use a NOEXPR value");
843 if (self->_ops[op]) {
845 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
846 self->_ops[op]->writes.erase(self->_ops[op]->writes.begin() + idx);
847 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
848 self->_ops[op]->reads.erase(self->_ops[op]->reads.begin() + idx);
852 v->writes.push_back(self);
854 v->reads.push_back(self);
860 /***********************************************************************
864 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
866 self->code.globaladdr = gaddr;
867 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
868 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
869 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
872 static int32_t ir_value_code_addr(const ir_value *self)
874 if (self->store == store_return)
875 return OFS_RETURN + self->code.addroffset;
876 return self->code.globaladdr + self->code.addroffset;
879 void* ir_value::operator new(std::size_t bytes) {
883 void ir_value::operator delete(void *data) {
887 ir_value::ir_value(std::string&& name_, store_type store_, qc_type vtype_)
892 fieldtype = TYPE_VOID;
898 context.file = "<@no context>";
901 memset(&constval, 0, sizeof(constval));
902 memset(&code, 0, sizeof(code));
904 members[0] = nullptr;
905 members[1] = nullptr;
906 members[2] = nullptr;
914 ir_value::~ir_value()
918 if (vtype == TYPE_STRING)
919 mem_d((void*)constval.vstring);
921 if (!(flags & IR_FLAG_SPLIT_VECTOR)) {
922 for (i = 0; i < 3; ++i) {
930 /* helper function */
931 static ir_value* ir_builder_imm_float(ir_builder *self, float value, bool add_to_list) {
932 ir_value *v = new ir_value("#IMMEDIATE", store_global, TYPE_FLOAT);
933 v->flags |= IR_FLAG_ERASABLE;
936 v->constval.vfloat = value;
938 self->globals.emplace_back(v);
940 self->const_floats.emplace_back(v);
944 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
951 if (self->members[member])
952 return self->members[member];
954 if (!self->name.empty()) {
955 char member_name[3] = { '_', char('x' + member), 0 };
956 name = self->name + member_name;
959 if (self->vtype == TYPE_VECTOR)
961 m = new ir_value(move(name), self->store, TYPE_FLOAT);
964 m->context = self->context;
966 self->members[member] = m;
967 m->code.addroffset = member;
969 else if (self->vtype == TYPE_FIELD)
971 if (self->fieldtype != TYPE_VECTOR)
973 m = new ir_value(move(name), self->store, TYPE_FIELD);
976 m->fieldtype = TYPE_FLOAT;
977 m->context = self->context;
979 self->members[member] = m;
980 m->code.addroffset = member;
984 irerror(self->context, "invalid member access on %s", self->name.c_str());
992 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
994 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
995 return type_sizeof_[TYPE_VECTOR];
996 return type_sizeof_[self->vtype];
999 static ir_value* ir_value_out(ir_function *owner, const char *name, store_type storetype, qc_type vtype)
1001 ir_value *v = new ir_value(name ? std::string(name) : std::string(), storetype, vtype);
1004 ir_function_collect_value(owner, v);
1008 bool ir_value_set_float(ir_value *self, float f)
1010 if (self->vtype != TYPE_FLOAT)
1012 self->constval.vfloat = f;
1013 self->hasvalue = true;
1017 bool ir_value_set_func(ir_value *self, int f)
1019 if (self->vtype != TYPE_FUNCTION)
1021 self->constval.vint = f;
1022 self->hasvalue = true;
1026 bool ir_value_set_vector(ir_value *self, vec3_t v)
1028 if (self->vtype != TYPE_VECTOR)
1030 self->constval.vvec = v;
1031 self->hasvalue = true;
1035 bool ir_value_set_field(ir_value *self, ir_value *fld)
1037 if (self->vtype != TYPE_FIELD)
1039 self->constval.vpointer = fld;
1040 self->hasvalue = true;
1044 bool ir_value_set_string(ir_value *self, const char *str)
1046 if (self->vtype != TYPE_STRING)
1048 self->constval.vstring = util_strdupe(str);
1049 self->hasvalue = true;
1054 bool ir_value_set_int(ir_value *self, int i)
1056 if (self->vtype != TYPE_INTEGER)
1058 self->constval.vint = i;
1059 self->hasvalue = true;
1064 bool ir_value_lives(ir_value *self, size_t at)
1066 for (auto& l : self->life) {
1067 if (l.start <= at && at <= l.end)
1069 if (l.start > at) /* since it's ordered */
1075 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1077 self->life.insert(self->life.begin() + idx, e);
1081 static bool ir_value_life_merge(ir_value *self, size_t s)
1084 const size_t vs = self->life.size();
1085 ir_life_entry_t *life_found = nullptr;
1086 ir_life_entry_t *before = nullptr;
1087 ir_life_entry_t new_entry;
1089 /* Find the first range >= s */
1090 for (i = 0; i < vs; ++i)
1092 before = life_found;
1093 life_found = &self->life[i];
1094 if (life_found->start > s)
1097 /* nothing found? append */
1100 if (life_found && life_found->end+1 == s)
1102 /* previous life range can be merged in */
1106 if (life_found && life_found->end >= s)
1108 e.start = e.end = s;
1109 self->life.emplace_back(e);
1115 if (before->end + 1 == s &&
1116 life_found->start - 1 == s)
1119 before->end = life_found->end;
1120 self->life.erase(self->life.begin()+i);
1123 if (before->end + 1 == s)
1129 /* already contained */
1130 if (before->end >= s)
1134 if (life_found->start - 1 == s)
1136 life_found->start--;
1139 /* insert a new entry */
1140 new_entry.start = new_entry.end = s;
1141 return ir_value_life_insert(self, i, new_entry);
1144 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1148 if (other->life.empty())
1151 if (self->life.empty()) {
1152 self->life = other->life;
1157 for (i = 0; i < other->life.size(); ++i)
1159 const ir_life_entry_t &otherlife = other->life[i];
1162 ir_life_entry_t *entry = &self->life[myi];
1164 if (otherlife.end+1 < entry->start)
1166 /* adding an interval before entry */
1167 if (!ir_value_life_insert(self, myi, otherlife))
1173 if (otherlife.start < entry->start &&
1174 otherlife.end+1 >= entry->start)
1176 /* starts earlier and overlaps */
1177 entry->start = otherlife.start;
1180 if (otherlife.end > entry->end &&
1181 otherlife.start <= entry->end+1)
1183 /* ends later and overlaps */
1184 entry->end = otherlife.end;
1187 /* see if our change combines it with the next ranges */
1188 while (myi+1 < self->life.size() &&
1189 entry->end+1 >= self->life[1+myi].start)
1191 /* overlaps with (myi+1) */
1192 if (entry->end < self->life[1+myi].end)
1193 entry->end = self->life[1+myi].end;
1194 self->life.erase(self->life.begin() + (myi + 1));
1195 entry = &self->life[myi];
1198 /* see if we're after the entry */
1199 if (otherlife.start > entry->end)
1202 /* append if we're at the end */
1203 if (myi >= self->life.size()) {
1204 self->life.emplace_back(otherlife);
1207 /* otherweise check the next range */
1216 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1218 /* For any life entry in A see if it overlaps with
1219 * any life entry in B.
1220 * Note that the life entries are orderes, so we can make a
1221 * more efficient algorithm there than naively translating the
1225 const ir_life_entry_t *la, *lb, *enda, *endb;
1227 /* first of all, if either has no life range, they cannot clash */
1228 if (a->life.empty() || b->life.empty())
1231 la = &a->life.front();
1232 lb = &b->life.front();
1233 enda = &a->life.back() + 1;
1234 endb = &b->life.back() + 1;
1237 /* check if the entries overlap, for that,
1238 * both must start before the other one ends.
1240 if (la->start < lb->end &&
1241 lb->start < la->end)
1246 /* entries are ordered
1247 * one entry is earlier than the other
1248 * that earlier entry will be moved forward
1250 if (la->start < lb->start)
1252 /* order: A B, move A forward
1253 * check if we hit the end with A
1258 else /* if (lb->start < la->start) actually <= */
1260 /* order: B A, move B forward
1261 * check if we hit the end with B
1270 /***********************************************************************
1274 static bool ir_check_unreachable(ir_block *self)
1276 /* The IR should never have to deal with unreachable code */
1277 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1279 irerror(self->context, "unreachable statement (%s)", self->label.c_str());
1283 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1286 if (!ir_check_unreachable(self))
1289 if (target->store == store_value &&
1290 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1292 irerror(self->context, "cannot store to an SSA value");
1293 irerror(self->context, "trying to store: %s <- %s", target->name.c_str(), what->name.c_str());
1294 irerror(self->context, "instruction: %s", util_instr_str[op]);
1298 in = new ir_instr(ctx, self, op);
1302 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1303 !ir_instr_op(in, 1, what, false))
1308 vec_push(self->instr, in);
1312 bool ir_block_create_state_op(ir_block *self, lex_ctx_t ctx, ir_value *frame, ir_value *think)
1315 if (!ir_check_unreachable(self))
1318 in = new ir_instr(ctx, self, INSTR_STATE);
1322 if (!ir_instr_op(in, 0, frame, false) ||
1323 !ir_instr_op(in, 1, think, false))
1328 vec_push(self->instr, in);
1332 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1336 if (target->vtype == TYPE_VARIANT)
1337 vtype = what->vtype;
1339 vtype = target->vtype;
1342 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1343 op = INSTR_CONV_ITOF;
1344 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1345 op = INSTR_CONV_FTOI;
1347 op = type_store_instr[vtype];
1349 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1350 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1354 return ir_block_create_store_op(self, ctx, op, target, what);
1357 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1362 if (target->vtype != TYPE_POINTER)
1365 /* storing using pointer - target is a pointer, type must be
1366 * inferred from source
1368 vtype = what->vtype;
1370 op = type_storep_instr[vtype];
1371 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1372 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1373 op = INSTR_STOREP_V;
1376 return ir_block_create_store_op(self, ctx, op, target, what);
1379 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1382 if (!ir_check_unreachable(self))
1387 self->is_return = true;
1388 in = new ir_instr(ctx, self, INSTR_RETURN);
1392 if (v && !ir_instr_op(in, 0, v, false)) {
1397 vec_push(self->instr, in);
1401 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1402 ir_block *ontrue, ir_block *onfalse)
1405 if (!ir_check_unreachable(self))
1408 /*in = new ir_instr(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1409 in = new ir_instr(ctx, self, VINSTR_COND);
1413 if (!ir_instr_op(in, 0, v, false)) {
1418 in->bops[0] = ontrue;
1419 in->bops[1] = onfalse;
1421 vec_push(self->instr, in);
1423 vec_push(self->exits, ontrue);
1424 vec_push(self->exits, onfalse);
1425 vec_push(ontrue->entries, self);
1426 vec_push(onfalse->entries, self);
1430 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1433 if (!ir_check_unreachable(self))
1436 in = new ir_instr(ctx, self, VINSTR_JUMP);
1441 vec_push(self->instr, in);
1443 vec_push(self->exits, to);
1444 vec_push(to->entries, self);
1448 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1450 self->owner->flags |= IR_FLAG_HAS_GOTO;
1451 return ir_block_create_jump(self, ctx, to);
1454 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, qc_type ot)
1458 if (!ir_check_unreachable(self))
1460 in = new ir_instr(ctx, self, VINSTR_PHI);
1463 out = ir_value_out(self->owner, label, store_value, ot);
1468 if (!ir_instr_op(in, 0, out, true)) {
1472 vec_push(self->instr, in);
1476 ir_value* ir_phi_value(ir_instr *self)
1478 return self->_ops[0];
1481 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1485 if (!vec_ir_block_find(self->owner->entries, b, nullptr)) {
1486 // Must not be possible to cause this, otherwise the AST
1487 // is doing something wrong.
1488 irerror(self->context, "Invalid entry block for PHI");
1494 v->reads.push_back(self);
1495 self->phi.push_back(pe);
1498 /* call related code */
1499 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1503 if (!ir_check_unreachable(self))
1505 in = new ir_instr(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1510 self->is_return = true;
1512 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1517 if (!ir_instr_op(in, 0, out, true) ||
1518 !ir_instr_op(in, 1, func, false))
1523 vec_push(self->instr, in);
1526 if (!ir_block_create_return(self, ctx, nullptr)) {
1527 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1536 ir_value* ir_call_value(ir_instr *self)
1538 return self->_ops[0];
1541 void ir_call_param(ir_instr* self, ir_value *v)
1543 self->params.push_back(v);
1544 v->reads.push_back(self);
1547 /* binary op related code */
1549 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1550 const char *label, int opcode,
1551 ir_value *left, ir_value *right)
1553 qc_type ot = TYPE_VOID;
1574 case INSTR_SUB_S: /* -- offset of string as float */
1579 case INSTR_BITOR_IF:
1580 case INSTR_BITOR_FI:
1581 case INSTR_BITAND_FI:
1582 case INSTR_BITAND_IF:
1597 case INSTR_BITAND_I:
1600 case INSTR_RSHIFT_I:
1601 case INSTR_LSHIFT_I:
1609 case VINSTR_BITAND_V:
1610 case VINSTR_BITOR_V:
1611 case VINSTR_BITXOR_V:
1612 case VINSTR_BITAND_VF:
1613 case VINSTR_BITOR_VF:
1614 case VINSTR_BITXOR_VF:
1629 * after the following default case, the value of opcode can never
1630 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1634 /* boolean operations result in floats */
1637 * opcode >= 10 takes true branch opcode is at least 10
1638 * opcode <= 23 takes false branch opcode is at least 24
1640 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1644 * At condition "opcode <= 23", the value of "opcode" must be
1646 * At condition "opcode <= 23", the value of "opcode" cannot be
1647 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1648 * The condition "opcode <= 23" cannot be true.
1650 * Thus ot=2 (TYPE_FLOAT) can never be true
1653 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1655 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1660 if (ot == TYPE_VOID) {
1661 /* The AST or parser were supposed to check this! */
1665 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1668 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1669 const char *label, int opcode,
1672 qc_type ot = TYPE_FLOAT;
1678 case INSTR_NOT_FNC: /*
1679 case INSTR_NOT_I: */
1684 * Negation for virtual instructions is emulated with 0-value. Thankfully
1685 * the operand for 0 already exists so we just source it from here.
1688 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_F, nullptr, operand, ot);
1690 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_V, nullptr, operand, TYPE_VECTOR);
1693 ot = operand->vtype;
1696 if (ot == TYPE_VOID) {
1697 /* The AST or parser were supposed to check this! */
1701 /* let's use the general instruction creator and pass nullptr for OPB */
1702 return ir_block_create_general_instr(self, ctx, label, opcode, operand, nullptr, ot);
1705 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1706 int op, ir_value *a, ir_value *b, qc_type outype)
1711 out = ir_value_out(self->owner, label, store_value, outype);
1715 instr = new ir_instr(ctx, self, op);
1720 if (!ir_instr_op(instr, 0, out, true) ||
1721 !ir_instr_op(instr, 1, a, false) ||
1722 !ir_instr_op(instr, 2, b, false) )
1727 vec_push(self->instr, instr);
1735 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1739 /* Support for various pointer types todo if so desired */
1740 if (ent->vtype != TYPE_ENTITY)
1743 if (field->vtype != TYPE_FIELD)
1746 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1747 v->fieldtype = field->fieldtype;
1751 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field, qc_type outype)
1754 if (ent->vtype != TYPE_ENTITY)
1757 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1758 if (field->vtype != TYPE_FIELD)
1763 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1764 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1765 case TYPE_STRING: op = INSTR_LOAD_S; break;
1766 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1767 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1768 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1770 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1771 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1774 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1778 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1781 /* PHI resolving breaks the SSA, and must thus be the last
1782 * step before life-range calculation.
1785 static bool ir_block_naive_phi(ir_block *self);
1786 bool ir_function_naive_phi(ir_function *self)
1788 for (auto& b : self->blocks)
1789 if (!ir_block_naive_phi(b.get()))
1794 static bool ir_block_naive_phi(ir_block *self)
1797 /* FIXME: optionally, create_phi can add the phis
1798 * to a list so we don't need to loop through blocks
1799 * - anyway: "don't optimize YET"
1801 for (i = 0; i < vec_size(self->instr); ++i)
1803 ir_instr *instr = self->instr[i];
1804 if (instr->opcode != VINSTR_PHI)
1807 vec_remove(self->instr, i, 1);
1808 --i; /* NOTE: i+1 below */
1810 for (auto &it : instr->phi) {
1811 ir_value *v = it.value;
1812 ir_block *b = it.from;
1813 if (v->store == store_value && v->reads.size() == 1 && v->writes.size() == 1) {
1814 /* replace the value */
1815 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1818 /* force a move instruction */
1819 ir_instr *prevjump = vec_last(b->instr);
1822 instr->_ops[0]->store = store_global;
1823 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
1825 instr->_ops[0]->store = store_value;
1826 vec_push(b->instr, prevjump);
1835 /***********************************************************************
1836 *IR Temp allocation code
1837 * Propagating value life ranges by walking through the function backwards
1838 * until no more changes are made.
1839 * In theory this should happen once more than once for every nested loop
1841 * Though this implementation might run an additional time for if nests.
1844 /* Enumerate instructions used by value's life-ranges
1846 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1850 for (i = 0; i < vec_size(self->instr); ++i)
1852 self->instr[i]->eid = eid++;
1857 /* Enumerate blocks and instructions.
1858 * The block-enumeration is unordered!
1859 * We do not really use the block enumreation, however
1860 * the instruction enumeration is important for life-ranges.
1862 void ir_function_enumerate(ir_function *self)
1864 size_t instruction_id = 0;
1865 size_t block_eid = 0;
1866 for (auto& block : self->blocks)
1868 /* each block now gets an additional "entry" instruction id
1869 * we can use to avoid point-life issues
1871 block->entry_id = instruction_id;
1872 block->eid = block_eid;
1876 ir_block_enumerate(block.get(), &instruction_id);
1880 /* Local-value allocator
1881 * After finishing creating the liferange of all values used in a function
1882 * we can allocate their global-positions.
1883 * This is the counterpart to register-allocation in register machines.
1885 struct function_allocator {
1892 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
1895 size_t vsize = ir_value_sizeof(var);
1897 var->code.local = vec_size(alloc->locals);
1899 slot = new ir_value("reg", store_global, var->vtype);
1903 if (!ir_value_life_merge_into(slot, var))
1906 vec_push(alloc->locals, slot);
1907 vec_push(alloc->sizes, vsize);
1908 vec_push(alloc->unique, var->unique_life);
1917 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
1923 return function_allocator_alloc(alloc, v);
1925 for (a = 0; a < vec_size(alloc->locals); ++a)
1927 /* if it's reserved for a unique liferange: skip */
1928 if (alloc->unique[a])
1931 slot = alloc->locals[a];
1933 /* never resize parameters
1934 * will be required later when overlapping temps + locals
1936 if (a < vec_size(self->params) &&
1937 alloc->sizes[a] < ir_value_sizeof(v))
1942 if (ir_values_overlap(v, slot))
1945 if (!ir_value_life_merge_into(slot, v))
1948 /* adjust size for this slot */
1949 if (alloc->sizes[a] < ir_value_sizeof(v))
1950 alloc->sizes[a] = ir_value_sizeof(v);
1955 if (a >= vec_size(alloc->locals)) {
1956 if (!function_allocator_alloc(alloc, v))
1962 bool ir_function_allocate_locals(ir_function *self)
1966 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
1968 function_allocator lockalloc, globalloc;
1970 if (self->locals.empty() && self->values.empty())
1973 globalloc.locals = nullptr;
1974 globalloc.sizes = nullptr;
1975 globalloc.positions = nullptr;
1976 globalloc.unique = nullptr;
1977 lockalloc.locals = nullptr;
1978 lockalloc.sizes = nullptr;
1979 lockalloc.positions = nullptr;
1980 lockalloc.unique = nullptr;
1983 for (i = 0; i < self->locals.size(); ++i)
1985 ir_value *v = self->locals[i].get();
1986 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
1988 v->unique_life = true;
1990 else if (i >= vec_size(self->params))
1993 v->locked = true; /* lock parameters locals */
1994 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
1997 for (; i < self->locals.size(); ++i)
1999 ir_value *v = self->locals[i].get();
2000 if (v->life.empty())
2002 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2006 /* Allocate a slot for any value that still exists */
2007 for (i = 0; i < self->values.size(); ++i)
2009 ir_value *v = self->values[i].get();
2011 if (v->life.empty())
2014 /* CALL optimization:
2015 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2016 * and it's not "locked", write it to the OFS_PARM directly.
2018 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2019 if (v->reads.size() == 1 && v->writes.size() == 1 &&
2020 (v->reads[0]->opcode == VINSTR_NRCALL ||
2021 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2026 ir_instr *call = v->reads[0];
2027 if (!vec_ir_value_find(call->params, v, ¶m)) {
2028 irerror(call->context, "internal error: unlocked parameter %s not found", v->name.c_str());
2031 ++opts_optimizationcount[OPTIM_CALL_STORES];
2032 v->callparam = true;
2034 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2036 size_t nprotos = self->owner->extparam_protos.size();
2039 if (nprotos > param)
2040 ep = self->owner->extparam_protos[param].get();
2043 ep = ir_gen_extparam_proto(self->owner);
2044 while (++nprotos <= param)
2045 ep = ir_gen_extparam_proto(self->owner);
2047 ir_instr_op(v->writes[0], 0, ep, true);
2048 call->params[param+8] = ep;
2052 if (v->writes.size() == 1 && v->writes[0]->opcode == INSTR_CALL0) {
2053 v->store = store_return;
2054 if (v->members[0]) v->members[0]->store = store_return;
2055 if (v->members[1]) v->members[1]->store = store_return;
2056 if (v->members[2]) v->members[2]->store = store_return;
2057 ++opts_optimizationcount[OPTIM_CALL_STORES];
2062 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2066 if (!lockalloc.sizes && !globalloc.sizes) {
2069 vec_push(lockalloc.positions, 0);
2070 vec_push(globalloc.positions, 0);
2072 /* Adjust slot positions based on sizes */
2073 if (lockalloc.sizes) {
2074 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2075 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2077 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2078 vec_push(lockalloc.positions, pos);
2080 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2082 if (globalloc.sizes) {
2083 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2084 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2086 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2087 vec_push(globalloc.positions, pos);
2089 self->globaltemps = pos + vec_last(globalloc.sizes);
2092 /* Locals need to know their new position */
2093 for (auto& local : self->locals) {
2094 if (local->locked || !opt_gt)
2095 local->code.local = lockalloc.positions[local->code.local];
2097 local->code.local = globalloc.positions[local->code.local];
2099 /* Take over the actual slot positions on values */
2100 for (auto& value : self->values) {
2101 if (value->locked || !opt_gt)
2102 value->code.local = lockalloc.positions[value->code.local];
2104 value->code.local = globalloc.positions[value->code.local];
2112 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2113 delete lockalloc.locals[i];
2114 for (i = 0; i < vec_size(globalloc.locals); ++i)
2115 delete globalloc.locals[i];
2116 vec_free(globalloc.unique);
2117 vec_free(globalloc.locals);
2118 vec_free(globalloc.sizes);
2119 vec_free(globalloc.positions);
2120 vec_free(lockalloc.unique);
2121 vec_free(lockalloc.locals);
2122 vec_free(lockalloc.sizes);
2123 vec_free(lockalloc.positions);
2127 /* Get information about which operand
2128 * is read from, or written to.
2130 static void ir_op_read_write(int op, size_t *read, size_t *write)
2150 case INSTR_STOREP_F:
2151 case INSTR_STOREP_V:
2152 case INSTR_STOREP_S:
2153 case INSTR_STOREP_ENT:
2154 case INSTR_STOREP_FLD:
2155 case INSTR_STOREP_FNC:
2166 static bool ir_block_living_add_instr(ir_block *self, size_t eid) {
2167 bool changed = false;
2168 for (auto &it : self->living)
2169 if (ir_value_life_merge(it, eid))
2174 static bool ir_block_living_lock(ir_block *self) {
2175 bool changed = false;
2176 for (auto &it : self->living) {
2185 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2189 size_t i, o, p, mem;
2190 // bitmasks which operands are read from or written to
2193 self->living.clear();
2195 p = vec_size(self->exits);
2196 for (i = 0; i < p; ++i) {
2197 ir_block *prev = self->exits[i];
2198 for (auto &it : prev->living)
2199 if (!vec_ir_value_find(self->living, it, nullptr))
2200 self->living.push_back(it);
2203 i = vec_size(self->instr);
2206 instr = self->instr[i];
2208 /* See which operands are read and write operands */
2209 ir_op_read_write(instr->opcode, &read, &write);
2211 /* Go through the 3 main operands
2212 * writes first, then reads
2214 for (o = 0; o < 3; ++o)
2216 if (!instr->_ops[o]) /* no such operand */
2219 value = instr->_ops[o];
2221 /* We only care about locals */
2222 /* we also calculate parameter liferanges so that locals
2223 * can take up parameter slots */
2224 if (value->store != store_value &&
2225 value->store != store_local &&
2226 value->store != store_param)
2229 /* write operands */
2230 /* When we write to a local, we consider it "dead" for the
2231 * remaining upper part of the function, since in SSA a value
2232 * can only be written once (== created)
2237 bool in_living = vec_ir_value_find(self->living, value, &idx);
2240 /* If the value isn't alive it hasn't been read before... */
2241 /* TODO: See if the warning can be emitted during parsing or AST processing
2242 * otherwise have warning printed here.
2243 * IF printing a warning here: include filecontext_t,
2244 * and make sure it's only printed once
2245 * since this function is run multiple times.
2247 /* con_err( "Value only written %s\n", value->name); */
2248 if (ir_value_life_merge(value, instr->eid))
2251 /* since 'living' won't contain it
2252 * anymore, merge the value, since
2255 if (ir_value_life_merge(value, instr->eid))
2258 self->living.erase(self->living.begin() + idx);
2260 /* Removing a vector removes all members */
2261 for (mem = 0; mem < 3; ++mem) {
2262 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2263 if (ir_value_life_merge(value->members[mem], instr->eid))
2265 self->living.erase(self->living.begin() + idx);
2268 /* Removing the last member removes the vector */
2269 if (value->memberof) {
2270 value = value->memberof;
2271 for (mem = 0; mem < 3; ++mem) {
2272 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], nullptr))
2275 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2276 if (ir_value_life_merge(value, instr->eid))
2278 self->living.erase(self->living.begin() + idx);
2284 /* These operations need a special case as they can break when using
2285 * same source and destination operand otherwise, as the engine may
2286 * read the source multiple times. */
2287 if (instr->opcode == INSTR_MUL_VF ||
2288 instr->opcode == VINSTR_BITAND_VF ||
2289 instr->opcode == VINSTR_BITOR_VF ||
2290 instr->opcode == VINSTR_BITXOR ||
2291 instr->opcode == VINSTR_BITXOR_VF ||
2292 instr->opcode == VINSTR_BITXOR_V ||
2293 instr->opcode == VINSTR_CROSS)
2295 value = instr->_ops[2];
2296 /* the float source will get an additional lifetime */
2297 if (ir_value_life_merge(value, instr->eid+1))
2299 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2303 if (instr->opcode == INSTR_MUL_FV ||
2304 instr->opcode == INSTR_LOAD_V ||
2305 instr->opcode == VINSTR_BITXOR ||
2306 instr->opcode == VINSTR_BITXOR_VF ||
2307 instr->opcode == VINSTR_BITXOR_V ||
2308 instr->opcode == VINSTR_CROSS)
2310 value = instr->_ops[1];
2311 /* the float source will get an additional lifetime */
2312 if (ir_value_life_merge(value, instr->eid+1))
2314 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2318 for (o = 0; o < 3; ++o)
2320 if (!instr->_ops[o]) /* no such operand */
2323 value = instr->_ops[o];
2325 /* We only care about locals */
2326 /* we also calculate parameter liferanges so that locals
2327 * can take up parameter slots */
2328 if (value->store != store_value &&
2329 value->store != store_local &&
2330 value->store != store_param)
2336 if (!vec_ir_value_find(self->living, value, nullptr))
2337 self->living.push_back(value);
2338 /* reading adds the full vector */
2339 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, nullptr))
2340 self->living.push_back(value->memberof);
2341 for (mem = 0; mem < 3; ++mem) {
2342 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], nullptr))
2343 self->living.push_back(value->members[mem]);
2347 /* PHI operands are always read operands */
2348 for (auto &it : instr->phi) {
2350 if (!vec_ir_value_find(self->living, value, nullptr))
2351 self->living.push_back(value);
2352 /* reading adds the full vector */
2353 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, nullptr))
2354 self->living.push_back(value->memberof);
2355 for (mem = 0; mem < 3; ++mem) {
2356 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], nullptr))
2357 self->living.push_back(value->members[mem]);
2361 /* on a call, all these values must be "locked" */
2362 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2363 if (ir_block_living_lock(self))
2366 /* call params are read operands too */
2367 for (auto &it : instr->params) {
2369 if (!vec_ir_value_find(self->living, value, nullptr))
2370 self->living.push_back(value);
2371 /* reading adds the full vector */
2372 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, nullptr))
2373 self->living.push_back(value->memberof);
2374 for (mem = 0; mem < 3; ++mem) {
2375 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], nullptr))
2376 self->living.push_back(value->members[mem]);
2381 if (ir_block_living_add_instr(self, instr->eid))
2384 /* the "entry" instruction ID */
2385 if (ir_block_living_add_instr(self, self->entry_id))
2391 bool ir_function_calculate_liferanges(ir_function *self)
2393 /* parameters live at 0 */
2394 for (size_t i = 0; i < vec_size(self->params); ++i)
2395 if (!ir_value_life_merge(self->locals[i].get(), 0))
2396 compile_error(self->context, "internal error: failed value-life merging");
2402 for (auto i = self->blocks.rbegin(); i != self->blocks.rend(); ++i)
2403 ir_block_life_propagate(i->get(), &changed);
2406 if (self->blocks.size()) {
2407 ir_block *block = self->blocks[0].get();
2408 for (auto &it : block->living) {
2410 if (v->store != store_local)
2412 if (v->vtype == TYPE_VECTOR)
2414 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2415 /* find the instruction reading from it */
2417 for (; s < v->reads.size(); ++s) {
2418 if (v->reads[s]->eid == v->life[0].end)
2421 if (s < v->reads.size()) {
2422 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2423 "variable `%s` may be used uninitialized in this function\n"
2426 v->reads[s]->context.file, v->reads[s]->context.line)
2434 ir_value *vec = v->memberof;
2435 for (s = 0; s < vec->reads.size(); ++s) {
2436 if (vec->reads[s]->eid == v->life[0].end)
2439 if (s < vec->reads.size()) {
2440 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2441 "variable `%s` may be used uninitialized in this function\n"
2444 vec->reads[s]->context.file, vec->reads[s]->context.line)
2452 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2453 "variable `%s` may be used uninitialized in this function", v->name.c_str()))
2462 /***********************************************************************
2465 * Since the IR has the convention of putting 'write' operands
2466 * at the beginning, we have to rotate the operands of instructions
2467 * properly in order to generate valid QCVM code.
2469 * Having destinations at a fixed position is more convenient. In QC
2470 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2471 * read from from OPA, and store to OPB rather than OPC. Which is
2472 * partially the reason why the implementation of these instructions
2473 * in darkplaces has been delayed for so long.
2475 * Breaking conventions is annoying...
2477 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2479 static bool gen_global_field(code_t *code, ir_value *global)
2481 if (global->hasvalue)
2483 ir_value *fld = global->constval.vpointer;
2485 irerror(global->context, "Invalid field constant with no field: %s", global->name.c_str());
2489 /* copy the field's value */
2490 ir_value_code_setaddr(global, code->globals.size());
2491 code->globals.push_back(fld->code.fieldaddr);
2492 if (global->fieldtype == TYPE_VECTOR) {
2493 code->globals.push_back(fld->code.fieldaddr+1);
2494 code->globals.push_back(fld->code.fieldaddr+2);
2499 ir_value_code_setaddr(global, code->globals.size());
2500 code->globals.push_back(0);
2501 if (global->fieldtype == TYPE_VECTOR) {
2502 code->globals.push_back(0);
2503 code->globals.push_back(0);
2506 if (global->code.globaladdr < 0)
2511 static bool gen_global_pointer(code_t *code, ir_value *global)
2513 if (global->hasvalue)
2515 ir_value *target = global->constval.vpointer;
2517 irerror(global->context, "Invalid pointer constant: %s", global->name.c_str());
2518 /* nullptr pointers are pointing to the nullptr constant, which also
2519 * sits at address 0, but still has an ir_value for itself.
2524 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2525 * void() foo; <- proto
2526 * void() *fooptr = &foo;
2527 * void() foo = { code }
2529 if (!target->code.globaladdr) {
2530 /* FIXME: Check for the constant nullptr ir_value!
2531 * because then code.globaladdr being 0 is valid.
2533 irerror(global->context, "FIXME: Relocation support");
2537 ir_value_code_setaddr(global, code->globals.size());
2538 code->globals.push_back(target->code.globaladdr);
2542 ir_value_code_setaddr(global, code->globals.size());
2543 code->globals.push_back(0);
2545 if (global->code.globaladdr < 0)
2550 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2552 prog_section_statement_t stmt;
2561 block->generated = true;
2562 block->code_start = code->statements.size();
2563 for (i = 0; i < vec_size(block->instr); ++i)
2565 instr = block->instr[i];
2567 if (instr->opcode == VINSTR_PHI) {
2568 irerror(block->context, "cannot generate virtual instruction (phi)");
2572 if (instr->opcode == VINSTR_JUMP) {
2573 target = instr->bops[0];
2574 /* for uncoditional jumps, if the target hasn't been generated
2575 * yet, we generate them right here.
2577 if (!target->generated)
2578 return gen_blocks_recursive(code, func, target);
2580 /* otherwise we generate a jump instruction */
2581 stmt.opcode = INSTR_GOTO;
2582 stmt.o1.s1 = target->code_start - code->statements.size();
2585 if (stmt.o1.s1 != 1)
2586 code_push_statement(code, &stmt, instr->context);
2588 /* no further instructions can be in this block */
2592 if (instr->opcode == VINSTR_BITXOR) {
2593 stmt.opcode = INSTR_BITOR;
2594 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2595 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2596 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2597 code_push_statement(code, &stmt, instr->context);
2598 stmt.opcode = INSTR_BITAND;
2599 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2600 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2601 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2602 code_push_statement(code, &stmt, instr->context);
2603 stmt.opcode = INSTR_SUB_F;
2604 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2605 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2606 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2607 code_push_statement(code, &stmt, instr->context);
2609 /* instruction generated */
2613 if (instr->opcode == VINSTR_BITAND_V) {
2614 stmt.opcode = INSTR_BITAND;
2615 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2616 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2617 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2618 code_push_statement(code, &stmt, instr->context);
2622 code_push_statement(code, &stmt, instr->context);
2626 code_push_statement(code, &stmt, instr->context);
2628 /* instruction generated */
2632 if (instr->opcode == VINSTR_BITOR_V) {
2633 stmt.opcode = INSTR_BITOR;
2634 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2635 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2636 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2637 code_push_statement(code, &stmt, instr->context);
2641 code_push_statement(code, &stmt, instr->context);
2645 code_push_statement(code, &stmt, instr->context);
2647 /* instruction generated */
2651 if (instr->opcode == VINSTR_BITXOR_V) {
2652 for (j = 0; j < 3; ++j) {
2653 stmt.opcode = INSTR_BITOR;
2654 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2655 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2656 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2657 code_push_statement(code, &stmt, instr->context);
2658 stmt.opcode = INSTR_BITAND;
2659 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2660 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2661 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2662 code_push_statement(code, &stmt, instr->context);
2664 stmt.opcode = INSTR_SUB_V;
2665 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2666 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2667 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2668 code_push_statement(code, &stmt, instr->context);
2670 /* instruction generated */
2674 if (instr->opcode == VINSTR_BITAND_VF) {
2675 stmt.opcode = INSTR_BITAND;
2676 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2677 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2678 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2679 code_push_statement(code, &stmt, instr->context);
2682 code_push_statement(code, &stmt, instr->context);
2685 code_push_statement(code, &stmt, instr->context);
2687 /* instruction generated */
2691 if (instr->opcode == VINSTR_BITOR_VF) {
2692 stmt.opcode = INSTR_BITOR;
2693 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2694 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2695 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2696 code_push_statement(code, &stmt, instr->context);
2699 code_push_statement(code, &stmt, instr->context);
2702 code_push_statement(code, &stmt, instr->context);
2704 /* instruction generated */
2708 if (instr->opcode == VINSTR_BITXOR_VF) {
2709 for (j = 0; j < 3; ++j) {
2710 stmt.opcode = INSTR_BITOR;
2711 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2712 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2713 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2714 code_push_statement(code, &stmt, instr->context);
2715 stmt.opcode = INSTR_BITAND;
2716 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2717 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2718 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2719 code_push_statement(code, &stmt, instr->context);
2721 stmt.opcode = INSTR_SUB_V;
2722 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2723 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2724 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2725 code_push_statement(code, &stmt, instr->context);
2727 /* instruction generated */
2731 if (instr->opcode == VINSTR_CROSS) {
2732 stmt.opcode = INSTR_MUL_F;
2733 for (j = 0; j < 3; ++j) {
2734 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 1) % 3;
2735 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 2) % 3;
2736 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2737 code_push_statement(code, &stmt, instr->context);
2738 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 2) % 3;
2739 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 1) % 3;
2740 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2741 code_push_statement(code, &stmt, instr->context);
2743 stmt.opcode = INSTR_SUB_V;
2744 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2745 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2746 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2747 code_push_statement(code, &stmt, instr->context);
2749 /* instruction generated */
2753 if (instr->opcode == VINSTR_COND) {
2754 ontrue = instr->bops[0];
2755 onfalse = instr->bops[1];
2756 /* TODO: have the AST signal which block should
2757 * come first: eg. optimize IFs without ELSE...
2760 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2764 if (ontrue->generated) {
2765 stmt.opcode = INSTR_IF;
2766 stmt.o2.s1 = ontrue->code_start - code->statements.size();
2767 if (stmt.o2.s1 != 1)
2768 code_push_statement(code, &stmt, instr->context);
2770 if (onfalse->generated) {
2771 stmt.opcode = INSTR_IFNOT;
2772 stmt.o2.s1 = onfalse->code_start - code->statements.size();
2773 if (stmt.o2.s1 != 1)
2774 code_push_statement(code, &stmt, instr->context);
2776 if (!ontrue->generated) {
2777 if (onfalse->generated)
2778 return gen_blocks_recursive(code, func, ontrue);
2780 if (!onfalse->generated) {
2781 if (ontrue->generated)
2782 return gen_blocks_recursive(code, func, onfalse);
2784 /* neither ontrue nor onfalse exist */
2785 stmt.opcode = INSTR_IFNOT;
2786 if (!instr->likely) {
2787 /* Honor the likelyhood hint */
2788 ir_block *tmp = onfalse;
2789 stmt.opcode = INSTR_IF;
2793 stidx = code->statements.size();
2794 code_push_statement(code, &stmt, instr->context);
2795 /* on false we jump, so add ontrue-path */
2796 if (!gen_blocks_recursive(code, func, ontrue))
2798 /* fixup the jump address */
2799 code->statements[stidx].o2.s1 = code->statements.size() - stidx;
2800 /* generate onfalse path */
2801 if (onfalse->generated) {
2802 /* fixup the jump address */
2803 code->statements[stidx].o2.s1 = onfalse->code_start - stidx;
2804 if (stidx+2 == code->statements.size() && code->statements[stidx].o2.s1 == 1) {
2805 code->statements[stidx] = code->statements[stidx+1];
2806 if (code->statements[stidx].o1.s1 < 0)
2807 code->statements[stidx].o1.s1++;
2808 code_pop_statement(code);
2810 stmt.opcode = code->statements.back().opcode;
2811 if (stmt.opcode == INSTR_GOTO ||
2812 stmt.opcode == INSTR_IF ||
2813 stmt.opcode == INSTR_IFNOT ||
2814 stmt.opcode == INSTR_RETURN ||
2815 stmt.opcode == INSTR_DONE)
2817 /* no use jumping from here */
2820 /* may have been generated in the previous recursive call */
2821 stmt.opcode = INSTR_GOTO;
2822 stmt.o1.s1 = onfalse->code_start - code->statements.size();
2825 if (stmt.o1.s1 != 1)
2826 code_push_statement(code, &stmt, instr->context);
2829 else if (stidx+2 == code->statements.size() && code->statements[stidx].o2.s1 == 1) {
2830 code->statements[stidx] = code->statements[stidx+1];
2831 if (code->statements[stidx].o1.s1 < 0)
2832 code->statements[stidx].o1.s1++;
2833 code_pop_statement(code);
2835 /* if not, generate now */
2836 return gen_blocks_recursive(code, func, onfalse);
2839 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2840 || instr->opcode == VINSTR_NRCALL)
2845 first = instr->params.size();
2848 for (p = 0; p < first; ++p)
2850 ir_value *param = instr->params[p];
2851 if (param->callparam)
2854 stmt.opcode = INSTR_STORE_F;
2857 if (param->vtype == TYPE_FIELD)
2858 stmt.opcode = field_store_instr[param->fieldtype];
2859 else if (param->vtype == TYPE_NIL)
2860 stmt.opcode = INSTR_STORE_V;
2862 stmt.opcode = type_store_instr[param->vtype];
2863 stmt.o1.u1 = ir_value_code_addr(param);
2864 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2866 if (param->vtype == TYPE_VECTOR && (param->flags & IR_FLAG_SPLIT_VECTOR)) {
2867 /* fetch 3 separate floats */
2868 stmt.opcode = INSTR_STORE_F;
2869 stmt.o1.u1 = ir_value_code_addr(param->members[0]);
2870 code_push_statement(code, &stmt, instr->context);
2872 stmt.o1.u1 = ir_value_code_addr(param->members[1]);
2873 code_push_statement(code, &stmt, instr->context);
2875 stmt.o1.u1 = ir_value_code_addr(param->members[2]);
2876 code_push_statement(code, &stmt, instr->context);
2879 code_push_statement(code, &stmt, instr->context);
2881 /* Now handle extparams */
2882 first = instr->params.size();
2883 for (; p < first; ++p)
2885 ir_builder *ir = func->owner;
2886 ir_value *param = instr->params[p];
2887 ir_value *targetparam;
2889 if (param->callparam)
2892 if (p-8 >= ir->extparams.size())
2893 ir_gen_extparam(ir);
2895 targetparam = ir->extparams[p-8];
2897 stmt.opcode = INSTR_STORE_F;
2900 if (param->vtype == TYPE_FIELD)
2901 stmt.opcode = field_store_instr[param->fieldtype];
2902 else if (param->vtype == TYPE_NIL)
2903 stmt.opcode = INSTR_STORE_V;
2905 stmt.opcode = type_store_instr[param->vtype];
2906 stmt.o1.u1 = ir_value_code_addr(param);
2907 stmt.o2.u1 = ir_value_code_addr(targetparam);
2908 if (param->vtype == TYPE_VECTOR && (param->flags & IR_FLAG_SPLIT_VECTOR)) {
2909 /* fetch 3 separate floats */
2910 stmt.opcode = INSTR_STORE_F;
2911 stmt.o1.u1 = ir_value_code_addr(param->members[0]);
2912 code_push_statement(code, &stmt, instr->context);
2914 stmt.o1.u1 = ir_value_code_addr(param->members[1]);
2915 code_push_statement(code, &stmt, instr->context);
2917 stmt.o1.u1 = ir_value_code_addr(param->members[2]);
2918 code_push_statement(code, &stmt, instr->context);
2921 code_push_statement(code, &stmt, instr->context);
2924 stmt.opcode = INSTR_CALL0 + instr->params.size();
2925 if (stmt.opcode > INSTR_CALL8)
2926 stmt.opcode = INSTR_CALL8;
2927 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2930 code_push_statement(code, &stmt, instr->context);
2932 retvalue = instr->_ops[0];
2933 if (retvalue && retvalue->store != store_return &&
2934 (retvalue->store == store_global || retvalue->life.size()))
2936 /* not to be kept in OFS_RETURN */
2937 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2938 stmt.opcode = field_store_instr[retvalue->fieldtype];
2940 stmt.opcode = type_store_instr[retvalue->vtype];
2941 stmt.o1.u1 = OFS_RETURN;
2942 stmt.o2.u1 = ir_value_code_addr(retvalue);
2944 code_push_statement(code, &stmt, instr->context);
2949 if (instr->opcode == INSTR_STATE) {
2950 stmt.opcode = instr->opcode;
2952 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2954 stmt.o2.u1 = ir_value_code_addr(instr->_ops[1]);
2956 code_push_statement(code, &stmt, instr->context);
2960 stmt.opcode = instr->opcode;
2965 /* This is the general order of operands */
2967 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2970 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2973 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2975 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2977 stmt.o1.u1 = stmt.o3.u1;
2980 else if ((stmt.opcode >= INSTR_STORE_F &&
2981 stmt.opcode <= INSTR_STORE_FNC) ||
2982 (stmt.opcode >= INSTR_STOREP_F &&
2983 stmt.opcode <= INSTR_STOREP_FNC))
2985 /* 2-operand instructions with A -> B */
2986 stmt.o2.u1 = stmt.o3.u1;
2989 /* tiny optimization, don't output
2992 if (stmt.o2.u1 == stmt.o1.u1 &&
2993 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2995 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2999 code_push_statement(code, &stmt, instr->context);
3004 static bool gen_function_code(code_t *code, ir_function *self)
3007 prog_section_statement_t stmt, *retst;
3009 /* Starting from entry point, we generate blocks "as they come"
3010 * for now. Dead blocks will not be translated obviously.
3012 if (self->blocks.empty()) {
3013 irerror(self->context, "Function '%s' declared without body.", self->name.c_str());
3017 block = self->blocks[0].get();
3018 if (block->generated)
3021 if (!gen_blocks_recursive(code, self, block)) {
3022 irerror(self->context, "failed to generate blocks for '%s'", self->name.c_str());
3026 /* code_write and qcvm -disasm need to know that the function ends here */
3027 retst = &code->statements.back();
3028 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3029 self->outtype == TYPE_VOID &&
3030 retst->opcode == INSTR_RETURN &&
3031 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3033 retst->opcode = INSTR_DONE;
3034 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3038 stmt.opcode = INSTR_DONE;
3042 last.line = code->linenums.back();
3043 last.column = code->columnnums.back();
3045 code_push_statement(code, &stmt, last);
3050 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3052 /* NOTE: filename pointers are copied, we never strdup them,
3053 * thus we can use pointer-comparison to find the string.
3057 for (size_t i = 0; i != ir->filenames.size(); ++i) {
3058 if (!strcmp(ir->filenames[i], filename))
3062 str = code_genstring(ir->code.get(), filename);
3063 ir->filenames.push_back(filename);
3064 ir->filestrings.push_back(str);
3068 static bool gen_global_function(ir_builder *ir, ir_value *global)
3070 prog_section_function_t fun;
3075 if (!global->hasvalue || (!global->constval.vfunc)) {
3076 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name.c_str());
3080 irfun = global->constval.vfunc;
3081 fun.name = global->code.name;
3082 fun.file = ir_builder_filestring(ir, global->context.file);
3083 fun.profile = 0; /* always 0 */
3084 fun.nargs = vec_size(irfun->params);
3088 for (i = 0; i < 8; ++i) {
3089 if ((int32_t)i >= fun.nargs)
3092 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3096 fun.locals = irfun->allocated_locals;
3099 fun.entry = irfun->builtin+1;
3101 irfun->code_function_def = ir->code->functions.size();
3102 fun.entry = ir->code->statements.size();
3105 ir->code->functions.push_back(fun);
3109 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3113 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(ir->extparam_protos.size()));
3114 ir_value *global = new ir_value(name, store_global, TYPE_VECTOR);
3115 ir->extparam_protos.emplace_back(global);
3120 static void ir_gen_extparam(ir_builder *ir)
3122 prog_section_def_t def;
3125 if (ir->extparam_protos.size() < ir->extparams.size()+1)
3126 global = ir_gen_extparam_proto(ir);
3128 global = ir->extparam_protos[ir->extparams.size()].get();
3130 def.name = code_genstring(ir->code.get(), global->name.c_str());
3131 def.type = TYPE_VECTOR;
3132 def.offset = ir->code->globals.size();
3134 ir->code->defs.push_back(def);
3136 ir_value_code_setaddr(global, def.offset);
3138 ir->code->globals.push_back(0);
3139 ir->code->globals.push_back(0);
3140 ir->code->globals.push_back(0);
3142 ir->extparams.emplace_back(global);
3145 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3147 ir_builder *ir = self->owner;
3149 size_t numparams = vec_size(self->params);
3153 prog_section_statement_t stmt;
3154 stmt.opcode = INSTR_STORE_F;
3156 for (size_t i = 8; i < numparams; ++i) {
3158 if (ext >= ir->extparams.size())
3159 ir_gen_extparam(ir);
3161 ir_value *ep = ir->extparams[ext];
3163 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3164 if (self->locals[i]->vtype == TYPE_FIELD &&
3165 self->locals[i]->fieldtype == TYPE_VECTOR)
3167 stmt.opcode = INSTR_STORE_V;
3169 stmt.o1.u1 = ir_value_code_addr(ep);
3170 stmt.o2.u1 = ir_value_code_addr(self->locals[i].get());
3171 code_push_statement(code, &stmt, self->context);
3177 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3179 size_t i, ext, numparams, maxparams;
3181 ir_builder *ir = self->owner;
3183 prog_section_statement_t stmt;
3185 numparams = vec_size(self->params);
3189 stmt.opcode = INSTR_STORE_V;
3191 maxparams = numparams + self->max_varargs;
3192 for (i = numparams; i < maxparams; ++i) {
3194 stmt.o1.u1 = OFS_PARM0 + 3*i;
3195 stmt.o2.u1 = ir_value_code_addr(self->locals[i].get());
3196 code_push_statement(code, &stmt, self->context);
3200 while (ext >= ir->extparams.size())
3201 ir_gen_extparam(ir);
3203 ep = ir->extparams[ext];
3205 stmt.o1.u1 = ir_value_code_addr(ep);
3206 stmt.o2.u1 = ir_value_code_addr(self->locals[i].get());
3207 code_push_statement(code, &stmt, self->context);
3213 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3215 prog_section_function_t *def;
3217 uint32_t firstlocal, firstglobal;
3219 irfun = global->constval.vfunc;
3220 def = &ir->code->functions[0] + irfun->code_function_def;
3222 if (OPTS_OPTION_BOOL(OPTION_G) ||
3223 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3224 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3226 firstlocal = def->firstlocal = ir->code->globals.size();
3228 firstlocal = def->firstlocal = ir->first_common_local;
3229 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3232 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3234 for (size_t i = ir->code->globals.size(); i < firstlocal + irfun->allocated_locals; ++i)
3235 ir->code->globals.push_back(0);
3237 for (auto& lp : irfun->locals) {
3238 ir_value *v = lp.get();
3239 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3240 ir_value_code_setaddr(v, firstlocal + v->code.local);
3241 if (!ir_builder_gen_global(ir, v, true)) {
3242 irerror(v->context, "failed to generate local %s", v->name.c_str());
3247 ir_value_code_setaddr(v, firstglobal + v->code.local);
3249 for (auto& vp : irfun->values) {
3250 ir_value *v = vp.get();
3254 ir_value_code_setaddr(v, firstlocal + v->code.local);
3256 ir_value_code_setaddr(v, firstglobal + v->code.local);
3261 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3263 prog_section_function_t *fundef;
3268 irfun = global->constval.vfunc;
3270 if (global->cvq == CV_NONE) {
3271 if (irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3272 "function `%s` has no body and in QC implicitly becomes a function-pointer",
3273 global->name.c_str()))
3275 /* Not bailing out just now. If this happens a lot you don't want to have
3276 * to rerun gmqcc for each such function.
3282 /* this was a function pointer, don't generate code for those */
3290 * If there is no definition and the thing is eraseable, we can ignore
3291 * outputting the function to begin with.
3293 if (global->flags & IR_FLAG_ERASABLE && irfun->code_function_def < 0) {
3297 if (irfun->code_function_def < 0) {
3298 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name.c_str());
3301 fundef = &ir->code->functions[irfun->code_function_def];
3303 fundef->entry = ir->code->statements.size();
3304 if (!gen_function_locals(ir, global)) {
3305 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name.c_str());
3308 if (!gen_function_extparam_copy(ir->code.get(), irfun)) {
3309 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name.c_str());
3312 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code.get(), irfun)) {
3313 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name.c_str());
3316 if (!gen_function_code(ir->code.get(), irfun)) {
3317 irerror(irfun->context, "Failed to generate code for function %s", irfun->name.c_str());
3323 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3328 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3331 def.type = TYPE_FLOAT;
3335 component = (char*)mem_a(len+3);
3336 memcpy(component, name, len);
3338 component[len-0] = 0;
3339 component[len-2] = '_';
3341 component[len-1] = 'x';
3343 for (i = 0; i < 3; ++i) {
3344 def.name = code_genstring(code, component);
3345 code->defs.push_back(def);
3353 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3358 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3361 fld.type = TYPE_FLOAT;
3365 component = (char*)mem_a(len+3);
3366 memcpy(component, name, len);
3368 component[len-0] = 0;
3369 component[len-2] = '_';
3371 component[len-1] = 'x';
3373 for (i = 0; i < 3; ++i) {
3374 fld.name = code_genstring(code, component);
3375 code->fields.push_back(fld);
3383 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3387 prog_section_def_t def;
3388 bool pushdef = opts.optimizeoff;
3390 /* we don't generate split-vectors */
3391 if (global->vtype == TYPE_VECTOR && (global->flags & IR_FLAG_SPLIT_VECTOR))
3394 def.type = global->vtype;
3395 def.offset = self->code->globals.size();
3397 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3402 * if we're eraseable and the function isn't referenced ignore outputting
3405 if (global->flags & IR_FLAG_ERASABLE && global->reads.empty()) {
3409 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3410 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3411 (global->name[0] == '#' || global->cvq == CV_CONST))
3417 if (global->name[0] == '#') {
3418 if (!self->str_immediate)
3419 self->str_immediate = code_genstring(self->code.get(), "IMMEDIATE");
3420 def.name = global->code.name = self->str_immediate;
3423 def.name = global->code.name = code_genstring(self->code.get(), global->name.c_str());
3428 def.offset = ir_value_code_addr(global);
3429 self->code->defs.push_back(def);
3430 if (global->vtype == TYPE_VECTOR)
3431 gen_vector_defs(self->code.get(), def, global->name.c_str());
3432 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3433 gen_vector_defs(self->code.get(), def, global->name.c_str());
3440 switch (global->vtype)
3443 if (0 == global->name.compare("end_sys_globals")) {
3444 // TODO: remember this point... all the defs before this one
3445 // should be checksummed and added to progdefs.h when we generate it.
3447 else if (0 == global->name.compare("end_sys_fields")) {
3448 // TODO: same as above but for entity-fields rather than globsl
3450 else if(irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3451 global->name.c_str()))
3453 /* Not bailing out */
3456 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3457 * the system fields actually go? Though the engine knows this anyway...
3458 * Maybe this could be an -foption
3459 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3461 ir_value_code_setaddr(global, self->code->globals.size());
3462 self->code->globals.push_back(0);
3464 if (pushdef) self->code->defs.push_back(def);
3467 if (pushdef) self->code->defs.push_back(def);
3468 return gen_global_pointer(self->code.get(), global);
3471 self->code->defs.push_back(def);
3472 if (global->fieldtype == TYPE_VECTOR)
3473 gen_vector_defs(self->code.get(), def, global->name.c_str());
3475 return gen_global_field(self->code.get(), global);
3480 ir_value_code_setaddr(global, self->code->globals.size());
3481 if (global->hasvalue) {
3482 iptr = (int32_t*)&global->constval.ivec[0];
3483 self->code->globals.push_back(*iptr);
3485 self->code->globals.push_back(0);
3487 if (!islocal && global->cvq != CV_CONST)
3488 def.type |= DEF_SAVEGLOBAL;
3489 if (pushdef) self->code->defs.push_back(def);
3491 return global->code.globaladdr >= 0;
3495 ir_value_code_setaddr(global, self->code->globals.size());
3496 if (global->hasvalue) {
3497 uint32_t load = code_genstring(self->code.get(), global->constval.vstring);
3498 self->code->globals.push_back(load);
3500 self->code->globals.push_back(0);
3502 if (!islocal && global->cvq != CV_CONST)
3503 def.type |= DEF_SAVEGLOBAL;
3504 if (pushdef) self->code->defs.push_back(def);
3505 return global->code.globaladdr >= 0;
3510 ir_value_code_setaddr(global, self->code->globals.size());
3511 if (global->hasvalue) {
3512 iptr = (int32_t*)&global->constval.ivec[0];
3513 self->code->globals.push_back(iptr[0]);
3514 if (global->code.globaladdr < 0)
3516 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3517 self->code->globals.push_back(iptr[d]);
3520 self->code->globals.push_back(0);
3521 if (global->code.globaladdr < 0)
3523 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3524 self->code->globals.push_back(0);
3527 if (!islocal && global->cvq != CV_CONST)
3528 def.type |= DEF_SAVEGLOBAL;
3531 self->code->defs.push_back(def);
3532 def.type &= ~DEF_SAVEGLOBAL;
3533 gen_vector_defs(self->code.get(), def, global->name.c_str());
3535 return global->code.globaladdr >= 0;
3538 ir_value_code_setaddr(global, self->code->globals.size());
3539 if (!global->hasvalue) {
3540 self->code->globals.push_back(0);
3541 if (global->code.globaladdr < 0)
3544 self->code->globals.push_back(self->code->functions.size());
3545 if (!gen_global_function(self, global))
3548 if (!islocal && global->cvq != CV_CONST)
3549 def.type |= DEF_SAVEGLOBAL;
3550 if (pushdef) self->code->defs.push_back(def);
3553 /* assume biggest type */
3554 ir_value_code_setaddr(global, self->code->globals.size());
3555 self->code->globals.push_back(0);
3556 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3557 self->code->globals.push_back(0);
3560 /* refuse to create 'void' type or any other fancy business. */
3561 irerror(global->context, "Invalid type for global variable `%s`: %s",
3562 global->name.c_str(), type_name[global->vtype]);
3567 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3569 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3572 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3574 prog_section_def_t def;
3575 prog_section_field_t fld;
3579 def.type = (uint16_t)field->vtype;
3580 def.offset = (uint16_t)self->code->globals.size();
3582 /* create a global named the same as the field */
3583 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3584 /* in our standard, the global gets a dot prefix */
3585 size_t len = field->name.length();
3588 /* we really don't want to have to allocate this, and 1024
3589 * bytes is more than enough for a variable/field name
3591 if (len+2 >= sizeof(name)) {
3592 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3597 memcpy(name+1, field->name.c_str(), len); // no strncpy - we used strlen above
3600 def.name = code_genstring(self->code.get(), name);
3601 fld.name = def.name + 1; /* we reuse that string table entry */
3603 /* in plain QC, there cannot be a global with the same name,
3604 * and so we also name the global the same.
3605 * FIXME: fteqcc should create a global as well
3606 * check if it actually uses the same name. Probably does
3608 def.name = code_genstring(self->code.get(), field->name.c_str());
3609 fld.name = def.name;
3612 field->code.name = def.name;
3614 self->code->defs.push_back(def);
3616 fld.type = field->fieldtype;
3618 if (fld.type == TYPE_VOID) {
3619 irerror(field->context, "field is missing a type: %s - don't know its size", field->name.c_str());
3623 fld.offset = field->code.fieldaddr;
3625 self->code->fields.push_back(fld);
3627 ir_value_code_setaddr(field, self->code->globals.size());
3628 self->code->globals.push_back(fld.offset);
3629 if (fld.type == TYPE_VECTOR) {
3630 self->code->globals.push_back(fld.offset+1);
3631 self->code->globals.push_back(fld.offset+2);
3634 if (field->fieldtype == TYPE_VECTOR) {
3635 gen_vector_defs (self->code.get(), def, field->name.c_str());
3636 gen_vector_fields(self->code.get(), fld, field->name.c_str());
3639 return field->code.globaladdr >= 0;
3642 static void ir_builder_collect_reusables(ir_builder *builder) {
3643 std::vector<ir_value*> reusables;
3645 for (auto& gp : builder->globals) {
3646 ir_value *value = gp.get();
3647 if (value->vtype != TYPE_FLOAT || !value->hasvalue)
3649 if (value->cvq == CV_CONST || (value->name.length() >= 1 && value->name[0] == '#'))
3650 reusables.emplace_back(value);
3652 builder->const_floats = move(reusables);
3655 static void ir_builder_split_vector(ir_builder *self, ir_value *vec) {
3656 ir_value* found[3] = { nullptr, nullptr, nullptr };
3658 // must not be written to
3659 if (vec->writes.size())
3661 // must not be trying to access individual members
3662 if (vec->members[0] || vec->members[1] || vec->members[2])
3664 // should be actually used otherwise it won't be generated anyway
3665 if (vec->reads.empty())
3667 //size_t count = vec->reads.size();
3671 // may only be used directly as function parameters, so if we find some other instruction cancel
3672 for (ir_instr *user : vec->reads) {
3673 // we only split vectors if they're used directly as parameter to a call only!
3674 if ((user->opcode < INSTR_CALL0 || user->opcode > INSTR_CALL8) && user->opcode != VINSTR_NRCALL)
3678 vec->flags |= IR_FLAG_SPLIT_VECTOR;
3680 // find existing floats making up the split
3681 for (ir_value *c : self->const_floats) {
3682 if (!found[0] && c->constval.vfloat == vec->constval.vvec.x)
3684 if (!found[1] && c->constval.vfloat == vec->constval.vvec.y)
3686 if (!found[2] && c->constval.vfloat == vec->constval.vvec.z)
3688 if (found[0] && found[1] && found[2])
3692 // generate floats for not yet found components
3694 found[0] = ir_builder_imm_float(self, vec->constval.vvec.x, true);
3696 if (vec->constval.vvec.y == vec->constval.vvec.x)
3697 found[1] = found[0];
3699 found[1] = ir_builder_imm_float(self, vec->constval.vvec.y, true);
3702 if (vec->constval.vvec.z == vec->constval.vvec.x)
3703 found[2] = found[0];
3704 else if (vec->constval.vvec.z == vec->constval.vvec.y)
3705 found[2] = found[1];
3707 found[2] = ir_builder_imm_float(self, vec->constval.vvec.z, true);
3710 // the .members array should be safe to use here
3711 vec->members[0] = found[0];
3712 vec->members[1] = found[1];
3713 vec->members[2] = found[2];
3715 // register the readers for these floats
3716 found[0]->reads.insert(found[0]->reads.end(), vec->reads.begin(), vec->reads.end());
3717 found[1]->reads.insert(found[1]->reads.end(), vec->reads.begin(), vec->reads.end());
3718 found[2]->reads.insert(found[2]->reads.end(), vec->reads.begin(), vec->reads.end());
3721 static void ir_builder_split_vectors(ir_builder *self) {
3722 // member values may be added to self->globals during this operation, but
3723 // no new vectors will be added, we need to iterate via an index as
3724 // c++ iterators would be invalidated
3725 const size_t count = self->globals.size();
3726 for (size_t i = 0; i != count; ++i) {
3727 ir_value *v = self->globals[i].get();
3728 if (v->vtype != TYPE_VECTOR || !v->name.length() || v->name[0] != '#')
3730 ir_builder_split_vector(self, v);
3734 bool ir_builder_generate(ir_builder *self, const char *filename)
3736 prog_section_statement_t stmt;
3737 char *lnofile = nullptr;
3739 if (OPTS_FLAG(SPLIT_VECTOR_PARAMETERS)) {
3740 ir_builder_collect_reusables(self);
3741 if (!self->const_floats.empty())
3742 ir_builder_split_vectors(self);
3745 for (auto& fp : self->fields)
3746 ir_builder_prepare_field(self->code.get(), fp.get());
3748 for (auto& gp : self->globals) {
3749 ir_value *global = gp.get();
3750 if (!ir_builder_gen_global(self, global, false)) {
3753 if (global->vtype == TYPE_FUNCTION) {
3754 ir_function *func = global->constval.vfunc;
3755 if (func && self->max_locals < func->allocated_locals &&
3756 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3758 self->max_locals = func->allocated_locals;
3760 if (func && self->max_globaltemps < func->globaltemps)
3761 self->max_globaltemps = func->globaltemps;
3765 for (auto& fp : self->fields) {
3766 if (!ir_builder_gen_field(self, fp.get()))
3771 ir_value_code_setaddr(self->nil, self->code->globals.size());
3772 self->code->globals.push_back(0);
3773 self->code->globals.push_back(0);
3774 self->code->globals.push_back(0);
3776 // generate virtual-instruction temps
3777 for (size_t i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
3778 ir_value_code_setaddr(self->vinstr_temp[i], self->code->globals.size());
3779 self->code->globals.push_back(0);
3780 self->code->globals.push_back(0);
3781 self->code->globals.push_back(0);
3784 // generate global temps
3785 self->first_common_globaltemp = self->code->globals.size();
3786 self->code->globals.insert(self->code->globals.end(), self->max_globaltemps, 0);
3788 //for (size_t i = 0; i < self->max_globaltemps; ++i) {
3789 // self->code->globals.push_back(0);
3791 // generate common locals
3792 self->first_common_local = self->code->globals.size();
3793 self->code->globals.insert(self->code->globals.end(), self->max_locals, 0);
3795 //for (i = 0; i < self->max_locals; ++i) {
3796 // self->code->globals.push_back(0);
3799 // generate function code
3801 for (auto& gp : self->globals) {
3802 ir_value *global = gp.get();
3803 if (global->vtype == TYPE_FUNCTION) {
3804 if (!gen_global_function_code(self, global)) {
3810 if (self->code->globals.size() >= 65536) {
3811 irerror(self->globals.back()->context,
3812 "This progs file would require more globals than the metadata can handle (%zu). Bailing out.",
3813 self->code->globals.size());
3817 /* DP errors if the last instruction is not an INSTR_DONE. */
3818 if (self->code->statements.back().opcode != INSTR_DONE)
3822 stmt.opcode = INSTR_DONE;
3826 last.line = self->code->linenums.back();
3827 last.column = self->code->columnnums.back();
3829 code_push_statement(self->code.get(), &stmt, last);
3832 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3835 if (self->code->statements.size() != self->code->linenums.size()) {
3836 con_err("Linecounter wrong: %lu != %lu\n",
3837 self->code->statements.size(),
3838 self->code->linenums.size());
3839 } else if (OPTS_FLAG(LNO)) {
3841 size_t filelen = strlen(filename);
3843 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3844 dot = strrchr(lnofile, '.');
3848 vec_shrinkto(lnofile, dot - lnofile);
3850 memcpy(vec_add(lnofile, 5), ".lno", 5);
3853 if (!code_write(self->code.get(), filename, lnofile)) {
3862 /***********************************************************************
3863 *IR DEBUG Dump functions...
3866 #define IND_BUFSZ 1024
3868 static const char *qc_opname(int op)
3870 if (op < 0) return "<INVALID>";
3871 if (op < VINSTR_END)
3872 return util_instr_str[op];
3874 case VINSTR_END: return "END";
3875 case VINSTR_PHI: return "PHI";
3876 case VINSTR_JUMP: return "JUMP";
3877 case VINSTR_COND: return "COND";
3878 case VINSTR_BITXOR: return "BITXOR";
3879 case VINSTR_BITAND_V: return "BITAND_V";
3880 case VINSTR_BITOR_V: return "BITOR_V";
3881 case VINSTR_BITXOR_V: return "BITXOR_V";
3882 case VINSTR_BITAND_VF: return "BITAND_VF";
3883 case VINSTR_BITOR_VF: return "BITOR_VF";
3884 case VINSTR_BITXOR_VF: return "BITXOR_VF";
3885 case VINSTR_CROSS: return "CROSS";
3886 case VINSTR_NEG_F: return "NEG_F";
3887 case VINSTR_NEG_V: return "NEG_V";
3888 default: return "<UNK>";
3892 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3895 char indent[IND_BUFSZ];
3899 oprintf("module %s\n", b->name.c_str());
3900 for (i = 0; i < b->globals.size(); ++i)
3903 if (b->globals[i]->hasvalue)
3904 oprintf("%s = ", b->globals[i]->name.c_str());
3905 ir_value_dump(b->globals[i].get(), oprintf);
3908 for (i = 0; i < b->functions.size(); ++i)
3909 ir_function_dump(b->functions[i].get(), indent, oprintf);
3910 oprintf("endmodule %s\n", b->name.c_str());
3913 static const char *storenames[] = {
3914 "[global]", "[local]", "[param]", "[value]", "[return]"
3917 void ir_function_dump(ir_function *f, char *ind,
3918 int (*oprintf)(const char*, ...))
3921 if (f->builtin != 0) {
3922 oprintf("%sfunction %s = builtin %i\n", ind, f->name.c_str(), -f->builtin);
3925 oprintf("%sfunction %s\n", ind, f->name.c_str());
3926 util_strncat(ind, "\t", IND_BUFSZ-1);
3927 if (f->locals.size())
3929 oprintf("%s%i locals:\n", ind, (int)f->locals.size());
3930 for (i = 0; i < f->locals.size(); ++i) {
3931 oprintf("%s\t", ind);
3932 ir_value_dump(f->locals[i].get(), oprintf);
3936 oprintf("%sliferanges:\n", ind);
3937 for (i = 0; i < f->locals.size(); ++i) {
3938 const char *attr = "";
3940 ir_value *v = f->locals[i].get();
3941 if (v->unique_life && v->locked)
3942 attr = "unique,locked ";
3943 else if (v->unique_life)
3947 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name.c_str(), type_name[v->vtype],
3948 storenames[v->store],
3949 attr, (v->callparam ? "callparam " : ""),
3950 (int)v->code.local);
3951 if (v->life.empty())
3953 for (l = 0; l < v->life.size(); ++l) {
3954 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3957 for (m = 0; m < 3; ++m) {
3958 ir_value *vm = v->members[m];
3961 oprintf("%s\t%s: @%i ", ind, vm->name.c_str(), (int)vm->code.local);
3962 for (l = 0; l < vm->life.size(); ++l) {
3963 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3968 for (i = 0; i < f->values.size(); ++i) {
3969 const char *attr = "";
3971 ir_value *v = f->values[i].get();
3972 if (v->unique_life && v->locked)
3973 attr = "unique,locked ";
3974 else if (v->unique_life)
3978 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name.c_str(), type_name[v->vtype],
3979 storenames[v->store],
3980 attr, (v->callparam ? "callparam " : ""),
3981 (int)v->code.local);
3982 if (v->life.empty())
3984 for (l = 0; l < v->life.size(); ++l) {
3985 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3988 for (m = 0; m < 3; ++m) {
3989 ir_value *vm = v->members[m];
3992 if (vm->unique_life && vm->locked)
3993 attr = "unique,locked ";
3994 else if (vm->unique_life)
3996 else if (vm->locked)
3998 oprintf("%s\t%s: %s@%i ", ind, vm->name.c_str(), attr, (int)vm->code.local);
3999 for (l = 0; l < vm->life.size(); ++l) {
4000 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4005 if (f->blocks.size())
4007 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
4008 for (i = 0; i < f->blocks.size(); ++i) {
4009 ir_block_dump(f->blocks[i].get(), ind, oprintf);
4013 ind[strlen(ind)-1] = 0;
4014 oprintf("%sendfunction %s\n", ind, f->name.c_str());
4017 void ir_block_dump(ir_block* b, char *ind,
4018 int (*oprintf)(const char*, ...))
4021 oprintf("%s:%s\n", ind, b->label.c_str());
4022 util_strncat(ind, "\t", IND_BUFSZ-1);
4024 if (b->instr && b->instr[0])
4025 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
4026 for (i = 0; i < vec_size(b->instr); ++i)
4027 ir_instr_dump(b->instr[i], ind, oprintf);
4028 ind[strlen(ind)-1] = 0;
4031 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
4033 oprintf("%s <- phi ", in->_ops[0]->name.c_str());
4034 for (auto &it : in->phi) {
4035 oprintf("([%s] : %s) ", it.from->label.c_str(),
4036 it.value->name.c_str());
4041 void ir_instr_dump(ir_instr *in, char *ind,
4042 int (*oprintf)(const char*, ...))
4045 const char *comma = nullptr;
4047 oprintf("%s (%i) ", ind, (int)in->eid);
4049 if (in->opcode == VINSTR_PHI) {
4050 dump_phi(in, oprintf);
4054 util_strncat(ind, "\t", IND_BUFSZ-1);
4056 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
4057 ir_value_dump(in->_ops[0], oprintf);
4058 if (in->_ops[1] || in->_ops[2])
4061 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
4062 oprintf("CALL%i\t", in->params.size());
4064 oprintf("%s\t", qc_opname(in->opcode));
4066 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
4067 ir_value_dump(in->_ops[0], oprintf);
4072 for (i = 1; i != 3; ++i) {
4076 ir_value_dump(in->_ops[i], oprintf);
4084 oprintf("[%s]", in->bops[0]->label.c_str());
4088 oprintf("%s[%s]", comma, in->bops[1]->label.c_str());
4089 if (in->params.size()) {
4090 oprintf("\tparams: ");
4091 for (auto &it : in->params)
4092 oprintf("%s, ", it->name.c_str());
4095 ind[strlen(ind)-1] = 0;
4098 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
4101 for (; *str; ++str) {
4103 case '\n': oprintf("\\n"); break;
4104 case '\r': oprintf("\\r"); break;
4105 case '\t': oprintf("\\t"); break;
4106 case '\v': oprintf("\\v"); break;
4107 case '\f': oprintf("\\f"); break;
4108 case '\b': oprintf("\\b"); break;
4109 case '\a': oprintf("\\a"); break;
4110 case '\\': oprintf("\\\\"); break;
4111 case '"': oprintf("\\\""); break;
4112 default: oprintf("%c", *str); break;
4118 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4127 oprintf("fn:%s", v->name.c_str());
4130 oprintf("%g", v->constval.vfloat);
4133 oprintf("'%g %g %g'",
4136 v->constval.vvec.z);
4139 oprintf("(entity)");
4142 ir_value_dump_string(v->constval.vstring, oprintf);
4146 oprintf("%i", v->constval.vint);
4151 v->constval.vpointer->name.c_str());
4155 oprintf("%s", v->name.c_str());
4159 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4161 oprintf("Life of %12s:", self->name.c_str());
4162 for (size_t i = 0; i < self->life.size(); ++i)
4164 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);