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