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