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