]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
make it also compilable with -std=c99 by not redefining extra_semicolon_, by appendin...
[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 ir_value* ir_value_var(const char *name, int storetype, int vtype)
523 {
524     ir_value *self;
525     self = (ir_value*)mem_a(sizeof(*self));
526     self->vtype = vtype;
527     self->fieldtype = TYPE_VOID;
528     self->outtype = TYPE_VOID;
529     self->store = storetype;
530     MEM_VECTOR_INIT(self, reads);
531     MEM_VECTOR_INIT(self, writes);
532     self->isconst = false;
533     self->context.file = "<@no context>";
534     self->context.line = 0;
535     self->name = NULL;
536     ir_value_set_name(self, name);
537
538     memset(&self->constval, 0, sizeof(self->constval));
539     memset(&self->code,     0, sizeof(self->code));
540
541     MEM_VECTOR_INIT(self, life);
542     return self;
543 }
544 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
545 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
546 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
547
548 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
549 {
550     ir_value *v = ir_value_var(name, storetype, vtype);
551     if (!v)
552         return NULL;
553     if (!ir_function_collect_value(owner, v))
554     {
555         ir_value_delete(v);
556         return NULL;
557     }
558     return v;
559 }
560
561 void ir_value_delete(ir_value* self)
562 {
563     if (self->name)
564         mem_d((void*)self->name);
565     if (self->isconst)
566     {
567         if (self->vtype == TYPE_STRING)
568             mem_d((void*)self->constval.vstring);
569     }
570     MEM_VECTOR_CLEAR(self, reads);
571     MEM_VECTOR_CLEAR(self, writes);
572     MEM_VECTOR_CLEAR(self, life);
573     mem_d(self);
574 }
575
576 void ir_value_set_name(ir_value *self, const char *name)
577 {
578     if (self->name)
579         mem_d((void*)self->name);
580     self->name = util_strdup(name);
581 }
582
583 bool ir_value_set_float(ir_value *self, float f)
584 {
585     if (self->vtype != TYPE_FLOAT)
586         return false;
587     self->constval.vfloat = f;
588     self->isconst = true;
589     return true;
590 }
591
592 bool ir_value_set_func(ir_value *self, int f)
593 {
594     if (self->vtype != TYPE_FUNCTION)
595         return false;
596     self->constval.vint = f;
597     self->isconst = true;
598     return true;
599 }
600
601 bool ir_value_set_vector(ir_value *self, vector v)
602 {
603     if (self->vtype != TYPE_VECTOR)
604         return false;
605     self->constval.vvec = v;
606     self->isconst = true;
607     return true;
608 }
609
610 bool ir_value_set_string(ir_value *self, const char *str)
611 {
612     if (self->vtype != TYPE_STRING)
613         return false;
614     self->constval.vstring = util_strdup(str);
615     self->isconst = true;
616     return true;
617 }
618
619 #if 0
620 bool ir_value_set_int(ir_value *self, int i)
621 {
622     if (self->vtype != TYPE_INTEGER)
623         return false;
624     self->constval.vint = i;
625     self->isconst = true;
626     return true;
627 }
628 #endif
629
630 bool ir_value_lives(ir_value *self, size_t at)
631 {
632     size_t i;
633     for (i = 0; i < self->life_count; ++i)
634     {
635         ir_life_entry_t *life = &self->life[i];
636         if (life->start <= at && at <= life->end)
637             return true;
638         if (life->start > at) /* since it's ordered */
639             return false;
640     }
641     return false;
642 }
643
644 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
645 {
646     size_t k;
647     if (!ir_value_life_add(self, e)) /* naive... */
648         return false;
649     for (k = self->life_count-1; k > idx; --k)
650         self->life[k] = self->life[k-1];
651     self->life[idx] = e;
652     return true;
653 }
654
655 bool ir_value_life_merge(ir_value *self, size_t s)
656 {
657     size_t i;
658     ir_life_entry_t *life = NULL;
659     ir_life_entry_t *before = NULL;
660     ir_life_entry_t new_entry;
661
662     /* Find the first range >= s */
663     for (i = 0; i < self->life_count; ++i)
664     {
665         before = life;
666         life = &self->life[i];
667         if (life->start > s)
668             break;
669     }
670     /* nothing found? append */
671     if (i == self->life_count) {
672         ir_life_entry_t e;
673         if (life && life->end+1 == s)
674         {
675             /* previous life range can be merged in */
676             life->end++;
677             return true;
678         }
679         if (life && life->end >= s)
680             return false;
681         e.start = e.end = s;
682         if (!ir_value_life_add(self, e))
683             return false; /* failing */
684         return true;
685     }
686     /* found */
687     if (before)
688     {
689         if (before->end + 1 == s &&
690             life->start - 1 == s)
691         {
692             /* merge */
693             before->end = life->end;
694             if (!ir_value_life_remove(self, i))
695                 return false; /* failing */
696             return true;
697         }
698         if (before->end + 1 == s)
699         {
700             /* extend before */
701             before->end++;
702             return true;
703         }
704         /* already contained */
705         if (before->end >= s)
706             return false;
707     }
708     /* extend */
709     if (life->start - 1 == s)
710     {
711         life->start--;
712         return true;
713     }
714     /* insert a new entry */
715     new_entry.start = new_entry.end = s;
716     return ir_value_life_insert(self, i, new_entry);
717 }
718
719 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
720 {
721     size_t i, myi;
722
723     if (!other->life_count)
724         return true;
725
726     if (!self->life_count) {
727         for (i = 0; i < other->life_count; ++i) {
728             if (!ir_value_life_add(self, other->life[i]))
729                 return false;
730         }
731         return true;
732     }
733
734     myi = 0;
735     for (i = 0; i < other->life_count; ++i)
736     {
737         const ir_life_entry_t *life = &other->life[i];
738         while (true)
739         {
740             ir_life_entry_t *entry = &self->life[myi];
741
742             if (life->end+1 < entry->start)
743             {
744                 /* adding an interval before entry */
745                 if (!ir_value_life_insert(self, myi, *life))
746                     return false;
747                 ++myi;
748                 break;
749             }
750
751             if (life->start <  entry->start &&
752                 life->end   >= entry->start)
753             {
754                 /* starts earlier and overlaps */
755                 entry->start = life->start;
756             }
757
758             if (life->end     >  entry->end &&
759                 life->start-1 <= entry->end)
760             {
761                 /* ends later and overlaps */
762                 entry->end = life->end;
763             }
764
765             /* see if our change combines it with the next ranges */
766             while (myi+1 < self->life_count &&
767                    entry->end+1 >= self->life[1+myi].start)
768             {
769                 /* overlaps with (myi+1) */
770                 if (entry->end < self->life[1+myi].end)
771                     entry->end = self->life[1+myi].end;
772                 if (!ir_value_life_remove(self, myi+1))
773                     return false;
774                 entry = &self->life[myi];
775             }
776
777             /* see if we're after the entry */
778             if (life->start > entry->end)
779             {
780                 ++myi;
781                 /* append if we're at the end */
782                 if (myi >= self->life_count) {
783                     if (!ir_value_life_add(self, *life))
784                         return false;
785                     break;
786                 }
787                 /* otherweise check the next range */
788                 continue;
789             }
790             break;
791         }
792     }
793     return true;
794 }
795
796 bool ir_values_overlap(const ir_value *a, const ir_value *b)
797 {
798     /* For any life entry in A see if it overlaps with
799      * any life entry in B.
800      * Note that the life entries are orderes, so we can make a
801      * more efficient algorithm there than naively translating the
802      * statement above.
803      */
804
805     ir_life_entry_t *la, *lb, *enda, *endb;
806
807     /* first of all, if either has no life range, they cannot clash */
808     if (!a->life_count || !b->life_count)
809         return false;
810
811     la = a->life;
812     lb = b->life;
813     enda = la + a->life_count;
814     endb = lb + b->life_count;
815     while (true)
816     {
817         /* check if the entries overlap, for that,
818          * both must start before the other one ends.
819          */
820 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
821         if (la->start <= lb->end &&
822             lb->start <= la->end)
823 #else
824         if (la->start <  lb->end &&
825             lb->start <  la->end)
826 #endif
827         {
828             return true;
829         }
830
831         /* entries are ordered
832          * one entry is earlier than the other
833          * that earlier entry will be moved forward
834          */
835         if (la->start < lb->start)
836         {
837             /* order: A B, move A forward
838              * check if we hit the end with A
839              */
840             if (++la == enda)
841                 break;
842         }
843         else if (lb->start < la->start)
844         {
845             /* order: B A, move B forward
846              * check if we hit the end with B
847              */
848             if (++lb == endb)
849                 break;
850         }
851     }
852     return false;
853 }
854
855 /***********************************************************************
856  *IR main operations
857  */
858
859 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
860 {
861     if (target->store == store_value) {
862         fprintf(stderr, "cannot store to an SSA value\n");
863         fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
864         return false;
865     } else {
866         ir_instr *in = ir_instr_new(self, op);
867         if (!in)
868             return false;
869         if (!ir_instr_op(in, 0, target, true) ||
870             !ir_instr_op(in, 1, what, false)  ||
871             !ir_block_instr_add(self, in) )
872         {
873             return false;
874         }
875         return true;
876     }
877 }
878
879 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
880 {
881     int op = 0;
882     int vtype;
883     if (target->vtype == TYPE_VARIANT)
884         vtype = what->vtype;
885     else
886         vtype = target->vtype;
887
888 #if 0
889     if      (vtype == TYPE_FLOAT   && what->vtype == TYPE_INTEGER)
890         op = INSTR_CONV_ITOF;
891     else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
892         op = INSTR_CONV_FTOI;
893 #endif
894         op = type_store_instr[vtype];
895
896     return ir_block_create_store_op(self, op, target, what);
897 }
898
899 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
900 {
901     int op = 0;
902     int vtype;
903
904     if (target->vtype != TYPE_POINTER)
905         return false;
906
907     /* storing using pointer - target is a pointer, type must be
908      * inferred from source
909      */
910     vtype = what->vtype;
911
912     op = type_storep_instr[vtype];
913
914     return ir_block_create_store_op(self, op, target, what);
915 }
916
917 bool ir_block_create_return(ir_block *self, ir_value *v)
918 {
919     ir_instr *in;
920     if (self->final) {
921         fprintf(stderr, "block already ended (%s)\n", self->label);
922         return false;
923     }
924     self->final = true;
925     self->is_return = true;
926     in = ir_instr_new(self, INSTR_RETURN);
927     if (!in)
928         return false;
929
930     if (!ir_instr_op(in, 0, v, false) ||
931         !ir_block_instr_add(self, in) )
932     {
933         return false;
934     }
935     return true;
936 }
937
938 bool ir_block_create_if(ir_block *self, ir_value *v,
939                         ir_block *ontrue, ir_block *onfalse)
940 {
941     ir_instr *in;
942     if (self->final) {
943         fprintf(stderr, "block already ended (%s)\n", self->label);
944         return false;
945     }
946     self->final = true;
947     /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
948     in = ir_instr_new(self, VINSTR_COND);
949     if (!in)
950         return false;
951
952     if (!ir_instr_op(in, 0, v, false)) {
953         ir_instr_delete(in);
954         return false;
955     }
956
957     in->bops[0] = ontrue;
958     in->bops[1] = onfalse;
959
960     if (!ir_block_instr_add(self, in))
961         return false;
962
963     if (!ir_block_exits_add(self, ontrue)    ||
964         !ir_block_exits_add(self, onfalse)   ||
965         !ir_block_entries_add(ontrue, self)  ||
966         !ir_block_entries_add(onfalse, self) )
967     {
968         return false;
969     }
970     return true;
971 }
972
973 bool ir_block_create_jump(ir_block *self, ir_block *to)
974 {
975     ir_instr *in;
976     if (self->final) {
977         fprintf(stderr, "block already ended (%s)\n", self->label);
978         return false;
979     }
980     self->final = true;
981     in = ir_instr_new(self, VINSTR_JUMP);
982     if (!in)
983         return false;
984
985     in->bops[0] = to;
986     if (!ir_block_instr_add(self, in))
987         return false;
988
989     if (!ir_block_exits_add(self, to) ||
990         !ir_block_entries_add(to, self) )
991     {
992         return false;
993     }
994     return true;
995 }
996
997 bool ir_block_create_goto(ir_block *self, ir_block *to)
998 {
999     ir_instr *in;
1000     if (self->final) {
1001         fprintf(stderr, "block already ended (%s)\n", self->label);
1002         return false;
1003     }
1004     self->final = true;
1005     in = ir_instr_new(self, INSTR_GOTO);
1006     if (!in)
1007         return false;
1008
1009     in->bops[0] = to;
1010     if (!ir_block_instr_add(self, in))
1011         return false;
1012
1013     if (!ir_block_exits_add(self, to) ||
1014         !ir_block_entries_add(to, self) )
1015     {
1016         return false;
1017     }
1018     return true;
1019 }
1020
1021 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1022 {
1023     ir_value *out;
1024     ir_instr *in;
1025     in = ir_instr_new(self, VINSTR_PHI);
1026     if (!in)
1027         return NULL;
1028     out = ir_value_out(self->owner, label, store_value, ot);
1029     if (!out) {
1030         ir_instr_delete(in);
1031         return NULL;
1032     }
1033     if (!ir_instr_op(in, 0, out, true)) {
1034         ir_instr_delete(in);
1035         ir_value_delete(out);
1036         return NULL;
1037     }
1038     if (!ir_block_instr_add(self, in)) {
1039         ir_instr_delete(in);
1040         ir_value_delete(out);
1041         return NULL;
1042     }
1043     return in;
1044 }
1045
1046 ir_value* ir_phi_value(ir_instr *self)
1047 {
1048     return self->_ops[0];
1049 }
1050
1051 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1052 {
1053     ir_phi_entry_t pe;
1054
1055     if (!ir_block_entries_find(self->owner, b, NULL)) {
1056         /* Must not be possible to cause this, otherwise the AST
1057          * is doing something wrong.
1058          */
1059         fprintf(stderr, "Invalid entry block for PHI\n");
1060         abort();
1061     }
1062
1063     pe.value = v;
1064     pe.from = b;
1065     if (!ir_value_reads_add(v, self))
1066         return false;
1067     return ir_instr_phi_add(self, pe);
1068 }
1069
1070 /* call related code */
1071 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1072 {
1073     ir_value *out;
1074     ir_instr *in;
1075     in = ir_instr_new(self, INSTR_CALL0);
1076     if (!in)
1077         return NULL;
1078     out = ir_value_out(self->owner, label, store_return, func->outtype);
1079     if (!out) {
1080         ir_instr_delete(in);
1081         return NULL;
1082     }
1083     if (!ir_instr_op(in, 0, out, true) ||
1084         !ir_instr_op(in, 1, func, false) ||
1085         !ir_block_instr_add(self, in))
1086     {
1087         ir_instr_delete(in);
1088         ir_value_delete(out);
1089         return NULL;
1090     }
1091     return in;
1092 }
1093
1094 ir_value* ir_call_value(ir_instr *self)
1095 {
1096     return self->_ops[0];
1097 }
1098
1099 bool ir_call_param(ir_instr* self, ir_value *v)
1100 {
1101     if (!ir_instr_params_add(self, v))
1102         return false;
1103     if (!ir_value_reads_add(v, self)) {
1104         if (!ir_instr_params_remove(self, self->params_count-1))
1105             GMQCC_SUPPRESS_EMPTY_BODY;
1106         return false;
1107     }
1108     return true;
1109 }
1110
1111 /* binary op related code */
1112
1113 ir_value* ir_block_create_binop(ir_block *self,
1114                                 const char *label, int opcode,
1115                                 ir_value *left, ir_value *right)
1116 {
1117     int ot = TYPE_VOID;
1118     switch (opcode) {
1119         case INSTR_ADD_F:
1120         case INSTR_SUB_F:
1121         case INSTR_DIV_F:
1122         case INSTR_MUL_F:
1123         case INSTR_MUL_V:
1124         case INSTR_AND:
1125         case INSTR_OR:
1126 #if 0
1127         case INSTR_AND_I:
1128         case INSTR_AND_IF:
1129         case INSTR_AND_FI:
1130         case INSTR_OR_I:
1131         case INSTR_OR_IF:
1132         case INSTR_OR_FI:
1133 #endif
1134         case INSTR_BITAND:
1135         case INSTR_BITOR:
1136 #if 0
1137         case INSTR_SUB_S: /* -- offset of string as float */
1138         case INSTR_MUL_IF:
1139         case INSTR_MUL_FI:
1140         case INSTR_DIV_IF:
1141         case INSTR_DIV_FI:
1142         case INSTR_BITOR_IF:
1143         case INSTR_BITOR_FI:
1144         case INSTR_BITAND_FI:
1145         case INSTR_BITAND_IF:
1146         case INSTR_EQ_I:
1147         case INSTR_NE_I:
1148 #endif
1149             ot = TYPE_FLOAT;
1150             break;
1151 #if 0
1152         case INSTR_ADD_I:
1153         case INSTR_ADD_IF:
1154         case INSTR_ADD_FI:
1155         case INSTR_SUB_I:
1156         case INSTR_SUB_FI:
1157         case INSTR_SUB_IF:
1158         case INSTR_MUL_I:
1159         case INSTR_DIV_I:
1160         case INSTR_BITAND_I:
1161         case INSTR_BITOR_I:
1162         case INSTR_XOR_I:
1163         case INSTR_RSHIFT_I:
1164         case INSTR_LSHIFT_I:
1165             ot = TYPE_INTEGER;
1166             break;
1167 #endif
1168         case INSTR_ADD_V:
1169         case INSTR_SUB_V:
1170         case INSTR_MUL_VF:
1171         case INSTR_MUL_FV:
1172 #if 0
1173         case INSTR_DIV_VF:
1174         case INSTR_MUL_IV:
1175         case INSTR_MUL_VI:
1176 #endif
1177             ot = TYPE_VECTOR;
1178             break;
1179 #if 0
1180         case INSTR_ADD_SF:
1181             ot = TYPE_POINTER;
1182             break;
1183 #endif
1184         default:
1185             /* ranges: */
1186             /* boolean operations result in floats */
1187             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1188                 ot = TYPE_FLOAT;
1189             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1190                 ot = TYPE_FLOAT;
1191 #if 0
1192             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1193                 ot = TYPE_FLOAT;
1194 #endif
1195             break;
1196     };
1197     if (ot == TYPE_VOID) {
1198         /* The AST or parser were supposed to check this! */
1199         return NULL;
1200     }
1201
1202     return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1203 }
1204
1205 ir_value* ir_block_create_unary(ir_block *self,
1206                                 const char *label, int opcode,
1207                                 ir_value *operand)
1208 {
1209     int ot = TYPE_FLOAT;
1210     switch (opcode) {
1211         case INSTR_NOT_F:
1212         case INSTR_NOT_V:
1213         case INSTR_NOT_S:
1214         case INSTR_NOT_ENT:
1215         case INSTR_NOT_FNC:
1216 #if 0
1217         case INSTR_NOT_I:
1218 #endif
1219             ot = TYPE_FLOAT;
1220             break;
1221         /* QC doesn't have other unary operations. We expect extensions to fill
1222          * the above list, otherwise we assume out-type = in-type, eg for an
1223          * unary minus
1224          */
1225         default:
1226             ot = operand->vtype;
1227             break;
1228     };
1229     if (ot == TYPE_VOID) {
1230         /* The AST or parser were supposed to check this! */
1231         return NULL;
1232     }
1233
1234     /* let's use the general instruction creator and pass NULL for OPB */
1235     return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1236 }
1237
1238 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1239                                         int op, ir_value *a, ir_value *b, int outype)
1240 {
1241     ir_instr *instr;
1242     ir_value *out;
1243
1244     out = ir_value_out(self->owner, label, store_value, outype);
1245     if (!out)
1246         return NULL;
1247
1248     instr = ir_instr_new(self, op);
1249     if (!instr) {
1250         ir_value_delete(out);
1251         return NULL;
1252     }
1253
1254     if (!ir_instr_op(instr, 0, out, true) ||
1255         !ir_instr_op(instr, 1, a, false) ||
1256         !ir_instr_op(instr, 2, b, false) )
1257     {
1258         goto on_error;
1259     }
1260
1261     if (!ir_block_instr_add(self, instr))
1262         goto on_error;
1263
1264     return out;
1265 on_error:
1266     ir_instr_delete(instr);
1267     ir_value_delete(out);
1268     return NULL;
1269 }
1270
1271 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1272 {
1273     ir_value *v;
1274
1275     /* Support for various pointer types todo if so desired */
1276     if (ent->vtype != TYPE_ENTITY)
1277         return NULL;
1278
1279     if (field->vtype != TYPE_FIELD)
1280         return NULL;
1281
1282     v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1283     v->fieldtype = field->fieldtype;
1284     return v;
1285 }
1286
1287 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1288 {
1289     int op;
1290     if (ent->vtype != TYPE_ENTITY)
1291         return NULL;
1292
1293     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1294     if (field->vtype != TYPE_FIELD)
1295         return NULL;
1296
1297     switch (outype)
1298     {
1299         case TYPE_FLOAT:   op = INSTR_LOAD_F;   break;
1300         case TYPE_VECTOR:  op = INSTR_LOAD_V;   break;
1301         case TYPE_STRING:  op = INSTR_LOAD_S;   break;
1302         case TYPE_FIELD:   op = INSTR_LOAD_FLD; break;
1303         case TYPE_ENTITY:  op = INSTR_LOAD_ENT; break;
1304 #if 0
1305         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1306         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1307 #endif
1308         default:
1309             return NULL;
1310     }
1311
1312     return ir_block_create_general_instr(self, label, op, ent, field, outype);
1313 }
1314
1315 ir_value* ir_block_create_add(ir_block *self,
1316                               const char *label,
1317                               ir_value *left, ir_value *right)
1318 {
1319     int op = 0;
1320     int l = left->vtype;
1321     int r = right->vtype;
1322     if (l == r) {
1323         switch (l) {
1324             default:
1325                 return NULL;
1326             case TYPE_FLOAT:
1327                 op = INSTR_ADD_F;
1328                 break;
1329 #if 0
1330             case TYPE_INTEGER:
1331                 op = INSTR_ADD_I;
1332                 break;
1333 #endif
1334             case TYPE_VECTOR:
1335                 op = INSTR_ADD_V;
1336                 break;
1337         }
1338     } else {
1339 #if 0
1340         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1341             op = INSTR_ADD_FI;
1342         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1343             op = INSTR_ADD_IF;
1344         else
1345 #endif
1346             return NULL;
1347     }
1348     return ir_block_create_binop(self, label, op, left, right);
1349 }
1350
1351 ir_value* ir_block_create_sub(ir_block *self,
1352                               const char *label,
1353                               ir_value *left, ir_value *right)
1354 {
1355     int op = 0;
1356     int l = left->vtype;
1357     int r = right->vtype;
1358     if (l == r) {
1359
1360         switch (l) {
1361             default:
1362                 return NULL;
1363             case TYPE_FLOAT:
1364                 op = INSTR_SUB_F;
1365                 break;
1366 #if 0
1367             case TYPE_INTEGER:
1368                 op = INSTR_SUB_I;
1369                 break;
1370 #endif
1371             case TYPE_VECTOR:
1372                 op = INSTR_SUB_V;
1373                 break;
1374         }
1375     } else {
1376 #if 0
1377         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1378             op = INSTR_SUB_FI;
1379         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1380             op = INSTR_SUB_IF;
1381         else
1382 #endif
1383             return NULL;
1384     }
1385     return ir_block_create_binop(self, label, op, left, right);
1386 }
1387
1388 ir_value* ir_block_create_mul(ir_block *self,
1389                               const char *label,
1390                               ir_value *left, ir_value *right)
1391 {
1392     int op = 0;
1393     int l = left->vtype;
1394     int r = right->vtype;
1395     if (l == r) {
1396
1397         switch (l) {
1398             default:
1399                 return NULL;
1400             case TYPE_FLOAT:
1401                 op = INSTR_MUL_F;
1402                 break;
1403 #if 0
1404             case TYPE_INTEGER:
1405                 op = INSTR_MUL_I;
1406                 break;
1407 #endif
1408             case TYPE_VECTOR:
1409                 op = INSTR_MUL_V;
1410                 break;
1411         }
1412     } else {
1413         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1414             op = INSTR_MUL_VF;
1415         else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1416             op = INSTR_MUL_FV;
1417 #if 0
1418         else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1419             op = INSTR_MUL_VI;
1420         else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1421             op = INSTR_MUL_IV;
1422         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1423             op = INSTR_MUL_FI;
1424         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1425             op = INSTR_MUL_IF;
1426 #endif
1427         else
1428             return NULL;
1429     }
1430     return ir_block_create_binop(self, label, op, left, right);
1431 }
1432
1433 ir_value* ir_block_create_div(ir_block *self,
1434                               const char *label,
1435                               ir_value *left, ir_value *right)
1436 {
1437     int op = 0;
1438     int l = left->vtype;
1439     int r = right->vtype;
1440     if (l == r) {
1441
1442         switch (l) {
1443             default:
1444                 return NULL;
1445             case TYPE_FLOAT:
1446                 op = INSTR_DIV_F;
1447                 break;
1448 #if 0
1449             case TYPE_INTEGER:
1450                 op = INSTR_DIV_I;
1451                 break;
1452 #endif
1453         }
1454     } else {
1455 #if 0
1456         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1457             op = INSTR_DIV_VF;
1458         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1459             op = INSTR_DIV_FI;
1460         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1461             op = INSTR_DIV_IF;
1462         else
1463 #endif
1464             return NULL;
1465     }
1466     return ir_block_create_binop(self, label, op, left, right);
1467 }
1468
1469 /* PHI resolving breaks the SSA, and must thus be the last
1470  * step before life-range calculation.
1471  */
1472
1473 static bool ir_block_naive_phi(ir_block *self);
1474 bool ir_function_naive_phi(ir_function *self)
1475 {
1476     size_t i;
1477
1478     for (i = 0; i < self->blocks_count; ++i)
1479     {
1480         if (!ir_block_naive_phi(self->blocks[i]))
1481             return false;
1482     }
1483     return true;
1484 }
1485
1486 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1487 {
1488     ir_instr *instr;
1489     size_t i;
1490
1491     /* create a store */
1492     if (!ir_block_create_store(block, old, what))
1493         return false;
1494
1495     /* we now move it up */
1496     instr = block->instr[block->instr_count-1];
1497     for (i = block->instr_count; i > iid; --i)
1498         block->instr[i] = block->instr[i-1];
1499     block->instr[i] = instr;
1500
1501     return true;
1502 }
1503
1504 static bool ir_block_naive_phi(ir_block *self)
1505 {
1506     size_t i, p, w;
1507     /* FIXME: optionally, create_phi can add the phis
1508      * to a list so we don't need to loop through blocks
1509      * - anyway: "don't optimize YET"
1510      */
1511     for (i = 0; i < self->instr_count; ++i)
1512     {
1513         ir_instr *instr = self->instr[i];
1514         if (instr->opcode != VINSTR_PHI)
1515             continue;
1516
1517         if (!ir_block_instr_remove(self, i))
1518             return false;
1519         --i; /* NOTE: i+1 below */
1520
1521         for (p = 0; p < instr->phi_count; ++p)
1522         {
1523             ir_value *v = instr->phi[p].value;
1524             for (w = 0; w < v->writes_count; ++w) {
1525                 ir_value *old;
1526
1527                 if (!v->writes[w]->_ops[0])
1528                     continue;
1529
1530                 /* When the write was to a global, we have to emit a mov */
1531                 old = v->writes[w]->_ops[0];
1532
1533                 /* The original instruction now writes to the PHI target local */
1534                 if (v->writes[w]->_ops[0] == v)
1535                     v->writes[w]->_ops[0] = instr->_ops[0];
1536
1537                 if (old->store != store_value && old->store != store_local && old->store != store_param)
1538                 {
1539                     /* If it originally wrote to a global we need to store the value
1540                      * there as welli
1541                      */
1542                     if (!ir_naive_phi_emit_store(self, i+1, old, v))
1543                         return false;
1544                     if (i+1 < self->instr_count)
1545                         instr = self->instr[i+1];
1546                     else
1547                         instr = NULL;
1548                     /* In case I forget and access instr later, it'll be NULL
1549                      * when it's a problem, to make sure we crash, rather than accessing
1550                      * invalid data.
1551                      */
1552                 }
1553                 else
1554                 {
1555                     /* If it didn't, we can replace all reads by the phi target now. */
1556                     size_t r;
1557                     for (r = 0; r < old->reads_count; ++r)
1558                     {
1559                         size_t op;
1560                         ir_instr *ri = old->reads[r];
1561                         for (op = 0; op < ri->phi_count; ++op) {
1562                             if (ri->phi[op].value == old)
1563                                 ri->phi[op].value = v;
1564                         }
1565                         for (op = 0; op < 3; ++op) {
1566                             if (ri->_ops[op] == old)
1567                                 ri->_ops[op] = v;
1568                         }
1569                     }
1570                 }
1571             }
1572         }
1573         ir_instr_delete(instr);
1574     }
1575     return true;
1576 }
1577
1578 /***********************************************************************
1579  *IR Temp allocation code
1580  * Propagating value life ranges by walking through the function backwards
1581  * until no more changes are made.
1582  * In theory this should happen once more than once for every nested loop
1583  * level.
1584  * Though this implementation might run an additional time for if nests.
1585  */
1586
1587 typedef struct
1588 {
1589     ir_value* *v;
1590     size_t    v_count;
1591     size_t    v_alloc;
1592 } new_reads_t;
1593 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1594
1595 /* Enumerate instructions used by value's life-ranges
1596  */
1597 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1598 {
1599     size_t i;
1600     size_t eid = *_eid;
1601     for (i = 0; i < self->instr_count; ++i)
1602     {
1603         self->instr[i]->eid = eid++;
1604     }
1605     *_eid = eid;
1606 }
1607
1608 /* Enumerate blocks and instructions.
1609  * The block-enumeration is unordered!
1610  * We do not really use the block enumreation, however
1611  * the instruction enumeration is important for life-ranges.
1612  */
1613 void ir_function_enumerate(ir_function *self)
1614 {
1615     size_t i;
1616     size_t instruction_id = 0;
1617     for (i = 0; i < self->blocks_count; ++i)
1618     {
1619         self->blocks[i]->eid = i;
1620         self->blocks[i]->run_id = 0;
1621         ir_block_enumerate(self->blocks[i], &instruction_id);
1622     }
1623 }
1624
1625 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1626 bool ir_function_calculate_liferanges(ir_function *self)
1627 {
1628     size_t i;
1629     bool changed;
1630
1631     do {
1632         self->run_id++;
1633         changed = false;
1634         for (i = 0; i != self->blocks_count; ++i)
1635         {
1636             if (self->blocks[i]->is_return)
1637             {
1638                 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1639                     return false;
1640             }
1641         }
1642     } while (changed);
1643     return true;
1644 }
1645
1646 /* Local-value allocator
1647  * After finishing creating the liferange of all values used in a function
1648  * we can allocate their global-positions.
1649  * This is the counterpart to register-allocation in register machines.
1650  */
1651 typedef struct {
1652     MEM_VECTOR_MAKE(ir_value*, locals);
1653     MEM_VECTOR_MAKE(size_t,    sizes);
1654     MEM_VECTOR_MAKE(size_t,    positions);
1655 } function_allocator;
1656 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1657 MEM_VEC_FUNCTIONS(function_allocator, size_t,    sizes)
1658 MEM_VEC_FUNCTIONS(function_allocator, size_t,    positions)
1659
1660 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1661 {
1662     ir_value *slot;
1663     size_t vsize = type_sizeof[var->vtype];
1664
1665     slot = ir_value_var("reg", store_global, var->vtype);
1666     if (!slot)
1667         return false;
1668
1669     if (!ir_value_life_merge_into(slot, var))
1670         goto localerror;
1671
1672     if (!function_allocator_locals_add(alloc, slot))
1673         goto localerror;
1674
1675     if (!function_allocator_sizes_add(alloc, vsize))
1676         goto localerror;
1677
1678     return true;
1679
1680 localerror:
1681     ir_value_delete(slot);
1682     return false;
1683 }
1684
1685 bool ir_function_allocate_locals(ir_function *self)
1686 {
1687     size_t i, a;
1688     bool   retval = true;
1689     size_t pos;
1690
1691     ir_value *slot;
1692     const ir_value *v;
1693
1694     function_allocator alloc;
1695
1696     if (!self->locals_count)
1697         return true;
1698
1699     MEM_VECTOR_INIT(&alloc, locals);
1700     MEM_VECTOR_INIT(&alloc, sizes);
1701     MEM_VECTOR_INIT(&alloc, positions);
1702
1703     for (i = 0; i < self->locals_count; ++i)
1704     {
1705         if (!function_allocator_alloc(&alloc, self->locals[i]))
1706             goto error;
1707     }
1708
1709     /* Allocate a slot for any value that still exists */
1710     for (i = 0; i < self->values_count; ++i)
1711     {
1712         v = self->values[i];
1713
1714         if (!v->life_count)
1715             continue;
1716
1717         for (a = 0; a < alloc.locals_count; ++a)
1718         {
1719             slot = alloc.locals[a];
1720
1721             if (ir_values_overlap(v, slot))
1722                 continue;
1723
1724             if (!ir_value_life_merge_into(slot, v))
1725                 goto error;
1726
1727             /* adjust size for this slot */
1728             if (alloc.sizes[a] < type_sizeof[v->vtype])
1729                 alloc.sizes[a] = type_sizeof[v->vtype];
1730
1731             self->values[i]->code.local = a;
1732             break;
1733         }
1734         if (a >= alloc.locals_count) {
1735             self->values[i]->code.local = alloc.locals_count;
1736             if (!function_allocator_alloc(&alloc, v))
1737                 goto error;
1738         }
1739     }
1740
1741     /* Adjust slot positions based on sizes */
1742     if (!function_allocator_positions_add(&alloc, 0))
1743         goto error;
1744
1745     if (alloc.sizes_count)
1746         pos = alloc.positions[0] + alloc.sizes[0];
1747     else
1748         pos = 0;
1749     for (i = 1; i < alloc.sizes_count; ++i)
1750     {
1751         pos = alloc.positions[i-1] + alloc.sizes[i-1];
1752         if (!function_allocator_positions_add(&alloc, pos))
1753             goto error;
1754     }
1755
1756     self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1757
1758     /* Take over the actual slot positions */
1759     for (i = 0; i < self->values_count; ++i)
1760         self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1761
1762     goto cleanup;
1763
1764 error:
1765     retval = false;
1766 cleanup:
1767     for (i = 0; i < alloc.locals_count; ++i)
1768         ir_value_delete(alloc.locals[i]);
1769     MEM_VECTOR_CLEAR(&alloc, locals);
1770     MEM_VECTOR_CLEAR(&alloc, sizes);
1771     MEM_VECTOR_CLEAR(&alloc, positions);
1772     return retval;
1773 }
1774
1775 /* Get information about which operand
1776  * is read from, or written to.
1777  */
1778 static void ir_op_read_write(int op, size_t *read, size_t *write)
1779 {
1780     switch (op)
1781     {
1782     case VINSTR_JUMP:
1783     case INSTR_GOTO:
1784         *write = 0;
1785         *read = 0;
1786         break;
1787     case INSTR_IF:
1788     case INSTR_IFNOT:
1789 #if 0
1790     case INSTR_IF_S:
1791     case INSTR_IFNOT_S:
1792 #endif
1793     case INSTR_RETURN:
1794     case VINSTR_COND:
1795         *write = 0;
1796         *read = 1;
1797         break;
1798     default:
1799         *write = 1;
1800         *read = 6;
1801         break;
1802     };
1803 }
1804
1805 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1806 {
1807     size_t i;
1808     bool changed = false;
1809     bool tempbool;
1810     for (i = 0; i != self->living_count; ++i)
1811     {
1812         tempbool = ir_value_life_merge(self->living[i], eid);
1813         /* debug
1814         if (tempbool)
1815             fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1816         */
1817         changed = changed || tempbool;
1818     }
1819     return changed;
1820 }
1821
1822 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1823 {
1824     size_t i;
1825     /* values which have been read in a previous iteration are now
1826      * in the "living" array even if the previous block doesn't use them.
1827      * So we have to remove whatever does not exist in the previous block.
1828      * They will be re-added on-read, but the liferange merge won't cause
1829      * a change.
1830      */
1831     for (i = 0; i < self->living_count; ++i)
1832     {
1833         if (!ir_block_living_find(prev, self->living[i], NULL)) {
1834             if (!ir_block_living_remove(self, i))
1835                 return false;
1836             --i;
1837         }
1838     }
1839
1840     /* Whatever the previous block still has in its living set
1841      * must now be added to ours as well.
1842      */
1843     for (i = 0; i < prev->living_count; ++i)
1844     {
1845         if (ir_block_living_find(self, prev->living[i], NULL))
1846             continue;
1847         if (!ir_block_living_add(self, prev->living[i]))
1848             return false;
1849         /*
1850         printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1851         */
1852     }
1853     return true;
1854 }
1855
1856 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1857 {
1858     ir_instr *instr;
1859     ir_value *value;
1860     bool  tempbool;
1861     size_t i, o, p;
1862     /* bitmasks which operands are read from or written to */
1863     size_t read, write;
1864 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1865     size_t rd;
1866     new_reads_t new_reads;
1867 #endif
1868     char dbg_ind[16] = { '#', '0' };
1869     (void)dbg_ind;
1870
1871 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1872     MEM_VECTOR_INIT(&new_reads, v);
1873 #endif
1874
1875     if (prev)
1876     {
1877         if (!ir_block_life_prop_previous(self, prev, changed))
1878             return false;
1879     }
1880
1881     i = self->instr_count;
1882     while (i)
1883     { --i;
1884         instr = self->instr[i];
1885
1886         /* PHI operands are always read operands */
1887         for (p = 0; p < instr->phi_count; ++p)
1888         {
1889             value = instr->phi[p].value;
1890 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1891             if (!ir_block_living_find(self, value, NULL) &&
1892                 !ir_block_living_add(self, value))
1893             {
1894                 goto on_error;
1895             }
1896 #else
1897             if (!new_reads_t_v_find(&new_reads, value, NULL))
1898             {
1899                 if (!new_reads_t_v_add(&new_reads, value))
1900                     goto on_error;
1901             }
1902 #endif
1903         }
1904
1905         /* See which operands are read and write operands */
1906         ir_op_read_write(instr->opcode, &read, &write);
1907
1908         /* Go through the 3 main operands */
1909         for (o = 0; o < 3; ++o)
1910         {
1911             if (!instr->_ops[o]) /* no such operand */
1912                 continue;
1913
1914             value = instr->_ops[o];
1915
1916             /* We only care about locals */
1917             /* we also calculate parameter liferanges so that locals
1918              * can take up parameter slots */
1919             if (value->store != store_value &&
1920                 value->store != store_local &&
1921                 value->store != store_param)
1922                 continue;
1923
1924             /* read operands */
1925             if (read & (1<<o))
1926             {
1927 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1928                 if (!ir_block_living_find(self, value, NULL) &&
1929                     !ir_block_living_add(self, value))
1930                 {
1931                     goto on_error;
1932                 }
1933 #else
1934                 /* fprintf(stderr, "read: %s\n", value->_name); */
1935                 if (!new_reads_t_v_find(&new_reads, value, NULL))
1936                 {
1937                     if (!new_reads_t_v_add(&new_reads, value))
1938                         goto on_error;
1939                 }
1940 #endif
1941             }
1942
1943             /* write operands */
1944             /* When we write to a local, we consider it "dead" for the
1945              * remaining upper part of the function, since in SSA a value
1946              * can only be written once (== created)
1947              */
1948             if (write & (1<<o))
1949             {
1950                 size_t idx;
1951                 bool in_living = ir_block_living_find(self, value, &idx);
1952 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1953                 size_t readidx;
1954                 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1955                 if (!in_living && !in_reads)
1956 #else
1957                 if (!in_living)
1958 #endif
1959                 {
1960                     /* If the value isn't alive it hasn't been read before... */
1961                     /* TODO: See if the warning can be emitted during parsing or AST processing
1962                      * otherwise have warning printed here.
1963                      * IF printing a warning here: include filecontext_t,
1964                      * and make sure it's only printed once
1965                      * since this function is run multiple times.
1966                      */
1967                     /* For now: debug info: */
1968                     fprintf(stderr, "Value only written %s\n", value->name);
1969                     tempbool = ir_value_life_merge(value, instr->eid);
1970                     *changed = *changed || tempbool;
1971                     /*
1972                     ir_instr_dump(instr, dbg_ind, printf);
1973                     abort();
1974                     */
1975                 } else {
1976                     /* since 'living' won't contain it
1977                      * anymore, merge the value, since
1978                      * (A) doesn't.
1979                      */
1980                     tempbool = ir_value_life_merge(value, instr->eid);
1981                     /*
1982                     if (tempbool)
1983                         fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1984                     */
1985                     *changed = *changed || tempbool;
1986                     /* Then remove */
1987 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1988                     if (!ir_block_living_remove(self, idx))
1989                         goto on_error;
1990 #else
1991                     if (in_reads)
1992                     {
1993                         if (!new_reads_t_v_remove(&new_reads, readidx))
1994                             goto on_error;
1995                     }
1996 #endif
1997                 }
1998             }
1999         }
2000         /* (A) */
2001         tempbool = ir_block_living_add_instr(self, instr->eid);
2002         /*fprintf(stderr, "living added values\n");*/
2003         *changed = *changed || tempbool;
2004
2005 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2006         /* new reads: */
2007         for (rd = 0; rd < new_reads.v_count; ++rd)
2008         {
2009             if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2010                 if (!ir_block_living_add(self, new_reads.v[rd]))
2011                     goto on_error;
2012             }
2013             if (!i && !self->entries_count) {
2014                 /* fix the top */
2015                 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2016             }
2017         }
2018         MEM_VECTOR_CLEAR(&new_reads, v);
2019 #endif
2020     }
2021
2022     if (self->run_id == self->owner->run_id)
2023         return true;
2024
2025     self->run_id = self->owner->run_id;
2026
2027     for (i = 0; i < self->entries_count; ++i)
2028     {
2029         ir_block *entry = self->entries[i];
2030         ir_block_life_propagate(entry, self, changed);
2031     }
2032
2033     return true;
2034 on_error:
2035 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2036     MEM_VECTOR_CLEAR(&new_reads, v);
2037 #endif
2038     return false;
2039 }
2040
2041 /***********************************************************************
2042  *IR Code-Generation
2043  *
2044  * Since the IR has the convention of putting 'write' operands
2045  * at the beginning, we have to rotate the operands of instructions
2046  * properly in order to generate valid QCVM code.
2047  *
2048  * Having destinations at a fixed position is more convenient. In QC
2049  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
2050  * read from from OPA,  and store to OPB rather than OPC.   Which is
2051  * partially the reason why the implementation of these instructions
2052  * in darkplaces has been delayed for so long.
2053  *
2054  * Breaking conventions is annoying...
2055  */
2056 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2057
2058 static bool gen_global_field(ir_value *global)
2059 {
2060     if (global->isconst)
2061     {
2062         ir_value *fld = global->constval.vpointer;
2063         if (!fld) {
2064             printf("Invalid field constant with no field: %s\n", global->name);
2065             return false;
2066         }
2067
2068         /* Now, in this case, a relocation would be impossible to code
2069          * since it looks like this:
2070          * .vector v = origin;     <- parse error, wtf is 'origin'?
2071          * .vector origin;
2072          *
2073          * But we will need a general relocation support later anyway
2074          * for functions... might as well support that here.
2075          */
2076         if (!fld->code.globaladdr) {
2077             printf("FIXME: Relocation support\n");
2078             return false;
2079         }
2080
2081         /* copy the field's value */
2082         global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2083     }
2084     else
2085     {
2086         global->code.globaladdr = code_globals_add(0);
2087     }
2088     if (global->code.globaladdr < 0)
2089         return false;
2090     return true;
2091 }
2092
2093 static bool gen_global_pointer(ir_value *global)
2094 {
2095     if (global->isconst)
2096     {
2097         ir_value *target = global->constval.vpointer;
2098         if (!target) {
2099             printf("Invalid pointer constant: %s\n", global->name);
2100             /* NULL pointers are pointing to the NULL constant, which also
2101              * sits at address 0, but still has an ir_value for itself.
2102              */
2103             return false;
2104         }
2105
2106         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2107          * void() foo; <- proto
2108          * void() *fooptr = &foo;
2109          * void() foo = { code }
2110          */
2111         if (!target->code.globaladdr) {
2112             /* FIXME: Check for the constant nullptr ir_value!
2113              * because then code.globaladdr being 0 is valid.
2114              */
2115             printf("FIXME: Relocation support\n");
2116             return false;
2117         }
2118
2119         global->code.globaladdr = code_globals_add(target->code.globaladdr);
2120     }
2121     else
2122     {
2123         global->code.globaladdr = code_globals_add(0);
2124     }
2125     if (global->code.globaladdr < 0)
2126         return false;
2127     return true;
2128 }
2129
2130 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2131 {
2132     prog_section_statement stmt;
2133     ir_instr *instr;
2134     ir_block *target;
2135     ir_block *ontrue;
2136     ir_block *onfalse;
2137     size_t    stidx;
2138     size_t    i;
2139
2140 tailcall:
2141     block->generated = true;
2142     block->code_start = code_statements_elements;
2143     for (i = 0; i < block->instr_count; ++i)
2144     {
2145         instr = block->instr[i];
2146
2147         if (instr->opcode == VINSTR_PHI) {
2148             printf("cannot generate virtual instruction (phi)\n");
2149             return false;
2150         }
2151
2152         if (instr->opcode == VINSTR_JUMP) {
2153             target = instr->bops[0];
2154             /* for uncoditional jumps, if the target hasn't been generated
2155              * yet, we generate them right here.
2156              */
2157             if (!target->generated) {
2158                 block = target;
2159                 goto tailcall;
2160             }
2161
2162             /* otherwise we generate a jump instruction */
2163             stmt.opcode = INSTR_GOTO;
2164             stmt.o1.s1 = (target->code_start) - code_statements_elements;
2165             stmt.o2.s1 = 0;
2166             stmt.o3.s1 = 0;
2167             if (code_statements_add(stmt) < 0)
2168                 return false;
2169
2170             /* no further instructions can be in this block */
2171             return true;
2172         }
2173
2174         if (instr->opcode == VINSTR_COND) {
2175             ontrue  = instr->bops[0];
2176             onfalse = instr->bops[1];
2177             /* TODO: have the AST signal which block should
2178              * come first: eg. optimize IFs without ELSE...
2179              */
2180
2181             stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2182             stmt.o2.u1 = 0;
2183             stmt.o3.s1 = 0;
2184
2185             if (ontrue->generated) {
2186                 stmt.opcode = INSTR_IF;
2187                 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2188                 if (code_statements_add(stmt) < 0)
2189                     return false;
2190             }
2191             if (onfalse->generated) {
2192                 stmt.opcode = INSTR_IFNOT;
2193                 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2194                 if (code_statements_add(stmt) < 0)
2195                     return false;
2196             }
2197             if (!ontrue->generated) {
2198                 if (onfalse->generated) {
2199                     block = ontrue;
2200                     goto tailcall;
2201                 }
2202             }
2203             if (!onfalse->generated) {
2204                 if (ontrue->generated) {
2205                     block = onfalse;
2206                     goto tailcall;
2207                 }
2208             }
2209             /* neither ontrue nor onfalse exist */
2210             stmt.opcode = INSTR_IFNOT;
2211             stidx = code_statements_elements;
2212             if (code_statements_add(stmt) < 0)
2213                 return false;
2214             /* on false we jump, so add ontrue-path */
2215             if (!gen_blocks_recursive(func, ontrue))
2216                 return false;
2217             /* fixup the jump address */
2218             code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2219             /* generate onfalse path */
2220             if (onfalse->generated) {
2221                 /* fixup the jump address */
2222                 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2223                 /* may have been generated in the previous recursive call */
2224                 stmt.opcode = INSTR_GOTO;
2225                 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2226                 stmt.o2.s1 = 0;
2227                 stmt.o3.s1 = 0;
2228                 return (code_statements_add(stmt) >= 0);
2229             }
2230             /* if not, generate now */
2231             block = onfalse;
2232             goto tailcall;
2233         }
2234
2235         if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2236             /* Trivial call translation:
2237              * copy all params to OFS_PARM*
2238              * if the output's storetype is not store_return,
2239              * add append a STORE instruction!
2240              *
2241              * NOTES on how to do it better without much trouble:
2242              * -) The liferanges!
2243              *      Simply check the liferange of all parameters for
2244              *      other CALLs. For each param with no CALL in its
2245              *      liferange, we can store it in an OFS_PARM at
2246              *      generation already. This would even include later
2247              *      reuse.... probably... :)
2248              */
2249             size_t p;
2250             ir_value *retvalue;
2251
2252             for (p = 0; p < instr->params_count; ++p)
2253             {
2254                 ir_value *param = instr->params[p];
2255
2256                 stmt.opcode = INSTR_STORE_F;
2257                 stmt.o3.u1 = 0;
2258
2259                 stmt.opcode = type_store_instr[param->vtype];
2260                 stmt.o1.u1 = param->code.globaladdr;
2261                 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2262                 if (code_statements_add(stmt) < 0)
2263                     return false;
2264             }
2265             stmt.opcode = INSTR_CALL0 + instr->params_count;
2266             if (stmt.opcode > INSTR_CALL8)
2267                 stmt.opcode = INSTR_CALL8;
2268             stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2269             stmt.o2.u1 = 0;
2270             stmt.o3.u1 = 0;
2271             if (code_statements_add(stmt) < 0)
2272                 return false;
2273
2274             retvalue = instr->_ops[0];
2275             if (retvalue && retvalue->store != store_return && retvalue->life_count)
2276             {
2277                 /* not to be kept in OFS_RETURN */
2278                 stmt.opcode = type_store_instr[retvalue->vtype];
2279                 stmt.o1.u1 = OFS_RETURN;
2280                 stmt.o2.u1 = retvalue->code.globaladdr;
2281                 stmt.o3.u1 = 0;
2282                 if (code_statements_add(stmt) < 0)
2283                     return false;
2284             }
2285             continue;
2286         }
2287
2288         if (instr->opcode == INSTR_STATE) {
2289             printf("TODO: state instruction\n");
2290             return false;
2291         }
2292
2293         stmt.opcode = instr->opcode;
2294         stmt.o1.u1 = 0;
2295         stmt.o2.u1 = 0;
2296         stmt.o3.u1 = 0;
2297
2298         /* This is the general order of operands */
2299         if (instr->_ops[0])
2300             stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2301
2302         if (instr->_ops[1])
2303             stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2304
2305         if (instr->_ops[2])
2306             stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2307
2308         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2309         {
2310             stmt.o1.u1 = stmt.o3.u1;
2311             stmt.o3.u1 = 0;
2312         }
2313         else if (stmt.opcode >= INSTR_STORE_F &&
2314                  stmt.opcode <= INSTR_STORE_FNC)
2315         {
2316             /* 2-operand instructions with A -> B */
2317             stmt.o2.u1 = stmt.o3.u1;
2318             stmt.o3.u1 = 0;
2319         }
2320
2321         if (code_statements_add(stmt) < 0)
2322             return false;
2323     }
2324     return true;
2325 }
2326
2327 static bool gen_function_code(ir_function *self)
2328 {
2329     ir_block *block;
2330     prog_section_statement stmt;
2331
2332     /* Starting from entry point, we generate blocks "as they come"
2333      * for now. Dead blocks will not be translated obviously.
2334      */
2335     if (!self->blocks_count) {
2336         printf("Function '%s' declared without body.\n", self->name);
2337         return false;
2338     }
2339
2340     block = self->blocks[0];
2341     if (block->generated)
2342         return true;
2343
2344     if (!gen_blocks_recursive(self, block)) {
2345         printf("failed to generate blocks for '%s'\n", self->name);
2346         return false;
2347     }
2348
2349     /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2350     stmt.opcode = AINSTR_END;
2351     stmt.o1.u1 = 0;
2352     stmt.o2.u1 = 0;
2353     stmt.o3.u1 = 0;
2354     if (code_statements_add(stmt) < 0)
2355         return false;
2356     return true;
2357 }
2358
2359 static bool gen_global_function(ir_builder *ir, ir_value *global)
2360 {
2361     prog_section_function fun;
2362     ir_function          *irfun;
2363
2364     size_t i;
2365     size_t local_var_end;
2366
2367     if (!global->isconst || (!global->constval.vfunc))
2368     {
2369         printf("Invalid state of function-global: not constant: %s\n", global->name);
2370         return false;
2371     }
2372
2373     irfun = global->constval.vfunc;
2374
2375     fun.name    = global->code.name;
2376     fun.file    = code_cachedstring(global->context.file);
2377     fun.profile = 0; /* always 0 */
2378     fun.nargs   = irfun->params_count;
2379
2380     for (i = 0;i < 8; ++i) {
2381         if (i >= fun.nargs)
2382             fun.argsize[i] = 0;
2383         else
2384             fun.argsize[i] = type_sizeof[irfun->params[i]];
2385     }
2386
2387     fun.firstlocal = code_globals_elements;
2388     fun.locals     = irfun->allocated_locals + irfun->locals_count;
2389
2390     local_var_end = 0;
2391     for (i = 0; i < irfun->locals_count; ++i) {
2392         if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2393             printf("Failed to generate global %s\n", irfun->locals[i]->name);
2394             return false;
2395         }
2396     }
2397     if (irfun->locals_count) {
2398         ir_value *last = irfun->locals[irfun->locals_count-1];
2399         local_var_end = last->code.globaladdr;
2400         local_var_end += type_sizeof[last->vtype];
2401     }
2402     for (i = 0; i < irfun->values_count; ++i)
2403     {
2404         /* generate code.globaladdr for ssa values */
2405         ir_value *v = irfun->values[i];
2406         v->code.globaladdr = local_var_end + v->code.local;
2407     }
2408     for (i = 0; i < irfun->locals_count; ++i) {
2409         /* fill the locals with zeros */
2410         code_globals_add(0);
2411     }
2412
2413     if (irfun->builtin)
2414         fun.entry = irfun->builtin;
2415     else {
2416         fun.entry = code_statements_elements;
2417         if (!gen_function_code(irfun)) {
2418             printf("Failed to generate code for function %s\n", irfun->name);
2419             return false;
2420         }
2421     }
2422
2423     return (code_functions_add(fun) >= 0);
2424 }
2425
2426 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2427 {
2428     size_t           i;
2429     int32_t         *iptr;
2430     prog_section_def def;
2431
2432     def.type   = global->vtype;
2433     def.offset = code_globals_elements;
2434     def.name   = global->code.name       = code_genstring(global->name);
2435
2436     switch (global->vtype)
2437     {
2438     case TYPE_POINTER:
2439         if (code_defs_add(def) < 0)
2440             return false;
2441         return gen_global_pointer(global);
2442     case TYPE_FIELD:
2443         if (code_defs_add(def) < 0)
2444             return false;
2445         return gen_global_field(global);
2446     case TYPE_ENTITY:
2447         /* fall through */
2448     case TYPE_FLOAT:
2449     {
2450         if (code_defs_add(def) < 0)
2451             return false;
2452
2453         if (global->isconst) {
2454             iptr = (int32_t*)&global->constval.vfloat;
2455             global->code.globaladdr = code_globals_add(*iptr);
2456         } else
2457             global->code.globaladdr = code_globals_add(0);
2458
2459         return global->code.globaladdr >= 0;
2460     }
2461     case TYPE_STRING:
2462     {
2463         if (code_defs_add(def) < 0)
2464             return false;
2465         if (global->isconst)
2466             global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2467         else
2468             global->code.globaladdr = code_globals_add(0);
2469         return global->code.globaladdr >= 0;
2470     }
2471     case TYPE_VECTOR:
2472     {
2473         size_t d;
2474         if (code_defs_add(def) < 0)
2475             return false;
2476
2477         if (global->isconst) {
2478             iptr = (int32_t*)&global->constval.vvec;
2479             global->code.globaladdr = code_globals_add(iptr[0]);
2480             if (global->code.globaladdr < 0)
2481                 return false;
2482             for (d = 1; d < type_sizeof[global->vtype]; ++d)
2483             {
2484                 if (code_globals_add(iptr[d]) < 0)
2485                     return false;
2486             }
2487         } else {
2488             global->code.globaladdr = code_globals_add(0);
2489             if (global->code.globaladdr < 0)
2490                 return false;
2491             for (d = 1; d < type_sizeof[global->vtype]; ++d)
2492             {
2493                 if (code_globals_add(0) < 0)
2494                     return false;
2495             }
2496         }
2497         return global->code.globaladdr >= 0;
2498     }
2499     case TYPE_FUNCTION:
2500         if (code_defs_add(def) < 0)
2501             return false;
2502         global->code.globaladdr = code_globals_elements;
2503         code_globals_add(code_functions_elements);
2504         return gen_global_function(self, global);
2505     case TYPE_VARIANT:
2506         /* assume biggest type */
2507             global->code.globaladdr = code_globals_add(0);
2508             for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2509                 code_globals_add(0);
2510             return true;
2511     default:
2512         /* refuse to create 'void' type or any other fancy business. */
2513         printf("Invalid type for global variable %s\n", global->name);
2514         return false;
2515     }
2516 }
2517
2518 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2519 {
2520     prog_section_def def;
2521     prog_section_field fld;
2522
2523     def.type   = field->vtype;
2524     def.offset = code_globals_elements;
2525     def.name   = field->code.name = code_genstring(field->name);
2526
2527     if (code_defs_add(def) < 0)
2528         return false;
2529
2530     fld.name = def.name;
2531     fld.offset = code_fields_elements;
2532     fld.type = field->fieldtype;
2533
2534     if (fld.type == TYPE_VOID) {
2535         printf("field is missing a type: %s - don't know its size\n", field->name);
2536         return false;
2537     }
2538
2539     if (code_fields_add(fld) < 0)
2540         return false;
2541
2542     if (!code_globals_add(code_alloc_field(type_sizeof[field->fieldtype])))
2543         return false;
2544
2545     field->code.globaladdr = code_globals_add(fld.offset);
2546     return field->code.globaladdr >= 0;
2547 }
2548
2549 bool ir_builder_generate(ir_builder *self, const char *filename)
2550 {
2551     size_t i;
2552
2553     code_init();
2554
2555     for (i = 0; i < self->fields_count; ++i)
2556     {
2557         if (!ir_builder_gen_field(self, self->fields[i])) {
2558             return false;
2559         }
2560     }
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                         case TYPE_VOID:
2725                                 oprintf("(void)");
2726                                 break;
2727                         case TYPE_FLOAT:
2728                                 oprintf("%g", v->constval.vfloat);
2729                                 break;
2730                         case TYPE_VECTOR:
2731                                 oprintf("'%g %g %g'",
2732                                         v->constval.vvec.x,
2733                                         v->constval.vvec.y,
2734                                         v->constval.vvec.z);
2735                                 break;
2736                         case TYPE_ENTITY:
2737                                 oprintf("(entity)");
2738                                 break;
2739                         case TYPE_STRING:
2740                                 oprintf("\"%s\"", v->constval.vstring);
2741                                 break;
2742 #if 0
2743                         case TYPE_INTEGER:
2744                                 oprintf("%i", v->constval.vint);
2745                                 break;
2746 #endif
2747                         case TYPE_POINTER:
2748                                 oprintf("&%s",
2749                                         v->constval.vpointer->name);
2750                                 break;
2751                 }
2752         } else {
2753                 oprintf("%s", v->name);
2754         }
2755 }
2756
2757 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2758 {
2759         size_t i;
2760         oprintf("Life of %s:\n", self->name);
2761         for (i = 0; i < self->life_count; ++i)
2762         {
2763                 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
2764         }
2765 }