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