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