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