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