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