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