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