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