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