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