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