0f5b05ca4a98383e22e61f4989c451ce94e353e5
[xonotic/gmqcc.git] / ast.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Wolfgang Bumiller
4  *     Dale Weiler 
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "gmqcc.h"
29 #include "ast.h"
30
31 #define ast_instantiate(T, ctx, destroyfn)                          \
32     T* self = (T*)mem_a(sizeof(T));                                 \
33     if (!self) {                                                    \
34         return NULL;                                                \
35     }                                                               \
36     ast_node_init((ast_node*)self, ctx, TYPE_##T);                  \
37     ( (ast_node*)self )->node.destroy = (ast_node_delete*)destroyfn
38
39
40 /* It must not be possible to get here. */
41 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
42 {
43     (void)self;
44     con_err("ast node missing destroy()\n");
45     abort();
46 }
47
48 /* Initialize main ast node aprts */
49 static void ast_node_init(ast_node *self, lex_ctx ctx, int nodetype)
50 {
51     self->node.context = ctx;
52     self->node.destroy = &_ast_node_destroy;
53     self->node.keep    = false;
54     self->node.nodetype = nodetype;
55     self->node.side_effects = false;
56 }
57
58 /* weight and side effects */
59 static void _ast_propagate_effects(ast_node *self, ast_node *other)
60 {
61     if (ast_side_effects(other))
62         ast_side_effects(self) = true;
63 }
64 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
65
66 /* General expression initialization */
67 static void ast_expression_init(ast_expression *self,
68                                 ast_expression_codegen *codegen)
69 {
70     self->expression.codegen  = codegen;
71     self->expression.vtype    = TYPE_VOID;
72     self->expression.next     = NULL;
73     self->expression.outl     = NULL;
74     self->expression.outr     = NULL;
75     self->expression.params   = NULL;
76     self->expression.count    = 0;
77     self->expression.flags    = 0;
78     self->expression.varparam = NULL;
79 }
80
81 static void ast_expression_delete(ast_expression *self)
82 {
83     size_t i;
84     if (self->expression.next)
85         ast_delete(self->expression.next);
86     for (i = 0; i < vec_size(self->expression.params); ++i) {
87         ast_delete(self->expression.params[i]);
88     }
89     vec_free(self->expression.params);
90 }
91
92 static void ast_expression_delete_full(ast_expression *self)
93 {
94     ast_expression_delete(self);
95     mem_d(self);
96 }
97
98 ast_value* ast_value_copy(const ast_value *self)
99 {
100     size_t i;
101     const ast_expression_common *fromex;
102     ast_expression_common *selfex;
103     ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
104     if (self->expression.next) {
105         cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
106         if (!cp->expression.next) {
107             ast_value_delete(cp);
108             return NULL;
109         }
110     }
111     fromex   = &self->expression;
112     selfex = &cp->expression;
113     selfex->count    = fromex->count;
114     selfex->flags    = fromex->flags;
115     for (i = 0; i < vec_size(fromex->params); ++i) {
116         ast_value *v = ast_value_copy(fromex->params[i]);
117         if (!v) {
118             ast_value_delete(cp);
119             return NULL;
120         }
121         vec_push(selfex->params, v);
122     }
123     return cp;
124 }
125
126 bool ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
127 {
128     size_t i;
129     const ast_expression_common *fromex;
130     ast_expression_common *selfex;
131     self->expression.vtype = other->expression.vtype;
132     if (other->expression.next) {
133         self->expression.next = (ast_expression*)ast_type_copy(ast_ctx(self), other->expression.next);
134         if (!self->expression.next)
135             return false;
136     }
137     fromex   = &other->expression;
138     selfex = &self->expression;
139     selfex->count    = fromex->count;
140     selfex->flags    = fromex->flags;
141     for (i = 0; i < vec_size(fromex->params); ++i) {
142         ast_value *v = ast_value_copy(fromex->params[i]);
143         if (!v)
144             return false;
145         vec_push(selfex->params, v);
146     }
147     return true;
148 }
149
150 static ast_expression* ast_shallow_type(lex_ctx ctx, int vtype)
151 {
152     ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
153     ast_expression_init(self, NULL);
154     self->expression.codegen = NULL;
155     self->expression.next    = NULL;
156     self->expression.vtype   = vtype;
157     return self;
158 }
159
160 ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
161 {
162     size_t i;
163     const ast_expression_common *fromex;
164     ast_expression_common *selfex;
165
166     if (!ex)
167         return NULL;
168     else
169     {
170         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
171         ast_expression_init(self, NULL);
172
173         fromex   = &ex->expression;
174         selfex = &self->expression;
175
176         /* This may never be codegen()d */
177         selfex->codegen = NULL;
178
179         selfex->vtype = fromex->vtype;
180         if (fromex->next)
181         {
182             selfex->next = ast_type_copy(ctx, fromex->next);
183             if (!selfex->next) {
184                 ast_expression_delete_full(self);
185                 return NULL;
186             }
187         }
188         else
189             selfex->next = NULL;
190
191         selfex->count    = fromex->count;
192         selfex->flags    = fromex->flags;
193         for (i = 0; i < vec_size(fromex->params); ++i) {
194             ast_value *v = ast_value_copy(fromex->params[i]);
195             if (!v) {
196                 ast_expression_delete_full(self);
197                 return NULL;
198             }
199             vec_push(selfex->params, v);
200         }
201
202         return self;
203     }
204 }
205
206 bool ast_compare_type(ast_expression *a, ast_expression *b)
207 {
208     if (a->expression.vtype == TYPE_NIL ||
209         b->expression.vtype == TYPE_NIL)
210         return true;
211     if (a->expression.vtype != b->expression.vtype)
212         return false;
213     if (!a->expression.next != !b->expression.next)
214         return false;
215     if (vec_size(a->expression.params) != vec_size(b->expression.params))
216         return false;
217     if ((a->expression.flags & AST_FLAG_TYPE_MASK) !=
218         (b->expression.flags & AST_FLAG_TYPE_MASK) )
219     {
220         return false;
221     }
222     if (vec_size(a->expression.params)) {
223         size_t i;
224         for (i = 0; i < vec_size(a->expression.params); ++i) {
225             if (!ast_compare_type((ast_expression*)a->expression.params[i],
226                                   (ast_expression*)b->expression.params[i]))
227                 return false;
228         }
229     }
230     if (a->expression.next)
231         return ast_compare_type(a->expression.next, b->expression.next);
232     return true;
233 }
234
235 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
236 {
237     const char *typestr;
238     size_t typelen;
239     size_t i;
240
241     if (!e) {
242         if (pos + 6 >= bufsize)
243             goto full;
244         strcpy(buf + pos, "(null)");
245         return pos + 6;
246     }
247
248     if (pos + 1 >= bufsize)
249         goto full;
250
251     switch (e->expression.vtype) {
252         case TYPE_VARIANT:
253             strcpy(buf + pos, "(variant)");
254             return pos + 9;
255
256         case TYPE_FIELD:
257             buf[pos++] = '.';
258             return ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
259
260         case TYPE_POINTER:
261             if (pos + 3 >= bufsize)
262                 goto full;
263             buf[pos++] = '*';
264             buf[pos++] = '(';
265             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
266             if (pos + 1 >= bufsize)
267                 goto full;
268             buf[pos++] = ')';
269             return pos;
270
271         case TYPE_FUNCTION:
272             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
273             if (pos + 2 >= bufsize)
274                 goto full;
275             if (!vec_size(e->expression.params)) {
276                 buf[pos++] = '(';
277                 buf[pos++] = ')';
278                 return pos;
279             }
280             buf[pos++] = '(';
281             pos = ast_type_to_string_impl((ast_expression*)(e->expression.params[0]), buf, bufsize, pos);
282             for (i = 1; i < vec_size(e->expression.params); ++i) {
283                 if (pos + 2 >= bufsize)
284                     goto full;
285                 buf[pos++] = ',';
286                 buf[pos++] = ' ';
287                 pos = ast_type_to_string_impl((ast_expression*)(e->expression.params[i]), buf, bufsize, pos);
288             }
289             if (pos + 1 >= bufsize)
290                 goto full;
291             buf[pos++] = ')';
292             return pos;
293
294         case TYPE_ARRAY:
295             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
296             if (pos + 1 >= bufsize)
297                 goto full;
298             buf[pos++] = '[';
299             pos += snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->expression.count);
300             if (pos + 1 >= bufsize)
301                 goto full;
302             buf[pos++] = ']';
303             return pos;
304
305         default:
306             typestr = type_name[e->expression.vtype];
307             typelen = strlen(typestr);
308             if (pos + typelen >= bufsize)
309                 goto full;
310             strcpy(buf + pos, typestr);
311             return pos + typelen;
312     }
313
314 full:
315     buf[bufsize-3] = '.';
316     buf[bufsize-2] = '.';
317     buf[bufsize-1] = '.';
318     return bufsize;
319 }
320
321 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
322 {
323     size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
324     buf[pos] = 0;
325 }
326
327 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
328 {
329     ast_instantiate(ast_value, ctx, ast_value_delete);
330     ast_expression_init((ast_expression*)self,
331                         (ast_expression_codegen*)&ast_value_codegen);
332     self->expression.node.keep = true; /* keep */
333
334     self->name = name ? util_strdup(name) : NULL;
335     self->expression.vtype = t;
336     self->expression.next  = NULL;
337     self->isfield  = false;
338     self->cvq      = CV_NONE;
339     self->hasvalue = false;
340     self->uses    = 0;
341     memset(&self->constval, 0, sizeof(self->constval));
342
343     self->ir_v           = NULL;
344     self->ir_values      = NULL;
345     self->ir_value_count = 0;
346
347     self->setter = NULL;
348     self->getter = NULL;
349     self->desc   = NULL;
350
351     self->argcounter = NULL;
352
353     return self;
354 }
355
356 void ast_value_delete(ast_value* self)
357 {
358     if (self->name)
359         mem_d((void*)self->name);
360     if (self->argcounter)
361         mem_d((void*)self->argcounter);
362     if (self->hasvalue) {
363         switch (self->expression.vtype)
364         {
365         case TYPE_STRING:
366             mem_d((void*)self->constval.vstring);
367             break;
368         case TYPE_FUNCTION:
369             /* unlink us from the function node */
370             self->constval.vfunc->vtype = NULL;
371             break;
372         /* NOTE: delete function? currently collected in
373          * the parser structure
374          */
375         default:
376             break;
377         }
378     }
379     if (self->ir_values)
380         mem_d(self->ir_values);
381
382     if (self->desc)
383         mem_d(self->desc);
384
385     ast_expression_delete((ast_expression*)self);
386     mem_d(self);
387 }
388
389 void ast_value_params_add(ast_value *self, ast_value *p)
390 {
391     vec_push(self->expression.params, p);
392 }
393
394 bool ast_value_set_name(ast_value *self, const char *name)
395 {
396     if (self->name)
397         mem_d((void*)self->name);
398     self->name = util_strdup(name);
399     return !!self->name;
400 }
401
402 ast_binary* ast_binary_new(lex_ctx ctx, int op,
403                            ast_expression* left, ast_expression* right)
404 {
405     ast_instantiate(ast_binary, ctx, ast_binary_delete);
406     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
407
408     self->op = op;
409     self->left = left;
410     self->right = right;
411
412     ast_propagate_effects(self, left);
413     ast_propagate_effects(self, right);
414
415     if (op >= INSTR_EQ_F && op <= INSTR_GT)
416         self->expression.vtype = TYPE_FLOAT;
417     else if (op == INSTR_AND || op == INSTR_OR) {
418         if (OPTS_FLAG(PERL_LOGIC))
419             ast_type_adopt(self, right);
420         else
421             self->expression.vtype = TYPE_FLOAT;
422     }
423     else if (op == INSTR_BITAND || op == INSTR_BITOR)
424         self->expression.vtype = TYPE_FLOAT;
425     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
426         self->expression.vtype = TYPE_VECTOR;
427     else if (op == INSTR_MUL_V)
428         self->expression.vtype = TYPE_FLOAT;
429     else
430         self->expression.vtype = left->expression.vtype;
431
432     return self;
433 }
434
435 void ast_binary_delete(ast_binary *self)
436 {
437     ast_unref(self->left);
438     ast_unref(self->right);
439     ast_expression_delete((ast_expression*)self);
440     mem_d(self);
441 }
442
443 ast_binstore* ast_binstore_new(lex_ctx ctx, int storop, int op,
444                                ast_expression* left, ast_expression* right)
445 {
446     ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
447     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
448
449     ast_side_effects(self) = true;
450
451     self->opstore = storop;
452     self->opbin   = op;
453     self->dest    = left;
454     self->source  = right;
455
456     self->keep_dest = false;
457
458     if (!ast_type_adopt(self, left)) {
459         ast_delete(self);
460         return NULL;
461     }
462
463     return self;
464 }
465
466 void ast_binstore_delete(ast_binstore *self)
467 {
468     if (!self->keep_dest)
469         ast_unref(self->dest);
470     ast_unref(self->source);
471     ast_expression_delete((ast_expression*)self);
472     mem_d(self);
473 }
474
475 ast_unary* ast_unary_new(lex_ctx ctx, int op,
476                          ast_expression *expr)
477 {
478     ast_instantiate(ast_unary, ctx, ast_unary_delete);
479     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
480
481     self->op = op;
482     self->operand = expr;
483
484     ast_propagate_effects(self, expr);
485
486     if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
487         self->expression.vtype = TYPE_FLOAT;
488     } else
489         compile_error(ctx, "cannot determine type of unary operation %s", asm_instr[op].m);
490
491     return self;
492 }
493
494 void ast_unary_delete(ast_unary *self)
495 {
496     if (self->operand) ast_unref(self->operand);
497     ast_expression_delete((ast_expression*)self);
498     mem_d(self);
499 }
500
501 ast_return* ast_return_new(lex_ctx ctx, ast_expression *expr)
502 {
503     ast_instantiate(ast_return, ctx, ast_return_delete);
504     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
505
506     self->operand = expr;
507
508     if (expr)
509         ast_propagate_effects(self, expr);
510
511     return self;
512 }
513
514 void ast_return_delete(ast_return *self)
515 {
516     if (self->operand)
517         ast_unref(self->operand);
518     ast_expression_delete((ast_expression*)self);
519     mem_d(self);
520 }
521
522 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
523 {
524     if (field->expression.vtype != TYPE_FIELD) {
525         compile_error(ctx, "ast_entfield_new with expression not of type field");
526         return NULL;
527     }
528     return ast_entfield_new_force(ctx, entity, field, field->expression.next);
529 }
530
531 ast_entfield* ast_entfield_new_force(lex_ctx ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
532 {
533     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
534
535     if (!outtype) {
536         mem_d(self);
537         /* Error: field has no type... */
538         return NULL;
539     }
540
541     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
542
543     self->entity = entity;
544     self->field  = field;
545     ast_propagate_effects(self, entity);
546     ast_propagate_effects(self, field);
547
548     if (!ast_type_adopt(self, outtype)) {
549         ast_entfield_delete(self);
550         return NULL;
551     }
552
553     return self;
554 }
555
556 void ast_entfield_delete(ast_entfield *self)
557 {
558     ast_unref(self->entity);
559     ast_unref(self->field);
560     ast_expression_delete((ast_expression*)self);
561     mem_d(self);
562 }
563
564 ast_member* ast_member_new(lex_ctx ctx, ast_expression *owner, unsigned int field, const char *name)
565 {
566     ast_instantiate(ast_member, ctx, ast_member_delete);
567     if (field >= 3) {
568         mem_d(self);
569         return NULL;
570     }
571
572     if (owner->expression.vtype != TYPE_VECTOR &&
573         owner->expression.vtype != TYPE_FIELD) {
574         compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->expression.vtype]);
575         mem_d(self);
576         return NULL;
577     }
578
579     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
580     self->expression.node.keep = true; /* keep */
581
582     if (owner->expression.vtype == TYPE_VECTOR) {
583         self->expression.vtype = TYPE_FLOAT;
584         self->expression.next  = NULL;
585     } else {
586         self->expression.vtype = TYPE_FIELD;
587         self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
588     }
589
590     self->rvalue = false;
591     self->owner  = owner;
592     ast_propagate_effects(self, owner);
593
594     self->field = field;
595     if (name)
596         self->name = util_strdup(name);
597     else
598         self->name = NULL;
599
600     return self;
601 }
602
603 void ast_member_delete(ast_member *self)
604 {
605     /* The owner is always an ast_value, which has .keep=true,
606      * also: ast_members are usually deleted after the owner, thus
607      * this will cause invalid access
608     ast_unref(self->owner);
609      * once we allow (expression).x to access a vector-member, we need
610      * to change this: preferably by creating an alternate ast node for this
611      * purpose that is not garbage-collected.
612     */
613     ast_expression_delete((ast_expression*)self);
614     mem_d(self);
615 }
616
617 bool ast_member_set_name(ast_member *self, const char *name)
618 {
619     if (self->name)
620         mem_d((void*)self->name);
621     self->name = util_strdup(name);
622     return !!self->name;
623 }
624
625 ast_array_index* ast_array_index_new(lex_ctx ctx, ast_expression *array, ast_expression *index)
626 {
627     ast_expression *outtype;
628     ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
629
630     outtype = array->expression.next;
631     if (!outtype) {
632         mem_d(self);
633         /* Error: field has no type... */
634         return NULL;
635     }
636
637     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
638
639     self->array = array;
640     self->index = index;
641     ast_propagate_effects(self, array);
642     ast_propagate_effects(self, index);
643
644     if (!ast_type_adopt(self, outtype)) {
645         ast_array_index_delete(self);
646         return NULL;
647     }
648     if (array->expression.vtype == TYPE_FIELD && outtype->expression.vtype == TYPE_ARRAY) {
649         if (self->expression.vtype != TYPE_ARRAY) {
650             compile_error(ast_ctx(self), "array_index node on type");
651             ast_array_index_delete(self);
652             return NULL;
653         }
654         self->array = outtype;
655         self->expression.vtype = TYPE_FIELD;
656     }
657
658     return self;
659 }
660
661 void ast_array_index_delete(ast_array_index *self)
662 {
663     ast_unref(self->array);
664     ast_unref(self->index);
665     ast_expression_delete((ast_expression*)self);
666     mem_d(self);
667 }
668
669 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
670 {
671     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
672     if (!ontrue && !onfalse) {
673         /* because it is invalid */
674         mem_d(self);
675         return NULL;
676     }
677     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
678
679     self->cond     = cond;
680     self->on_true  = ontrue;
681     self->on_false = onfalse;
682     ast_propagate_effects(self, cond);
683     if (ontrue)
684         ast_propagate_effects(self, ontrue);
685     if (onfalse)
686         ast_propagate_effects(self, onfalse);
687
688     return self;
689 }
690
691 void ast_ifthen_delete(ast_ifthen *self)
692 {
693     ast_unref(self->cond);
694     if (self->on_true)
695         ast_unref(self->on_true);
696     if (self->on_false)
697         ast_unref(self->on_false);
698     ast_expression_delete((ast_expression*)self);
699     mem_d(self);
700 }
701
702 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
703 {
704     ast_expression *exprtype = ontrue;
705     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
706     /* This time NEITHER must be NULL */
707     if (!ontrue || !onfalse) {
708         mem_d(self);
709         return NULL;
710     }
711     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
712
713     self->cond     = cond;
714     self->on_true  = ontrue;
715     self->on_false = onfalse;
716     ast_propagate_effects(self, cond);
717     ast_propagate_effects(self, ontrue);
718     ast_propagate_effects(self, onfalse);
719
720     if (ontrue->expression.vtype == TYPE_NIL)
721         exprtype = onfalse;
722     if (!ast_type_adopt(self, exprtype)) {
723         ast_ternary_delete(self);
724         return NULL;
725     }
726
727     return self;
728 }
729
730 void ast_ternary_delete(ast_ternary *self)
731 {
732     /* the if()s are only there because computed-gotos can set them
733      * to NULL
734      */
735     if (self->cond)     ast_unref(self->cond);
736     if (self->on_true)  ast_unref(self->on_true);
737     if (self->on_false) ast_unref(self->on_false);
738     ast_expression_delete((ast_expression*)self);
739     mem_d(self);
740 }
741
742 ast_loop* ast_loop_new(lex_ctx ctx,
743                        ast_expression *initexpr,
744                        ast_expression *precond, bool pre_not,
745                        ast_expression *postcond, bool post_not,
746                        ast_expression *increment,
747                        ast_expression *body)
748 {
749     ast_instantiate(ast_loop, ctx, ast_loop_delete);
750     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
751
752     self->initexpr  = initexpr;
753     self->precond   = precond;
754     self->postcond  = postcond;
755     self->increment = increment;
756     self->body      = body;
757
758     self->pre_not   = pre_not;
759     self->post_not  = post_not;
760
761     if (initexpr)
762         ast_propagate_effects(self, initexpr);
763     if (precond)
764         ast_propagate_effects(self, precond);
765     if (postcond)
766         ast_propagate_effects(self, postcond);
767     if (increment)
768         ast_propagate_effects(self, increment);
769     if (body)
770         ast_propagate_effects(self, body);
771
772     return self;
773 }
774
775 void ast_loop_delete(ast_loop *self)
776 {
777     if (self->initexpr)
778         ast_unref(self->initexpr);
779     if (self->precond)
780         ast_unref(self->precond);
781     if (self->postcond)
782         ast_unref(self->postcond);
783     if (self->increment)
784         ast_unref(self->increment);
785     if (self->body)
786         ast_unref(self->body);
787     ast_expression_delete((ast_expression*)self);
788     mem_d(self);
789 }
790
791 ast_breakcont* ast_breakcont_new(lex_ctx ctx, bool iscont, unsigned int levels)
792 {
793     ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
794     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
795
796     self->is_continue = iscont;
797     self->levels      = levels;
798
799     return self;
800 }
801
802 void ast_breakcont_delete(ast_breakcont *self)
803 {
804     ast_expression_delete((ast_expression*)self);
805     mem_d(self);
806 }
807
808 ast_switch* ast_switch_new(lex_ctx ctx, ast_expression *op)
809 {
810     ast_instantiate(ast_switch, ctx, ast_switch_delete);
811     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
812
813     self->operand = op;
814     self->cases   = NULL;
815
816     ast_propagate_effects(self, op);
817
818     return self;
819 }
820
821 void ast_switch_delete(ast_switch *self)
822 {
823     size_t i;
824     ast_unref(self->operand);
825
826     for (i = 0; i < vec_size(self->cases); ++i) {
827         if (self->cases[i].value)
828             ast_unref(self->cases[i].value);
829         ast_unref(self->cases[i].code);
830     }
831     vec_free(self->cases);
832
833     ast_expression_delete((ast_expression*)self);
834     mem_d(self);
835 }
836
837 ast_label* ast_label_new(lex_ctx ctx, const char *name, bool undefined)
838 {
839     ast_instantiate(ast_label, ctx, ast_label_delete);
840     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
841
842     self->expression.vtype = TYPE_NOEXPR;
843
844     self->name      = util_strdup(name);
845     self->irblock   = NULL;
846     self->gotos     = NULL;
847     self->undefined = undefined;
848
849     return self;
850 }
851
852 void ast_label_delete(ast_label *self)
853 {
854     mem_d((void*)self->name);
855     vec_free(self->gotos);
856     ast_expression_delete((ast_expression*)self);
857     mem_d(self);
858 }
859
860 void ast_label_register_goto(ast_label *self, ast_goto *g)
861 {
862     vec_push(self->gotos, g);
863 }
864
865 ast_goto* ast_goto_new(lex_ctx ctx, const char *name)
866 {
867     ast_instantiate(ast_goto, ctx, ast_goto_delete);
868     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
869
870     self->name    = util_strdup(name);
871     self->target  = NULL;
872     self->irblock_from = NULL;
873
874     return self;
875 }
876
877 void ast_goto_delete(ast_goto *self)
878 {
879     mem_d((void*)self->name);
880     ast_expression_delete((ast_expression*)self);
881     mem_d(self);
882 }
883
884 void ast_goto_set_label(ast_goto *self, ast_label *label)
885 {
886     self->target = label;
887 }
888
889 ast_call* ast_call_new(lex_ctx ctx,
890                        ast_expression *funcexpr)
891 {
892     ast_instantiate(ast_call, ctx, ast_call_delete);
893     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
894
895     ast_side_effects(self) = true;
896
897     self->params = NULL;
898     self->func   = funcexpr;
899
900     ast_type_adopt(self, funcexpr->expression.next);
901
902     return self;
903 }
904
905 void ast_call_delete(ast_call *self)
906 {
907     size_t i;
908     for (i = 0; i < vec_size(self->params); ++i)
909         ast_unref(self->params[i]);
910     vec_free(self->params);
911
912     if (self->func)
913         ast_unref(self->func);
914
915     ast_expression_delete((ast_expression*)self);
916     mem_d(self);
917 }
918
919 bool ast_call_check_types(ast_call *self)
920 {
921     char texp[1024];
922     char tgot[1024];
923     size_t i;
924     bool   retval = true;
925     const  ast_expression *func = self->func;
926     size_t count = vec_size(self->params);
927     if (count > vec_size(func->expression.params))
928         count = vec_size(func->expression.params);
929
930     for (i = 0; i < count; ++i) {
931         if (!ast_compare_type(self->params[i], (ast_expression*)(func->expression.params[i])))
932         {
933             ast_type_to_string(self->params[i], tgot, sizeof(tgot));
934             ast_type_to_string((ast_expression*)func->expression.params[i], texp, sizeof(texp));
935             compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
936                      (unsigned int)(i+1), texp, tgot);
937             /* we don't immediately return */
938             retval = false;
939         }
940     }
941     count = vec_size(self->params);
942     if (count > vec_size(func->expression.params) && func->expression.varparam) {
943         for (; i < count; ++i) {
944             if (!ast_compare_type(self->params[i], func->expression.varparam))
945             {
946                 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
947                 ast_type_to_string(func->expression.varparam, texp, sizeof(texp));
948                 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
949                          (unsigned int)(i+1), texp, tgot);
950                 /* we don't immediately return */
951                 retval = false;
952             }
953         }
954     }
955     return retval;
956 }
957
958 ast_store* ast_store_new(lex_ctx ctx, int op,
959                          ast_expression *dest, ast_expression *source)
960 {
961     ast_instantiate(ast_store, ctx, ast_store_delete);
962     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
963
964     ast_side_effects(self) = true;
965
966     self->op = op;
967     self->dest = dest;
968     self->source = source;
969
970     if (!ast_type_adopt(self, dest)) {
971         ast_delete(self);
972         return NULL;
973     }
974
975     return self;
976 }
977
978 void ast_store_delete(ast_store *self)
979 {
980     ast_unref(self->dest);
981     ast_unref(self->source);
982     ast_expression_delete((ast_expression*)self);
983     mem_d(self);
984 }
985
986 ast_block* ast_block_new(lex_ctx ctx)
987 {
988     ast_instantiate(ast_block, ctx, ast_block_delete);
989     ast_expression_init((ast_expression*)self,
990                         (ast_expression_codegen*)&ast_block_codegen);
991
992     self->locals  = NULL;
993     self->exprs   = NULL;
994     self->collect = NULL;
995
996     return self;
997 }
998
999 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1000 {
1001     ast_propagate_effects(self, e);
1002     vec_push(self->exprs, e);
1003     if (self->expression.next) {
1004         ast_delete(self->expression.next);
1005         self->expression.next = NULL;
1006     }
1007     if (!ast_type_adopt(self, e)) {
1008         compile_error(ast_ctx(self), "internal error: failed to adopt type");
1009         return false;
1010     }
1011     return true;
1012 }
1013
1014 void ast_block_collect(ast_block *self, ast_expression *expr)
1015 {
1016     vec_push(self->collect, expr);
1017     expr->expression.node.keep = true;
1018 }
1019
1020 void ast_block_delete(ast_block *self)
1021 {
1022     size_t i;
1023     for (i = 0; i < vec_size(self->exprs); ++i)
1024         ast_unref(self->exprs[i]);
1025     vec_free(self->exprs);
1026     for (i = 0; i < vec_size(self->locals); ++i)
1027         ast_delete(self->locals[i]);
1028     vec_free(self->locals);
1029     for (i = 0; i < vec_size(self->collect); ++i)
1030         ast_delete(self->collect[i]);
1031     vec_free(self->collect);
1032     ast_expression_delete((ast_expression*)self);
1033     mem_d(self);
1034 }
1035
1036 bool ast_block_set_type(ast_block *self, ast_expression *from)
1037 {
1038     if (self->expression.next)
1039         ast_delete(self->expression.next);
1040     if (!ast_type_adopt(self, from))
1041         return false;
1042     return true;
1043 }
1044
1045 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
1046 {
1047     ast_instantiate(ast_function, ctx, ast_function_delete);
1048
1049     if (!vtype ||
1050         vtype->hasvalue ||
1051         vtype->expression.vtype != TYPE_FUNCTION)
1052     {
1053         compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1054                  (int)!vtype,
1055                  (int)vtype->hasvalue,
1056                  vtype->expression.vtype);
1057         mem_d(self);
1058         return NULL;
1059     }
1060
1061     self->vtype  = vtype;
1062     self->name   = name ? util_strdup(name) : NULL;
1063     self->blocks = NULL;
1064
1065     self->labelcount = 0;
1066     self->builtin = 0;
1067
1068     self->ir_func = NULL;
1069     self->curblock = NULL;
1070
1071     self->breakblocks    = NULL;
1072     self->continueblocks = NULL;
1073
1074     vtype->hasvalue = true;
1075     vtype->constval.vfunc = self;
1076
1077     self->varargs = NULL;
1078
1079     return self;
1080 }
1081
1082 void ast_function_delete(ast_function *self)
1083 {
1084     size_t i;
1085     if (self->name)
1086         mem_d((void*)self->name);
1087     if (self->vtype) {
1088         /* ast_value_delete(self->vtype); */
1089         self->vtype->hasvalue = false;
1090         self->vtype->constval.vfunc = NULL;
1091         /* We use unref - if it was stored in a global table it is supposed
1092          * to be deleted from *there*
1093          */
1094         ast_unref(self->vtype);
1095     }
1096     for (i = 0; i < vec_size(self->blocks); ++i)
1097         ast_delete(self->blocks[i]);
1098     vec_free(self->blocks);
1099     vec_free(self->breakblocks);
1100     vec_free(self->continueblocks);
1101     if (self->varargs)
1102         ast_delete(self->varargs);
1103     mem_d(self);
1104 }
1105
1106 const char* ast_function_label(ast_function *self, const char *prefix)
1107 {
1108     size_t id;
1109     size_t len;
1110     char  *from;
1111
1112     if (!opts.dump && !opts.dumpfin && !opts.debug)
1113         return NULL;
1114
1115     id  = (self->labelcount++);
1116     len = strlen(prefix);
1117
1118     from = self->labelbuf + sizeof(self->labelbuf)-1;
1119     *from-- = 0;
1120     do {
1121         *from-- = (id%10) + '0';
1122         id /= 10;
1123     } while (id);
1124     ++from;
1125     memcpy(from - len, prefix, len);
1126     return from - len;
1127 }
1128
1129 /*********************************************************************/
1130 /* AST codegen part
1131  * by convention you must never pass NULL to the 'ir_value **out'
1132  * parameter. If you really don't care about the output, pass a dummy.
1133  * But I can't imagine a pituation where the output is truly unnecessary.
1134  */
1135
1136 void _ast_codegen_output_type(ast_expression_common *self, ir_value *out)
1137 {
1138     if (out->vtype == TYPE_FIELD)
1139         out->fieldtype = self->next->expression.vtype;
1140     if (out->vtype == TYPE_FUNCTION)
1141         out->outtype = self->next->expression.vtype;
1142 }
1143
1144 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1145
1146 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1147 {
1148     (void)func;
1149     (void)lvalue;
1150     if (self->expression.vtype == TYPE_NIL) {
1151         *out = func->ir_func->owner->nil;
1152         return true;
1153     }
1154     /* NOTE: This is the codegen for a variable used in an expression.
1155      * It is not the codegen to generate the value. For this purpose,
1156      * ast_local_codegen and ast_global_codegen are to be used before this
1157      * is executed. ast_function_codegen should take care of its locals,
1158      * and the ast-user should take care of ast_global_codegen to be used
1159      * on all the globals.
1160      */
1161     if (!self->ir_v) {
1162         char tname[1024]; /* typename is reserved in C++ */
1163         ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1164         compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1165         return false;
1166     }
1167     *out = self->ir_v;
1168     return true;
1169 }
1170
1171 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1172 {
1173     ir_value *v = NULL;
1174
1175     if (self->expression.vtype == TYPE_NIL) {
1176         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1177         return false;
1178     }
1179
1180     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1181     {
1182         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
1183         if (!func)
1184             return false;
1185         func->context = ast_ctx(self);
1186         func->value->context = ast_ctx(self);
1187
1188         self->constval.vfunc->ir_func = func;
1189         self->ir_v = func->value;
1190         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1191             self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1192         /* The function is filled later on ast_function_codegen... */
1193         return true;
1194     }
1195
1196     if (isfield && self->expression.vtype == TYPE_FIELD) {
1197         ast_expression *fieldtype = self->expression.next;
1198
1199         if (self->hasvalue) {
1200             compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1201             goto error;
1202         }
1203
1204         if (fieldtype->expression.vtype == TYPE_ARRAY) {
1205             size_t ai;
1206             char   *name;
1207             size_t  namelen;
1208
1209             ast_expression_common *elemtype;
1210             int                    vtype;
1211             ast_value             *array = (ast_value*)fieldtype;
1212
1213             if (!ast_istype(fieldtype, ast_value)) {
1214                 compile_error(ast_ctx(self), "internal error: ast_value required");
1215                 return false;
1216             }
1217
1218             /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1219             if (!array->expression.count || array->expression.count > opts.max_array_size)
1220                 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1221
1222             elemtype = &array->expression.next->expression;
1223             vtype = elemtype->vtype;
1224
1225             v = ir_builder_create_field(ir, self->name, vtype);
1226             if (!v) {
1227                 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1228                 return false;
1229             }
1230             v->context = ast_ctx(self);
1231             v->unique_life = true;
1232             v->locked      = true;
1233             array->ir_v = self->ir_v = v;
1234             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1235                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1236
1237             namelen = strlen(self->name);
1238             name    = (char*)mem_a(namelen + 16);
1239             strcpy(name, self->name);
1240
1241             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1242             array->ir_values[0] = v;
1243             for (ai = 1; ai < array->expression.count; ++ai) {
1244                 snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1245                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1246                 if (!array->ir_values[ai]) {
1247                     mem_d(name);
1248                     compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1249                     return false;
1250                 }
1251                 array->ir_values[ai]->context = ast_ctx(self);
1252                 array->ir_values[ai]->unique_life = true;
1253                 array->ir_values[ai]->locked      = true;
1254                 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1255                     self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1256             }
1257             mem_d(name);
1258         }
1259         else
1260         {
1261             v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
1262             if (!v)
1263                 return false;
1264             v->context = ast_ctx(self);
1265             self->ir_v = v;
1266             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1267                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1268         }
1269         return true;
1270     }
1271
1272     if (self->expression.vtype == TYPE_ARRAY) {
1273         size_t ai;
1274         char   *name;
1275         size_t  namelen;
1276
1277         ast_expression_common *elemtype = &self->expression.next->expression;
1278         int vtype = elemtype->vtype;
1279
1280         /* same as with field arrays */
1281         if (!self->expression.count || self->expression.count > opts.max_array_size)
1282             compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1283
1284         v = ir_builder_create_global(ir, self->name, vtype);
1285         if (!v) {
1286             compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1287             return false;
1288         }
1289         v->context = ast_ctx(self);
1290         v->unique_life = true;
1291         v->locked      = true;
1292         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1293             v->flags |= IR_FLAG_INCLUDE_DEF;
1294
1295         namelen = strlen(self->name);
1296         name    = (char*)mem_a(namelen + 16);
1297         strcpy(name, self->name);
1298
1299         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1300         self->ir_values[0] = v;
1301         for (ai = 1; ai < self->expression.count; ++ai) {
1302             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1303             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1304             if (!self->ir_values[ai]) {
1305                 mem_d(name);
1306                 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1307                 return false;
1308             }
1309             self->ir_values[ai]->context = ast_ctx(self);
1310             self->ir_values[ai]->unique_life = true;
1311             self->ir_values[ai]->locked      = true;
1312             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1313                 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1314         }
1315         mem_d(name);
1316     }
1317     else
1318     {
1319         /* Arrays don't do this since there's no "array" value which spans across the
1320          * whole thing.
1321          */
1322         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1323         if (!v) {
1324             compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1325             return false;
1326         }
1327         codegen_output_type(self, v);
1328         v->context = ast_ctx(self);
1329     }
1330
1331     if (self->hasvalue) {
1332         switch (self->expression.vtype)
1333         {
1334             case TYPE_FLOAT:
1335                 if (!ir_value_set_float(v, self->constval.vfloat))
1336                     goto error;
1337                 break;
1338             case TYPE_VECTOR:
1339                 if (!ir_value_set_vector(v, self->constval.vvec))
1340                     goto error;
1341                 break;
1342             case TYPE_STRING:
1343                 if (!ir_value_set_string(v, self->constval.vstring))
1344                     goto error;
1345                 break;
1346             case TYPE_ARRAY:
1347                 compile_error(ast_ctx(self), "TODO: global constant array");
1348                 break;
1349             case TYPE_FUNCTION:
1350                 compile_error(ast_ctx(self), "global of type function not properly generated");
1351                 goto error;
1352                 /* Cannot generate an IR value for a function,
1353                  * need a pointer pointing to a function rather.
1354                  */
1355             case TYPE_FIELD:
1356                 if (!self->constval.vfield) {
1357                     compile_error(ast_ctx(self), "field constant without vfield set");
1358                     goto error;
1359                 }
1360                 if (!self->constval.vfield->ir_v) {
1361                     compile_error(ast_ctx(self), "field constant generated before its field");
1362                     goto error;
1363                 }
1364                 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1365                     goto error;
1366                 break;
1367             default:
1368                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1369                 break;
1370         }
1371     }
1372
1373     /* link us to the ir_value */
1374     v->cvq = self->cvq;
1375     self->ir_v = v;
1376     if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1377         self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1378     return true;
1379
1380 error: /* clean up */
1381     ir_value_delete(v);
1382     return false;
1383 }
1384
1385 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1386 {
1387     ir_value *v = NULL;
1388
1389     if (self->expression.vtype == TYPE_NIL) {
1390         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1391         return false;
1392     }
1393
1394     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1395     {
1396         /* Do we allow local functions? I think not...
1397          * this is NOT a function pointer atm.
1398          */
1399         return false;
1400     }
1401
1402     if (self->expression.vtype == TYPE_ARRAY) {
1403         size_t ai;
1404         char   *name;
1405         size_t  namelen;
1406
1407         ast_expression_common *elemtype = &self->expression.next->expression;
1408         int vtype = elemtype->vtype;
1409
1410         func->flags |= IR_FLAG_HAS_ARRAYS;
1411
1412         if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1413             compile_error(ast_ctx(self), "array-parameters are not supported");
1414             return false;
1415         }
1416
1417         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1418         if (!self->expression.count || self->expression.count > opts.max_array_size) {
1419             compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1420         }
1421
1422         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1423         if (!self->ir_values) {
1424             compile_error(ast_ctx(self), "failed to allocate array values");
1425             return false;
1426         }
1427
1428         v = ir_function_create_local(func, self->name, vtype, param);
1429         if (!v) {
1430             compile_error(ast_ctx(self), "ir_function_create_local failed");
1431             return false;
1432         }
1433         v->context = ast_ctx(self);
1434         v->unique_life = true;
1435         v->locked      = true;
1436
1437         namelen = strlen(self->name);
1438         name    = (char*)mem_a(namelen + 16);
1439         strcpy(name, self->name);
1440
1441         self->ir_values[0] = v;
1442         for (ai = 1; ai < self->expression.count; ++ai) {
1443             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1444             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1445             if (!self->ir_values[ai]) {
1446                 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1447                 return false;
1448             }
1449             self->ir_values[ai]->context = ast_ctx(self);
1450             self->ir_values[ai]->unique_life = true;
1451             self->ir_values[ai]->locked      = true;
1452         }
1453     }
1454     else
1455     {
1456         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1457         if (!v)
1458             return false;
1459         codegen_output_type(self, v);
1460         v->context = ast_ctx(self);
1461     }
1462
1463     /* A constant local... hmmm...
1464      * I suppose the IR will have to deal with this
1465      */
1466     if (self->hasvalue) {
1467         switch (self->expression.vtype)
1468         {
1469             case TYPE_FLOAT:
1470                 if (!ir_value_set_float(v, self->constval.vfloat))
1471                     goto error;
1472                 break;
1473             case TYPE_VECTOR:
1474                 if (!ir_value_set_vector(v, self->constval.vvec))
1475                     goto error;
1476                 break;
1477             case TYPE_STRING:
1478                 if (!ir_value_set_string(v, self->constval.vstring))
1479                     goto error;
1480                 break;
1481             default:
1482                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1483                 break;
1484         }
1485     }
1486
1487     /* link us to the ir_value */
1488     v->cvq = self->cvq;
1489     self->ir_v = v;
1490
1491     if (!ast_generate_accessors(self, func->owner))
1492         return false;
1493     return true;
1494
1495 error: /* clean up */
1496     ir_value_delete(v);
1497     return false;
1498 }
1499
1500 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1501 {
1502     size_t i;
1503     bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1504     if (!self->setter || !self->getter)
1505         return true;
1506     for (i = 0; i < self->expression.count; ++i) {
1507         if (!self->ir_values) {
1508             compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1509             return false;
1510         }
1511         if (!self->ir_values[i]) {
1512             compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1513             return false;
1514         }
1515         if (self->ir_values[i]->life) {
1516             compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1517             return false;
1518         }
1519     }
1520
1521     opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1522     if (self->setter) {
1523         if (!ast_global_codegen  (self->setter, ir, false) ||
1524             !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1525             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1526         {
1527             compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1528             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1529             return false;
1530         }
1531     }
1532     if (self->getter) {
1533         if (!ast_global_codegen  (self->getter, ir, false) ||
1534             !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1535             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1536         {
1537             compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1538             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1539             return false;
1540         }
1541     }
1542     for (i = 0; i < self->expression.count; ++i) {
1543         vec_free(self->ir_values[i]->life);
1544     }
1545     opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1546     return true;
1547 }
1548
1549 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1550 {
1551     ir_function *irf;
1552     ir_value    *dummy;
1553     ast_expression_common *ec;
1554     size_t    i;
1555
1556     (void)ir;
1557
1558     irf = self->ir_func;
1559     if (!irf) {
1560         compile_error(ast_ctx(self), "ast_function's related ast_value was not generated yet");
1561         return false;
1562     }
1563
1564     /* fill the parameter list */
1565     ec = &self->vtype->expression;
1566     for (i = 0; i < vec_size(ec->params); ++i)
1567     {
1568         if (ec->params[i]->expression.vtype == TYPE_FIELD)
1569             vec_push(irf->params, ec->params[i]->expression.next->expression.vtype);
1570         else
1571             vec_push(irf->params, ec->params[i]->expression.vtype);
1572         if (!self->builtin) {
1573             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1574                 return false;
1575         }
1576     }
1577
1578     if (self->varargs) {
1579         if (!ast_local_codegen(self->varargs, self->ir_func, true))
1580             return false;
1581     }
1582
1583     if (self->builtin) {
1584         irf->builtin = self->builtin;
1585         return true;
1586     }
1587
1588     if (!vec_size(self->blocks)) {
1589         compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1590         return false;
1591     }
1592
1593     self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1594     if (!self->curblock) {
1595         compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1596         return false;
1597     }
1598
1599     for (i = 0; i < vec_size(self->blocks); ++i) {
1600         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
1601         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
1602             return false;
1603     }
1604
1605     /* TODO: check return types */
1606     if (!self->curblock->final)
1607     {
1608         if (!self->vtype->expression.next ||
1609             self->vtype->expression.next->expression.vtype == TYPE_VOID)
1610         {
1611             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1612         }
1613         else if (vec_size(self->curblock->entries))
1614         {
1615             /* error("missing return"); */
1616             if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1617                                 "control reaches end of non-void function (`%s`) via %s",
1618                                 self->name, self->curblock->label))
1619             {
1620                 return false;
1621             }
1622             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1623         }
1624     }
1625     return true;
1626 }
1627
1628 /* Note, you will not see ast_block_codegen generate ir_blocks.
1629  * To the AST and the IR, blocks are 2 different things.
1630  * In the AST it represents a block of code, usually enclosed in
1631  * curly braces {...}.
1632  * While in the IR it represents a block in terms of control-flow.
1633  */
1634 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1635 {
1636     size_t i;
1637
1638     /* We don't use this
1639      * Note: an ast-representation using the comma-operator
1640      * of the form: (a, b, c) = x should not assign to c...
1641      */
1642     if (lvalue) {
1643         compile_error(ast_ctx(self), "not an l-value (code-block)");
1644         return false;
1645     }
1646
1647     if (self->expression.outr) {
1648         *out = self->expression.outr;
1649         return true;
1650     }
1651
1652     /* output is NULL at first, we'll have each expression
1653      * assign to out output, thus, a comma-operator represention
1654      * using an ast_block will return the last generated value,
1655      * so: (b, c) + a  executed both b and c, and returns c,
1656      * which is then added to a.
1657      */
1658     *out = NULL;
1659
1660     /* generate locals */
1661     for (i = 0; i < vec_size(self->locals); ++i)
1662     {
1663         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1664             if (opts.debug)
1665                 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1666             return false;
1667         }
1668     }
1669
1670     for (i = 0; i < vec_size(self->exprs); ++i)
1671     {
1672         ast_expression_codegen *gen;
1673         if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1674             if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1675                 return false;
1676             continue;
1677         }
1678         gen = self->exprs[i]->expression.codegen;
1679         if (!(*gen)(self->exprs[i], func, false, out))
1680             return false;
1681     }
1682
1683     self->expression.outr = *out;
1684
1685     return true;
1686 }
1687
1688 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1689 {
1690     ast_expression_codegen *cgen;
1691     ir_value *left  = NULL;
1692     ir_value *right = NULL;
1693
1694     ast_value       *arr;
1695     ast_value       *idx = 0;
1696     ast_array_index *ai = NULL;
1697
1698     if (lvalue && self->expression.outl) {
1699         *out = self->expression.outl;
1700         return true;
1701     }
1702
1703     if (!lvalue && self->expression.outr) {
1704         *out = self->expression.outr;
1705         return true;
1706     }
1707
1708     if (ast_istype(self->dest, ast_array_index))
1709     {
1710
1711         ai = (ast_array_index*)self->dest;
1712         idx = (ast_value*)ai->index;
1713
1714         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1715             ai = NULL;
1716     }
1717
1718     if (ai) {
1719         /* we need to call the setter */
1720         ir_value  *iridx, *funval;
1721         ir_instr  *call;
1722
1723         if (lvalue) {
1724             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1725             return false;
1726         }
1727
1728         arr = (ast_value*)ai->array;
1729         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1730             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1731             return false;
1732         }
1733
1734         cgen = idx->expression.codegen;
1735         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1736             return false;
1737
1738         cgen = arr->setter->expression.codegen;
1739         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1740             return false;
1741
1742         cgen = self->source->expression.codegen;
1743         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1744             return false;
1745
1746         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1747         if (!call)
1748             return false;
1749         ir_call_param(call, iridx);
1750         ir_call_param(call, right);
1751         self->expression.outr = right;
1752     }
1753     else
1754     {
1755         /* regular code */
1756
1757         cgen = self->dest->expression.codegen;
1758         /* lvalue! */
1759         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1760             return false;
1761         self->expression.outl = left;
1762
1763         cgen = self->source->expression.codegen;
1764         /* rvalue! */
1765         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1766             return false;
1767
1768         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
1769             return false;
1770         self->expression.outr = right;
1771     }
1772
1773     /* Theoretically, an assinment returns its left side as an
1774      * lvalue, if we don't need an lvalue though, we return
1775      * the right side as an rvalue, otherwise we have to
1776      * somehow know whether or not we need to dereference the pointer
1777      * on the left side - that is: OP_LOAD if it was an address.
1778      * Also: in original QC we cannot OP_LOADP *anyway*.
1779      */
1780     *out = (lvalue ? left : right);
1781
1782     return true;
1783 }
1784
1785 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1786 {
1787     ast_expression_codegen *cgen;
1788     ir_value *left, *right;
1789
1790     /* A binary operation cannot yield an l-value */
1791     if (lvalue) {
1792         compile_error(ast_ctx(self), "not an l-value (binop)");
1793         return false;
1794     }
1795
1796     if (self->expression.outr) {
1797         *out = self->expression.outr;
1798         return true;
1799     }
1800
1801     if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
1802         (self->op == INSTR_AND || self->op == INSTR_OR))
1803     {
1804         /* short circuit evaluation */
1805         ir_block *other, *merge;
1806         ir_block *from_left, *from_right;
1807         ir_instr *phi;
1808         size_t    merge_id;
1809
1810         /* prepare end-block */
1811         merge_id = vec_size(func->ir_func->blocks);
1812         merge    = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
1813
1814         /* generate the left expression */
1815         cgen = self->left->expression.codegen;
1816         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1817             return false;
1818         /* remember the block */
1819         from_left = func->curblock;
1820
1821         /* create a new block for the right expression */
1822         other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
1823         if (self->op == INSTR_AND) {
1824             /* on AND: left==true -> other */
1825             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
1826                 return false;
1827         } else {
1828             /* on OR: left==false -> other */
1829             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
1830                 return false;
1831         }
1832         /* use the likely flag */
1833         vec_last(func->curblock->instr)->likely = true;
1834
1835         /* enter the right-expression's block */
1836         func->curblock = other;
1837         /* generate */
1838         cgen = self->right->expression.codegen;
1839         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1840             return false;
1841         /* remember block */
1842         from_right = func->curblock;
1843
1844         /* jump to the merge block */
1845         if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
1846             return false;
1847
1848         vec_remove(func->ir_func->blocks, merge_id, 1);
1849         vec_push(func->ir_func->blocks, merge);
1850
1851         func->curblock = merge;
1852         phi = ir_block_create_phi(func->curblock, ast_ctx(self),
1853                                   ast_function_label(func, "sce_value"),
1854                                   self->expression.vtype);
1855         ir_phi_add(phi, from_left, left);
1856         ir_phi_add(phi, from_right, right);
1857         *out = ir_phi_value(phi);
1858         if (!*out)
1859             return false;
1860
1861         if (!OPTS_FLAG(PERL_LOGIC)) {
1862             /* cast-to-bool */
1863             if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
1864                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1865                                              ast_function_label(func, "sce_bool_v"),
1866                                              INSTR_NOT_V, *out);
1867                 if (!*out)
1868                     return false;
1869                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1870                                              ast_function_label(func, "sce_bool"),
1871                                              INSTR_NOT_F, *out);
1872                 if (!*out)
1873                     return false;
1874             }
1875             else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
1876                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1877                                              ast_function_label(func, "sce_bool_s"),
1878                                              INSTR_NOT_S, *out);
1879                 if (!*out)
1880                     return false;
1881                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1882                                              ast_function_label(func, "sce_bool"),
1883                                              INSTR_NOT_F, *out);
1884                 if (!*out)
1885                     return false;
1886             }
1887             else {
1888                 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
1889                                              ast_function_label(func, "sce_bool"),
1890                                              INSTR_AND, *out, *out);
1891                 if (!*out)
1892                     return false;
1893             }
1894         }
1895
1896         self->expression.outr = *out;
1897         codegen_output_type(self, *out);
1898         return true;
1899     }
1900
1901     cgen = self->left->expression.codegen;
1902     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1903         return false;
1904
1905     cgen = self->right->expression.codegen;
1906     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1907         return false;
1908
1909     *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
1910                                  self->op, left, right);
1911     if (!*out)
1912         return false;
1913     self->expression.outr = *out;
1914     codegen_output_type(self, *out);
1915
1916     return true;
1917 }
1918
1919 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1920 {
1921     ast_expression_codegen *cgen;
1922     ir_value *leftl = NULL, *leftr, *right, *bin;
1923
1924     ast_value       *arr;
1925     ast_value       *idx = 0;
1926     ast_array_index *ai = NULL;
1927     ir_value        *iridx = NULL;
1928
1929     if (lvalue && self->expression.outl) {
1930         *out = self->expression.outl;
1931         return true;
1932     }
1933
1934     if (!lvalue && self->expression.outr) {
1935         *out = self->expression.outr;
1936         return true;
1937     }
1938
1939     if (ast_istype(self->dest, ast_array_index))
1940     {
1941
1942         ai = (ast_array_index*)self->dest;
1943         idx = (ast_value*)ai->index;
1944
1945         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1946             ai = NULL;
1947     }
1948
1949     /* for a binstore we need both an lvalue and an rvalue for the left side */
1950     /* rvalue of destination! */
1951     if (ai) {
1952         cgen = idx->expression.codegen;
1953         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1954             return false;
1955     }
1956     cgen = self->dest->expression.codegen;
1957     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
1958         return false;
1959
1960     /* source as rvalue only */
1961     cgen = self->source->expression.codegen;
1962     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1963         return false;
1964
1965     /* now the binary */
1966     bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
1967                                 self->opbin, leftr, right);
1968     self->expression.outr = bin;
1969
1970
1971     if (ai) {
1972         /* we need to call the setter */
1973         ir_value  *funval;
1974         ir_instr  *call;
1975
1976         if (lvalue) {
1977             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1978             return false;
1979         }
1980
1981         arr = (ast_value*)ai->array;
1982         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1983             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1984             return false;
1985         }
1986
1987         cgen = arr->setter->expression.codegen;
1988         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1989             return false;
1990
1991         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1992         if (!call)
1993             return false;
1994         ir_call_param(call, iridx);
1995         ir_call_param(call, bin);
1996         self->expression.outr = bin;
1997     } else {
1998         /* now store them */
1999         cgen = self->dest->expression.codegen;
2000         /* lvalue of destination */
2001         if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2002             return false;
2003         self->expression.outl = leftl;
2004
2005         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2006             return false;
2007         self->expression.outr = bin;
2008     }
2009
2010     /* Theoretically, an assinment returns its left side as an
2011      * lvalue, if we don't need an lvalue though, we return
2012      * the right side as an rvalue, otherwise we have to
2013      * somehow know whether or not we need to dereference the pointer
2014      * on the left side - that is: OP_LOAD if it was an address.
2015      * Also: in original QC we cannot OP_LOADP *anyway*.
2016      */
2017     *out = (lvalue ? leftl : bin);
2018
2019     return true;
2020 }
2021
2022 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2023 {
2024     ast_expression_codegen *cgen;
2025     ir_value *operand;
2026
2027     /* An unary operation cannot yield an l-value */
2028     if (lvalue) {
2029         compile_error(ast_ctx(self), "not an l-value (binop)");
2030         return false;
2031     }
2032
2033     if (self->expression.outr) {
2034         *out = self->expression.outr;
2035         return true;
2036     }
2037
2038     cgen = self->operand->expression.codegen;
2039     /* lvalue! */
2040     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2041         return false;
2042
2043     *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2044                                  self->op, operand);
2045     if (!*out)
2046         return false;
2047     self->expression.outr = *out;
2048
2049     return true;
2050 }
2051
2052 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2053 {
2054     ast_expression_codegen *cgen;
2055     ir_value *operand;
2056
2057     *out = NULL;
2058
2059     /* In the context of a return operation, we don't actually return
2060      * anything...
2061      */
2062     if (lvalue) {
2063         compile_error(ast_ctx(self), "return-expression is not an l-value");
2064         return false;
2065     }
2066
2067     if (self->expression.outr) {
2068         compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2069         return false;
2070     }
2071     self->expression.outr = (ir_value*)1;
2072
2073     if (self->operand) {
2074         cgen = self->operand->expression.codegen;
2075         /* lvalue! */
2076         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2077             return false;
2078
2079         if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2080             return false;
2081     } else {
2082         if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2083             return false;
2084     }
2085
2086     return true;
2087 }
2088
2089 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2090 {
2091     ast_expression_codegen *cgen;
2092     ir_value *ent, *field;
2093
2094     /* This function needs to take the 'lvalue' flag into account!
2095      * As lvalue we provide a field-pointer, as rvalue we provide the
2096      * value in a temp.
2097      */
2098
2099     if (lvalue && self->expression.outl) {
2100         *out = self->expression.outl;
2101         return true;
2102     }
2103
2104     if (!lvalue && self->expression.outr) {
2105         *out = self->expression.outr;
2106         return true;
2107     }
2108
2109     cgen = self->entity->expression.codegen;
2110     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2111         return false;
2112
2113     cgen = self->field->expression.codegen;
2114     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2115         return false;
2116
2117     if (lvalue) {
2118         /* address! */
2119         *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2120                                             ent, field);
2121     } else {
2122         *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2123                                              ent, field, self->expression.vtype);
2124         /* Done AFTER error checking: 
2125         codegen_output_type(self, *out);
2126         */
2127     }
2128     if (!*out) {
2129         compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2130                  (lvalue ? "ADDRESS" : "FIELD"),
2131                  type_name[self->expression.vtype]);
2132         return false;
2133     }
2134     if (!lvalue)
2135         codegen_output_type(self, *out);
2136
2137     if (lvalue)
2138         self->expression.outl = *out;
2139     else
2140         self->expression.outr = *out;
2141
2142     /* Hm that should be it... */
2143     return true;
2144 }
2145
2146 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2147 {
2148     ast_expression_codegen *cgen;
2149     ir_value *vec;
2150
2151     /* in QC this is always an lvalue */
2152     if (lvalue && self->rvalue) {
2153         compile_error(ast_ctx(self), "not an l-value (member access)");
2154         return false;
2155     }
2156     if (self->expression.outl) {
2157         *out = self->expression.outl;
2158         return true;
2159     }
2160
2161     cgen = self->owner->expression.codegen;
2162     if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2163         return false;
2164
2165     if (vec->vtype != TYPE_VECTOR &&
2166         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
2167     {
2168         return false;
2169     }
2170
2171     *out = ir_value_vector_member(vec, self->field);
2172     self->expression.outl = *out;
2173
2174     return (*out != NULL);
2175 }
2176
2177 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2178 {
2179     ast_value *arr;
2180     ast_value *idx;
2181
2182     if (!lvalue && self->expression.outr) {
2183         *out = self->expression.outr;
2184     }
2185     if (lvalue && self->expression.outl) {
2186         *out = self->expression.outl;
2187     }
2188
2189     if (!ast_istype(self->array, ast_value)) {
2190         compile_error(ast_ctx(self), "array indexing this way is not supported");
2191         /* note this would actually be pointer indexing because the left side is
2192          * not an actual array but (hopefully) an indexable expression.
2193          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2194          * support this path will be filled.
2195          */
2196         return false;
2197     }
2198
2199     arr = (ast_value*)self->array;
2200     idx = (ast_value*)self->index;
2201
2202     if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2203         /* Time to use accessor functions */
2204         ast_expression_codegen *cgen;
2205         ir_value               *iridx, *funval;
2206         ir_instr               *call;
2207
2208         if (lvalue) {
2209             compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2210             return false;
2211         }
2212
2213         if (!arr->getter) {
2214             compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2215             return false;
2216         }
2217
2218         cgen = self->index->expression.codegen;
2219         if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2220             return false;
2221
2222         cgen = arr->getter->expression.codegen;
2223         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2224             return false;
2225
2226         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2227         if (!call)
2228             return false;
2229         ir_call_param(call, iridx);
2230
2231         *out = ir_call_value(call);
2232         self->expression.outr = *out;
2233         return true;
2234     }
2235
2236     if (idx->expression.vtype == TYPE_FLOAT) {
2237         unsigned int arridx = idx->constval.vfloat;
2238         if (arridx >= self->array->expression.count)
2239         {
2240             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2241             return false;
2242         }
2243         *out = arr->ir_values[arridx];
2244     }
2245     else if (idx->expression.vtype == TYPE_INTEGER) {
2246         unsigned int arridx = idx->constval.vint;
2247         if (arridx >= self->array->expression.count)
2248         {
2249             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2250             return false;
2251         }
2252         *out = arr->ir_values[arridx];
2253     }
2254     else {
2255         compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2256         return false;
2257     }
2258     return true;
2259 }
2260
2261 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2262 {
2263     ast_expression_codegen *cgen;
2264
2265     ir_value *condval;
2266     ir_value *dummy;
2267
2268     ir_block *cond;
2269     ir_block *ontrue;
2270     ir_block *onfalse;
2271     ir_block *ontrue_endblock = NULL;
2272     ir_block *onfalse_endblock = NULL;
2273     ir_block *merge = NULL;
2274
2275     /* We don't output any value, thus also don't care about r/lvalue */
2276     (void)out;
2277     (void)lvalue;
2278
2279     if (self->expression.outr) {
2280         compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2281         return false;
2282     }
2283     self->expression.outr = (ir_value*)1;
2284
2285     /* generate the condition */
2286     cgen = self->cond->expression.codegen;
2287     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2288         return false;
2289     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2290     cond = func->curblock;
2291
2292     /* on-true path */
2293
2294     if (self->on_true) {
2295         /* create on-true block */
2296         ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2297         if (!ontrue)
2298             return false;
2299
2300         /* enter the block */
2301         func->curblock = ontrue;
2302
2303         /* generate */
2304         cgen = self->on_true->expression.codegen;
2305         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2306             return false;
2307
2308         /* we now need to work from the current endpoint */
2309         ontrue_endblock = func->curblock;
2310     } else
2311         ontrue = NULL;
2312
2313     /* on-false path */
2314     if (self->on_false) {
2315         /* create on-false block */
2316         onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2317         if (!onfalse)
2318             return false;
2319
2320         /* enter the block */
2321         func->curblock = onfalse;
2322
2323         /* generate */
2324         cgen = self->on_false->expression.codegen;
2325         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2326             return false;
2327
2328         /* we now need to work from the current endpoint */
2329         onfalse_endblock = func->curblock;
2330     } else
2331         onfalse = NULL;
2332
2333     /* Merge block were they all merge in to */
2334     if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2335     {
2336         merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2337         if (!merge)
2338             return false;
2339         /* add jumps ot the merge block */
2340         if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2341             return false;
2342         if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2343             return false;
2344
2345         /* Now enter the merge block */
2346         func->curblock = merge;
2347     }
2348
2349     /* we create the if here, that way all blocks are ordered :)
2350      */
2351     if (!ir_block_create_if(cond, ast_ctx(self), condval,
2352                             (ontrue  ? ontrue  : merge),
2353                             (onfalse ? onfalse : merge)))
2354     {
2355         return false;
2356     }
2357
2358     return true;
2359 }
2360
2361 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2362 {
2363     ast_expression_codegen *cgen;
2364
2365     ir_value *condval;
2366     ir_value *trueval, *falseval;
2367     ir_instr *phi;
2368
2369     ir_block *cond = func->curblock;
2370     ir_block *cond_out = NULL;
2371     ir_block *ontrue, *ontrue_out = NULL;
2372     ir_block *onfalse, *onfalse_out = NULL;
2373     ir_block *merge;
2374
2375     /* Ternary can never create an lvalue... */
2376     if (lvalue)
2377         return false;
2378
2379     /* In theory it shouldn't be possible to pass through a node twice, but
2380      * in case we add any kind of optimization pass for the AST itself, it
2381      * may still happen, thus we remember a created ir_value and simply return one
2382      * if it already exists.
2383      */
2384     if (self->expression.outr) {
2385         *out = self->expression.outr;
2386         return true;
2387     }
2388
2389     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2390
2391     /* generate the condition */
2392     func->curblock = cond;
2393     cgen = self->cond->expression.codegen;
2394     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2395         return false;
2396     cond_out = func->curblock;
2397
2398     /* create on-true block */
2399     ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2400     if (!ontrue)
2401         return false;
2402     else
2403     {
2404         /* enter the block */
2405         func->curblock = ontrue;
2406
2407         /* generate */
2408         cgen = self->on_true->expression.codegen;
2409         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2410             return false;
2411
2412         ontrue_out = func->curblock;
2413     }
2414
2415     /* create on-false block */
2416     onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2417     if (!onfalse)
2418         return false;
2419     else
2420     {
2421         /* enter the block */
2422         func->curblock = onfalse;
2423
2424         /* generate */
2425         cgen = self->on_false->expression.codegen;
2426         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2427             return false;
2428
2429         onfalse_out = func->curblock;
2430     }
2431
2432     /* create merge block */
2433     merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2434     if (!merge)
2435         return false;
2436     /* jump to merge block */
2437     if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2438         return false;
2439     if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2440         return false;
2441
2442     /* create if instruction */
2443     if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2444         return false;
2445
2446     /* Now enter the merge block */
2447     func->curblock = merge;
2448
2449     /* Here, now, we need a PHI node
2450      * but first some sanity checking...
2451      */
2452     if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2453         /* error("ternary with different types on the two sides"); */
2454         compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2455         return false;
2456     }
2457
2458     /* create PHI */
2459     phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2460     if (!phi) {
2461         compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2462         return false;
2463     }
2464     ir_phi_add(phi, ontrue_out,  trueval);
2465     ir_phi_add(phi, onfalse_out, falseval);
2466
2467     self->expression.outr = ir_phi_value(phi);
2468     *out = self->expression.outr;
2469
2470     codegen_output_type(self, *out);
2471
2472     return true;
2473 }
2474
2475 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2476 {
2477     ast_expression_codegen *cgen;
2478
2479     ir_value *dummy      = NULL;
2480     ir_value *precond    = NULL;
2481     ir_value *postcond   = NULL;
2482
2483     /* Since we insert some jumps "late" so we have blocks
2484      * ordered "nicely", we need to keep track of the actual end-blocks
2485      * of expressions to add the jumps to.
2486      */
2487     ir_block *bbody      = NULL, *end_bbody      = NULL;
2488     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2489     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2490     ir_block *bincrement = NULL, *end_bincrement = NULL;
2491     ir_block *bout       = NULL, *bin            = NULL;
2492
2493     /* let's at least move the outgoing block to the end */
2494     size_t    bout_id;
2495
2496     /* 'break' and 'continue' need to be able to find the right blocks */
2497     ir_block *bcontinue     = NULL;
2498     ir_block *bbreak        = NULL;
2499
2500     ir_block *tmpblock      = NULL;
2501
2502     (void)lvalue;
2503     (void)out;
2504
2505     if (self->expression.outr) {
2506         compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2507         return false;
2508     }
2509     self->expression.outr = (ir_value*)1;
2510
2511     /* NOTE:
2512      * Should we ever need some kind of block ordering, better make this function
2513      * move blocks around than write a block ordering algorithm later... after all
2514      * the ast and ir should work together, not against each other.
2515      */
2516
2517     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2518      * anyway if for example it contains a ternary.
2519      */
2520     if (self->initexpr)
2521     {
2522         cgen = self->initexpr->expression.codegen;
2523         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2524             return false;
2525     }
2526
2527     /* Store the block from which we enter this chaos */
2528     bin = func->curblock;
2529
2530     /* The pre-loop condition needs its own block since we
2531      * need to be able to jump to the start of that expression.
2532      */
2533     if (self->precond)
2534     {
2535         bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2536         if (!bprecond)
2537             return false;
2538
2539         /* the pre-loop-condition the least important place to 'continue' at */
2540         bcontinue = bprecond;
2541
2542         /* enter */
2543         func->curblock = bprecond;
2544
2545         /* generate */
2546         cgen = self->precond->expression.codegen;
2547         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2548             return false;
2549
2550         end_bprecond = func->curblock;
2551     } else {
2552         bprecond = end_bprecond = NULL;
2553     }
2554
2555     /* Now the next blocks won't be ordered nicely, but we need to
2556      * generate them this early for 'break' and 'continue'.
2557      */
2558     if (self->increment) {
2559         bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2560         if (!bincrement)
2561             return false;
2562         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2563     } else {
2564         bincrement = end_bincrement = NULL;
2565     }
2566
2567     if (self->postcond) {
2568         bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2569         if (!bpostcond)
2570             return false;
2571         bcontinue = bpostcond; /* postcond comes before the increment */
2572     } else {
2573         bpostcond = end_bpostcond = NULL;
2574     }
2575
2576     bout_id = vec_size(func->ir_func->blocks);
2577     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2578     if (!bout)
2579         return false;
2580     bbreak = bout;
2581
2582     /* The loop body... */
2583     /* if (self->body) */
2584     {
2585         bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2586         if (!bbody)
2587             return false;
2588
2589         /* enter */
2590         func->curblock = bbody;
2591
2592         vec_push(func->breakblocks,    bbreak);
2593         if (bcontinue)
2594             vec_push(func->continueblocks, bcontinue);
2595         else
2596             vec_push(func->continueblocks, bbody);
2597
2598         /* generate */
2599         if (self->body) {
2600             cgen = self->body->expression.codegen;
2601             if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2602                 return false;
2603         }
2604
2605         end_bbody = func->curblock;
2606         vec_pop(func->breakblocks);
2607         vec_pop(func->continueblocks);
2608     }
2609
2610     /* post-loop-condition */
2611     if (self->postcond)
2612     {
2613         /* enter */
2614         func->curblock = bpostcond;
2615
2616         /* generate */
2617         cgen = self->postcond->expression.codegen;
2618         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2619             return false;
2620
2621         end_bpostcond = func->curblock;
2622     }
2623
2624     /* The incrementor */
2625     if (self->increment)
2626     {
2627         /* enter */
2628         func->curblock = bincrement;
2629
2630         /* generate */
2631         cgen = self->increment->expression.codegen;
2632         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2633             return false;
2634
2635         end_bincrement = func->curblock;
2636     }
2637
2638     /* In any case now, we continue from the outgoing block */
2639     func->curblock = bout;
2640
2641     /* Now all blocks are in place */
2642     /* From 'bin' we jump to whatever comes first */
2643     if      (bprecond)   tmpblock = bprecond;
2644     else if (bbody)      tmpblock = bbody;
2645     else if (bpostcond)  tmpblock = bpostcond;
2646     else                 tmpblock = bout;
2647     if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2648         return false;
2649
2650     /* From precond */
2651     if (bprecond)
2652     {
2653         ir_block *ontrue, *onfalse;
2654         if      (bbody)      ontrue = bbody;
2655         else if (bincrement) ontrue = bincrement;
2656         else if (bpostcond)  ontrue = bpostcond;
2657         else                 ontrue = bprecond;
2658         onfalse = bout;
2659         if (self->pre_not) {
2660             tmpblock = ontrue;
2661             ontrue   = onfalse;
2662             onfalse  = tmpblock;
2663         }
2664         if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2665             return false;
2666     }
2667
2668     /* from body */
2669     if (bbody)
2670     {
2671         if      (bincrement) tmpblock = bincrement;
2672         else if (bpostcond)  tmpblock = bpostcond;
2673         else if (bprecond)   tmpblock = bprecond;
2674         else                 tmpblock = bbody;
2675         if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2676             return false;
2677     }
2678
2679     /* from increment */
2680     if (bincrement)
2681     {
2682         if      (bpostcond)  tmpblock = bpostcond;
2683         else if (bprecond)   tmpblock = bprecond;
2684         else if (bbody)      tmpblock = bbody;
2685         else                 tmpblock = bout;
2686         if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2687             return false;
2688     }
2689
2690     /* from postcond */
2691     if (bpostcond)
2692     {
2693         ir_block *ontrue, *onfalse;
2694         if      (bprecond)   ontrue = bprecond;
2695         else if (bbody)      ontrue = bbody;
2696         else if (bincrement) ontrue = bincrement;
2697         else                 ontrue = bpostcond;
2698         onfalse = bout;
2699         if (self->post_not) {
2700             tmpblock = ontrue;
2701             ontrue   = onfalse;
2702             onfalse  = tmpblock;
2703         }
2704         if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2705             return false;
2706     }
2707
2708     /* Move 'bout' to the end */
2709     vec_remove(func->ir_func->blocks, bout_id, 1);
2710     vec_push(func->ir_func->blocks, bout);
2711
2712     return true;
2713 }
2714
2715 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2716 {
2717     ir_block *target;
2718
2719     *out = NULL;
2720
2721     if (lvalue) {
2722         compile_error(ast_ctx(self), "break/continue expression is not an l-value");
2723         return false;
2724     }
2725
2726     if (self->expression.outr) {
2727         compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2728         return false;
2729     }
2730     self->expression.outr = (ir_value*)1;
2731
2732     if (self->is_continue)
2733         target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
2734     else
2735         target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
2736
2737     if (!target) {
2738         compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
2739         return false;
2740     }
2741
2742     if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
2743         return false;
2744     return true;
2745 }
2746
2747 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
2748 {
2749     ast_expression_codegen *cgen;
2750
2751     ast_switch_case *def_case     = NULL;
2752     ir_block        *def_bfall    = NULL;
2753     ir_block        *def_bfall_to = NULL;
2754     bool set_def_bfall_to = false;
2755
2756     ir_value *dummy     = NULL;
2757     ir_value *irop      = NULL;
2758     ir_block *bout      = NULL;
2759     ir_block *bfall     = NULL;
2760     size_t    bout_id;
2761     size_t    c;
2762
2763     char      typestr[1024];
2764     uint16_t  cmpinstr;
2765
2766     if (lvalue) {
2767         compile_error(ast_ctx(self), "switch expression is not an l-value");
2768         return false;
2769     }
2770
2771     if (self->expression.outr) {
2772         compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
2773         return false;
2774     }
2775     self->expression.outr = (ir_value*)1;
2776
2777     (void)lvalue;
2778     (void)out;
2779
2780     cgen = self->operand->expression.codegen;
2781     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
2782         return false;
2783
2784     if (!vec_size(self->cases))
2785         return true;
2786
2787     cmpinstr = type_eq_instr[irop->vtype];
2788     if (cmpinstr >= AINSTR_END) {
2789         ast_type_to_string(self->operand, typestr, sizeof(typestr));
2790         compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
2791         return false;
2792     }
2793
2794     bout_id = vec_size(func->ir_func->blocks);
2795     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
2796     if (!bout)
2797         return false;
2798
2799     /* setup the break block */
2800     vec_push(func->breakblocks, bout);
2801
2802     /* Now create all cases */
2803     for (c = 0; c < vec_size(self->cases); ++c) {
2804         ir_value *cond, *val;
2805         ir_block *bcase, *bnot;
2806         size_t bnot_id;
2807
2808         ast_switch_case *swcase = &self->cases[c];
2809
2810         if (swcase->value) {
2811             /* A regular case */
2812             /* generate the condition operand */
2813             cgen = swcase->value->expression.codegen;
2814             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
2815                 return false;
2816             /* generate the condition */
2817             cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
2818             if (!cond)
2819                 return false;
2820
2821             bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
2822             bnot_id = vec_size(func->ir_func->blocks);
2823             bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
2824             if (!bcase || !bnot)
2825                 return false;
2826             if (set_def_bfall_to) {
2827                 set_def_bfall_to = false;
2828                 def_bfall_to = bcase;
2829             }
2830             if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
2831                 return false;
2832
2833             /* Make the previous case-end fall through */
2834             if (bfall && !bfall->final) {
2835                 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
2836                     return false;
2837             }
2838
2839             /* enter the case */
2840             func->curblock = bcase;
2841             cgen = swcase->code->expression.codegen;
2842             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
2843                 return false;
2844
2845             /* remember this block to fall through from */
2846             bfall = func->curblock;
2847
2848             /* enter the else and move it down */
2849             func->curblock = bnot;
2850             vec_remove(func->ir_func->blocks, bnot_id, 1);
2851             vec_push(func->ir_func->blocks, bnot);
2852         } else {
2853             /* The default case */
2854             /* Remember where to fall through from: */
2855             def_bfall = bfall;
2856             bfall     = NULL;
2857             /* remember which case it was */
2858             def_case  = swcase;
2859             /* And the next case will be remembered */
2860             set_def_bfall_to = true;
2861         }
2862     }
2863
2864     /* Jump from the last bnot to bout */
2865     if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
2866         /*
2867         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
2868         */
2869         return false;
2870     }
2871
2872     /* If there was a default case, put it down here */
2873     if (def_case) {
2874         ir_block *bcase;
2875
2876         /* No need to create an extra block */
2877         bcase = func->curblock;
2878
2879         /* Insert the fallthrough jump */
2880         if (def_bfall && !def_bfall->final) {
2881             if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
2882                 return false;
2883         }
2884
2885         /* Now generate the default code */
2886         cgen = def_case->code->expression.codegen;
2887         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
2888             return false;
2889
2890         /* see if we need to fall through */
2891         if (def_bfall_to && !func->curblock->final)
2892         {
2893             if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
2894                 return false;
2895         }
2896     }
2897
2898     /* Jump from the last bnot to bout */
2899     if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
2900         return false;
2901     /* enter the outgoing block */
2902     func->curblock = bout;
2903
2904     /* restore the break block */
2905     vec_pop(func->breakblocks);
2906
2907     /* Move 'bout' to the end, it's nicer */
2908     vec_remove(func->ir_func->blocks, bout_id, 1);
2909     vec_push(func->ir_func->blocks, bout);
2910
2911     return true;
2912 }
2913
2914 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
2915 {
2916     size_t i;
2917     ir_value *dummy;
2918
2919     if (self->undefined) {
2920         compile_error(ast_ctx(self), "internal error: ast_label never defined");
2921         return false;
2922     }
2923
2924     *out = NULL;
2925     if (lvalue) {
2926         compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
2927         return false;
2928     }
2929
2930     /* simply create a new block and jump to it */
2931     self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
2932     if (!self->irblock) {
2933         compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
2934         return false;
2935     }
2936     if (!func->curblock->final) {
2937         if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
2938             return false;
2939     }
2940
2941     /* enter the new block */
2942     func->curblock = self->irblock;
2943
2944     /* Generate all the leftover gotos */
2945     for (i = 0; i < vec_size(self->gotos); ++i) {
2946         if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
2947             return false;
2948     }
2949
2950     return true;
2951 }
2952
2953 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
2954 {
2955     *out = NULL;
2956     if (lvalue) {
2957         compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
2958         return false;
2959     }
2960
2961     if (self->target->irblock) {
2962         if (self->irblock_from) {
2963             /* we already tried once, this is the callback */
2964             self->irblock_from->final = false;
2965             if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
2966                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
2967                 return false;
2968             }
2969         }
2970         else
2971         {
2972             if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
2973                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
2974                 return false;
2975             }
2976         }
2977     }
2978     else
2979     {
2980         /* the target has not yet been created...
2981          * close this block in a sneaky way:
2982          */
2983         func->curblock->final = true;
2984         self->irblock_from = func->curblock;
2985         ast_label_register_goto(self->target, self);
2986     }
2987
2988     return true;
2989 }
2990
2991 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
2992 {
2993     ast_expression_codegen *cgen;
2994     ir_value              **params;
2995     ir_instr               *callinstr;
2996     size_t i;
2997
2998     ir_value *funval = NULL;
2999
3000     /* return values are never lvalues */
3001     if (lvalue) {
3002         compile_error(ast_ctx(self), "not an l-value (function call)");
3003         return false;
3004     }
3005
3006     if (self->expression.outr) {
3007         *out = self->expression.outr;
3008         return true;
3009     }
3010
3011     cgen = self->func->expression.codegen;
3012     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3013         return false;
3014     if (!funval)
3015         return false;
3016
3017     params = NULL;
3018
3019     /* parameters */
3020     for (i = 0; i < vec_size(self->params); ++i)
3021     {
3022         ir_value *param;
3023         ast_expression *expr = self->params[i];
3024
3025         cgen = expr->expression.codegen;
3026         if (!(*cgen)(expr, func, false, &param))
3027             goto error;
3028         if (!param)
3029             goto error;
3030         vec_push(params, param);
3031     }
3032
3033     callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3034                                      ast_function_label(func, "call"),
3035                                      funval, !!(self->func->expression.flags & AST_FLAG_NORETURN));
3036     if (!callinstr)
3037         goto error;
3038
3039     for (i = 0; i < vec_size(params); ++i) {
3040         ir_call_param(callinstr, params[i]);
3041     }
3042
3043     *out = ir_call_value(callinstr);
3044     self->expression.outr = *out;
3045
3046     codegen_output_type(self, *out);
3047
3048     vec_free(params);
3049     return true;
3050 error:
3051     vec_free(params);
3052     return false;
3053 }