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