]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
Merging master and adopting its main.c
[xonotic/gmqcc.git] / ir.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdlib.h>
24 #include <string.h>
25 #include "gmqcc.h"
26 #include "ir.h"
27
28 /***********************************************************************
29  * Type sizes used at multiple points in the IR codegen
30  */
31
32 const char *type_name[TYPE_COUNT] = {
33     "void",
34     "string",
35     "float",
36     "vector",
37     "entity",
38     "field",
39     "function",
40     "pointer",
41 #if 0
42     "integer",
43 #endif
44     "quaternion",
45     "matrix",
46     "variant"
47 };
48
49 size_t type_sizeof[TYPE_COUNT] = {
50     1, /* TYPE_VOID     */
51     1, /* TYPE_STRING   */
52     1, /* TYPE_FLOAT    */
53     3, /* TYPE_VECTOR   */
54     1, /* TYPE_ENTITY   */
55     1, /* TYPE_FIELD    */
56     1, /* TYPE_FUNCTION */
57     1, /* TYPE_POINTER  */
58 #if 0
59     1, /* TYPE_INTEGER  */
60 #endif
61     4, /* TYPE_QUATERNION */
62     16, /* TYPE_MATRIX */
63     16, /* TYPE_VARIANT  */
64 };
65
66 uint16_t type_store_instr[TYPE_COUNT] = {
67     INSTR_STORE_F, /* should use I when having integer support */
68     INSTR_STORE_S,
69     INSTR_STORE_F,
70     INSTR_STORE_V,
71     INSTR_STORE_ENT,
72     INSTR_STORE_FLD,
73     INSTR_STORE_FNC,
74     INSTR_STORE_ENT, /* should use I */
75 #if 0
76     INSTR_STORE_I, /* integer type */
77 #endif
78     INSTR_STORE_Q,
79     INSTR_STORE_M,
80
81     INSTR_STORE_M, /* variant, should never be accessed */
82 };
83
84 uint16_t type_storep_instr[TYPE_COUNT] = {
85     INSTR_STOREP_F, /* should use I when having integer support */
86     INSTR_STOREP_S,
87     INSTR_STOREP_F,
88     INSTR_STOREP_V,
89     INSTR_STOREP_ENT,
90     INSTR_STOREP_FLD,
91     INSTR_STOREP_FNC,
92     INSTR_STOREP_ENT, /* should use I */
93 #if 0
94     INSTR_STOREP_ENT, /* integer type */
95 #endif
96     INSTR_STOREP_Q,
97     INSTR_STOREP_M,
98
99     INSTR_STOREP_M, /* variant, should never be accessed */
100 };
101
102 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
103
104 /***********************************************************************
105  *IR Builder
106  */
107
108 ir_builder* ir_builder_new(const char *modulename)
109 {
110     ir_builder* self;
111
112     self = (ir_builder*)mem_a(sizeof(*self));
113     if (!self)
114         return NULL;
115
116     MEM_VECTOR_INIT(self, functions);
117     MEM_VECTOR_INIT(self, globals);
118     self->name = NULL;
119     if (!ir_builder_set_name(self, modulename)) {
120         mem_d(self);
121         return NULL;
122     }
123
124     /* globals which always exist */
125
126     /* for now we give it a vector size */
127     ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
128
129     return self;
130 }
131
132 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
133 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
134
135 void ir_builder_delete(ir_builder* self)
136 {
137     size_t i;
138     mem_d((void*)self->name);
139     for (i = 0; i != self->functions_count; ++i) {
140         ir_function_delete(self->functions[i]);
141     }
142     MEM_VECTOR_CLEAR(self, functions);
143     for (i = 0; i != self->globals_count; ++i) {
144         ir_value_delete(self->globals[i]);
145     }
146     MEM_VECTOR_CLEAR(self, globals);
147     mem_d(self);
148 }
149
150 bool ir_builder_set_name(ir_builder *self, const char *name)
151 {
152     if (self->name)
153         mem_d((void*)self->name);
154     self->name = util_strdup(name);
155     return !!self->name;
156 }
157
158 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
159 {
160     size_t i;
161     for (i = 0; i < self->functions_count; ++i) {
162         if (!strcmp(name, self->functions[i]->name))
163             return self->functions[i];
164     }
165     return NULL;
166 }
167
168 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
169 {
170     ir_function *fn = ir_builder_get_function(self, name);
171     if (fn) {
172         return NULL;
173     }
174
175     fn = ir_function_new(self, outtype);
176     if (!ir_function_set_name(fn, name) ||
177         !ir_builder_functions_add(self, fn) )
178     {
179         ir_function_delete(fn);
180         return NULL;
181     }
182
183     fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
184     if (!fn->value) {
185         ir_function_delete(fn);
186         return NULL;
187     }
188
189     fn->value->isconst = true;
190     fn->value->outtype = outtype;
191     fn->value->constval.vfunc = fn;
192     fn->value->context = fn->context;
193
194     return fn;
195 }
196
197 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
198 {
199     size_t i;
200     for (i = 0; i < self->globals_count; ++i) {
201         if (!strcmp(self->globals[i]->name, name))
202             return self->globals[i];
203     }
204     return NULL;
205 }
206
207 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
208 {
209     ir_value *ve;
210
211     if (name && name[0] != '#')
212     {
213         ve = ir_builder_get_global(self, name);
214         if (ve) {
215             return NULL;
216         }
217     }
218
219     ve = ir_value_var(name, store_global, vtype);
220     if (!ir_builder_globals_add(self, ve)) {
221         ir_value_delete(ve);
222         return NULL;
223     }
224     return ve;
225 }
226
227 /***********************************************************************
228  *IR Function
229  */
230
231 bool ir_function_naive_phi(ir_function*);
232 void ir_function_enumerate(ir_function*);
233 bool ir_function_calculate_liferanges(ir_function*);
234 bool ir_function_allocate_locals(ir_function*);
235
236 ir_function* ir_function_new(ir_builder* owner, int outtype)
237 {
238     ir_function *self;
239     self = (ir_function*)mem_a(sizeof(*self));
240
241     if (!self)
242         return NULL;
243
244     self->name = NULL;
245     if (!ir_function_set_name(self, "<@unnamed>")) {
246         mem_d(self);
247         return NULL;
248     }
249     self->owner = owner;
250     self->context.file = "<@no context>";
251     self->context.line = 0;
252     self->outtype = outtype;
253     self->value = NULL;
254     self->builtin = 0;
255     MEM_VECTOR_INIT(self, params);
256     MEM_VECTOR_INIT(self, blocks);
257     MEM_VECTOR_INIT(self, values);
258     MEM_VECTOR_INIT(self, locals);
259
260     self->run_id = 0;
261     return self;
262 }
263 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
264 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
265 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
266 MEM_VEC_FUNCTIONS(ir_function, int,       params)
267
268 bool ir_function_set_name(ir_function *self, const char *name)
269 {
270     if (self->name)
271         mem_d((void*)self->name);
272     self->name = util_strdup(name);
273     return !!self->name;
274 }
275
276 void ir_function_delete(ir_function *self)
277 {
278     size_t i;
279     mem_d((void*)self->name);
280
281     for (i = 0; i != self->blocks_count; ++i)
282         ir_block_delete(self->blocks[i]);
283     MEM_VECTOR_CLEAR(self, blocks);
284
285     MEM_VECTOR_CLEAR(self, params);
286
287     for (i = 0; i != self->values_count; ++i)
288         ir_value_delete(self->values[i]);
289     MEM_VECTOR_CLEAR(self, values);
290
291     for (i = 0; i != self->locals_count; ++i)
292         ir_value_delete(self->locals[i]);
293     MEM_VECTOR_CLEAR(self, locals);
294
295     /* self->value is deleted by the builder */
296
297     mem_d(self);
298 }
299
300 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
301 {
302     return ir_function_values_add(self, v);
303 }
304
305 ir_block* ir_function_create_block(ir_function *self, const char *label)
306 {
307     ir_block* bn = ir_block_new(self, label);
308     memcpy(&bn->context, &self->context, sizeof(self->context));
309     if (!ir_function_blocks_add(self, bn)) {
310         ir_block_delete(bn);
311         return NULL;
312     }
313     return bn;
314 }
315
316 bool ir_function_finalize(ir_function *self)
317 {
318     if (self->builtin)
319         return true;
320
321     if (!ir_function_naive_phi(self))
322         return false;
323
324     ir_function_enumerate(self);
325
326     if (!ir_function_calculate_liferanges(self))
327         return false;
328
329     if (!ir_function_allocate_locals(self))
330         return false;
331     return true;
332 }
333
334 ir_value* ir_function_get_local(ir_function *self, const char *name)
335 {
336     size_t i;
337     for (i = 0; i < self->locals_count; ++i) {
338         if (!strcmp(self->locals[i]->name, name))
339             return self->locals[i];
340     }
341     return NULL;
342 }
343
344 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
345 {
346     ir_value *ve = ir_function_get_local(self, name);
347     if (ve) {
348         return NULL;
349     }
350
351     if (param &&
352         self->locals_count &&
353         self->locals[self->locals_count-1]->store != store_param) {
354         printf("cannot add parameters after adding locals\n");
355         return NULL;
356     }
357
358     ve = ir_value_var(name, (param ? store_param : store_local), vtype);
359     if (!ir_function_locals_add(self, ve)) {
360         ir_value_delete(ve);
361         return NULL;
362     }
363     return ve;
364 }
365
366 /***********************************************************************
367  *IR Block
368  */
369
370 ir_block* ir_block_new(ir_function* owner, const char *name)
371 {
372     ir_block *self;
373     self = (ir_block*)mem_a(sizeof(*self));
374     if (!self)
375         return NULL;
376
377     memset(self, 0, sizeof(*self));
378
379     self->label = NULL;
380     if (!ir_block_set_label(self, name)) {
381         mem_d(self);
382         return NULL;
383     }
384     self->owner = owner;
385     self->context.file = "<@no context>";
386     self->context.line = 0;
387     self->final = false;
388     MEM_VECTOR_INIT(self, instr);
389     MEM_VECTOR_INIT(self, entries);
390     MEM_VECTOR_INIT(self, exits);
391
392     self->eid = 0;
393     self->is_return = false;
394     self->run_id = 0;
395     MEM_VECTOR_INIT(self, living);
396
397     self->generated = false;
398
399     return self;
400 }
401 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
402 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
403 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
404 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
405
406 void ir_block_delete(ir_block* self)
407 {
408     size_t i;
409     mem_d(self->label);
410     for (i = 0; i != self->instr_count; ++i)
411         ir_instr_delete(self->instr[i]);
412     MEM_VECTOR_CLEAR(self, instr);
413     MEM_VECTOR_CLEAR(self, entries);
414     MEM_VECTOR_CLEAR(self, exits);
415     MEM_VECTOR_CLEAR(self, living);
416     mem_d(self);
417 }
418
419 bool ir_block_set_label(ir_block *self, const char *name)
420 {
421     if (self->label)
422         mem_d((void*)self->label);
423     self->label = util_strdup(name);
424     return !!self->label;
425 }
426
427 /***********************************************************************
428  *IR Instructions
429  */
430
431 ir_instr* ir_instr_new(ir_block* owner, int op)
432 {
433     ir_instr *self;
434     self = (ir_instr*)mem_a(sizeof(*self));
435     if (!self)
436         return NULL;
437
438     self->owner = owner;
439     self->context.file = "<@no context>";
440     self->context.line = 0;
441     self->opcode = op;
442     self->_ops[0] = NULL;
443     self->_ops[1] = NULL;
444     self->_ops[2] = NULL;
445     self->bops[0] = NULL;
446     self->bops[1] = NULL;
447     MEM_VECTOR_INIT(self, phi);
448     MEM_VECTOR_INIT(self, params);
449
450     self->eid = 0;
451     return self;
452 }
453 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
454 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
455
456 void ir_instr_delete(ir_instr *self)
457 {
458     size_t i;
459     /* The following calls can only delete from
460      * vectors, we still want to delete this instruction
461      * so ignore the return value. Since with the warn_unused_result attribute
462      * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
463      * I have to improvise here and use if(foo());
464      */
465     for (i = 0; i < self->phi_count; ++i) {
466         size_t idx;
467         if (ir_value_writes_find(self->phi[i].value, self, &idx))
468             if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
469         if (ir_value_reads_find(self->phi[i].value, self, &idx))
470             if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
471     }
472     MEM_VECTOR_CLEAR(self, phi);
473     for (i = 0; i < self->params_count; ++i) {
474         size_t idx;
475         if (ir_value_writes_find(self->params[i], self, &idx))
476             if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
477         if (ir_value_reads_find(self->params[i], self, &idx))
478             if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
479     }
480     MEM_VECTOR_CLEAR(self, params);
481     if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
482     if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
483     if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
484     mem_d(self);
485 }
486
487 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
488 {
489     if (self->_ops[op]) {
490         size_t idx;
491         if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
492         {
493             if (!ir_value_writes_remove(self->_ops[op], idx))
494                 return false;
495         }
496         else if (ir_value_reads_find(self->_ops[op], self, &idx))
497         {
498             if (!ir_value_reads_remove(self->_ops[op], idx))
499                 return false;
500         }
501     }
502     if (v) {
503         if (writing) {
504             if (!ir_value_writes_add(v, self))
505                 return false;
506         } else {
507             if (!ir_value_reads_add(v, self))
508                 return false;
509         }
510     }
511     self->_ops[op] = v;
512     return true;
513 }
514
515 /***********************************************************************
516  *IR Value
517  */
518
519 ir_value* ir_value_var(const char *name, int storetype, int vtype)
520 {
521     ir_value *self;
522     self = (ir_value*)mem_a(sizeof(*self));
523     self->vtype = vtype;
524     self->fieldtype = TYPE_VOID;
525     self->outtype = TYPE_VOID;
526     self->store = storetype;
527     MEM_VECTOR_INIT(self, reads);
528     MEM_VECTOR_INIT(self, writes);
529     self->isconst = false;
530     self->context.file = "<@no context>";
531     self->context.line = 0;
532     self->name = NULL;
533     ir_value_set_name(self, name);
534
535     memset(&self->constval, 0, sizeof(self->constval));
536     memset(&self->code,     0, sizeof(self->code));
537
538     MEM_VECTOR_INIT(self, life);
539     return self;
540 }
541 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
542 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
543 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
544
545 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
546 {
547     ir_value *v = ir_value_var(name, storetype, vtype);
548     if (!v)
549         return NULL;
550     if (!ir_function_collect_value(owner, v))
551     {
552         ir_value_delete(v);
553         return NULL;
554     }
555     return v;
556 }
557
558 void ir_value_delete(ir_value* self)
559 {
560     if (self->name)
561         mem_d((void*)self->name);
562     if (self->isconst)
563     {
564         if (self->vtype == TYPE_STRING)
565             mem_d((void*)self->constval.vstring);
566     }
567     MEM_VECTOR_CLEAR(self, reads);
568     MEM_VECTOR_CLEAR(self, writes);
569     MEM_VECTOR_CLEAR(self, life);
570     mem_d(self);
571 }
572
573 void ir_value_set_name(ir_value *self, const char *name)
574 {
575     if (self->name)
576         mem_d((void*)self->name);
577     self->name = util_strdup(name);
578 }
579
580 bool ir_value_set_float(ir_value *self, float f)
581 {
582     if (self->vtype != TYPE_FLOAT)
583         return false;
584     self->constval.vfloat = f;
585     self->isconst = true;
586     return true;
587 }
588
589 bool ir_value_set_func(ir_value *self, int f)
590 {
591     if (self->vtype != TYPE_FUNCTION)
592         return false;
593     self->constval.vint = f;
594     self->isconst = true;
595     return true;
596 }
597
598 bool ir_value_set_vector(ir_value *self, vector v)
599 {
600     if (self->vtype != TYPE_VECTOR)
601         return false;
602     self->constval.vvec = v;
603     self->isconst = true;
604     return true;
605 }
606
607 bool ir_value_set_quaternion(ir_value *self, quaternion v)
608 {
609     if (self->vtype != TYPE_QUATERNION)
610         return false;
611     memcpy(&self->constval.vquat, v, sizeof(self->constval.vquat));
612     self->isconst = true;
613     return true;
614 }
615
616 bool ir_value_set_matrix(ir_value *self, matrix v)
617 {
618     if (self->vtype != TYPE_MATRIX)
619         return false;
620     memcpy(&self->constval.vmat, v, sizeof(self->constval.vmat));
621     self->isconst = true;
622     return true;
623 }
624
625 bool ir_value_set_string(ir_value *self, const char *str)
626 {
627     if (self->vtype != TYPE_STRING)
628         return false;
629     self->constval.vstring = util_strdup(str);
630     self->isconst = true;
631     return true;
632 }
633
634 #if 0
635 bool ir_value_set_int(ir_value *self, int i)
636 {
637     if (self->vtype != TYPE_INTEGER)
638         return false;
639     self->constval.vint = i;
640     self->isconst = true;
641     return true;
642 }
643 #endif
644
645 bool ir_value_lives(ir_value *self, size_t at)
646 {
647     size_t i;
648     for (i = 0; i < self->life_count; ++i)
649     {
650         ir_life_entry_t *life = &self->life[i];
651         if (life->start <= at && at <= life->end)
652             return true;
653         if (life->start > at) /* since it's ordered */
654             return false;
655     }
656     return false;
657 }
658
659 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
660 {
661     size_t k;
662     if (!ir_value_life_add(self, e)) /* naive... */
663         return false;
664     for (k = self->life_count-1; k > idx; --k)
665         self->life[k] = self->life[k-1];
666     self->life[idx] = e;
667     return true;
668 }
669
670 bool ir_value_life_merge(ir_value *self, size_t s)
671 {
672     size_t i;
673     ir_life_entry_t *life = NULL;
674     ir_life_entry_t *before = NULL;
675     ir_life_entry_t new_entry;
676
677     /* Find the first range >= s */
678     for (i = 0; i < self->life_count; ++i)
679     {
680         before = life;
681         life = &self->life[i];
682         if (life->start > s)
683             break;
684     }
685     /* nothing found? append */
686     if (i == self->life_count) {
687         ir_life_entry_t e;
688         if (life && life->end+1 == s)
689         {
690             /* previous life range can be merged in */
691             life->end++;
692             return true;
693         }
694         if (life && life->end >= s)
695             return false;
696         e.start = e.end = s;
697         if (!ir_value_life_add(self, e))
698             return false; /* failing */
699         return true;
700     }
701     /* found */
702     if (before)
703     {
704         if (before->end + 1 == s &&
705             life->start - 1 == s)
706         {
707             /* merge */
708             before->end = life->end;
709             if (!ir_value_life_remove(self, i))
710                 return false; /* failing */
711             return true;
712         }
713         if (before->end + 1 == s)
714         {
715             /* extend before */
716             before->end++;
717             return true;
718         }
719         /* already contained */
720         if (before->end >= s)
721             return false;
722     }
723     /* extend */
724     if (life->start - 1 == s)
725     {
726         life->start--;
727         return true;
728     }
729     /* insert a new entry */
730     new_entry.start = new_entry.end = s;
731     return ir_value_life_insert(self, i, new_entry);
732 }
733
734 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
735 {
736     size_t i, myi;
737
738     if (!other->life_count)
739         return true;
740
741     if (!self->life_count) {
742         for (i = 0; i < other->life_count; ++i) {
743             if (!ir_value_life_add(self, other->life[i]))
744                 return false;
745         }
746         return true;
747     }
748
749     myi = 0;
750     for (i = 0; i < other->life_count; ++i)
751     {
752         const ir_life_entry_t *life = &other->life[i];
753         while (true)
754         {
755             ir_life_entry_t *entry = &self->life[myi];
756
757             if (life->end+1 < entry->start)
758             {
759                 /* adding an interval before entry */
760                 if (!ir_value_life_insert(self, myi, *life))
761                     return false;
762                 ++myi;
763                 break;
764             }
765
766             if (life->start <  entry->start &&
767                 life->end   >= entry->start)
768             {
769                 /* starts earlier and overlaps */
770                 entry->start = life->start;
771             }
772
773             if (life->end     >  entry->end &&
774                 life->start-1 <= entry->end)
775             {
776                 /* ends later and overlaps */
777                 entry->end = life->end;
778             }
779
780             /* see if our change combines it with the next ranges */
781             while (myi+1 < self->life_count &&
782                    entry->end+1 >= self->life[1+myi].start)
783             {
784                 /* overlaps with (myi+1) */
785                 if (entry->end < self->life[1+myi].end)
786                     entry->end = self->life[1+myi].end;
787                 if (!ir_value_life_remove(self, myi+1))
788                     return false;
789                 entry = &self->life[myi];
790             }
791
792             /* see if we're after the entry */
793             if (life->start > entry->end)
794             {
795                 ++myi;
796                 /* append if we're at the end */
797                 if (myi >= self->life_count) {
798                     if (!ir_value_life_add(self, *life))
799                         return false;
800                     break;
801                 }
802                 /* otherweise check the next range */
803                 continue;
804             }
805             break;
806         }
807     }
808     return true;
809 }
810
811 bool ir_values_overlap(const ir_value *a, const ir_value *b)
812 {
813     /* For any life entry in A see if it overlaps with
814      * any life entry in B.
815      * Note that the life entries are orderes, so we can make a
816      * more efficient algorithm there than naively translating the
817      * statement above.
818      */
819
820     ir_life_entry_t *la, *lb, *enda, *endb;
821
822     /* first of all, if either has no life range, they cannot clash */
823     if (!a->life_count || !b->life_count)
824         return false;
825
826     la = a->life;
827     lb = b->life;
828     enda = la + a->life_count;
829     endb = lb + b->life_count;
830     while (true)
831     {
832         /* check if the entries overlap, for that,
833          * both must start before the other one ends.
834          */
835 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
836         if (la->start <= lb->end &&
837             lb->start <= la->end)
838 #else
839         if (la->start <  lb->end &&
840             lb->start <  la->end)
841 #endif
842         {
843             return true;
844         }
845
846         /* entries are ordered
847          * one entry is earlier than the other
848          * that earlier entry will be moved forward
849          */
850         if (la->start < lb->start)
851         {
852             /* order: A B, move A forward
853              * check if we hit the end with A
854              */
855             if (++la == enda)
856                 break;
857         }
858         else if (lb->start < la->start)
859         {
860             /* order: B A, move B forward
861              * check if we hit the end with B
862              */
863             if (++lb == endb)
864                 break;
865         }
866     }
867     return false;
868 }
869
870 /***********************************************************************
871  *IR main operations
872  */
873
874 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
875 {
876     if (target->store == store_value) {
877         fprintf(stderr, "cannot store to an SSA value\n");
878         fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
879         return false;
880     } else {
881         ir_instr *in = ir_instr_new(self, op);
882         if (!in)
883             return false;
884         if (!ir_instr_op(in, 0, target, true) ||
885             !ir_instr_op(in, 1, what, false)  ||
886             !ir_block_instr_add(self, in) )
887         {
888             return false;
889         }
890         return true;
891     }
892 }
893
894 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
895 {
896     int op = 0;
897     int vtype;
898     if (target->vtype == TYPE_VARIANT)
899         vtype = what->vtype;
900     else
901         vtype = target->vtype;
902
903 #if 0
904     if      (vtype == TYPE_FLOAT   && what->vtype == TYPE_INTEGER)
905         op = INSTR_CONV_ITOF;
906     else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
907         op = INSTR_CONV_FTOI;
908 #endif
909         op = type_store_instr[vtype];
910
911     return ir_block_create_store_op(self, op, target, what);
912 }
913
914 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
915 {
916     int op = 0;
917     int vtype;
918
919     if (target->vtype != TYPE_POINTER)
920         return false;
921
922     /* storing using pointer - target is a pointer, type must be
923      * inferred from source
924      */
925     vtype = what->vtype;
926
927     op = type_storep_instr[vtype];
928     return ir_block_create_store_op(self, op, target, what);
929 }
930
931 bool ir_block_create_return(ir_block *self, ir_value *v)
932 {
933     ir_instr *in;
934     if (self->final) {
935         fprintf(stderr, "block already ended (%s)\n", self->label);
936         return false;
937     }
938     self->final = true;
939     self->is_return = true;
940     in = ir_instr_new(self, INSTR_RETURN);
941     if (!in)
942         return false;
943
944     if (!ir_instr_op(in, 0, v, false) ||
945         !ir_block_instr_add(self, in) )
946     {
947         return false;
948     }
949     return true;
950 }
951
952 bool ir_block_create_if(ir_block *self, ir_value *v,
953                         ir_block *ontrue, ir_block *onfalse)
954 {
955     ir_instr *in;
956     if (self->final) {
957         fprintf(stderr, "block already ended (%s)\n", self->label);
958         return false;
959     }
960     self->final = true;
961     /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
962     in = ir_instr_new(self, VINSTR_COND);
963     if (!in)
964         return false;
965
966     if (!ir_instr_op(in, 0, v, false)) {
967         ir_instr_delete(in);
968         return false;
969     }
970
971     in->bops[0] = ontrue;
972     in->bops[1] = onfalse;
973
974     if (!ir_block_instr_add(self, in))
975         return false;
976
977     if (!ir_block_exits_add(self, ontrue)    ||
978         !ir_block_exits_add(self, onfalse)   ||
979         !ir_block_entries_add(ontrue, self)  ||
980         !ir_block_entries_add(onfalse, self) )
981     {
982         return false;
983     }
984     return true;
985 }
986
987 bool ir_block_create_jump(ir_block *self, ir_block *to)
988 {
989     ir_instr *in;
990     if (self->final) {
991         fprintf(stderr, "block already ended (%s)\n", self->label);
992         return false;
993     }
994     self->final = true;
995     in = ir_instr_new(self, VINSTR_JUMP);
996     if (!in)
997         return false;
998
999     in->bops[0] = to;
1000     if (!ir_block_instr_add(self, in))
1001         return false;
1002
1003     if (!ir_block_exits_add(self, to) ||
1004         !ir_block_entries_add(to, self) )
1005     {
1006         return false;
1007     }
1008     return true;
1009 }
1010
1011 bool ir_block_create_goto(ir_block *self, ir_block *to)
1012 {
1013     ir_instr *in;
1014     if (self->final) {
1015         fprintf(stderr, "block already ended (%s)\n", self->label);
1016         return false;
1017     }
1018     self->final = true;
1019     in = ir_instr_new(self, INSTR_GOTO);
1020     if (!in)
1021         return false;
1022
1023     in->bops[0] = to;
1024     if (!ir_block_instr_add(self, in))
1025         return false;
1026
1027     if (!ir_block_exits_add(self, to) ||
1028         !ir_block_entries_add(to, self) )
1029     {
1030         return false;
1031     }
1032     return true;
1033 }
1034
1035 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1036 {
1037     ir_value *out;
1038     ir_instr *in;
1039     in = ir_instr_new(self, VINSTR_PHI);
1040     if (!in)
1041         return NULL;
1042     out = ir_value_out(self->owner, label, store_value, ot);
1043     if (!out) {
1044         ir_instr_delete(in);
1045         return NULL;
1046     }
1047     if (!ir_instr_op(in, 0, out, true)) {
1048         ir_instr_delete(in);
1049         ir_value_delete(out);
1050         return NULL;
1051     }
1052     if (!ir_block_instr_add(self, in)) {
1053         ir_instr_delete(in);
1054         ir_value_delete(out);
1055         return NULL;
1056     }
1057     return in;
1058 }
1059
1060 ir_value* ir_phi_value(ir_instr *self)
1061 {
1062     return self->_ops[0];
1063 }
1064
1065 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1066 {
1067     ir_phi_entry_t pe;
1068
1069     if (!ir_block_entries_find(self->owner, b, NULL)) {
1070         /* Must not be possible to cause this, otherwise the AST
1071          * is doing something wrong.
1072          */
1073         fprintf(stderr, "Invalid entry block for PHI\n");
1074         abort();
1075     }
1076
1077     pe.value = v;
1078     pe.from = b;
1079     if (!ir_value_reads_add(v, self))
1080         return false;
1081     return ir_instr_phi_add(self, pe);
1082 }
1083
1084 /* call related code */
1085 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1086 {
1087     ir_value *out;
1088     ir_instr *in;
1089     in = ir_instr_new(self, INSTR_CALL0);
1090     if (!in)
1091         return NULL;
1092     out = ir_value_out(self->owner, label, store_return, func->outtype);
1093     if (!out) {
1094         ir_instr_delete(in);
1095         return NULL;
1096     }
1097     if (!ir_instr_op(in, 0, out, true) ||
1098         !ir_instr_op(in, 1, func, false) ||
1099         !ir_block_instr_add(self, in))
1100     {
1101         ir_instr_delete(in);
1102         ir_value_delete(out);
1103         return NULL;
1104     }
1105     return in;
1106 }
1107
1108 ir_value* ir_call_value(ir_instr *self)
1109 {
1110     return self->_ops[0];
1111 }
1112
1113 bool ir_call_param(ir_instr* self, ir_value *v)
1114 {
1115     if (!ir_instr_params_add(self, v))
1116         return false;
1117     if (!ir_value_reads_add(v, self)) {
1118         if (!ir_instr_params_remove(self, self->params_count-1))
1119             GMQCC_SUPPRESS_EMPTY_BODY;
1120         return false;
1121     }
1122     return true;
1123 }
1124
1125 /* binary op related code */
1126
1127 ir_value* ir_block_create_binop(ir_block *self,
1128                                 const char *label, int opcode,
1129                                 ir_value *left, ir_value *right)
1130 {
1131     int ot = TYPE_VOID;
1132     switch (opcode) {
1133         case INSTR_ADD_F:
1134         case INSTR_SUB_F:
1135         case INSTR_DIV_F:
1136         case INSTR_MUL_F:
1137         case INSTR_MUL_V:
1138         case INSTR_AND:
1139         case INSTR_OR:
1140 #if 0
1141         case INSTR_AND_I:
1142         case INSTR_AND_IF:
1143         case INSTR_AND_FI:
1144         case INSTR_OR_I:
1145         case INSTR_OR_IF:
1146         case INSTR_OR_FI:
1147 #endif
1148         case INSTR_BITAND:
1149         case INSTR_BITOR:
1150 #if 0
1151         case INSTR_SUB_S: /* -- offset of string as float */
1152         case INSTR_MUL_IF:
1153         case INSTR_MUL_FI:
1154         case INSTR_DIV_IF:
1155         case INSTR_DIV_FI:
1156         case INSTR_BITOR_IF:
1157         case INSTR_BITOR_FI:
1158         case INSTR_BITAND_FI:
1159         case INSTR_BITAND_IF:
1160         case INSTR_EQ_I:
1161         case INSTR_NE_I:
1162 #endif
1163             ot = TYPE_FLOAT;
1164             break;
1165 #if 0
1166         case INSTR_ADD_I:
1167         case INSTR_ADD_IF:
1168         case INSTR_ADD_FI:
1169         case INSTR_SUB_I:
1170         case INSTR_SUB_FI:
1171         case INSTR_SUB_IF:
1172         case INSTR_MUL_I:
1173         case INSTR_DIV_I:
1174         case INSTR_BITAND_I:
1175         case INSTR_BITOR_I:
1176         case INSTR_XOR_I:
1177         case INSTR_RSHIFT_I:
1178         case INSTR_LSHIFT_I:
1179             ot = TYPE_INTEGER;
1180             break;
1181 #endif
1182         case INSTR_ADD_V:
1183         case INSTR_SUB_V:
1184         case INSTR_MUL_VF:
1185         case INSTR_MUL_FV:
1186 #if 0
1187         case INSTR_DIV_VF:
1188         case INSTR_MUL_IV:
1189         case INSTR_MUL_VI:
1190 #endif
1191             ot = TYPE_VECTOR;
1192             break;
1193 #if 0
1194         case INSTR_ADD_SF:
1195             ot = TYPE_POINTER;
1196             break;
1197 #endif
1198         default:
1199             /* ranges: */
1200             /* boolean operations result in floats */
1201             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1202                 ot = TYPE_FLOAT;
1203             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1204                 ot = TYPE_FLOAT;
1205 #if 0
1206             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1207                 ot = TYPE_FLOAT;
1208 #endif
1209             break;
1210     };
1211     if (ot == TYPE_VOID) {
1212         /* The AST or parser were supposed to check this! */
1213         return NULL;
1214     }
1215
1216     return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1217 }
1218
1219 ir_value* ir_block_create_unary(ir_block *self,
1220                                 const char *label, int opcode,
1221                                 ir_value *operand)
1222 {
1223     int ot = TYPE_FLOAT;
1224     switch (opcode) {
1225         case INSTR_NOT_F:
1226         case INSTR_NOT_V:
1227         case INSTR_NOT_S:
1228         case INSTR_NOT_ENT:
1229         case INSTR_NOT_FNC:
1230 #if 0
1231         case INSTR_NOT_I:
1232 #endif
1233             ot = TYPE_FLOAT;
1234             break;
1235         /* QC doesn't have other unary operations. We expect extensions to fill
1236          * the above list, otherwise we assume out-type = in-type, eg for an
1237          * unary minus
1238          */
1239         default:
1240             ot = operand->vtype;
1241             break;
1242     };
1243     if (ot == TYPE_VOID) {
1244         /* The AST or parser were supposed to check this! */
1245         return NULL;
1246     }
1247
1248     /* let's use the general instruction creator and pass NULL for OPB */
1249     return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1250 }
1251
1252 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1253                                         int op, ir_value *a, ir_value *b, int outype)
1254 {
1255     ir_instr *instr;
1256     ir_value *out;
1257
1258     out = ir_value_out(self->owner, label, store_value, outype);
1259     if (!out)
1260         return NULL;
1261
1262     instr = ir_instr_new(self, op);
1263     if (!instr) {
1264         ir_value_delete(out);
1265         return NULL;
1266     }
1267
1268     if (!ir_instr_op(instr, 0, out, true) ||
1269         !ir_instr_op(instr, 1, a, false) ||
1270         !ir_instr_op(instr, 2, b, false) )
1271     {
1272         goto on_error;
1273     }
1274
1275     if (!ir_block_instr_add(self, instr))
1276         goto on_error;
1277
1278     return out;
1279 on_error:
1280     ir_instr_delete(instr);
1281     ir_value_delete(out);
1282     return NULL;
1283 }
1284
1285 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1286 {
1287     /* Support for various pointer types todo if so desired */
1288     if (ent->vtype != TYPE_ENTITY)
1289         return NULL;
1290
1291     if (field->vtype != TYPE_FIELD)
1292         return NULL;
1293
1294     return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1295 }
1296
1297 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1298 {
1299     int op;
1300     if (ent->vtype != TYPE_ENTITY)
1301         return NULL;
1302
1303     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1304     if (field->vtype != TYPE_FIELD)
1305         return NULL;
1306
1307     switch (outype)
1308     {
1309         case TYPE_FLOAT:   op = INSTR_LOAD_F;   break;
1310         case TYPE_VECTOR:  op = INSTR_LOAD_V;   break;
1311         case TYPE_STRING:  op = INSTR_LOAD_S;   break;
1312         case TYPE_FIELD:   op = INSTR_LOAD_FLD; break;
1313         case TYPE_ENTITY:  op = INSTR_LOAD_ENT; break;
1314 #if 0
1315         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1316         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1317 #endif
1318         case TYPE_QUATERNION: op = INSTR_LOAD_Q; break;
1319         case TYPE_MATRIX:     op = INSTR_LOAD_M; break;
1320         default:
1321             return NULL;
1322     }
1323
1324     return ir_block_create_general_instr(self, label, op, ent, field, outype);
1325 }
1326
1327 ir_value* ir_block_create_add(ir_block *self,
1328                               const char *label,
1329                               ir_value *left, ir_value *right)
1330 {
1331     int op = 0;
1332     int l = left->vtype;
1333     int r = right->vtype;
1334     if (l == r) {
1335         switch (l) {
1336             default:
1337                 return NULL;
1338             case TYPE_FLOAT:
1339                 op = INSTR_ADD_F;
1340                 break;
1341 #if 0
1342             case TYPE_INTEGER:
1343                 op = INSTR_ADD_I;
1344                 break;
1345 #endif
1346             case TYPE_VECTOR:
1347                 op = INSTR_ADD_V;
1348                 break;
1349         }
1350     } else {
1351 #if 0
1352         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1353             op = INSTR_ADD_FI;
1354         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1355             op = INSTR_ADD_IF;
1356         else
1357 #endif
1358             return NULL;
1359     }
1360     return ir_block_create_binop(self, label, op, left, right);
1361 }
1362
1363 ir_value* ir_block_create_sub(ir_block *self,
1364                               const char *label,
1365                               ir_value *left, ir_value *right)
1366 {
1367     int op = 0;
1368     int l = left->vtype;
1369     int r = right->vtype;
1370     if (l == r) {
1371
1372         switch (l) {
1373             default:
1374                 return NULL;
1375             case TYPE_FLOAT:
1376                 op = INSTR_SUB_F;
1377                 break;
1378 #if 0
1379             case TYPE_INTEGER:
1380                 op = INSTR_SUB_I;
1381                 break;
1382 #endif
1383             case TYPE_VECTOR:
1384                 op = INSTR_SUB_V;
1385                 break;
1386         }
1387     } else {
1388 #if 0
1389         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1390             op = INSTR_SUB_FI;
1391         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1392             op = INSTR_SUB_IF;
1393         else
1394 #endif
1395             return NULL;
1396     }
1397     return ir_block_create_binop(self, label, op, left, right);
1398 }
1399
1400 ir_value* ir_block_create_mul(ir_block *self,
1401                               const char *label,
1402                               ir_value *left, ir_value *right)
1403 {
1404     int op = 0;
1405     int l = left->vtype;
1406     int r = right->vtype;
1407     if (l == r) {
1408
1409         switch (l) {
1410             default:
1411                 return NULL;
1412             case TYPE_FLOAT:
1413                 op = INSTR_MUL_F;
1414                 break;
1415 #if 0
1416             case TYPE_INTEGER:
1417                 op = INSTR_MUL_I;
1418                 break;
1419 #endif
1420             case TYPE_VECTOR:
1421                 op = INSTR_MUL_V;
1422                 break;
1423             case TYPE_QUATERNION:
1424                 op = INSTR_MUL_Q;
1425                 break;
1426             case TYPE_MATRIX:
1427                 op = INSTR_MUL_M;
1428                 break;
1429         }
1430     } else {
1431         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1432             op = INSTR_MUL_VF;
1433         else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1434             op = INSTR_MUL_FV;
1435         else if ( (l == TYPE_QUATERNION && r == TYPE_FLOAT) )
1436             op = INSTR_MUL_QF;
1437         else if ( (l == TYPE_MATRIX && r == TYPE_FLOAT) )
1438             op = INSTR_MUL_MF;
1439 #if 0
1440         else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1441             op = INSTR_MUL_VI;
1442         else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1443             op = INSTR_MUL_IV;
1444         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1445             op = INSTR_MUL_FI;
1446         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1447             op = INSTR_MUL_IF;
1448 #endif
1449         else
1450             return NULL;
1451     }
1452     return ir_block_create_binop(self, label, op, left, right);
1453 }
1454
1455 ir_value* ir_block_create_div(ir_block *self,
1456                               const char *label,
1457                               ir_value *left, ir_value *right)
1458 {
1459     int op = 0;
1460     int l = left->vtype;
1461     int r = right->vtype;
1462     if (l == r) {
1463
1464         switch (l) {
1465             default:
1466                 return NULL;
1467             case TYPE_FLOAT:
1468                 op = INSTR_DIV_F;
1469                 break;
1470 #if 0
1471             case TYPE_INTEGER:
1472                 op = INSTR_DIV_I;
1473                 break;
1474 #endif
1475         }
1476     } else {
1477 #if 0
1478         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1479             op = INSTR_DIV_VF;
1480         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1481             op = INSTR_DIV_FI;
1482         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1483             op = INSTR_DIV_IF;
1484         else
1485 #endif
1486             return NULL;
1487     }
1488     return ir_block_create_binop(self, label, op, left, right);
1489 }
1490
1491 /* PHI resolving breaks the SSA, and must thus be the last
1492  * step before life-range calculation.
1493  */
1494
1495 static bool ir_block_naive_phi(ir_block *self);
1496 bool ir_function_naive_phi(ir_function *self)
1497 {
1498     size_t i;
1499
1500     for (i = 0; i < self->blocks_count; ++i)
1501     {
1502         if (!ir_block_naive_phi(self->blocks[i]))
1503             return false;
1504     }
1505     return true;
1506 }
1507
1508 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1509 {
1510     ir_instr *instr;
1511     size_t i;
1512
1513     /* create a store */
1514     if (!ir_block_create_store(block, old, what))
1515         return false;
1516
1517     /* we now move it up */
1518     instr = block->instr[block->instr_count-1];
1519     for (i = block->instr_count; i > iid; --i)
1520         block->instr[i] = block->instr[i-1];
1521     block->instr[i] = instr;
1522
1523     return true;
1524 }
1525
1526 static bool ir_block_naive_phi(ir_block *self)
1527 {
1528     size_t i, p, w;
1529     /* FIXME: optionally, create_phi can add the phis
1530      * to a list so we don't need to loop through blocks
1531      * - anyway: "don't optimize YET"
1532      */
1533     for (i = 0; i < self->instr_count; ++i)
1534     {
1535         ir_instr *instr = self->instr[i];
1536         if (instr->opcode != VINSTR_PHI)
1537             continue;
1538
1539         if (!ir_block_instr_remove(self, i))
1540             return false;
1541         --i; /* NOTE: i+1 below */
1542
1543         for (p = 0; p < instr->phi_count; ++p)
1544         {
1545             ir_value *v = instr->phi[p].value;
1546             for (w = 0; w < v->writes_count; ++w) {
1547                 ir_value *old;
1548
1549                 if (!v->writes[w]->_ops[0])
1550                     continue;
1551
1552                 /* When the write was to a global, we have to emit a mov */
1553                 old = v->writes[w]->_ops[0];
1554
1555                 /* The original instruction now writes to the PHI target local */
1556                 if (v->writes[w]->_ops[0] == v)
1557                     v->writes[w]->_ops[0] = instr->_ops[0];
1558
1559                 if (old->store != store_value && old->store != store_local && old->store != store_param)
1560                 {
1561                     /* If it originally wrote to a global we need to store the value
1562                      * there as welli
1563                      */
1564                     if (!ir_naive_phi_emit_store(self, i+1, old, v))
1565                         return false;
1566                     if (i+1 < self->instr_count)
1567                         instr = self->instr[i+1];
1568                     else
1569                         instr = NULL;
1570                     /* In case I forget and access instr later, it'll be NULL
1571                      * when it's a problem, to make sure we crash, rather than accessing
1572                      * invalid data.
1573                      */
1574                 }
1575                 else
1576                 {
1577                     /* If it didn't, we can replace all reads by the phi target now. */
1578                     size_t r;
1579                     for (r = 0; r < old->reads_count; ++r)
1580                     {
1581                         size_t op;
1582                         ir_instr *ri = old->reads[r];
1583                         for (op = 0; op < ri->phi_count; ++op) {
1584                             if (ri->phi[op].value == old)
1585                                 ri->phi[op].value = v;
1586                         }
1587                         for (op = 0; op < 3; ++op) {
1588                             if (ri->_ops[op] == old)
1589                                 ri->_ops[op] = v;
1590                         }
1591                     }
1592                 }
1593             }
1594         }
1595         ir_instr_delete(instr);
1596     }
1597     return true;
1598 }
1599
1600 /***********************************************************************
1601  *IR Temp allocation code
1602  * Propagating value life ranges by walking through the function backwards
1603  * until no more changes are made.
1604  * In theory this should happen once more than once for every nested loop
1605  * level.
1606  * Though this implementation might run an additional time for if nests.
1607  */
1608
1609 typedef struct
1610 {
1611     ir_value* *v;
1612     size_t    v_count;
1613     size_t    v_alloc;
1614 } new_reads_t;
1615 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1616
1617 /* Enumerate instructions used by value's life-ranges
1618  */
1619 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1620 {
1621     size_t i;
1622     size_t eid = *_eid;
1623     for (i = 0; i < self->instr_count; ++i)
1624     {
1625         self->instr[i]->eid = eid++;
1626     }
1627     *_eid = eid;
1628 }
1629
1630 /* Enumerate blocks and instructions.
1631  * The block-enumeration is unordered!
1632  * We do not really use the block enumreation, however
1633  * the instruction enumeration is important for life-ranges.
1634  */
1635 void ir_function_enumerate(ir_function *self)
1636 {
1637     size_t i;
1638     size_t instruction_id = 0;
1639     for (i = 0; i < self->blocks_count; ++i)
1640     {
1641         self->blocks[i]->eid = i;
1642         self->blocks[i]->run_id = 0;
1643         ir_block_enumerate(self->blocks[i], &instruction_id);
1644     }
1645 }
1646
1647 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1648 bool ir_function_calculate_liferanges(ir_function *self)
1649 {
1650     size_t i;
1651     bool changed;
1652
1653     do {
1654         self->run_id++;
1655         changed = false;
1656         for (i = 0; i != self->blocks_count; ++i)
1657         {
1658             if (self->blocks[i]->is_return)
1659             {
1660                 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1661                     return false;
1662             }
1663         }
1664     } while (changed);
1665     return true;
1666 }
1667
1668 /* Local-value allocator
1669  * After finishing creating the liferange of all values used in a function
1670  * we can allocate their global-positions.
1671  * This is the counterpart to register-allocation in register machines.
1672  */
1673 typedef struct {
1674     MEM_VECTOR_MAKE(ir_value*, locals);
1675     MEM_VECTOR_MAKE(size_t,    sizes);
1676     MEM_VECTOR_MAKE(size_t,    positions);
1677 } function_allocator;
1678 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1679 MEM_VEC_FUNCTIONS(function_allocator, size_t,    sizes)
1680 MEM_VEC_FUNCTIONS(function_allocator, size_t,    positions)
1681
1682 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1683 {
1684     ir_value *slot;
1685     size_t vsize = type_sizeof[var->vtype];
1686
1687     slot = ir_value_var("reg", store_global, var->vtype);
1688     if (!slot)
1689         return false;
1690
1691     if (!ir_value_life_merge_into(slot, var))
1692         goto localerror;
1693
1694     if (!function_allocator_locals_add(alloc, slot))
1695         goto localerror;
1696
1697     if (!function_allocator_sizes_add(alloc, vsize))
1698         goto localerror;
1699
1700     return true;
1701
1702 localerror:
1703     ir_value_delete(slot);
1704     return false;
1705 }
1706
1707 bool ir_function_allocate_locals(ir_function *self)
1708 {
1709     size_t i, a;
1710     bool   retval = true;
1711     size_t pos;
1712
1713     ir_value *slot;
1714     const ir_value *v;
1715
1716     function_allocator alloc;
1717
1718     if (!self->locals_count)
1719         return true;
1720
1721     MEM_VECTOR_INIT(&alloc, locals);
1722     MEM_VECTOR_INIT(&alloc, sizes);
1723     MEM_VECTOR_INIT(&alloc, positions);
1724
1725     for (i = 0; i < self->locals_count; ++i)
1726     {
1727         if (!function_allocator_alloc(&alloc, self->locals[i]))
1728             goto error;
1729     }
1730
1731     /* Allocate a slot for any value that still exists */
1732     for (i = 0; i < self->values_count; ++i)
1733     {
1734         v = self->values[i];
1735
1736         if (!v->life_count)
1737             continue;
1738
1739         for (a = 0; a < alloc.locals_count; ++a)
1740         {
1741             slot = alloc.locals[a];
1742
1743             if (ir_values_overlap(v, slot))
1744                 continue;
1745
1746             if (!ir_value_life_merge_into(slot, v))
1747                 goto error;
1748
1749             /* adjust size for this slot */
1750             if (alloc.sizes[a] < type_sizeof[v->vtype])
1751                 alloc.sizes[a] = type_sizeof[v->vtype];
1752
1753             self->values[i]->code.local = a;
1754             break;
1755         }
1756         if (a >= alloc.locals_count) {
1757             self->values[i]->code.local = alloc.locals_count;
1758             if (!function_allocator_alloc(&alloc, v))
1759                 goto error;
1760         }
1761     }
1762
1763     /* Adjust slot positions based on sizes */
1764     if (!function_allocator_positions_add(&alloc, 0))
1765         goto error;
1766
1767     if (alloc.sizes_count)
1768         pos = alloc.positions[0] + alloc.sizes[0];
1769     else
1770         pos = 0;
1771     for (i = 1; i < alloc.sizes_count; ++i)
1772     {
1773         pos = alloc.positions[i-1] + alloc.sizes[i-1];
1774         if (!function_allocator_positions_add(&alloc, pos))
1775             goto error;
1776     }
1777
1778     self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1779
1780     /* Take over the actual slot positions */
1781     for (i = 0; i < self->values_count; ++i)
1782         self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1783
1784     goto cleanup;
1785
1786 error:
1787     retval = false;
1788 cleanup:
1789     for (i = 0; i < alloc.locals_count; ++i)
1790         ir_value_delete(alloc.locals[i]);
1791     MEM_VECTOR_CLEAR(&alloc, locals);
1792     MEM_VECTOR_CLEAR(&alloc, sizes);
1793     MEM_VECTOR_CLEAR(&alloc, positions);
1794     return retval;
1795 }
1796
1797 /* Get information about which operand
1798  * is read from, or written to.
1799  */
1800 static void ir_op_read_write(int op, size_t *read, size_t *write)
1801 {
1802     switch (op)
1803     {
1804     case VINSTR_JUMP:
1805     case INSTR_GOTO:
1806         *write = 0;
1807         *read = 0;
1808         break;
1809     case INSTR_IF:
1810     case INSTR_IFNOT:
1811 #if 0
1812     case INSTR_IF_S:
1813     case INSTR_IFNOT_S:
1814 #endif
1815     case INSTR_RETURN:
1816     case VINSTR_COND:
1817         *write = 0;
1818         *read = 1;
1819         break;
1820     default:
1821         *write = 1;
1822         *read = 6;
1823         break;
1824     };
1825 }
1826
1827 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1828 {
1829     size_t i;
1830     bool changed = false;
1831     bool tempbool;
1832     for (i = 0; i != self->living_count; ++i)
1833     {
1834         tempbool = ir_value_life_merge(self->living[i], eid);
1835         /* debug
1836         if (tempbool)
1837             fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1838         */
1839         changed = changed || tempbool;
1840     }
1841     return changed;
1842 }
1843
1844 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1845 {
1846     size_t i;
1847     /* values which have been read in a previous iteration are now
1848      * in the "living" array even if the previous block doesn't use them.
1849      * So we have to remove whatever does not exist in the previous block.
1850      * They will be re-added on-read, but the liferange merge won't cause
1851      * a change.
1852      */
1853     for (i = 0; i < self->living_count; ++i)
1854     {
1855         if (!ir_block_living_find(prev, self->living[i], NULL)) {
1856             if (!ir_block_living_remove(self, i))
1857                 return false;
1858             --i;
1859         }
1860     }
1861
1862     /* Whatever the previous block still has in its living set
1863      * must now be added to ours as well.
1864      */
1865     for (i = 0; i < prev->living_count; ++i)
1866     {
1867         if (ir_block_living_find(self, prev->living[i], NULL))
1868             continue;
1869         if (!ir_block_living_add(self, prev->living[i]))
1870             return false;
1871         /*
1872         printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1873         */
1874     }
1875     return true;
1876 }
1877
1878 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1879 {
1880     ir_instr *instr;
1881     ir_value *value;
1882     bool  tempbool;
1883     size_t i, o, p;
1884     /* bitmasks which operands are read from or written to */
1885     size_t read, write;
1886 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1887     size_t rd;
1888     new_reads_t new_reads;
1889 #endif
1890     char dbg_ind[16] = { '#', '0' };
1891     (void)dbg_ind;
1892
1893 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1894     MEM_VECTOR_INIT(&new_reads, v);
1895 #endif
1896
1897     if (prev)
1898     {
1899         if (!ir_block_life_prop_previous(self, prev, changed))
1900             return false;
1901     }
1902
1903     i = self->instr_count;
1904     while (i)
1905     { --i;
1906         instr = self->instr[i];
1907
1908         /* PHI operands are always read operands */
1909         for (p = 0; p < instr->phi_count; ++p)
1910         {
1911             value = instr->phi[p].value;
1912 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1913             if (!ir_block_living_find(self, value, NULL) &&
1914                 !ir_block_living_add(self, value))
1915             {
1916                 goto on_error;
1917             }
1918 #else
1919             if (!new_reads_t_v_find(&new_reads, value, NULL))
1920             {
1921                 if (!new_reads_t_v_add(&new_reads, value))
1922                     goto on_error;
1923             }
1924 #endif
1925         }
1926
1927         /* See which operands are read and write operands */
1928         ir_op_read_write(instr->opcode, &read, &write);
1929
1930         /* Go through the 3 main operands */
1931         for (o = 0; o < 3; ++o)
1932         {
1933             if (!instr->_ops[o]) /* no such operand */
1934                 continue;
1935
1936             value = instr->_ops[o];
1937
1938             /* We only care about locals */
1939             /* we also calculate parameter liferanges so that locals
1940              * can take up parameter slots */
1941             if (value->store != store_value &&
1942                 value->store != store_local &&
1943                 value->store != store_param)
1944                 continue;
1945
1946             /* read operands */
1947             if (read & (1<<o))
1948             {
1949 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1950                 if (!ir_block_living_find(self, value, NULL) &&
1951                     !ir_block_living_add(self, value))
1952                 {
1953                     goto on_error;
1954                 }
1955 #else
1956                 /* fprintf(stderr, "read: %s\n", value->_name); */
1957                 if (!new_reads_t_v_find(&new_reads, value, NULL))
1958                 {
1959                     if (!new_reads_t_v_add(&new_reads, value))
1960                         goto on_error;
1961                 }
1962 #endif
1963             }
1964
1965             /* write operands */
1966             /* When we write to a local, we consider it "dead" for the
1967              * remaining upper part of the function, since in SSA a value
1968              * can only be written once (== created)
1969              */
1970             if (write & (1<<o))
1971             {
1972                 size_t idx;
1973                 bool in_living = ir_block_living_find(self, value, &idx);
1974 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1975                 size_t readidx;
1976                 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1977                 if (!in_living && !in_reads)
1978 #else
1979                 if (!in_living)
1980 #endif
1981                 {
1982                     /* If the value isn't alive it hasn't been read before... */
1983                     /* TODO: See if the warning can be emitted during parsing or AST processing
1984                      * otherwise have warning printed here.
1985                      * IF printing a warning here: include filecontext_t,
1986                      * and make sure it's only printed once
1987                      * since this function is run multiple times.
1988                      */
1989                     /* For now: debug info: */
1990                     fprintf(stderr, "Value only written %s\n", value->name);
1991                     tempbool = ir_value_life_merge(value, instr->eid);
1992                     *changed = *changed || tempbool;
1993                     /*
1994                     ir_instr_dump(instr, dbg_ind, printf);
1995                     abort();
1996                     */
1997                 } else {
1998                     /* since 'living' won't contain it
1999                      * anymore, merge the value, since
2000                      * (A) doesn't.
2001                      */
2002                     tempbool = ir_value_life_merge(value, instr->eid);
2003                     /*
2004                     if (tempbool)
2005                         fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2006                     */
2007                     *changed = *changed || tempbool;
2008                     /* Then remove */
2009 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2010                     if (!ir_block_living_remove(self, idx))
2011                         goto on_error;
2012 #else
2013                     if (in_reads)
2014                     {
2015                         if (!new_reads_t_v_remove(&new_reads, readidx))
2016                             goto on_error;
2017                     }
2018 #endif
2019                 }
2020             }
2021         }
2022         /* (A) */
2023         tempbool = ir_block_living_add_instr(self, instr->eid);
2024         /*fprintf(stderr, "living added values\n");*/
2025         *changed = *changed || tempbool;
2026
2027 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2028         /* new reads: */
2029         for (rd = 0; rd < new_reads.v_count; ++rd)
2030         {
2031             if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2032                 if (!ir_block_living_add(self, new_reads.v[rd]))
2033                     goto on_error;
2034             }
2035             if (!i && !self->entries_count) {
2036                 /* fix the top */
2037                 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2038             }
2039         }
2040         MEM_VECTOR_CLEAR(&new_reads, v);
2041 #endif
2042     }
2043
2044     if (self->run_id == self->owner->run_id)
2045         return true;
2046
2047     self->run_id = self->owner->run_id;
2048
2049     for (i = 0; i < self->entries_count; ++i)
2050     {
2051         ir_block *entry = self->entries[i];
2052         ir_block_life_propagate(entry, self, changed);
2053     }
2054
2055     return true;
2056 on_error:
2057 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2058     MEM_VECTOR_CLEAR(&new_reads, v);
2059 #endif
2060     return false;
2061 }
2062
2063 /***********************************************************************
2064  *IR Code-Generation
2065  *
2066  * Since the IR has the convention of putting 'write' operands
2067  * at the beginning, we have to rotate the operands of instructions
2068  * properly in order to generate valid QCVM code.
2069  *
2070  * Having destinations at a fixed position is more convenient. In QC
2071  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
2072  * read from from OPA,  and store to OPB rather than OPC.   Which is
2073  * partially the reason why the implementation of these instructions
2074  * in darkplaces has been delayed for so long.
2075  *
2076  * Breaking conventions is annoying...
2077  */
2078 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2079
2080 static bool gen_global_field(ir_value *global)
2081 {
2082     if (global->isconst)
2083     {
2084         ir_value *fld = global->constval.vpointer;
2085         if (!fld) {
2086             printf("Invalid field constant with no field: %s\n", global->name);
2087             return false;
2088         }
2089
2090         /* Now, in this case, a relocation would be impossible to code
2091          * since it looks like this:
2092          * .vector v = origin;     <- parse error, wtf is 'origin'?
2093          * .vector origin;
2094          *
2095          * But we will need a general relocation support later anyway
2096          * for functions... might as well support that here.
2097          */
2098         if (!fld->code.globaladdr) {
2099             printf("FIXME: Relocation support\n");
2100             return false;
2101         }
2102
2103         /* copy the field's value */
2104         global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2105     }
2106     else
2107     {
2108         prog_section_field fld;
2109
2110         fld.name = global->code.name;
2111         fld.offset = code_fields_elements;
2112         fld.type = global->fieldtype;
2113
2114         if (fld.type == TYPE_VOID) {
2115             printf("Field is missing a type: %s\n", global->name);
2116             return false;
2117         }
2118
2119         if (code_fields_add(fld) < 0)
2120             return false;
2121
2122         global->code.globaladdr = code_globals_add(fld.offset);
2123     }
2124     if (global->code.globaladdr < 0)
2125         return false;
2126     return true;
2127 }
2128
2129 static bool gen_global_pointer(ir_value *global)
2130 {
2131     if (global->isconst)
2132     {
2133         ir_value *target = global->constval.vpointer;
2134         if (!target) {
2135             printf("Invalid pointer constant: %s\n", global->name);
2136             /* NULL pointers are pointing to the NULL constant, which also
2137              * sits at address 0, but still has an ir_value for itself.
2138              */
2139             return false;
2140         }
2141
2142         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2143          * void() foo; <- proto
2144          * void() *fooptr = &foo;
2145          * void() foo = { code }
2146          */
2147         if (!target->code.globaladdr) {
2148             /* FIXME: Check for the constant nullptr ir_value!
2149              * because then code.globaladdr being 0 is valid.
2150              */
2151             printf("FIXME: Relocation support\n");
2152             return false;
2153         }
2154
2155         global->code.globaladdr = code_globals_add(target->code.globaladdr);
2156     }
2157     else
2158     {
2159         global->code.globaladdr = code_globals_add(0);
2160     }
2161     if (global->code.globaladdr < 0)
2162         return false;
2163     return true;
2164 }
2165
2166 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2167 {
2168     prog_section_statement stmt;
2169     ir_instr *instr;
2170     ir_block *target;
2171     ir_block *ontrue;
2172     ir_block *onfalse;
2173     size_t    stidx;
2174     size_t    i;
2175
2176 tailcall:
2177     block->generated = true;
2178     block->code_start = code_statements_elements;
2179     for (i = 0; i < block->instr_count; ++i)
2180     {
2181         instr = block->instr[i];
2182
2183         if (instr->opcode == VINSTR_PHI) {
2184             printf("cannot generate virtual instruction (phi)\n");
2185             return false;
2186         }
2187
2188         if (instr->opcode == VINSTR_JUMP) {
2189             target = instr->bops[0];
2190             /* for uncoditional jumps, if the target hasn't been generated
2191              * yet, we generate them right here.
2192              */
2193             if (!target->generated) {
2194                 block = target;
2195                 goto tailcall;
2196             }
2197
2198             /* otherwise we generate a jump instruction */
2199             stmt.opcode = INSTR_GOTO;
2200             stmt.o1.s1 = (target->code_start) - code_statements_elements;
2201             stmt.o2.s1 = 0;
2202             stmt.o3.s1 = 0;
2203             if (code_statements_add(stmt) < 0)
2204                 return false;
2205
2206             /* no further instructions can be in this block */
2207             return true;
2208         }
2209
2210         if (instr->opcode == VINSTR_COND) {
2211             ontrue  = instr->bops[0];
2212             onfalse = instr->bops[1];
2213             /* TODO: have the AST signal which block should
2214              * come first: eg. optimize IFs without ELSE...
2215              */
2216
2217             stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2218             stmt.o2.u1 = 0;
2219             stmt.o3.s1 = 0;
2220
2221             if (ontrue->generated) {
2222                 stmt.opcode = INSTR_IF;
2223                 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2224                 if (code_statements_add(stmt) < 0)
2225                     return false;
2226             }
2227             if (onfalse->generated) {
2228                 stmt.opcode = INSTR_IFNOT;
2229                 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2230                 if (code_statements_add(stmt) < 0)
2231                     return false;
2232             }
2233             if (!ontrue->generated) {
2234                 if (onfalse->generated) {
2235                     block = ontrue;
2236                     goto tailcall;
2237                 }
2238             }
2239             if (!onfalse->generated) {
2240                 if (ontrue->generated) {
2241                     block = onfalse;
2242                     goto tailcall;
2243                 }
2244             }
2245             /* neither ontrue nor onfalse exist */
2246             stmt.opcode = INSTR_IFNOT;
2247             stidx = code_statements_elements;
2248             if (code_statements_add(stmt) < 0)
2249                 return false;
2250             /* on false we jump, so add ontrue-path */
2251             if (!gen_blocks_recursive(func, ontrue))
2252                 return false;
2253             /* fixup the jump address */
2254             code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2255             /* generate onfalse path */
2256             if (onfalse->generated) {
2257                 /* fixup the jump address */
2258                 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2259                 /* may have been generated in the previous recursive call */
2260                 stmt.opcode = INSTR_GOTO;
2261                 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2262                 stmt.o2.s1 = 0;
2263                 stmt.o3.s1 = 0;
2264                 return (code_statements_add(stmt) >= 0);
2265             }
2266             /* if not, generate now */
2267             block = onfalse;
2268             goto tailcall;
2269         }
2270
2271         if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2272             /* Trivial call translation:
2273              * copy all params to OFS_PARM*
2274              * if the output's storetype is not store_return,
2275              * add append a STORE instruction!
2276              *
2277              * NOTES on how to do it better without much trouble:
2278              * -) The liferanges!
2279              *      Simply check the liferange of all parameters for
2280              *      other CALLs. For each param with no CALL in its
2281              *      liferange, we can store it in an OFS_PARM at
2282              *      generation already. This would even include later
2283              *      reuse.... probably... :)
2284              */
2285             size_t p;
2286             ir_value *retvalue;
2287
2288             for (p = 0; p < instr->params_count; ++p)
2289             {
2290                 ir_value *param = instr->params[p];
2291
2292                 stmt.opcode = INSTR_STORE_F;
2293                 stmt.o3.u1 = 0;
2294
2295                 stmt.opcode = type_store_instr[param->vtype];
2296                 stmt.o1.u1 = param->code.globaladdr;
2297                 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2298                 if (code_statements_add(stmt) < 0)
2299                     return false;
2300             }
2301             stmt.opcode = INSTR_CALL0 + instr->params_count;
2302             if (stmt.opcode > INSTR_CALL8)
2303                 stmt.opcode = INSTR_CALL8;
2304             stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2305             stmt.o2.u1 = 0;
2306             stmt.o3.u1 = 0;
2307             if (code_statements_add(stmt) < 0)
2308                 return false;
2309
2310             retvalue = instr->_ops[0];
2311             if (retvalue && retvalue->store != store_return && retvalue->life_count)
2312             {
2313                 /* not to be kept in OFS_RETURN */
2314                 stmt.opcode = type_store_instr[retvalue->vtype];
2315                 stmt.o1.u1 = OFS_RETURN;
2316                 stmt.o2.u1 = retvalue->code.globaladdr;
2317                 stmt.o3.u1 = 0;
2318                 if (code_statements_add(stmt) < 0)
2319                     return false;
2320             }
2321             continue;
2322         }
2323
2324         if (instr->opcode == INSTR_STATE) {
2325             printf("TODO: state instruction\n");
2326             return false;
2327         }
2328
2329         stmt.opcode = instr->opcode;
2330         stmt.o1.u1 = 0;
2331         stmt.o2.u1 = 0;
2332         stmt.o3.u1 = 0;
2333
2334         /* This is the general order of operands */
2335         if (instr->_ops[0])
2336             stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2337
2338         if (instr->_ops[1])
2339             stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2340
2341         if (instr->_ops[2])
2342             stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2343
2344         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2345         {
2346             stmt.o1.u1 = stmt.o3.u1;
2347             stmt.o3.u1 = 0;
2348         }
2349         else if (stmt.opcode >= INSTR_STORE_F &&
2350                  stmt.opcode <= INSTR_STORE_FNC)
2351         {
2352             /* 2-operand instructions with A -> B */
2353             stmt.o2.u1 = stmt.o3.u1;
2354             stmt.o3.u1 = 0;
2355         }
2356
2357         if (code_statements_add(stmt) < 0)
2358             return false;
2359     }
2360     return true;
2361 }
2362
2363 static bool gen_function_code(ir_function *self)
2364 {
2365     ir_block *block;
2366     prog_section_statement stmt;
2367
2368     /* Starting from entry point, we generate blocks "as they come"
2369      * for now. Dead blocks will not be translated obviously.
2370      */
2371     if (!self->blocks_count) {
2372         printf("Function '%s' declared without body.\n", self->name);
2373         return false;
2374     }
2375
2376     block = self->blocks[0];
2377     if (block->generated)
2378         return true;
2379
2380     if (!gen_blocks_recursive(self, block)) {
2381         printf("failed to generate blocks for '%s'\n", self->name);
2382         return false;
2383     }
2384
2385     /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2386     stmt.opcode = AINSTR_END;
2387     stmt.o1.u1 = 0;
2388     stmt.o2.u1 = 0;
2389     stmt.o3.u1 = 0;
2390     if (code_statements_add(stmt) < 0)
2391         return false;
2392     return true;
2393 }
2394
2395 static bool gen_global_function(ir_builder *ir, ir_value *global)
2396 {
2397     prog_section_function fun;
2398     ir_function          *irfun;
2399
2400     size_t i;
2401     size_t local_var_end;
2402
2403     if (!global->isconst || (!global->constval.vfunc))
2404     {
2405         printf("Invalid state of function-global: not constant: %s\n", global->name);
2406         return false;
2407     }
2408
2409     irfun = global->constval.vfunc;
2410
2411     fun.name    = global->code.name;
2412     fun.file    = code_cachedstring(global->context.file);
2413     fun.profile = 0; /* always 0 */
2414     fun.nargs   = irfun->params_count;
2415
2416     for (i = 0;i < 8; ++i) {
2417         if (i >= fun.nargs)
2418             fun.argsize[i] = 0;
2419         else
2420             fun.argsize[i] = type_sizeof[irfun->params[i]];
2421     }
2422
2423     fun.firstlocal = code_globals_elements;
2424     fun.locals     = irfun->allocated_locals + irfun->locals_count;
2425
2426     local_var_end = 0;
2427     for (i = 0; i < irfun->locals_count; ++i) {
2428         if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2429             printf("Failed to generate global %s\n", irfun->locals[i]->name);
2430             return false;
2431         }
2432     }
2433     if (irfun->locals_count) {
2434         ir_value *last = irfun->locals[irfun->locals_count-1];
2435         local_var_end = last->code.globaladdr;
2436         local_var_end += type_sizeof[last->vtype];
2437     }
2438     for (i = 0; i < irfun->values_count; ++i)
2439     {
2440         /* generate code.globaladdr for ssa values */
2441         ir_value *v = irfun->values[i];
2442         v->code.globaladdr = local_var_end + v->code.local;
2443     }
2444     for (i = 0; i < irfun->locals_count; ++i) {
2445         /* fill the locals with zeros */
2446         code_globals_add(0);
2447     }
2448
2449     if (irfun->builtin)
2450         fun.entry = irfun->builtin;
2451     else {
2452         fun.entry = code_statements_elements;
2453         if (!gen_function_code(irfun)) {
2454             printf("Failed to generate code for function %s\n", irfun->name);
2455             return false;
2456         }
2457     }
2458
2459     return (code_functions_add(fun) >= 0);
2460 }
2461
2462 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2463 {
2464     size_t           i;
2465     int32_t         *iptr;
2466     prog_section_def def;
2467
2468     def.type   = global->vtype;
2469     def.offset = code_globals_elements;
2470     def.name   = global->code.name       = code_genstring(global->name);
2471
2472     switch (global->vtype)
2473     {
2474     case TYPE_POINTER:
2475         if (code_defs_add(def) < 0)
2476             return false;
2477         return gen_global_pointer(global);
2478     case TYPE_FIELD:
2479         if (code_defs_add(def) < 0)
2480             return false;
2481         return gen_global_field(global);
2482     case TYPE_ENTITY:
2483         /* fall through */
2484     case TYPE_FLOAT:
2485     {
2486         if (code_defs_add(def) < 0)
2487             return false;
2488
2489         if (global->isconst) {
2490             iptr = (int32_t*)&global->constval.vfloat;
2491             global->code.globaladdr = code_globals_add(*iptr);
2492         } else
2493             global->code.globaladdr = code_globals_add(0);
2494
2495         return global->code.globaladdr >= 0;
2496     }
2497     case TYPE_STRING:
2498     {
2499         if (code_defs_add(def) < 0)
2500             return false;
2501         if (global->isconst)
2502             global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2503         else
2504             global->code.globaladdr = code_globals_add(0);
2505         return global->code.globaladdr >= 0;
2506     }
2507     case TYPE_VECTOR:
2508     case TYPE_QUATERNION:
2509     case TYPE_MATRIX:
2510     {
2511         size_t d;
2512         if (code_defs_add(def) < 0)
2513             return false;
2514
2515         if (global->isconst) {
2516             iptr = (int32_t*)&global->constval.vvec;
2517             global->code.globaladdr = code_globals_add(iptr[0]);
2518             if (global->code.globaladdr < 0)
2519                 return false;
2520             for (d = 1; d < type_sizeof[global->vtype]; ++d)
2521             {
2522                 if (code_globals_add(iptr[d]) < 0)
2523                     return false;
2524             }
2525         } else {
2526             global->code.globaladdr = code_globals_add(0);
2527             if (global->code.globaladdr < 0)
2528                 return false;
2529             for (d = 1; d < type_sizeof[global->vtype]; ++d)
2530             {
2531                 if (code_globals_add(0) < 0)
2532                     return false;
2533             }
2534         }
2535         return global->code.globaladdr >= 0;
2536     }
2537     case TYPE_FUNCTION:
2538         if (code_defs_add(def) < 0)
2539             return false;
2540         global->code.globaladdr = code_globals_elements;
2541         code_globals_add(code_functions_elements);
2542         return gen_global_function(self, global);
2543     case TYPE_VARIANT:
2544         /* assume biggest type */
2545             global->code.globaladdr = code_globals_add(0);
2546             for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2547                 code_globals_add(0);
2548             return true;
2549     default:
2550         /* refuse to create 'void' type or any other fancy business. */
2551         printf("Invalid type for global variable %s\n", global->name);
2552         return false;
2553     }
2554 }
2555
2556 bool ir_builder_generate(ir_builder *self, const char *filename)
2557 {
2558     size_t i;
2559
2560     code_init();
2561
2562     for (i = 0; i < self->globals_count; ++i)
2563     {
2564         if (!ir_builder_gen_global(self, self->globals[i])) {
2565             return false;
2566         }
2567     }
2568
2569     printf("writing '%s'...\n", filename);
2570     return code_write(filename);
2571 }
2572
2573 /***********************************************************************
2574  *IR DEBUG Dump functions...
2575  */
2576
2577 #define IND_BUFSZ 1024
2578
2579 const char *qc_opname(int op)
2580 {
2581     if (op < 0) return "<INVALID>";
2582     if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2583         return asm_instr[op].m;
2584     switch (op) {
2585         case VINSTR_PHI:  return "PHI";
2586         case VINSTR_JUMP: return "JUMP";
2587         case VINSTR_COND: return "COND";
2588         default:          return "<UNK>";
2589     }
2590 }
2591
2592 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2593 {
2594         size_t i;
2595         char indent[IND_BUFSZ];
2596         indent[0] = '\t';
2597         indent[1] = 0;
2598
2599         oprintf("module %s\n", b->name);
2600         for (i = 0; i < b->globals_count; ++i)
2601         {
2602                 oprintf("global ");
2603                 if (b->globals[i]->isconst)
2604                         oprintf("%s = ", b->globals[i]->name);
2605                 ir_value_dump(b->globals[i], oprintf);
2606                 oprintf("\n");
2607         }
2608         for (i = 0; i < b->functions_count; ++i)
2609                 ir_function_dump(b->functions[i], indent, oprintf);
2610         oprintf("endmodule %s\n", b->name);
2611 }
2612
2613 void ir_function_dump(ir_function *f, char *ind,
2614                       int (*oprintf)(const char*, ...))
2615 {
2616         size_t i;
2617         if (f->builtin != 0) {
2618             oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2619             return;
2620         }
2621         oprintf("%sfunction %s\n", ind, f->name);
2622         strncat(ind, "\t", IND_BUFSZ);
2623         if (f->locals_count)
2624         {
2625                 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2626                 for (i = 0; i < f->locals_count; ++i) {
2627                         oprintf("%s\t", ind);
2628                         ir_value_dump(f->locals[i], oprintf);
2629                         oprintf("\n");
2630                 }
2631         }
2632         if (f->blocks_count)
2633         {
2634                 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2635                 for (i = 0; i < f->blocks_count; ++i) {
2636                     if (f->blocks[i]->run_id != f->run_id) {
2637                         oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2638                     }
2639                         ir_block_dump(f->blocks[i], ind, oprintf);
2640                 }
2641
2642         }
2643         ind[strlen(ind)-1] = 0;
2644         oprintf("%sendfunction %s\n", ind, f->name);
2645 }
2646
2647 void ir_block_dump(ir_block* b, char *ind,
2648                    int (*oprintf)(const char*, ...))
2649 {
2650         size_t i;
2651         oprintf("%s:%s\n", ind, b->label);
2652         strncat(ind, "\t", IND_BUFSZ);
2653
2654         for (i = 0; i < b->instr_count; ++i)
2655                 ir_instr_dump(b->instr[i], ind, oprintf);
2656         ind[strlen(ind)-1] = 0;
2657 }
2658
2659 void dump_phi(ir_instr *in, char *ind,
2660               int (*oprintf)(const char*, ...))
2661 {
2662         size_t i;
2663         oprintf("%s <- phi ", in->_ops[0]->name);
2664         for (i = 0; i < in->phi_count; ++i)
2665         {
2666                 oprintf("([%s] : %s) ", in->phi[i].from->label,
2667                                         in->phi[i].value->name);
2668         }
2669         oprintf("\n");
2670 }
2671
2672 void ir_instr_dump(ir_instr *in, char *ind,
2673                        int (*oprintf)(const char*, ...))
2674 {
2675         size_t i;
2676         const char *comma = NULL;
2677
2678         oprintf("%s (%i) ", ind, (int)in->eid);
2679
2680         if (in->opcode == VINSTR_PHI) {
2681                 dump_phi(in, ind, oprintf);
2682                 return;
2683         }
2684
2685         strncat(ind, "\t", IND_BUFSZ);
2686
2687         if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2688                 ir_value_dump(in->_ops[0], oprintf);
2689                 if (in->_ops[1] || in->_ops[2])
2690                         oprintf(" <- ");
2691         }
2692         oprintf("%s\t", qc_opname(in->opcode));
2693         if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2694                 ir_value_dump(in->_ops[0], oprintf);
2695                 comma = ",\t";
2696         }
2697         else
2698         {
2699                 for (i = 1; i != 3; ++i) {
2700                         if (in->_ops[i]) {
2701                                 if (comma)
2702                                         oprintf(comma);
2703                                 ir_value_dump(in->_ops[i], oprintf);
2704                                 comma = ",\t";
2705                         }
2706                 }
2707         }
2708         if (in->bops[0]) {
2709                 if (comma)
2710                         oprintf(comma);
2711                 oprintf("[%s]", in->bops[0]->label);
2712                 comma = ",\t";
2713         }
2714         if (in->bops[1])
2715                 oprintf("%s[%s]", comma, in->bops[1]->label);
2716         oprintf("\n");
2717         ind[strlen(ind)-1] = 0;
2718 }
2719
2720 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2721 {
2722         if (v->isconst) {
2723                 switch (v->vtype) {
2724                     default:
2725                         case TYPE_VOID:
2726                                 oprintf("(void)");
2727                                 break;
2728                         case TYPE_FLOAT:
2729                                 oprintf("%g", v->constval.vfloat);
2730                                 break;
2731                         case TYPE_VECTOR:
2732                                 oprintf("'%g %g %g'",
2733                                         v->constval.vvec.x,
2734                                         v->constval.vvec.y,
2735                                         v->constval.vvec.z);
2736                                 break;
2737                         case TYPE_ENTITY:
2738                                 oprintf("(entity)");
2739                                 break;
2740                         case TYPE_STRING:
2741                                 oprintf("\"%s\"", v->constval.vstring);
2742                                 break;
2743 #if 0
2744                         case TYPE_INTEGER:
2745                                 oprintf("%i", v->constval.vint);
2746                                 break;
2747 #endif
2748                         case TYPE_POINTER:
2749                                 oprintf("&%s",
2750                                         v->constval.vpointer->name);
2751                                 break;
2752                 }
2753         } else {
2754                 oprintf("%s", v->name);
2755         }
2756 }
2757
2758 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2759 {
2760         size_t i;
2761         oprintf("Life of %s:\n", self->name);
2762         for (i = 0; i < self->life_count; ++i)
2763         {
2764                 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
2765         }
2766 }