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