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