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