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