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