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