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