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