]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.cpp
f3a4dca13b0b089838ddae273223308e33cb5dc2
[xonotic/gmqcc.git] / ir.cpp
1 #include <stdlib.h>
2 #include <string.h>
3
4 #include "gmqcc.h"
5 #include "ir.h"
6
7 /***********************************************************************
8  * Type sizes used at multiple points in the IR codegen
9  */
10
11 const char *type_name[TYPE_COUNT] = {
12     "void",
13     "string",
14     "float",
15     "vector",
16     "entity",
17     "field",
18     "function",
19     "pointer",
20     "integer",
21     "variant",
22     "struct",
23     "union",
24     "array",
25
26     "nil",
27     "<no-expression>"
28 };
29
30 static size_t type_sizeof_[TYPE_COUNT] = {
31     1, /* TYPE_VOID     */
32     1, /* TYPE_STRING   */
33     1, /* TYPE_FLOAT    */
34     3, /* TYPE_VECTOR   */
35     1, /* TYPE_ENTITY   */
36     1, /* TYPE_FIELD    */
37     1, /* TYPE_FUNCTION */
38     1, /* TYPE_POINTER  */
39     1, /* TYPE_INTEGER  */
40     3, /* TYPE_VARIANT  */
41     0, /* TYPE_STRUCT   */
42     0, /* TYPE_UNION    */
43     0, /* TYPE_ARRAY    */
44     0, /* TYPE_NIL      */
45     0, /* TYPE_NOESPR   */
46 };
47
48 const uint16_t type_store_instr[TYPE_COUNT] = {
49     INSTR_STORE_F, /* should use I when having integer support */
50     INSTR_STORE_S,
51     INSTR_STORE_F,
52     INSTR_STORE_V,
53     INSTR_STORE_ENT,
54     INSTR_STORE_FLD,
55     INSTR_STORE_FNC,
56     INSTR_STORE_ENT, /* should use I */
57 #if 0
58     INSTR_STORE_I, /* integer type */
59 #else
60     INSTR_STORE_F,
61 #endif
62
63     INSTR_STORE_V, /* variant, should never be accessed */
64
65     VINSTR_END, /* struct */
66     VINSTR_END, /* union  */
67     VINSTR_END, /* array  */
68     VINSTR_END, /* nil    */
69     VINSTR_END, /* noexpr */
70 };
71
72 const uint16_t field_store_instr[TYPE_COUNT] = {
73     INSTR_STORE_FLD,
74     INSTR_STORE_FLD,
75     INSTR_STORE_FLD,
76     INSTR_STORE_V,
77     INSTR_STORE_FLD,
78     INSTR_STORE_FLD,
79     INSTR_STORE_FLD,
80     INSTR_STORE_FLD,
81 #if 0
82     INSTR_STORE_FLD, /* integer type */
83 #else
84     INSTR_STORE_FLD,
85 #endif
86
87     INSTR_STORE_V, /* variant, should never be accessed */
88
89     VINSTR_END, /* struct */
90     VINSTR_END, /* union  */
91     VINSTR_END, /* array  */
92     VINSTR_END, /* nil    */
93     VINSTR_END, /* noexpr */
94 };
95
96 const uint16_t type_storep_instr[TYPE_COUNT] = {
97     INSTR_STOREP_F, /* should use I when having integer support */
98     INSTR_STOREP_S,
99     INSTR_STOREP_F,
100     INSTR_STOREP_V,
101     INSTR_STOREP_ENT,
102     INSTR_STOREP_FLD,
103     INSTR_STOREP_FNC,
104     INSTR_STOREP_ENT, /* should use I */
105 #if 0
106     INSTR_STOREP_ENT, /* integer type */
107 #else
108     INSTR_STOREP_F,
109 #endif
110
111     INSTR_STOREP_V, /* variant, should never be accessed */
112
113     VINSTR_END, /* struct */
114     VINSTR_END, /* union  */
115     VINSTR_END, /* array  */
116     VINSTR_END, /* nil    */
117     VINSTR_END, /* noexpr */
118 };
119
120 const uint16_t type_eq_instr[TYPE_COUNT] = {
121     INSTR_EQ_F, /* should use I when having integer support */
122     INSTR_EQ_S,
123     INSTR_EQ_F,
124     INSTR_EQ_V,
125     INSTR_EQ_E,
126     INSTR_EQ_E, /* FLD has no comparison */
127     INSTR_EQ_FNC,
128     INSTR_EQ_E, /* should use I */
129 #if 0
130     INSTR_EQ_I,
131 #else
132     INSTR_EQ_F,
133 #endif
134
135     INSTR_EQ_V, /* variant, should never be accessed */
136
137     VINSTR_END, /* struct */
138     VINSTR_END, /* union  */
139     VINSTR_END, /* array  */
140     VINSTR_END, /* nil    */
141     VINSTR_END, /* noexpr */
142 };
143
144 const uint16_t type_ne_instr[TYPE_COUNT] = {
145     INSTR_NE_F, /* should use I when having integer support */
146     INSTR_NE_S,
147     INSTR_NE_F,
148     INSTR_NE_V,
149     INSTR_NE_E,
150     INSTR_NE_E, /* FLD has no comparison */
151     INSTR_NE_FNC,
152     INSTR_NE_E, /* should use I */
153 #if 0
154     INSTR_NE_I,
155 #else
156     INSTR_NE_F,
157 #endif
158
159     INSTR_NE_V, /* variant, should never be accessed */
160
161     VINSTR_END, /* struct */
162     VINSTR_END, /* union  */
163     VINSTR_END, /* array  */
164     VINSTR_END, /* nil    */
165     VINSTR_END, /* noexpr */
166 };
167
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 */
171     INSTR_NOT_F,
172     INSTR_NOT_V,
173     INSTR_NOT_ENT,
174     INSTR_NOT_ENT,
175     INSTR_NOT_FNC,
176     INSTR_NOT_ENT, /* should use I */
177 #if 0
178     INSTR_NOT_I, /* integer type */
179 #else
180     INSTR_NOT_F,
181 #endif
182
183     INSTR_NOT_V, /* variant, should never be accessed */
184
185     VINSTR_END, /* struct */
186     VINSTR_END, /* union  */
187     VINSTR_END, /* array  */
188     VINSTR_END, /* nil    */
189     VINSTR_END, /* noexpr */
190 };
191
192 /* protos */
193 static void            ir_function_dump(ir_function*, char *ind, int (*oprintf)(const char*,...));
194
195 static ir_value*       ir_block_create_general_instr(ir_block *self, lex_ctx_t, const char *label,
196                                                      int op, ir_value *a, ir_value *b, qc_type outype);
197 static bool GMQCC_WARN ir_block_create_store(ir_block*, lex_ctx_t, ir_value *target, ir_value *what);
198 static void            ir_block_dump(ir_block*, char *ind, int (*oprintf)(const char*,...));
199
200 static bool            ir_instr_op(ir_instr*, int op, ir_value *value, bool writing);
201 static void            ir_instr_dump(ir_instr* in, char *ind, int (*oprintf)(const char*,...));
202 /* error functions */
203
204 static void irerror(lex_ctx_t ctx, const char *msg, ...)
205 {
206     va_list ap;
207     va_start(ap, msg);
208     con_cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
209     va_end(ap);
210 }
211
212 static bool GMQCC_WARN irwarning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
213 {
214     bool    r;
215     va_list ap;
216     va_start(ap, fmt);
217     r = vcompile_warning(ctx, warntype, fmt, ap);
218     va_end(ap);
219     return r;
220 }
221
222 /***********************************************************************
223  * Vector utility functions
224  */
225
226 static bool GMQCC_WARN vec_ir_value_find(std::vector<ir_value *> &vec, const ir_value *what, size_t *idx)
227 {
228     for (auto &it : vec) {
229         if (it != what)
230             continue;
231         if (idx)
232             *idx = &it - &vec[0];
233         return true;
234     }
235     return false;
236 }
237
238 static bool GMQCC_WARN vec_ir_block_find(std::vector<ir_block *> &vec, ir_block *what, size_t *idx)
239 {
240     for (auto &it : vec) {
241         if (it != what)
242             continue;
243         if (idx)
244             *idx = &it - &vec[0];
245         return true;
246     }
247     return false;
248 }
249
250 static bool GMQCC_WARN vec_ir_instr_find(std::vector<ir_instr *> &vec, ir_instr *what, size_t *idx)
251 {
252     for (auto &it : vec) {
253         if (it != what)
254             continue;
255         if (idx)
256             *idx = &it - &vec[0];
257         return true;
258     }
259     return false;
260 }
261
262 /***********************************************************************
263  * IR Builder
264  */
265
266 static void ir_block_delete_quick(ir_block* self);
267 static void ir_instr_delete_quick(ir_instr *self);
268 static void ir_function_delete_quick(ir_function *self);
269
270 ir_builder::ir_builder(const std::string& modulename)
271 : m_name(modulename),
272   m_code(new code_t)
273 {
274     m_htglobals   = util_htnew(IR_HT_SIZE);
275     m_htfields    = util_htnew(IR_HT_SIZE);
276     m_htfunctions = util_htnew(IR_HT_SIZE);
277
278     m_nil = new ir_value("nil", store_value, TYPE_NIL);
279     m_nil->m_cvq = CV_CONST;
280
281     for (size_t i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
282         /* we write to them, but they're not supposed to be used outside the IR, so
283          * let's not allow the generation of ir_instrs which use these.
284          * So it's a constant noexpr.
285          */
286         m_vinstr_temp[i] = new ir_value("vinstr_temp", store_value, TYPE_NOEXPR);
287         m_vinstr_temp[i]->m_cvq = CV_CONST;
288     }
289 }
290
291 ir_builder::~ir_builder()
292 {
293     util_htdel(m_htglobals);
294     util_htdel(m_htfields);
295     util_htdel(m_htfunctions);
296     for (auto& f : m_functions)
297         ir_function_delete_quick(f.release());
298     m_functions.clear(); // delete them now before deleting the rest:
299
300     delete m_nil;
301
302     for (size_t i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
303         delete m_vinstr_temp[i];
304     }
305
306     m_extparams.clear();
307     m_extparam_protos.clear();
308 }
309
310 ir_function* ir_builder::createFunction(const std::string& name, qc_type outtype)
311 {
312     ir_function *fn = (ir_function*)util_htget(m_htfunctions, name.c_str());
313     if (fn)
314         return nullptr;
315
316     fn = new ir_function(this, outtype);
317     fn->m_name = name;
318     m_functions.emplace_back(fn);
319     util_htset(m_htfunctions, name.c_str(), fn);
320
321     fn->m_value = createGlobal(fn->m_name, TYPE_FUNCTION);
322     if (!fn->m_value) {
323         delete fn;
324         return nullptr;
325     }
326
327     fn->m_value->m_hasvalue = true;
328     fn->m_value->m_outtype = outtype;
329     fn->m_value->m_constval.vfunc = fn;
330     fn->m_value->m_context = fn->m_context;
331
332     return fn;
333 }
334
335 ir_value* ir_builder::createGlobal(const std::string& name, qc_type vtype)
336 {
337     ir_value *ve;
338
339     if (name[0] != '#')
340     {
341         ve = (ir_value*)util_htget(m_htglobals, name.c_str());
342         if (ve) {
343             return nullptr;
344         }
345     }
346
347     ve = new ir_value(std::string(name), store_global, vtype);
348     m_globals.emplace_back(ve);
349     util_htset(m_htglobals, name.c_str(), ve);
350     return ve;
351 }
352
353 ir_value* ir_builder::get_va_count()
354 {
355     if (m_reserved_va_count)
356         return m_reserved_va_count;
357     return (m_reserved_va_count = createGlobal("reserved:va_count", TYPE_FLOAT));
358 }
359
360 ir_value* ir_builder::createField(const std::string& name, qc_type vtype)
361 {
362     ir_value *ve = (ir_value*)util_htget(m_htfields, name.c_str());
363     if (ve) {
364         return nullptr;
365     }
366
367     ve = new ir_value(std::string(name), store_global, TYPE_FIELD);
368     ve->m_fieldtype = vtype;
369     m_fields.emplace_back(ve);
370     util_htset(m_htfields, name.c_str(), ve);
371     return ve;
372 }
373
374 /***********************************************************************
375  *IR Function
376  */
377
378 static bool ir_function_naive_phi(ir_function*);
379 static void ir_function_enumerate(ir_function*);
380 static bool ir_function_calculate_liferanges(ir_function*);
381 static bool ir_function_allocate_locals(ir_function*);
382
383 ir_function::ir_function(ir_builder* owner_, qc_type outtype_)
384 : m_owner(owner_),
385   m_name("<@unnamed>"),
386   m_outtype(outtype_)
387 {
388     m_context.file = "<@no context>";
389     m_context.line = 0;
390 }
391
392 ir_function::~ir_function()
393 {
394 }
395
396 static void ir_function_delete_quick(ir_function *self)
397 {
398     for (auto& b : self->m_blocks)
399         ir_block_delete_quick(b.release());
400     delete self;
401 }
402
403 static void ir_function_collect_value(ir_function *self, ir_value *v)
404 {
405     self->m_values.emplace_back(v);
406 }
407
408 ir_block* ir_function_create_block(lex_ctx_t ctx, ir_function *self, const char *label)
409 {
410     ir_block* bn = new ir_block(self, label ? std::string(label) : std::string());
411     bn->m_context = ctx;
412     self->m_blocks.emplace_back(bn);
413
414     if ((self->m_flags & IR_FLAG_BLOCK_COVERAGE) && self->m_owner->m_coverage_func)
415         (void)ir_block_create_call(bn, ctx, nullptr, self->m_owner->m_coverage_func, false);
416
417     return bn;
418 }
419
420 static bool instr_is_operation(uint16_t op)
421 {
422     return ( (op >= INSTR_MUL_F  && op <= INSTR_GT) ||
423              (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
424              (op == INSTR_ADDRESS) ||
425              (op >= INSTR_NOT_F  && op <= INSTR_NOT_FNC) ||
426              (op >= INSTR_AND    && op <= INSTR_BITOR) ||
427              (op >= INSTR_CALL0  && op <= INSTR_CALL8) ||
428              (op >= VINSTR_BITAND_V && op <= VINSTR_NEG_V) );
429 }
430
431 static bool ir_function_pass_peephole(ir_function *self)
432 {
433     for (auto& bp : self->m_blocks) {
434         ir_block *block = bp.get();
435         for (size_t i = 0; i < block->m_instr.size(); ++i) {
436             ir_instr *inst;
437             inst = block->m_instr[i];
438
439             if (i >= 1 &&
440                 (inst->m_opcode >= INSTR_STORE_F &&
441                  inst->m_opcode <= INSTR_STORE_FNC))
442             {
443                 ir_instr *store;
444                 ir_instr *oper;
445                 ir_value *value;
446
447                 store = inst;
448
449                 oper  = block->m_instr[i-1];
450                 if (!instr_is_operation(oper->m_opcode))
451                     continue;
452
453                 /* Don't change semantics of MUL_VF in engines where these may not alias. */
454                 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
455                     if (oper->m_opcode == INSTR_MUL_VF && oper->_m_ops[2]->m_memberof == oper->_m_ops[1])
456                         continue;
457                     if (oper->m_opcode == INSTR_MUL_FV && oper->_m_ops[1]->m_memberof == oper->_m_ops[2])
458                         continue;
459                 }
460
461                 value = oper->_m_ops[0];
462
463                 /* only do it for SSA values */
464                 if (value->m_store != store_value)
465                     continue;
466
467                 /* don't optimize out the temp if it's used later again */
468                 if (value->m_reads.size() != 1)
469                     continue;
470
471                 /* The very next store must use this value */
472                 if (value->m_reads[0] != store)
473                     continue;
474
475                 /* And of course the store must _read_ from it, so it's in
476                  * OP 1 */
477                 if (store->_m_ops[1] != value)
478                     continue;
479
480                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
481                 (void)!ir_instr_op(oper, 0, store->_m_ops[0], true);
482
483                 block->m_instr.erase(block->m_instr.begin() + i);
484                 delete store;
485             }
486             else if (inst->m_opcode == VINSTR_COND)
487             {
488                 /* COND on a value resulting from a NOT could
489                  * remove the NOT and swap its operands
490                  */
491                 while (true) {
492                     ir_block *tmp;
493                     size_t    inotid;
494                     ir_instr *inot;
495                     ir_value *value;
496                     value = inst->_m_ops[0];
497
498                     if (value->m_store != store_value || value->m_reads.size() != 1 || value->m_reads[0] != inst)
499                         break;
500
501                     inot = value->m_writes[0];
502                     if (inot->_m_ops[0] != value ||
503                         inot->m_opcode < INSTR_NOT_F ||
504                         inot->m_opcode > INSTR_NOT_FNC ||
505                         inot->m_opcode == INSTR_NOT_V || /* can't do these */
506                         inot->m_opcode == INSTR_NOT_S)
507                     {
508                         break;
509                     }
510
511                     /* count */
512                     ++opts_optimizationcount[OPTIM_PEEPHOLE];
513                     /* change operand */
514                     (void)!ir_instr_op(inst, 0, inot->_m_ops[1], false);
515                     /* remove NOT */
516                     tmp = inot->m_owner;
517                     for (inotid = 0; inotid < tmp->m_instr.size(); ++inotid) {
518                         if (tmp->m_instr[inotid] == inot)
519                             break;
520                     }
521                     if (inotid >= tmp->m_instr.size()) {
522                         compile_error(inst->m_context, "sanity-check failed: failed to find instruction to optimize out");
523                         return false;
524                     }
525                     tmp->m_instr.erase(tmp->m_instr.begin() + inotid);
526                     delete inot;
527                     /* swap ontrue/onfalse */
528                     tmp = inst->m_bops[0];
529                     inst->m_bops[0] = inst->m_bops[1];
530                     inst->m_bops[1] = tmp;
531                 }
532                 continue;
533             }
534         }
535     }
536
537     return true;
538 }
539
540 static bool ir_function_pass_tailrecursion(ir_function *self)
541 {
542     size_t p;
543
544     for (auto& bp : self->m_blocks) {
545         ir_block *block = bp.get();
546
547         ir_value *funcval;
548         ir_instr *ret, *call, *store = nullptr;
549
550         if (!block->m_final || block->m_instr.size() < 2)
551             continue;
552
553         ret = block->m_instr.back();
554         if (ret->m_opcode != INSTR_DONE && ret->m_opcode != INSTR_RETURN)
555             continue;
556
557         call = block->m_instr[block->m_instr.size()-2];
558         if (call->m_opcode >= INSTR_STORE_F && call->m_opcode <= INSTR_STORE_FNC) {
559             /* account for the unoptimized
560              * CALL
561              * STORE %return, %tmp
562              * RETURN %tmp
563              * version
564              */
565             if (block->m_instr.size() < 3)
566                 continue;
567
568             store = call;
569             call = block->m_instr[block->m_instr.size()-3];
570         }
571
572         if (call->m_opcode < INSTR_CALL0 || call->m_opcode > INSTR_CALL8)
573             continue;
574
575         if (store) {
576             /* optimize out the STORE */
577             if (ret->_m_ops[0]   &&
578                 ret->_m_ops[0]   == store->_m_ops[0] &&
579                 store->_m_ops[1] == call->_m_ops[0])
580             {
581                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
582                 call->_m_ops[0] = store->_m_ops[0];
583                 block->m_instr.erase(block->m_instr.end()-2);
584                 delete store;
585             }
586             else
587                 continue;
588         }
589
590         if (!call->_m_ops[0])
591             continue;
592
593         funcval = call->_m_ops[1];
594         if (!funcval)
595             continue;
596         if (funcval->m_vtype != TYPE_FUNCTION || funcval->m_constval.vfunc != self)
597             continue;
598
599         /* now we have a CALL and a RET, check if it's a tailcall */
600         if (ret->_m_ops[0] && call->_m_ops[0] != ret->_m_ops[0])
601             continue;
602
603         ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
604         block->m_instr.erase(block->m_instr.end()-2, block->m_instr.end());
605
606         block->m_final = false; /* open it back up */
607
608         /* emite parameter-stores */
609         for (p = 0; p < call->m_params.size(); ++p) {
610             /* assert(call->params_count <= self->locals_count); */
611             if (!ir_block_create_store(block, call->m_context, self->m_locals[p].get(), call->m_params[p])) {
612                 irerror(call->m_context, "failed to create tailcall store instruction for parameter %i", (int)p);
613                 return false;
614             }
615         }
616         if (!ir_block_create_jump(block, call->m_context, self->m_blocks[0].get())) {
617             irerror(call->m_context, "failed to create tailcall jump");
618             return false;
619         }
620
621         delete call;
622         delete ret;
623     }
624
625     return true;
626 }
627
628 bool ir_function_finalize(ir_function *self)
629 {
630     if (self->m_builtin)
631         return true;
632
633     for (auto& lp : self->m_locals) {
634         ir_value *v = lp.get();
635         if (v->m_reads.empty() && v->m_writes.size() && !(v->m_flags & IR_FLAG_NOREF)) {
636             // if it's a vector check to ensure all it's members are unused before
637             // claiming it's unused, otherwise skip the vector entierly
638             if (v->m_vtype == TYPE_VECTOR)
639             {
640                 size_t mask = (1 << 3) - 1, bits = 0;
641                 for (size_t i = 0; i < 3; i++)
642                     if (!v->m_members[i] || (v->m_members[i]->m_reads.empty()
643                         && v->m_members[i]->m_writes.size()))
644                         bits |= (1 << i);
645                 // all components are unused so just report the vector
646                 if (bits == mask && irwarning(v->m_context, WARN_UNUSED_VARIABLE,
647                     "unused variable: `%s`", v->m_name.c_str()))
648                     return false;
649                 else if (bits != mask)
650                     // individual components are unused so mention them
651                     for (size_t i = 0; i < 3; i++)
652                         if ((bits & (1 << i))
653                             && irwarning(v->m_context, WARN_UNUSED_COMPONENT,
654                                 "unused vector component: `%s.%c`", v->m_name.c_str(), "xyz"[i]))
655                             return false;
656             }
657             // just a standard variable
658             else if (irwarning(v->m_context, WARN_UNUSED_VARIABLE,
659                     "unused variable: `%s`", v->m_name.c_str())) return false;
660         }
661     }
662
663     if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
664         if (!ir_function_pass_peephole(self)) {
665             irerror(self->m_context, "generic optimization pass broke something in `%s`", self->m_name.c_str());
666             return false;
667         }
668     }
669
670     if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
671         if (!ir_function_pass_tailrecursion(self)) {
672             irerror(self->m_context, "tail-recursion optimization pass broke something in `%s`", self->m_name.c_str());
673             return false;
674         }
675     }
676
677     if (!ir_function_naive_phi(self)) {
678         irerror(self->m_context, "internal error: ir_function_naive_phi failed");
679         return false;
680     }
681
682     for (auto& lp : self->m_locals) {
683         ir_value *v = lp.get();
684         if (v->m_vtype == TYPE_VECTOR ||
685             (v->m_vtype == TYPE_FIELD && v->m_outtype == TYPE_VECTOR))
686         {
687             v->vectorMember(0);
688             v->vectorMember(1);
689             v->vectorMember(2);
690         }
691     }
692     for (auto& vp : self->m_values) {
693         ir_value *v = vp.get();
694         if (v->m_vtype == TYPE_VECTOR ||
695             (v->m_vtype == TYPE_FIELD && v->m_outtype == TYPE_VECTOR))
696         {
697             v->vectorMember(0);
698             v->vectorMember(1);
699             v->vectorMember(2);
700         }
701     }
702
703     ir_function_enumerate(self);
704
705     if (!ir_function_calculate_liferanges(self))
706         return false;
707     if (!ir_function_allocate_locals(self))
708         return false;
709     return true;
710 }
711
712 ir_value* ir_function_create_local(ir_function *self, const std::string& name, qc_type vtype, bool param)
713 {
714     ir_value *ve;
715
716     if (param &&
717         !self->m_locals.empty() &&
718         self->m_locals.back()->m_store != store_param)
719     {
720         irerror(self->m_context, "cannot add parameters after adding locals");
721         return nullptr;
722     }
723
724     ve = new ir_value(std::string(name), (param ? store_param : store_local), vtype);
725     if (param)
726         ve->m_locked = true;
727     self->m_locals.emplace_back(ve);
728     return ve;
729 }
730
731 /***********************************************************************
732  *IR Block
733  */
734
735 ir_block::ir_block(ir_function* owner, const std::string& name)
736 : m_owner(owner),
737   m_label(name)
738 {
739     m_context.file = "<@no context>";
740     m_context.line = 0;
741 }
742
743 ir_block::~ir_block()
744 {
745     for (auto &i : m_instr)
746         delete i;
747 }
748
749 static void ir_block_delete_quick(ir_block* self)
750 {
751     for (auto &i : self->m_instr)
752         ir_instr_delete_quick(i);
753     self->m_instr.clear();
754     delete self;
755 }
756
757 /***********************************************************************
758  *IR Instructions
759  */
760
761 ir_instr::ir_instr(lex_ctx_t ctx, ir_block* owner_, int op)
762 : m_opcode(op),
763   m_context(ctx),
764   m_owner(owner_)
765 {
766 }
767
768 ir_instr::~ir_instr()
769 {
770     // The following calls can only delete from
771     // vectors, we still want to delete this instruction
772     // so ignore the return value. Since with the warn_unused_result attribute
773     // gcc doesn't care about an explicit: (void)foo(); to ignore the result,
774     // I have to improvise here and use if(foo());
775     for (auto &it : m_phi) {
776         size_t idx;
777         if (vec_ir_instr_find(it.value->m_writes, this, &idx))
778             it.value->m_writes.erase(it.value->m_writes.begin() + idx);
779         if (vec_ir_instr_find(it.value->m_reads, this, &idx))
780             it.value->m_reads.erase(it.value->m_reads.begin() + idx);
781     }
782     for (auto &it : m_params) {
783         size_t idx;
784         if (vec_ir_instr_find(it->m_writes, this, &idx))
785             it->m_writes.erase(it->m_writes.begin() + idx);
786         if (vec_ir_instr_find(it->m_reads, this, &idx))
787             it->m_reads.erase(it->m_reads.begin() + idx);
788     }
789     (void)!ir_instr_op(this, 0, nullptr, false);
790     (void)!ir_instr_op(this, 1, nullptr, false);
791     (void)!ir_instr_op(this, 2, nullptr, false);
792 }
793
794 static void ir_instr_delete_quick(ir_instr *self)
795 {
796     self->m_phi.clear();
797     self->m_params.clear();
798     self->_m_ops[0] = nullptr;
799     self->_m_ops[1] = nullptr;
800     self->_m_ops[2] = nullptr;
801     delete self;
802 }
803
804 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
805 {
806     if (v && v->m_vtype == TYPE_NOEXPR) {
807         irerror(self->m_context, "tried to use a NOEXPR value");
808         return false;
809     }
810
811     if (self->_m_ops[op]) {
812         size_t idx;
813         if (writing && vec_ir_instr_find(self->_m_ops[op]->m_writes, self, &idx))
814             self->_m_ops[op]->m_writes.erase(self->_m_ops[op]->m_writes.begin() + idx);
815         else if (vec_ir_instr_find(self->_m_ops[op]->m_reads, self, &idx))
816             self->_m_ops[op]->m_reads.erase(self->_m_ops[op]->m_reads.begin() + idx);
817     }
818     if (v) {
819         if (writing)
820             v->m_writes.push_back(self);
821         else
822             v->m_reads.push_back(self);
823     }
824     self->_m_ops[op] = v;
825     return true;
826 }
827
828 /***********************************************************************
829  *IR Value
830  */
831
832 void ir_value::setCodeAddress(int32_t gaddr)
833 {
834     m_code.globaladdr = gaddr;
835     if (m_members[0]) m_members[0]->m_code.globaladdr = gaddr;
836     if (m_members[1]) m_members[1]->m_code.globaladdr = gaddr;
837     if (m_members[2]) m_members[2]->m_code.globaladdr = gaddr;
838 }
839
840 int32_t ir_value::codeAddress() const
841 {
842     if (m_store == store_return)
843         return OFS_RETURN + m_code.addroffset;
844     return m_code.globaladdr + m_code.addroffset;
845 }
846
847 ir_value::ir_value(std::string&& name_, store_type store_, qc_type vtype_)
848     : m_name(move(name_))
849     , m_vtype(vtype_)
850     , m_store(store_)
851 {
852     m_fieldtype = TYPE_VOID;
853     m_outtype = TYPE_VOID;
854     m_flags = 0;
855
856     m_cvq          = CV_NONE;
857     m_hasvalue     = false;
858     m_context.file = "<@no context>";
859     m_context.line = 0;
860
861     memset(&m_constval, 0, sizeof(m_constval));
862     memset(&m_code,     0, sizeof(m_code));
863
864     m_members[0] = nullptr;
865     m_members[1] = nullptr;
866     m_members[2] = nullptr;
867     m_memberof = nullptr;
868
869     m_unique_life = false;
870     m_locked = false;
871     m_callparam  = false;
872 }
873
874 ir_value::ir_value(ir_function *owner, std::string&& name, store_type storetype, qc_type vtype)
875     : ir_value(move(name), storetype, vtype)
876 {
877     ir_function_collect_value(owner, this);
878 }
879
880 ir_value::~ir_value()
881 {
882     size_t i;
883     if (m_hasvalue) {
884         if (m_vtype == TYPE_STRING)
885             mem_d((void*)m_constval.vstring);
886     }
887     if (!(m_flags & IR_FLAG_SPLIT_VECTOR)) {
888         for (i = 0; i < 3; ++i) {
889             if (m_members[i])
890                 delete m_members[i];
891         }
892     }
893 }
894
895
896 /*  helper function */
897 ir_value* ir_builder::literalFloat(float value, bool add_to_list) {
898     ir_value *v = new ir_value("#IMMEDIATE", store_global, TYPE_FLOAT);
899     v->m_flags |= IR_FLAG_ERASABLE;
900     v->m_hasvalue = true;
901     v->m_cvq = CV_CONST;
902     v->m_constval.vfloat = value;
903
904     m_globals.emplace_back(v);
905     if (add_to_list)
906         m_const_floats.emplace_back(v);
907     return v;
908 }
909
910 ir_value* ir_value::vectorMember(unsigned int member)
911 {
912     std::string name;
913     ir_value *m;
914     if (member >= 3)
915         return nullptr;
916
917     if (m_members[member])
918         return m_members[member];
919
920     if (!m_name.empty()) {
921         char member_name[3] = { '_', char('x' + member), 0 };
922         name = m_name + member_name;
923     }
924
925     if (m_vtype == TYPE_VECTOR)
926     {
927         m = new ir_value(move(name), m_store, TYPE_FLOAT);
928         if (!m)
929             return nullptr;
930         m->m_context = m_context;
931
932         m_members[member] = m;
933         m->m_code.addroffset = member;
934     }
935     else if (m_vtype == TYPE_FIELD)
936     {
937         if (m_fieldtype != TYPE_VECTOR)
938             return nullptr;
939         m = new ir_value(move(name), m_store, TYPE_FIELD);
940         if (!m)
941             return nullptr;
942         m->m_fieldtype = TYPE_FLOAT;
943         m->m_context = m_context;
944
945         m_members[member] = m;
946         m->m_code.addroffset = member;
947     }
948     else
949     {
950         irerror(m_context, "invalid member access on %s", m_name.c_str());
951         return nullptr;
952     }
953
954     m->m_memberof = this;
955     return m;
956 }
957
958 size_t ir_value::size() const {
959     if (m_vtype == TYPE_FIELD && m_fieldtype == TYPE_VECTOR)
960         return type_sizeof_[TYPE_VECTOR];
961     return type_sizeof_[m_vtype];
962 }
963
964 bool ir_value::setFloat(float f)
965 {
966     if (m_vtype != TYPE_FLOAT)
967         return false;
968     m_constval.vfloat = f;
969     m_hasvalue = true;
970     return true;
971 }
972
973 bool ir_value::setFunc(int f)
974 {
975     if (m_vtype != TYPE_FUNCTION)
976         return false;
977     m_constval.vint = f;
978     m_hasvalue = true;
979     return true;
980 }
981
982 bool ir_value::setVector(vec3_t v)
983 {
984     if (m_vtype != TYPE_VECTOR)
985         return false;
986     m_constval.vvec = v;
987     m_hasvalue = true;
988     return true;
989 }
990
991 bool ir_value::setField(ir_value *fld)
992 {
993     if (m_vtype != TYPE_FIELD)
994         return false;
995     m_constval.vpointer = fld;
996     m_hasvalue = true;
997     return true;
998 }
999
1000 bool ir_value::setString(const char *str)
1001 {
1002     if (m_vtype != TYPE_STRING)
1003         return false;
1004     m_constval.vstring = util_strdupe(str);
1005     m_hasvalue = true;
1006     return true;
1007 }
1008
1009 #if 0
1010 bool ir_value::setInt(int i)
1011 {
1012     if (m_vtype != TYPE_INTEGER)
1013         return false;
1014     m_constval.vint = i;
1015     m_hasvalue = true;
1016     return true;
1017 }
1018 #endif
1019
1020 bool ir_value::lives(size_t at)
1021 {
1022     for (auto& l : m_life) {
1023         if (l.start <= at && at <= l.end)
1024             return true;
1025         if (l.start > at) /* since it's ordered */
1026             return false;
1027     }
1028     return false;
1029 }
1030
1031 bool ir_value::insertLife(size_t idx, ir_life_entry_t e)
1032 {
1033     m_life.insert(m_life.begin() + idx, e);
1034     return true;
1035 }
1036
1037 bool ir_value::setAlive(size_t s)
1038 {
1039     size_t i;
1040     const size_t vs = m_life.size();
1041     ir_life_entry_t *life_found = nullptr;
1042     ir_life_entry_t *before = nullptr;
1043     ir_life_entry_t new_entry;
1044
1045     /* Find the first range >= s */
1046     for (i = 0; i < vs; ++i)
1047     {
1048         before = life_found;
1049         life_found = &m_life[i];
1050         if (life_found->start > s)
1051             break;
1052     }
1053     /* nothing found? append */
1054     if (i == vs) {
1055         ir_life_entry_t e;
1056         if (life_found && life_found->end+1 == s)
1057         {
1058             /* previous life range can be merged in */
1059             life_found->end++;
1060             return true;
1061         }
1062         if (life_found && life_found->end >= s)
1063             return false;
1064         e.start = e.end = s;
1065         m_life.emplace_back(e);
1066         return true;
1067     }
1068     /* found */
1069     if (before)
1070     {
1071         if (before->end + 1 == s &&
1072             life_found->start - 1 == s)
1073         {
1074             /* merge */
1075             before->end = life_found->end;
1076             m_life.erase(m_life.begin()+i);
1077             return true;
1078         }
1079         if (before->end + 1 == s)
1080         {
1081             /* extend before */
1082             before->end++;
1083             return true;
1084         }
1085         /* already contained */
1086         if (before->end >= s)
1087             return false;
1088     }
1089     /* extend */
1090     if (life_found->start - 1 == s)
1091     {
1092         life_found->start--;
1093         return true;
1094     }
1095     /* insert a new entry */
1096     new_entry.start = new_entry.end = s;
1097     return insertLife(i, new_entry);
1098 }
1099
1100 bool ir_value::mergeLife(const ir_value *other)
1101 {
1102     size_t i, myi;
1103
1104     if (other->m_life.empty())
1105         return true;
1106
1107     if (m_life.empty()) {
1108         m_life = other->m_life;
1109         return true;
1110     }
1111
1112     myi = 0;
1113     for (i = 0; i < other->m_life.size(); ++i)
1114     {
1115         const ir_life_entry_t &otherlife = other->m_life[i];
1116         while (true)
1117         {
1118             ir_life_entry_t *entry = &m_life[myi];
1119
1120             if (otherlife.end+1 < entry->start)
1121             {
1122                 /* adding an interval before entry */
1123                 if (!insertLife(myi, otherlife))
1124                     return false;
1125                 ++myi;
1126                 break;
1127             }
1128
1129             if (otherlife.start <  entry->start &&
1130                 otherlife.end+1 >= entry->start)
1131             {
1132                 /* starts earlier and overlaps */
1133                 entry->start = otherlife.start;
1134             }
1135
1136             if (otherlife.end   >  entry->end &&
1137                 otherlife.start <= entry->end+1)
1138             {
1139                 /* ends later and overlaps */
1140                 entry->end = otherlife.end;
1141             }
1142
1143             /* see if our change combines it with the next ranges */
1144             while (myi+1 < m_life.size() &&
1145                    entry->end+1 >= m_life[1+myi].start)
1146             {
1147                 /* overlaps with (myi+1) */
1148                 if (entry->end < m_life[1+myi].end)
1149                     entry->end = m_life[1+myi].end;
1150                 m_life.erase(m_life.begin() + (myi + 1));
1151                 entry = &m_life[myi];
1152             }
1153
1154             /* see if we're after the entry */
1155             if (otherlife.start > entry->end)
1156             {
1157                 ++myi;
1158                 /* append if we're at the end */
1159                 if (myi >= m_life.size()) {
1160                     m_life.emplace_back(otherlife);
1161                     break;
1162                 }
1163                 /* otherweise check the next range */
1164                 continue;
1165             }
1166             break;
1167         }
1168     }
1169     return true;
1170 }
1171
1172 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1173 {
1174     /* For any life entry in A see if it overlaps with
1175      * any life entry in B.
1176      * Note that the life entries are orderes, so we can make a
1177      * more efficient algorithm there than naively translating the
1178      * statement above.
1179      */
1180
1181     const ir_life_entry_t *la, *lb, *enda, *endb;
1182
1183     /* first of all, if either has no life range, they cannot clash */
1184     if (a->m_life.empty() || b->m_life.empty())
1185         return false;
1186
1187     la = &a->m_life.front();
1188     lb = &b->m_life.front();
1189     enda = &a->m_life.back() + 1;
1190     endb = &b->m_life.back() + 1;
1191     while (true)
1192     {
1193         /* check if the entries overlap, for that,
1194          * both must start before the other one ends.
1195          */
1196         if (la->start < lb->end &&
1197             lb->start < la->end)
1198         {
1199             return true;
1200         }
1201
1202         /* entries are ordered
1203          * one entry is earlier than the other
1204          * that earlier entry will be moved forward
1205          */
1206         if (la->start < lb->start)
1207         {
1208             /* order: A B, move A forward
1209              * check if we hit the end with A
1210              */
1211             if (++la == enda)
1212                 break;
1213         }
1214         else /* if (lb->start < la->start)  actually <= */
1215         {
1216             /* order: B A, move B forward
1217              * check if we hit the end with B
1218              */
1219             if (++lb == endb)
1220                 break;
1221         }
1222     }
1223     return false;
1224 }
1225
1226 /***********************************************************************
1227  *IR main operations
1228  */
1229
1230 static bool ir_check_unreachable(ir_block *self)
1231 {
1232     /* The IR should never have to deal with unreachable code */
1233     if (!self->m_final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1234         return true;
1235     irerror(self->m_context, "unreachable statement (%s)", self->m_label.c_str());
1236     return false;
1237 }
1238
1239 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1240 {
1241     ir_instr *in;
1242     if (!ir_check_unreachable(self))
1243         return false;
1244
1245     if (target->m_store == store_value &&
1246         (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1247     {
1248         irerror(self->m_context, "cannot store to an SSA value");
1249         irerror(self->m_context, "trying to store: %s <- %s", target->m_name.c_str(), what->m_name.c_str());
1250         irerror(self->m_context, "instruction: %s", util_instr_str[op]);
1251         return false;
1252     }
1253
1254     in = new ir_instr(ctx, self, op);
1255     if (!in)
1256         return false;
1257
1258     if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1259         !ir_instr_op(in, 1, what, false))
1260     {
1261         delete in;
1262         return false;
1263     }
1264     self->m_instr.push_back(in);
1265     return true;
1266 }
1267
1268 bool ir_block_create_state_op(ir_block *self, lex_ctx_t ctx, ir_value *frame, ir_value *think)
1269 {
1270     ir_instr *in;
1271     if (!ir_check_unreachable(self))
1272         return false;
1273
1274     in = new ir_instr(ctx, self, INSTR_STATE);
1275     if (!in)
1276         return false;
1277
1278     if (!ir_instr_op(in, 0, frame, false) ||
1279         !ir_instr_op(in, 1, think, false))
1280     {
1281         delete in;
1282         return false;
1283     }
1284     self->m_instr.push_back(in);
1285     return true;
1286 }
1287
1288 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1289 {
1290     int op = 0;
1291     qc_type vtype;
1292     if (target->m_vtype == TYPE_VARIANT)
1293         vtype = what->m_vtype;
1294     else
1295         vtype = target->m_vtype;
1296
1297 #if 0
1298     if      (vtype == TYPE_FLOAT   && what->m_vtype == TYPE_INTEGER)
1299         op = INSTR_CONV_ITOF;
1300     else if (vtype == TYPE_INTEGER && what->m_vtype == TYPE_FLOAT)
1301         op = INSTR_CONV_FTOI;
1302 #endif
1303         op = type_store_instr[vtype];
1304
1305     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1306         if (op == INSTR_STORE_FLD && what->m_fieldtype == TYPE_VECTOR)
1307             op = INSTR_STORE_V;
1308     }
1309
1310     return ir_block_create_store_op(self, ctx, op, target, what);
1311 }
1312
1313 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1314 {
1315     int op = 0;
1316     qc_type vtype;
1317
1318     if (target->m_vtype != TYPE_POINTER)
1319         return false;
1320
1321     /* storing using pointer - target is a pointer, type must be
1322      * inferred from source
1323      */
1324     vtype = what->m_vtype;
1325
1326     op = type_storep_instr[vtype];
1327     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1328         if (op == INSTR_STOREP_FLD && what->m_fieldtype == TYPE_VECTOR)
1329             op = INSTR_STOREP_V;
1330     }
1331
1332     return ir_block_create_store_op(self, ctx, op, target, what);
1333 }
1334
1335 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1336 {
1337     ir_instr *in;
1338     if (!ir_check_unreachable(self))
1339         return false;
1340
1341     self->m_final = true;
1342
1343     self->m_is_return = true;
1344     in = new ir_instr(ctx, self, INSTR_RETURN);
1345     if (!in)
1346         return false;
1347
1348     if (v && !ir_instr_op(in, 0, v, false)) {
1349         delete in;
1350         return false;
1351     }
1352
1353     self->m_instr.push_back(in);
1354     return true;
1355 }
1356
1357 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1358                         ir_block *ontrue, ir_block *onfalse)
1359 {
1360     ir_instr *in;
1361     if (!ir_check_unreachable(self))
1362         return false;
1363     self->m_final = true;
1364     /*in = new ir_instr(ctx, self, (v->m_vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1365     in = new ir_instr(ctx, self, VINSTR_COND);
1366     if (!in)
1367         return false;
1368
1369     if (!ir_instr_op(in, 0, v, false)) {
1370         delete in;
1371         return false;
1372     }
1373
1374     in->m_bops[0] = ontrue;
1375     in->m_bops[1] = onfalse;
1376
1377     self->m_instr.push_back(in);
1378
1379     self->m_exits.push_back(ontrue);
1380     self->m_exits.push_back(onfalse);
1381     ontrue->m_entries.push_back(self);
1382     onfalse->m_entries.push_back(self);
1383     return true;
1384 }
1385
1386 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1387 {
1388     ir_instr *in;
1389     if (!ir_check_unreachable(self))
1390         return false;
1391     self->m_final = true;
1392     in = new ir_instr(ctx, self, VINSTR_JUMP);
1393     if (!in)
1394         return false;
1395
1396     in->m_bops[0] = to;
1397     self->m_instr.push_back(in);
1398
1399     self->m_exits.push_back(to);
1400     to->m_entries.push_back(self);
1401     return true;
1402 }
1403
1404 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1405 {
1406     self->m_owner->m_flags |= IR_FLAG_HAS_GOTO;
1407     return ir_block_create_jump(self, ctx, to);
1408 }
1409
1410 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, qc_type ot)
1411 {
1412     ir_value *out;
1413     ir_instr *in;
1414     if (!ir_check_unreachable(self))
1415         return nullptr;
1416     in = new ir_instr(ctx, self, VINSTR_PHI);
1417     if (!in)
1418         return nullptr;
1419     out = new ir_value(self->m_owner, label ? label : "", store_value, ot);
1420     if (!out) {
1421         delete in;
1422         return nullptr;
1423     }
1424     if (!ir_instr_op(in, 0, out, true)) {
1425         delete in;
1426         return nullptr;
1427     }
1428     self->m_instr.push_back(in);
1429     return in;
1430 }
1431
1432 ir_value* ir_phi_value(ir_instr *self)
1433 {
1434     return self->_m_ops[0];
1435 }
1436
1437 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1438 {
1439     ir_phi_entry_t pe;
1440
1441     if (!vec_ir_block_find(self->m_owner->m_entries, b, nullptr)) {
1442         // Must not be possible to cause this, otherwise the AST
1443         // is doing something wrong.
1444         irerror(self->m_context, "Invalid entry block for PHI");
1445         exit(EXIT_FAILURE);
1446     }
1447
1448     pe.value = v;
1449     pe.from = b;
1450     v->m_reads.push_back(self);
1451     self->m_phi.push_back(pe);
1452 }
1453
1454 /* call related code */
1455 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1456 {
1457     ir_value *out;
1458     ir_instr *in;
1459     if (!ir_check_unreachable(self))
1460         return nullptr;
1461     in = new ir_instr(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1462     if (!in)
1463         return nullptr;
1464     if (noreturn) {
1465         self->m_final = true;
1466         self->m_is_return = true;
1467     }
1468     out = new ir_value(self->m_owner, label ? label : "", (func->m_outtype == TYPE_VOID) ? store_return : store_value, func->m_outtype);
1469     if (!out) {
1470         delete in;
1471         return nullptr;
1472     }
1473     if (!ir_instr_op(in, 0, out, true) ||
1474         !ir_instr_op(in, 1, func, false))
1475     {
1476         delete in;
1477         return nullptr;
1478     }
1479     self->m_instr.push_back(in);
1480     /*
1481     if (noreturn) {
1482         if (!ir_block_create_return(self, ctx, nullptr)) {
1483             compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1484             delete in;
1485             return nullptr;
1486         }
1487     }
1488     */
1489     return in;
1490 }
1491
1492 ir_value* ir_call_value(ir_instr *self)
1493 {
1494     return self->_m_ops[0];
1495 }
1496
1497 void ir_call_param(ir_instr* self, ir_value *v)
1498 {
1499     self->m_params.push_back(v);
1500     v->m_reads.push_back(self);
1501 }
1502
1503 /* binary op related code */
1504
1505 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1506                                 const char *label, int opcode,
1507                                 ir_value *left, ir_value *right)
1508 {
1509     qc_type ot = TYPE_VOID;
1510     switch (opcode) {
1511         case INSTR_ADD_F:
1512         case INSTR_SUB_F:
1513         case INSTR_DIV_F:
1514         case INSTR_MUL_F:
1515         case INSTR_MUL_V:
1516         case INSTR_AND:
1517         case INSTR_OR:
1518 #if 0
1519         case INSTR_AND_I:
1520         case INSTR_AND_IF:
1521         case INSTR_AND_FI:
1522         case INSTR_OR_I:
1523         case INSTR_OR_IF:
1524         case INSTR_OR_FI:
1525 #endif
1526         case INSTR_BITAND:
1527         case INSTR_BITOR:
1528         case VINSTR_BITXOR:
1529 #if 0
1530         case INSTR_SUB_S: /* -- offset of string as float */
1531         case INSTR_MUL_IF:
1532         case INSTR_MUL_FI:
1533         case INSTR_DIV_IF:
1534         case INSTR_DIV_FI:
1535         case INSTR_BITOR_IF:
1536         case INSTR_BITOR_FI:
1537         case INSTR_BITAND_FI:
1538         case INSTR_BITAND_IF:
1539         case INSTR_EQ_I:
1540         case INSTR_NE_I:
1541 #endif
1542             ot = TYPE_FLOAT;
1543             break;
1544 #if 0
1545         case INSTR_ADD_I:
1546         case INSTR_ADD_IF:
1547         case INSTR_ADD_FI:
1548         case INSTR_SUB_I:
1549         case INSTR_SUB_FI:
1550         case INSTR_SUB_IF:
1551         case INSTR_MUL_I:
1552         case INSTR_DIV_I:
1553         case INSTR_BITAND_I:
1554         case INSTR_BITOR_I:
1555         case INSTR_XOR_I:
1556         case INSTR_RSHIFT_I:
1557         case INSTR_LSHIFT_I:
1558             ot = TYPE_INTEGER;
1559             break;
1560 #endif
1561         case INSTR_ADD_V:
1562         case INSTR_SUB_V:
1563         case INSTR_MUL_VF:
1564         case INSTR_MUL_FV:
1565         case VINSTR_BITAND_V:
1566         case VINSTR_BITOR_V:
1567         case VINSTR_BITXOR_V:
1568         case VINSTR_BITAND_VF:
1569         case VINSTR_BITOR_VF:
1570         case VINSTR_BITXOR_VF:
1571         case VINSTR_CROSS:
1572 #if 0
1573         case INSTR_DIV_VF:
1574         case INSTR_MUL_IV:
1575         case INSTR_MUL_VI:
1576 #endif
1577             ot = TYPE_VECTOR;
1578             break;
1579 #if 0
1580         case INSTR_ADD_SF:
1581             ot = TYPE_POINTER;
1582             break;
1583 #endif
1584     /*
1585      * after the following default case, the value of opcode can never
1586      * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1587      */
1588         default:
1589             /* ranges: */
1590             /* boolean operations result in floats */
1591
1592             /*
1593              * opcode >= 10 takes true branch opcode is at least 10
1594              * opcode <= 23 takes false branch opcode is at least 24
1595              */
1596             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1597                 ot = TYPE_FLOAT;
1598
1599             /*
1600              * At condition "opcode <= 23", the value of "opcode" must be
1601              * at least 24.
1602              * At condition "opcode <= 23", the value of "opcode" cannot be
1603              * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1604              * The condition "opcode <= 23" cannot be true.
1605              *
1606              * Thus ot=2 (TYPE_FLOAT) can never be true
1607              */
1608 #if 0
1609             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1610                 ot = TYPE_FLOAT;
1611             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1612                 ot = TYPE_FLOAT;
1613 #endif
1614             break;
1615     };
1616     if (ot == TYPE_VOID) {
1617         /* The AST or parser were supposed to check this! */
1618         return nullptr;
1619     }
1620
1621     return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1622 }
1623
1624 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1625                                 const char *label, int opcode,
1626                                 ir_value *operand)
1627 {
1628     qc_type ot = TYPE_FLOAT;
1629     switch (opcode) {
1630         case INSTR_NOT_F:
1631         case INSTR_NOT_V:
1632         case INSTR_NOT_S:
1633         case INSTR_NOT_ENT:
1634         case INSTR_NOT_FNC: /*
1635         case INSTR_NOT_I:   */
1636             ot = TYPE_FLOAT;
1637             break;
1638
1639         /*
1640          * Negation for virtual instructions is emulated with 0-value. Thankfully
1641          * the operand for 0 already exists so we just source it from here.
1642          */
1643         case VINSTR_NEG_F:
1644             return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_F, nullptr, operand, ot);
1645         case VINSTR_NEG_V:
1646             return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_V, nullptr, operand, TYPE_VECTOR);
1647
1648         default:
1649             ot = operand->m_vtype;
1650             break;
1651     };
1652     if (ot == TYPE_VOID) {
1653         /* The AST or parser were supposed to check this! */
1654         return nullptr;
1655     }
1656
1657     /* let's use the general instruction creator and pass nullptr for OPB */
1658     return ir_block_create_general_instr(self, ctx, label, opcode, operand, nullptr, ot);
1659 }
1660
1661 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1662                                         int op, ir_value *a, ir_value *b, qc_type outype)
1663 {
1664     ir_instr *instr;
1665     ir_value *out;
1666
1667     out = new ir_value(self->m_owner, label ? label : "", store_value, outype);
1668     if (!out)
1669         return nullptr;
1670
1671     instr = new ir_instr(ctx, self, op);
1672     if (!instr) {
1673         return nullptr;
1674     }
1675
1676     if (!ir_instr_op(instr, 0, out, true) ||
1677         !ir_instr_op(instr, 1, a, false) ||
1678         !ir_instr_op(instr, 2, b, false) )
1679     {
1680         goto on_error;
1681     }
1682
1683     self->m_instr.push_back(instr);
1684
1685     return out;
1686 on_error:
1687     delete instr;
1688     return nullptr;
1689 }
1690
1691 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1692 {
1693     ir_value *v;
1694
1695     /* Support for various pointer types todo if so desired */
1696     if (ent->m_vtype != TYPE_ENTITY)
1697         return nullptr;
1698
1699     if (field->m_vtype != TYPE_FIELD)
1700         return nullptr;
1701
1702     v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1703     v->m_fieldtype = field->m_fieldtype;
1704     return v;
1705 }
1706
1707 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 {
1709     int op;
1710     if (ent->m_vtype != TYPE_ENTITY)
1711         return nullptr;
1712
1713     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1714     if (field->m_vtype != TYPE_FIELD)
1715         return nullptr;
1716
1717     switch (outype)
1718     {
1719         case TYPE_FLOAT:    op = INSTR_LOAD_F;   break;
1720         case TYPE_VECTOR:   op = INSTR_LOAD_V;   break;
1721         case TYPE_STRING:   op = INSTR_LOAD_S;   break;
1722         case TYPE_FIELD:    op = INSTR_LOAD_FLD; break;
1723         case TYPE_ENTITY:   op = INSTR_LOAD_ENT; break;
1724         case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1725 #if 0
1726         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1727         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1728 #endif
1729         default:
1730             irerror(self->m_context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1731             return nullptr;
1732     }
1733
1734     return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1735 }
1736
1737 /* PHI resolving breaks the SSA, and must thus be the last
1738  * step before life-range calculation.
1739  */
1740
1741 static bool ir_block_naive_phi(ir_block *self);
1742 bool ir_function_naive_phi(ir_function *self)
1743 {
1744     for (auto& b : self->m_blocks)
1745         if (!ir_block_naive_phi(b.get()))
1746             return false;
1747     return true;
1748 }
1749
1750 static bool ir_block_naive_phi(ir_block *self)
1751 {
1752     size_t i;
1753     /* FIXME: optionally, create_phi can add the phis
1754      * to a list so we don't need to loop through blocks
1755      * - anyway: "don't optimize YET"
1756      */
1757     for (i = 0; i < self->m_instr.size(); ++i)
1758     {
1759         ir_instr *instr = self->m_instr[i];
1760         if (instr->m_opcode != VINSTR_PHI)
1761             continue;
1762
1763         self->m_instr.erase(self->m_instr.begin()+i);
1764         --i; /* NOTE: i+1 below */
1765
1766         for (auto &it : instr->m_phi) {
1767             ir_value *v = it.value;
1768             ir_block *b = it.from;
1769             if (v->m_store == store_value && v->m_reads.size() == 1 && v->m_writes.size() == 1) {
1770                 /* replace the value */
1771                 if (!ir_instr_op(v->m_writes[0], 0, instr->_m_ops[0], true))
1772                     return false;
1773             } else {
1774                 /* force a move instruction */
1775                 ir_instr *prevjump = b->m_instr.back();
1776                 b->m_instr.pop_back();
1777                 b->m_final = false;
1778                 instr->_m_ops[0]->m_store = store_global;
1779                 if (!ir_block_create_store(b, instr->m_context, instr->_m_ops[0], v))
1780                     return false;
1781                 instr->_m_ops[0]->m_store = store_value;
1782                 b->m_instr.push_back(prevjump);
1783                 b->m_final = true;
1784             }
1785         }
1786         delete instr;
1787     }
1788     return true;
1789 }
1790
1791 /***********************************************************************
1792  *IR Temp allocation code
1793  * Propagating value life ranges by walking through the function backwards
1794  * until no more changes are made.
1795  * In theory this should happen once more than once for every nested loop
1796  * level.
1797  * Though this implementation might run an additional time for if nests.
1798  */
1799
1800 /* Enumerate instructions used by value's life-ranges
1801  */
1802 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1803 {
1804     size_t eid = *_eid;
1805     for (auto &i : self->m_instr)
1806         i->m_eid = eid++;
1807     *_eid = eid;
1808 }
1809
1810 /* Enumerate blocks and instructions.
1811  * The block-enumeration is unordered!
1812  * We do not really use the block enumreation, however
1813  * the instruction enumeration is important for life-ranges.
1814  */
1815 void ir_function_enumerate(ir_function *self)
1816 {
1817     size_t instruction_id = 0;
1818     size_t block_eid = 0;
1819     for (auto& block : self->m_blocks)
1820     {
1821         /* each block now gets an additional "entry" instruction id
1822          * we can use to avoid point-life issues
1823          */
1824         block->m_entry_id = instruction_id;
1825         block->m_eid      = block_eid;
1826         ++instruction_id;
1827         ++block_eid;
1828
1829         ir_block_enumerate(block.get(), &instruction_id);
1830     }
1831 }
1832
1833 /* Local-value allocator
1834  * After finishing creating the liferange of all values used in a function
1835  * we can allocate their global-positions.
1836  * This is the counterpart to register-allocation in register machines.
1837  */
1838 struct function_allocator {
1839     ir_value **locals;
1840     size_t *sizes;
1841     size_t *positions;
1842     bool *unique;
1843 };
1844
1845 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
1846 {
1847     ir_value *slot;
1848     size_t vsize = var->size();
1849
1850     var->m_code.local = vec_size(alloc->locals);
1851
1852     slot = new ir_value("reg", store_global, var->m_vtype);
1853     if (!slot)
1854         return false;
1855
1856     if (!slot->mergeLife(var))
1857         goto localerror;
1858
1859     vec_push(alloc->locals, slot);
1860     vec_push(alloc->sizes, vsize);
1861     vec_push(alloc->unique, var->m_unique_life);
1862
1863     return true;
1864
1865 localerror:
1866     delete slot;
1867     return false;
1868 }
1869
1870 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
1871 {
1872     size_t a;
1873     ir_value *slot;
1874
1875     if (v->m_unique_life)
1876         return function_allocator_alloc(alloc, v);
1877
1878     for (a = 0; a < vec_size(alloc->locals); ++a)
1879     {
1880         /* if it's reserved for a unique liferange: skip */
1881         if (alloc->unique[a])
1882             continue;
1883
1884         slot = alloc->locals[a];
1885
1886         /* never resize parameters
1887          * will be required later when overlapping temps + locals
1888          */
1889         if (a < vec_size(self->m_params) &&
1890             alloc->sizes[a] < v->size())
1891         {
1892             continue;
1893         }
1894
1895         if (ir_values_overlap(v, slot))
1896             continue;
1897
1898         if (!slot->mergeLife(v))
1899             return false;
1900
1901         /* adjust size for this slot */
1902         if (alloc->sizes[a] < v->size())
1903             alloc->sizes[a] = v->size();
1904
1905         v->m_code.local = a;
1906         return true;
1907     }
1908     if (a >= vec_size(alloc->locals)) {
1909         if (!function_allocator_alloc(alloc, v))
1910             return false;
1911     }
1912     return true;
1913 }
1914
1915 bool ir_function_allocate_locals(ir_function *self)
1916 {
1917     bool   retval = true;
1918     size_t pos;
1919     bool   opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
1920
1921     function_allocator lockalloc, globalloc;
1922
1923     if (self->m_locals.empty() && self->m_values.empty())
1924         return true;
1925
1926     globalloc.locals    = nullptr;
1927     globalloc.sizes     = nullptr;
1928     globalloc.positions = nullptr;
1929     globalloc.unique    = nullptr;
1930     lockalloc.locals    = nullptr;
1931     lockalloc.sizes     = nullptr;
1932     lockalloc.positions = nullptr;
1933     lockalloc.unique    = nullptr;
1934
1935     size_t i;
1936     for (i = 0; i < self->m_locals.size(); ++i)
1937     {
1938         ir_value *v = self->m_locals[i].get();
1939         if ((self->m_flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
1940             v->m_locked      = true;
1941             v->m_unique_life = true;
1942         }
1943         else if (i >= vec_size(self->m_params))
1944             break;
1945         else
1946             v->m_locked = true; /* lock parameters locals */
1947         if (!function_allocator_alloc((v->m_locked || !opt_gt ? &lockalloc : &globalloc), v))
1948             goto error;
1949     }
1950     for (; i < self->m_locals.size(); ++i)
1951     {
1952         ir_value *v = self->m_locals[i].get();
1953         if (v->m_life.empty())
1954             continue;
1955         if (!ir_function_allocator_assign(self, (v->m_locked || !opt_gt ? &lockalloc : &globalloc), v))
1956             goto error;
1957     }
1958
1959     /* Allocate a slot for any value that still exists */
1960     for (i = 0; i < self->m_values.size(); ++i)
1961     {
1962         ir_value *v = self->m_values[i].get();
1963
1964         if (v->m_life.empty())
1965             continue;
1966
1967         /* CALL optimization:
1968          * If the value is a parameter-temp: 1 write, 1 read from a CALL
1969          * and it's not "locked", write it to the OFS_PARM directly.
1970          */
1971         if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->m_locked && !v->m_unique_life) {
1972             if (v->m_reads.size() == 1 && v->m_writes.size() == 1 &&
1973                 (v->m_reads[0]->m_opcode == VINSTR_NRCALL ||
1974                  (v->m_reads[0]->m_opcode >= INSTR_CALL0 && v->m_reads[0]->m_opcode <= INSTR_CALL8)
1975                 )
1976                )
1977             {
1978                 size_t param;
1979                 ir_instr *call = v->m_reads[0];
1980                 if (!vec_ir_value_find(call->m_params, v, &param)) {
1981                     irerror(call->m_context, "internal error: unlocked parameter %s not found", v->m_name.c_str());
1982                     goto error;
1983                 }
1984                 ++opts_optimizationcount[OPTIM_CALL_STORES];
1985                 v->m_callparam = true;
1986                 if (param < 8)
1987                     v->setCodeAddress(OFS_PARM0 + 3*param);
1988                 else {
1989                     size_t nprotos = self->m_owner->m_extparam_protos.size();
1990                     ir_value *ep;
1991                     param -= 8;
1992                     if (nprotos > param)
1993                         ep = self->m_owner->m_extparam_protos[param].get();
1994                     else
1995                     {
1996                         ep = self->m_owner->generateExtparamProto();
1997                         while (++nprotos <= param)
1998                             ep = self->m_owner->generateExtparamProto();
1999                     }
2000                     ir_instr_op(v->m_writes[0], 0, ep, true);
2001                     call->m_params[param+8] = ep;
2002                 }
2003                 continue;
2004             }
2005             if (v->m_writes.size() == 1 && v->m_writes[0]->m_opcode == INSTR_CALL0) {
2006                 v->m_store = store_return;
2007                 if (v->m_members[0]) v->m_members[0]->m_store = store_return;
2008                 if (v->m_members[1]) v->m_members[1]->m_store = store_return;
2009                 if (v->m_members[2]) v->m_members[2]->m_store = store_return;
2010                 ++opts_optimizationcount[OPTIM_CALL_STORES];
2011                 continue;
2012             }
2013         }
2014
2015         if (!ir_function_allocator_assign(self, (v->m_locked || !opt_gt ? &lockalloc : &globalloc), v))
2016             goto error;
2017     }
2018
2019     if (!lockalloc.sizes && !globalloc.sizes) {
2020         goto cleanup;
2021     }
2022     vec_push(lockalloc.positions, 0);
2023     vec_push(globalloc.positions, 0);
2024
2025     /* Adjust slot positions based on sizes */
2026     if (lockalloc.sizes) {
2027         pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2028         for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2029         {
2030             pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2031             vec_push(lockalloc.positions, pos);
2032         }
2033         self->m_allocated_locals = pos + vec_last(lockalloc.sizes);
2034     }
2035     if (globalloc.sizes) {
2036         pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2037         for (i = 1; i < vec_size(globalloc.sizes); ++i)
2038         {
2039             pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2040             vec_push(globalloc.positions, pos);
2041         }
2042         self->m_globaltemps = pos + vec_last(globalloc.sizes);
2043     }
2044
2045     /* Locals need to know their new position */
2046     for (auto& local : self->m_locals) {
2047         if (local->m_locked || !opt_gt)
2048             local->m_code.local = lockalloc.positions[local->m_code.local];
2049         else
2050             local->m_code.local = globalloc.positions[local->m_code.local];
2051     }
2052     /* Take over the actual slot positions on values */
2053     for (auto& value : self->m_values) {
2054         if (value->m_locked || !opt_gt)
2055             value->m_code.local = lockalloc.positions[value->m_code.local];
2056         else
2057             value->m_code.local = globalloc.positions[value->m_code.local];
2058     }
2059
2060     goto cleanup;
2061
2062 error:
2063     retval = false;
2064 cleanup:
2065     for (i = 0; i < vec_size(lockalloc.locals); ++i)
2066         delete lockalloc.locals[i];
2067     for (i = 0; i < vec_size(globalloc.locals); ++i)
2068         delete globalloc.locals[i];
2069     vec_free(globalloc.unique);
2070     vec_free(globalloc.locals);
2071     vec_free(globalloc.sizes);
2072     vec_free(globalloc.positions);
2073     vec_free(lockalloc.unique);
2074     vec_free(lockalloc.locals);
2075     vec_free(lockalloc.sizes);
2076     vec_free(lockalloc.positions);
2077     return retval;
2078 }
2079
2080 /* Get information about which operand
2081  * is read from, or written to.
2082  */
2083 static void ir_op_read_write(int op, size_t *read, size_t *write)
2084 {
2085     switch (op)
2086     {
2087     case VINSTR_JUMP:
2088     case INSTR_GOTO:
2089         *write = 0;
2090         *read = 0;
2091         break;
2092     case INSTR_IF:
2093     case INSTR_IFNOT:
2094 #if 0
2095     case INSTR_IF_S:
2096     case INSTR_IFNOT_S:
2097 #endif
2098     case INSTR_RETURN:
2099     case VINSTR_COND:
2100         *write = 0;
2101         *read = 1;
2102         break;
2103     case INSTR_STOREP_F:
2104     case INSTR_STOREP_V:
2105     case INSTR_STOREP_S:
2106     case INSTR_STOREP_ENT:
2107     case INSTR_STOREP_FLD:
2108     case INSTR_STOREP_FNC:
2109         *write = 0;
2110         *read  = 7;
2111         break;
2112     default:
2113         *write = 1;
2114         *read = 6;
2115         break;
2116     };
2117 }
2118
2119 static bool ir_block_living_add_instr(ir_block *self, size_t eid) {
2120     bool changed = false;
2121     for (auto &it : self->m_living)
2122         if (it->setAlive(eid))
2123             changed = true;
2124     return changed;
2125 }
2126
2127 static bool ir_block_living_lock(ir_block *self) {
2128     bool changed = false;
2129     for (auto &it : self->m_living) {
2130         if (it->m_locked)
2131             continue;
2132         it->m_locked = true;
2133         changed = true;
2134     }
2135     return changed;
2136 }
2137
2138 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2139 {
2140     ir_instr *instr;
2141     ir_value *value;
2142     size_t i, o, mem;
2143     // bitmasks which operands are read from or written to
2144     size_t read, write;
2145
2146     self->m_living.clear();
2147
2148     for (auto &prev : self->m_exits) {
2149         for (auto &it : prev->m_living)
2150             if (!vec_ir_value_find(self->m_living, it, nullptr))
2151                 self->m_living.push_back(it);
2152     }
2153
2154     i = self->m_instr.size();
2155     while (i)
2156     { --i;
2157         instr = self->m_instr[i];
2158
2159         /* See which operands are read and write operands */
2160         ir_op_read_write(instr->m_opcode, &read, &write);
2161
2162         /* Go through the 3 main operands
2163          * writes first, then reads
2164          */
2165         for (o = 0; o < 3; ++o)
2166         {
2167             if (!instr->_m_ops[o]) /* no such operand */
2168                 continue;
2169
2170             value = instr->_m_ops[o];
2171
2172             /* We only care about locals */
2173             /* we also calculate parameter liferanges so that locals
2174              * can take up parameter slots */
2175             if (value->m_store != store_value &&
2176                 value->m_store != store_local &&
2177                 value->m_store != store_param)
2178                 continue;
2179
2180             /* write operands */
2181             /* When we write to a local, we consider it "dead" for the
2182              * remaining upper part of the function, since in SSA a value
2183              * can only be written once (== created)
2184              */
2185             if (write & (1<<o))
2186             {
2187                 size_t idx;
2188                 bool in_living = vec_ir_value_find(self->m_living, value, &idx);
2189                 if (!in_living)
2190                 {
2191                     /* If the value isn't alive it hasn't been read before... */
2192                     /* TODO: See if the warning can be emitted during parsing or AST processing
2193                      * otherwise have warning printed here.
2194                      * IF printing a warning here: include filecontext_t,
2195                      * and make sure it's only printed once
2196                      * since this function is run multiple times.
2197                      */
2198                     /* con_err( "Value only written %s\n", value->m_name); */
2199                     if (value->setAlive(instr->m_eid))
2200                         *changed = true;
2201                 } else {
2202                     /* since 'living' won't contain it
2203                      * anymore, merge the value, since
2204                      * (A) doesn't.
2205                      */
2206                     if (value->setAlive(instr->m_eid))
2207                         *changed = true;
2208                     // Then remove
2209                     self->m_living.erase(self->m_living.begin() + idx);
2210                 }
2211                 /* Removing a vector removes all members */
2212                 for (mem = 0; mem < 3; ++mem) {
2213                     if (value->m_members[mem] && vec_ir_value_find(self->m_living, value->m_members[mem], &idx)) {
2214                         if (value->m_members[mem]->setAlive(instr->m_eid))
2215                             *changed = true;
2216                         self->m_living.erase(self->m_living.begin() + idx);
2217                     }
2218                 }
2219                 /* Removing the last member removes the vector */
2220                 if (value->m_memberof) {
2221                     value = value->m_memberof;
2222                     for (mem = 0; mem < 3; ++mem) {
2223                         if (value->m_members[mem] && vec_ir_value_find(self->m_living, value->m_members[mem], nullptr))
2224                             break;
2225                     }
2226                     if (mem == 3 && vec_ir_value_find(self->m_living, value, &idx)) {
2227                         if (value->setAlive(instr->m_eid))
2228                             *changed = true;
2229                         self->m_living.erase(self->m_living.begin() + idx);
2230                     }
2231                 }
2232             }
2233         }
2234
2235         /* These operations need a special case as they can break when using
2236          * same source and destination operand otherwise, as the engine may
2237          * read the source multiple times. */
2238         if (instr->m_opcode == INSTR_MUL_VF ||
2239             instr->m_opcode == VINSTR_BITAND_VF ||
2240             instr->m_opcode == VINSTR_BITOR_VF ||
2241             instr->m_opcode == VINSTR_BITXOR ||
2242             instr->m_opcode == VINSTR_BITXOR_VF ||
2243             instr->m_opcode == VINSTR_BITXOR_V ||
2244             instr->m_opcode == VINSTR_CROSS)
2245         {
2246             value = instr->_m_ops[2];
2247             /* the float source will get an additional lifetime */
2248             if (value->setAlive(instr->m_eid+1))
2249                 *changed = true;
2250             if (value->m_memberof && value->m_memberof->setAlive(instr->m_eid+1))
2251                 *changed = true;
2252         }
2253
2254         if (instr->m_opcode == INSTR_MUL_FV ||
2255             instr->m_opcode == INSTR_LOAD_V ||
2256             instr->m_opcode == VINSTR_BITXOR ||
2257             instr->m_opcode == VINSTR_BITXOR_VF ||
2258             instr->m_opcode == VINSTR_BITXOR_V ||
2259             instr->m_opcode == VINSTR_CROSS)
2260         {
2261             value = instr->_m_ops[1];
2262             /* the float source will get an additional lifetime */
2263             if (value->setAlive(instr->m_eid+1))
2264                 *changed = true;
2265             if (value->m_memberof && value->m_memberof->setAlive(instr->m_eid+1))
2266                 *changed = true;
2267         }
2268
2269         for (o = 0; o < 3; ++o)
2270         {
2271             if (!instr->_m_ops[o]) /* no such operand */
2272                 continue;
2273
2274             value = instr->_m_ops[o];
2275
2276             /* We only care about locals */
2277             /* we also calculate parameter liferanges so that locals
2278              * can take up parameter slots */
2279             if (value->m_store != store_value &&
2280                 value->m_store != store_local &&
2281                 value->m_store != store_param)
2282                 continue;
2283
2284             /* read operands */
2285             if (read & (1<<o))
2286             {
2287                 if (!vec_ir_value_find(self->m_living, value, nullptr))
2288                     self->m_living.push_back(value);
2289                 /* reading adds the full vector */
2290                 if (value->m_memberof && !vec_ir_value_find(self->m_living, value->m_memberof, nullptr))
2291                     self->m_living.push_back(value->m_memberof);
2292                 for (mem = 0; mem < 3; ++mem) {
2293                     if (value->m_members[mem] && !vec_ir_value_find(self->m_living, value->m_members[mem], nullptr))
2294                         self->m_living.push_back(value->m_members[mem]);
2295                 }
2296             }
2297         }
2298         /* PHI operands are always read operands */
2299         for (auto &it : instr->m_phi) {
2300             value = it.value;
2301             if (!vec_ir_value_find(self->m_living, value, nullptr))
2302                 self->m_living.push_back(value);
2303             /* reading adds the full vector */
2304             if (value->m_memberof && !vec_ir_value_find(self->m_living, value->m_memberof, nullptr))
2305                 self->m_living.push_back(value->m_memberof);
2306             for (mem = 0; mem < 3; ++mem) {
2307                 if (value->m_members[mem] && !vec_ir_value_find(self->m_living, value->m_members[mem], nullptr))
2308                     self->m_living.push_back(value->m_members[mem]);
2309             }
2310         }
2311
2312         /* on a call, all these values must be "locked" */
2313         if (instr->m_opcode >= INSTR_CALL0 && instr->m_opcode <= INSTR_CALL8) {
2314             if (ir_block_living_lock(self))
2315                 *changed = true;
2316         }
2317         /* call params are read operands too */
2318         for (auto &it : instr->m_params) {
2319             value = it;
2320             if (!vec_ir_value_find(self->m_living, value, nullptr))
2321                 self->m_living.push_back(value);
2322             /* reading adds the full vector */
2323             if (value->m_memberof && !vec_ir_value_find(self->m_living, value->m_memberof, nullptr))
2324                 self->m_living.push_back(value->m_memberof);
2325             for (mem = 0; mem < 3; ++mem) {
2326                 if (value->m_members[mem] && !vec_ir_value_find(self->m_living, value->m_members[mem], nullptr))
2327                     self->m_living.push_back(value->m_members[mem]);
2328             }
2329         }
2330
2331         /* (A) */
2332         if (ir_block_living_add_instr(self, instr->m_eid))
2333             *changed = true;
2334     }
2335     /* the "entry" instruction ID */
2336     if (ir_block_living_add_instr(self, self->m_entry_id))
2337         *changed = true;
2338
2339     return true;
2340 }
2341
2342 bool ir_function_calculate_liferanges(ir_function *self)
2343 {
2344     /* parameters live at 0 */
2345     for (size_t i = 0; i < vec_size(self->m_params); ++i)
2346         if (!self->m_locals[i].get()->setAlive(0))
2347             compile_error(self->m_context, "internal error: failed value-life merging");
2348
2349     bool changed;
2350     do {
2351         self->m_run_id++;
2352         changed = false;
2353         for (auto i = self->m_blocks.rbegin(); i != self->m_blocks.rend(); ++i)
2354             ir_block_life_propagate(i->get(), &changed);
2355     } while (changed);
2356
2357     if (self->m_blocks.size()) {
2358         ir_block *block = self->m_blocks[0].get();
2359         for (auto &it : block->m_living) {
2360             ir_value *v = it;
2361             if (v->m_store != store_local)
2362                 continue;
2363             if (v->m_vtype == TYPE_VECTOR)
2364                 continue;
2365             self->m_flags |= IR_FLAG_HAS_UNINITIALIZED;
2366             /* find the instruction reading from it */
2367             size_t s = 0;
2368             for (; s < v->m_reads.size(); ++s) {
2369                 if (v->m_reads[s]->m_eid == v->m_life[0].end)
2370                     break;
2371             }
2372             if (s < v->m_reads.size()) {
2373                 if (irwarning(v->m_context, WARN_USED_UNINITIALIZED,
2374                               "variable `%s` may be used uninitialized in this function\n"
2375                               " -> %s:%i",
2376                               v->m_name.c_str(),
2377                               v->m_reads[s]->m_context.file, v->m_reads[s]->m_context.line)
2378                    )
2379                 {
2380                     return false;
2381                 }
2382                 continue;
2383             }
2384             if (v->m_memberof) {
2385                 ir_value *vec = v->m_memberof;
2386                 for (s = 0; s < vec->m_reads.size(); ++s) {
2387                     if (vec->m_reads[s]->m_eid == v->m_life[0].end)
2388                         break;
2389                 }
2390                 if (s < vec->m_reads.size()) {
2391                     if (irwarning(v->m_context, WARN_USED_UNINITIALIZED,
2392                                   "variable `%s` may be used uninitialized in this function\n"
2393                                   " -> %s:%i",
2394                                   v->m_name.c_str(),
2395                                   vec->m_reads[s]->m_context.file, vec->m_reads[s]->m_context.line)
2396                        )
2397                     {
2398                         return false;
2399                     }
2400                     continue;
2401                 }
2402             }
2403             if (irwarning(v->m_context, WARN_USED_UNINITIALIZED,
2404                           "variable `%s` may be used uninitialized in this function", v->m_name.c_str()))
2405             {
2406                 return false;
2407             }
2408         }
2409     }
2410     return true;
2411 }
2412
2413 /***********************************************************************
2414  *IR Code-Generation
2415  *
2416  * Since the IR has the convention of putting 'write' operands
2417  * at the beginning, we have to rotate the operands of instructions
2418  * properly in order to generate valid QCVM code.
2419  *
2420  * Having destinations at a fixed position is more convenient. In QC
2421  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
2422  * read from from OPA,  and store to OPB rather than OPC.   Which is
2423  * partially the reason why the implementation of these instructions
2424  * in darkplaces has been delayed for so long.
2425  *
2426  * Breaking conventions is annoying...
2427  */
2428 static bool gen_global_field(code_t *code, ir_value *global)
2429 {
2430     if (global->m_hasvalue)
2431     {
2432         ir_value *fld = global->m_constval.vpointer;
2433         if (!fld) {
2434             irerror(global->m_context, "Invalid field constant with no field: %s", global->m_name.c_str());
2435             return false;
2436         }
2437
2438         /* copy the field's value */
2439         global->setCodeAddress(code->globals.size());
2440         code->globals.push_back(fld->m_code.fieldaddr);
2441         if (global->m_fieldtype == TYPE_VECTOR) {
2442             code->globals.push_back(fld->m_code.fieldaddr+1);
2443             code->globals.push_back(fld->m_code.fieldaddr+2);
2444         }
2445     }
2446     else
2447     {
2448         global->setCodeAddress(code->globals.size());
2449         code->globals.push_back(0);
2450         if (global->m_fieldtype == TYPE_VECTOR) {
2451             code->globals.push_back(0);
2452             code->globals.push_back(0);
2453         }
2454     }
2455     if (global->m_code.globaladdr < 0)
2456         return false;
2457     return true;
2458 }
2459
2460 static bool gen_global_pointer(code_t *code, ir_value *global)
2461 {
2462     if (global->m_hasvalue)
2463     {
2464         ir_value *target = global->m_constval.vpointer;
2465         if (!target) {
2466             irerror(global->m_context, "Invalid pointer constant: %s", global->m_name.c_str());
2467             /* nullptr pointers are pointing to the nullptr constant, which also
2468              * sits at address 0, but still has an ir_value for itself.
2469              */
2470             return false;
2471         }
2472
2473         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2474          * void() foo; <- proto
2475          * void() *fooptr = &foo;
2476          * void() foo = { code }
2477          */
2478         if (!target->m_code.globaladdr) {
2479             /* FIXME: Check for the constant nullptr ir_value!
2480              * because then code.globaladdr being 0 is valid.
2481              */
2482             irerror(global->m_context, "FIXME: Relocation support");
2483             return false;
2484         }
2485
2486         global->setCodeAddress(code->globals.size());
2487         code->globals.push_back(target->m_code.globaladdr);
2488     }
2489     else
2490     {
2491         global->setCodeAddress(code->globals.size());
2492         code->globals.push_back(0);
2493     }
2494     if (global->m_code.globaladdr < 0)
2495         return false;
2496     return true;
2497 }
2498
2499 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2500 {
2501     prog_section_statement_t stmt;
2502     ir_instr *instr;
2503     ir_block *target;
2504     ir_block *ontrue;
2505     ir_block *onfalse;
2506     size_t    stidx;
2507     size_t    i;
2508     int       j;
2509
2510     block->m_generated = true;
2511     block->m_code_start = code->statements.size();
2512     for (i = 0; i < block->m_instr.size(); ++i)
2513     {
2514         instr = block->m_instr[i];
2515
2516         if (instr->m_opcode == VINSTR_PHI) {
2517             irerror(block->m_context, "cannot generate virtual instruction (phi)");
2518             return false;
2519         }
2520
2521         if (instr->m_opcode == VINSTR_JUMP) {
2522             target = instr->m_bops[0];
2523             /* for uncoditional jumps, if the target hasn't been generated
2524              * yet, we generate them right here.
2525              */
2526             if (!target->m_generated)
2527                 return gen_blocks_recursive(code, func, target);
2528
2529             /* otherwise we generate a jump instruction */
2530             stmt.opcode = INSTR_GOTO;
2531             stmt.o1.s1 = target->m_code_start - code->statements.size();
2532             stmt.o2.s1 = 0;
2533             stmt.o3.s1 = 0;
2534             if (stmt.o1.s1 != 1)
2535                 code_push_statement(code, &stmt, instr->m_context);
2536
2537             /* no further instructions can be in this block */
2538             return true;
2539         }
2540
2541         if (instr->m_opcode == VINSTR_BITXOR) {
2542             stmt.opcode = INSTR_BITOR;
2543             stmt.o1.s1 = instr->_m_ops[1]->codeAddress();
2544             stmt.o2.s1 = instr->_m_ops[2]->codeAddress();
2545             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2546             code_push_statement(code, &stmt, instr->m_context);
2547             stmt.opcode = INSTR_BITAND;
2548             stmt.o1.s1 = instr->_m_ops[1]->codeAddress();
2549             stmt.o2.s1 = instr->_m_ops[2]->codeAddress();
2550             stmt.o3.s1 = func->m_owner->m_vinstr_temp[0]->codeAddress();
2551             code_push_statement(code, &stmt, instr->m_context);
2552             stmt.opcode = INSTR_SUB_F;
2553             stmt.o1.s1 = instr->_m_ops[0]->codeAddress();
2554             stmt.o2.s1 = func->m_owner->m_vinstr_temp[0]->codeAddress();
2555             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2556             code_push_statement(code, &stmt, instr->m_context);
2557
2558             /* instruction generated */
2559             continue;
2560         }
2561
2562         if (instr->m_opcode == VINSTR_BITAND_V) {
2563             stmt.opcode = INSTR_BITAND;
2564             stmt.o1.s1 = instr->_m_ops[1]->codeAddress();
2565             stmt.o2.s1 = instr->_m_ops[2]->codeAddress();
2566             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2567             code_push_statement(code, &stmt, instr->m_context);
2568             ++stmt.o1.s1;
2569             ++stmt.o2.s1;
2570             ++stmt.o3.s1;
2571             code_push_statement(code, &stmt, instr->m_context);
2572             ++stmt.o1.s1;
2573             ++stmt.o2.s1;
2574             ++stmt.o3.s1;
2575             code_push_statement(code, &stmt, instr->m_context);
2576
2577             /* instruction generated */
2578             continue;
2579         }
2580
2581         if (instr->m_opcode == VINSTR_BITOR_V) {
2582             stmt.opcode = INSTR_BITOR;
2583             stmt.o1.s1 = instr->_m_ops[1]->codeAddress();
2584             stmt.o2.s1 = instr->_m_ops[2]->codeAddress();
2585             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2586             code_push_statement(code, &stmt, instr->m_context);
2587             ++stmt.o1.s1;
2588             ++stmt.o2.s1;
2589             ++stmt.o3.s1;
2590             code_push_statement(code, &stmt, instr->m_context);
2591             ++stmt.o1.s1;
2592             ++stmt.o2.s1;
2593             ++stmt.o3.s1;
2594             code_push_statement(code, &stmt, instr->m_context);
2595
2596             /* instruction generated */
2597             continue;
2598         }
2599
2600         if (instr->m_opcode == VINSTR_BITXOR_V) {
2601             for (j = 0; j < 3; ++j) {
2602                 stmt.opcode = INSTR_BITOR;
2603                 stmt.o1.s1 = instr->_m_ops[1]->codeAddress() + j;
2604                 stmt.o2.s1 = instr->_m_ops[2]->codeAddress() + j;
2605                 stmt.o3.s1 = instr->_m_ops[0]->codeAddress() + j;
2606                 code_push_statement(code, &stmt, instr->m_context);
2607                 stmt.opcode = INSTR_BITAND;
2608                 stmt.o1.s1 = instr->_m_ops[1]->codeAddress() + j;
2609                 stmt.o2.s1 = instr->_m_ops[2]->codeAddress() + j;
2610                 stmt.o3.s1 = func->m_owner->m_vinstr_temp[0]->codeAddress() + j;
2611                 code_push_statement(code, &stmt, instr->m_context);
2612             }
2613             stmt.opcode = INSTR_SUB_V;
2614             stmt.o1.s1 = instr->_m_ops[0]->codeAddress();
2615             stmt.o2.s1 = func->m_owner->m_vinstr_temp[0]->codeAddress();
2616             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2617             code_push_statement(code, &stmt, instr->m_context);
2618
2619             /* instruction generated */
2620             continue;
2621         }
2622
2623         if (instr->m_opcode == VINSTR_BITAND_VF) {
2624             stmt.opcode = INSTR_BITAND;
2625             stmt.o1.s1 = instr->_m_ops[1]->codeAddress();
2626             stmt.o2.s1 = instr->_m_ops[2]->codeAddress();
2627             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2628             code_push_statement(code, &stmt, instr->m_context);
2629             ++stmt.o1.s1;
2630             ++stmt.o3.s1;
2631             code_push_statement(code, &stmt, instr->m_context);
2632             ++stmt.o1.s1;
2633             ++stmt.o3.s1;
2634             code_push_statement(code, &stmt, instr->m_context);
2635
2636             /* instruction generated */
2637             continue;
2638         }
2639
2640         if (instr->m_opcode == VINSTR_BITOR_VF) {
2641             stmt.opcode = INSTR_BITOR;
2642             stmt.o1.s1 = instr->_m_ops[1]->codeAddress();
2643             stmt.o2.s1 = instr->_m_ops[2]->codeAddress();
2644             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2645             code_push_statement(code, &stmt, instr->m_context);
2646             ++stmt.o1.s1;
2647             ++stmt.o3.s1;
2648             code_push_statement(code, &stmt, instr->m_context);
2649             ++stmt.o1.s1;
2650             ++stmt.o3.s1;
2651             code_push_statement(code, &stmt, instr->m_context);
2652
2653             /* instruction generated */
2654             continue;
2655         }
2656
2657         if (instr->m_opcode == VINSTR_BITXOR_VF) {
2658             for (j = 0; j < 3; ++j) {
2659                 stmt.opcode = INSTR_BITOR;
2660                 stmt.o1.s1 = instr->_m_ops[1]->codeAddress() + j;
2661                 stmt.o2.s1 = instr->_m_ops[2]->codeAddress();
2662                 stmt.o3.s1 = instr->_m_ops[0]->codeAddress() + j;
2663                 code_push_statement(code, &stmt, instr->m_context);
2664                 stmt.opcode = INSTR_BITAND;
2665                 stmt.o1.s1 = instr->_m_ops[1]->codeAddress() + j;
2666                 stmt.o2.s1 = instr->_m_ops[2]->codeAddress();
2667                 stmt.o3.s1 = func->m_owner->m_vinstr_temp[0]->codeAddress() + j;
2668                 code_push_statement(code, &stmt, instr->m_context);
2669             }
2670             stmt.opcode = INSTR_SUB_V;
2671             stmt.o1.s1 = instr->_m_ops[0]->codeAddress();
2672             stmt.o2.s1 = func->m_owner->m_vinstr_temp[0]->codeAddress();
2673             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2674             code_push_statement(code, &stmt, instr->m_context);
2675
2676             /* instruction generated */
2677             continue;
2678         }
2679
2680         if (instr->m_opcode == VINSTR_CROSS) {
2681             stmt.opcode = INSTR_MUL_F;
2682             for (j = 0; j < 3; ++j) {
2683                 stmt.o1.s1 = instr->_m_ops[1]->codeAddress() + (j + 1) % 3;
2684                 stmt.o2.s1 = instr->_m_ops[2]->codeAddress() + (j + 2) % 3;
2685                 stmt.o3.s1 = instr->_m_ops[0]->codeAddress() + j;
2686                 code_push_statement(code, &stmt, instr->m_context);
2687                 stmt.o1.s1 = instr->_m_ops[1]->codeAddress() + (j + 2) % 3;
2688                 stmt.o2.s1 = instr->_m_ops[2]->codeAddress() + (j + 1) % 3;
2689                 stmt.o3.s1 = func->m_owner->m_vinstr_temp[0]->codeAddress() + j;
2690                 code_push_statement(code, &stmt, instr->m_context);
2691             }
2692             stmt.opcode = INSTR_SUB_V;
2693             stmt.o1.s1 = instr->_m_ops[0]->codeAddress();
2694             stmt.o2.s1 = func->m_owner->m_vinstr_temp[0]->codeAddress();
2695             stmt.o3.s1 = instr->_m_ops[0]->codeAddress();
2696             code_push_statement(code, &stmt, instr->m_context);
2697
2698             /* instruction generated */
2699             continue;
2700         }
2701
2702         if (instr->m_opcode == VINSTR_COND) {
2703             ontrue  = instr->m_bops[0];
2704             onfalse = instr->m_bops[1];
2705             /* TODO: have the AST signal which block should
2706              * come first: eg. optimize IFs without ELSE...
2707              */
2708
2709             stmt.o1.u1 = instr->_m_ops[0]->codeAddress();
2710             stmt.o2.u1 = 0;
2711             stmt.o3.s1 = 0;
2712
2713             if (ontrue->m_generated) {
2714                 stmt.opcode = INSTR_IF;
2715                 stmt.o2.s1 = ontrue->m_code_start - code->statements.size();
2716                 if (stmt.o2.s1 != 1)
2717                     code_push_statement(code, &stmt, instr->m_context);
2718             }
2719             if (onfalse->m_generated) {
2720                 stmt.opcode = INSTR_IFNOT;
2721                 stmt.o2.s1 = onfalse->m_code_start - code->statements.size();
2722                 if (stmt.o2.s1 != 1)
2723                     code_push_statement(code, &stmt, instr->m_context);
2724             }
2725             if (!ontrue->m_generated) {
2726                 if (onfalse->m_generated)
2727                     return gen_blocks_recursive(code, func, ontrue);
2728             }
2729             if (!onfalse->m_generated) {
2730                 if (ontrue->m_generated)
2731                     return gen_blocks_recursive(code, func, onfalse);
2732             }
2733             /* neither ontrue nor onfalse exist */
2734             stmt.opcode = INSTR_IFNOT;
2735             if (!instr->m_likely) {
2736                 /* Honor the likelyhood hint */
2737                 ir_block *tmp = onfalse;
2738                 stmt.opcode = INSTR_IF;
2739                 onfalse = ontrue;
2740                 ontrue = tmp;
2741             }
2742             stidx = code->statements.size();
2743             code_push_statement(code, &stmt, instr->m_context);
2744             /* on false we jump, so add ontrue-path */
2745             if (!gen_blocks_recursive(code, func, ontrue))
2746                 return false;
2747             /* fixup the jump address */
2748             code->statements[stidx].o2.s1 = code->statements.size() - stidx;
2749             /* generate onfalse path */
2750             if (onfalse->m_generated) {
2751                 /* fixup the jump address */
2752                 code->statements[stidx].o2.s1 = onfalse->m_code_start - stidx;
2753                 if (stidx+2 == code->statements.size() && code->statements[stidx].o2.s1 == 1) {
2754                     code->statements[stidx] = code->statements[stidx+1];
2755                     if (code->statements[stidx].o1.s1 < 0)
2756                         code->statements[stidx].o1.s1++;
2757                     code_pop_statement(code);
2758                 }
2759                 stmt.opcode = code->statements.back().opcode;
2760                 if (stmt.opcode == INSTR_GOTO ||
2761                     stmt.opcode == INSTR_IF ||
2762                     stmt.opcode == INSTR_IFNOT ||
2763                     stmt.opcode == INSTR_RETURN ||
2764                     stmt.opcode == INSTR_DONE)
2765                 {
2766                     /* no use jumping from here */
2767                     return true;
2768                 }
2769                 /* may have been generated in the previous recursive call */
2770                 stmt.opcode = INSTR_GOTO;
2771                 stmt.o1.s1 = onfalse->m_code_start - code->statements.size();
2772                 stmt.o2.s1 = 0;
2773                 stmt.o3.s1 = 0;
2774                 if (stmt.o1.s1 != 1)
2775                     code_push_statement(code, &stmt, instr->m_context);
2776                 return true;
2777             }
2778             else if (stidx+2 == code->statements.size() && code->statements[stidx].o2.s1 == 1) {
2779                 code->statements[stidx] = code->statements[stidx+1];
2780                 if (code->statements[stidx].o1.s1 < 0)
2781                     code->statements[stidx].o1.s1++;
2782                 code_pop_statement(code);
2783             }
2784             /* if not, generate now */
2785             return gen_blocks_recursive(code, func, onfalse);
2786         }
2787
2788         if ( (instr->m_opcode >= INSTR_CALL0 && instr->m_opcode <= INSTR_CALL8)
2789            || instr->m_opcode == VINSTR_NRCALL)
2790         {
2791             size_t p, first;
2792             ir_value *retvalue;
2793
2794             first = instr->m_params.size();
2795             if (first > 8)
2796                 first = 8;
2797             for (p = 0; p < first; ++p)
2798             {
2799                 ir_value *param = instr->m_params[p];
2800                 if (param->m_callparam)
2801                     continue;
2802
2803                 stmt.opcode = INSTR_STORE_F;
2804                 stmt.o3.u1 = 0;
2805
2806                 if (param->m_vtype == TYPE_FIELD)
2807                     stmt.opcode = field_store_instr[param->m_fieldtype];
2808                 else if (param->m_vtype == TYPE_NIL)
2809                     stmt.opcode = INSTR_STORE_V;
2810                 else
2811                     stmt.opcode = type_store_instr[param->m_vtype];
2812                 stmt.o1.u1 = param->codeAddress();
2813                 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2814
2815                 if (param->m_vtype == TYPE_VECTOR && (param->m_flags & IR_FLAG_SPLIT_VECTOR)) {
2816                     /* fetch 3 separate floats */
2817                     stmt.opcode = INSTR_STORE_F;
2818                     stmt.o1.u1 = param->m_members[0]->codeAddress();
2819                     code_push_statement(code, &stmt, instr->m_context);
2820                     stmt.o2.u1++;
2821                     stmt.o1.u1 = param->m_members[1]->codeAddress();
2822                     code_push_statement(code, &stmt, instr->m_context);
2823                     stmt.o2.u1++;
2824                     stmt.o1.u1 = param->m_members[2]->codeAddress();
2825                     code_push_statement(code, &stmt, instr->m_context);
2826                 }
2827                 else
2828                     code_push_statement(code, &stmt, instr->m_context);
2829             }
2830             /* Now handle extparams */
2831             first = instr->m_params.size();
2832             for (; p < first; ++p)
2833             {
2834                 ir_builder *ir = func->m_owner;
2835                 ir_value *param = instr->m_params[p];
2836                 ir_value *targetparam;
2837
2838                 if (param->m_callparam)
2839                     continue;
2840
2841                 if (p-8 >= ir->m_extparams.size())
2842                     ir->generateExtparam();
2843
2844                 targetparam = ir->m_extparams[p-8];
2845
2846                 stmt.opcode = INSTR_STORE_F;
2847                 stmt.o3.u1 = 0;
2848
2849                 if (param->m_vtype == TYPE_FIELD)
2850                     stmt.opcode = field_store_instr[param->m_fieldtype];
2851                 else if (param->m_vtype == TYPE_NIL)
2852                     stmt.opcode = INSTR_STORE_V;
2853                 else
2854                     stmt.opcode = type_store_instr[param->m_vtype];
2855                 stmt.o1.u1 = param->codeAddress();
2856                 stmt.o2.u1 = targetparam->codeAddress();
2857                 if (param->m_vtype == TYPE_VECTOR && (param->m_flags & IR_FLAG_SPLIT_VECTOR)) {
2858                     /* fetch 3 separate floats */
2859                     stmt.opcode = INSTR_STORE_F;
2860                     stmt.o1.u1 = param->m_members[0]->codeAddress();
2861                     code_push_statement(code, &stmt, instr->m_context);
2862                     stmt.o2.u1++;
2863                     stmt.o1.u1 = param->m_members[1]->codeAddress();
2864                     code_push_statement(code, &stmt, instr->m_context);
2865                     stmt.o2.u1++;
2866                     stmt.o1.u1 = param->m_members[2]->codeAddress();
2867                     code_push_statement(code, &stmt, instr->m_context);
2868                 }
2869                 else
2870                     code_push_statement(code, &stmt, instr->m_context);
2871             }
2872
2873             stmt.opcode = INSTR_CALL0 + instr->m_params.size();
2874             if (stmt.opcode > INSTR_CALL8)
2875                 stmt.opcode = INSTR_CALL8;
2876             stmt.o1.u1 = instr->_m_ops[1]->codeAddress();
2877             stmt.o2.u1 = 0;
2878             stmt.o3.u1 = 0;
2879             code_push_statement(code, &stmt, instr->m_context);
2880
2881             retvalue = instr->_m_ops[0];
2882             if (retvalue && retvalue->m_store != store_return &&
2883                 (retvalue->m_store == store_global || retvalue->m_life.size()))
2884             {
2885                 /* not to be kept in OFS_RETURN */
2886                 if (retvalue->m_vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2887                     stmt.opcode = field_store_instr[retvalue->m_fieldtype];
2888                 else
2889                     stmt.opcode = type_store_instr[retvalue->m_vtype];
2890                 stmt.o1.u1 = OFS_RETURN;
2891                 stmt.o2.u1 = retvalue->codeAddress();
2892                 stmt.o3.u1 = 0;
2893                 code_push_statement(code, &stmt, instr->m_context);
2894             }
2895             continue;
2896         }
2897
2898         if (instr->m_opcode == INSTR_STATE) {
2899             stmt.opcode = instr->m_opcode;
2900             if (instr->_m_ops[0])
2901                 stmt.o1.u1 = instr->_m_ops[0]->codeAddress();
2902             if (instr->_m_ops[1])
2903                 stmt.o2.u1 = instr->_m_ops[1]->codeAddress();
2904             stmt.o3.u1 = 0;
2905             code_push_statement(code, &stmt, instr->m_context);
2906             continue;
2907         }
2908
2909         stmt.opcode = instr->m_opcode;
2910         stmt.o1.u1 = 0;
2911         stmt.o2.u1 = 0;
2912         stmt.o3.u1 = 0;
2913
2914         /* This is the general order of operands */
2915         if (instr->_m_ops[0])
2916             stmt.o3.u1 = instr->_m_ops[0]->codeAddress();
2917
2918         if (instr->_m_ops[1])
2919             stmt.o1.u1 = instr->_m_ops[1]->codeAddress();
2920
2921         if (instr->_m_ops[2])
2922             stmt.o2.u1 = instr->_m_ops[2]->codeAddress();
2923
2924         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2925         {
2926             stmt.o1.u1 = stmt.o3.u1;
2927             stmt.o3.u1 = 0;
2928         }
2929         else if ((stmt.opcode >= INSTR_STORE_F &&
2930                   stmt.opcode <= INSTR_STORE_FNC) ||
2931                  (stmt.opcode >= INSTR_STOREP_F &&
2932                   stmt.opcode <= INSTR_STOREP_FNC))
2933         {
2934             /* 2-operand instructions with A -> B */
2935             stmt.o2.u1 = stmt.o3.u1;
2936             stmt.o3.u1 = 0;
2937
2938             /* tiny optimization, don't output
2939              * STORE a, a
2940              */
2941             if (stmt.o2.u1 == stmt.o1.u1 &&
2942                 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2943             {
2944                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2945                 continue;
2946             }
2947         }
2948         code_push_statement(code, &stmt, instr->m_context);
2949     }
2950     return true;
2951 }
2952
2953 static bool gen_function_code(code_t *code, ir_function *self)
2954 {
2955     ir_block *block;
2956     prog_section_statement_t stmt, *retst;
2957
2958     /* Starting from entry point, we generate blocks "as they come"
2959      * for now. Dead blocks will not be translated obviously.
2960      */
2961     if (self->m_blocks.empty()) {
2962         irerror(self->m_context, "Function '%s' declared without body.", self->m_name.c_str());
2963         return false;
2964     }
2965
2966     block = self->m_blocks[0].get();
2967     if (block->m_generated)
2968         return true;
2969
2970     if (!gen_blocks_recursive(code, self, block)) {
2971         irerror(self->m_context, "failed to generate blocks for '%s'", self->m_name.c_str());
2972         return false;
2973     }
2974
2975     /* code_write and qcvm -disasm need to know that the function ends here */
2976     retst = &code->statements.back();
2977     if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
2978         self->m_outtype == TYPE_VOID &&
2979         retst->opcode == INSTR_RETURN &&
2980         !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
2981     {
2982         retst->opcode = INSTR_DONE;
2983         ++opts_optimizationcount[OPTIM_VOID_RETURN];
2984     } else {
2985         lex_ctx_t last;
2986
2987         stmt.opcode = INSTR_DONE;
2988         stmt.o1.u1  = 0;
2989         stmt.o2.u1  = 0;
2990         stmt.o3.u1  = 0;
2991         last.line   = code->linenums.back();
2992         last.column = code->columnnums.back();
2993
2994         code_push_statement(code, &stmt, last);
2995     }
2996     return true;
2997 }
2998
2999 qcint_t ir_builder::filestring(const char *filename)
3000 {
3001     /* NOTE: filename pointers are copied, we never strdup them,
3002      * thus we can use pointer-comparison to find the string.
3003      */
3004     qcint_t  str;
3005
3006     for (size_t i = 0; i != m_filenames.size(); ++i) {
3007         if (!strcmp(m_filenames[i], filename))
3008             return i;
3009     }
3010
3011     str = code_genstring(m_code.get(), filename);
3012     m_filenames.push_back(filename);
3013     m_filestrings.push_back(str);
3014     return str;
3015 }
3016
3017 bool ir_builder::generateGlobalFunction(ir_value *global)
3018 {
3019     prog_section_function_t fun;
3020     ir_function            *irfun;
3021
3022     size_t i;
3023
3024     if (!global->m_hasvalue || (!global->m_constval.vfunc)) {
3025         irerror(global->m_context, "Invalid state of function-global: not constant: %s", global->m_name.c_str());
3026         return false;
3027     }
3028
3029     irfun = global->m_constval.vfunc;
3030     fun.name = global->m_code.name;
3031     fun.file = filestring(global->m_context.file);
3032     fun.profile = 0; /* always 0 */
3033     fun.nargs = vec_size(irfun->m_params);
3034     if (fun.nargs > 8)
3035         fun.nargs = 8;
3036
3037     for (i = 0; i < 8; ++i) {
3038         if ((int32_t)i >= fun.nargs)
3039             fun.argsize[i] = 0;
3040         else
3041             fun.argsize[i] = type_sizeof_[irfun->m_params[i]];
3042     }
3043
3044     fun.firstlocal = 0;
3045     fun.locals = irfun->m_allocated_locals;
3046
3047     if (irfun->m_builtin)
3048         fun.entry = irfun->m_builtin+1;
3049     else {
3050         irfun->m_code_function_def = m_code->functions.size();
3051         fun.entry = m_code->statements.size();
3052     }
3053
3054     m_code->functions.push_back(fun);
3055     return true;
3056 }
3057
3058 ir_value* ir_builder::generateExtparamProto()
3059 {
3060     char      name[128];
3061
3062     util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(m_extparam_protos.size()));
3063     ir_value *global = new ir_value(name, store_global, TYPE_VECTOR);
3064     m_extparam_protos.emplace_back(global);
3065
3066     return global;
3067 }
3068
3069 void ir_builder::generateExtparam()
3070 {
3071     prog_section_def_t def;
3072     ir_value          *global;
3073
3074     if (m_extparam_protos.size() < m_extparams.size()+1)
3075         global = generateExtparamProto();
3076     else
3077         global = m_extparam_protos[m_extparams.size()].get();
3078
3079     def.name = code_genstring(m_code.get(), global->m_name.c_str());
3080     def.type = TYPE_VECTOR;
3081     def.offset = m_code->globals.size();
3082
3083     m_code->defs.push_back(def);
3084
3085     global->setCodeAddress(def.offset);
3086
3087     m_code->globals.push_back(0);
3088     m_code->globals.push_back(0);
3089     m_code->globals.push_back(0);
3090
3091     m_extparams.emplace_back(global);
3092 }
3093
3094 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3095 {
3096     ir_builder *ir = self->m_owner;
3097
3098     size_t numparams = vec_size(self->m_params);
3099     if (!numparams)
3100         return true;
3101
3102     prog_section_statement_t stmt;
3103     stmt.opcode = INSTR_STORE_F;
3104     stmt.o3.s1 = 0;
3105     for (size_t i = 8; i < numparams; ++i) {
3106         size_t ext = i - 8;
3107         if (ext >= ir->m_extparams.size())
3108             ir->generateExtparam();
3109
3110         ir_value *ep = ir->m_extparams[ext];
3111
3112         stmt.opcode = type_store_instr[self->m_locals[i]->m_vtype];
3113         if (self->m_locals[i]->m_vtype == TYPE_FIELD &&
3114             self->m_locals[i]->m_fieldtype == TYPE_VECTOR)
3115         {
3116             stmt.opcode = INSTR_STORE_V;
3117         }
3118         stmt.o1.u1 = ep->codeAddress();
3119         stmt.o2.u1 = self->m_locals[i].get()->codeAddress();
3120         code_push_statement(code, &stmt, self->m_context);
3121     }
3122
3123     return true;
3124 }
3125
3126 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3127 {
3128     size_t i, ext, numparams, maxparams;
3129
3130     ir_builder *ir = self->m_owner;
3131     ir_value   *ep;
3132     prog_section_statement_t stmt;
3133
3134     numparams = vec_size(self->m_params);
3135     if (!numparams)
3136         return true;
3137
3138     stmt.opcode = INSTR_STORE_V;
3139     stmt.o3.s1 = 0;
3140     maxparams = numparams + self->m_max_varargs;
3141     for (i = numparams; i < maxparams; ++i) {
3142         if (i < 8) {
3143             stmt.o1.u1 = OFS_PARM0 + 3*i;
3144             stmt.o2.u1 = self->m_locals[i].get()->codeAddress();
3145             code_push_statement(code, &stmt, self->m_context);
3146             continue;
3147         }
3148         ext = i - 8;
3149         while (ext >= ir->m_extparams.size())
3150             ir->generateExtparam();
3151
3152         ep = ir->m_extparams[ext];
3153
3154         stmt.o1.u1 = ep->codeAddress();
3155         stmt.o2.u1 = self->m_locals[i].get()->codeAddress();
3156         code_push_statement(code, &stmt, self->m_context);
3157     }
3158
3159     return true;
3160 }
3161
3162 bool ir_builder::generateFunctionLocals(ir_value *global)
3163 {
3164     prog_section_function_t *def;
3165     ir_function             *irfun;
3166     uint32_t                 firstlocal, firstglobal;
3167
3168     irfun = global->m_constval.vfunc;
3169     def   = &m_code->functions[0] + irfun->m_code_function_def;
3170
3171     if (OPTS_OPTION_BOOL(OPTION_G) ||
3172         !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS)        ||
3173         (irfun->m_flags & IR_FLAG_MASK_NO_OVERLAP))
3174     {
3175         firstlocal = def->firstlocal = m_code->globals.size();
3176     } else {
3177         firstlocal = def->firstlocal = m_first_common_local;
3178         ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3179     }
3180
3181     firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? m_first_common_globaltemp : firstlocal);
3182
3183     for (size_t i = m_code->globals.size(); i < firstlocal + irfun->m_allocated_locals; ++i)
3184         m_code->globals.push_back(0);
3185
3186     for (auto& lp : irfun->m_locals) {
3187         ir_value *v = lp.get();
3188         if (v->m_locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3189             v->setCodeAddress(firstlocal + v->m_code.local);
3190             if (!generateGlobal(v, true)) {
3191                 irerror(v->m_context, "failed to generate local %s", v->m_name.c_str());
3192                 return false;
3193             }
3194         }
3195         else
3196             v->setCodeAddress(firstglobal + v->m_code.local);
3197     }
3198     for (auto& vp : irfun->m_values) {
3199         ir_value *v = vp.get();
3200         if (v->m_callparam)
3201             continue;
3202         if (v->m_locked)
3203             v->setCodeAddress(firstlocal + v->m_code.local);
3204         else
3205             v->setCodeAddress(firstglobal + v->m_code.local);
3206     }
3207     return true;
3208 }
3209
3210 bool ir_builder::generateGlobalFunctionCode(ir_value *global)
3211 {
3212     prog_section_function_t *fundef;
3213     ir_function             *irfun;
3214
3215     irfun = global->m_constval.vfunc;
3216     if (!irfun) {
3217         if (global->m_cvq == CV_NONE) {
3218             if (irwarning(global->m_context, WARN_IMPLICIT_FUNCTION_POINTER,
3219                           "function `%s` has no body and in QC implicitly becomes a function-pointer",
3220                           global->m_name.c_str()))
3221             {
3222                 /* Not bailing out just now. If this happens a lot you don't want to have
3223                  * to rerun gmqcc for each such function.
3224                  */
3225
3226                 /* return false; */
3227             }
3228         }
3229         /* this was a function pointer, don't generate code for those */
3230         return true;
3231     }
3232
3233     if (irfun->m_builtin)
3234         return true;
3235
3236     /*
3237      * If there is no definition and the thing is eraseable, we can ignore
3238      * outputting the function to begin with.
3239      */
3240     if (global->m_flags & IR_FLAG_ERASABLE && irfun->m_code_function_def < 0) {
3241         return true;
3242     }
3243
3244     if (irfun->m_code_function_def < 0) {
3245         irerror(irfun->m_context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->m_name.c_str());
3246         return false;
3247     }
3248     fundef = &m_code->functions[irfun->m_code_function_def];
3249
3250     fundef->entry = m_code->statements.size();
3251     if (!generateFunctionLocals(global)) {
3252         irerror(irfun->m_context, "Failed to generate locals for function %s", irfun->m_name.c_str());
3253         return false;
3254     }
3255     if (!gen_function_extparam_copy(m_code.get(), irfun)) {
3256         irerror(irfun->m_context, "Failed to generate extparam-copy code for function %s", irfun->m_name.c_str());
3257         return false;
3258     }
3259     if (irfun->m_max_varargs && !gen_function_varargs_copy(m_code.get(), irfun)) {
3260         irerror(irfun->m_context, "Failed to generate vararg-copy code for function %s", irfun->m_name.c_str());
3261         return false;
3262     }
3263     if (!gen_function_code(m_code.get(), irfun)) {
3264         irerror(irfun->m_context, "Failed to generate code for function %s", irfun->m_name.c_str());
3265         return false;
3266     }
3267     return true;
3268 }
3269
3270 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3271 {
3272     char  *component;
3273     size_t len, i;
3274
3275     if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3276         return;
3277
3278     def.type = TYPE_FLOAT;
3279
3280     len = strlen(name);
3281
3282     component = (char*)mem_a(len+3);
3283     memcpy(component, name, len);
3284     len += 2;
3285     component[len-0] = 0;
3286     component[len-2] = '_';
3287
3288     component[len-1] = 'x';
3289
3290     for (i = 0; i < 3; ++i) {
3291         def.name = code_genstring(code, component);
3292         code->defs.push_back(def);
3293         def.offset++;
3294         component[len-1]++;
3295     }
3296
3297     mem_d(component);
3298 }
3299
3300 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3301 {
3302     char  *component;
3303     size_t len, i;
3304
3305     if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3306         return;
3307
3308     fld.type = TYPE_FLOAT;
3309
3310     len = strlen(name);
3311
3312     component = (char*)mem_a(len+3);
3313     memcpy(component, name, len);
3314     len += 2;
3315     component[len-0] = 0;
3316     component[len-2] = '_';
3317
3318     component[len-1] = 'x';
3319
3320     for (i = 0; i < 3; ++i) {
3321         fld.name = code_genstring(code, component);
3322         code->fields.push_back(fld);
3323         fld.offset++;
3324         component[len-1]++;
3325     }
3326
3327     mem_d(component);
3328 }
3329
3330 bool ir_builder::generateGlobal(ir_value *global, bool islocal)
3331 {
3332     size_t             i;
3333     int32_t           *iptr;
3334     prog_section_def_t def;
3335     bool               pushdef = opts.optimizeoff;
3336
3337     /* we don't generate split-vectors */
3338     if (global->m_vtype == TYPE_VECTOR && (global->m_flags & IR_FLAG_SPLIT_VECTOR))
3339         return true;
3340
3341     def.type = global->m_vtype;
3342     def.offset = m_code->globals.size();
3343     def.name = 0;
3344     if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3345     {
3346         pushdef = true;
3347
3348         /*
3349          * if we're eraseable and the function isn't referenced ignore outputting
3350          * the function.
3351          */
3352         if (global->m_flags & IR_FLAG_ERASABLE && global->m_reads.empty()) {
3353             return true;
3354         }
3355
3356         if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3357             !(global->m_flags & IR_FLAG_INCLUDE_DEF) &&
3358             (global->m_name[0] == '#' || global->m_cvq == CV_CONST))
3359         {
3360             pushdef = false;
3361         }
3362
3363         if (pushdef) {
3364             if (global->m_name[0] == '#') {
3365                 if (!m_str_immediate)
3366                     m_str_immediate = code_genstring(m_code.get(), "IMMEDIATE");
3367                 def.name = global->m_code.name = m_str_immediate;
3368             }
3369             else
3370                 def.name = global->m_code.name = code_genstring(m_code.get(), global->m_name.c_str());
3371         }
3372         else
3373             def.name   = 0;
3374         if (islocal) {
3375             def.offset = global->codeAddress();
3376             m_code->defs.push_back(def);
3377             if (global->m_vtype == TYPE_VECTOR)
3378                 gen_vector_defs(m_code.get(), def, global->m_name.c_str());
3379             else if (global->m_vtype == TYPE_FIELD && global->m_fieldtype == TYPE_VECTOR)
3380                 gen_vector_defs(m_code.get(), def, global->m_name.c_str());
3381             return true;
3382         }
3383     }
3384     if (islocal)
3385         return true;
3386
3387     switch (global->m_vtype)
3388     {
3389     case TYPE_VOID:
3390         if (0 == global->m_name.compare("end_sys_globals")) {
3391             // TODO: remember this point... all the defs before this one
3392             // should be checksummed and added to progdefs.h when we generate it.
3393         }
3394         else if (0 == global->m_name.compare("end_sys_fields")) {
3395             // TODO: same as above but for entity-fields rather than globsl
3396         }
3397         else if(irwarning(global->m_context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3398                           global->m_name.c_str()))
3399         {
3400             /* Not bailing out */
3401             /* return false; */
3402         }
3403         /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3404          * the system fields actually go? Though the engine knows this anyway...
3405          * Maybe this could be an -foption
3406          * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3407          */
3408         global->setCodeAddress(m_code->globals.size());
3409         m_code->globals.push_back(0);
3410         /* Add the def */
3411         if (pushdef)
3412             m_code->defs.push_back(def);
3413         return true;
3414     case TYPE_POINTER:
3415         if (pushdef)
3416             m_code->defs.push_back(def);
3417         return gen_global_pointer(m_code.get(), global);
3418     case TYPE_FIELD:
3419         if (pushdef) {
3420             m_code->defs.push_back(def);
3421             if (global->m_fieldtype == TYPE_VECTOR)
3422                 gen_vector_defs(m_code.get(), def, global->m_name.c_str());
3423         }
3424         return gen_global_field(m_code.get(), global);
3425     case TYPE_ENTITY:
3426         /* fall through */
3427     case TYPE_FLOAT:
3428     {
3429         global->setCodeAddress(m_code->globals.size());
3430         if (global->m_hasvalue) {
3431             if (global->m_cvq == CV_CONST && global->m_reads.empty())
3432                 return true;
3433             iptr = (int32_t*)&global->m_constval.ivec[0];
3434             m_code->globals.push_back(*iptr);
3435         } else {
3436             m_code->globals.push_back(0);
3437         }
3438         if (!islocal && global->m_cvq != CV_CONST)
3439             def.type |= DEF_SAVEGLOBAL;
3440         if (pushdef)
3441             m_code->defs.push_back(def);
3442
3443         return global->m_code.globaladdr >= 0;
3444     }
3445     case TYPE_STRING:
3446     {
3447         global->setCodeAddress(m_code->globals.size());
3448         if (global->m_hasvalue) {
3449             if (global->m_cvq == CV_CONST && global->m_reads.empty())
3450                 return true;
3451             uint32_t load = code_genstring(m_code.get(), global->m_constval.vstring);
3452             m_code->globals.push_back(load);
3453         } else {
3454             m_code->globals.push_back(0);
3455         }
3456         if (!islocal && global->m_cvq != CV_CONST)
3457             def.type |= DEF_SAVEGLOBAL;
3458         if (pushdef)
3459             m_code->defs.push_back(def);
3460         return global->m_code.globaladdr >= 0;
3461     }
3462     case TYPE_VECTOR:
3463     {
3464         size_t d;
3465         global->setCodeAddress(m_code->globals.size());
3466         if (global->m_hasvalue) {
3467             iptr = (int32_t*)&global->m_constval.ivec[0];
3468             m_code->globals.push_back(iptr[0]);
3469             if (global->m_code.globaladdr < 0)
3470                 return false;
3471             for (d = 1; d < type_sizeof_[global->m_vtype]; ++d) {
3472                 m_code->globals.push_back(iptr[d]);
3473             }
3474         } else {
3475             m_code->globals.push_back(0);
3476             if (global->m_code.globaladdr < 0)
3477                 return false;
3478             for (d = 1; d < type_sizeof_[global->m_vtype]; ++d) {
3479                 m_code->globals.push_back(0);
3480             }
3481         }
3482         if (!islocal && global->m_cvq != CV_CONST)
3483             def.type |= DEF_SAVEGLOBAL;
3484
3485         if (pushdef) {
3486             m_code->defs.push_back(def);
3487             def.type &= ~DEF_SAVEGLOBAL;
3488             gen_vector_defs(m_code.get(), def, global->m_name.c_str());
3489         }
3490         return global->m_code.globaladdr >= 0;
3491     }
3492     case TYPE_FUNCTION:
3493         global->setCodeAddress(m_code->globals.size());
3494         if (!global->m_hasvalue) {
3495             m_code->globals.push_back(0);
3496             if (global->m_code.globaladdr < 0)
3497                 return false;
3498         } else {
3499             m_code->globals.push_back(m_code->functions.size());
3500             if (!generateGlobalFunction(global))
3501                 return false;
3502         }
3503         if (!islocal && global->m_cvq != CV_CONST)
3504             def.type |= DEF_SAVEGLOBAL;
3505         if (pushdef)
3506             m_code->defs.push_back(def);
3507         return true;
3508     case TYPE_VARIANT:
3509         /* assume biggest type */
3510             global->setCodeAddress(m_code->globals.size());
3511             m_code->globals.push_back(0);
3512             for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3513                 m_code->globals.push_back(0);
3514             return true;
3515     default:
3516         /* refuse to create 'void' type or any other fancy business. */
3517         irerror(global->m_context, "Invalid type for global variable `%s`: %s",
3518                 global->m_name.c_str(), type_name[global->m_vtype]);
3519         return false;
3520     }
3521 }
3522
3523 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3524 {
3525     field->m_code.fieldaddr = code_alloc_field(code, type_sizeof_[field->m_fieldtype]);
3526 }
3527
3528 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3529 {
3530     prog_section_def_t def;
3531     prog_section_field_t fld;
3532
3533     (void)self;
3534
3535     def.type   = (uint16_t)field->m_vtype;
3536     def.offset = (uint16_t)self->m_code->globals.size();
3537
3538     /* create a global named the same as the field */
3539     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3540         /* in our standard, the global gets a dot prefix */
3541         size_t len = field->m_name.length();
3542         char name[1024];
3543
3544         /* we really don't want to have to allocate this, and 1024
3545          * bytes is more than enough for a variable/field name
3546          */
3547         if (len+2 >= sizeof(name)) {
3548             irerror(field->m_context, "invalid field name size: %u", (unsigned int)len);
3549             return false;
3550         }
3551
3552         name[0] = '.';
3553         memcpy(name+1, field->m_name.c_str(), len); // no strncpy - we used strlen above
3554         name[len+1] = 0;
3555
3556         def.name = code_genstring(self->m_code.get(), name);
3557         fld.name = def.name + 1; /* we reuse that string table entry */
3558     } else {
3559         /* in plain QC, there cannot be a global with the same name,
3560          * and so we also name the global the same.
3561          * FIXME: fteqcc should create a global as well
3562          * check if it actually uses the same name. Probably does
3563          */
3564         def.name = code_genstring(self->m_code.get(), field->m_name.c_str());
3565         fld.name = def.name;
3566     }
3567
3568     field->m_code.name = def.name;
3569
3570     self->m_code->defs.push_back(def);
3571
3572     fld.type = field->m_fieldtype;
3573
3574     if (fld.type == TYPE_VOID) {
3575         irerror(field->m_context, "field is missing a type: %s - don't know its size", field->m_name.c_str());
3576         return false;
3577     }
3578
3579     fld.offset = field->m_code.fieldaddr;
3580
3581     self->m_code->fields.push_back(fld);
3582
3583     field->setCodeAddress(self->m_code->globals.size());
3584     self->m_code->globals.push_back(fld.offset);
3585     if (fld.type == TYPE_VECTOR) {
3586         self->m_code->globals.push_back(fld.offset+1);
3587         self->m_code->globals.push_back(fld.offset+2);
3588     }
3589
3590     if (field->m_fieldtype == TYPE_VECTOR) {
3591         gen_vector_defs  (self->m_code.get(), def, field->m_name.c_str());
3592         gen_vector_fields(self->m_code.get(), fld, field->m_name.c_str());
3593     }
3594
3595     return field->m_code.globaladdr >= 0;
3596 }
3597
3598 static void ir_builder_collect_reusables(ir_builder *builder) {
3599     std::vector<ir_value*> reusables;
3600
3601     for (auto& gp : builder->m_globals) {
3602         ir_value *value = gp.get();
3603         if (value->m_vtype != TYPE_FLOAT || !value->m_hasvalue)
3604             continue;
3605         if (value->m_cvq == CV_CONST || (value->m_name.length() >= 1 && value->m_name[0] == '#'))
3606             reusables.emplace_back(value);
3607     }
3608     builder->m_const_floats = move(reusables);
3609 }
3610
3611 static void ir_builder_split_vector(ir_builder *self, ir_value *vec) {
3612     ir_value* found[3] = { nullptr, nullptr, nullptr };
3613
3614     // must not be written to
3615     if (vec->m_writes.size())
3616         return;
3617     // must not be trying to access individual members
3618     if (vec->m_members[0] || vec->m_members[1] || vec->m_members[2])
3619         return;
3620     // should be actually used otherwise it won't be generated anyway
3621     if (vec->m_reads.empty())
3622         return;
3623     //size_t count = vec->m_reads.size();
3624     //if (!count)
3625     //    return;
3626
3627     // may only be used directly as function parameters, so if we find some other instruction cancel
3628     for (ir_instr *user : vec->m_reads) {
3629         // we only split vectors if they're used directly as parameter to a call only!
3630         if ((user->m_opcode < INSTR_CALL0 || user->m_opcode > INSTR_CALL8) && user->m_opcode != VINSTR_NRCALL)
3631             return;
3632     }
3633
3634     vec->m_flags |= IR_FLAG_SPLIT_VECTOR;
3635
3636     // find existing floats making up the split
3637     for (ir_value *c : self->m_const_floats) {
3638         if (!found[0] && c->m_constval.vfloat == vec->m_constval.vvec.x)
3639             found[0] = c;
3640         if (!found[1] && c->m_constval.vfloat == vec->m_constval.vvec.y)
3641             found[1] = c;
3642         if (!found[2] && c->m_constval.vfloat == vec->m_constval.vvec.z)
3643             found[2] = c;
3644         if (found[0] && found[1] && found[2])
3645             break;
3646     }
3647
3648     // generate floats for not yet found components
3649     if (!found[0])
3650         found[0] = self->literalFloat(vec->m_constval.vvec.x, true);
3651     if (!found[1]) {
3652         if (vec->m_constval.vvec.y == vec->m_constval.vvec.x)
3653             found[1] = found[0];
3654         else
3655             found[1] = self->literalFloat(vec->m_constval.vvec.y, true);
3656     }
3657     if (!found[2]) {
3658         if (vec->m_constval.vvec.z == vec->m_constval.vvec.x)
3659             found[2] = found[0];
3660         else if (vec->m_constval.vvec.z == vec->m_constval.vvec.y)
3661             found[2] = found[1];
3662         else
3663             found[2] = self->literalFloat(vec->m_constval.vvec.z, true);
3664     }
3665
3666     // the .members array should be safe to use here
3667     vec->m_members[0] = found[0];
3668     vec->m_members[1] = found[1];
3669     vec->m_members[2] = found[2];
3670
3671     // register the readers for these floats
3672     found[0]->m_reads.insert(found[0]->m_reads.end(), vec->m_reads.begin(), vec->m_reads.end());
3673     found[1]->m_reads.insert(found[1]->m_reads.end(), vec->m_reads.begin(), vec->m_reads.end());
3674     found[2]->m_reads.insert(found[2]->m_reads.end(), vec->m_reads.begin(), vec->m_reads.end());
3675 }
3676
3677 static void ir_builder_split_vectors(ir_builder *self) {
3678     // member values may be added to self->m_globals during this operation, but
3679     // no new vectors will be added, we need to iterate via an index as
3680     // c++ iterators would be invalidated
3681     const size_t count = self->m_globals.size();
3682     for (size_t i = 0; i != count; ++i) {
3683         ir_value *v = self->m_globals[i].get();
3684         if (v->m_vtype != TYPE_VECTOR || !v->m_name.length() || v->m_name[0] != '#')
3685             continue;
3686         ir_builder_split_vector(self, v);
3687     }
3688 }
3689
3690 bool ir_builder::generate(const char *filename)
3691 {
3692     prog_section_statement_t stmt;
3693     char  *lnofile = nullptr;
3694
3695     if (OPTS_FLAG(SPLIT_VECTOR_PARAMETERS)) {
3696         ir_builder_collect_reusables(this);
3697         if (!m_const_floats.empty())
3698             ir_builder_split_vectors(this);
3699     }
3700
3701     for (auto& fp : m_fields)
3702         ir_builder_prepare_field(m_code.get(), fp.get());
3703
3704     for (auto& gp : m_globals) {
3705         ir_value *global = gp.get();
3706         if (!generateGlobal(global, false)) {
3707             return false;
3708         }
3709         if (global->m_vtype == TYPE_FUNCTION) {
3710             ir_function *func = global->m_constval.vfunc;
3711             if (func && m_max_locals < func->m_allocated_locals &&
3712                 !(func->m_flags & IR_FLAG_MASK_NO_OVERLAP))
3713             {
3714                 m_max_locals = func->m_allocated_locals;
3715             }
3716             if (func && m_max_globaltemps < func->m_globaltemps)
3717                 m_max_globaltemps = func->m_globaltemps;
3718         }
3719     }
3720
3721     for (auto& fp : m_fields) {
3722         if (!ir_builder_gen_field(this, fp.get()))
3723             return false;
3724     }
3725
3726     // generate nil
3727     m_nil->setCodeAddress(m_code->globals.size());
3728     m_code->globals.push_back(0);
3729     m_code->globals.push_back(0);
3730     m_code->globals.push_back(0);
3731
3732     // generate virtual-instruction temps
3733     for (size_t i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
3734         m_vinstr_temp[i]->setCodeAddress(m_code->globals.size());
3735         m_code->globals.push_back(0);
3736         m_code->globals.push_back(0);
3737         m_code->globals.push_back(0);
3738     }
3739
3740     // generate global temps
3741     m_first_common_globaltemp = m_code->globals.size();
3742     m_code->globals.insert(m_code->globals.end(), m_max_globaltemps, 0);
3743     // FIXME:DELME:
3744     //for (size_t i = 0; i < m_max_globaltemps; ++i) {
3745     //    m_code->globals.push_back(0);
3746     //}
3747     // generate common locals
3748     m_first_common_local = m_code->globals.size();
3749     m_code->globals.insert(m_code->globals.end(), m_max_locals, 0);
3750     // FIXME:DELME:
3751     //for (i = 0; i < m_max_locals; ++i) {
3752     //    m_code->globals.push_back(0);
3753     //}
3754
3755     // generate function code
3756
3757     for (auto& gp : m_globals) {
3758         ir_value *global = gp.get();
3759         if (global->m_vtype == TYPE_FUNCTION) {
3760             if (!this->generateGlobalFunctionCode(global))
3761                 return false;
3762         }
3763     }
3764
3765     if (m_code->globals.size() >= 65536) {
3766         irerror(m_globals.back()->m_context,
3767             "This progs file would require more globals than the metadata can handle (%zu). Bailing out.",
3768             m_code->globals.size());
3769         return false;
3770     }
3771
3772     /* DP errors if the last instruction is not an INSTR_DONE. */
3773     if (m_code->statements.back().opcode != INSTR_DONE)
3774     {
3775         lex_ctx_t last;
3776
3777         stmt.opcode = INSTR_DONE;
3778         stmt.o1.u1  = 0;
3779         stmt.o2.u1  = 0;
3780         stmt.o3.u1  = 0;
3781         last.line   = m_code->linenums.back();
3782         last.column = m_code->columnnums.back();
3783
3784         code_push_statement(m_code.get(), &stmt, last);
3785     }
3786
3787     if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3788         return true;
3789
3790     if (m_code->statements.size() != m_code->linenums.size()) {
3791         con_err("Linecounter wrong: %lu != %lu\n",
3792                 m_code->statements.size(),
3793                 m_code->linenums.size());
3794     } else if (OPTS_FLAG(LNO)) {
3795         char  *dot;
3796         size_t filelen = strlen(filename);
3797
3798         memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3799         dot = strrchr(lnofile, '.');
3800         if (!dot) {
3801             vec_pop(lnofile);
3802         } else {
3803             vec_shrinkto(lnofile, dot - lnofile);
3804         }
3805         memcpy(vec_add(lnofile, 5), ".lno", 5);
3806     }
3807
3808     if (!code_write(m_code.get(), filename, lnofile)) {
3809         vec_free(lnofile);
3810         return false;
3811     }
3812
3813     vec_free(lnofile);
3814     return true;
3815 }
3816
3817 /***********************************************************************
3818  *IR DEBUG Dump functions...
3819  */
3820
3821 #define IND_BUFSZ 1024
3822
3823 static const char *qc_opname(int op)
3824 {
3825     if (op < 0) return "<INVALID>";
3826     if (op < VINSTR_END)
3827         return util_instr_str[op];
3828     switch (op) {
3829         case VINSTR_END:       return "END";
3830         case VINSTR_PHI:       return "PHI";
3831         case VINSTR_JUMP:      return "JUMP";
3832         case VINSTR_COND:      return "COND";
3833         case VINSTR_BITXOR:    return "BITXOR";
3834         case VINSTR_BITAND_V:  return "BITAND_V";
3835         case VINSTR_BITOR_V:   return "BITOR_V";
3836         case VINSTR_BITXOR_V:  return "BITXOR_V";
3837         case VINSTR_BITAND_VF: return "BITAND_VF";
3838         case VINSTR_BITOR_VF:  return "BITOR_VF";
3839         case VINSTR_BITXOR_VF: return "BITXOR_VF";
3840         case VINSTR_CROSS:     return "CROSS";
3841         case VINSTR_NEG_F:     return "NEG_F";
3842         case VINSTR_NEG_V:     return "NEG_V";
3843         default:               return "<UNK>";
3844     }
3845 }
3846
3847 void ir_builder::dump(int (*oprintf)(const char*, ...)) const
3848 {
3849     size_t i;
3850     char indent[IND_BUFSZ];
3851     indent[0] = '\t';
3852     indent[1] = 0;
3853
3854     oprintf("module %s\n", m_name.c_str());
3855     for (i = 0; i < m_globals.size(); ++i)
3856     {
3857         oprintf("global ");
3858         if (m_globals[i]->m_hasvalue)
3859             oprintf("%s = ", m_globals[i]->m_name.c_str());
3860         m_globals[i].get()->dump(oprintf);
3861         oprintf("\n");
3862     }
3863     for (i = 0; i < m_functions.size(); ++i)
3864         ir_function_dump(m_functions[i].get(), indent, oprintf);
3865     oprintf("endmodule %s\n", m_name.c_str());
3866 }
3867
3868 static const char *storenames[] = {
3869     "[global]", "[local]", "[param]", "[value]", "[return]"
3870 };
3871
3872 void ir_function_dump(ir_function *f, char *ind,
3873                       int (*oprintf)(const char*, ...))
3874 {
3875     size_t i;
3876     if (f->m_builtin != 0) {
3877         oprintf("%sfunction %s = builtin %i\n", ind, f->m_name.c_str(), -f->m_builtin);
3878         return;
3879     }
3880     oprintf("%sfunction %s\n", ind, f->m_name.c_str());
3881     util_strncat(ind, "\t", IND_BUFSZ-1);
3882     if (f->m_locals.size())
3883     {
3884         oprintf("%s%i locals:\n", ind, (int)f->m_locals.size());
3885         for (i = 0; i < f->m_locals.size(); ++i) {
3886             oprintf("%s\t", ind);
3887             f->m_locals[i].get()->dump(oprintf);
3888             oprintf("\n");
3889         }
3890     }
3891     oprintf("%sliferanges:\n", ind);
3892     for (i = 0; i < f->m_locals.size(); ++i) {
3893         const char *attr = "";
3894         size_t l, m;
3895         ir_value *v = f->m_locals[i].get();
3896         if (v->m_unique_life && v->m_locked)
3897             attr = "unique,locked ";
3898         else if (v->m_unique_life)
3899             attr = "unique ";
3900         else if (v->m_locked)
3901             attr = "locked ";
3902         oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->m_name.c_str(), type_name[v->m_vtype],
3903                 storenames[v->m_store],
3904                 attr, (v->m_callparam ? "callparam " : ""),
3905                 (int)v->m_code.local);
3906         if (v->m_life.empty())
3907             oprintf("[null]");
3908         for (l = 0; l < v->m_life.size(); ++l) {
3909             oprintf("[%i,%i] ", v->m_life[l].start, v->m_life[l].end);
3910         }
3911         oprintf("\n");
3912         for (m = 0; m < 3; ++m) {
3913             ir_value *vm = v->m_members[m];
3914             if (!vm)
3915                 continue;
3916             oprintf("%s\t%s: @%i ", ind, vm->m_name.c_str(), (int)vm->m_code.local);
3917             for (l = 0; l < vm->m_life.size(); ++l) {
3918                 oprintf("[%i,%i] ", vm->m_life[l].start, vm->m_life[l].end);
3919             }
3920             oprintf("\n");
3921         }
3922     }
3923     for (i = 0; i < f->m_values.size(); ++i) {
3924         const char *attr = "";
3925         size_t l, m;
3926         ir_value *v = f->m_values[i].get();
3927         if (v->m_unique_life && v->m_locked)
3928             attr = "unique,locked ";
3929         else if (v->m_unique_life)
3930             attr = "unique ";
3931         else if (v->m_locked)
3932             attr = "locked ";
3933         oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->m_name.c_str(), type_name[v->m_vtype],
3934                 storenames[v->m_store],
3935                 attr, (v->m_callparam ? "callparam " : ""),
3936                 (int)v->m_code.local);
3937         if (v->m_life.empty())
3938             oprintf("[null]");
3939         for (l = 0; l < v->m_life.size(); ++l) {
3940             oprintf("[%i,%i] ", v->m_life[l].start, v->m_life[l].end);
3941         }
3942         oprintf("\n");
3943         for (m = 0; m < 3; ++m) {
3944             ir_value *vm = v->m_members[m];
3945             if (!vm)
3946                 continue;
3947             if (vm->m_unique_life && vm->m_locked)
3948                 attr = "unique,locked ";
3949             else if (vm->m_unique_life)
3950                 attr = "unique ";
3951             else if (vm->m_locked)
3952                 attr = "locked ";
3953             oprintf("%s\t%s: %s@%i ", ind, vm->m_name.c_str(), attr, (int)vm->m_code.local);
3954             for (l = 0; l < vm->m_life.size(); ++l) {
3955                 oprintf("[%i,%i] ", vm->m_life[l].start, vm->m_life[l].end);
3956             }
3957             oprintf("\n");
3958         }
3959     }
3960     if (f->m_blocks.size())
3961     {
3962         oprintf("%slife passes: %i\n", ind, (int)f->m_run_id);
3963         for (i = 0; i < f->m_blocks.size(); ++i) {
3964             ir_block_dump(f->m_blocks[i].get(), ind, oprintf);
3965         }
3966
3967     }
3968     ind[strlen(ind)-1] = 0;
3969     oprintf("%sendfunction %s\n", ind, f->m_name.c_str());
3970 }
3971
3972 void ir_block_dump(ir_block* b, char *ind,
3973                    int (*oprintf)(const char*, ...))
3974 {
3975     oprintf("%s:%s\n", ind, b->m_label.c_str());
3976     util_strncat(ind, "\t", IND_BUFSZ-1);
3977
3978     if (!b->m_instr.empty() && b->m_instr[0])
3979         oprintf("%s (%i) [entry]\n", ind, (int)(b->m_instr[0]->m_eid-1));
3980     for (auto &i : b->m_instr)
3981         ir_instr_dump(i, ind, oprintf);
3982     ind[strlen(ind)-1] = 0;
3983 }
3984
3985 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3986 {
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());
3991     }
3992     oprintf("\n");
3993 }
3994
3995 void ir_instr_dump(ir_instr *in, char *ind,
3996                        int (*oprintf)(const char*, ...))
3997 {
3998     size_t i;
3999     const char *comma = nullptr;
4000
4001     oprintf("%s (%i) ", ind, (int)in->m_eid);
4002
4003     if (in->m_opcode == VINSTR_PHI) {
4004         dump_phi(in, oprintf);
4005         return;
4006     }
4007
4008     util_strncat(ind, "\t", IND_BUFSZ-1);
4009
4010     if (in->_m_ops[0] && (in->_m_ops[1] || in->_m_ops[2])) {
4011         in->_m_ops[0]->dump(oprintf);
4012         if (in->_m_ops[1] || in->_m_ops[2])
4013             oprintf(" <- ");
4014     }
4015     if (in->m_opcode == INSTR_CALL0 || in->m_opcode == VINSTR_NRCALL) {
4016         oprintf("CALL%i\t", in->m_params.size());
4017     } else
4018         oprintf("%s\t", qc_opname(in->m_opcode));
4019
4020     if (in->_m_ops[0] && !(in->_m_ops[1] || in->_m_ops[2])) {
4021         in->_m_ops[0]->dump(oprintf);
4022         comma = ",\t";
4023     }
4024     else
4025     {
4026         for (i = 1; i != 3; ++i) {
4027             if (in->_m_ops[i]) {
4028                 if (comma)
4029                     oprintf(comma);
4030                 in->_m_ops[i]->dump(oprintf);
4031                 comma = ",\t";
4032             }
4033         }
4034     }
4035     if (in->m_bops[0]) {
4036         if (comma)
4037             oprintf(comma);
4038         oprintf("[%s]", in->m_bops[0]->m_label.c_str());
4039         comma = ",\t";
4040     }
4041     if (in->m_bops[1])
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());
4047     }
4048     oprintf("\n");
4049     ind[strlen(ind)-1] = 0;
4050 }
4051
4052 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
4053 {
4054     oprintf("\"");
4055     for (; *str; ++str) {
4056         switch (*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;
4067         }
4068     }
4069     oprintf("\"");
4070 }
4071
4072 void ir_value::dump(int (*oprintf)(const char*, ...)) const
4073 {
4074     if (m_hasvalue) {
4075         switch (m_vtype) {
4076             default:
4077             case TYPE_VOID:
4078                 oprintf("(void)");
4079                 break;
4080             case TYPE_FUNCTION:
4081                 oprintf("fn:%s", m_name.c_str());
4082                 break;
4083             case TYPE_FLOAT:
4084                 oprintf("%g", m_constval.vfloat);
4085                 break;
4086             case TYPE_VECTOR:
4087                 oprintf("'%g %g %g'",
4088                         m_constval.vvec.x,
4089                         m_constval.vvec.y,
4090                         m_constval.vvec.z);
4091                 break;
4092             case TYPE_ENTITY:
4093                 oprintf("(entity)");
4094                 break;
4095             case TYPE_STRING:
4096                 ir_value_dump_string(m_constval.vstring, oprintf);
4097                 break;
4098 #if 0
4099             case TYPE_INTEGER:
4100                 oprintf("%i", m_constval.vint);
4101                 break;
4102 #endif
4103             case TYPE_POINTER:
4104                 oprintf("&%s",
4105                     m_constval.vpointer->m_name.c_str());
4106                 break;
4107         }
4108     } else {
4109         oprintf("%s", m_name.c_str());
4110     }
4111 }
4112
4113 void ir_value::dumpLife(int (*oprintf)(const char*,...)) const
4114 {
4115     oprintf("Life of %12s:", m_name.c_str());
4116     for (size_t i = 0; i < m_life.size(); ++i)
4117     {
4118         oprintf(" + [%i, %i]\n", m_life[i].start, m_life[i].end);
4119     }
4120 }