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