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