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 ir_builder::ir_builder(const std::string& modulename)
277 : m_name(modulename),
280 m_htglobals = util_htnew(IR_HT_SIZE);
281 m_htfields = util_htnew(IR_HT_SIZE);
282 m_htfunctions = util_htnew(IR_HT_SIZE);
284 m_nil = new ir_value("nil", store_value, TYPE_NIL);
285 m_nil->m_cvq = CV_CONST;
287 for (size_t i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
288 /* we write to them, but they're not supposed to be used outside the IR, so
289 * let's not allow the generation of ir_instrs which use these.
290 * So it's a constant noexpr.
292 m_vinstr_temp[i] = new ir_value("vinstr_temp", store_value, TYPE_NOEXPR);
293 m_vinstr_temp[i]->m_cvq = CV_CONST;
297 ir_builder::~ir_builder()
299 util_htdel(m_htglobals);
300 util_htdel(m_htfields);
301 util_htdel(m_htfunctions);
302 for (auto& f : m_functions)
303 ir_function_delete_quick(f.release());
304 m_functions.clear(); // delete them now before deleting the rest:
308 for (size_t i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
309 delete m_vinstr_temp[i];
313 m_extparam_protos.clear();
316 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
318 return (ir_function*)util_htget(self->m_htfunctions, name);
321 ir_function* ir_builder_create_function(ir_builder *self, const std::string& name, qc_type outtype)
323 ir_function *fn = ir_builder_get_function(self, name.c_str());
328 fn = new ir_function(self, outtype);
330 self->m_functions.emplace_back(fn);
331 util_htset(self->m_htfunctions, name.c_str(), fn);
333 fn->m_value = ir_builder_create_global(self, fn->m_name, TYPE_FUNCTION);
339 fn->m_value->m_hasvalue = true;
340 fn->m_value->m_outtype = outtype;
341 fn->m_value->m_constval.vfunc = fn;
342 fn->m_value->m_context = fn->m_context;
347 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
349 return (ir_value*)util_htget(self->m_htglobals, name);
352 ir_value* ir_builder_create_global(ir_builder *self, const std::string& name, qc_type vtype)
358 ve = ir_builder_get_global(self, name.c_str());
364 ve = new ir_value(std::string(name), store_global, vtype);
365 self->m_globals.emplace_back(ve);
366 util_htset(self->m_htglobals, name.c_str(), ve);
370 ir_value* ir_builder_get_va_count(ir_builder *self)
372 if (self->m_reserved_va_count)
373 return self->m_reserved_va_count;
374 return (self->m_reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
377 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
379 return (ir_value*)util_htget(self->m_htfields, name);
383 ir_value* ir_builder_create_field(ir_builder *self, const std::string& name, qc_type vtype)
385 ir_value *ve = ir_builder_get_field(self, name.c_str());
390 ve = new ir_value(std::string(name), store_global, TYPE_FIELD);
391 ve->m_fieldtype = vtype;
392 self->m_fields.emplace_back(ve);
393 util_htset(self->m_htfields, name.c_str(), ve);
397 /***********************************************************************
401 static bool ir_function_naive_phi(ir_function*);
402 static void ir_function_enumerate(ir_function*);
403 static bool ir_function_calculate_liferanges(ir_function*);
404 static bool ir_function_allocate_locals(ir_function*);
406 ir_function::ir_function(ir_builder* owner_, qc_type outtype_)
408 m_name("<@unnamed>"),
411 m_context.file = "<@no context>";
415 ir_function::~ir_function()
419 static void ir_function_delete_quick(ir_function *self)
421 for (auto& b : self->m_blocks)
422 ir_block_delete_quick(b.release());
426 static void ir_function_collect_value(ir_function *self, ir_value *v)
428 self->m_values.emplace_back(v);
431 ir_block* ir_function_create_block(lex_ctx_t ctx, ir_function *self, const char *label)
433 ir_block* bn = new ir_block(self, label ? std::string(label) : std::string());
435 self->m_blocks.emplace_back(bn);
437 if ((self->m_flags & IR_FLAG_BLOCK_COVERAGE) && self->m_owner->m_coverage_func)
438 (void)ir_block_create_call(bn, ctx, nullptr, self->m_owner->m_coverage_func, false);
443 static bool instr_is_operation(uint16_t op)
445 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
446 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
447 (op == INSTR_ADDRESS) ||
448 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
449 (op >= INSTR_AND && op <= INSTR_BITOR) ||
450 (op >= INSTR_CALL0 && op <= INSTR_CALL8) ||
451 (op >= VINSTR_BITAND_V && op <= VINSTR_NEG_V) );
454 static bool ir_function_pass_peephole(ir_function *self)
456 for (auto& bp : self->m_blocks) {
457 ir_block *block = bp.get();
458 for (size_t i = 0; i < vec_size(block->m_instr); ++i) {
460 inst = block->m_instr[i];
463 (inst->m_opcode >= INSTR_STORE_F &&
464 inst->m_opcode <= INSTR_STORE_FNC))
472 oper = block->m_instr[i-1];
473 if (!instr_is_operation(oper->m_opcode))
476 /* Don't change semantics of MUL_VF in engines where these may not alias. */
477 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
478 if (oper->m_opcode == INSTR_MUL_VF && oper->_m_ops[2]->m_memberof == oper->_m_ops[1])
480 if (oper->m_opcode == INSTR_MUL_FV && oper->_m_ops[1]->m_memberof == oper->_m_ops[2])
484 value = oper->_m_ops[0];
486 /* only do it for SSA values */
487 if (value->m_store != store_value)
490 /* don't optimize out the temp if it's used later again */
491 if (value->m_reads.size() != 1)
494 /* The very next store must use this value */
495 if (value->m_reads[0] != store)
498 /* And of course the store must _read_ from it, so it's in
500 if (store->_m_ops[1] != value)
503 ++opts_optimizationcount[OPTIM_PEEPHOLE];
504 (void)!ir_instr_op(oper, 0, store->_m_ops[0], true);
506 vec_remove(block->m_instr, i, 1);
509 else if (inst->m_opcode == VINSTR_COND)
511 /* COND on a value resulting from a NOT could
512 * remove the NOT and swap its operands
519 value = inst->_m_ops[0];
521 if (value->m_store != store_value || value->m_reads.size() != 1 || value->m_reads[0] != inst)
524 inot = value->m_writes[0];
525 if (inot->_m_ops[0] != value ||
526 inot->m_opcode < INSTR_NOT_F ||
527 inot->m_opcode > INSTR_NOT_FNC ||
528 inot->m_opcode == INSTR_NOT_V || /* can't do these */
529 inot->m_opcode == INSTR_NOT_S)
535 ++opts_optimizationcount[OPTIM_PEEPHOLE];
537 (void)!ir_instr_op(inst, 0, inot->_m_ops[1], false);
540 for (inotid = 0; inotid < vec_size(tmp->m_instr); ++inotid) {
541 if (tmp->m_instr[inotid] == inot)
544 if (inotid >= vec_size(tmp->m_instr)) {
545 compile_error(inst->m_context, "sanity-check failed: failed to find instruction to optimize out");
548 vec_remove(tmp->m_instr, inotid, 1);
550 /* swap ontrue/onfalse */
551 tmp = inst->m_bops[0];
552 inst->m_bops[0] = inst->m_bops[1];
553 inst->m_bops[1] = tmp;
563 static bool ir_function_pass_tailrecursion(ir_function *self)
567 for (auto& bp : self->m_blocks) {
568 ir_block *block = bp.get();
571 ir_instr *ret, *call, *store = nullptr;
573 if (!block->m_final || vec_size(block->m_instr) < 2)
576 ret = block->m_instr[vec_size(block->m_instr)-1];
577 if (ret->m_opcode != INSTR_DONE && ret->m_opcode != INSTR_RETURN)
580 call = block->m_instr[vec_size(block->m_instr)-2];
581 if (call->m_opcode >= INSTR_STORE_F && call->m_opcode <= INSTR_STORE_FNC) {
582 /* account for the unoptimized
584 * STORE %return, %tmp
588 if (vec_size(block->m_instr) < 3)
592 call = block->m_instr[vec_size(block->m_instr)-3];
595 if (call->m_opcode < INSTR_CALL0 || call->m_opcode > INSTR_CALL8)
599 /* optimize out the STORE */
600 if (ret->_m_ops[0] &&
601 ret->_m_ops[0] == store->_m_ops[0] &&
602 store->_m_ops[1] == call->_m_ops[0])
604 ++opts_optimizationcount[OPTIM_PEEPHOLE];
605 call->_m_ops[0] = store->_m_ops[0];
606 vec_remove(block->m_instr, vec_size(block->m_instr) - 2, 1);
613 if (!call->_m_ops[0])
616 funcval = call->_m_ops[1];
619 if (funcval->m_vtype != TYPE_FUNCTION || funcval->m_constval.vfunc != self)
622 /* now we have a CALL and a RET, check if it's a tailcall */
623 if (ret->_m_ops[0] && call->_m_ops[0] != ret->_m_ops[0])
626 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
627 vec_shrinkby(block->m_instr, 2);
629 block->m_final = false; /* open it back up */
631 /* emite parameter-stores */
632 for (p = 0; p < call->m_params.size(); ++p) {
633 /* assert(call->params_count <= self->locals_count); */
634 if (!ir_block_create_store(block, call->m_context, self->m_locals[p].get(), call->m_params[p])) {
635 irerror(call->m_context, "failed to create tailcall store instruction for parameter %i", (int)p);
639 if (!ir_block_create_jump(block, call->m_context, self->m_blocks[0].get())) {
640 irerror(call->m_context, "failed to create tailcall jump");
651 bool ir_function_finalize(ir_function *self)
656 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
657 if (!ir_function_pass_peephole(self)) {
658 irerror(self->m_context, "generic optimization pass broke something in `%s`", self->m_name.c_str());
663 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
664 if (!ir_function_pass_tailrecursion(self)) {
665 irerror(self->m_context, "tail-recursion optimization pass broke something in `%s`", self->m_name.c_str());
670 if (!ir_function_naive_phi(self)) {
671 irerror(self->m_context, "internal error: ir_function_naive_phi failed");
675 for (auto& lp : self->m_locals) {
676 ir_value *v = lp.get();
677 if (v->m_vtype == TYPE_VECTOR ||
678 (v->m_vtype == TYPE_FIELD && v->m_outtype == TYPE_VECTOR))
680 ir_value_vector_member(v, 0);
681 ir_value_vector_member(v, 1);
682 ir_value_vector_member(v, 2);
685 for (auto& vp : self->m_values) {
686 ir_value *v = vp.get();
687 if (v->m_vtype == TYPE_VECTOR ||
688 (v->m_vtype == TYPE_FIELD && v->m_outtype == TYPE_VECTOR))
690 ir_value_vector_member(v, 0);
691 ir_value_vector_member(v, 1);
692 ir_value_vector_member(v, 2);
696 ir_function_enumerate(self);
698 if (!ir_function_calculate_liferanges(self))
700 if (!ir_function_allocate_locals(self))
705 ir_value* ir_function_create_local(ir_function *self, const std::string& name, qc_type vtype, bool param)
710 !self->m_locals.empty() &&
711 self->m_locals.back()->m_store != store_param)
713 irerror(self->m_context, "cannot add parameters after adding locals");
717 ve = new ir_value(std::string(name), (param ? store_param : store_local), vtype);
720 self->m_locals.emplace_back(ve);
724 /***********************************************************************
728 ir_block::ir_block(ir_function* owner, const std::string& name)
732 m_context.file = "<@no context>";
736 ir_block::~ir_block()
738 for (size_t i = 0; i != vec_size(m_instr); ++i)
745 static void ir_block_delete_quick(ir_block* self)
748 for (i = 0; i != vec_size(self->m_instr); ++i)
749 ir_instr_delete_quick(self->m_instr[i]);
750 vec_free(self->m_instr);
754 /***********************************************************************
758 ir_instr::ir_instr(lex_ctx_t ctx, ir_block* owner_, int op)
765 ir_instr::~ir_instr()
767 // The following calls can only delete from
768 // vectors, we still want to delete this instruction
769 // so ignore the return value. Since with the warn_unused_result attribute
770 // gcc doesn't care about an explicit: (void)foo(); to ignore the result,
771 // I have to improvise here and use if(foo());
772 for (auto &it : m_phi) {
774 if (vec_ir_instr_find(it.value->m_writes, this, &idx))
775 it.value->m_writes.erase(it.value->m_writes.begin() + idx);
776 if (vec_ir_instr_find(it.value->m_reads, this, &idx))
777 it.value->m_reads.erase(it.value->m_reads.begin() + idx);
779 for (auto &it : m_params) {
781 if (vec_ir_instr_find(it->m_writes, this, &idx))
782 it->m_writes.erase(it->m_writes.begin() + idx);
783 if (vec_ir_instr_find(it->m_reads, this, &idx))
784 it->m_reads.erase(it->m_reads.begin() + idx);
786 (void)!ir_instr_op(this, 0, nullptr, false);
787 (void)!ir_instr_op(this, 1, nullptr, false);
788 (void)!ir_instr_op(this, 2, nullptr, false);
791 static void ir_instr_delete_quick(ir_instr *self)
794 self->m_params.clear();
798 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
800 if (v && v->m_vtype == TYPE_NOEXPR) {
801 irerror(self->m_context, "tried to use a NOEXPR value");
805 if (self->_m_ops[op]) {
807 if (writing && vec_ir_instr_find(self->_m_ops[op]->m_writes, self, &idx))
808 self->_m_ops[op]->m_writes.erase(self->_m_ops[op]->m_writes.begin() + idx);
809 else if (vec_ir_instr_find(self->_m_ops[op]->m_reads, self, &idx))
810 self->_m_ops[op]->m_reads.erase(self->_m_ops[op]->m_reads.begin() + idx);
814 v->m_writes.push_back(self);
816 v->m_reads.push_back(self);
818 self->_m_ops[op] = v;
822 /***********************************************************************
826 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
828 self->m_code.globaladdr = gaddr;
829 if (self->m_members[0]) self->m_members[0]->m_code.globaladdr = gaddr;
830 if (self->m_members[1]) self->m_members[1]->m_code.globaladdr = gaddr;
831 if (self->m_members[2]) self->m_members[2]->m_code.globaladdr = gaddr;
834 static int32_t ir_value_code_addr(const ir_value *self)
836 if (self->m_store == store_return)
837 return OFS_RETURN + self->m_code.addroffset;
838 return self->m_code.globaladdr + self->m_code.addroffset;
841 ir_value::ir_value(std::string&& name_, store_type store_, qc_type vtype_)
842 : m_name(move(name_)),
846 m_fieldtype = TYPE_VOID;
847 m_outtype = TYPE_VOID;
852 m_context.file = "<@no context>";
855 memset(&m_constval, 0, sizeof(m_constval));
856 memset(&m_code, 0, sizeof(m_code));
858 m_members[0] = nullptr;
859 m_members[1] = nullptr;
860 m_members[2] = nullptr;
861 m_memberof = nullptr;
863 m_unique_life = false;
868 ir_value::~ir_value()
872 if (m_vtype == TYPE_STRING)
873 mem_d((void*)m_constval.vstring);
875 if (!(m_flags & IR_FLAG_SPLIT_VECTOR)) {
876 for (i = 0; i < 3; ++i) {
884 /* helper function */
885 static ir_value* ir_builder_imm_float(ir_builder *self, float value, bool add_to_list) {
886 ir_value *v = new ir_value("#IMMEDIATE", store_global, TYPE_FLOAT);
887 v->m_flags |= IR_FLAG_ERASABLE;
888 v->m_hasvalue = true;
890 v->m_constval.vfloat = value;
892 self->m_globals.emplace_back(v);
894 self->m_const_floats.emplace_back(v);
898 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
905 if (self->m_members[member])
906 return self->m_members[member];
908 if (!self->m_name.empty()) {
909 char member_name[3] = { '_', char('x' + member), 0 };
910 name = self->m_name + member_name;
913 if (self->m_vtype == TYPE_VECTOR)
915 m = new ir_value(move(name), self->m_store, TYPE_FLOAT);
918 m->m_context = self->m_context;
920 self->m_members[member] = m;
921 m->m_code.addroffset = member;
923 else if (self->m_vtype == TYPE_FIELD)
925 if (self->m_fieldtype != TYPE_VECTOR)
927 m = new ir_value(move(name), self->m_store, TYPE_FIELD);
930 m->m_fieldtype = TYPE_FLOAT;
931 m->m_context = self->m_context;
933 self->m_members[member] = m;
934 m->m_code.addroffset = member;
938 irerror(self->m_context, "invalid member access on %s", self->m_name.c_str());
942 m->m_memberof = self;
946 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
948 if (self->m_vtype == TYPE_FIELD && self->m_fieldtype == TYPE_VECTOR)
949 return type_sizeof_[TYPE_VECTOR];
950 return type_sizeof_[self->m_vtype];
953 static ir_value* ir_value_out(ir_function *owner, const char *name, store_type storetype, qc_type vtype)
955 ir_value *v = new ir_value(name ? std::string(name) : std::string(), storetype, vtype);
958 ir_function_collect_value(owner, v);
962 bool ir_value_set_float(ir_value *self, float f)
964 if (self->m_vtype != TYPE_FLOAT)
966 self->m_constval.vfloat = f;
967 self->m_hasvalue = true;
971 bool ir_value_set_func(ir_value *self, int f)
973 if (self->m_vtype != TYPE_FUNCTION)
975 self->m_constval.vint = f;
976 self->m_hasvalue = true;
980 bool ir_value_set_vector(ir_value *self, vec3_t v)
982 if (self->m_vtype != TYPE_VECTOR)
984 self->m_constval.vvec = v;
985 self->m_hasvalue = true;
989 bool ir_value_set_field(ir_value *self, ir_value *fld)
991 if (self->m_vtype != TYPE_FIELD)
993 self->m_constval.vpointer = fld;
994 self->m_hasvalue = true;
998 bool ir_value_set_string(ir_value *self, const char *str)
1000 if (self->m_vtype != TYPE_STRING)
1002 self->m_constval.vstring = util_strdupe(str);
1003 self->m_hasvalue = true;
1008 bool ir_value_set_int(ir_value *self, int i)
1010 if (self->m_vtype != TYPE_INTEGER)
1012 self->m_constval.vint = i;
1013 self->m_hasvalue = true;
1018 bool ir_value_lives(ir_value *self, size_t at)
1020 for (auto& l : self->m_life) {
1021 if (l.start <= at && at <= l.end)
1023 if (l.start > at) /* since it's ordered */
1029 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1031 self->m_life.insert(self->m_life.begin() + idx, e);
1035 static bool ir_value_life_merge(ir_value *self, size_t s)
1038 const size_t vs = self->m_life.size();
1039 ir_life_entry_t *life_found = nullptr;
1040 ir_life_entry_t *before = nullptr;
1041 ir_life_entry_t new_entry;
1043 /* Find the first range >= s */
1044 for (i = 0; i < vs; ++i)
1046 before = life_found;
1047 life_found = &self->m_life[i];
1048 if (life_found->start > s)
1051 /* nothing found? append */
1054 if (life_found && life_found->end+1 == s)
1056 /* previous life range can be merged in */
1060 if (life_found && life_found->end >= s)
1062 e.start = e.end = s;
1063 self->m_life.emplace_back(e);
1069 if (before->end + 1 == s &&
1070 life_found->start - 1 == s)
1073 before->end = life_found->end;
1074 self->m_life.erase(self->m_life.begin()+i);
1077 if (before->end + 1 == s)
1083 /* already contained */
1084 if (before->end >= s)
1088 if (life_found->start - 1 == s)
1090 life_found->start--;
1093 /* insert a new entry */
1094 new_entry.start = new_entry.end = s;
1095 return ir_value_life_insert(self, i, new_entry);
1098 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1102 if (other->m_life.empty())
1105 if (self->m_life.empty()) {
1106 self->m_life = other->m_life;
1111 for (i = 0; i < other->m_life.size(); ++i)
1113 const ir_life_entry_t &otherlife = other->m_life[i];
1116 ir_life_entry_t *entry = &self->m_life[myi];
1118 if (otherlife.end+1 < entry->start)
1120 /* adding an interval before entry */
1121 if (!ir_value_life_insert(self, myi, otherlife))
1127 if (otherlife.start < entry->start &&
1128 otherlife.end+1 >= entry->start)
1130 /* starts earlier and overlaps */
1131 entry->start = otherlife.start;
1134 if (otherlife.end > entry->end &&
1135 otherlife.start <= entry->end+1)
1137 /* ends later and overlaps */
1138 entry->end = otherlife.end;
1141 /* see if our change combines it with the next ranges */
1142 while (myi+1 < self->m_life.size() &&
1143 entry->end+1 >= self->m_life[1+myi].start)
1145 /* overlaps with (myi+1) */
1146 if (entry->end < self->m_life[1+myi].end)
1147 entry->end = self->m_life[1+myi].end;
1148 self->m_life.erase(self->m_life.begin() + (myi + 1));
1149 entry = &self->m_life[myi];
1152 /* see if we're after the entry */
1153 if (otherlife.start > entry->end)
1156 /* append if we're at the end */
1157 if (myi >= self->m_life.size()) {
1158 self->m_life.emplace_back(otherlife);
1161 /* otherweise check the next range */
1170 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1172 /* For any life entry in A see if it overlaps with
1173 * any life entry in B.
1174 * Note that the life entries are orderes, so we can make a
1175 * more efficient algorithm there than naively translating the
1179 const ir_life_entry_t *la, *lb, *enda, *endb;
1181 /* first of all, if either has no life range, they cannot clash */
1182 if (a->m_life.empty() || b->m_life.empty())
1185 la = &a->m_life.front();
1186 lb = &b->m_life.front();
1187 enda = &a->m_life.back() + 1;
1188 endb = &b->m_life.back() + 1;
1191 /* check if the entries overlap, for that,
1192 * both must start before the other one ends.
1194 if (la->start < lb->end &&
1195 lb->start < la->end)
1200 /* entries are ordered
1201 * one entry is earlier than the other
1202 * that earlier entry will be moved forward
1204 if (la->start < lb->start)
1206 /* order: A B, move A forward
1207 * check if we hit the end with A
1212 else /* if (lb->start < la->start) actually <= */
1214 /* order: B A, move B forward
1215 * check if we hit the end with B
1224 /***********************************************************************
1228 static bool ir_check_unreachable(ir_block *self)
1230 /* The IR should never have to deal with unreachable code */
1231 if (!self->m_final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1233 irerror(self->m_context, "unreachable statement (%s)", self->m_label.c_str());
1237 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1240 if (!ir_check_unreachable(self))
1243 if (target->m_store == store_value &&
1244 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1246 irerror(self->m_context, "cannot store to an SSA value");
1247 irerror(self->m_context, "trying to store: %s <- %s", target->m_name.c_str(), what->m_name.c_str());
1248 irerror(self->m_context, "instruction: %s", util_instr_str[op]);
1252 in = new ir_instr(ctx, self, op);
1256 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1257 !ir_instr_op(in, 1, what, false))
1262 vec_push(self->m_instr, in);
1266 bool ir_block_create_state_op(ir_block *self, lex_ctx_t ctx, ir_value *frame, ir_value *think)
1269 if (!ir_check_unreachable(self))
1272 in = new ir_instr(ctx, self, INSTR_STATE);
1276 if (!ir_instr_op(in, 0, frame, false) ||
1277 !ir_instr_op(in, 1, think, false))
1282 vec_push(self->m_instr, in);
1286 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1290 if (target->m_vtype == TYPE_VARIANT)
1291 vtype = what->m_vtype;
1293 vtype = target->m_vtype;
1296 if (vtype == TYPE_FLOAT && what->m_vtype == TYPE_INTEGER)
1297 op = INSTR_CONV_ITOF;
1298 else if (vtype == TYPE_INTEGER && what->m_vtype == TYPE_FLOAT)
1299 op = INSTR_CONV_FTOI;
1301 op = type_store_instr[vtype];
1303 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1304 if (op == INSTR_STORE_FLD && what->m_fieldtype == TYPE_VECTOR)
1308 return ir_block_create_store_op(self, ctx, op, target, what);
1311 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1316 if (target->m_vtype != TYPE_POINTER)
1319 /* storing using pointer - target is a pointer, type must be
1320 * inferred from source
1322 vtype = what->m_vtype;
1324 op = type_storep_instr[vtype];
1325 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1326 if (op == INSTR_STOREP_FLD && what->m_fieldtype == TYPE_VECTOR)
1327 op = INSTR_STOREP_V;
1330 return ir_block_create_store_op(self, ctx, op, target, what);
1333 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1336 if (!ir_check_unreachable(self))
1339 self->m_final = true;
1341 self->m_is_return = true;
1342 in = new ir_instr(ctx, self, INSTR_RETURN);
1346 if (v && !ir_instr_op(in, 0, v, false)) {
1351 vec_push(self->m_instr, in);
1355 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1356 ir_block *ontrue, ir_block *onfalse)
1359 if (!ir_check_unreachable(self))
1361 self->m_final = true;
1362 /*in = new ir_instr(ctx, self, (v->m_vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1363 in = new ir_instr(ctx, self, VINSTR_COND);
1367 if (!ir_instr_op(in, 0, v, false)) {
1372 in->m_bops[0] = ontrue;
1373 in->m_bops[1] = onfalse;
1375 vec_push(self->m_instr, in);
1377 vec_push(self->m_exits, ontrue);
1378 vec_push(self->m_exits, onfalse);
1379 vec_push(ontrue->m_entries, self);
1380 vec_push(onfalse->m_entries, self);
1384 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1387 if (!ir_check_unreachable(self))
1389 self->m_final = true;
1390 in = new ir_instr(ctx, self, VINSTR_JUMP);
1395 vec_push(self->m_instr, in);
1397 vec_push(self->m_exits, to);
1398 vec_push(to->m_entries, self);
1402 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1404 self->m_owner->m_flags |= IR_FLAG_HAS_GOTO;
1405 return ir_block_create_jump(self, ctx, to);
1408 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, qc_type ot)
1412 if (!ir_check_unreachable(self))
1414 in = new ir_instr(ctx, self, VINSTR_PHI);
1417 out = ir_value_out(self->m_owner, label, store_value, ot);
1422 if (!ir_instr_op(in, 0, out, true)) {
1426 vec_push(self->m_instr, in);
1430 ir_value* ir_phi_value(ir_instr *self)
1432 return self->_m_ops[0];
1435 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1439 if (!vec_ir_block_find(self->m_owner->m_entries, b, nullptr)) {
1440 // Must not be possible to cause this, otherwise the AST
1441 // is doing something wrong.
1442 irerror(self->m_context, "Invalid entry block for PHI");
1448 v->m_reads.push_back(self);
1449 self->m_phi.push_back(pe);
1452 /* call related code */
1453 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1457 if (!ir_check_unreachable(self))
1459 in = new ir_instr(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1463 self->m_final = true;
1464 self->m_is_return = true;
1466 out = ir_value_out(self->m_owner, label, (func->m_outtype == TYPE_VOID) ? store_return : store_value, func->m_outtype);
1471 if (!ir_instr_op(in, 0, out, true) ||
1472 !ir_instr_op(in, 1, func, false))
1477 vec_push(self->m_instr, in);
1480 if (!ir_block_create_return(self, ctx, nullptr)) {
1481 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1490 ir_value* ir_call_value(ir_instr *self)
1492 return self->_m_ops[0];
1495 void ir_call_param(ir_instr* self, ir_value *v)
1497 self->m_params.push_back(v);
1498 v->m_reads.push_back(self);
1501 /* binary op related code */
1503 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1504 const char *label, int opcode,
1505 ir_value *left, ir_value *right)
1507 qc_type ot = TYPE_VOID;
1528 case INSTR_SUB_S: /* -- offset of string as float */
1533 case INSTR_BITOR_IF:
1534 case INSTR_BITOR_FI:
1535 case INSTR_BITAND_FI:
1536 case INSTR_BITAND_IF:
1551 case INSTR_BITAND_I:
1554 case INSTR_RSHIFT_I:
1555 case INSTR_LSHIFT_I:
1563 case VINSTR_BITAND_V:
1564 case VINSTR_BITOR_V:
1565 case VINSTR_BITXOR_V:
1566 case VINSTR_BITAND_VF:
1567 case VINSTR_BITOR_VF:
1568 case VINSTR_BITXOR_VF:
1583 * after the following default case, the value of opcode can never
1584 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1588 /* boolean operations result in floats */
1591 * opcode >= 10 takes true branch opcode is at least 10
1592 * opcode <= 23 takes false branch opcode is at least 24
1594 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1598 * At condition "opcode <= 23", the value of "opcode" must be
1600 * At condition "opcode <= 23", the value of "opcode" cannot be
1601 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1602 * The condition "opcode <= 23" cannot be true.
1604 * Thus ot=2 (TYPE_FLOAT) can never be true
1607 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1609 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1614 if (ot == TYPE_VOID) {
1615 /* The AST or parser were supposed to check this! */
1619 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1622 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1623 const char *label, int opcode,
1626 qc_type ot = TYPE_FLOAT;
1632 case INSTR_NOT_FNC: /*
1633 case INSTR_NOT_I: */
1638 * Negation for virtual instructions is emulated with 0-value. Thankfully
1639 * the operand for 0 already exists so we just source it from here.
1642 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_F, nullptr, operand, ot);
1644 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_V, nullptr, operand, TYPE_VECTOR);
1647 ot = operand->m_vtype;
1650 if (ot == TYPE_VOID) {
1651 /* The AST or parser were supposed to check this! */
1655 /* let's use the general instruction creator and pass nullptr for OPB */
1656 return ir_block_create_general_instr(self, ctx, label, opcode, operand, nullptr, ot);
1659 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1660 int op, ir_value *a, ir_value *b, qc_type outype)
1665 out = ir_value_out(self->m_owner, label, store_value, outype);
1669 instr = new ir_instr(ctx, self, op);
1674 if (!ir_instr_op(instr, 0, out, true) ||
1675 !ir_instr_op(instr, 1, a, false) ||
1676 !ir_instr_op(instr, 2, b, false) )
1681 vec_push(self->m_instr, instr);
1689 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1693 /* Support for various pointer types todo if so desired */
1694 if (ent->m_vtype != TYPE_ENTITY)
1697 if (field->m_vtype != TYPE_FIELD)
1700 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1701 v->m_fieldtype = field->m_fieldtype;
1705 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)
1708 if (ent->m_vtype != TYPE_ENTITY)
1711 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1712 if (field->m_vtype != TYPE_FIELD)
1717 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1718 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1719 case TYPE_STRING: op = INSTR_LOAD_S; break;
1720 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1721 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1722 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1724 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1725 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1728 irerror(self->m_context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1732 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1735 /* PHI resolving breaks the SSA, and must thus be the last
1736 * step before life-range calculation.
1739 static bool ir_block_naive_phi(ir_block *self);
1740 bool ir_function_naive_phi(ir_function *self)
1742 for (auto& b : self->m_blocks)
1743 if (!ir_block_naive_phi(b.get()))
1748 static bool ir_block_naive_phi(ir_block *self)
1751 /* FIXME: optionally, create_phi can add the phis
1752 * to a list so we don't need to loop through blocks
1753 * - anyway: "don't optimize YET"
1755 for (i = 0; i < vec_size(self->m_instr); ++i)
1757 ir_instr *instr = self->m_instr[i];
1758 if (instr->m_opcode != VINSTR_PHI)
1761 vec_remove(self->m_instr, i, 1);
1762 --i; /* NOTE: i+1 below */
1764 for (auto &it : instr->m_phi) {
1765 ir_value *v = it.value;
1766 ir_block *b = it.from;
1767 if (v->m_store == store_value && v->m_reads.size() == 1 && v->m_writes.size() == 1) {
1768 /* replace the value */
1769 if (!ir_instr_op(v->m_writes[0], 0, instr->_m_ops[0], true))
1772 /* force a move instruction */
1773 ir_instr *prevjump = vec_last(b->m_instr);
1774 vec_pop(b->m_instr);
1776 instr->_m_ops[0]->m_store = store_global;
1777 if (!ir_block_create_store(b, instr->m_context, instr->_m_ops[0], v))
1779 instr->_m_ops[0]->m_store = store_value;
1780 vec_push(b->m_instr, prevjump);
1789 /***********************************************************************
1790 *IR Temp allocation code
1791 * Propagating value life ranges by walking through the function backwards
1792 * until no more changes are made.
1793 * In theory this should happen once more than once for every nested loop
1795 * Though this implementation might run an additional time for if nests.
1798 /* Enumerate instructions used by value's life-ranges
1800 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1804 for (i = 0; i < vec_size(self->m_instr); ++i)
1806 self->m_instr[i]->m_eid = eid++;
1811 /* Enumerate blocks and instructions.
1812 * The block-enumeration is unordered!
1813 * We do not really use the block enumreation, however
1814 * the instruction enumeration is important for life-ranges.
1816 void ir_function_enumerate(ir_function *self)
1818 size_t instruction_id = 0;
1819 size_t block_eid = 0;
1820 for (auto& block : self->m_blocks)
1822 /* each block now gets an additional "entry" instruction id
1823 * we can use to avoid point-life issues
1825 block->m_entry_id = instruction_id;
1826 block->m_eid = block_eid;
1830 ir_block_enumerate(block.get(), &instruction_id);
1834 /* Local-value allocator
1835 * After finishing creating the liferange of all values used in a function
1836 * we can allocate their global-positions.
1837 * This is the counterpart to register-allocation in register machines.
1839 struct function_allocator {
1846 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
1849 size_t vsize = ir_value_sizeof(var);
1851 var->m_code.local = vec_size(alloc->locals);
1853 slot = new ir_value("reg", store_global, var->m_vtype);
1857 if (!ir_value_life_merge_into(slot, var))
1860 vec_push(alloc->locals, slot);
1861 vec_push(alloc->sizes, vsize);
1862 vec_push(alloc->unique, var->m_unique_life);
1871 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
1876 if (v->m_unique_life)
1877 return function_allocator_alloc(alloc, v);
1879 for (a = 0; a < vec_size(alloc->locals); ++a)
1881 /* if it's reserved for a unique liferange: skip */
1882 if (alloc->unique[a])
1885 slot = alloc->locals[a];
1887 /* never resize parameters
1888 * will be required later when overlapping temps + locals
1890 if (a < vec_size(self->m_params) &&
1891 alloc->sizes[a] < ir_value_sizeof(v))
1896 if (ir_values_overlap(v, slot))
1899 if (!ir_value_life_merge_into(slot, v))
1902 /* adjust size for this slot */
1903 if (alloc->sizes[a] < ir_value_sizeof(v))
1904 alloc->sizes[a] = ir_value_sizeof(v);
1906 v->m_code.local = a;
1909 if (a >= vec_size(alloc->locals)) {
1910 if (!function_allocator_alloc(alloc, v))
1916 bool ir_function_allocate_locals(ir_function *self)
1920 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
1922 function_allocator lockalloc, globalloc;
1924 if (self->m_locals.empty() && self->m_values.empty())
1927 globalloc.locals = nullptr;
1928 globalloc.sizes = nullptr;
1929 globalloc.positions = nullptr;
1930 globalloc.unique = nullptr;
1931 lockalloc.locals = nullptr;
1932 lockalloc.sizes = nullptr;
1933 lockalloc.positions = nullptr;
1934 lockalloc.unique = nullptr;
1937 for (i = 0; i < self->m_locals.size(); ++i)
1939 ir_value *v = self->m_locals[i].get();
1940 if ((self->m_flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
1942 v->m_unique_life = true;
1944 else if (i >= vec_size(self->m_params))
1947 v->m_locked = true; /* lock parameters locals */
1948 if (!function_allocator_alloc((v->m_locked || !opt_gt ? &lockalloc : &globalloc), v))
1951 for (; i < self->m_locals.size(); ++i)
1953 ir_value *v = self->m_locals[i].get();
1954 if (v->m_life.empty())
1956 if (!ir_function_allocator_assign(self, (v->m_locked || !opt_gt ? &lockalloc : &globalloc), v))
1960 /* Allocate a slot for any value that still exists */
1961 for (i = 0; i < self->m_values.size(); ++i)
1963 ir_value *v = self->m_values[i].get();
1965 if (v->m_life.empty())
1968 /* CALL optimization:
1969 * If the value is a parameter-temp: 1 write, 1 read from a CALL
1970 * and it's not "locked", write it to the OFS_PARM directly.
1972 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->m_locked && !v->m_unique_life) {
1973 if (v->m_reads.size() == 1 && v->m_writes.size() == 1 &&
1974 (v->m_reads[0]->m_opcode == VINSTR_NRCALL ||
1975 (v->m_reads[0]->m_opcode >= INSTR_CALL0 && v->m_reads[0]->m_opcode <= INSTR_CALL8)
1980 ir_instr *call = v->m_reads[0];
1981 if (!vec_ir_value_find(call->m_params, v, ¶m)) {
1982 irerror(call->m_context, "internal error: unlocked parameter %s not found", v->m_name.c_str());
1985 ++opts_optimizationcount[OPTIM_CALL_STORES];
1986 v->m_callparam = true;
1988 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
1990 size_t nprotos = self->m_owner->m_extparam_protos.size();
1993 if (nprotos > param)
1994 ep = self->m_owner->m_extparam_protos[param].get();
1997 ep = ir_gen_extparam_proto(self->m_owner);
1998 while (++nprotos <= param)
1999 ep = ir_gen_extparam_proto(self->m_owner);
2001 ir_instr_op(v->m_writes[0], 0, ep, true);
2002 call->m_params[param+8] = ep;
2006 if (v->m_writes.size() == 1 && v->m_writes[0]->m_opcode == INSTR_CALL0) {
2007 v->m_store = store_return;
2008 if (v->m_members[0]) v->m_members[0]->m_store = store_return;
2009 if (v->m_members[1]) v->m_members[1]->m_store = store_return;
2010 if (v->m_members[2]) v->m_members[2]->m_store = store_return;
2011 ++opts_optimizationcount[OPTIM_CALL_STORES];
2016 if (!ir_function_allocator_assign(self, (v->m_locked || !opt_gt ? &lockalloc : &globalloc), v))
2020 if (!lockalloc.sizes && !globalloc.sizes) {
2023 vec_push(lockalloc.positions, 0);
2024 vec_push(globalloc.positions, 0);
2026 /* Adjust slot positions based on sizes */
2027 if (lockalloc.sizes) {
2028 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2029 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2031 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2032 vec_push(lockalloc.positions, pos);
2034 self->m_allocated_locals = pos + vec_last(lockalloc.sizes);
2036 if (globalloc.sizes) {
2037 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2038 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2040 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2041 vec_push(globalloc.positions, pos);
2043 self->m_globaltemps = pos + vec_last(globalloc.sizes);
2046 /* Locals need to know their new position */
2047 for (auto& local : self->m_locals) {
2048 if (local->m_locked || !opt_gt)
2049 local->m_code.local = lockalloc.positions[local->m_code.local];
2051 local->m_code.local = globalloc.positions[local->m_code.local];
2053 /* Take over the actual slot positions on values */
2054 for (auto& value : self->m_values) {
2055 if (value->m_locked || !opt_gt)
2056 value->m_code.local = lockalloc.positions[value->m_code.local];
2058 value->m_code.local = globalloc.positions[value->m_code.local];
2066 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2067 delete lockalloc.locals[i];
2068 for (i = 0; i < vec_size(globalloc.locals); ++i)
2069 delete globalloc.locals[i];
2070 vec_free(globalloc.unique);
2071 vec_free(globalloc.locals);
2072 vec_free(globalloc.sizes);
2073 vec_free(globalloc.positions);
2074 vec_free(lockalloc.unique);
2075 vec_free(lockalloc.locals);
2076 vec_free(lockalloc.sizes);
2077 vec_free(lockalloc.positions);
2081 /* Get information about which operand
2082 * is read from, or written to.
2084 static void ir_op_read_write(int op, size_t *read, size_t *write)
2104 case INSTR_STOREP_F:
2105 case INSTR_STOREP_V:
2106 case INSTR_STOREP_S:
2107 case INSTR_STOREP_ENT:
2108 case INSTR_STOREP_FLD:
2109 case INSTR_STOREP_FNC:
2120 static bool ir_block_living_add_instr(ir_block *self, size_t eid) {
2121 bool changed = false;
2122 for (auto &it : self->m_living)
2123 if (ir_value_life_merge(it, eid))
2128 static bool ir_block_living_lock(ir_block *self) {
2129 bool changed = false;
2130 for (auto &it : self->m_living) {
2133 it->m_locked = true;
2139 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2143 size_t i, o, p, mem;
2144 // bitmasks which operands are read from or written to
2147 self->m_living.clear();
2149 p = vec_size(self->m_exits);
2150 for (i = 0; i < p; ++i) {
2151 ir_block *prev = self->m_exits[i];
2152 for (auto &it : prev->m_living)
2153 if (!vec_ir_value_find(self->m_living, it, nullptr))
2154 self->m_living.push_back(it);
2157 i = vec_size(self->m_instr);
2160 instr = self->m_instr[i];
2162 /* See which operands are read and write operands */
2163 ir_op_read_write(instr->m_opcode, &read, &write);
2165 /* Go through the 3 main operands
2166 * writes first, then reads
2168 for (o = 0; o < 3; ++o)
2170 if (!instr->_m_ops[o]) /* no such operand */
2173 value = instr->_m_ops[o];
2175 /* We only care about locals */
2176 /* we also calculate parameter liferanges so that locals
2177 * can take up parameter slots */
2178 if (value->m_store != store_value &&
2179 value->m_store != store_local &&
2180 value->m_store != store_param)
2183 /* write operands */
2184 /* When we write to a local, we consider it "dead" for the
2185 * remaining upper part of the function, since in SSA a value
2186 * can only be written once (== created)
2191 bool in_living = vec_ir_value_find(self->m_living, value, &idx);
2194 /* If the value isn't alive it hasn't been read before... */
2195 /* TODO: See if the warning can be emitted during parsing or AST processing
2196 * otherwise have warning printed here.
2197 * IF printing a warning here: include filecontext_t,
2198 * and make sure it's only printed once
2199 * since this function is run multiple times.
2201 /* con_err( "Value only written %s\n", value->m_name); */
2202 if (ir_value_life_merge(value, instr->m_eid))
2205 /* since 'living' won't contain it
2206 * anymore, merge the value, since
2209 if (ir_value_life_merge(value, instr->m_eid))
2212 self->m_living.erase(self->m_living.begin() + idx);
2214 /* Removing a vector removes all members */
2215 for (mem = 0; mem < 3; ++mem) {
2216 if (value->m_members[mem] && vec_ir_value_find(self->m_living, value->m_members[mem], &idx)) {
2217 if (ir_value_life_merge(value->m_members[mem], instr->m_eid))
2219 self->m_living.erase(self->m_living.begin() + idx);
2222 /* Removing the last member removes the vector */
2223 if (value->m_memberof) {
2224 value = value->m_memberof;
2225 for (mem = 0; mem < 3; ++mem) {
2226 if (value->m_members[mem] && vec_ir_value_find(self->m_living, value->m_members[mem], nullptr))
2229 if (mem == 3 && vec_ir_value_find(self->m_living, value, &idx)) {
2230 if (ir_value_life_merge(value, instr->m_eid))
2232 self->m_living.erase(self->m_living.begin() + idx);
2238 /* These operations need a special case as they can break when using
2239 * same source and destination operand otherwise, as the engine may
2240 * read the source multiple times. */
2241 if (instr->m_opcode == INSTR_MUL_VF ||
2242 instr->m_opcode == VINSTR_BITAND_VF ||
2243 instr->m_opcode == VINSTR_BITOR_VF ||
2244 instr->m_opcode == VINSTR_BITXOR ||
2245 instr->m_opcode == VINSTR_BITXOR_VF ||
2246 instr->m_opcode == VINSTR_BITXOR_V ||
2247 instr->m_opcode == VINSTR_CROSS)
2249 value = instr->_m_ops[2];
2250 /* the float source will get an additional lifetime */
2251 if (ir_value_life_merge(value, instr->m_eid+1))
2253 if (value->m_memberof && ir_value_life_merge(value->m_memberof, instr->m_eid+1))
2257 if (instr->m_opcode == INSTR_MUL_FV ||
2258 instr->m_opcode == INSTR_LOAD_V ||
2259 instr->m_opcode == VINSTR_BITXOR ||
2260 instr->m_opcode == VINSTR_BITXOR_VF ||
2261 instr->m_opcode == VINSTR_BITXOR_V ||
2262 instr->m_opcode == VINSTR_CROSS)
2264 value = instr->_m_ops[1];
2265 /* the float source will get an additional lifetime */
2266 if (ir_value_life_merge(value, instr->m_eid+1))
2268 if (value->m_memberof && ir_value_life_merge(value->m_memberof, instr->m_eid+1))
2272 for (o = 0; o < 3; ++o)
2274 if (!instr->_m_ops[o]) /* no such operand */
2277 value = instr->_m_ops[o];
2279 /* We only care about locals */
2280 /* we also calculate parameter liferanges so that locals
2281 * can take up parameter slots */
2282 if (value->m_store != store_value &&
2283 value->m_store != store_local &&
2284 value->m_store != store_param)
2290 if (!vec_ir_value_find(self->m_living, value, nullptr))
2291 self->m_living.push_back(value);
2292 /* reading adds the full vector */
2293 if (value->m_memberof && !vec_ir_value_find(self->m_living, value->m_memberof, nullptr))
2294 self->m_living.push_back(value->m_memberof);
2295 for (mem = 0; mem < 3; ++mem) {
2296 if (value->m_members[mem] && !vec_ir_value_find(self->m_living, value->m_members[mem], nullptr))
2297 self->m_living.push_back(value->m_members[mem]);
2301 /* PHI operands are always read operands */
2302 for (auto &it : instr->m_phi) {
2304 if (!vec_ir_value_find(self->m_living, value, nullptr))
2305 self->m_living.push_back(value);
2306 /* reading adds the full vector */
2307 if (value->m_memberof && !vec_ir_value_find(self->m_living, value->m_memberof, nullptr))
2308 self->m_living.push_back(value->m_memberof);
2309 for (mem = 0; mem < 3; ++mem) {
2310 if (value->m_members[mem] && !vec_ir_value_find(self->m_living, value->m_members[mem], nullptr))
2311 self->m_living.push_back(value->m_members[mem]);
2315 /* on a call, all these values must be "locked" */
2316 if (instr->m_opcode >= INSTR_CALL0 && instr->m_opcode <= INSTR_CALL8) {
2317 if (ir_block_living_lock(self))
2320 /* call params are read operands too */
2321 for (auto &it : instr->m_params) {
2323 if (!vec_ir_value_find(self->m_living, value, nullptr))
2324 self->m_living.push_back(value);
2325 /* reading adds the full vector */
2326 if (value->m_memberof && !vec_ir_value_find(self->m_living, value->m_memberof, nullptr))
2327 self->m_living.push_back(value->m_memberof);
2328 for (mem = 0; mem < 3; ++mem) {
2329 if (value->m_members[mem] && !vec_ir_value_find(self->m_living, value->m_members[mem], nullptr))
2330 self->m_living.push_back(value->m_members[mem]);
2335 if (ir_block_living_add_instr(self, instr->m_eid))
2338 /* the "entry" instruction ID */
2339 if (ir_block_living_add_instr(self, self->m_entry_id))
2345 bool ir_function_calculate_liferanges(ir_function *self)
2347 /* parameters live at 0 */
2348 for (size_t i = 0; i < vec_size(self->m_params); ++i)
2349 if (!ir_value_life_merge(self->m_locals[i].get(), 0))
2350 compile_error(self->m_context, "internal error: failed value-life merging");
2356 for (auto i = self->m_blocks.rbegin(); i != self->m_blocks.rend(); ++i)
2357 ir_block_life_propagate(i->get(), &changed);
2360 if (self->m_blocks.size()) {
2361 ir_block *block = self->m_blocks[0].get();
2362 for (auto &it : block->m_living) {
2364 if (v->m_store != store_local)
2366 if (v->m_vtype == TYPE_VECTOR)
2368 self->m_flags |= IR_FLAG_HAS_UNINITIALIZED;
2369 /* find the instruction reading from it */
2371 for (; s < v->m_reads.size(); ++s) {
2372 if (v->m_reads[s]->m_eid == v->m_life[0].end)
2375 if (s < v->m_reads.size()) {
2376 if (irwarning(v->m_context, WARN_USED_UNINITIALIZED,
2377 "variable `%s` may be used uninitialized in this function\n"
2380 v->m_reads[s]->m_context.file, v->m_reads[s]->m_context.line)
2387 if (v->m_memberof) {
2388 ir_value *vec = v->m_memberof;
2389 for (s = 0; s < vec->m_reads.size(); ++s) {
2390 if (vec->m_reads[s]->m_eid == v->m_life[0].end)
2393 if (s < vec->m_reads.size()) {
2394 if (irwarning(v->m_context, WARN_USED_UNINITIALIZED,
2395 "variable `%s` may be used uninitialized in this function\n"
2398 vec->m_reads[s]->m_context.file, vec->m_reads[s]->m_context.line)
2406 if (irwarning(v->m_context, WARN_USED_UNINITIALIZED,
2407 "variable `%s` may be used uninitialized in this function", v->m_name.c_str()))
2416 /***********************************************************************
2419 * Since the IR has the convention of putting 'write' operands
2420 * at the beginning, we have to rotate the operands of instructions
2421 * properly in order to generate valid QCVM code.
2423 * Having destinations at a fixed position is more convenient. In QC
2424 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2425 * read from from OPA, and store to OPB rather than OPC. Which is
2426 * partially the reason why the implementation of these instructions
2427 * in darkplaces has been delayed for so long.
2429 * Breaking conventions is annoying...
2431 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2433 static bool gen_global_field(code_t *code, ir_value *global)
2435 if (global->m_hasvalue)
2437 ir_value *fld = global->m_constval.vpointer;
2439 irerror(global->m_context, "Invalid field constant with no field: %s", global->m_name.c_str());
2443 /* copy the field's value */
2444 ir_value_code_setaddr(global, code->globals.size());
2445 code->globals.push_back(fld->m_code.fieldaddr);
2446 if (global->m_fieldtype == TYPE_VECTOR) {
2447 code->globals.push_back(fld->m_code.fieldaddr+1);
2448 code->globals.push_back(fld->m_code.fieldaddr+2);
2453 ir_value_code_setaddr(global, code->globals.size());
2454 code->globals.push_back(0);
2455 if (global->m_fieldtype == TYPE_VECTOR) {
2456 code->globals.push_back(0);
2457 code->globals.push_back(0);
2460 if (global->m_code.globaladdr < 0)
2465 static bool gen_global_pointer(code_t *code, ir_value *global)
2467 if (global->m_hasvalue)
2469 ir_value *target = global->m_constval.vpointer;
2471 irerror(global->m_context, "Invalid pointer constant: %s", global->m_name.c_str());
2472 /* nullptr pointers are pointing to the nullptr constant, which also
2473 * sits at address 0, but still has an ir_value for itself.
2478 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2479 * void() foo; <- proto
2480 * void() *fooptr = &foo;
2481 * void() foo = { code }
2483 if (!target->m_code.globaladdr) {
2484 /* FIXME: Check for the constant nullptr ir_value!
2485 * because then code.globaladdr being 0 is valid.
2487 irerror(global->m_context, "FIXME: Relocation support");
2491 ir_value_code_setaddr(global, code->globals.size());
2492 code->globals.push_back(target->m_code.globaladdr);
2496 ir_value_code_setaddr(global, code->globals.size());
2497 code->globals.push_back(0);
2499 if (global->m_code.globaladdr < 0)
2504 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2506 prog_section_statement_t stmt;
2515 block->m_generated = true;
2516 block->m_code_start = code->statements.size();
2517 for (i = 0; i < vec_size(block->m_instr); ++i)
2519 instr = block->m_instr[i];
2521 if (instr->m_opcode == VINSTR_PHI) {
2522 irerror(block->m_context, "cannot generate virtual instruction (phi)");
2526 if (instr->m_opcode == VINSTR_JUMP) {
2527 target = instr->m_bops[0];
2528 /* for uncoditional jumps, if the target hasn't been generated
2529 * yet, we generate them right here.
2531 if (!target->m_generated)
2532 return gen_blocks_recursive(code, func, target);
2534 /* otherwise we generate a jump instruction */
2535 stmt.opcode = INSTR_GOTO;
2536 stmt.o1.s1 = target->m_code_start - code->statements.size();
2539 if (stmt.o1.s1 != 1)
2540 code_push_statement(code, &stmt, instr->m_context);
2542 /* no further instructions can be in this block */
2546 if (instr->m_opcode == VINSTR_BITXOR) {
2547 stmt.opcode = INSTR_BITOR;
2548 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]);
2549 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]);
2550 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2551 code_push_statement(code, &stmt, instr->m_context);
2552 stmt.opcode = INSTR_BITAND;
2553 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]);
2554 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]);
2555 stmt.o3.s1 = ir_value_code_addr(func->m_owner->m_vinstr_temp[0]);
2556 code_push_statement(code, &stmt, instr->m_context);
2557 stmt.opcode = INSTR_SUB_F;
2558 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[0]);
2559 stmt.o2.s1 = ir_value_code_addr(func->m_owner->m_vinstr_temp[0]);
2560 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2561 code_push_statement(code, &stmt, instr->m_context);
2563 /* instruction generated */
2567 if (instr->m_opcode == VINSTR_BITAND_V) {
2568 stmt.opcode = INSTR_BITAND;
2569 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]);
2570 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]);
2571 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2572 code_push_statement(code, &stmt, instr->m_context);
2576 code_push_statement(code, &stmt, instr->m_context);
2580 code_push_statement(code, &stmt, instr->m_context);
2582 /* instruction generated */
2586 if (instr->m_opcode == VINSTR_BITOR_V) {
2587 stmt.opcode = INSTR_BITOR;
2588 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]);
2589 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]);
2590 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2591 code_push_statement(code, &stmt, instr->m_context);
2595 code_push_statement(code, &stmt, instr->m_context);
2599 code_push_statement(code, &stmt, instr->m_context);
2601 /* instruction generated */
2605 if (instr->m_opcode == VINSTR_BITXOR_V) {
2606 for (j = 0; j < 3; ++j) {
2607 stmt.opcode = INSTR_BITOR;
2608 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]) + j;
2609 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]) + j;
2610 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]) + j;
2611 code_push_statement(code, &stmt, instr->m_context);
2612 stmt.opcode = INSTR_BITAND;
2613 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]) + j;
2614 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]) + j;
2615 stmt.o3.s1 = ir_value_code_addr(func->m_owner->m_vinstr_temp[0]) + j;
2616 code_push_statement(code, &stmt, instr->m_context);
2618 stmt.opcode = INSTR_SUB_V;
2619 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[0]);
2620 stmt.o2.s1 = ir_value_code_addr(func->m_owner->m_vinstr_temp[0]);
2621 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2622 code_push_statement(code, &stmt, instr->m_context);
2624 /* instruction generated */
2628 if (instr->m_opcode == VINSTR_BITAND_VF) {
2629 stmt.opcode = INSTR_BITAND;
2630 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]);
2631 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]);
2632 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2633 code_push_statement(code, &stmt, instr->m_context);
2636 code_push_statement(code, &stmt, instr->m_context);
2639 code_push_statement(code, &stmt, instr->m_context);
2641 /* instruction generated */
2645 if (instr->m_opcode == VINSTR_BITOR_VF) {
2646 stmt.opcode = INSTR_BITOR;
2647 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]);
2648 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]);
2649 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2650 code_push_statement(code, &stmt, instr->m_context);
2653 code_push_statement(code, &stmt, instr->m_context);
2656 code_push_statement(code, &stmt, instr->m_context);
2658 /* instruction generated */
2662 if (instr->m_opcode == VINSTR_BITXOR_VF) {
2663 for (j = 0; j < 3; ++j) {
2664 stmt.opcode = INSTR_BITOR;
2665 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]) + j;
2666 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]);
2667 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]) + j;
2668 code_push_statement(code, &stmt, instr->m_context);
2669 stmt.opcode = INSTR_BITAND;
2670 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]) + j;
2671 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]);
2672 stmt.o3.s1 = ir_value_code_addr(func->m_owner->m_vinstr_temp[0]) + j;
2673 code_push_statement(code, &stmt, instr->m_context);
2675 stmt.opcode = INSTR_SUB_V;
2676 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[0]);
2677 stmt.o2.s1 = ir_value_code_addr(func->m_owner->m_vinstr_temp[0]);
2678 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2679 code_push_statement(code, &stmt, instr->m_context);
2681 /* instruction generated */
2685 if (instr->m_opcode == VINSTR_CROSS) {
2686 stmt.opcode = INSTR_MUL_F;
2687 for (j = 0; j < 3; ++j) {
2688 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]) + (j + 1) % 3;
2689 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]) + (j + 2) % 3;
2690 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]) + j;
2691 code_push_statement(code, &stmt, instr->m_context);
2692 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[1]) + (j + 2) % 3;
2693 stmt.o2.s1 = ir_value_code_addr(instr->_m_ops[2]) + (j + 1) % 3;
2694 stmt.o3.s1 = ir_value_code_addr(func->m_owner->m_vinstr_temp[0]) + j;
2695 code_push_statement(code, &stmt, instr->m_context);
2697 stmt.opcode = INSTR_SUB_V;
2698 stmt.o1.s1 = ir_value_code_addr(instr->_m_ops[0]);
2699 stmt.o2.s1 = ir_value_code_addr(func->m_owner->m_vinstr_temp[0]);
2700 stmt.o3.s1 = ir_value_code_addr(instr->_m_ops[0]);
2701 code_push_statement(code, &stmt, instr->m_context);
2703 /* instruction generated */
2707 if (instr->m_opcode == VINSTR_COND) {
2708 ontrue = instr->m_bops[0];
2709 onfalse = instr->m_bops[1];
2710 /* TODO: have the AST signal which block should
2711 * come first: eg. optimize IFs without ELSE...
2714 stmt.o1.u1 = ir_value_code_addr(instr->_m_ops[0]);
2718 if (ontrue->m_generated) {
2719 stmt.opcode = INSTR_IF;
2720 stmt.o2.s1 = ontrue->m_code_start - code->statements.size();
2721 if (stmt.o2.s1 != 1)
2722 code_push_statement(code, &stmt, instr->m_context);
2724 if (onfalse->m_generated) {
2725 stmt.opcode = INSTR_IFNOT;
2726 stmt.o2.s1 = onfalse->m_code_start - code->statements.size();
2727 if (stmt.o2.s1 != 1)
2728 code_push_statement(code, &stmt, instr->m_context);
2730 if (!ontrue->m_generated) {
2731 if (onfalse->m_generated)
2732 return gen_blocks_recursive(code, func, ontrue);
2734 if (!onfalse->m_generated) {
2735 if (ontrue->m_generated)
2736 return gen_blocks_recursive(code, func, onfalse);
2738 /* neither ontrue nor onfalse exist */
2739 stmt.opcode = INSTR_IFNOT;
2740 if (!instr->m_likely) {
2741 /* Honor the likelyhood hint */
2742 ir_block *tmp = onfalse;
2743 stmt.opcode = INSTR_IF;
2747 stidx = code->statements.size();
2748 code_push_statement(code, &stmt, instr->m_context);
2749 /* on false we jump, so add ontrue-path */
2750 if (!gen_blocks_recursive(code, func, ontrue))
2752 /* fixup the jump address */
2753 code->statements[stidx].o2.s1 = code->statements.size() - stidx;
2754 /* generate onfalse path */
2755 if (onfalse->m_generated) {
2756 /* fixup the jump address */
2757 code->statements[stidx].o2.s1 = onfalse->m_code_start - stidx;
2758 if (stidx+2 == code->statements.size() && code->statements[stidx].o2.s1 == 1) {
2759 code->statements[stidx] = code->statements[stidx+1];
2760 if (code->statements[stidx].o1.s1 < 0)
2761 code->statements[stidx].o1.s1++;
2762 code_pop_statement(code);
2764 stmt.opcode = code->statements.back().opcode;
2765 if (stmt.opcode == INSTR_GOTO ||
2766 stmt.opcode == INSTR_IF ||
2767 stmt.opcode == INSTR_IFNOT ||
2768 stmt.opcode == INSTR_RETURN ||
2769 stmt.opcode == INSTR_DONE)
2771 /* no use jumping from here */
2774 /* may have been generated in the previous recursive call */
2775 stmt.opcode = INSTR_GOTO;
2776 stmt.o1.s1 = onfalse->m_code_start - code->statements.size();
2779 if (stmt.o1.s1 != 1)
2780 code_push_statement(code, &stmt, instr->m_context);
2783 else if (stidx+2 == code->statements.size() && code->statements[stidx].o2.s1 == 1) {
2784 code->statements[stidx] = code->statements[stidx+1];
2785 if (code->statements[stidx].o1.s1 < 0)
2786 code->statements[stidx].o1.s1++;
2787 code_pop_statement(code);
2789 /* if not, generate now */
2790 return gen_blocks_recursive(code, func, onfalse);
2793 if ( (instr->m_opcode >= INSTR_CALL0 && instr->m_opcode <= INSTR_CALL8)
2794 || instr->m_opcode == VINSTR_NRCALL)
2799 first = instr->m_params.size();
2802 for (p = 0; p < first; ++p)
2804 ir_value *param = instr->m_params[p];
2805 if (param->m_callparam)
2808 stmt.opcode = INSTR_STORE_F;
2811 if (param->m_vtype == TYPE_FIELD)
2812 stmt.opcode = field_store_instr[param->m_fieldtype];
2813 else if (param->m_vtype == TYPE_NIL)
2814 stmt.opcode = INSTR_STORE_V;
2816 stmt.opcode = type_store_instr[param->m_vtype];
2817 stmt.o1.u1 = ir_value_code_addr(param);
2818 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2820 if (param->m_vtype == TYPE_VECTOR && (param->m_flags & IR_FLAG_SPLIT_VECTOR)) {
2821 /* fetch 3 separate floats */
2822 stmt.opcode = INSTR_STORE_F;
2823 stmt.o1.u1 = ir_value_code_addr(param->m_members[0]);
2824 code_push_statement(code, &stmt, instr->m_context);
2826 stmt.o1.u1 = ir_value_code_addr(param->m_members[1]);
2827 code_push_statement(code, &stmt, instr->m_context);
2829 stmt.o1.u1 = ir_value_code_addr(param->m_members[2]);
2830 code_push_statement(code, &stmt, instr->m_context);
2833 code_push_statement(code, &stmt, instr->m_context);
2835 /* Now handle extparams */
2836 first = instr->m_params.size();
2837 for (; p < first; ++p)
2839 ir_builder *ir = func->m_owner;
2840 ir_value *param = instr->m_params[p];
2841 ir_value *targetparam;
2843 if (param->m_callparam)
2846 if (p-8 >= ir->m_extparams.size())
2847 ir_gen_extparam(ir);
2849 targetparam = ir->m_extparams[p-8];
2851 stmt.opcode = INSTR_STORE_F;
2854 if (param->m_vtype == TYPE_FIELD)
2855 stmt.opcode = field_store_instr[param->m_fieldtype];
2856 else if (param->m_vtype == TYPE_NIL)
2857 stmt.opcode = INSTR_STORE_V;
2859 stmt.opcode = type_store_instr[param->m_vtype];
2860 stmt.o1.u1 = ir_value_code_addr(param);
2861 stmt.o2.u1 = ir_value_code_addr(targetparam);
2862 if (param->m_vtype == TYPE_VECTOR && (param->m_flags & IR_FLAG_SPLIT_VECTOR)) {
2863 /* fetch 3 separate floats */
2864 stmt.opcode = INSTR_STORE_F;
2865 stmt.o1.u1 = ir_value_code_addr(param->m_members[0]);
2866 code_push_statement(code, &stmt, instr->m_context);
2868 stmt.o1.u1 = ir_value_code_addr(param->m_members[1]);
2869 code_push_statement(code, &stmt, instr->m_context);
2871 stmt.o1.u1 = ir_value_code_addr(param->m_members[2]);
2872 code_push_statement(code, &stmt, instr->m_context);
2875 code_push_statement(code, &stmt, instr->m_context);
2878 stmt.opcode = INSTR_CALL0 + instr->m_params.size();
2879 if (stmt.opcode > INSTR_CALL8)
2880 stmt.opcode = INSTR_CALL8;
2881 stmt.o1.u1 = ir_value_code_addr(instr->_m_ops[1]);
2884 code_push_statement(code, &stmt, instr->m_context);
2886 retvalue = instr->_m_ops[0];
2887 if (retvalue && retvalue->m_store != store_return &&
2888 (retvalue->m_store == store_global || retvalue->m_life.size()))
2890 /* not to be kept in OFS_RETURN */
2891 if (retvalue->m_vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2892 stmt.opcode = field_store_instr[retvalue->m_fieldtype];
2894 stmt.opcode = type_store_instr[retvalue->m_vtype];
2895 stmt.o1.u1 = OFS_RETURN;
2896 stmt.o2.u1 = ir_value_code_addr(retvalue);
2898 code_push_statement(code, &stmt, instr->m_context);
2903 if (instr->m_opcode == INSTR_STATE) {
2904 stmt.opcode = instr->m_opcode;
2905 if (instr->_m_ops[0])
2906 stmt.o1.u1 = ir_value_code_addr(instr->_m_ops[0]);
2907 if (instr->_m_ops[1])
2908 stmt.o2.u1 = ir_value_code_addr(instr->_m_ops[1]);
2910 code_push_statement(code, &stmt, instr->m_context);
2914 stmt.opcode = instr->m_opcode;
2919 /* This is the general order of operands */
2920 if (instr->_m_ops[0])
2921 stmt.o3.u1 = ir_value_code_addr(instr->_m_ops[0]);
2923 if (instr->_m_ops[1])
2924 stmt.o1.u1 = ir_value_code_addr(instr->_m_ops[1]);
2926 if (instr->_m_ops[2])
2927 stmt.o2.u1 = ir_value_code_addr(instr->_m_ops[2]);
2929 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2931 stmt.o1.u1 = stmt.o3.u1;
2934 else if ((stmt.opcode >= INSTR_STORE_F &&
2935 stmt.opcode <= INSTR_STORE_FNC) ||
2936 (stmt.opcode >= INSTR_STOREP_F &&
2937 stmt.opcode <= INSTR_STOREP_FNC))
2939 /* 2-operand instructions with A -> B */
2940 stmt.o2.u1 = stmt.o3.u1;
2943 /* tiny optimization, don't output
2946 if (stmt.o2.u1 == stmt.o1.u1 &&
2947 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2949 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2953 code_push_statement(code, &stmt, instr->m_context);
2958 static bool gen_function_code(code_t *code, ir_function *self)
2961 prog_section_statement_t stmt, *retst;
2963 /* Starting from entry point, we generate blocks "as they come"
2964 * for now. Dead blocks will not be translated obviously.
2966 if (self->m_blocks.empty()) {
2967 irerror(self->m_context, "Function '%s' declared without body.", self->m_name.c_str());
2971 block = self->m_blocks[0].get();
2972 if (block->m_generated)
2975 if (!gen_blocks_recursive(code, self, block)) {
2976 irerror(self->m_context, "failed to generate blocks for '%s'", self->m_name.c_str());
2980 /* code_write and qcvm -disasm need to know that the function ends here */
2981 retst = &code->statements.back();
2982 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
2983 self->m_outtype == TYPE_VOID &&
2984 retst->opcode == INSTR_RETURN &&
2985 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
2987 retst->opcode = INSTR_DONE;
2988 ++opts_optimizationcount[OPTIM_VOID_RETURN];
2992 stmt.opcode = INSTR_DONE;
2996 last.line = code->linenums.back();
2997 last.column = code->columnnums.back();
2999 code_push_statement(code, &stmt, last);
3004 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3006 /* NOTE: filename pointers are copied, we never strdup them,
3007 * thus we can use pointer-comparison to find the string.
3011 for (size_t i = 0; i != ir->m_filenames.size(); ++i) {
3012 if (!strcmp(ir->m_filenames[i], filename))
3016 str = code_genstring(ir->m_code.get(), filename);
3017 ir->m_filenames.push_back(filename);
3018 ir->m_filestrings.push_back(str);
3022 static bool gen_global_function(ir_builder *ir, ir_value *global)
3024 prog_section_function_t fun;
3029 if (!global->m_hasvalue || (!global->m_constval.vfunc)) {
3030 irerror(global->m_context, "Invalid state of function-global: not constant: %s", global->m_name.c_str());
3034 irfun = global->m_constval.vfunc;
3035 fun.name = global->m_code.name;
3036 fun.file = ir_builder_filestring(ir, global->m_context.file);
3037 fun.profile = 0; /* always 0 */
3038 fun.nargs = vec_size(irfun->m_params);
3042 for (i = 0; i < 8; ++i) {
3043 if ((int32_t)i >= fun.nargs)
3046 fun.argsize[i] = type_sizeof_[irfun->m_params[i]];
3050 fun.locals = irfun->m_allocated_locals;
3052 if (irfun->m_builtin)
3053 fun.entry = irfun->m_builtin+1;
3055 irfun->m_code_function_def = ir->m_code->functions.size();
3056 fun.entry = ir->m_code->statements.size();
3059 ir->m_code->functions.push_back(fun);
3063 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3067 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(ir->m_extparam_protos.size()));
3068 ir_value *global = new ir_value(name, store_global, TYPE_VECTOR);
3069 ir->m_extparam_protos.emplace_back(global);
3074 static void ir_gen_extparam(ir_builder *ir)
3076 prog_section_def_t def;
3079 if (ir->m_extparam_protos.size() < ir->m_extparams.size()+1)
3080 global = ir_gen_extparam_proto(ir);
3082 global = ir->m_extparam_protos[ir->m_extparams.size()].get();
3084 def.name = code_genstring(ir->m_code.get(), global->m_name.c_str());
3085 def.type = TYPE_VECTOR;
3086 def.offset = ir->m_code->globals.size();
3088 ir->m_code->defs.push_back(def);
3090 ir_value_code_setaddr(global, def.offset);
3092 ir->m_code->globals.push_back(0);
3093 ir->m_code->globals.push_back(0);
3094 ir->m_code->globals.push_back(0);
3096 ir->m_extparams.emplace_back(global);
3099 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3101 ir_builder *ir = self->m_owner;
3103 size_t numparams = vec_size(self->m_params);
3107 prog_section_statement_t stmt;
3108 stmt.opcode = INSTR_STORE_F;
3110 for (size_t i = 8; i < numparams; ++i) {
3112 if (ext >= ir->m_extparams.size())
3113 ir_gen_extparam(ir);
3115 ir_value *ep = ir->m_extparams[ext];
3117 stmt.opcode = type_store_instr[self->m_locals[i]->m_vtype];
3118 if (self->m_locals[i]->m_vtype == TYPE_FIELD &&
3119 self->m_locals[i]->m_fieldtype == TYPE_VECTOR)
3121 stmt.opcode = INSTR_STORE_V;
3123 stmt.o1.u1 = ir_value_code_addr(ep);
3124 stmt.o2.u1 = ir_value_code_addr(self->m_locals[i].get());
3125 code_push_statement(code, &stmt, self->m_context);
3131 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3133 size_t i, ext, numparams, maxparams;
3135 ir_builder *ir = self->m_owner;
3137 prog_section_statement_t stmt;
3139 numparams = vec_size(self->m_params);
3143 stmt.opcode = INSTR_STORE_V;
3145 maxparams = numparams + self->m_max_varargs;
3146 for (i = numparams; i < maxparams; ++i) {
3148 stmt.o1.u1 = OFS_PARM0 + 3*i;
3149 stmt.o2.u1 = ir_value_code_addr(self->m_locals[i].get());
3150 code_push_statement(code, &stmt, self->m_context);
3154 while (ext >= ir->m_extparams.size())
3155 ir_gen_extparam(ir);
3157 ep = ir->m_extparams[ext];
3159 stmt.o1.u1 = ir_value_code_addr(ep);
3160 stmt.o2.u1 = ir_value_code_addr(self->m_locals[i].get());
3161 code_push_statement(code, &stmt, self->m_context);
3167 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3169 prog_section_function_t *def;
3171 uint32_t firstlocal, firstglobal;
3173 irfun = global->m_constval.vfunc;
3174 def = &ir->m_code->functions[0] + irfun->m_code_function_def;
3176 if (OPTS_OPTION_BOOL(OPTION_G) ||
3177 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3178 (irfun->m_flags & IR_FLAG_MASK_NO_OVERLAP))
3180 firstlocal = def->firstlocal = ir->m_code->globals.size();
3182 firstlocal = def->firstlocal = ir->m_first_common_local;
3183 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3186 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->m_first_common_globaltemp : firstlocal);
3188 for (size_t i = ir->m_code->globals.size(); i < firstlocal + irfun->m_allocated_locals; ++i)
3189 ir->m_code->globals.push_back(0);
3191 for (auto& lp : irfun->m_locals) {
3192 ir_value *v = lp.get();
3193 if (v->m_locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3194 ir_value_code_setaddr(v, firstlocal + v->m_code.local);
3195 if (!ir_builder_gen_global(ir, v, true)) {
3196 irerror(v->m_context, "failed to generate local %s", v->m_name.c_str());
3201 ir_value_code_setaddr(v, firstglobal + v->m_code.local);
3203 for (auto& vp : irfun->m_values) {
3204 ir_value *v = vp.get();
3208 ir_value_code_setaddr(v, firstlocal + v->m_code.local);
3210 ir_value_code_setaddr(v, firstglobal + v->m_code.local);
3215 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3217 prog_section_function_t *fundef;
3222 irfun = global->m_constval.vfunc;
3224 if (global->m_cvq == CV_NONE) {
3225 if (irwarning(global->m_context, WARN_IMPLICIT_FUNCTION_POINTER,
3226 "function `%s` has no body and in QC implicitly becomes a function-pointer",
3227 global->m_name.c_str()))
3229 /* Not bailing out just now. If this happens a lot you don't want to have
3230 * to rerun gmqcc for each such function.
3236 /* this was a function pointer, don't generate code for those */
3240 if (irfun->m_builtin)
3244 * If there is no definition and the thing is eraseable, we can ignore
3245 * outputting the function to begin with.
3247 if (global->m_flags & IR_FLAG_ERASABLE && irfun->m_code_function_def < 0) {
3251 if (irfun->m_code_function_def < 0) {
3252 irerror(irfun->m_context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->m_name.c_str());
3255 fundef = &ir->m_code->functions[irfun->m_code_function_def];
3257 fundef->entry = ir->m_code->statements.size();
3258 if (!gen_function_locals(ir, global)) {
3259 irerror(irfun->m_context, "Failed to generate locals for function %s", irfun->m_name.c_str());
3262 if (!gen_function_extparam_copy(ir->m_code.get(), irfun)) {
3263 irerror(irfun->m_context, "Failed to generate extparam-copy code for function %s", irfun->m_name.c_str());
3266 if (irfun->m_max_varargs && !gen_function_varargs_copy(ir->m_code.get(), irfun)) {
3267 irerror(irfun->m_context, "Failed to generate vararg-copy code for function %s", irfun->m_name.c_str());
3270 if (!gen_function_code(ir->m_code.get(), irfun)) {
3271 irerror(irfun->m_context, "Failed to generate code for function %s", irfun->m_name.c_str());
3277 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3282 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3285 def.type = TYPE_FLOAT;
3289 component = (char*)mem_a(len+3);
3290 memcpy(component, name, len);
3292 component[len-0] = 0;
3293 component[len-2] = '_';
3295 component[len-1] = 'x';
3297 for (i = 0; i < 3; ++i) {
3298 def.name = code_genstring(code, component);
3299 code->defs.push_back(def);
3307 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3312 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3315 fld.type = TYPE_FLOAT;
3319 component = (char*)mem_a(len+3);
3320 memcpy(component, name, len);
3322 component[len-0] = 0;
3323 component[len-2] = '_';
3325 component[len-1] = 'x';
3327 for (i = 0; i < 3; ++i) {
3328 fld.name = code_genstring(code, component);
3329 code->fields.push_back(fld);
3337 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3341 prog_section_def_t def;
3342 bool pushdef = opts.optimizeoff;
3344 /* we don't generate split-vectors */
3345 if (global->m_vtype == TYPE_VECTOR && (global->m_flags & IR_FLAG_SPLIT_VECTOR))
3348 def.type = global->m_vtype;
3349 def.offset = self->m_code->globals.size();
3351 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3356 * if we're eraseable and the function isn't referenced ignore outputting
3359 if (global->m_flags & IR_FLAG_ERASABLE && global->m_reads.empty()) {
3363 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3364 !(global->m_flags & IR_FLAG_INCLUDE_DEF) &&
3365 (global->m_name[0] == '#' || global->m_cvq == CV_CONST))
3371 if (global->m_name[0] == '#') {
3372 if (!self->m_str_immediate)
3373 self->m_str_immediate = code_genstring(self->m_code.get(), "IMMEDIATE");
3374 def.name = global->m_code.name = self->m_str_immediate;
3377 def.name = global->m_code.name = code_genstring(self->m_code.get(), global->m_name.c_str());
3382 def.offset = ir_value_code_addr(global);
3383 self->m_code->defs.push_back(def);
3384 if (global->m_vtype == TYPE_VECTOR)
3385 gen_vector_defs(self->m_code.get(), def, global->m_name.c_str());
3386 else if (global->m_vtype == TYPE_FIELD && global->m_fieldtype == TYPE_VECTOR)
3387 gen_vector_defs(self->m_code.get(), def, global->m_name.c_str());
3394 switch (global->m_vtype)
3397 if (0 == global->m_name.compare("end_sys_globals")) {
3398 // TODO: remember this point... all the defs before this one
3399 // should be checksummed and added to progdefs.h when we generate it.
3401 else if (0 == global->m_name.compare("end_sys_fields")) {
3402 // TODO: same as above but for entity-fields rather than globsl
3404 else if(irwarning(global->m_context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3405 global->m_name.c_str()))
3407 /* Not bailing out */
3410 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3411 * the system fields actually go? Though the engine knows this anyway...
3412 * Maybe this could be an -foption
3413 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3415 ir_value_code_setaddr(global, self->m_code->globals.size());
3416 self->m_code->globals.push_back(0);
3418 if (pushdef) self->m_code->defs.push_back(def);
3421 if (pushdef) self->m_code->defs.push_back(def);
3422 return gen_global_pointer(self->m_code.get(), global);
3425 self->m_code->defs.push_back(def);
3426 if (global->m_fieldtype == TYPE_VECTOR)
3427 gen_vector_defs(self->m_code.get(), def, global->m_name.c_str());
3429 return gen_global_field(self->m_code.get(), global);
3434 ir_value_code_setaddr(global, self->m_code->globals.size());
3435 if (global->m_hasvalue) {
3436 iptr = (int32_t*)&global->m_constval.ivec[0];
3437 self->m_code->globals.push_back(*iptr);
3439 self->m_code->globals.push_back(0);
3441 if (!islocal && global->m_cvq != CV_CONST)
3442 def.type |= DEF_SAVEGLOBAL;
3443 if (pushdef) self->m_code->defs.push_back(def);
3445 return global->m_code.globaladdr >= 0;
3449 ir_value_code_setaddr(global, self->m_code->globals.size());
3450 if (global->m_hasvalue) {
3451 uint32_t load = code_genstring(self->m_code.get(), global->m_constval.vstring);
3452 self->m_code->globals.push_back(load);
3454 self->m_code->globals.push_back(0);
3456 if (!islocal && global->m_cvq != CV_CONST)
3457 def.type |= DEF_SAVEGLOBAL;
3458 if (pushdef) self->m_code->defs.push_back(def);
3459 return global->m_code.globaladdr >= 0;
3464 ir_value_code_setaddr(global, self->m_code->globals.size());
3465 if (global->m_hasvalue) {
3466 iptr = (int32_t*)&global->m_constval.ivec[0];
3467 self->m_code->globals.push_back(iptr[0]);
3468 if (global->m_code.globaladdr < 0)
3470 for (d = 1; d < type_sizeof_[global->m_vtype]; ++d) {
3471 self->m_code->globals.push_back(iptr[d]);
3474 self->m_code->globals.push_back(0);
3475 if (global->m_code.globaladdr < 0)
3477 for (d = 1; d < type_sizeof_[global->m_vtype]; ++d) {
3478 self->m_code->globals.push_back(0);
3481 if (!islocal && global->m_cvq != CV_CONST)
3482 def.type |= DEF_SAVEGLOBAL;
3485 self->m_code->defs.push_back(def);
3486 def.type &= ~DEF_SAVEGLOBAL;
3487 gen_vector_defs(self->m_code.get(), def, global->m_name.c_str());
3489 return global->m_code.globaladdr >= 0;
3492 ir_value_code_setaddr(global, self->m_code->globals.size());
3493 if (!global->m_hasvalue) {
3494 self->m_code->globals.push_back(0);
3495 if (global->m_code.globaladdr < 0)
3498 self->m_code->globals.push_back(self->m_code->functions.size());
3499 if (!gen_global_function(self, global))
3502 if (!islocal && global->m_cvq != CV_CONST)
3503 def.type |= DEF_SAVEGLOBAL;
3504 if (pushdef) self->m_code->defs.push_back(def);
3507 /* assume biggest type */
3508 ir_value_code_setaddr(global, self->m_code->globals.size());
3509 self->m_code->globals.push_back(0);
3510 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3511 self->m_code->globals.push_back(0);
3514 /* refuse to create 'void' type or any other fancy business. */
3515 irerror(global->m_context, "Invalid type for global variable `%s`: %s",
3516 global->m_name.c_str(), type_name[global->m_vtype]);
3521 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3523 field->m_code.fieldaddr = code_alloc_field(code, type_sizeof_[field->m_fieldtype]);
3526 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3528 prog_section_def_t def;
3529 prog_section_field_t fld;
3533 def.type = (uint16_t)field->m_vtype;
3534 def.offset = (uint16_t)self->m_code->globals.size();
3536 /* create a global named the same as the field */
3537 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3538 /* in our standard, the global gets a dot prefix */
3539 size_t len = field->m_name.length();
3542 /* we really don't want to have to allocate this, and 1024
3543 * bytes is more than enough for a variable/field name
3545 if (len+2 >= sizeof(name)) {
3546 irerror(field->m_context, "invalid field name size: %u", (unsigned int)len);
3551 memcpy(name+1, field->m_name.c_str(), len); // no strncpy - we used strlen above
3554 def.name = code_genstring(self->m_code.get(), name);
3555 fld.name = def.name + 1; /* we reuse that string table entry */
3557 /* in plain QC, there cannot be a global with the same name,
3558 * and so we also name the global the same.
3559 * FIXME: fteqcc should create a global as well
3560 * check if it actually uses the same name. Probably does
3562 def.name = code_genstring(self->m_code.get(), field->m_name.c_str());
3563 fld.name = def.name;
3566 field->m_code.name = def.name;
3568 self->m_code->defs.push_back(def);
3570 fld.type = field->m_fieldtype;
3572 if (fld.type == TYPE_VOID) {
3573 irerror(field->m_context, "field is missing a type: %s - don't know its size", field->m_name.c_str());
3577 fld.offset = field->m_code.fieldaddr;
3579 self->m_code->fields.push_back(fld);
3581 ir_value_code_setaddr(field, self->m_code->globals.size());
3582 self->m_code->globals.push_back(fld.offset);
3583 if (fld.type == TYPE_VECTOR) {
3584 self->m_code->globals.push_back(fld.offset+1);
3585 self->m_code->globals.push_back(fld.offset+2);
3588 if (field->m_fieldtype == TYPE_VECTOR) {
3589 gen_vector_defs (self->m_code.get(), def, field->m_name.c_str());
3590 gen_vector_fields(self->m_code.get(), fld, field->m_name.c_str());
3593 return field->m_code.globaladdr >= 0;
3596 static void ir_builder_collect_reusables(ir_builder *builder) {
3597 std::vector<ir_value*> reusables;
3599 for (auto& gp : builder->m_globals) {
3600 ir_value *value = gp.get();
3601 if (value->m_vtype != TYPE_FLOAT || !value->m_hasvalue)
3603 if (value->m_cvq == CV_CONST || (value->m_name.length() >= 1 && value->m_name[0] == '#'))
3604 reusables.emplace_back(value);
3606 builder->m_const_floats = move(reusables);
3609 static void ir_builder_split_vector(ir_builder *self, ir_value *vec) {
3610 ir_value* found[3] = { nullptr, nullptr, nullptr };
3612 // must not be written to
3613 if (vec->m_writes.size())
3615 // must not be trying to access individual members
3616 if (vec->m_members[0] || vec->m_members[1] || vec->m_members[2])
3618 // should be actually used otherwise it won't be generated anyway
3619 if (vec->m_reads.empty())
3621 //size_t count = vec->m_reads.size();
3625 // may only be used directly as function parameters, so if we find some other instruction cancel
3626 for (ir_instr *user : vec->m_reads) {
3627 // we only split vectors if they're used directly as parameter to a call only!
3628 if ((user->m_opcode < INSTR_CALL0 || user->m_opcode > INSTR_CALL8) && user->m_opcode != VINSTR_NRCALL)
3632 vec->m_flags |= IR_FLAG_SPLIT_VECTOR;
3634 // find existing floats making up the split
3635 for (ir_value *c : self->m_const_floats) {
3636 if (!found[0] && c->m_constval.vfloat == vec->m_constval.vvec.x)
3638 if (!found[1] && c->m_constval.vfloat == vec->m_constval.vvec.y)
3640 if (!found[2] && c->m_constval.vfloat == vec->m_constval.vvec.z)
3642 if (found[0] && found[1] && found[2])
3646 // generate floats for not yet found components
3648 found[0] = ir_builder_imm_float(self, vec->m_constval.vvec.x, true);
3650 if (vec->m_constval.vvec.y == vec->m_constval.vvec.x)
3651 found[1] = found[0];
3653 found[1] = ir_builder_imm_float(self, vec->m_constval.vvec.y, true);
3656 if (vec->m_constval.vvec.z == vec->m_constval.vvec.x)
3657 found[2] = found[0];
3658 else if (vec->m_constval.vvec.z == vec->m_constval.vvec.y)
3659 found[2] = found[1];
3661 found[2] = ir_builder_imm_float(self, vec->m_constval.vvec.z, true);
3664 // the .members array should be safe to use here
3665 vec->m_members[0] = found[0];
3666 vec->m_members[1] = found[1];
3667 vec->m_members[2] = found[2];
3669 // register the readers for these floats
3670 found[0]->m_reads.insert(found[0]->m_reads.end(), vec->m_reads.begin(), vec->m_reads.end());
3671 found[1]->m_reads.insert(found[1]->m_reads.end(), vec->m_reads.begin(), vec->m_reads.end());
3672 found[2]->m_reads.insert(found[2]->m_reads.end(), vec->m_reads.begin(), vec->m_reads.end());
3675 static void ir_builder_split_vectors(ir_builder *self) {
3676 // member values may be added to self->m_globals during this operation, but
3677 // no new vectors will be added, we need to iterate via an index as
3678 // c++ iterators would be invalidated
3679 const size_t count = self->m_globals.size();
3680 for (size_t i = 0; i != count; ++i) {
3681 ir_value *v = self->m_globals[i].get();
3682 if (v->m_vtype != TYPE_VECTOR || !v->m_name.length() || v->m_name[0] != '#')
3684 ir_builder_split_vector(self, v);
3688 bool ir_builder_generate(ir_builder *self, const char *filename)
3690 prog_section_statement_t stmt;
3691 char *lnofile = nullptr;
3693 if (OPTS_FLAG(SPLIT_VECTOR_PARAMETERS)) {
3694 ir_builder_collect_reusables(self);
3695 if (!self->m_const_floats.empty())
3696 ir_builder_split_vectors(self);
3699 for (auto& fp : self->m_fields)
3700 ir_builder_prepare_field(self->m_code.get(), fp.get());
3702 for (auto& gp : self->m_globals) {
3703 ir_value *global = gp.get();
3704 if (!ir_builder_gen_global(self, global, false)) {
3707 if (global->m_vtype == TYPE_FUNCTION) {
3708 ir_function *func = global->m_constval.vfunc;
3709 if (func && self->m_max_locals < func->m_allocated_locals &&
3710 !(func->m_flags & IR_FLAG_MASK_NO_OVERLAP))
3712 self->m_max_locals = func->m_allocated_locals;
3714 if (func && self->m_max_globaltemps < func->m_globaltemps)
3715 self->m_max_globaltemps = func->m_globaltemps;
3719 for (auto& fp : self->m_fields) {
3720 if (!ir_builder_gen_field(self, fp.get()))
3725 ir_value_code_setaddr(self->m_nil, self->m_code->globals.size());
3726 self->m_code->globals.push_back(0);
3727 self->m_code->globals.push_back(0);
3728 self->m_code->globals.push_back(0);
3730 // generate virtual-instruction temps
3731 for (size_t i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
3732 ir_value_code_setaddr(self->m_vinstr_temp[i], self->m_code->globals.size());
3733 self->m_code->globals.push_back(0);
3734 self->m_code->globals.push_back(0);
3735 self->m_code->globals.push_back(0);
3738 // generate global temps
3739 self->m_first_common_globaltemp = self->m_code->globals.size();
3740 self->m_code->globals.insert(self->m_code->globals.end(), self->m_max_globaltemps, 0);
3742 //for (size_t i = 0; i < self->m_max_globaltemps; ++i) {
3743 // self->m_code->globals.push_back(0);
3745 // generate common locals
3746 self->m_first_common_local = self->m_code->globals.size();
3747 self->m_code->globals.insert(self->m_code->globals.end(), self->m_max_locals, 0);
3749 //for (i = 0; i < self->m_max_locals; ++i) {
3750 // self->m_code->globals.push_back(0);
3753 // generate function code
3755 for (auto& gp : self->m_globals) {
3756 ir_value *global = gp.get();
3757 if (global->m_vtype == TYPE_FUNCTION) {
3758 if (!gen_global_function_code(self, global)) {
3764 if (self->m_code->globals.size() >= 65536) {
3765 irerror(self->m_globals.back()->m_context,
3766 "This progs file would require more globals than the metadata can handle (%zu). Bailing out.",
3767 self->m_code->globals.size());
3771 /* DP errors if the last instruction is not an INSTR_DONE. */
3772 if (self->m_code->statements.back().opcode != INSTR_DONE)
3776 stmt.opcode = INSTR_DONE;
3780 last.line = self->m_code->linenums.back();
3781 last.column = self->m_code->columnnums.back();
3783 code_push_statement(self->m_code.get(), &stmt, last);
3786 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3789 if (self->m_code->statements.size() != self->m_code->linenums.size()) {
3790 con_err("Linecounter wrong: %lu != %lu\n",
3791 self->m_code->statements.size(),
3792 self->m_code->linenums.size());
3793 } else if (OPTS_FLAG(LNO)) {
3795 size_t filelen = strlen(filename);
3797 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3798 dot = strrchr(lnofile, '.');
3802 vec_shrinkto(lnofile, dot - lnofile);
3804 memcpy(vec_add(lnofile, 5), ".lno", 5);
3807 if (!code_write(self->m_code.get(), filename, lnofile)) {
3816 /***********************************************************************
3817 *IR DEBUG Dump functions...
3820 #define IND_BUFSZ 1024
3822 static const char *qc_opname(int op)
3824 if (op < 0) return "<INVALID>";
3825 if (op < VINSTR_END)
3826 return util_instr_str[op];
3828 case VINSTR_END: return "END";
3829 case VINSTR_PHI: return "PHI";
3830 case VINSTR_JUMP: return "JUMP";
3831 case VINSTR_COND: return "COND";
3832 case VINSTR_BITXOR: return "BITXOR";
3833 case VINSTR_BITAND_V: return "BITAND_V";
3834 case VINSTR_BITOR_V: return "BITOR_V";
3835 case VINSTR_BITXOR_V: return "BITXOR_V";
3836 case VINSTR_BITAND_VF: return "BITAND_VF";
3837 case VINSTR_BITOR_VF: return "BITOR_VF";
3838 case VINSTR_BITXOR_VF: return "BITXOR_VF";
3839 case VINSTR_CROSS: return "CROSS";
3840 case VINSTR_NEG_F: return "NEG_F";
3841 case VINSTR_NEG_V: return "NEG_V";
3842 default: return "<UNK>";
3846 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3849 char indent[IND_BUFSZ];
3853 oprintf("module %s\n", b->m_name.c_str());
3854 for (i = 0; i < b->m_globals.size(); ++i)
3857 if (b->m_globals[i]->m_hasvalue)
3858 oprintf("%s = ", b->m_globals[i]->m_name.c_str());
3859 ir_value_dump(b->m_globals[i].get(), oprintf);
3862 for (i = 0; i < b->m_functions.size(); ++i)
3863 ir_function_dump(b->m_functions[i].get(), indent, oprintf);
3864 oprintf("endmodule %s\n", b->m_name.c_str());
3867 static const char *storenames[] = {
3868 "[global]", "[local]", "[param]", "[value]", "[return]"
3871 void ir_function_dump(ir_function *f, char *ind,
3872 int (*oprintf)(const char*, ...))
3875 if (f->m_builtin != 0) {
3876 oprintf("%sfunction %s = builtin %i\n", ind, f->m_name.c_str(), -f->m_builtin);
3879 oprintf("%sfunction %s\n", ind, f->m_name.c_str());
3880 util_strncat(ind, "\t", IND_BUFSZ-1);
3881 if (f->m_locals.size())
3883 oprintf("%s%i locals:\n", ind, (int)f->m_locals.size());
3884 for (i = 0; i < f->m_locals.size(); ++i) {
3885 oprintf("%s\t", ind);
3886 ir_value_dump(f->m_locals[i].get(), oprintf);
3890 oprintf("%sliferanges:\n", ind);
3891 for (i = 0; i < f->m_locals.size(); ++i) {
3892 const char *attr = "";
3894 ir_value *v = f->m_locals[i].get();
3895 if (v->m_unique_life && v->m_locked)
3896 attr = "unique,locked ";
3897 else if (v->m_unique_life)
3899 else if (v->m_locked)
3901 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->m_name.c_str(), type_name[v->m_vtype],
3902 storenames[v->m_store],
3903 attr, (v->m_callparam ? "callparam " : ""),
3904 (int)v->m_code.local);
3905 if (v->m_life.empty())
3907 for (l = 0; l < v->m_life.size(); ++l) {
3908 oprintf("[%i,%i] ", v->m_life[l].start, v->m_life[l].end);
3911 for (m = 0; m < 3; ++m) {
3912 ir_value *vm = v->m_members[m];
3915 oprintf("%s\t%s: @%i ", ind, vm->m_name.c_str(), (int)vm->m_code.local);
3916 for (l = 0; l < vm->m_life.size(); ++l) {
3917 oprintf("[%i,%i] ", vm->m_life[l].start, vm->m_life[l].end);
3922 for (i = 0; i < f->m_values.size(); ++i) {
3923 const char *attr = "";
3925 ir_value *v = f->m_values[i].get();
3926 if (v->m_unique_life && v->m_locked)
3927 attr = "unique,locked ";
3928 else if (v->m_unique_life)
3930 else if (v->m_locked)
3932 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->m_name.c_str(), type_name[v->m_vtype],
3933 storenames[v->m_store],
3934 attr, (v->m_callparam ? "callparam " : ""),
3935 (int)v->m_code.local);
3936 if (v->m_life.empty())
3938 for (l = 0; l < v->m_life.size(); ++l) {
3939 oprintf("[%i,%i] ", v->m_life[l].start, v->m_life[l].end);
3942 for (m = 0; m < 3; ++m) {
3943 ir_value *vm = v->m_members[m];
3946 if (vm->m_unique_life && vm->m_locked)
3947 attr = "unique,locked ";
3948 else if (vm->m_unique_life)
3950 else if (vm->m_locked)
3952 oprintf("%s\t%s: %s@%i ", ind, vm->m_name.c_str(), attr, (int)vm->m_code.local);
3953 for (l = 0; l < vm->m_life.size(); ++l) {
3954 oprintf("[%i,%i] ", vm->m_life[l].start, vm->m_life[l].end);
3959 if (f->m_blocks.size())
3961 oprintf("%slife passes: %i\n", ind, (int)f->m_run_id);
3962 for (i = 0; i < f->m_blocks.size(); ++i) {
3963 ir_block_dump(f->m_blocks[i].get(), ind, oprintf);
3967 ind[strlen(ind)-1] = 0;
3968 oprintf("%sendfunction %s\n", ind, f->m_name.c_str());
3971 void ir_block_dump(ir_block* b, char *ind,
3972 int (*oprintf)(const char*, ...))
3975 oprintf("%s:%s\n", ind, b->m_label.c_str());
3976 util_strncat(ind, "\t", IND_BUFSZ-1);
3978 if (b->m_instr && b->m_instr[0])
3979 oprintf("%s (%i) [entry]\n", ind, (int)(b->m_instr[0]->m_eid-1));
3980 for (i = 0; i < vec_size(b->m_instr); ++i)
3981 ir_instr_dump(b->m_instr[i], ind, oprintf);
3982 ind[strlen(ind)-1] = 0;
3985 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3987 oprintf("%s <- phi ", in->_m_ops[0]->m_name.c_str());
3988 for (auto &it : in->m_phi) {
3989 oprintf("([%s] : %s) ", it.from->m_label.c_str(),
3990 it.value->m_name.c_str());
3995 void ir_instr_dump(ir_instr *in, char *ind,
3996 int (*oprintf)(const char*, ...))
3999 const char *comma = nullptr;
4001 oprintf("%s (%i) ", ind, (int)in->m_eid);
4003 if (in->m_opcode == VINSTR_PHI) {
4004 dump_phi(in, oprintf);
4008 util_strncat(ind, "\t", IND_BUFSZ-1);
4010 if (in->_m_ops[0] && (in->_m_ops[1] || in->_m_ops[2])) {
4011 ir_value_dump(in->_m_ops[0], oprintf);
4012 if (in->_m_ops[1] || in->_m_ops[2])
4015 if (in->m_opcode == INSTR_CALL0 || in->m_opcode == VINSTR_NRCALL) {
4016 oprintf("CALL%i\t", in->m_params.size());
4018 oprintf("%s\t", qc_opname(in->m_opcode));
4020 if (in->_m_ops[0] && !(in->_m_ops[1] || in->_m_ops[2])) {
4021 ir_value_dump(in->_m_ops[0], oprintf);
4026 for (i = 1; i != 3; ++i) {
4027 if (in->_m_ops[i]) {
4030 ir_value_dump(in->_m_ops[i], oprintf);
4035 if (in->m_bops[0]) {
4038 oprintf("[%s]", in->m_bops[0]->m_label.c_str());
4042 oprintf("%s[%s]", comma, in->m_bops[1]->m_label.c_str());
4043 if (in->m_params.size()) {
4044 oprintf("\tparams: ");
4045 for (auto &it : in->m_params)
4046 oprintf("%s, ", it->m_name.c_str());
4049 ind[strlen(ind)-1] = 0;
4052 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
4055 for (; *str; ++str) {
4057 case '\n': oprintf("\\n"); break;
4058 case '\r': oprintf("\\r"); break;
4059 case '\t': oprintf("\\t"); break;
4060 case '\v': oprintf("\\v"); break;
4061 case '\f': oprintf("\\f"); break;
4062 case '\b': oprintf("\\b"); break;
4063 case '\a': oprintf("\\a"); break;
4064 case '\\': oprintf("\\\\"); break;
4065 case '"': oprintf("\\\""); break;
4066 default: oprintf("%c", *str); break;
4072 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4074 if (v->m_hasvalue) {
4075 switch (v->m_vtype) {
4081 oprintf("fn:%s", v->m_name.c_str());
4084 oprintf("%g", v->m_constval.vfloat);
4087 oprintf("'%g %g %g'",
4088 v->m_constval.vvec.x,
4089 v->m_constval.vvec.y,
4090 v->m_constval.vvec.z);
4093 oprintf("(entity)");
4096 ir_value_dump_string(v->m_constval.vstring, oprintf);
4100 oprintf("%i", v->m_constval.vint);
4105 v->m_constval.vpointer->m_name.c_str());
4109 oprintf("%s", v->m_name.c_str());
4113 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4115 oprintf("Life of %12s:", self->m_name.c_str());
4116 for (size_t i = 0; i < self->m_life.size(); ++i)
4118 oprintf(" + [%i, %i]\n", self->m_life[i].start, self->m_life[i].end);