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