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