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