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