]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
ir_function.allocated_locals now contains the number of locals a function requires...
[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.local = a;
1585             break;
1586         }
1587         if (a >= alloc.locals_count) {
1588             self->values[i]->code.local = 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     self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1606
1607     /* Take over the actual slot positions */
1608     for (i = 0; i < self->values_count; ++i)
1609         self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1610
1611     goto cleanup;
1612
1613 error:
1614     retval = false;
1615 cleanup:
1616     for (i = 0; i < alloc.locals_count; ++i)
1617         ir_value_delete(alloc.locals[i]);
1618     MEM_VECTOR_CLEAR(&alloc, locals);
1619     MEM_VECTOR_CLEAR(&alloc, sizes);
1620     MEM_VECTOR_CLEAR(&alloc, positions);
1621     return retval;
1622 }
1623
1624 /* Get information about which operand
1625  * is read from, or written to.
1626  */
1627 static void ir_op_read_write(int op, size_t *read, size_t *write)
1628 {
1629     switch (op)
1630     {
1631     case VINSTR_JUMP:
1632     case INSTR_GOTO:
1633         *write = 0;
1634         *read = 0;
1635         break;
1636     case INSTR_IF:
1637     case INSTR_IFNOT:
1638 #if 0
1639     case INSTR_IF_S:
1640     case INSTR_IFNOT_S:
1641 #endif
1642     case INSTR_RETURN:
1643     case VINSTR_COND:
1644         *write = 0;
1645         *read = 1;
1646         break;
1647     default:
1648         *write = 1;
1649         *read = 6;
1650         break;
1651     };
1652 }
1653
1654 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1655 {
1656     size_t i;
1657     bool changed = false;
1658     bool tempbool;
1659     for (i = 0; i != self->living_count; ++i)
1660     {
1661         tempbool = ir_value_life_merge(self->living[i], eid);
1662         /* debug
1663         if (tempbool)
1664             fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1665         */
1666         changed = changed || tempbool;
1667     }
1668     return changed;
1669 }
1670
1671 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1672 {
1673     size_t i;
1674     /* values which have been read in a previous iteration are now
1675      * in the "living" array even if the previous block doesn't use them.
1676      * So we have to remove whatever does not exist in the previous block.
1677      * They will be re-added on-read, but the liferange merge won't cause
1678      * a change.
1679      */
1680     for (i = 0; i < self->living_count; ++i)
1681     {
1682         if (!ir_block_living_find(prev, self->living[i], NULL)) {
1683             if (!ir_block_living_remove(self, i))
1684                 return false;
1685             --i;
1686         }
1687     }
1688
1689     /* Whatever the previous block still has in its living set
1690      * must now be added to ours as well.
1691      */
1692     for (i = 0; i < prev->living_count; ++i)
1693     {
1694         if (ir_block_living_find(self, prev->living[i], NULL))
1695             continue;
1696         if (!ir_block_living_add(self, prev->living[i]))
1697             return false;
1698         /*
1699         printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1700         */
1701     }
1702     return true;
1703 }
1704
1705 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1706 {
1707     ir_instr *instr;
1708     ir_value *value;
1709     bool  tempbool;
1710     size_t i, o, p;
1711     /* bitmasks which operands are read from or written to */
1712     size_t read, write;
1713 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1714     size_t rd;
1715     new_reads_t new_reads;
1716 #endif
1717     char dbg_ind[16] = { '#', '0' };
1718     (void)dbg_ind;
1719
1720 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1721     MEM_VECTOR_INIT(&new_reads, v);
1722 #endif
1723
1724     if (prev)
1725     {
1726         if (!ir_block_life_prop_previous(self, prev, changed))
1727             return false;
1728     }
1729
1730     i = self->instr_count;
1731     while (i)
1732     { --i;
1733         instr = self->instr[i];
1734
1735         /* PHI operands are always read operands */
1736         for (p = 0; p < instr->phi_count; ++p)
1737         {
1738             value = instr->phi[p].value;
1739 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1740             if (!ir_block_living_find(self, value, NULL) &&
1741                 !ir_block_living_add(self, value))
1742             {
1743                 goto on_error;
1744             }
1745 #else
1746             if (!new_reads_t_v_find(&new_reads, value, NULL))
1747             {
1748                 if (!new_reads_t_v_add(&new_reads, value))
1749                     goto on_error;
1750             }
1751 #endif
1752         }
1753
1754         /* See which operands are read and write operands */
1755         ir_op_read_write(instr->opcode, &read, &write);
1756
1757         /* Go through the 3 main operands */
1758         for (o = 0; o < 3; ++o)
1759         {
1760             if (!instr->_ops[o]) /* no such operand */
1761                 continue;
1762
1763             value = instr->_ops[o];
1764
1765             /* We only care about locals */
1766             if (value->store != store_value &&
1767                 value->store != store_local)
1768                 continue;
1769
1770             /* read operands */
1771             if (read & (1<<o))
1772             {
1773 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1774                 if (!ir_block_living_find(self, value, NULL) &&
1775                     !ir_block_living_add(self, value))
1776                 {
1777                     goto on_error;
1778                 }
1779 #else
1780                 /* fprintf(stderr, "read: %s\n", value->_name); */
1781                 if (!new_reads_t_v_find(&new_reads, value, NULL))
1782                 {
1783                     if (!new_reads_t_v_add(&new_reads, value))
1784                         goto on_error;
1785                 }
1786 #endif
1787             }
1788
1789             /* write operands */
1790             /* When we write to a local, we consider it "dead" for the
1791              * remaining upper part of the function, since in SSA a value
1792              * can only be written once (== created)
1793              */
1794             if (write & (1<<o))
1795             {
1796                 size_t idx;
1797                 bool in_living = ir_block_living_find(self, value, &idx);
1798 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1799                 size_t readidx;
1800                 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1801                 if (!in_living && !in_reads)
1802 #else
1803                 if (!in_living)
1804 #endif
1805                 {
1806                     /* If the value isn't alive it hasn't been read before... */
1807                     /* TODO: See if the warning can be emitted during parsing or AST processing
1808                      * otherwise have warning printed here.
1809                      * IF printing a warning here: include filecontext_t,
1810                      * and make sure it's only printed once
1811                      * since this function is run multiple times.
1812                      */
1813                     /* For now: debug info: */
1814                     fprintf(stderr, "Value only written %s\n", value->name);
1815                     tempbool = ir_value_life_merge(value, instr->eid);
1816                     *changed = *changed || tempbool;
1817                     /*
1818                     ir_instr_dump(instr, dbg_ind, printf);
1819                     abort();
1820                     */
1821                 } else {
1822                     /* since 'living' won't contain it
1823                      * anymore, merge the value, since
1824                      * (A) doesn't.
1825                      */
1826                     tempbool = ir_value_life_merge(value, instr->eid);
1827                     /*
1828                     if (tempbool)
1829                         fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1830                     */
1831                     *changed = *changed || tempbool;
1832                     /* Then remove */
1833 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1834                     if (!ir_block_living_remove(self, idx))
1835                         goto on_error;
1836 #else
1837                     if (in_reads)
1838                     {
1839                         if (!new_reads_t_v_remove(&new_reads, readidx))
1840                             goto on_error;
1841                     }
1842 #endif
1843                 }
1844             }
1845         }
1846         /* (A) */
1847         tempbool = ir_block_living_add_instr(self, instr->eid);
1848         /*fprintf(stderr, "living added values\n");*/
1849         *changed = *changed || tempbool;
1850
1851 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1852         /* new reads: */
1853         for (rd = 0; rd < new_reads.v_count; ++rd)
1854         {
1855             if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1856                 if (!ir_block_living_add(self, new_reads.v[rd]))
1857                     goto on_error;
1858             }
1859             if (!i && !self->entries_count) {
1860                 /* fix the top */
1861                 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1862             }
1863         }
1864         MEM_VECTOR_CLEAR(&new_reads, v);
1865 #endif
1866     }
1867
1868     if (self->run_id == self->owner->run_id)
1869         return true;
1870
1871     self->run_id = self->owner->run_id;
1872
1873     for (i = 0; i < self->entries_count; ++i)
1874     {
1875         ir_block *entry = self->entries[i];
1876         ir_block_life_propagate(entry, self, changed);
1877     }
1878
1879     return true;
1880 on_error:
1881 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1882     MEM_VECTOR_CLEAR(&new_reads, v);
1883 #endif
1884     return false;
1885 }
1886
1887 /***********************************************************************
1888  *IR Code-Generation
1889  *
1890  * Since the IR has the convention of putting 'write' operands
1891  * at the beginning, we have to rotate the operands of instructions
1892  * properly in order to generate valid QCVM code.
1893  *
1894  * Having destinations at a fixed position is more convenient. In QC
1895  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
1896  * read from from OPA,  and store to OPB rather than OPC.   Which is
1897  * partially the reason why the implementation of these instructions
1898  * in darkplaces has been delayed for so long.
1899  *
1900  * Breaking conventions is annoying...
1901  */
1902 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
1903
1904 static bool gen_global_field(ir_value *global)
1905 {
1906     if (global->isconst)
1907     {
1908         ir_value *fld = global->constval.vpointer;
1909         if (!fld) {
1910             printf("Invalid field constant with no field: %s\n", global->name);
1911             return false;
1912         }
1913
1914         /* Now, in this case, a relocation would be impossible to code
1915          * since it looks like this:
1916          * .vector v = origin;     <- parse error, wtf is 'origin'?
1917          * .vector origin;
1918          *
1919          * But we will need a general relocation support later anyway
1920          * for functions... might as well support that here.
1921          */
1922         if (!fld->code.globaladdr) {
1923             printf("FIXME: Relocation support\n");
1924             return false;
1925         }
1926
1927         /* copy the field's value */
1928         global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
1929     }
1930     else
1931     {
1932         prog_section_field fld;
1933
1934         fld.name = global->code.name;
1935         fld.offset = code_fields_elements;
1936         fld.type = global->fieldtype;
1937
1938         if (fld.type == TYPE_VOID) {
1939             printf("Field is missing a type: %s\n", global->name);
1940             return false;
1941         }
1942
1943         if (code_fields_add(fld) < 0)
1944             return false;
1945
1946         global->code.globaladdr = code_globals_add(fld.offset);
1947     }
1948     if (global->code.globaladdr < 0)
1949         return false;
1950     return true;
1951 }
1952
1953 static bool gen_global_pointer(ir_value *global)
1954 {
1955     if (global->isconst)
1956     {
1957         ir_value *target = global->constval.vpointer;
1958         if (!target) {
1959             printf("Invalid pointer constant: %s\n", global->name);
1960             /* NULL pointers are pointing to the NULL constant, which also
1961              * sits at address 0, but still has an ir_value for itself.
1962              */
1963             return false;
1964         }
1965
1966         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
1967          * void() foo; <- proto
1968          * void() *fooptr = &foo;
1969          * void() foo = { code }
1970          */
1971         if (!target->code.globaladdr) {
1972             /* FIXME: Check for the constant nullptr ir_value!
1973              * because then code.globaladdr being 0 is valid.
1974              */
1975             printf("FIXME: Relocation support\n");
1976             return false;
1977         }
1978
1979         global->code.globaladdr = code_globals_add(target->code.globaladdr);
1980     }
1981     else
1982     {
1983         global->code.globaladdr = code_globals_add(0);
1984     }
1985     if (global->code.globaladdr < 0)
1986         return false;
1987     return true;
1988 }
1989
1990 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
1991 {
1992     prog_section_statement stmt;
1993     prog_section_statement *stptr;
1994     ir_instr *instr;
1995     ir_block *target;
1996     ir_block *ontrue;
1997     ir_block *onfalse;
1998     size_t    stidx;
1999     size_t    i;
2000
2001 tailcall:
2002     block->generated = true;
2003     block->code_start = code_statements_elements;
2004     for (i = 0; i < block->instr_count; ++i)
2005     {
2006         instr = block->instr[i];
2007
2008         if (instr->opcode == VINSTR_PHI) {
2009             printf("cannot generate virtual instruction (phi)\n");
2010             return false;
2011         }
2012
2013         if (instr->opcode == VINSTR_JUMP) {
2014             target = instr->bops[0];
2015             /* for uncoditional jumps, if the target hasn't been generated
2016              * yet, we generate them right here.
2017              */
2018             if (!target->generated) {
2019                 block = target;
2020                 goto tailcall;
2021             }
2022
2023             /* otherwise we generate a jump instruction */
2024             stmt.opcode = INSTR_GOTO;
2025             stmt.o1.s1 = (target->code_start-1) - code_statements_elements;
2026             stmt.o2.s1 = 0;
2027             stmt.o3.s1 = 0;
2028             if (code_statements_add(stmt) < 0)
2029                 return false;
2030
2031             /* no further instructions can be in this block */
2032             return true;
2033         }
2034
2035         if (instr->opcode == VINSTR_COND) {
2036             ontrue  = instr->bops[0];
2037             onfalse = instr->bops[1];
2038             /* TODO: have the AST signal which block should
2039              * come first: eg. optimize IFs without ELSE...
2040              */
2041
2042             stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2043
2044             stmt.o3.s1 = 0;
2045             if (ontrue->generated) {
2046                 stmt.opcode = INSTR_IF;
2047                 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2048                 if (code_statements_add(stmt) < 0)
2049                     return false;
2050             }
2051             if (onfalse->generated) {
2052                 stmt.opcode = INSTR_IFNOT;
2053                 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2054                 if (code_statements_add(stmt) < 0)
2055                     return false;
2056             }
2057             if (!ontrue->generated) {
2058                 if (onfalse->generated) {
2059                     block = ontrue;
2060                     goto tailcall;
2061                 }
2062             }
2063             if (!onfalse->generated) {
2064                 if (ontrue->generated) {
2065                     block = onfalse;
2066                     goto tailcall;
2067                 }
2068             }
2069             /* neither ontrue nor onfalse exist */
2070             stmt.opcode = INSTR_IFNOT;
2071             stidx = code_statements_elements - 1;
2072             if (code_statements_add(stmt) < 0)
2073                 return false;
2074             stptr = &code_statements_data[stidx];
2075             /* on false we jump, so add ontrue-path */
2076             if (!gen_blocks_recursive(func, ontrue))
2077                 return false;
2078             /* fixup the jump address */
2079             stptr->o2.s1 = (ontrue->code_start-1) - (stidx+1);
2080             /* generate onfalse path */
2081             if (onfalse->generated) {
2082                 /* may have been generated in the previous recursive call */
2083                 stmt.opcode = INSTR_GOTO;
2084                 stmt.o2.s1 = 0;
2085                 stmt.o3.s1 = 0;
2086                 stmt.o1.s1 = (onfalse->code_start-1) - code_statements_elements;
2087                 return (code_statements_add(stmt) >= 0);
2088             }
2089             /* if not, generate now */
2090             block = onfalse;
2091             goto tailcall;
2092         }
2093
2094         if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2095             printf("TODO: call instruction\n");
2096             return false;
2097         }
2098
2099         if (instr->opcode == INSTR_STATE) {
2100             printf("TODO: state instruction\n");
2101             return false;
2102         }
2103
2104         stmt.opcode = instr->opcode;
2105         stmt.o1.u1 = 0;
2106         stmt.o2.u1 = 0;
2107         stmt.o3.u1 = 0;
2108
2109         /* This is the general order of operands */
2110         if (instr->_ops[0])
2111             stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2112
2113         if (instr->_ops[1])
2114             stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2115
2116         if (instr->_ops[2])
2117             stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2118
2119         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2120         {
2121             stmt.o1.u1 = stmt.o3.u1;
2122             stmt.o3.u1 = 0;
2123         }
2124         else if ((stmt.opcode >= INSTR_STORE_F    &&
2125                   stmt.opcode <= INSTR_STORE_FNC)    ||
2126                  (stmt.opcode >= INSTR_NOT_F      &&
2127                   stmt.opcode <= INSTR_NOT_FNC))
2128         {
2129             /* 2-operand instructions with A -> B */
2130             stmt.o2.u1 = stmt.o3.u1;
2131             stmt.o3.u1 = 0;
2132         }
2133
2134         if (code_statements_add(stmt) < 0)
2135             return false;
2136     }
2137     return true;
2138 }
2139
2140 static bool gen_function_code(ir_function *self)
2141 {
2142     ir_block *block;
2143
2144     /* Starting from entry point, we generate blocks "as they come"
2145      * for now. Dead blocks will not be translated obviously.
2146      */
2147     if (!self->blocks_count) {
2148         printf("Function '%s' declared without body.\n", self->name);
2149         return false;
2150     }
2151
2152     block = self->blocks[0];
2153     if (block->generated)
2154         return true;
2155
2156     if (!gen_blocks_recursive(self, block)) {
2157         printf("failed to generate blocks for '%s'\n", self->name);
2158         return false;
2159     }
2160     return true;
2161 }
2162
2163 static bool gen_global_function(ir_builder *ir, ir_value *global)
2164 {
2165     prog_section_function fun;
2166     ir_function          *irfun;
2167
2168     size_t i;
2169
2170     if (!global->isconst ||
2171         !global->constval.vfunc)
2172     {
2173         printf("Invalid state of function-global: not constant: %s\n", global->name);
2174         return false;
2175     }
2176
2177     irfun = global->constval.vfunc;
2178
2179     fun.name    = global->code.name;
2180     fun.file    = code_cachedstring(global->context.file);
2181     fun.profile = 0; /* always 0 */
2182     fun.nargs   = irfun->params_count;
2183
2184     for (i = 0;i < 8; ++i) {
2185         if (i >= fun.nargs)
2186             fun.argsize[i] = 0;
2187         else if (irfun->params[i] == TYPE_VECTOR)
2188             fun.argsize[i] = 3;
2189         else
2190             fun.argsize[i] = 1;
2191     }
2192
2193     fun.firstlocal = code_globals_elements;
2194     fun.locals = irfun->locals_count;
2195     for (i = 0; i < irfun->locals_count; ++i) {
2196         if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2197             printf("Failed to generate global %s\n", irfun->locals[i]->name);
2198             return false;
2199         }
2200     }
2201
2202     fun.entry      = code_statements_elements;
2203     if (!gen_function_code(irfun)) {
2204         printf("Failed to generate code for function %s\n", irfun->name);
2205         return false;
2206     }
2207
2208     return (code_functions_add(fun) >= 0);
2209 }
2210
2211 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2212 {
2213     int32_t         *iptr;
2214     prog_section_def def;
2215
2216     def.type   = global->vtype;
2217     def.offset = code_globals_elements;
2218     def.name   = global->code.name       = code_genstring(global->name);
2219
2220     switch (global->vtype)
2221     {
2222     case TYPE_POINTER:
2223         if (code_defs_add(def) < 0)
2224             return false;
2225         return gen_global_pointer(global);
2226     case TYPE_FIELD:
2227         if (code_defs_add(def) < 0)
2228             return false;
2229         return gen_global_field(global);
2230     case TYPE_ENTITY:
2231         /* fall through */
2232     case TYPE_FLOAT:
2233     {
2234         if (code_defs_add(def) < 0)
2235             return false;
2236
2237         if (global->isconst) {
2238             iptr = (int32_t*)&global->constval.vfloat;
2239             global->code.globaladdr = code_globals_add(*iptr);
2240         } else
2241             global->code.globaladdr = code_globals_add(0);
2242
2243         return global->code.globaladdr >= 0;
2244     }
2245     case TYPE_STRING:
2246     {
2247         if (code_defs_add(def) < 0)
2248             return false;
2249         if (global->isconst)
2250             global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2251         else
2252             global->code.globaladdr = code_globals_add(0);
2253         return global->code.globaladdr >= 0;
2254     }
2255     case TYPE_VECTOR:
2256     {
2257         if (code_defs_add(def) < 0)
2258             return false;
2259
2260         if (global->isconst) {
2261             iptr = (int32_t*)&global->constval.vvec;
2262             global->code.globaladdr = code_globals_add(iptr[0]);
2263             if (code_globals_add(iptr[1]) < 0 || code_globals_add(iptr[2]) < 0)
2264                 return false;
2265         } else {
2266             global->code.globaladdr = code_globals_add(0);
2267             if (code_globals_add(0) < 0 || code_globals_add(0) < 0)
2268                 return false;
2269         }
2270         return global->code.globaladdr >= 0;
2271     }
2272     case TYPE_FUNCTION:
2273         if (code_defs_add(def) < 0)
2274             return false;
2275         code_globals_add(code_functions_elements);
2276         return gen_global_function(self, global);
2277     case TYPE_VARIANT:
2278         /* assume biggest type */
2279             global->code.globaladdr = code_globals_add(0);
2280             code_globals_add(0);
2281             code_globals_add(0);
2282             return true;
2283     default:
2284         /* refuse to create 'void' type or any other fancy business. */
2285         printf("Invalid type for global variable %s\n", global->name);
2286         return false;
2287     }
2288 }
2289
2290 bool ir_builder_generate(ir_builder *self, const char *filename)
2291 {
2292     size_t i;
2293
2294     code_init();
2295
2296     /* FIXME: generate TYPE_FUNCTION globals and link them
2297      * to their ir_function.
2298      */
2299
2300     for (i = 0; i < self->functions_count; ++i)
2301     {
2302         ir_value    *funval;
2303         ir_function *fun = self->functions[i];
2304
2305         funval = ir_builder_create_global(self, fun->name, TYPE_FUNCTION);
2306         funval->isconst = true;
2307         funval->constval.vfunc = fun;
2308         funval->context = fun->context;
2309     }
2310
2311     for (i = 0; i < self->globals_count; ++i)
2312     {
2313         if (!ir_builder_gen_global(self, self->globals[i])) {
2314             return false;
2315         }
2316     }
2317
2318     printf("writing '%s'...\n", filename);
2319     return code_write(filename);
2320 }
2321
2322 /***********************************************************************
2323  *IR DEBUG Dump functions...
2324  */
2325
2326 #define IND_BUFSZ 1024
2327
2328 const char *qc_opname(int op)
2329 {
2330     if (op < 0) return "<INVALID>";
2331     if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2332         return asm_instr[op].m;
2333     switch (op) {
2334         case VINSTR_PHI:  return "PHI";
2335         case VINSTR_JUMP: return "JUMP";
2336         case VINSTR_COND: return "COND";
2337         default:          return "<UNK>";
2338     }
2339 }
2340
2341 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2342 {
2343         size_t i;
2344         char indent[IND_BUFSZ];
2345         indent[0] = '\t';
2346         indent[1] = 0;
2347
2348         oprintf("module %s\n", b->name);
2349         for (i = 0; i < b->globals_count; ++i)
2350         {
2351                 oprintf("global ");
2352                 if (b->globals[i]->isconst)
2353                         oprintf("%s = ", b->globals[i]->name);
2354                 ir_value_dump(b->globals[i], oprintf);
2355                 oprintf("\n");
2356         }
2357         for (i = 0; i < b->functions_count; ++i)
2358                 ir_function_dump(b->functions[i], indent, oprintf);
2359         oprintf("endmodule %s\n", b->name);
2360 }
2361
2362 void ir_function_dump(ir_function *f, char *ind,
2363                       int (*oprintf)(const char*, ...))
2364 {
2365         size_t i;
2366         oprintf("%sfunction %s\n", ind, f->name);
2367         strncat(ind, "\t", IND_BUFSZ);
2368         if (f->locals_count)
2369         {
2370                 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2371                 for (i = 0; i < f->locals_count; ++i) {
2372                         oprintf("%s\t", ind);
2373                         ir_value_dump(f->locals[i], oprintf);
2374                         oprintf("\n");
2375                 }
2376         }
2377         if (f->blocks_count)
2378         {
2379                 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2380                 for (i = 0; i < f->blocks_count; ++i) {
2381                     if (f->blocks[i]->run_id != f->run_id) {
2382                         oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2383                     }
2384                         ir_block_dump(f->blocks[i], ind, oprintf);
2385                 }
2386
2387         }
2388         ind[strlen(ind)-1] = 0;
2389         oprintf("%sendfunction %s\n", ind, f->name);
2390 }
2391
2392 void ir_block_dump(ir_block* b, char *ind,
2393                    int (*oprintf)(const char*, ...))
2394 {
2395         size_t i;
2396         oprintf("%s:%s\n", ind, b->label);
2397         strncat(ind, "\t", IND_BUFSZ);
2398
2399         for (i = 0; i < b->instr_count; ++i)
2400                 ir_instr_dump(b->instr[i], ind, oprintf);
2401         ind[strlen(ind)-1] = 0;
2402 }
2403
2404 void dump_phi(ir_instr *in, char *ind,
2405               int (*oprintf)(const char*, ...))
2406 {
2407         size_t i;
2408         oprintf("%s <- phi ", in->_ops[0]->name);
2409         for (i = 0; i < in->phi_count; ++i)
2410         {
2411                 oprintf("([%s] : %s) ", in->phi[i].from->label,
2412                                         in->phi[i].value->name);
2413         }
2414         oprintf("\n");
2415 }
2416
2417 void ir_instr_dump(ir_instr *in, char *ind,
2418                        int (*oprintf)(const char*, ...))
2419 {
2420         size_t i;
2421         const char *comma = NULL;
2422
2423         oprintf("%s (%i) ", ind, (int)in->eid);
2424
2425         if (in->opcode == VINSTR_PHI) {
2426                 dump_phi(in, ind, oprintf);
2427                 return;
2428         }
2429
2430         strncat(ind, "\t", IND_BUFSZ);
2431
2432         if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2433                 ir_value_dump(in->_ops[0], oprintf);
2434                 if (in->_ops[1] || in->_ops[2])
2435                         oprintf(" <- ");
2436         }
2437         oprintf("%s\t", qc_opname(in->opcode));
2438         if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2439                 ir_value_dump(in->_ops[0], oprintf);
2440                 comma = ",\t";
2441         }
2442         else
2443         {
2444                 for (i = 1; i != 3; ++i) {
2445                         if (in->_ops[i]) {
2446                                 if (comma)
2447                                         oprintf(comma);
2448                                 ir_value_dump(in->_ops[i], oprintf);
2449                                 comma = ",\t";
2450                         }
2451                 }
2452         }
2453         if (in->bops[0]) {
2454                 if (comma)
2455                         oprintf(comma);
2456                 oprintf("[%s]", in->bops[0]->label);
2457                 comma = ",\t";
2458         }
2459         if (in->bops[1])
2460                 oprintf("%s[%s]", comma, in->bops[1]->label);
2461         oprintf("\n");
2462         ind[strlen(ind)-1] = 0;
2463 }
2464
2465 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2466 {
2467         if (v->isconst) {
2468                 switch (v->vtype) {
2469                         case TYPE_VOID:
2470                                 oprintf("(void)");
2471                                 break;
2472                         case TYPE_FLOAT:
2473                                 oprintf("%g", v->constval.vfloat);
2474                                 break;
2475                         case TYPE_VECTOR:
2476                                 oprintf("'%g %g %g'",
2477                                         v->constval.vvec.x,
2478                                         v->constval.vvec.y,
2479                                         v->constval.vvec.z);
2480                                 break;
2481                         case TYPE_ENTITY:
2482                                 oprintf("(entity)");
2483                                 break;
2484                         case TYPE_STRING:
2485                                 oprintf("\"%s\"", v->constval.vstring);
2486                                 break;
2487 #if 0
2488                         case TYPE_INTEGER:
2489                                 oprintf("%i", v->constval.vint);
2490                                 break;
2491 #endif
2492                         case TYPE_POINTER:
2493                                 oprintf("&%s",
2494                                         v->constval.vpointer->name);
2495                                 break;
2496                 }
2497         } else {
2498                 oprintf("%s", v->name);
2499         }
2500 }
2501
2502 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2503 {
2504         size_t i;
2505         oprintf("Life of %s:\n", self->name);
2506         for (i = 0; i < self->life_count; ++i)
2507         {
2508                 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
2509         }
2510 }