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