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