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