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