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