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