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