]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
error when trying to pass a TYPE_NOEXPR value to ir_instr_op
[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 (v && v->vtype == TYPE_NOEXPR) {
1036         irerror(self->context, "tried to use a NOEXPR value");
1037         return false;
1038     }
1039
1040     if (self->_ops[op]) {
1041         size_t idx;
1042         if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1043             vec_remove(self->_ops[op]->writes, idx, 1);
1044         else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1045             vec_remove(self->_ops[op]->reads, idx, 1);
1046     }
1047     if (v) {
1048         if (writing)
1049             vec_push(v->writes, self);
1050         else
1051             vec_push(v->reads, self);
1052     }
1053     self->_ops[op] = v;
1054     return true;
1055 }
1056
1057 /***********************************************************************
1058  *IR Value
1059  */
1060
1061 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1062 {
1063     self->code.globaladdr = gaddr;
1064     if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1065     if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1066     if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1067 }
1068
1069 static int32_t ir_value_code_addr(const ir_value *self)
1070 {
1071     if (self->store == store_return)
1072         return OFS_RETURN + self->code.addroffset;
1073     return self->code.globaladdr + self->code.addroffset;
1074 }
1075
1076 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1077 {
1078     ir_value *self;
1079     self = (ir_value*)mem_a(sizeof(*self));
1080     self->vtype = vtype;
1081     self->fieldtype = TYPE_VOID;
1082     self->outtype = TYPE_VOID;
1083     self->store = storetype;
1084     self->flags = 0;
1085
1086     self->reads  = NULL;
1087     self->writes = NULL;
1088
1089     self->cvq          = CV_NONE;
1090     self->hasvalue     = false;
1091     self->context.file = "<@no context>";
1092     self->context.line = 0;
1093     self->name = NULL;
1094     if (name && !ir_value_set_name(self, name)) {
1095         irerror(self->context, "out of memory");
1096         mem_d(self);
1097         return NULL;
1098     }
1099
1100     memset(&self->constval, 0, sizeof(self->constval));
1101     memset(&self->code,     0, sizeof(self->code));
1102
1103     self->members[0] = NULL;
1104     self->members[1] = NULL;
1105     self->members[2] = NULL;
1106     self->memberof = NULL;
1107
1108     self->unique_life = false;
1109     self->locked      = false;
1110     self->callparam   = false;
1111
1112     self->life = NULL;
1113     return self;
1114 }
1115
1116 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1117 {
1118     char     *name;
1119     size_t    len;
1120     ir_value *m;
1121     if (member >= 3)
1122         return NULL;
1123
1124     if (self->members[member])
1125         return self->members[member];
1126
1127     if (self->name) {
1128         len = strlen(self->name);
1129         name = (char*)mem_a(len + 3);
1130         memcpy(name, self->name, len);
1131         name[len+0] = '_';
1132         name[len+1] = 'x' + member;
1133         name[len+2] = '\0';
1134     }
1135     else
1136         name = NULL;
1137
1138     if (self->vtype == TYPE_VECTOR)
1139     {
1140         m = ir_value_var(name, self->store, TYPE_FLOAT);
1141         if (name)
1142             mem_d(name);
1143         if (!m)
1144             return NULL;
1145         m->context = self->context;
1146
1147         self->members[member] = m;
1148         m->code.addroffset = member;
1149     }
1150     else if (self->vtype == TYPE_FIELD)
1151     {
1152         if (self->fieldtype != TYPE_VECTOR)
1153             return NULL;
1154         m = ir_value_var(name, self->store, TYPE_FIELD);
1155         if (name)
1156             mem_d(name);
1157         if (!m)
1158             return NULL;
1159         m->fieldtype = TYPE_FLOAT;
1160         m->context = self->context;
1161
1162         self->members[member] = m;
1163         m->code.addroffset = member;
1164     }
1165     else
1166     {
1167         irerror(self->context, "invalid member access on %s", self->name);
1168         return NULL;
1169     }
1170
1171     m->memberof = self;
1172     return m;
1173 }
1174
1175 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1176 {
1177     if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1178         return type_sizeof_[TYPE_VECTOR];
1179     return type_sizeof_[self->vtype];
1180 }
1181
1182 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1183 {
1184     ir_value *v = ir_value_var(name, storetype, vtype);
1185     if (!v)
1186         return NULL;
1187     ir_function_collect_value(owner, v);
1188     return v;
1189 }
1190
1191 void ir_value_delete(ir_value* self)
1192 {
1193     size_t i;
1194     if (self->name)
1195         mem_d((void*)self->name);
1196     if (self->hasvalue)
1197     {
1198         if (self->vtype == TYPE_STRING)
1199             mem_d((void*)self->constval.vstring);
1200     }
1201     for (i = 0; i < 3; ++i) {
1202         if (self->members[i])
1203             ir_value_delete(self->members[i]);
1204     }
1205     vec_free(self->reads);
1206     vec_free(self->writes);
1207     vec_free(self->life);
1208     mem_d(self);
1209 }
1210
1211 bool ir_value_set_name(ir_value *self, const char *name)
1212 {
1213     if (self->name)
1214         mem_d((void*)self->name);
1215     self->name = util_strdup(name);
1216     return !!self->name;
1217 }
1218
1219 bool ir_value_set_float(ir_value *self, float f)
1220 {
1221     if (self->vtype != TYPE_FLOAT)
1222         return false;
1223     self->constval.vfloat = f;
1224     self->hasvalue = true;
1225     return true;
1226 }
1227
1228 bool ir_value_set_func(ir_value *self, int f)
1229 {
1230     if (self->vtype != TYPE_FUNCTION)
1231         return false;
1232     self->constval.vint = f;
1233     self->hasvalue = true;
1234     return true;
1235 }
1236
1237 bool ir_value_set_vector(ir_value *self, vec3_t v)
1238 {
1239     if (self->vtype != TYPE_VECTOR)
1240         return false;
1241     self->constval.vvec = v;
1242     self->hasvalue = true;
1243     return true;
1244 }
1245
1246 bool ir_value_set_field(ir_value *self, ir_value *fld)
1247 {
1248     if (self->vtype != TYPE_FIELD)
1249         return false;
1250     self->constval.vpointer = fld;
1251     self->hasvalue = true;
1252     return true;
1253 }
1254
1255 bool ir_value_set_string(ir_value *self, const char *str)
1256 {
1257     if (self->vtype != TYPE_STRING)
1258         return false;
1259     self->constval.vstring = util_strdupe(str);
1260     self->hasvalue = true;
1261     return true;
1262 }
1263
1264 #if 0
1265 bool ir_value_set_int(ir_value *self, int i)
1266 {
1267     if (self->vtype != TYPE_INTEGER)
1268         return false;
1269     self->constval.vint = i;
1270     self->hasvalue = true;
1271     return true;
1272 }
1273 #endif
1274
1275 bool ir_value_lives(ir_value *self, size_t at)
1276 {
1277     size_t i;
1278     for (i = 0; i < vec_size(self->life); ++i)
1279     {
1280         ir_life_entry_t *life = &self->life[i];
1281         if (life->start <= at && at <= life->end)
1282             return true;
1283         if (life->start > at) /* since it's ordered */
1284             return false;
1285     }
1286     return false;
1287 }
1288
1289 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1290 {
1291     size_t k;
1292     vec_push(self->life, e);
1293     for (k = vec_size(self->life)-1; k > idx; --k)
1294         self->life[k] = self->life[k-1];
1295     self->life[idx] = e;
1296     return true;
1297 }
1298
1299 static bool ir_value_life_merge(ir_value *self, size_t s)
1300 {
1301     size_t i;
1302     const size_t vs = vec_size(self->life);
1303     ir_life_entry_t *life = NULL;
1304     ir_life_entry_t *before = NULL;
1305     ir_life_entry_t new_entry;
1306
1307     /* Find the first range >= s */
1308     for (i = 0; i < vs; ++i)
1309     {
1310         before = life;
1311         life = &self->life[i];
1312         if (life->start > s)
1313             break;
1314     }
1315     /* nothing found? append */
1316     if (i == vs) {
1317         ir_life_entry_t e;
1318         if (life && life->end+1 == s)
1319         {
1320             /* previous life range can be merged in */
1321             life->end++;
1322             return true;
1323         }
1324         if (life && life->end >= s)
1325             return false;
1326         e.start = e.end = s;
1327         vec_push(self->life, e);
1328         return true;
1329     }
1330     /* found */
1331     if (before)
1332     {
1333         if (before->end + 1 == s &&
1334             life->start - 1 == s)
1335         {
1336             /* merge */
1337             before->end = life->end;
1338             vec_remove(self->life, i, 1);
1339             return true;
1340         }
1341         if (before->end + 1 == s)
1342         {
1343             /* extend before */
1344             before->end++;
1345             return true;
1346         }
1347         /* already contained */
1348         if (before->end >= s)
1349             return false;
1350     }
1351     /* extend */
1352     if (life->start - 1 == s)
1353     {
1354         life->start--;
1355         return true;
1356     }
1357     /* insert a new entry */
1358     new_entry.start = new_entry.end = s;
1359     return ir_value_life_insert(self, i, new_entry);
1360 }
1361
1362 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1363 {
1364     size_t i, myi;
1365
1366     if (!vec_size(other->life))
1367         return true;
1368
1369     if (!vec_size(self->life)) {
1370         size_t count = vec_size(other->life);
1371         ir_life_entry_t *life = vec_add(self->life, count);
1372         memcpy(life, other->life, count * sizeof(*life));
1373         return true;
1374     }
1375
1376     myi = 0;
1377     for (i = 0; i < vec_size(other->life); ++i)
1378     {
1379         const ir_life_entry_t *life = &other->life[i];
1380         while (true)
1381         {
1382             ir_life_entry_t *entry = &self->life[myi];
1383
1384             if (life->end+1 < entry->start)
1385             {
1386                 /* adding an interval before entry */
1387                 if (!ir_value_life_insert(self, myi, *life))
1388                     return false;
1389                 ++myi;
1390                 break;
1391             }
1392
1393             if (life->start <  entry->start &&
1394                 life->end+1 >= entry->start)
1395             {
1396                 /* starts earlier and overlaps */
1397                 entry->start = life->start;
1398             }
1399
1400             if (life->end   >  entry->end &&
1401                 life->start <= entry->end+1)
1402             {
1403                 /* ends later and overlaps */
1404                 entry->end = life->end;
1405             }
1406
1407             /* see if our change combines it with the next ranges */
1408             while (myi+1 < vec_size(self->life) &&
1409                    entry->end+1 >= self->life[1+myi].start)
1410             {
1411                 /* overlaps with (myi+1) */
1412                 if (entry->end < self->life[1+myi].end)
1413                     entry->end = self->life[1+myi].end;
1414                 vec_remove(self->life, myi+1, 1);
1415                 entry = &self->life[myi];
1416             }
1417
1418             /* see if we're after the entry */
1419             if (life->start > entry->end)
1420             {
1421                 ++myi;
1422                 /* append if we're at the end */
1423                 if (myi >= vec_size(self->life)) {
1424                     vec_push(self->life, *life);
1425                     break;
1426                 }
1427                 /* otherweise check the next range */
1428                 continue;
1429             }
1430             break;
1431         }
1432     }
1433     return true;
1434 }
1435
1436 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1437 {
1438     /* For any life entry in A see if it overlaps with
1439      * any life entry in B.
1440      * Note that the life entries are orderes, so we can make a
1441      * more efficient algorithm there than naively translating the
1442      * statement above.
1443      */
1444
1445     ir_life_entry_t *la, *lb, *enda, *endb;
1446
1447     /* first of all, if either has no life range, they cannot clash */
1448     if (!vec_size(a->life) || !vec_size(b->life))
1449         return false;
1450
1451     la = a->life;
1452     lb = b->life;
1453     enda = la + vec_size(a->life);
1454     endb = lb + vec_size(b->life);
1455     while (true)
1456     {
1457         /* check if the entries overlap, for that,
1458          * both must start before the other one ends.
1459          */
1460         if (la->start < lb->end &&
1461             lb->start < la->end)
1462         {
1463             return true;
1464         }
1465
1466         /* entries are ordered
1467          * one entry is earlier than the other
1468          * that earlier entry will be moved forward
1469          */
1470         if (la->start < lb->start)
1471         {
1472             /* order: A B, move A forward
1473              * check if we hit the end with A
1474              */
1475             if (++la == enda)
1476                 break;
1477         }
1478         else /* if (lb->start < la->start)  actually <= */
1479         {
1480             /* order: B A, move B forward
1481              * check if we hit the end with B
1482              */
1483             if (++lb == endb)
1484                 break;
1485         }
1486     }
1487     return false;
1488 }
1489
1490 /***********************************************************************
1491  *IR main operations
1492  */
1493
1494 static bool ir_check_unreachable(ir_block *self)
1495 {
1496     /* The IR should never have to deal with unreachable code */
1497     if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1498         return true;
1499     irerror(self->context, "unreachable statement (%s)", self->label);
1500     return false;
1501 }
1502
1503 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1504 {
1505     ir_instr *in;
1506     if (!ir_check_unreachable(self))
1507         return false;
1508
1509     if (target->store == store_value &&
1510         (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1511     {
1512         irerror(self->context, "cannot store to an SSA value");
1513         irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1514         irerror(self->context, "instruction: %s", util_instr_str[op]);
1515         return false;
1516     }
1517
1518     in = ir_instr_new(ctx, self, op);
1519     if (!in)
1520         return false;
1521
1522     if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1523         !ir_instr_op(in, 1, what, false))
1524     {
1525         ir_instr_delete(in);
1526         return false;
1527     }
1528     vec_push(self->instr, in);
1529     return true;
1530 }
1531
1532 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1533 {
1534     int op = 0;
1535     int vtype;
1536     if (target->vtype == TYPE_VARIANT)
1537         vtype = what->vtype;
1538     else
1539         vtype = target->vtype;
1540
1541 #if 0
1542     if      (vtype == TYPE_FLOAT   && what->vtype == TYPE_INTEGER)
1543         op = INSTR_CONV_ITOF;
1544     else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1545         op = INSTR_CONV_FTOI;
1546 #endif
1547         op = type_store_instr[vtype];
1548
1549     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1550         if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1551             op = INSTR_STORE_V;
1552     }
1553
1554     return ir_block_create_store_op(self, ctx, op, target, what);
1555 }
1556
1557 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1558 {
1559     int op = 0;
1560     int vtype;
1561
1562     if (target->vtype != TYPE_POINTER)
1563         return false;
1564
1565     /* storing using pointer - target is a pointer, type must be
1566      * inferred from source
1567      */
1568     vtype = what->vtype;
1569
1570     op = type_storep_instr[vtype];
1571     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1572         if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1573             op = INSTR_STOREP_V;
1574     }
1575
1576     return ir_block_create_store_op(self, ctx, op, target, what);
1577 }
1578
1579 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1580 {
1581     ir_instr *in;
1582     if (!ir_check_unreachable(self))
1583         return false;
1584     self->final = true;
1585     self->is_return = true;
1586     in = ir_instr_new(ctx, self, INSTR_RETURN);
1587     if (!in)
1588         return false;
1589
1590     if (v && !ir_instr_op(in, 0, v, false)) {
1591         ir_instr_delete(in);
1592         return false;
1593     }
1594
1595     vec_push(self->instr, in);
1596     return true;
1597 }
1598
1599 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1600                         ir_block *ontrue, ir_block *onfalse)
1601 {
1602     ir_instr *in;
1603     if (!ir_check_unreachable(self))
1604         return false;
1605     self->final = true;
1606     /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1607     in = ir_instr_new(ctx, self, VINSTR_COND);
1608     if (!in)
1609         return false;
1610
1611     if (!ir_instr_op(in, 0, v, false)) {
1612         ir_instr_delete(in);
1613         return false;
1614     }
1615
1616     in->bops[0] = ontrue;
1617     in->bops[1] = onfalse;
1618
1619     vec_push(self->instr, in);
1620
1621     vec_push(self->exits, ontrue);
1622     vec_push(self->exits, onfalse);
1623     vec_push(ontrue->entries,  self);
1624     vec_push(onfalse->entries, self);
1625     return true;
1626 }
1627
1628 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1629 {
1630     ir_instr *in;
1631     if (!ir_check_unreachable(self))
1632         return false;
1633     self->final = true;
1634     in = ir_instr_new(ctx, self, VINSTR_JUMP);
1635     if (!in)
1636         return false;
1637
1638     in->bops[0] = to;
1639     vec_push(self->instr, in);
1640
1641     vec_push(self->exits, to);
1642     vec_push(to->entries, self);
1643     return true;
1644 }
1645
1646 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1647 {
1648     self->owner->flags |= IR_FLAG_HAS_GOTO;
1649     return ir_block_create_jump(self, ctx, to);
1650 }
1651
1652 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, int ot)
1653 {
1654     ir_value *out;
1655     ir_instr *in;
1656     if (!ir_check_unreachable(self))
1657         return NULL;
1658     in = ir_instr_new(ctx, self, VINSTR_PHI);
1659     if (!in)
1660         return NULL;
1661     out = ir_value_out(self->owner, label, store_value, ot);
1662     if (!out) {
1663         ir_instr_delete(in);
1664         return NULL;
1665     }
1666     if (!ir_instr_op(in, 0, out, true)) {
1667         ir_instr_delete(in);
1668         ir_value_delete(out);
1669         return NULL;
1670     }
1671     vec_push(self->instr, in);
1672     return in;
1673 }
1674
1675 ir_value* ir_phi_value(ir_instr *self)
1676 {
1677     return self->_ops[0];
1678 }
1679
1680 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1681 {
1682     ir_phi_entry_t pe;
1683
1684     if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1685         /* Must not be possible to cause this, otherwise the AST
1686          * is doing something wrong.
1687          */
1688         irerror(self->context, "Invalid entry block for PHI");
1689         exit(EXIT_FAILURE);
1690     }
1691
1692     pe.value = v;
1693     pe.from = b;
1694     vec_push(v->reads, self);
1695     vec_push(self->phi, pe);
1696 }
1697
1698 /* call related code */
1699 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1700 {
1701     ir_value *out;
1702     ir_instr *in;
1703     if (!ir_check_unreachable(self))
1704         return NULL;
1705     in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1706     if (!in)
1707         return NULL;
1708     if (noreturn) {
1709         self->final = true;
1710         self->is_return = true;
1711     }
1712     out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1713     if (!out) {
1714         ir_instr_delete(in);
1715         return NULL;
1716     }
1717     if (!ir_instr_op(in, 0, out, true) ||
1718         !ir_instr_op(in, 1, func, false))
1719     {
1720         ir_instr_delete(in);
1721         ir_value_delete(out);
1722         return NULL;
1723     }
1724     vec_push(self->instr, in);
1725     /*
1726     if (noreturn) {
1727         if (!ir_block_create_return(self, ctx, NULL)) {
1728             compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1729             ir_instr_delete(in);
1730             return NULL;
1731         }
1732     }
1733     */
1734     return in;
1735 }
1736
1737 ir_value* ir_call_value(ir_instr *self)
1738 {
1739     return self->_ops[0];
1740 }
1741
1742 void ir_call_param(ir_instr* self, ir_value *v)
1743 {
1744     vec_push(self->params, v);
1745     vec_push(v->reads, self);
1746 }
1747
1748 /* binary op related code */
1749
1750 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1751                                 const char *label, int opcode,
1752                                 ir_value *left, ir_value *right)
1753 {
1754     int ot = TYPE_VOID;
1755     switch (opcode) {
1756         case INSTR_ADD_F:
1757         case INSTR_SUB_F:
1758         case INSTR_DIV_F:
1759         case INSTR_MUL_F:
1760         case INSTR_MUL_V:
1761         case INSTR_AND:
1762         case INSTR_OR:
1763 #if 0
1764         case INSTR_AND_I:
1765         case INSTR_AND_IF:
1766         case INSTR_AND_FI:
1767         case INSTR_OR_I:
1768         case INSTR_OR_IF:
1769         case INSTR_OR_FI:
1770 #endif
1771         case INSTR_BITAND:
1772         case INSTR_BITOR:
1773 #if 0
1774         case INSTR_SUB_S: /* -- offset of string as float */
1775         case INSTR_MUL_IF:
1776         case INSTR_MUL_FI:
1777         case INSTR_DIV_IF:
1778         case INSTR_DIV_FI:
1779         case INSTR_BITOR_IF:
1780         case INSTR_BITOR_FI:
1781         case INSTR_BITAND_FI:
1782         case INSTR_BITAND_IF:
1783         case INSTR_EQ_I:
1784         case INSTR_NE_I:
1785 #endif
1786             ot = TYPE_FLOAT;
1787             break;
1788 #if 0
1789         case INSTR_ADD_I:
1790         case INSTR_ADD_IF:
1791         case INSTR_ADD_FI:
1792         case INSTR_SUB_I:
1793         case INSTR_SUB_FI:
1794         case INSTR_SUB_IF:
1795         case INSTR_MUL_I:
1796         case INSTR_DIV_I:
1797         case INSTR_BITAND_I:
1798         case INSTR_BITOR_I:
1799         case INSTR_XOR_I:
1800         case INSTR_RSHIFT_I:
1801         case INSTR_LSHIFT_I:
1802             ot = TYPE_INTEGER;
1803             break;
1804 #endif
1805         case INSTR_ADD_V:
1806         case INSTR_SUB_V:
1807         case INSTR_MUL_VF:
1808         case INSTR_MUL_FV:
1809 #if 0
1810         case INSTR_DIV_VF:
1811         case INSTR_MUL_IV:
1812         case INSTR_MUL_VI:
1813 #endif
1814             ot = TYPE_VECTOR;
1815             break;
1816 #if 0
1817         case INSTR_ADD_SF:
1818             ot = TYPE_POINTER;
1819             break;
1820 #endif
1821     /*
1822      * after the following default case, the value of opcode can never
1823      * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1824      */
1825         default:
1826             /* ranges: */
1827             /* boolean operations result in floats */
1828
1829             /*
1830              * opcode >= 10 takes true branch opcode is at least 10
1831              * opcode <= 23 takes false branch opcode is at least 24
1832              */
1833             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1834                 ot = TYPE_FLOAT;
1835
1836             /*
1837              * At condition "opcode <= 23", the value of "opcode" must be
1838              * at least 24.
1839              * At condition "opcode <= 23", the value of "opcode" cannot be
1840              * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1841              * The condition "opcode <= 23" cannot be true.
1842              *
1843              * Thus ot=2 (TYPE_FLOAT) can never be true
1844              */
1845 #if 0
1846             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1847                 ot = TYPE_FLOAT;
1848             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1849                 ot = TYPE_FLOAT;
1850 #endif
1851             break;
1852     };
1853     if (ot == TYPE_VOID) {
1854         /* The AST or parser were supposed to check this! */
1855         return NULL;
1856     }
1857
1858     return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1859 }
1860
1861 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1862                                 const char *label, int opcode,
1863                                 ir_value *operand)
1864 {
1865     int ot = TYPE_FLOAT;
1866     switch (opcode) {
1867         case INSTR_NOT_F:
1868         case INSTR_NOT_V:
1869         case INSTR_NOT_S:
1870         case INSTR_NOT_ENT:
1871         case INSTR_NOT_FNC:
1872 #if 0
1873         case INSTR_NOT_I:
1874 #endif
1875             ot = TYPE_FLOAT;
1876             break;
1877         /* QC doesn't have other unary operations. We expect extensions to fill
1878          * the above list, otherwise we assume out-type = in-type, eg for an
1879          * unary minus
1880          */
1881         default:
1882             ot = operand->vtype;
1883             break;
1884     };
1885     if (ot == TYPE_VOID) {
1886         /* The AST or parser were supposed to check this! */
1887         return NULL;
1888     }
1889
1890     /* let's use the general instruction creator and pass NULL for OPB */
1891     return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1892 }
1893
1894 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1895                                         int op, ir_value *a, ir_value *b, int outype)
1896 {
1897     ir_instr *instr;
1898     ir_value *out;
1899
1900     out = ir_value_out(self->owner, label, store_value, outype);
1901     if (!out)
1902         return NULL;
1903
1904     instr = ir_instr_new(ctx, self, op);
1905     if (!instr) {
1906         ir_value_delete(out);
1907         return NULL;
1908     }
1909
1910     if (!ir_instr_op(instr, 0, out, true) ||
1911         !ir_instr_op(instr, 1, a, false) ||
1912         !ir_instr_op(instr, 2, b, false) )
1913     {
1914         goto on_error;
1915     }
1916
1917     vec_push(self->instr, instr);
1918
1919     return out;
1920 on_error:
1921     ir_instr_delete(instr);
1922     ir_value_delete(out);
1923     return NULL;
1924 }
1925
1926 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1927 {
1928     ir_value *v;
1929
1930     /* Support for various pointer types todo if so desired */
1931     if (ent->vtype != TYPE_ENTITY)
1932         return NULL;
1933
1934     if (field->vtype != TYPE_FIELD)
1935         return NULL;
1936
1937     v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1938     v->fieldtype = field->fieldtype;
1939     return v;
1940 }
1941
1942 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)
1943 {
1944     int op;
1945     if (ent->vtype != TYPE_ENTITY)
1946         return NULL;
1947
1948     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1949     if (field->vtype != TYPE_FIELD)
1950         return NULL;
1951
1952     switch (outype)
1953     {
1954         case TYPE_FLOAT:    op = INSTR_LOAD_F;   break;
1955         case TYPE_VECTOR:   op = INSTR_LOAD_V;   break;
1956         case TYPE_STRING:   op = INSTR_LOAD_S;   break;
1957         case TYPE_FIELD:    op = INSTR_LOAD_FLD; break;
1958         case TYPE_ENTITY:   op = INSTR_LOAD_ENT; break;
1959         case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1960 #if 0
1961         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1962         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1963 #endif
1964         default:
1965             irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1966             return NULL;
1967     }
1968
1969     return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1970 }
1971
1972 /* PHI resolving breaks the SSA, and must thus be the last
1973  * step before life-range calculation.
1974  */
1975
1976 static bool ir_block_naive_phi(ir_block *self);
1977 bool ir_function_naive_phi(ir_function *self)
1978 {
1979     size_t i;
1980
1981     for (i = 0; i < vec_size(self->blocks); ++i)
1982     {
1983         if (!ir_block_naive_phi(self->blocks[i]))
1984             return false;
1985     }
1986     return true;
1987 }
1988
1989 static bool ir_block_naive_phi(ir_block *self)
1990 {
1991     size_t i, p; /*, w;*/
1992     /* FIXME: optionally, create_phi can add the phis
1993      * to a list so we don't need to loop through blocks
1994      * - anyway: "don't optimize YET"
1995      */
1996     for (i = 0; i < vec_size(self->instr); ++i)
1997     {
1998         ir_instr *instr = self->instr[i];
1999         if (instr->opcode != VINSTR_PHI)
2000             continue;
2001
2002         vec_remove(self->instr, i, 1);
2003         --i; /* NOTE: i+1 below */
2004
2005         for (p = 0; p < vec_size(instr->phi); ++p)
2006         {
2007             ir_value *v = instr->phi[p].value;
2008             ir_block *b = instr->phi[p].from;
2009
2010             if (v->store == store_value &&
2011                 vec_size(v->reads) == 1 &&
2012                 vec_size(v->writes) == 1)
2013             {
2014                 /* replace the value */
2015                 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2016                     return false;
2017             }
2018             else
2019             {
2020                 /* force a move instruction */
2021                 ir_instr *prevjump = vec_last(b->instr);
2022                 vec_pop(b->instr);
2023                 b->final = false;
2024                 instr->_ops[0]->store = store_global;
2025                 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2026                     return false;
2027                 instr->_ops[0]->store = store_value;
2028                 vec_push(b->instr, prevjump);
2029                 b->final = true;
2030             }
2031         }
2032         ir_instr_delete(instr);
2033     }
2034     return true;
2035 }
2036
2037 /***********************************************************************
2038  *IR Temp allocation code
2039  * Propagating value life ranges by walking through the function backwards
2040  * until no more changes are made.
2041  * In theory this should happen once more than once for every nested loop
2042  * level.
2043  * Though this implementation might run an additional time for if nests.
2044  */
2045
2046 /* Enumerate instructions used by value's life-ranges
2047  */
2048 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2049 {
2050     size_t i;
2051     size_t eid = *_eid;
2052     for (i = 0; i < vec_size(self->instr); ++i)
2053     {
2054         self->instr[i]->eid = eid++;
2055     }
2056     *_eid = eid;
2057 }
2058
2059 /* Enumerate blocks and instructions.
2060  * The block-enumeration is unordered!
2061  * We do not really use the block enumreation, however
2062  * the instruction enumeration is important for life-ranges.
2063  */
2064 void ir_function_enumerate(ir_function *self)
2065 {
2066     size_t i;
2067     size_t instruction_id = 0;
2068     for (i = 0; i < vec_size(self->blocks); ++i)
2069     {
2070         /* each block now gets an additional "entry" instruction id
2071          * we can use to avoid point-life issues
2072          */
2073         self->blocks[i]->entry_id = instruction_id;
2074         ++instruction_id;
2075
2076         self->blocks[i]->eid = i;
2077         ir_block_enumerate(self->blocks[i], &instruction_id);
2078     }
2079 }
2080
2081 /* Local-value allocator
2082  * After finishing creating the liferange of all values used in a function
2083  * we can allocate their global-positions.
2084  * This is the counterpart to register-allocation in register machines.
2085  */
2086 typedef struct {
2087     ir_value **locals;
2088     size_t    *sizes;
2089     size_t    *positions;
2090     bool      *unique;
2091 } function_allocator;
2092
2093 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2094 {
2095     ir_value *slot;
2096     size_t vsize = ir_value_sizeof(var);
2097
2098     var->code.local = vec_size(alloc->locals);
2099
2100     slot = ir_value_var("reg", store_global, var->vtype);
2101     if (!slot)
2102         return false;
2103
2104     if (!ir_value_life_merge_into(slot, var))
2105         goto localerror;
2106
2107     vec_push(alloc->locals, slot);
2108     vec_push(alloc->sizes, vsize);
2109     vec_push(alloc->unique, var->unique_life);
2110
2111     return true;
2112
2113 localerror:
2114     ir_value_delete(slot);
2115     return false;
2116 }
2117
2118 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2119 {
2120     size_t a;
2121     ir_value *slot;
2122
2123     if (v->unique_life)
2124         return function_allocator_alloc(alloc, v);
2125
2126     for (a = 0; a < vec_size(alloc->locals); ++a)
2127     {
2128         /* if it's reserved for a unique liferange: skip */
2129         if (alloc->unique[a])
2130             continue;
2131
2132         slot = alloc->locals[a];
2133
2134         /* never resize parameters
2135          * will be required later when overlapping temps + locals
2136          */
2137         if (a < vec_size(self->params) &&
2138             alloc->sizes[a] < ir_value_sizeof(v))
2139         {
2140             continue;
2141         }
2142
2143         if (ir_values_overlap(v, slot))
2144             continue;
2145
2146         if (!ir_value_life_merge_into(slot, v))
2147             return false;
2148
2149         /* adjust size for this slot */
2150         if (alloc->sizes[a] < ir_value_sizeof(v))
2151             alloc->sizes[a] = ir_value_sizeof(v);
2152
2153         v->code.local = a;
2154         return true;
2155     }
2156     if (a >= vec_size(alloc->locals)) {
2157         if (!function_allocator_alloc(alloc, v))
2158             return false;
2159     }
2160     return true;
2161 }
2162
2163 bool ir_function_allocate_locals(ir_function *self)
2164 {
2165     size_t i;
2166     bool   retval = true;
2167     size_t pos;
2168     bool   opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2169
2170     ir_value *v;
2171
2172     function_allocator lockalloc, globalloc;
2173
2174     if (!vec_size(self->locals) && !vec_size(self->values))
2175         return true;
2176
2177     globalloc.locals    = NULL;
2178     globalloc.sizes     = NULL;
2179     globalloc.positions = NULL;
2180     globalloc.unique    = NULL;
2181     lockalloc.locals    = NULL;
2182     lockalloc.sizes     = NULL;
2183     lockalloc.positions = NULL;
2184     lockalloc.unique    = NULL;
2185
2186     for (i = 0; i < vec_size(self->locals); ++i)
2187     {
2188         v = self->locals[i];
2189         if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2190             v->locked      = true;
2191             v->unique_life = true;
2192         }
2193         else if (i >= vec_size(self->params))
2194             break;
2195         else
2196             v->locked = true; /* lock parameters locals */
2197         if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2198             goto error;
2199     }
2200     for (; i < vec_size(self->locals); ++i)
2201     {
2202         v = self->locals[i];
2203         if (!vec_size(v->life))
2204             continue;
2205         if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2206             goto error;
2207     }
2208
2209     /* Allocate a slot for any value that still exists */
2210     for (i = 0; i < vec_size(self->values); ++i)
2211     {
2212         v = self->values[i];
2213
2214         if (!vec_size(v->life))
2215             continue;
2216
2217         /* CALL optimization:
2218          * If the value is a parameter-temp: 1 write, 1 read from a CALL
2219          * and it's not "locked", write it to the OFS_PARM directly.
2220          */
2221         if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2222             if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2223                 (v->reads[0]->opcode == VINSTR_NRCALL ||
2224                  (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2225                 )
2226                )
2227             {
2228                 size_t    param;
2229                 ir_instr *call = v->reads[0];
2230                 if (!vec_ir_value_find(call->params, v, &param)) {
2231                     irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2232                     goto error;
2233                 }
2234                 ++opts_optimizationcount[OPTIM_CALL_STORES];
2235                 v->callparam = true;
2236                 if (param < 8)
2237                     ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2238                 else {
2239                     size_t nprotos = vec_size(self->owner->extparam_protos);
2240                     ir_value *ep;
2241                     param -= 8;
2242                     if (nprotos > param)
2243                         ep = self->owner->extparam_protos[param];
2244                     else
2245                     {
2246                         ep = ir_gen_extparam_proto(self->owner);
2247                         while (++nprotos <= param)
2248                             ep = ir_gen_extparam_proto(self->owner);
2249                     }
2250                     ir_instr_op(v->writes[0], 0, ep, true);
2251                     call->params[param+8] = ep;
2252                 }
2253                 continue;
2254             }
2255             if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2256             {
2257                 v->store = store_return;
2258                 if (v->members[0]) v->members[0]->store = store_return;
2259                 if (v->members[1]) v->members[1]->store = store_return;
2260                 if (v->members[2]) v->members[2]->store = store_return;
2261                 ++opts_optimizationcount[OPTIM_CALL_STORES];
2262                 continue;
2263             }
2264         }
2265
2266         if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2267             goto error;
2268     }
2269
2270     if (!lockalloc.sizes && !globalloc.sizes) {
2271         goto cleanup;
2272     }
2273     vec_push(lockalloc.positions, 0);
2274     vec_push(globalloc.positions, 0);
2275
2276     /* Adjust slot positions based on sizes */
2277     if (lockalloc.sizes) {
2278         pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2279         for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2280         {
2281             pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2282             vec_push(lockalloc.positions, pos);
2283         }
2284         self->allocated_locals = pos + vec_last(lockalloc.sizes);
2285     }
2286     if (globalloc.sizes) {
2287         pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2288         for (i = 1; i < vec_size(globalloc.sizes); ++i)
2289         {
2290             pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2291             vec_push(globalloc.positions, pos);
2292         }
2293         self->globaltemps = pos + vec_last(globalloc.sizes);
2294     }
2295
2296     /* Locals need to know their new position */
2297     for (i = 0; i < vec_size(self->locals); ++i) {
2298         v = self->locals[i];
2299         if (v->locked || !opt_gt)
2300             v->code.local = lockalloc.positions[v->code.local];
2301         else
2302             v->code.local = globalloc.positions[v->code.local];
2303     }
2304     /* Take over the actual slot positions on values */
2305     for (i = 0; i < vec_size(self->values); ++i) {
2306         v = self->values[i];
2307         if (v->locked || !opt_gt)
2308             v->code.local = lockalloc.positions[v->code.local];
2309         else
2310             v->code.local = globalloc.positions[v->code.local];
2311     }
2312
2313     goto cleanup;
2314
2315 error:
2316     retval = false;
2317 cleanup:
2318     for (i = 0; i < vec_size(lockalloc.locals); ++i)
2319         ir_value_delete(lockalloc.locals[i]);
2320     for (i = 0; i < vec_size(globalloc.locals); ++i)
2321         ir_value_delete(globalloc.locals[i]);
2322     vec_free(globalloc.unique);
2323     vec_free(globalloc.locals);
2324     vec_free(globalloc.sizes);
2325     vec_free(globalloc.positions);
2326     vec_free(lockalloc.unique);
2327     vec_free(lockalloc.locals);
2328     vec_free(lockalloc.sizes);
2329     vec_free(lockalloc.positions);
2330     return retval;
2331 }
2332
2333 /* Get information about which operand
2334  * is read from, or written to.
2335  */
2336 static void ir_op_read_write(int op, size_t *read, size_t *write)
2337 {
2338     switch (op)
2339     {
2340     case VINSTR_JUMP:
2341     case INSTR_GOTO:
2342         *write = 0;
2343         *read = 0;
2344         break;
2345     case INSTR_IF:
2346     case INSTR_IFNOT:
2347 #if 0
2348     case INSTR_IF_S:
2349     case INSTR_IFNOT_S:
2350 #endif
2351     case INSTR_RETURN:
2352     case VINSTR_COND:
2353         *write = 0;
2354         *read = 1;
2355         break;
2356     case INSTR_STOREP_F:
2357     case INSTR_STOREP_V:
2358     case INSTR_STOREP_S:
2359     case INSTR_STOREP_ENT:
2360     case INSTR_STOREP_FLD:
2361     case INSTR_STOREP_FNC:
2362         *write = 0;
2363         *read  = 7;
2364         break;
2365     default:
2366         *write = 1;
2367         *read = 6;
2368         break;
2369     };
2370 }
2371
2372 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2373 {
2374     size_t       i;
2375     const size_t vs = vec_size(self->living);
2376     bool         changed = false;
2377     for (i = 0; i != vs; ++i)
2378     {
2379         if (ir_value_life_merge(self->living[i], eid))
2380             changed = true;
2381     }
2382     return changed;
2383 }
2384
2385 static bool ir_block_living_lock(ir_block *self)
2386 {
2387     size_t i;
2388     bool changed = false;
2389     for (i = 0; i != vec_size(self->living); ++i)
2390     {
2391         if (!self->living[i]->locked) {
2392             self->living[i]->locked = true;
2393             changed = true;
2394         }
2395     }
2396     return changed;
2397 }
2398
2399 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2400 {
2401     ir_instr *instr;
2402     ir_value *value;
2403     size_t i, o, p, mem, cnt;
2404     /* bitmasks which operands are read from or written to */
2405     size_t read, write;
2406     char dbg_ind[16];
2407     dbg_ind[0] = '#';
2408     dbg_ind[1] = '0';
2409     (void)dbg_ind;
2410
2411     vec_free(self->living);
2412
2413     p = vec_size(self->exits);
2414     for (i = 0; i < p; ++i) {
2415         ir_block *prev = self->exits[i];
2416         cnt = vec_size(prev->living);
2417         for (o = 0; o < cnt; ++o) {
2418             if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2419                 vec_push(self->living, prev->living[o]);
2420         }
2421     }
2422
2423     i = vec_size(self->instr);
2424     while (i)
2425     { --i;
2426         instr = self->instr[i];
2427
2428         /* See which operands are read and write operands */
2429         ir_op_read_write(instr->opcode, &read, &write);
2430
2431         /* Go through the 3 main operands
2432          * writes first, then reads
2433          */
2434         for (o = 0; o < 3; ++o)
2435         {
2436             if (!instr->_ops[o]) /* no such operand */
2437                 continue;
2438
2439             value = instr->_ops[o];
2440
2441             /* We only care about locals */
2442             /* we also calculate parameter liferanges so that locals
2443              * can take up parameter slots */
2444             if (value->store != store_value &&
2445                 value->store != store_local &&
2446                 value->store != store_param)
2447                 continue;
2448
2449             /* write operands */
2450             /* When we write to a local, we consider it "dead" for the
2451              * remaining upper part of the function, since in SSA a value
2452              * can only be written once (== created)
2453              */
2454             if (write & (1<<o))
2455             {
2456                 size_t idx;
2457                 bool in_living = vec_ir_value_find(self->living, value, &idx);
2458                 if (!in_living)
2459                 {
2460                     /* If the value isn't alive it hasn't been read before... */
2461                     /* TODO: See if the warning can be emitted during parsing or AST processing
2462                      * otherwise have warning printed here.
2463                      * IF printing a warning here: include filecontext_t,
2464                      * and make sure it's only printed once
2465                      * since this function is run multiple times.
2466                      */
2467                     /* con_err( "Value only written %s\n", value->name); */
2468                     if (ir_value_life_merge(value, instr->eid))
2469                         *changed = true;
2470                 } else {
2471                     /* since 'living' won't contain it
2472                      * anymore, merge the value, since
2473                      * (A) doesn't.
2474                      */
2475                     if (ir_value_life_merge(value, instr->eid))
2476                         *changed = true;
2477                     /* Then remove */
2478                     vec_remove(self->living, idx, 1);
2479                 }
2480                 /* Removing a vector removes all members */
2481                 for (mem = 0; mem < 3; ++mem) {
2482                     if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2483                         if (ir_value_life_merge(value->members[mem], instr->eid))
2484                             *changed = true;
2485                         vec_remove(self->living, idx, 1);
2486                     }
2487                 }
2488                 /* Removing the last member removes the vector */
2489                 if (value->memberof) {
2490                     value = value->memberof;
2491                     for (mem = 0; mem < 3; ++mem) {
2492                         if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2493                             break;
2494                     }
2495                     if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2496                         if (ir_value_life_merge(value, instr->eid))
2497                             *changed = true;
2498                         vec_remove(self->living, idx, 1);
2499                     }
2500                 }
2501             }
2502         }
2503
2504         if (instr->opcode == INSTR_MUL_VF)
2505         {
2506             value = instr->_ops[2];
2507             /* the float source will get an additional lifetime */
2508             if (ir_value_life_merge(value, instr->eid+1))
2509                 *changed = true;
2510             if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2511                 *changed = true;
2512         }
2513         else if (instr->opcode == INSTR_MUL_FV || instr->opcode == INSTR_LOAD_V)
2514         {
2515             value = instr->_ops[1];
2516             /* the float source will get an additional lifetime */
2517             if (ir_value_life_merge(value, instr->eid+1))
2518                 *changed = true;
2519             if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2520                 *changed = true;
2521         }
2522
2523         for (o = 0; o < 3; ++o)
2524         {
2525             if (!instr->_ops[o]) /* no such operand */
2526                 continue;
2527
2528             value = instr->_ops[o];
2529
2530             /* We only care about locals */
2531             /* we also calculate parameter liferanges so that locals
2532              * can take up parameter slots */
2533             if (value->store != store_value &&
2534                 value->store != store_local &&
2535                 value->store != store_param)
2536                 continue;
2537
2538             /* read operands */
2539             if (read & (1<<o))
2540             {
2541                 if (!vec_ir_value_find(self->living, value, NULL))
2542                     vec_push(self->living, value);
2543                 /* reading adds the full vector */
2544                 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2545                     vec_push(self->living, value->memberof);
2546                 for (mem = 0; mem < 3; ++mem) {
2547                     if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2548                         vec_push(self->living, value->members[mem]);
2549                 }
2550             }
2551         }
2552         /* PHI operands are always read operands */
2553         for (p = 0; p < vec_size(instr->phi); ++p)
2554         {
2555             value = instr->phi[p].value;
2556             if (!vec_ir_value_find(self->living, value, NULL))
2557                 vec_push(self->living, value);
2558             /* reading adds the full vector */
2559             if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2560                 vec_push(self->living, value->memberof);
2561             for (mem = 0; mem < 3; ++mem) {
2562                 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2563                     vec_push(self->living, value->members[mem]);
2564             }
2565         }
2566
2567         /* on a call, all these values must be "locked" */
2568         if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2569             if (ir_block_living_lock(self))
2570                 *changed = true;
2571         }
2572         /* call params are read operands too */
2573         for (p = 0; p < vec_size(instr->params); ++p)
2574         {
2575             value = instr->params[p];
2576             if (!vec_ir_value_find(self->living, value, NULL))
2577                 vec_push(self->living, value);
2578             /* reading adds the full vector */
2579             if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2580                 vec_push(self->living, value->memberof);
2581             for (mem = 0; mem < 3; ++mem) {
2582                 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2583                     vec_push(self->living, value->members[mem]);
2584             }
2585         }
2586
2587         /* (A) */
2588         if (ir_block_living_add_instr(self, instr->eid))
2589             *changed = true;
2590     }
2591     /* the "entry" instruction ID */
2592     if (ir_block_living_add_instr(self, self->entry_id))
2593         *changed = true;
2594
2595     return true;
2596 }
2597
2598 bool ir_function_calculate_liferanges(ir_function *self)
2599 {
2600     size_t i, s;
2601     bool changed;
2602
2603     /* parameters live at 0 */
2604     for (i = 0; i < vec_size(self->params); ++i)
2605         if (!ir_value_life_merge(self->locals[i], 0))
2606             compile_error(self->context, "internal error: failed value-life merging");
2607
2608     do {
2609         self->run_id++;
2610         changed = false;
2611         i = vec_size(self->blocks);
2612         while (i--) {
2613             ir_block_life_propagate(self->blocks[i], &changed);
2614         }
2615     } while (changed);
2616
2617     if (vec_size(self->blocks)) {
2618         ir_block *block = self->blocks[0];
2619         for (i = 0; i < vec_size(block->living); ++i) {
2620             ir_value *v = block->living[i];
2621             if (v->store != store_local)
2622                 continue;
2623             if (v->vtype == TYPE_VECTOR)
2624                 continue;
2625             self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2626             /* find the instruction reading from it */
2627             for (s = 0; s < vec_size(v->reads); ++s) {
2628                 if (v->reads[s]->eid == v->life[0].end)
2629                     break;
2630             }
2631             if (s < vec_size(v->reads)) {
2632                 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2633                               "variable `%s` may be used uninitialized in this function\n"
2634                               " -> %s:%i",
2635                               v->name,
2636                               v->reads[s]->context.file, v->reads[s]->context.line)
2637                    )
2638                 {
2639                     return false;
2640                 }
2641                 continue;
2642             }
2643             if (v->memberof) {
2644                 ir_value *vec = v->memberof;
2645                 for (s = 0; s < vec_size(vec->reads); ++s) {
2646                     if (vec->reads[s]->eid == v->life[0].end)
2647                         break;
2648                 }
2649                 if (s < vec_size(vec->reads)) {
2650                     if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2651                                   "variable `%s` may be used uninitialized in this function\n"
2652                                   " -> %s:%i",
2653                                   v->name,
2654                                   vec->reads[s]->context.file, vec->reads[s]->context.line)
2655                        )
2656                     {
2657                         return false;
2658                     }
2659                     continue;
2660                 }
2661             }
2662             if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2663                           "variable `%s` may be used uninitialized in this function", v->name))
2664             {
2665                 return false;
2666             }
2667         }
2668     }
2669     return true;
2670 }
2671
2672 /***********************************************************************
2673  *IR Code-Generation
2674  *
2675  * Since the IR has the convention of putting 'write' operands
2676  * at the beginning, we have to rotate the operands of instructions
2677  * properly in order to generate valid QCVM code.
2678  *
2679  * Having destinations at a fixed position is more convenient. In QC
2680  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
2681  * read from from OPA,  and store to OPB rather than OPC.   Which is
2682  * partially the reason why the implementation of these instructions
2683  * in darkplaces has been delayed for so long.
2684  *
2685  * Breaking conventions is annoying...
2686  */
2687 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2688
2689 static bool gen_global_field(code_t *code, ir_value *global)
2690 {
2691     if (global->hasvalue)
2692     {
2693         ir_value *fld = global->constval.vpointer;
2694         if (!fld) {
2695             irerror(global->context, "Invalid field constant with no field: %s", global->name);
2696             return false;
2697         }
2698
2699         /* copy the field's value */
2700         ir_value_code_setaddr(global, vec_size(code->globals));
2701         vec_push(code->globals, fld->code.fieldaddr);
2702         if (global->fieldtype == TYPE_VECTOR) {
2703             vec_push(code->globals, fld->code.fieldaddr+1);
2704             vec_push(code->globals, fld->code.fieldaddr+2);
2705         }
2706     }
2707     else
2708     {
2709         ir_value_code_setaddr(global, vec_size(code->globals));
2710         vec_push(code->globals, 0);
2711         if (global->fieldtype == TYPE_VECTOR) {
2712             vec_push(code->globals, 0);
2713             vec_push(code->globals, 0);
2714         }
2715     }
2716     if (global->code.globaladdr < 0)
2717         return false;
2718     return true;
2719 }
2720
2721 static bool gen_global_pointer(code_t *code, ir_value *global)
2722 {
2723     if (global->hasvalue)
2724     {
2725         ir_value *target = global->constval.vpointer;
2726         if (!target) {
2727             irerror(global->context, "Invalid pointer constant: %s", global->name);
2728             /* NULL pointers are pointing to the NULL constant, which also
2729              * sits at address 0, but still has an ir_value for itself.
2730              */
2731             return false;
2732         }
2733
2734         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2735          * void() foo; <- proto
2736          * void() *fooptr = &foo;
2737          * void() foo = { code }
2738          */
2739         if (!target->code.globaladdr) {
2740             /* FIXME: Check for the constant nullptr ir_value!
2741              * because then code.globaladdr being 0 is valid.
2742              */
2743             irerror(global->context, "FIXME: Relocation support");
2744             return false;
2745         }
2746
2747         ir_value_code_setaddr(global, vec_size(code->globals));
2748         vec_push(code->globals, target->code.globaladdr);
2749     }
2750     else
2751     {
2752         ir_value_code_setaddr(global, vec_size(code->globals));
2753         vec_push(code->globals, 0);
2754     }
2755     if (global->code.globaladdr < 0)
2756         return false;
2757     return true;
2758 }
2759
2760 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2761 {
2762     prog_section_statement_t stmt;
2763     ir_instr *instr;
2764     ir_block *target;
2765     ir_block *ontrue;
2766     ir_block *onfalse;
2767     size_t    stidx;
2768     size_t    i;
2769
2770     block->generated = true;
2771     block->code_start = vec_size(code->statements);
2772     for (i = 0; i < vec_size(block->instr); ++i)
2773     {
2774         instr = block->instr[i];
2775
2776         if (instr->opcode == VINSTR_PHI) {
2777             irerror(block->context, "cannot generate virtual instruction (phi)");
2778             return false;
2779         }
2780
2781         if (instr->opcode == VINSTR_JUMP) {
2782             target = instr->bops[0];
2783             /* for uncoditional jumps, if the target hasn't been generated
2784              * yet, we generate them right here.
2785              */
2786             if (!target->generated)
2787                 return gen_blocks_recursive(code, func, target);
2788
2789             /* otherwise we generate a jump instruction */
2790             stmt.opcode = INSTR_GOTO;
2791             stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2792             stmt.o2.s1 = 0;
2793             stmt.o3.s1 = 0;
2794             if (stmt.o1.s1 != 1)
2795                 code_push_statement(code, &stmt, instr->context.line);
2796
2797             /* no further instructions can be in this block */
2798             return true;
2799         }
2800
2801         if (instr->opcode == VINSTR_COND) {
2802             ontrue  = instr->bops[0];
2803             onfalse = instr->bops[1];
2804             /* TODO: have the AST signal which block should
2805              * come first: eg. optimize IFs without ELSE...
2806              */
2807
2808             stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2809             stmt.o2.u1 = 0;
2810             stmt.o3.s1 = 0;
2811
2812             if (ontrue->generated) {
2813                 stmt.opcode = INSTR_IF;
2814                 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
2815                 if (stmt.o2.s1 != 1)
2816                     code_push_statement(code, &stmt, instr->context.line);
2817             }
2818             if (onfalse->generated) {
2819                 stmt.opcode = INSTR_IFNOT;
2820                 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
2821                 if (stmt.o2.s1 != 1)
2822                     code_push_statement(code, &stmt, instr->context.line);
2823             }
2824             if (!ontrue->generated) {
2825                 if (onfalse->generated)
2826                     return gen_blocks_recursive(code, func, ontrue);
2827             }
2828             if (!onfalse->generated) {
2829                 if (ontrue->generated)
2830                     return gen_blocks_recursive(code, func, onfalse);
2831             }
2832             /* neither ontrue nor onfalse exist */
2833             stmt.opcode = INSTR_IFNOT;
2834             if (!instr->likely) {
2835                 /* Honor the likelyhood hint */
2836                 ir_block *tmp = onfalse;
2837                 stmt.opcode = INSTR_IF;
2838                 onfalse = ontrue;
2839                 ontrue = tmp;
2840             }
2841             stidx = vec_size(code->statements);
2842             code_push_statement(code, &stmt, instr->context.line);
2843             /* on false we jump, so add ontrue-path */
2844             if (!gen_blocks_recursive(code, func, ontrue))
2845                 return false;
2846             /* fixup the jump address */
2847             code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
2848             /* generate onfalse path */
2849             if (onfalse->generated) {
2850                 /* fixup the jump address */
2851                 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2852                 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2853                     code->statements[stidx] = code->statements[stidx+1];
2854                     if (code->statements[stidx].o1.s1 < 0)
2855                         code->statements[stidx].o1.s1++;
2856                     code_pop_statement(code);
2857                 }
2858                 stmt.opcode = vec_last(code->statements).opcode;
2859                 if (stmt.opcode == INSTR_GOTO ||
2860                     stmt.opcode == INSTR_IF ||
2861                     stmt.opcode == INSTR_IFNOT ||
2862                     stmt.opcode == INSTR_RETURN ||
2863                     stmt.opcode == INSTR_DONE)
2864                 {
2865                     /* no use jumping from here */
2866                     return true;
2867                 }
2868                 /* may have been generated in the previous recursive call */
2869                 stmt.opcode = INSTR_GOTO;
2870                 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
2871                 stmt.o2.s1 = 0;
2872                 stmt.o3.s1 = 0;
2873                 if (stmt.o1.s1 != 1)
2874                     code_push_statement(code, &stmt, instr->context.line);
2875                 return true;
2876             }
2877             else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2878                 code->statements[stidx] = code->statements[stidx+1];
2879                 if (code->statements[stidx].o1.s1 < 0)
2880                     code->statements[stidx].o1.s1++;
2881                 code_pop_statement(code);
2882             }
2883             /* if not, generate now */
2884             return gen_blocks_recursive(code, func, onfalse);
2885         }
2886
2887         if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2888            || instr->opcode == VINSTR_NRCALL)
2889         {
2890             size_t p, first;
2891             ir_value *retvalue;
2892
2893             first = vec_size(instr->params);
2894             if (first > 8)
2895                 first = 8;
2896             for (p = 0; p < first; ++p)
2897             {
2898                 ir_value *param = instr->params[p];
2899                 if (param->callparam)
2900                     continue;
2901
2902                 stmt.opcode = INSTR_STORE_F;
2903                 stmt.o3.u1 = 0;
2904
2905                 if (param->vtype == TYPE_FIELD)
2906                     stmt.opcode = field_store_instr[param->fieldtype];
2907                 else if (param->vtype == TYPE_NIL)
2908                     stmt.opcode = INSTR_STORE_V;
2909                 else
2910                     stmt.opcode = type_store_instr[param->vtype];
2911                 stmt.o1.u1 = ir_value_code_addr(param);
2912                 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2913                 code_push_statement(code, &stmt, instr->context.line);
2914             }
2915             /* Now handle extparams */
2916             first = vec_size(instr->params);
2917             for (; p < first; ++p)
2918             {
2919                 ir_builder *ir = func->owner;
2920                 ir_value *param = instr->params[p];
2921                 ir_value *targetparam;
2922
2923                 if (param->callparam)
2924                     continue;
2925
2926                 if (p-8 >= vec_size(ir->extparams))
2927                     ir_gen_extparam(ir);
2928
2929                 targetparam = ir->extparams[p-8];
2930
2931                 stmt.opcode = INSTR_STORE_F;
2932                 stmt.o3.u1 = 0;
2933
2934                 if (param->vtype == TYPE_FIELD)
2935                     stmt.opcode = field_store_instr[param->fieldtype];
2936                 else if (param->vtype == TYPE_NIL)
2937                     stmt.opcode = INSTR_STORE_V;
2938                 else
2939                     stmt.opcode = type_store_instr[param->vtype];
2940                 stmt.o1.u1 = ir_value_code_addr(param);
2941                 stmt.o2.u1 = ir_value_code_addr(targetparam);
2942                 code_push_statement(code, &stmt, instr->context.line);
2943             }
2944
2945             stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2946             if (stmt.opcode > INSTR_CALL8)
2947                 stmt.opcode = INSTR_CALL8;
2948             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2949             stmt.o2.u1 = 0;
2950             stmt.o3.u1 = 0;
2951             code_push_statement(code, &stmt, instr->context.line);
2952
2953             retvalue = instr->_ops[0];
2954             if (retvalue && retvalue->store != store_return &&
2955                 (retvalue->store == store_global || vec_size(retvalue->life)))
2956             {
2957                 /* not to be kept in OFS_RETURN */
2958                 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2959                     stmt.opcode = field_store_instr[retvalue->fieldtype];
2960                 else
2961                     stmt.opcode = type_store_instr[retvalue->vtype];
2962                 stmt.o1.u1 = OFS_RETURN;
2963                 stmt.o2.u1 = ir_value_code_addr(retvalue);
2964                 stmt.o3.u1 = 0;
2965                 code_push_statement(code, &stmt, instr->context.line);
2966             }
2967             continue;
2968         }
2969
2970         if (instr->opcode == INSTR_STATE) {
2971             irerror(block->context, "TODO: state instruction");
2972             return false;
2973         }
2974
2975         stmt.opcode = instr->opcode;
2976         stmt.o1.u1 = 0;
2977         stmt.o2.u1 = 0;
2978         stmt.o3.u1 = 0;
2979
2980         /* This is the general order of operands */
2981         if (instr->_ops[0])
2982             stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2983
2984         if (instr->_ops[1])
2985             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2986
2987         if (instr->_ops[2])
2988             stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2989
2990         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2991         {
2992             stmt.o1.u1 = stmt.o3.u1;
2993             stmt.o3.u1 = 0;
2994         }
2995         else if ((stmt.opcode >= INSTR_STORE_F &&
2996                   stmt.opcode <= INSTR_STORE_FNC) ||
2997                  (stmt.opcode >= INSTR_STOREP_F &&
2998                   stmt.opcode <= INSTR_STOREP_FNC))
2999         {
3000             /* 2-operand instructions with A -> B */
3001             stmt.o2.u1 = stmt.o3.u1;
3002             stmt.o3.u1 = 0;
3003
3004             /* tiny optimization, don't output
3005              * STORE a, a
3006              */
3007             if (stmt.o2.u1 == stmt.o1.u1 &&
3008                 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
3009             {
3010                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
3011                 continue;
3012             }
3013         }
3014
3015         code_push_statement(code, &stmt, instr->context.line);
3016     }
3017     return true;
3018 }
3019
3020 static bool gen_function_code(code_t *code, ir_function *self)
3021 {
3022     ir_block *block;
3023     prog_section_statement_t stmt, *retst;
3024
3025     /* Starting from entry point, we generate blocks "as they come"
3026      * for now. Dead blocks will not be translated obviously.
3027      */
3028     if (!vec_size(self->blocks)) {
3029         irerror(self->context, "Function '%s' declared without body.", self->name);
3030         return false;
3031     }
3032
3033     block = self->blocks[0];
3034     if (block->generated)
3035         return true;
3036
3037     if (!gen_blocks_recursive(code, self, block)) {
3038         irerror(self->context, "failed to generate blocks for '%s'", self->name);
3039         return false;
3040     }
3041
3042     /* code_write and qcvm -disasm need to know that the function ends here */
3043     retst = &vec_last(code->statements);
3044     if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3045         self->outtype == TYPE_VOID &&
3046         retst->opcode == INSTR_RETURN &&
3047         !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3048     {
3049         retst->opcode = INSTR_DONE;
3050         ++opts_optimizationcount[OPTIM_VOID_RETURN];
3051     } else {
3052         stmt.opcode = INSTR_DONE;
3053         stmt.o1.u1 = 0;
3054         stmt.o2.u1 = 0;
3055         stmt.o3.u1 = 0;
3056         code_push_statement(code, &stmt, vec_last(code->linenums));
3057     }
3058     return true;
3059 }
3060
3061 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3062 {
3063     /* NOTE: filename pointers are copied, we never strdup them,
3064      * thus we can use pointer-comparison to find the string.
3065      */
3066     size_t i;
3067     qcint_t  str;
3068
3069     for (i = 0; i < vec_size(ir->filenames); ++i) {
3070         if (ir->filenames[i] == filename)
3071             return ir->filestrings[i];
3072     }
3073
3074     str = code_genstring(ir->code, filename);
3075     vec_push(ir->filenames, filename);
3076     vec_push(ir->filestrings, str);
3077     return str;
3078 }
3079
3080 static bool gen_global_function(ir_builder *ir, ir_value *global)
3081 {
3082     prog_section_function_t fun;
3083     ir_function            *irfun;
3084
3085     size_t i;
3086
3087     if (!global->hasvalue || (!global->constval.vfunc))
3088     {
3089         irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3090         return false;
3091     }
3092
3093     irfun = global->constval.vfunc;
3094
3095     fun.name    = global->code.name;
3096     fun.file    = ir_builder_filestring(ir, global->context.file);
3097     fun.profile = 0; /* always 0 */
3098     fun.nargs   = vec_size(irfun->params);
3099     if (fun.nargs > 8)
3100         fun.nargs = 8;
3101
3102     for (i = 0;i < 8; ++i) {
3103         if ((int32_t)i >= fun.nargs)
3104             fun.argsize[i] = 0;
3105         else
3106             fun.argsize[i] = type_sizeof_[irfun->params[i]];
3107     }
3108
3109     fun.firstlocal = 0;
3110     fun.locals     = irfun->allocated_locals;
3111
3112     if (irfun->builtin)
3113         fun.entry = irfun->builtin+1;
3114     else {
3115         irfun->code_function_def = vec_size(ir->code->functions);
3116         fun.entry                = vec_size(ir->code->statements);
3117     }
3118
3119     vec_push(ir->code->functions, fun);
3120     return true;
3121 }
3122
3123 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3124 {
3125     ir_value *global;
3126     char      name[128];
3127
3128     util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3129     global = ir_value_var(name, store_global, TYPE_VECTOR);
3130
3131     vec_push(ir->extparam_protos, global);
3132     return global;
3133 }
3134
3135 static void ir_gen_extparam(ir_builder *ir)
3136 {
3137     prog_section_def_t def;
3138     ir_value          *global;
3139
3140     if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3141         global = ir_gen_extparam_proto(ir);
3142     else
3143         global = ir->extparam_protos[vec_size(ir->extparams)];
3144
3145     def.name   = code_genstring(ir->code, global->name);
3146     def.type   = TYPE_VECTOR;
3147     def.offset = vec_size(ir->code->globals);
3148
3149     vec_push(ir->code->defs, def);
3150
3151     ir_value_code_setaddr(global, def.offset);
3152
3153     vec_push(ir->code->globals, 0);
3154     vec_push(ir->code->globals, 0);
3155     vec_push(ir->code->globals, 0);
3156
3157     vec_push(ir->extparams, global);
3158 }
3159
3160 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3161 {
3162     size_t i, ext, numparams;
3163
3164     ir_builder *ir = self->owner;
3165     ir_value   *ep;
3166     prog_section_statement_t stmt;
3167
3168     numparams = vec_size(self->params);
3169     if (!numparams)
3170         return true;
3171
3172     stmt.opcode = INSTR_STORE_F;
3173     stmt.o3.s1 = 0;
3174     for (i = 8; i < numparams; ++i) {
3175         ext = i - 8;
3176         if (ext >= vec_size(ir->extparams))
3177             ir_gen_extparam(ir);
3178
3179         ep = ir->extparams[ext];
3180
3181         stmt.opcode = type_store_instr[self->locals[i]->vtype];
3182         if (self->locals[i]->vtype == TYPE_FIELD &&
3183             self->locals[i]->fieldtype == TYPE_VECTOR)
3184         {
3185             stmt.opcode = INSTR_STORE_V;
3186         }
3187         stmt.o1.u1 = ir_value_code_addr(ep);
3188         stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3189         code_push_statement(code, &stmt, self->context.line);
3190     }
3191
3192     return true;
3193 }
3194
3195 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3196 {
3197     size_t i, ext, numparams, maxparams;
3198
3199     ir_builder *ir = self->owner;
3200     ir_value   *ep;
3201     prog_section_statement_t stmt;
3202
3203     numparams = vec_size(self->params);
3204     if (!numparams)
3205         return true;
3206
3207     stmt.opcode = INSTR_STORE_V;
3208     stmt.o3.s1 = 0;
3209     maxparams = numparams + self->max_varargs;
3210     for (i = numparams; i < maxparams; ++i) {
3211         if (i < 8) {
3212             stmt.o1.u1 = OFS_PARM0 + 3*i;
3213             stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3214             code_push_statement(code, &stmt, self->context.line);
3215             continue;
3216         }
3217         ext = i - 8;
3218         while (ext >= vec_size(ir->extparams))
3219             ir_gen_extparam(ir);
3220
3221         ep = ir->extparams[ext];
3222
3223         stmt.o1.u1 = ir_value_code_addr(ep);
3224         stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3225         code_push_statement(code, &stmt, self->context.line);
3226     }
3227
3228     return true;
3229 }
3230
3231 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3232 {
3233     prog_section_function_t *def;
3234     ir_function             *irfun;
3235     size_t                   i;
3236     uint32_t                 firstlocal, firstglobal;
3237
3238     irfun = global->constval.vfunc;
3239     def   = ir->code->functions + irfun->code_function_def;
3240
3241     if (OPTS_OPTION_BOOL(OPTION_G) ||
3242         !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS)        ||
3243         (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3244     {
3245         firstlocal = def->firstlocal = vec_size(ir->code->globals);
3246     } else {
3247         firstlocal = def->firstlocal = ir->first_common_local;
3248         ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3249     }
3250
3251     firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3252
3253     for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3254         vec_push(ir->code->globals, 0);
3255     for (i = 0; i < vec_size(irfun->locals); ++i) {
3256         ir_value *v = irfun->locals[i];
3257         if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3258             ir_value_code_setaddr(v, firstlocal + v->code.local);
3259             if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3260                 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3261                 return false;
3262             }
3263         }
3264         else
3265             ir_value_code_setaddr(v, firstglobal + v->code.local);
3266     }
3267     for (i = 0; i < vec_size(irfun->values); ++i)
3268     {
3269         ir_value *v = irfun->values[i];
3270         if (v->callparam)
3271             continue;
3272         if (v->locked)
3273             ir_value_code_setaddr(v, firstlocal + v->code.local);
3274         else
3275             ir_value_code_setaddr(v, firstglobal + v->code.local);
3276     }
3277     return true;
3278 }
3279
3280 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3281 {
3282     prog_section_function_t *fundef;
3283     ir_function             *irfun;
3284
3285     (void)ir;
3286
3287     irfun = global->constval.vfunc;
3288     if (!irfun) {
3289         if (global->cvq == CV_NONE) {
3290             irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3291                       "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3292         }
3293         /* this was a function pointer, don't generate code for those */
3294         return true;
3295     }
3296
3297     if (irfun->builtin)
3298         return true;
3299
3300     if (irfun->code_function_def < 0) {
3301         irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3302         return false;
3303     }
3304     fundef = &ir->code->functions[irfun->code_function_def];
3305
3306     fundef->entry = vec_size(ir->code->statements);
3307     if (!gen_function_locals(ir, global)) {
3308         irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3309         return false;
3310     }
3311     if (!gen_function_extparam_copy(ir->code, irfun)) {
3312         irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3313         return false;
3314     }
3315     if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3316         irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3317         return false;
3318     }
3319     if (!gen_function_code(ir->code, irfun)) {
3320         irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3321         return false;
3322     }
3323     return true;
3324 }
3325
3326 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3327 {
3328     char  *component;
3329     size_t len, i;
3330
3331     if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3332         return;
3333
3334     def.type = TYPE_FLOAT;
3335
3336     len = strlen(name);
3337
3338     component = (char*)mem_a(len+3);
3339     memcpy(component, name, len);
3340     len += 2;
3341     component[len-0] = 0;
3342     component[len-2] = '_';
3343
3344     component[len-1] = 'x';
3345
3346     for (i = 0; i < 3; ++i) {
3347         def.name = code_genstring(code, component);
3348         vec_push(code->defs, def);
3349         def.offset++;
3350         component[len-1]++;
3351     }
3352
3353     mem_d(component);
3354 }
3355
3356 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3357 {
3358     char  *component;
3359     size_t len, i;
3360
3361     if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3362         return;
3363
3364     fld.type = TYPE_FLOAT;
3365
3366     len = strlen(name);
3367
3368     component = (char*)mem_a(len+3);
3369     memcpy(component, name, len);
3370     len += 2;
3371     component[len-0] = 0;
3372     component[len-2] = '_';
3373
3374     component[len-1] = 'x';
3375
3376     for (i = 0; i < 3; ++i) {
3377         fld.name = code_genstring(code, component);
3378         vec_push(code->fields, fld);
3379         fld.offset++;
3380         component[len-1]++;
3381     }
3382
3383     mem_d(component);
3384 }
3385
3386 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3387 {
3388     size_t             i;
3389     int32_t           *iptr;
3390     prog_section_def_t def;
3391     bool               pushdef = opts.optimizeoff;
3392
3393     def.type   = global->vtype;
3394     def.offset = vec_size(self->code->globals);
3395     def.name   = 0;
3396     if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3397     {
3398         pushdef = true;
3399
3400         if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3401             !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3402             (global->name[0] == '#' || global->cvq == CV_CONST))
3403         {
3404             pushdef = false;
3405         }
3406
3407         if (pushdef) {
3408             if (global->name[0] == '#') {
3409                 if (!self->str_immediate)
3410                     self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3411                 def.name = global->code.name = self->str_immediate;
3412             }
3413             else
3414                 def.name = global->code.name = code_genstring(self->code, global->name);
3415         }
3416         else
3417             def.name   = 0;
3418         if (islocal) {
3419             def.offset = ir_value_code_addr(global);
3420             vec_push(self->code->defs, def);
3421             if (global->vtype == TYPE_VECTOR)
3422                 gen_vector_defs(self->code, def, global->name);
3423             else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3424                 gen_vector_defs(self->code, def, global->name);
3425             return true;
3426         }
3427     }
3428     if (islocal)
3429         return true;
3430
3431     switch (global->vtype)
3432     {
3433     case TYPE_VOID:
3434         if (!strcmp(global->name, "end_sys_globals")) {
3435             /* TODO: remember this point... all the defs before this one
3436              * should be checksummed and added to progdefs.h when we generate it.
3437              */
3438         }
3439         else if (!strcmp(global->name, "end_sys_fields")) {
3440             /* TODO: same as above but for entity-fields rather than globsl
3441              */
3442         }
3443         else
3444             irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3445                       global->name);
3446         /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3447          * the system fields actually go? Though the engine knows this anyway...
3448          * Maybe this could be an -foption
3449          * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3450          */
3451         ir_value_code_setaddr(global, vec_size(self->code->globals));
3452         vec_push(self->code->globals, 0);
3453         /* Add the def */
3454         if (pushdef) vec_push(self->code->defs, def);
3455         return true;
3456     case TYPE_POINTER:
3457         if (pushdef) vec_push(self->code->defs, def);
3458         return gen_global_pointer(self->code, global);
3459     case TYPE_FIELD:
3460         if (pushdef) {
3461             vec_push(self->code->defs, def);
3462             if (global->fieldtype == TYPE_VECTOR)
3463                 gen_vector_defs(self->code, def, global->name);
3464         }
3465         return gen_global_field(self->code, global);
3466     case TYPE_ENTITY:
3467         /* fall through */
3468     case TYPE_FLOAT:
3469     {
3470         ir_value_code_setaddr(global, vec_size(self->code->globals));
3471         if (global->hasvalue) {
3472             iptr = (int32_t*)&global->constval.ivec[0];
3473             vec_push(self->code->globals, *iptr);
3474         } else {
3475             vec_push(self->code->globals, 0);
3476         }
3477         if (!islocal && global->cvq != CV_CONST)
3478             def.type |= DEF_SAVEGLOBAL;
3479         if (pushdef) vec_push(self->code->defs, def);
3480
3481         return global->code.globaladdr >= 0;
3482     }
3483     case TYPE_STRING:
3484     {
3485         ir_value_code_setaddr(global, vec_size(self->code->globals));
3486         if (global->hasvalue) {
3487             uint32_t load = code_genstring(self->code, global->constval.vstring);
3488             vec_push(self->code->globals, load);
3489         } else {
3490             vec_push(self->code->globals, 0);
3491         }
3492         if (!islocal && global->cvq != CV_CONST)
3493             def.type |= DEF_SAVEGLOBAL;
3494         if (pushdef) vec_push(self->code->defs, def);
3495         return global->code.globaladdr >= 0;
3496     }
3497     case TYPE_VECTOR:
3498     {
3499         size_t d;
3500         ir_value_code_setaddr(global, vec_size(self->code->globals));
3501         if (global->hasvalue) {
3502             iptr = (int32_t*)&global->constval.ivec[0];
3503             vec_push(self->code->globals, iptr[0]);
3504             if (global->code.globaladdr < 0)
3505                 return false;
3506             for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3507                 vec_push(self->code->globals, iptr[d]);
3508             }
3509         } else {
3510             vec_push(self->code->globals, 0);
3511             if (global->code.globaladdr < 0)
3512                 return false;
3513             for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3514                 vec_push(self->code->globals, 0);
3515             }
3516         }
3517         if (!islocal && global->cvq != CV_CONST)
3518             def.type |= DEF_SAVEGLOBAL;
3519
3520         if (pushdef) {
3521             vec_push(self->code->defs, def);
3522             def.type &= ~DEF_SAVEGLOBAL;
3523             gen_vector_defs(self->code, def, global->name);
3524         }
3525         return global->code.globaladdr >= 0;
3526     }
3527     case TYPE_FUNCTION:
3528         ir_value_code_setaddr(global, vec_size(self->code->globals));
3529         if (!global->hasvalue) {
3530             vec_push(self->code->globals, 0);
3531             if (global->code.globaladdr < 0)
3532                 return false;
3533         } else {
3534             vec_push(self->code->globals, vec_size(self->code->functions));
3535             if (!gen_global_function(self, global))
3536                 return false;
3537         }
3538         if (!islocal && global->cvq != CV_CONST)
3539             def.type |= DEF_SAVEGLOBAL;
3540         if (pushdef) vec_push(self->code->defs, def);
3541         return true;
3542     case TYPE_VARIANT:
3543         /* assume biggest type */
3544             ir_value_code_setaddr(global, vec_size(self->code->globals));
3545             vec_push(self->code->globals, 0);
3546             for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3547                 vec_push(self->code->globals, 0);
3548             return true;
3549     default:
3550         /* refuse to create 'void' type or any other fancy business. */
3551         irerror(global->context, "Invalid type for global variable `%s`: %s",
3552                 global->name, type_name[global->vtype]);
3553         return false;
3554     }
3555 }
3556
3557 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3558 {
3559     field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3560 }
3561
3562 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3563 {
3564     prog_section_def_t def;
3565     prog_section_field_t fld;
3566
3567     (void)self;
3568
3569     def.type   = (uint16_t)field->vtype;
3570     def.offset = (uint16_t)vec_size(self->code->globals);
3571
3572     /* create a global named the same as the field */
3573     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3574         /* in our standard, the global gets a dot prefix */
3575         size_t len = strlen(field->name);
3576         char name[1024];
3577
3578         /* we really don't want to have to allocate this, and 1024
3579          * bytes is more than enough for a variable/field name
3580          */
3581         if (len+2 >= sizeof(name)) {
3582             irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3583             return false;
3584         }
3585
3586         name[0] = '.';
3587         memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3588         name[len+1] = 0;
3589
3590         def.name = code_genstring(self->code, name);
3591         fld.name = def.name + 1; /* we reuse that string table entry */
3592     } else {
3593         /* in plain QC, there cannot be a global with the same name,
3594          * and so we also name the global the same.
3595          * FIXME: fteqcc should create a global as well
3596          * check if it actually uses the same name. Probably does
3597          */
3598         def.name = code_genstring(self->code, field->name);
3599         fld.name = def.name;
3600     }
3601
3602     field->code.name = def.name;
3603
3604     vec_push(self->code->defs, def);
3605
3606     fld.type = field->fieldtype;
3607
3608     if (fld.type == TYPE_VOID) {
3609         irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3610         return false;
3611     }
3612
3613     fld.offset = field->code.fieldaddr;
3614
3615     vec_push(self->code->fields, fld);
3616
3617     ir_value_code_setaddr(field, vec_size(self->code->globals));
3618     vec_push(self->code->globals, fld.offset);
3619     if (fld.type == TYPE_VECTOR) {
3620         vec_push(self->code->globals, fld.offset+1);
3621         vec_push(self->code->globals, fld.offset+2);
3622     }
3623
3624     if (field->fieldtype == TYPE_VECTOR) {
3625         gen_vector_defs  (self->code, def, field->name);
3626         gen_vector_fields(self->code, fld, field->name);
3627     }
3628
3629     return field->code.globaladdr >= 0;
3630 }
3631
3632 bool ir_builder_generate(ir_builder *self, const char *filename)
3633 {
3634     prog_section_statement_t stmt;
3635     size_t i;
3636     char  *lnofile = NULL;
3637
3638     for (i = 0; i < vec_size(self->fields); ++i)
3639     {
3640         ir_builder_prepare_field(self->code, self->fields[i]);
3641     }
3642
3643     for (i = 0; i < vec_size(self->globals); ++i)
3644     {
3645         if (!ir_builder_gen_global(self, self->globals[i], false)) {
3646             return false;
3647         }
3648         if (self->globals[i]->vtype == TYPE_FUNCTION) {
3649             ir_function *func = self->globals[i]->constval.vfunc;
3650             if (func && self->max_locals < func->allocated_locals &&
3651                 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3652             {
3653                 self->max_locals = func->allocated_locals;
3654             }
3655             if (func && self->max_globaltemps < func->globaltemps)
3656                 self->max_globaltemps = func->globaltemps;
3657         }
3658     }
3659
3660     for (i = 0; i < vec_size(self->fields); ++i)
3661     {
3662         if (!ir_builder_gen_field(self, self->fields[i])) {
3663             return false;
3664         }
3665     }
3666
3667     /* generate nil */
3668     ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
3669     vec_push(self->code->globals, 0);
3670     vec_push(self->code->globals, 0);
3671     vec_push(self->code->globals, 0);
3672
3673     /* generate virtual-instruction temps */
3674     for (i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
3675         ir_value_code_setaddr(self->vinstr_temp[i], vec_size(self->code->globals));
3676         vec_push(self->code->globals, 0);
3677         vec_push(self->code->globals, 0);
3678         vec_push(self->code->globals, 0);
3679     }
3680
3681     /* generate global temps */
3682     self->first_common_globaltemp = vec_size(self->code->globals);
3683     for (i = 0; i < self->max_globaltemps; ++i) {
3684         vec_push(self->code->globals, 0);
3685     }
3686     /* generate common locals */
3687     self->first_common_local = vec_size(self->code->globals);
3688     for (i = 0; i < self->max_locals; ++i) {
3689         vec_push(self->code->globals, 0);
3690     }
3691
3692     /* generate function code */
3693     for (i = 0; i < vec_size(self->globals); ++i)
3694     {
3695         if (self->globals[i]->vtype == TYPE_FUNCTION) {
3696             if (!gen_global_function_code(self, self->globals[i])) {
3697                 return false;
3698             }
3699         }
3700     }
3701
3702     if (vec_size(self->code->globals) >= 65536) {
3703         irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3704         return false;
3705     }
3706
3707     /* DP errors if the last instruction is not an INSTR_DONE. */
3708     if (vec_last(self->code->statements).opcode != INSTR_DONE)
3709     {
3710         stmt.opcode = INSTR_DONE;
3711         stmt.o1.u1 = 0;
3712         stmt.o2.u1 = 0;
3713         stmt.o3.u1 = 0;
3714         code_push_statement(self->code, &stmt, vec_last(self->code->linenums));
3715     }
3716
3717     if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3718         return true;
3719
3720     if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
3721         con_err("Linecounter wrong: %lu != %lu\n",
3722                 (unsigned long)vec_size(self->code->statements),
3723                 (unsigned long)vec_size(self->code->linenums));
3724     } else if (OPTS_FLAG(LNO)) {
3725         char  *dot;
3726         size_t filelen = strlen(filename);
3727
3728         memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3729         dot = strrchr(lnofile, '.');
3730         if (!dot) {
3731             vec_pop(lnofile);
3732         } else {
3733             vec_shrinkto(lnofile, dot - lnofile);
3734         }
3735         memcpy(vec_add(lnofile, 5), ".lno", 5);
3736     }
3737
3738     if (!code_write(self->code, filename, lnofile)) {
3739         vec_free(lnofile);
3740         return false;
3741     }
3742
3743     vec_free(lnofile);
3744     return true;
3745 }
3746
3747 /***********************************************************************
3748  *IR DEBUG Dump functions...
3749  */
3750
3751 #define IND_BUFSZ 1024
3752
3753 #ifdef _MSC_VER
3754 #   define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3755 #endif
3756
3757 static const char *qc_opname(int op)
3758 {
3759     if (op < 0) return "<INVALID>";
3760     if (op < VINSTR_END)
3761         return util_instr_str[op];
3762     switch (op) {
3763         case VINSTR_END:  return "END";
3764         case VINSTR_PHI:  return "PHI";
3765         case VINSTR_JUMP: return "JUMP";
3766         case VINSTR_COND: return "COND";
3767         default:          return "<UNK>";
3768     }
3769 }
3770
3771 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3772 {
3773     size_t i;
3774     char indent[IND_BUFSZ];
3775     indent[0] = '\t';
3776     indent[1] = 0;
3777
3778     oprintf("module %s\n", b->name);
3779     for (i = 0; i < vec_size(b->globals); ++i)
3780     {
3781         oprintf("global ");
3782         if (b->globals[i]->hasvalue)
3783             oprintf("%s = ", b->globals[i]->name);
3784         ir_value_dump(b->globals[i], oprintf);
3785         oprintf("\n");
3786     }
3787     for (i = 0; i < vec_size(b->functions); ++i)
3788         ir_function_dump(b->functions[i], indent, oprintf);
3789     oprintf("endmodule %s\n", b->name);
3790 }
3791
3792 static const char *storenames[] = {
3793     "[global]", "[local]", "[param]", "[value]", "[return]"
3794 };
3795
3796 void ir_function_dump(ir_function *f, char *ind,
3797                       int (*oprintf)(const char*, ...))
3798 {
3799     size_t i;
3800     if (f->builtin != 0) {
3801         oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3802         return;
3803     }
3804     oprintf("%sfunction %s\n", ind, f->name);
3805     strncat(ind, "\t", IND_BUFSZ-1);
3806     if (vec_size(f->locals))
3807     {
3808         oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3809         for (i = 0; i < vec_size(f->locals); ++i) {
3810             oprintf("%s\t", ind);
3811             ir_value_dump(f->locals[i], oprintf);
3812             oprintf("\n");
3813         }
3814     }
3815     oprintf("%sliferanges:\n", ind);
3816     for (i = 0; i < vec_size(f->locals); ++i) {
3817         const char *attr = "";
3818         size_t l, m;
3819         ir_value *v = f->locals[i];
3820         if (v->unique_life && v->locked)
3821             attr = "unique,locked ";
3822         else if (v->unique_life)
3823             attr = "unique ";
3824         else if (v->locked)
3825             attr = "locked ";
3826         oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3827                 storenames[v->store],
3828                 attr, (v->callparam ? "callparam " : ""),
3829                 (int)v->code.local);
3830         if (!v->life)
3831             oprintf("[null]");
3832         for (l = 0; l < vec_size(v->life); ++l) {
3833             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3834         }
3835         oprintf("\n");
3836         for (m = 0; m < 3; ++m) {
3837             ir_value *vm = v->members[m];
3838             if (!vm)
3839                 continue;
3840             oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
3841             for (l = 0; l < vec_size(vm->life); ++l) {
3842                 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3843             }
3844             oprintf("\n");
3845         }
3846     }
3847     for (i = 0; i < vec_size(f->values); ++i) {
3848         const char *attr = "";
3849         size_t l, m;
3850         ir_value *v = f->values[i];
3851         if (v->unique_life && v->locked)
3852             attr = "unique,locked ";
3853         else if (v->unique_life)
3854             attr = "unique ";
3855         else if (v->locked)
3856             attr = "locked ";
3857         oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3858                 storenames[v->store],
3859                 attr, (v->callparam ? "callparam " : ""),
3860                 (int)v->code.local);
3861         if (!v->life)
3862             oprintf("[null]");
3863         for (l = 0; l < vec_size(v->life); ++l) {
3864             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3865         }
3866         oprintf("\n");
3867         for (m = 0; m < 3; ++m) {
3868             ir_value *vm = v->members[m];
3869             if (!vm)
3870                 continue;
3871             if (vm->unique_life && vm->locked)
3872                 attr = "unique,locked ";
3873             else if (vm->unique_life)
3874                 attr = "unique ";
3875             else if (vm->locked)
3876                 attr = "locked ";
3877             oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
3878             for (l = 0; l < vec_size(vm->life); ++l) {
3879                 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3880             }
3881             oprintf("\n");
3882         }
3883     }
3884     if (vec_size(f->blocks))
3885     {
3886         oprintf("%slife passes: %i\n", ind, (int)f->run_id);
3887         for (i = 0; i < vec_size(f->blocks); ++i) {
3888             ir_block_dump(f->blocks[i], ind, oprintf);
3889         }
3890
3891     }
3892     ind[strlen(ind)-1] = 0;
3893     oprintf("%sendfunction %s\n", ind, f->name);
3894 }
3895
3896 void ir_block_dump(ir_block* b, char *ind,
3897                    int (*oprintf)(const char*, ...))
3898 {
3899     size_t i;
3900     oprintf("%s:%s\n", ind, b->label);
3901     strncat(ind, "\t", IND_BUFSZ-1);
3902
3903     if (b->instr && b->instr[0])
3904         oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
3905     for (i = 0; i < vec_size(b->instr); ++i)
3906         ir_instr_dump(b->instr[i], ind, oprintf);
3907     ind[strlen(ind)-1] = 0;
3908 }
3909
3910 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3911 {
3912     size_t i;
3913     oprintf("%s <- phi ", in->_ops[0]->name);
3914     for (i = 0; i < vec_size(in->phi); ++i)
3915     {
3916         oprintf("([%s] : %s) ", in->phi[i].from->label,
3917                                 in->phi[i].value->name);
3918     }
3919     oprintf("\n");
3920 }
3921
3922 void ir_instr_dump(ir_instr *in, char *ind,
3923                        int (*oprintf)(const char*, ...))
3924 {
3925     size_t i;
3926     const char *comma = NULL;
3927
3928     oprintf("%s (%i) ", ind, (int)in->eid);
3929
3930     if (in->opcode == VINSTR_PHI) {
3931         dump_phi(in, oprintf);
3932         return;
3933     }
3934
3935     strncat(ind, "\t", IND_BUFSZ-1);
3936
3937     if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3938         ir_value_dump(in->_ops[0], oprintf);
3939         if (in->_ops[1] || in->_ops[2])
3940             oprintf(" <- ");
3941     }
3942     if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3943         oprintf("CALL%i\t", vec_size(in->params));
3944     } else
3945         oprintf("%s\t", qc_opname(in->opcode));
3946
3947     if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3948         ir_value_dump(in->_ops[0], oprintf);
3949         comma = ",\t";
3950     }
3951     else
3952     {
3953         for (i = 1; i != 3; ++i) {
3954             if (in->_ops[i]) {
3955                 if (comma)
3956                     oprintf(comma);
3957                 ir_value_dump(in->_ops[i], oprintf);
3958                 comma = ",\t";
3959             }
3960         }
3961     }
3962     if (in->bops[0]) {
3963         if (comma)
3964             oprintf(comma);
3965         oprintf("[%s]", in->bops[0]->label);
3966         comma = ",\t";
3967     }
3968     if (in->bops[1])
3969         oprintf("%s[%s]", comma, in->bops[1]->label);
3970     if (vec_size(in->params)) {
3971         oprintf("\tparams: ");
3972         for (i = 0; i != vec_size(in->params); ++i) {
3973             oprintf("%s, ", in->params[i]->name);
3974         }
3975     }
3976     oprintf("\n");
3977     ind[strlen(ind)-1] = 0;
3978 }
3979
3980 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3981 {
3982     oprintf("\"");
3983     for (; *str; ++str) {
3984         switch (*str) {
3985             case '\n': oprintf("\\n"); break;
3986             case '\r': oprintf("\\r"); break;
3987             case '\t': oprintf("\\t"); break;
3988             case '\v': oprintf("\\v"); break;
3989             case '\f': oprintf("\\f"); break;
3990             case '\b': oprintf("\\b"); break;
3991             case '\a': oprintf("\\a"); break;
3992             case '\\': oprintf("\\\\"); break;
3993             case '"': oprintf("\\\""); break;
3994             default: oprintf("%c", *str); break;
3995         }
3996     }
3997     oprintf("\"");
3998 }
3999
4000 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4001 {
4002     if (v->hasvalue) {
4003         switch (v->vtype) {
4004             default:
4005             case TYPE_VOID:
4006                 oprintf("(void)");
4007                 break;
4008             case TYPE_FUNCTION:
4009                 oprintf("fn:%s", v->name);
4010                 break;
4011             case TYPE_FLOAT:
4012                 oprintf("%g", v->constval.vfloat);
4013                 break;
4014             case TYPE_VECTOR:
4015                 oprintf("'%g %g %g'",
4016                         v->constval.vvec.x,
4017                         v->constval.vvec.y,
4018                         v->constval.vvec.z);
4019                 break;
4020             case TYPE_ENTITY:
4021                 oprintf("(entity)");
4022                 break;
4023             case TYPE_STRING:
4024                 ir_value_dump_string(v->constval.vstring, oprintf);
4025                 break;
4026 #if 0
4027             case TYPE_INTEGER:
4028                 oprintf("%i", v->constval.vint);
4029                 break;
4030 #endif
4031             case TYPE_POINTER:
4032                 oprintf("&%s",
4033                     v->constval.vpointer->name);
4034                 break;
4035         }
4036     } else {
4037         oprintf("%s", v->name);
4038     }
4039 }
4040
4041 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4042 {
4043     size_t i;
4044     oprintf("Life of %12s:", self->name);
4045     for (i = 0; i < vec_size(self->life); ++i)
4046     {
4047         oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
4048     }
4049 }