]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
202adb64dc08e22ac87011b3920b7b485d64a70d
[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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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_t 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     /* eliminate branches if value is constant */
2535     if (condval->vtype == TYPE_FLOAT && condval->hasvalue && condval->cvq == CV_CONST) {
2536         /* don't generate if statements */
2537         if (condval->constval.vfloat == 1.0f && self->on_true) {
2538             if (!(ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"))))
2539                 return false;
2540             /* generate */
2541             if (!(*(cgen = self->on_true->codegen))((ast_expression*)(self->on_true), func, false, &dummy))
2542                 return false;
2543             if (!ir_block_create_jump(func->curblock, ast_ctx(self), ontrue))
2544                 return false;
2545             func->curblock = ontrue;
2546             return true;
2547         } else if (condval->constval.vfloat == 0.0f && self->on_false) {
2548             if (!(onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"))))
2549                 return false;
2550             /* generate */
2551             if (!(*(cgen = self->on_false->codegen))((ast_expression*)(self->on_false), func, false, &dummy))
2552                 return false;
2553             if (!ir_block_create_jump(func->curblock, ast_ctx(self), onfalse))
2554                 return false;
2555             func->curblock = onfalse;
2556             return true;
2557         }
2558     } 
2559     /* on-true path */
2560
2561     if (self->on_true) {
2562         /* create on-true block */
2563         ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2564         if (!ontrue)
2565             return false;
2566
2567         /* enter the block */
2568         func->curblock = ontrue;
2569
2570         /* generate */
2571         cgen = self->on_true->codegen;
2572         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2573             return false;
2574
2575         /* we now need to work from the current endpoint */
2576         ontrue_endblock = func->curblock;
2577     } else
2578         ontrue = NULL;
2579
2580     /* on-false path */
2581     if (self->on_false) {
2582         /* create on-false block */
2583         onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2584         if (!onfalse)
2585             return false;
2586
2587         /* enter the block */
2588         func->curblock = onfalse;
2589
2590         /* generate */
2591         cgen = self->on_false->codegen;
2592         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2593             return false;
2594
2595         /* we now need to work from the current endpoint */
2596         onfalse_endblock = func->curblock;
2597     } else
2598         onfalse = NULL;
2599
2600     /* Merge block were they all merge in to */
2601     if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2602     {
2603         merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2604         if (!merge)
2605             return false;
2606         /* add jumps ot the merge block */
2607         if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2608             return false;
2609         if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2610             return false;
2611
2612         /* Now enter the merge block */
2613         func->curblock = merge;
2614     }
2615
2616     /* we create the if here, that way all blocks are ordered :)
2617      */
2618     if (!ir_block_create_if(cond, ast_ctx(self), condval,
2619                             (ontrue  ? ontrue  : merge),
2620                             (onfalse ? onfalse : merge)))
2621     {
2622         return false;
2623     }
2624
2625     return true;
2626 }
2627
2628 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2629 {
2630     ast_expression_codegen *cgen;
2631
2632     ir_value *condval;
2633     ir_value *trueval, *falseval;
2634     ir_instr *phi;
2635
2636     ir_block *cond = func->curblock;
2637     ir_block *cond_out = NULL;
2638     ir_block *ontrue, *ontrue_out = NULL;
2639     ir_block *onfalse, *onfalse_out = NULL;
2640     ir_block *merge;
2641
2642     /* Ternary can never create an lvalue... */
2643     if (lvalue)
2644         return false;
2645
2646     /* In theory it shouldn't be possible to pass through a node twice, but
2647      * in case we add any kind of optimization pass for the AST itself, it
2648      * may still happen, thus we remember a created ir_value and simply return one
2649      * if it already exists.
2650      */
2651     if (self->expression.outr) {
2652         *out = self->expression.outr;
2653         return true;
2654     }
2655
2656     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2657
2658     /* generate the condition */
2659     func->curblock = cond;
2660     cgen = self->cond->codegen;
2661     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2662         return false;
2663     cond_out = func->curblock;
2664
2665     /* create on-true block */
2666     ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2667     if (!ontrue)
2668         return false;
2669     else
2670     {
2671         /* enter the block */
2672         func->curblock = ontrue;
2673
2674         /* generate */
2675         cgen = self->on_true->codegen;
2676         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2677             return false;
2678
2679         ontrue_out = func->curblock;
2680     }
2681
2682     /* create on-false block */
2683     onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2684     if (!onfalse)
2685         return false;
2686     else
2687     {
2688         /* enter the block */
2689         func->curblock = onfalse;
2690
2691         /* generate */
2692         cgen = self->on_false->codegen;
2693         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2694             return false;
2695
2696         onfalse_out = func->curblock;
2697     }
2698
2699     /* create merge block */
2700     merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2701     if (!merge)
2702         return false;
2703     /* jump to merge block */
2704     if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2705         return false;
2706     if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2707         return false;
2708
2709     /* create if instruction */
2710     if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2711         return false;
2712
2713     /* Now enter the merge block */
2714     func->curblock = merge;
2715
2716     /* Here, now, we need a PHI node
2717      * but first some sanity checking...
2718      */
2719     if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2720         /* error("ternary with different types on the two sides"); */
2721         compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2722         return false;
2723     }
2724
2725     /* create PHI */
2726     phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2727     if (!phi) {
2728         compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2729         return false;
2730     }
2731     ir_phi_add(phi, ontrue_out,  trueval);
2732     ir_phi_add(phi, onfalse_out, falseval);
2733
2734     self->expression.outr = ir_phi_value(phi);
2735     *out = self->expression.outr;
2736
2737     codegen_output_type(self, *out);
2738
2739     return true;
2740 }
2741
2742 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2743 {
2744     ast_expression_codegen *cgen;
2745
2746     ir_value *dummy      = NULL;
2747     ir_value *precond    = NULL;
2748     ir_value *postcond   = NULL;
2749
2750     /* Since we insert some jumps "late" so we have blocks
2751      * ordered "nicely", we need to keep track of the actual end-blocks
2752      * of expressions to add the jumps to.
2753      */
2754     ir_block *bbody      = NULL, *end_bbody      = NULL;
2755     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2756     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2757     ir_block *bincrement = NULL, *end_bincrement = NULL;
2758     ir_block *bout       = NULL, *bin            = NULL;
2759
2760     /* let's at least move the outgoing block to the end */
2761     size_t    bout_id;
2762
2763     /* 'break' and 'continue' need to be able to find the right blocks */
2764     ir_block *bcontinue     = NULL;
2765     ir_block *bbreak        = NULL;
2766
2767     ir_block *tmpblock      = NULL;
2768
2769     (void)lvalue;
2770     (void)out;
2771
2772     if (self->expression.outr) {
2773         compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2774         return false;
2775     }
2776     self->expression.outr = (ir_value*)1;
2777
2778     /* NOTE:
2779      * Should we ever need some kind of block ordering, better make this function
2780      * move blocks around than write a block ordering algorithm later... after all
2781      * the ast and ir should work together, not against each other.
2782      */
2783
2784     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2785      * anyway if for example it contains a ternary.
2786      */
2787     if (self->initexpr)
2788     {
2789         cgen = self->initexpr->codegen;
2790         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2791             return false;
2792     }
2793
2794     /* Store the block from which we enter this chaos */
2795     bin = func->curblock;
2796
2797     /* The pre-loop condition needs its own block since we
2798      * need to be able to jump to the start of that expression.
2799      */
2800     if (self->precond)
2801     {
2802         bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2803         if (!bprecond)
2804             return false;
2805
2806         /* the pre-loop-condition the least important place to 'continue' at */
2807         bcontinue = bprecond;
2808
2809         /* enter */
2810         func->curblock = bprecond;
2811
2812         /* generate */
2813         cgen = self->precond->codegen;
2814         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2815             return false;
2816
2817         end_bprecond = func->curblock;
2818     } else {
2819         bprecond = end_bprecond = NULL;
2820     }
2821
2822     /* Now the next blocks won't be ordered nicely, but we need to
2823      * generate them this early for 'break' and 'continue'.
2824      */
2825     if (self->increment) {
2826         bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2827         if (!bincrement)
2828             return false;
2829         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2830     } else {
2831         bincrement = end_bincrement = NULL;
2832     }
2833
2834     if (self->postcond) {
2835         bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2836         if (!bpostcond)
2837             return false;
2838         bcontinue = bpostcond; /* postcond comes before the increment */
2839     } else {
2840         bpostcond = end_bpostcond = NULL;
2841     }
2842
2843     bout_id = vec_size(func->ir_func->blocks);
2844     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2845     if (!bout)
2846         return false;
2847     bbreak = bout;
2848
2849     /* The loop body... */
2850     /* if (self->body) */
2851     {
2852         bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2853         if (!bbody)
2854             return false;
2855
2856         /* enter */
2857         func->curblock = bbody;
2858
2859         vec_push(func->breakblocks,    bbreak);
2860         if (bcontinue)
2861             vec_push(func->continueblocks, bcontinue);
2862         else
2863             vec_push(func->continueblocks, bbody);
2864
2865         /* generate */
2866         if (self->body) {
2867             cgen = self->body->codegen;
2868             if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2869                 return false;
2870         }
2871
2872         end_bbody = func->curblock;
2873         vec_pop(func->breakblocks);
2874         vec_pop(func->continueblocks);
2875     }
2876
2877     /* post-loop-condition */
2878     if (self->postcond)
2879     {
2880         /* enter */
2881         func->curblock = bpostcond;
2882
2883         /* generate */
2884         cgen = self->postcond->codegen;
2885         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2886             return false;
2887
2888         end_bpostcond = func->curblock;
2889     }
2890
2891     /* The incrementor */
2892     if (self->increment)
2893     {
2894         /* enter */
2895         func->curblock = bincrement;
2896
2897         /* generate */
2898         cgen = self->increment->codegen;
2899         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2900             return false;
2901
2902         end_bincrement = func->curblock;
2903     }
2904
2905     /* In any case now, we continue from the outgoing block */
2906     func->curblock = bout;
2907
2908     /* Now all blocks are in place */
2909     /* From 'bin' we jump to whatever comes first */
2910     if      (bprecond)   tmpblock = bprecond;
2911     else                 tmpblock = bbody;    /* can never be null */
2912
2913     /* DEAD CODE
2914     else if (bpostcond)  tmpblock = bpostcond;
2915     else                 tmpblock = bout;
2916     */
2917
2918     if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2919         return false;
2920
2921     /* From precond */
2922     if (bprecond)
2923     {
2924         ir_block *ontrue, *onfalse;
2925         ontrue = bbody; /* can never be null */
2926
2927         /* all of this is dead code
2928         else if (bincrement) ontrue = bincrement;
2929         else                 ontrue = bpostcond;
2930         */
2931
2932         onfalse = bout;
2933         if (self->pre_not) {
2934             tmpblock = ontrue;
2935             ontrue   = onfalse;
2936             onfalse  = tmpblock;
2937         }
2938         if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2939             return false;
2940     }
2941
2942     /* from body */
2943     if (bbody)
2944     {
2945         if      (bincrement) tmpblock = bincrement;
2946         else if (bpostcond)  tmpblock = bpostcond;
2947         else if (bprecond)   tmpblock = bprecond;
2948         else                 tmpblock = bbody;
2949         if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2950             return false;
2951     }
2952
2953     /* from increment */
2954     if (bincrement)
2955     {
2956         if      (bpostcond)  tmpblock = bpostcond;
2957         else if (bprecond)   tmpblock = bprecond;
2958         else if (bbody)      tmpblock = bbody;
2959         else                 tmpblock = bout;
2960         if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2961             return false;
2962     }
2963
2964     /* from postcond */
2965     if (bpostcond)
2966     {
2967         ir_block *ontrue, *onfalse;
2968         if      (bprecond)   ontrue = bprecond;
2969         else                 ontrue = bbody; /* can never be null */
2970
2971         /* all of this is dead code
2972         else if (bincrement) ontrue = bincrement;
2973         else                 ontrue = bpostcond;
2974         */
2975
2976         onfalse = bout;
2977         if (self->post_not) {
2978             tmpblock = ontrue;
2979             ontrue   = onfalse;
2980             onfalse  = tmpblock;
2981         }
2982         if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2983             return false;
2984     }
2985
2986     /* Move 'bout' to the end */
2987     vec_remove(func->ir_func->blocks, bout_id, 1);
2988     vec_push(func->ir_func->blocks, bout);
2989
2990     return true;
2991 }
2992
2993 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2994 {
2995     ir_block *target;
2996
2997     *out = NULL;
2998
2999     if (lvalue) {
3000         compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3001         return false;
3002     }
3003
3004     if (self->expression.outr) {
3005         compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3006         return false;
3007     }
3008     self->expression.outr = (ir_value*)1;
3009
3010     if (self->is_continue)
3011         target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3012     else
3013         target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3014
3015     if (!target) {
3016         compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3017         return false;
3018     }
3019
3020     if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3021         return false;
3022     return true;
3023 }
3024
3025 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3026 {
3027     ast_expression_codegen *cgen;
3028
3029     ast_switch_case *def_case     = NULL;
3030     ir_block        *def_bfall    = NULL;
3031     ir_block        *def_bfall_to = NULL;
3032     bool set_def_bfall_to = false;
3033
3034     ir_value *dummy     = NULL;
3035     ir_value *irop      = NULL;
3036     ir_block *bout      = NULL;
3037     ir_block *bfall     = NULL;
3038     size_t    bout_id;
3039     size_t    c;
3040
3041     char      typestr[1024];
3042     uint16_t  cmpinstr;
3043
3044     if (lvalue) {
3045         compile_error(ast_ctx(self), "switch expression is not an l-value");
3046         return false;
3047     }
3048
3049     if (self->expression.outr) {
3050         compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3051         return false;
3052     }
3053     self->expression.outr = (ir_value*)1;
3054
3055     (void)lvalue;
3056     (void)out;
3057
3058     cgen = self->operand->codegen;
3059     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3060         return false;
3061
3062     if (!vec_size(self->cases))
3063         return true;
3064
3065     cmpinstr = type_eq_instr[irop->vtype];
3066     if (cmpinstr >= VINSTR_END) {
3067         ast_type_to_string(self->operand, typestr, sizeof(typestr));
3068         compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3069         return false;
3070     }
3071
3072     bout_id = vec_size(func->ir_func->blocks);
3073     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3074     if (!bout)
3075         return false;
3076
3077     /* setup the break block */
3078     vec_push(func->breakblocks, bout);
3079
3080     /* Now create all cases */
3081     for (c = 0; c < vec_size(self->cases); ++c) {
3082         ir_value *cond, *val;
3083         ir_block *bcase, *bnot;
3084         size_t bnot_id;
3085
3086         ast_switch_case *swcase = &self->cases[c];
3087
3088         if (swcase->value) {
3089             /* A regular case */
3090             /* generate the condition operand */
3091             cgen = swcase->value->codegen;
3092             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3093                 return false;
3094             /* generate the condition */
3095             cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3096             if (!cond)
3097                 return false;
3098
3099             bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3100             bnot_id = vec_size(func->ir_func->blocks);
3101             bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3102             if (!bcase || !bnot)
3103                 return false;
3104             if (set_def_bfall_to) {
3105                 set_def_bfall_to = false;
3106                 def_bfall_to = bcase;
3107             }
3108             if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3109                 return false;
3110
3111             /* Make the previous case-end fall through */
3112             if (bfall && !bfall->final) {
3113                 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3114                     return false;
3115             }
3116
3117             /* enter the case */
3118             func->curblock = bcase;
3119             cgen = swcase->code->codegen;
3120             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3121                 return false;
3122
3123             /* remember this block to fall through from */
3124             bfall = func->curblock;
3125
3126             /* enter the else and move it down */
3127             func->curblock = bnot;
3128             vec_remove(func->ir_func->blocks, bnot_id, 1);
3129             vec_push(func->ir_func->blocks, bnot);
3130         } else {
3131             /* The default case */
3132             /* Remember where to fall through from: */
3133             def_bfall = bfall;
3134             bfall     = NULL;
3135             /* remember which case it was */
3136             def_case  = swcase;
3137             /* And the next case will be remembered */
3138             set_def_bfall_to = true;
3139         }
3140     }
3141
3142     /* Jump from the last bnot to bout */
3143     if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3144         /*
3145         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3146         */
3147         return false;
3148     }
3149
3150     /* If there was a default case, put it down here */
3151     if (def_case) {
3152         ir_block *bcase;
3153
3154         /* No need to create an extra block */
3155         bcase = func->curblock;
3156
3157         /* Insert the fallthrough jump */
3158         if (def_bfall && !def_bfall->final) {
3159             if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3160                 return false;
3161         }
3162
3163         /* Now generate the default code */
3164         cgen = def_case->code->codegen;
3165         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3166             return false;
3167
3168         /* see if we need to fall through */
3169         if (def_bfall_to && !func->curblock->final)
3170         {
3171             if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3172                 return false;
3173         }
3174     }
3175
3176     /* Jump from the last bnot to bout */
3177     if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3178         return false;
3179     /* enter the outgoing block */
3180     func->curblock = bout;
3181
3182     /* restore the break block */
3183     vec_pop(func->breakblocks);
3184
3185     /* Move 'bout' to the end, it's nicer */
3186     vec_remove(func->ir_func->blocks, bout_id, 1);
3187     vec_push(func->ir_func->blocks, bout);
3188
3189     return true;
3190 }
3191
3192 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3193 {
3194     size_t i;
3195     ir_value *dummy;
3196
3197     if (self->undefined) {
3198         compile_error(ast_ctx(self), "internal error: ast_label never defined");
3199         return false;
3200     }
3201
3202     *out = NULL;
3203     if (lvalue) {
3204         compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3205         return false;
3206     }
3207
3208     /* simply create a new block and jump to it */
3209     self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3210     if (!self->irblock) {
3211         compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3212         return false;
3213     }
3214     if (!func->curblock->final) {
3215         if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3216             return false;
3217     }
3218
3219     /* enter the new block */
3220     func->curblock = self->irblock;
3221
3222     /* Generate all the leftover gotos */
3223     for (i = 0; i < vec_size(self->gotos); ++i) {
3224         if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3225             return false;
3226     }
3227
3228     return true;
3229 }
3230
3231 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3232 {
3233     *out = NULL;
3234     if (lvalue) {
3235         compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3236         return false;
3237     }
3238
3239     if (self->target->irblock) {
3240         if (self->irblock_from) {
3241             /* we already tried once, this is the callback */
3242             self->irblock_from->final = false;
3243             if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3244                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3245                 return false;
3246             }
3247         }
3248         else
3249         {
3250             if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3251                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3252                 return false;
3253             }
3254         }
3255     }
3256     else
3257     {
3258         /* the target has not yet been created...
3259          * close this block in a sneaky way:
3260          */
3261         func->curblock->final = true;
3262         self->irblock_from = func->curblock;
3263         ast_label_register_goto(self->target, self);
3264     }
3265
3266     return true;
3267 }
3268
3269 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3270 {
3271     ast_expression_codegen *cgen;
3272     ir_value              **params;
3273     ir_instr               *callinstr;
3274     size_t i;
3275
3276     ir_value *funval = NULL;
3277
3278     /* return values are never lvalues */
3279     if (lvalue) {
3280         compile_error(ast_ctx(self), "not an l-value (function call)");
3281         return false;
3282     }
3283
3284     if (self->expression.outr) {
3285         *out = self->expression.outr;
3286         return true;
3287     }
3288
3289     cgen = self->func->codegen;
3290     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3291         return false;
3292     if (!funval)
3293         return false;
3294
3295     params = NULL;
3296
3297     /* parameters */
3298     for (i = 0; i < vec_size(self->params); ++i)
3299     {
3300         ir_value *param;
3301         ast_expression *expr = self->params[i];
3302
3303         cgen = expr->codegen;
3304         if (!(*cgen)(expr, func, false, &param))
3305             goto error;
3306         if (!param)
3307             goto error;
3308         vec_push(params, param);
3309     }
3310
3311     /* varargs counter */
3312     if (self->va_count) {
3313         ir_value   *va_count;
3314         ir_builder *builder = func->curblock->owner->owner;
3315         cgen = self->va_count->codegen;
3316         if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3317             return false;
3318         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3319                                       ir_builder_get_va_count(builder), va_count))
3320         {
3321             return false;
3322         }
3323     }
3324
3325     callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3326                                      ast_function_label(func, "call"),
3327                                      funval, !!(self->func->flags & AST_FLAG_NORETURN));
3328     if (!callinstr)
3329         goto error;
3330
3331     for (i = 0; i < vec_size(params); ++i) {
3332         ir_call_param(callinstr, params[i]);
3333     }
3334
3335     *out = ir_call_value(callinstr);
3336     self->expression.outr = *out;
3337
3338     codegen_output_type(self, *out);
3339
3340     vec_free(params);
3341     return true;
3342 error:
3343     vec_free(params);
3344     return false;
3345 }