]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
2a8caf2cc2c1f263a8eeb1e85510840f729b1b5f
[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 static bool check_array(ast_value *self, ast_value *array)
1352 {
1353     if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1354         compile_error(ast_ctx(self), "array without size: %s", self->name);
1355         return false;
1356     }
1357     /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1358     if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1359         compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1360         return false;
1361     }
1362     return true;
1363 }
1364
1365 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1366 {
1367     ir_value *v = NULL;
1368
1369     if (self->expression.vtype == TYPE_NIL) {
1370         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1371         return false;
1372     }
1373
1374     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1375     {
1376         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1377         if (!func)
1378             return false;
1379         func->context = ast_ctx(self);
1380         func->value->context = ast_ctx(self);
1381
1382         self->constval.vfunc->ir_func = func;
1383         self->ir_v = func->value;
1384         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1385             self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1386         /* The function is filled later on ast_function_codegen... */
1387         return true;
1388     }
1389
1390     if (isfield && self->expression.vtype == TYPE_FIELD) {
1391         ast_expression *fieldtype = self->expression.next;
1392
1393         if (self->hasvalue) {
1394             compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1395             goto error;
1396         }
1397
1398         if (fieldtype->vtype == TYPE_ARRAY) {
1399             size_t ai;
1400             char   *name;
1401             size_t  namelen;
1402
1403             ast_expression *elemtype;
1404             int             vtype;
1405             ast_value      *array = (ast_value*)fieldtype;
1406
1407             if (!ast_istype(fieldtype, ast_value)) {
1408                 compile_error(ast_ctx(self), "internal error: ast_value required");
1409                 return false;
1410             }
1411
1412             if (!check_array(self, array))
1413                 return false;
1414
1415             elemtype = array->expression.next;
1416             vtype = elemtype->vtype;
1417
1418             v = ir_builder_create_field(ir, self->name, vtype);
1419             if (!v) {
1420                 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1421                 return false;
1422             }
1423             v->context = ast_ctx(self);
1424             v->unique_life = true;
1425             v->locked      = true;
1426             array->ir_v = self->ir_v = v;
1427             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1428                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1429
1430             namelen = strlen(self->name);
1431             name    = (char*)mem_a(namelen + 16);
1432             util_strncpy(name, self->name, namelen);
1433
1434             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1435             array->ir_values[0] = v;
1436             for (ai = 1; ai < array->expression.count; ++ai) {
1437                 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1438                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1439                 if (!array->ir_values[ai]) {
1440                     mem_d(name);
1441                     compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1442                     return false;
1443                 }
1444                 array->ir_values[ai]->context = ast_ctx(self);
1445                 array->ir_values[ai]->unique_life = true;
1446                 array->ir_values[ai]->locked      = true;
1447                 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1448                     self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1449             }
1450             mem_d(name);
1451         }
1452         else
1453         {
1454             v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1455             if (!v)
1456                 return false;
1457             v->context = ast_ctx(self);
1458             self->ir_v = v;
1459             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1460                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1461         }
1462         return true;
1463     }
1464
1465     if (self->expression.vtype == TYPE_ARRAY) {
1466         size_t ai;
1467         char   *name;
1468         size_t  namelen;
1469
1470         ast_expression *elemtype = self->expression.next;
1471         int vtype = elemtype->vtype;
1472
1473         if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1474             compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1475             return false;
1476         }
1477
1478         /* same as with field arrays */
1479         if (!check_array(self, self))
1480             return false;
1481
1482         v = ir_builder_create_global(ir, self->name, vtype);
1483         if (!v) {
1484             compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1485             return false;
1486         }
1487         v->context = ast_ctx(self);
1488         v->unique_life = true;
1489         v->locked      = true;
1490         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1491             v->flags |= IR_FLAG_INCLUDE_DEF;
1492
1493         namelen = strlen(self->name);
1494         name    = (char*)mem_a(namelen + 16);
1495         util_strncpy(name, self->name, namelen);
1496
1497         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1498         self->ir_values[0] = v;
1499         for (ai = 1; ai < self->expression.count; ++ai) {
1500             util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1501             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1502             if (!self->ir_values[ai]) {
1503                 mem_d(name);
1504                 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1505                 return false;
1506             }
1507             self->ir_values[ai]->context = ast_ctx(self);
1508             self->ir_values[ai]->unique_life = true;
1509             self->ir_values[ai]->locked      = true;
1510             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1511                 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1512         }
1513         mem_d(name);
1514     }
1515     else
1516     {
1517         /* Arrays don't do this since there's no "array" value which spans across the
1518          * whole thing.
1519          */
1520         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1521         if (!v) {
1522             compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1523             return false;
1524         }
1525         codegen_output_type(self, v);
1526         v->context = ast_ctx(self);
1527     }
1528
1529     /* link us to the ir_value */
1530     v->cvq = self->cvq;
1531     self->ir_v = v;
1532     if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1533         self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1534
1535     /* initialize */
1536     if (self->hasvalue) {
1537         switch (self->expression.vtype)
1538         {
1539             case TYPE_FLOAT:
1540                 if (!ir_value_set_float(v, self->constval.vfloat))
1541                     goto error;
1542                 break;
1543             case TYPE_VECTOR:
1544                 if (!ir_value_set_vector(v, self->constval.vvec))
1545                     goto error;
1546                 break;
1547             case TYPE_STRING:
1548                 if (!ir_value_set_string(v, self->constval.vstring))
1549                     goto error;
1550                 break;
1551             case TYPE_ARRAY:
1552                 ast_global_array_set(self);
1553                 break;
1554             case TYPE_FUNCTION:
1555                 compile_error(ast_ctx(self), "global of type function not properly generated");
1556                 goto error;
1557                 /* Cannot generate an IR value for a function,
1558                  * need a pointer pointing to a function rather.
1559                  */
1560             case TYPE_FIELD:
1561                 if (!self->constval.vfield) {
1562                     compile_error(ast_ctx(self), "field constant without vfield set");
1563                     goto error;
1564                 }
1565                 if (!self->constval.vfield->ir_v) {
1566                     compile_error(ast_ctx(self), "field constant generated before its field");
1567                     goto error;
1568                 }
1569                 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1570                     goto error;
1571                 break;
1572             default:
1573                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1574                 break;
1575         }
1576     }
1577     return true;
1578
1579 error: /* clean up */
1580     if(v) ir_value_delete(v);
1581     return false;
1582 }
1583
1584 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1585 {
1586     ir_value *v = NULL;
1587
1588     if (self->expression.vtype == TYPE_NIL) {
1589         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1590         return false;
1591     }
1592
1593     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1594     {
1595         /* Do we allow local functions? I think not...
1596          * this is NOT a function pointer atm.
1597          */
1598         return false;
1599     }
1600
1601     if (self->expression.vtype == TYPE_ARRAY) {
1602         size_t ai;
1603         char   *name;
1604         size_t  namelen;
1605
1606         ast_expression *elemtype = self->expression.next;
1607         int vtype = elemtype->vtype;
1608
1609         func->flags |= IR_FLAG_HAS_ARRAYS;
1610
1611         if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1612             compile_error(ast_ctx(self), "array-parameters are not supported");
1613             return false;
1614         }
1615
1616         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1617         if (!check_array(self, self))
1618             return false;
1619
1620         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1621         if (!self->ir_values) {
1622             compile_error(ast_ctx(self), "failed to allocate array values");
1623             return false;
1624         }
1625
1626         v = ir_function_create_local(func, self->name, vtype, param);
1627         if (!v) {
1628             compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1629             return false;
1630         }
1631         v->context = ast_ctx(self);
1632         v->unique_life = true;
1633         v->locked      = true;
1634
1635         namelen = strlen(self->name);
1636         name    = (char*)mem_a(namelen + 16);
1637         util_strncpy(name, self->name, namelen);
1638
1639         self->ir_values[0] = v;
1640         for (ai = 1; ai < self->expression.count; ++ai) {
1641             util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1642             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1643             if (!self->ir_values[ai]) {
1644                 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1645                 return false;
1646             }
1647             self->ir_values[ai]->context = ast_ctx(self);
1648             self->ir_values[ai]->unique_life = true;
1649             self->ir_values[ai]->locked      = true;
1650         }
1651         mem_d(name);
1652     }
1653     else
1654     {
1655         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1656         if (!v)
1657             return false;
1658         codegen_output_type(self, v);
1659         v->context = ast_ctx(self);
1660     }
1661
1662     /* A constant local... hmmm...
1663      * I suppose the IR will have to deal with this
1664      */
1665     if (self->hasvalue) {
1666         switch (self->expression.vtype)
1667         {
1668             case TYPE_FLOAT:
1669                 if (!ir_value_set_float(v, self->constval.vfloat))
1670                     goto error;
1671                 break;
1672             case TYPE_VECTOR:
1673                 if (!ir_value_set_vector(v, self->constval.vvec))
1674                     goto error;
1675                 break;
1676             case TYPE_STRING:
1677                 if (!ir_value_set_string(v, self->constval.vstring))
1678                     goto error;
1679                 break;
1680             default:
1681                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1682                 break;
1683         }
1684     }
1685
1686     /* link us to the ir_value */
1687     v->cvq = self->cvq;
1688     self->ir_v = v;
1689
1690     if (!ast_generate_accessors(self, func->owner))
1691         return false;
1692     return true;
1693
1694 error: /* clean up */
1695     ir_value_delete(v);
1696     return false;
1697 }
1698
1699 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1700 {
1701     size_t i;
1702     bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1703     if (!self->setter || !self->getter)
1704         return true;
1705     for (i = 0; i < self->expression.count; ++i) {
1706         if (!self->ir_values) {
1707             compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1708             return false;
1709         }
1710         if (!self->ir_values[i]) {
1711             compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1712             return false;
1713         }
1714         if (self->ir_values[i]->life) {
1715             compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1716             return false;
1717         }
1718     }
1719
1720     opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1721     if (self->setter) {
1722         if (!ast_global_codegen  (self->setter, ir, false) ||
1723             !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1724             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1725         {
1726             compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1727             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1728             return false;
1729         }
1730     }
1731     if (self->getter) {
1732         if (!ast_global_codegen  (self->getter, ir, false) ||
1733             !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1734             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1735         {
1736             compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1737             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1738             return false;
1739         }
1740     }
1741     for (i = 0; i < self->expression.count; ++i) {
1742         vec_free(self->ir_values[i]->life);
1743     }
1744     opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1745     return true;
1746 }
1747
1748 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1749 {
1750     ir_function *irf;
1751     ir_value    *dummy;
1752     ast_expression         *ec;
1753     ast_expression_codegen *cgen;
1754     size_t    i;
1755
1756     (void)ir;
1757
1758     irf = self->ir_func;
1759     if (!irf) {
1760         compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1761         return false;
1762     }
1763
1764     /* fill the parameter list */
1765     ec = &self->vtype->expression;
1766     for (i = 0; i < vec_size(ec->params); ++i)
1767     {
1768         if (ec->params[i]->expression.vtype == TYPE_FIELD)
1769             vec_push(irf->params, ec->params[i]->expression.next->vtype);
1770         else
1771             vec_push(irf->params, ec->params[i]->expression.vtype);
1772         if (!self->builtin) {
1773             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1774                 return false;
1775         }
1776     }
1777
1778     if (self->varargs) {
1779         if (!ast_local_codegen(self->varargs, self->ir_func, true))
1780             return false;
1781         irf->max_varargs = self->varargs->expression.count;
1782     }
1783
1784     if (self->builtin) {
1785         irf->builtin = self->builtin;
1786         return true;
1787     }
1788
1789     /* have a local return value variable? */
1790     if (self->return_value) {
1791         if (!ast_local_codegen(self->return_value, self->ir_func, false))
1792             return false;
1793     }
1794
1795     if (!vec_size(self->blocks)) {
1796         compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1797         return false;
1798     }
1799
1800     irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1801     if (!self->curblock) {
1802         compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1803         return false;
1804     }
1805
1806     if (self->argc) {
1807         ir_value *va_count;
1808         ir_value *fixed;
1809         ir_value *sub;
1810         if (!ast_local_codegen(self->argc, self->ir_func, true))
1811             return false;
1812         cgen = self->argc->expression.codegen;
1813         if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1814             return false;
1815         cgen = self->fixedparams->expression.codegen;
1816         if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1817             return false;
1818         sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1819                                     ast_function_label(self, "va_count"), INSTR_SUB_F,
1820                                     ir_builder_get_va_count(ir), fixed);
1821         if (!sub)
1822             return false;
1823         if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1824                                       va_count, sub))
1825         {
1826             return false;
1827         }
1828     }
1829
1830     for (i = 0; i < vec_size(self->blocks); ++i) {
1831         cgen = self->blocks[i]->expression.codegen;
1832         if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1833             return false;
1834     }
1835
1836     /* TODO: check return types */
1837     if (!self->curblock->final)
1838     {
1839         if (!self->vtype->expression.next ||
1840             self->vtype->expression.next->vtype == TYPE_VOID)
1841         {
1842             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1843         }
1844         else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1845         {
1846             if (self->return_value) {
1847                 cgen = self->return_value->expression.codegen;
1848                 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1849                     return false;
1850                 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1851             }
1852             else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1853                                 "control reaches end of non-void function (`%s`) via %s",
1854                                 self->name, self->curblock->label))
1855             {
1856                 return false;
1857             }
1858             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1859         }
1860     }
1861     return true;
1862 }
1863
1864 /* Note, you will not see ast_block_codegen generate ir_blocks.
1865  * To the AST and the IR, blocks are 2 different things.
1866  * In the AST it represents a block of code, usually enclosed in
1867  * curly braces {...}.
1868  * While in the IR it represents a block in terms of control-flow.
1869  */
1870 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1871 {
1872     size_t i;
1873
1874     /* We don't use this
1875      * Note: an ast-representation using the comma-operator
1876      * of the form: (a, b, c) = x should not assign to c...
1877      */
1878     if (lvalue) {
1879         compile_error(ast_ctx(self), "not an l-value (code-block)");
1880         return false;
1881     }
1882
1883     if (self->expression.outr) {
1884         *out = self->expression.outr;
1885         return true;
1886     }
1887
1888     /* output is NULL at first, we'll have each expression
1889      * assign to out output, thus, a comma-operator represention
1890      * using an ast_block will return the last generated value,
1891      * so: (b, c) + a  executed both b and c, and returns c,
1892      * which is then added to a.
1893      */
1894     *out = NULL;
1895
1896     /* generate locals */
1897     for (i = 0; i < vec_size(self->locals); ++i)
1898     {
1899         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1900             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1901                 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1902             return false;
1903         }
1904     }
1905
1906     for (i = 0; i < vec_size(self->exprs); ++i)
1907     {
1908         ast_expression_codegen *gen;
1909         if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1910             if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1911                 return false;
1912             continue;
1913         }
1914         gen = self->exprs[i]->codegen;
1915         if (!(*gen)(self->exprs[i], func, false, out))
1916             return false;
1917     }
1918
1919     self->expression.outr = *out;
1920
1921     return true;
1922 }
1923
1924 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1925 {
1926     ast_expression_codegen *cgen;
1927     ir_value *left  = NULL;
1928     ir_value *right = NULL;
1929
1930     ast_value       *arr;
1931     ast_value       *idx = 0;
1932     ast_array_index *ai = NULL;
1933
1934     if (lvalue && self->expression.outl) {
1935         *out = self->expression.outl;
1936         return true;
1937     }
1938
1939     if (!lvalue && self->expression.outr) {
1940         *out = self->expression.outr;
1941         return true;
1942     }
1943
1944     if (ast_istype(self->dest, ast_array_index))
1945     {
1946
1947         ai = (ast_array_index*)self->dest;
1948         idx = (ast_value*)ai->index;
1949
1950         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1951             ai = NULL;
1952     }
1953
1954     if (ai) {
1955         /* we need to call the setter */
1956         ir_value  *iridx, *funval;
1957         ir_instr  *call;
1958
1959         if (lvalue) {
1960             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1961             return false;
1962         }
1963
1964         arr = (ast_value*)ai->array;
1965         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1966             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1967             return false;
1968         }
1969
1970         cgen = idx->expression.codegen;
1971         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1972             return false;
1973
1974         cgen = arr->setter->expression.codegen;
1975         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1976             return false;
1977
1978         cgen = self->source->codegen;
1979         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1980             return false;
1981
1982         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1983         if (!call)
1984             return false;
1985         ir_call_param(call, iridx);
1986         ir_call_param(call, right);
1987         self->expression.outr = right;
1988     }
1989     else
1990     {
1991         /* regular code */
1992
1993         cgen = self->dest->codegen;
1994         /* lvalue! */
1995         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1996             return false;
1997         self->expression.outl = left;
1998
1999         cgen = self->source->codegen;
2000         /* rvalue! */
2001         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2002             return false;
2003
2004         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2005             return false;
2006         self->expression.outr = right;
2007     }
2008
2009     /* Theoretically, an assinment returns its left side as an
2010      * lvalue, if we don't need an lvalue though, we return
2011      * the right side as an rvalue, otherwise we have to
2012      * somehow know whether or not we need to dereference the pointer
2013      * on the left side - that is: OP_LOAD if it was an address.
2014      * Also: in original QC we cannot OP_LOADP *anyway*.
2015      */
2016     *out = (lvalue ? left : right);
2017
2018     return true;
2019 }
2020
2021 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2022 {
2023     ast_expression_codegen *cgen;
2024     ir_value *left, *right;
2025
2026     /* A binary operation cannot yield an l-value */
2027     if (lvalue) {
2028         compile_error(ast_ctx(self), "not an l-value (binop)");
2029         return false;
2030     }
2031
2032     if (self->expression.outr) {
2033         *out = self->expression.outr;
2034         return true;
2035     }
2036
2037     if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2038         (self->op == INSTR_AND || self->op == INSTR_OR))
2039     {
2040         /* short circuit evaluation */
2041         ir_block *other, *merge;
2042         ir_block *from_left, *from_right;
2043         ir_instr *phi;
2044         size_t    merge_id;
2045
2046         /* prepare end-block */
2047         merge_id = vec_size(func->ir_func->blocks);
2048         merge    = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2049
2050         /* generate the left expression */
2051         cgen = self->left->codegen;
2052         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2053             return false;
2054         /* remember the block */
2055         from_left = func->curblock;
2056
2057         /* create a new block for the right expression */
2058         other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2059         if (self->op == INSTR_AND) {
2060             /* on AND: left==true -> other */
2061             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2062                 return false;
2063         } else {
2064             /* on OR: left==false -> other */
2065             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2066                 return false;
2067         }
2068         /* use the likely flag */
2069         vec_last(func->curblock->instr)->likely = true;
2070
2071         /* enter the right-expression's block */
2072         func->curblock = other;
2073         /* generate */
2074         cgen = self->right->codegen;
2075         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2076             return false;
2077         /* remember block */
2078         from_right = func->curblock;
2079
2080         /* jump to the merge block */
2081         if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2082             return false;
2083
2084         vec_remove(func->ir_func->blocks, merge_id, 1);
2085         vec_push(func->ir_func->blocks, merge);
2086
2087         func->curblock = merge;
2088         phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2089                                   ast_function_label(func, "sce_value"),
2090                                   self->expression.vtype);
2091         ir_phi_add(phi, from_left, left);
2092         ir_phi_add(phi, from_right, right);
2093         *out = ir_phi_value(phi);
2094         if (!*out)
2095             return false;
2096
2097         if (!OPTS_FLAG(PERL_LOGIC)) {
2098             /* cast-to-bool */
2099             if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2100                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2101                                              ast_function_label(func, "sce_bool_v"),
2102                                              INSTR_NOT_V, *out);
2103                 if (!*out)
2104                     return false;
2105                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2106                                              ast_function_label(func, "sce_bool"),
2107                                              INSTR_NOT_F, *out);
2108                 if (!*out)
2109                     return false;
2110             }
2111             else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2112                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2113                                              ast_function_label(func, "sce_bool_s"),
2114                                              INSTR_NOT_S, *out);
2115                 if (!*out)
2116                     return false;
2117                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2118                                              ast_function_label(func, "sce_bool"),
2119                                              INSTR_NOT_F, *out);
2120                 if (!*out)
2121                     return false;
2122             }
2123             else {
2124                 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2125                                              ast_function_label(func, "sce_bool"),
2126                                              INSTR_AND, *out, *out);
2127                 if (!*out)
2128                     return false;
2129             }
2130         }
2131
2132         self->expression.outr = *out;
2133         codegen_output_type(self, *out);
2134         return true;
2135     }
2136
2137     cgen = self->left->codegen;
2138     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2139         return false;
2140
2141     cgen = self->right->codegen;
2142     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2143         return false;
2144
2145     *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2146                                  self->op, left, right);
2147     if (!*out)
2148         return false;
2149     self->expression.outr = *out;
2150     codegen_output_type(self, *out);
2151
2152     return true;
2153 }
2154
2155 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2156 {
2157     ast_expression_codegen *cgen;
2158     ir_value *leftl = NULL, *leftr, *right, *bin;
2159
2160     ast_value       *arr;
2161     ast_value       *idx = 0;
2162     ast_array_index *ai = NULL;
2163     ir_value        *iridx = NULL;
2164
2165     if (lvalue && self->expression.outl) {
2166         *out = self->expression.outl;
2167         return true;
2168     }
2169
2170     if (!lvalue && self->expression.outr) {
2171         *out = self->expression.outr;
2172         return true;
2173     }
2174
2175     if (ast_istype(self->dest, ast_array_index))
2176     {
2177
2178         ai = (ast_array_index*)self->dest;
2179         idx = (ast_value*)ai->index;
2180
2181         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2182             ai = NULL;
2183     }
2184
2185     /* for a binstore we need both an lvalue and an rvalue for the left side */
2186     /* rvalue of destination! */
2187     if (ai) {
2188         cgen = idx->expression.codegen;
2189         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2190             return false;
2191     }
2192     cgen = self->dest->codegen;
2193     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2194         return false;
2195
2196     /* source as rvalue only */
2197     cgen = self->source->codegen;
2198     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2199         return false;
2200
2201     /* now the binary */
2202     bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2203                                 self->opbin, leftr, right);
2204     self->expression.outr = bin;
2205
2206
2207     if (ai) {
2208         /* we need to call the setter */
2209         ir_value  *funval;
2210         ir_instr  *call;
2211
2212         if (lvalue) {
2213             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2214             return false;
2215         }
2216
2217         arr = (ast_value*)ai->array;
2218         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2219             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2220             return false;
2221         }
2222
2223         cgen = arr->setter->expression.codegen;
2224         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2225             return false;
2226
2227         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2228         if (!call)
2229             return false;
2230         ir_call_param(call, iridx);
2231         ir_call_param(call, bin);
2232         self->expression.outr = bin;
2233     } else {
2234         /* now store them */
2235         cgen = self->dest->codegen;
2236         /* lvalue of destination */
2237         if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2238             return false;
2239         self->expression.outl = leftl;
2240
2241         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2242             return false;
2243         self->expression.outr = bin;
2244     }
2245
2246     /* Theoretically, an assinment returns its left side as an
2247      * lvalue, if we don't need an lvalue though, we return
2248      * the right side as an rvalue, otherwise we have to
2249      * somehow know whether or not we need to dereference the pointer
2250      * on the left side - that is: OP_LOAD if it was an address.
2251      * Also: in original QC we cannot OP_LOADP *anyway*.
2252      */
2253     *out = (lvalue ? leftl : bin);
2254
2255     return true;
2256 }
2257
2258 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2259 {
2260     ast_expression_codegen *cgen;
2261     ir_value *operand;
2262
2263     /* An unary operation cannot yield an l-value */
2264     if (lvalue) {
2265         compile_error(ast_ctx(self), "not an l-value (binop)");
2266         return false;
2267     }
2268
2269     if (self->expression.outr) {
2270         *out = self->expression.outr;
2271         return true;
2272     }
2273
2274     cgen = self->operand->codegen;
2275     /* lvalue! */
2276     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2277         return false;
2278
2279     *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2280                                  self->op, operand);
2281     if (!*out)
2282         return false;
2283     self->expression.outr = *out;
2284
2285     return true;
2286 }
2287
2288 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2289 {
2290     ast_expression_codegen *cgen;
2291     ir_value *operand;
2292
2293     *out = NULL;
2294
2295     /* In the context of a return operation, we don't actually return
2296      * anything...
2297      */
2298     if (lvalue) {
2299         compile_error(ast_ctx(self), "return-expression is not an l-value");
2300         return false;
2301     }
2302
2303     if (self->expression.outr) {
2304         compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2305         return false;
2306     }
2307     self->expression.outr = (ir_value*)1;
2308
2309     if (self->operand) {
2310         cgen = self->operand->codegen;
2311         /* lvalue! */
2312         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2313             return false;
2314
2315         if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2316             return false;
2317     } else {
2318         if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2319             return false;
2320     }
2321
2322     return true;
2323 }
2324
2325 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2326 {
2327     ast_expression_codegen *cgen;
2328     ir_value *ent, *field;
2329
2330     /* This function needs to take the 'lvalue' flag into account!
2331      * As lvalue we provide a field-pointer, as rvalue we provide the
2332      * value in a temp.
2333      */
2334
2335     if (lvalue && self->expression.outl) {
2336         *out = self->expression.outl;
2337         return true;
2338     }
2339
2340     if (!lvalue && self->expression.outr) {
2341         *out = self->expression.outr;
2342         return true;
2343     }
2344
2345     cgen = self->entity->codegen;
2346     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2347         return false;
2348
2349     cgen = self->field->codegen;
2350     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2351         return false;
2352
2353     if (lvalue) {
2354         /* address! */
2355         *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2356                                             ent, field);
2357     } else {
2358         *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2359                                              ent, field, self->expression.vtype);
2360         /* Done AFTER error checking:
2361         codegen_output_type(self, *out);
2362         */
2363     }
2364     if (!*out) {
2365         compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2366                  (lvalue ? "ADDRESS" : "FIELD"),
2367                  type_name[self->expression.vtype]);
2368         return false;
2369     }
2370     if (!lvalue)
2371         codegen_output_type(self, *out);
2372
2373     if (lvalue)
2374         self->expression.outl = *out;
2375     else
2376         self->expression.outr = *out;
2377
2378     /* Hm that should be it... */
2379     return true;
2380 }
2381
2382 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2383 {
2384     ast_expression_codegen *cgen;
2385     ir_value *vec;
2386
2387     /* in QC this is always an lvalue */
2388     if (lvalue && self->rvalue) {
2389         compile_error(ast_ctx(self), "not an l-value (member access)");
2390         return false;
2391     }
2392     if (self->expression.outl) {
2393         *out = self->expression.outl;
2394         return true;
2395     }
2396
2397     cgen = self->owner->codegen;
2398     if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2399         return false;
2400
2401     if (vec->vtype != TYPE_VECTOR &&
2402         !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2403     {
2404         return false;
2405     }
2406
2407     *out = ir_value_vector_member(vec, self->field);
2408     self->expression.outl = *out;
2409
2410     return (*out != NULL);
2411 }
2412
2413 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2414 {
2415     ast_value *arr;
2416     ast_value *idx;
2417
2418     if (!lvalue && self->expression.outr) {
2419         *out = self->expression.outr;
2420         return true;
2421     }
2422     if (lvalue && self->expression.outl) {
2423         *out = self->expression.outl;
2424         return true;
2425     }
2426
2427     if (!ast_istype(self->array, ast_value)) {
2428         compile_error(ast_ctx(self), "array indexing this way is not supported");
2429         /* note this would actually be pointer indexing because the left side is
2430          * not an actual array but (hopefully) an indexable expression.
2431          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2432          * support this path will be filled.
2433          */
2434         return false;
2435     }
2436
2437     arr = (ast_value*)self->array;
2438     idx = (ast_value*)self->index;
2439
2440     if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2441         /* Time to use accessor functions */
2442         ast_expression_codegen *cgen;
2443         ir_value               *iridx, *funval;
2444         ir_instr               *call;
2445
2446         if (lvalue) {
2447             compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2448             return false;
2449         }
2450
2451         if (!arr->getter) {
2452             compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2453             return false;
2454         }
2455
2456         cgen = self->index->codegen;
2457         if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2458             return false;
2459
2460         cgen = arr->getter->expression.codegen;
2461         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2462             return false;
2463
2464         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2465         if (!call)
2466             return false;
2467         ir_call_param(call, iridx);
2468
2469         *out = ir_call_value(call);
2470         self->expression.outr = *out;
2471         (*out)->vtype = self->expression.vtype;
2472         codegen_output_type(self, *out);
2473         return true;
2474     }
2475
2476     if (idx->expression.vtype == TYPE_FLOAT) {
2477         unsigned int arridx = idx->constval.vfloat;
2478         if (arridx >= self->array->count)
2479         {
2480             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2481             return false;
2482         }
2483         *out = arr->ir_values[arridx];
2484     }
2485     else if (idx->expression.vtype == TYPE_INTEGER) {
2486         unsigned int arridx = idx->constval.vint;
2487         if (arridx >= self->array->count)
2488         {
2489             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2490             return false;
2491         }
2492         *out = arr->ir_values[arridx];
2493     }
2494     else {
2495         compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2496         return false;
2497     }
2498     (*out)->vtype = self->expression.vtype;
2499     codegen_output_type(self, *out);
2500     return true;
2501 }
2502
2503 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2504 {
2505     *out = NULL;
2506     if (lvalue) {
2507         compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2508         return false;
2509     }
2510     (void)func;
2511     (void)out;
2512     compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2513     return false;
2514 }
2515
2516 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2517 {
2518     ast_expression_codegen *cgen;
2519
2520     ir_value *condval;
2521     ir_value *dummy;
2522
2523     ir_block *cond;
2524     ir_block *ontrue;
2525     ir_block *onfalse;
2526     ir_block *ontrue_endblock = NULL;
2527     ir_block *onfalse_endblock = NULL;
2528     ir_block *merge = NULL;
2529     int       fold  = 0;
2530
2531     /* We don't output any value, thus also don't care about r/lvalue */
2532     (void)out;
2533     (void)lvalue;
2534
2535     if (self->expression.outr) {
2536         compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2537         return false;
2538     }
2539     self->expression.outr = (ir_value*)1;
2540
2541     /* generate the condition */
2542     cgen = self->cond->codegen;
2543     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2544         return false;
2545     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2546     cond = func->curblock;
2547
2548     /* try constant folding away the if */
2549     if ((fold = fold_cond(condval, func, self)) != -1)
2550         return fold;
2551
2552     if (self->on_true) {
2553         /* create on-true block */
2554         ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2555         if (!ontrue)
2556             return false;
2557
2558         /* enter the block */
2559         func->curblock = ontrue;
2560
2561         /* generate */
2562         cgen = self->on_true->codegen;
2563         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2564             return false;
2565
2566         /* we now need to work from the current endpoint */
2567         ontrue_endblock = func->curblock;
2568     } else
2569         ontrue = NULL;
2570
2571     /* on-false path */
2572     if (self->on_false) {
2573         /* create on-false block */
2574         onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2575         if (!onfalse)
2576             return false;
2577
2578         /* enter the block */
2579         func->curblock = onfalse;
2580
2581         /* generate */
2582         cgen = self->on_false->codegen;
2583         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2584             return false;
2585
2586         /* we now need to work from the current endpoint */
2587         onfalse_endblock = func->curblock;
2588     } else
2589         onfalse = NULL;
2590
2591     /* Merge block were they all merge in to */
2592     if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2593     {
2594         merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2595         if (!merge)
2596             return false;
2597         /* add jumps ot the merge block */
2598         if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2599             return false;
2600         if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2601             return false;
2602
2603         /* Now enter the merge block */
2604         func->curblock = merge;
2605     }
2606
2607     /* we create the if here, that way all blocks are ordered :)
2608      */
2609     if (!ir_block_create_if(cond, ast_ctx(self), condval,
2610                             (ontrue  ? ontrue  : merge),
2611                             (onfalse ? onfalse : merge)))
2612     {
2613         return false;
2614     }
2615
2616     return true;
2617 }
2618
2619 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2620 {
2621     ast_expression_codegen *cgen;
2622
2623     ir_value *condval;
2624     ir_value *trueval, *falseval;
2625     ir_instr *phi;
2626
2627     ir_block *cond = func->curblock;
2628     ir_block *cond_out = NULL;
2629     ir_block *ontrue, *ontrue_out = NULL;
2630     ir_block *onfalse, *onfalse_out = NULL;
2631     ir_block *merge;
2632
2633     /* Ternary can never create an lvalue... */
2634     if (lvalue)
2635         return false;
2636
2637     /* In theory it shouldn't be possible to pass through a node twice, but
2638      * in case we add any kind of optimization pass for the AST itself, it
2639      * may still happen, thus we remember a created ir_value and simply return one
2640      * if it already exists.
2641      */
2642     if (self->expression.outr) {
2643         *out = self->expression.outr;
2644         return true;
2645     }
2646
2647     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2648
2649     /* generate the condition */
2650     func->curblock = cond;
2651     cgen = self->cond->codegen;
2652     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2653         return false;
2654     cond_out = func->curblock;
2655
2656     /* create on-true block */
2657     ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2658     if (!ontrue)
2659         return false;
2660     else
2661     {
2662         /* enter the block */
2663         func->curblock = ontrue;
2664
2665         /* generate */
2666         cgen = self->on_true->codegen;
2667         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2668             return false;
2669
2670         ontrue_out = func->curblock;
2671     }
2672
2673     /* create on-false block */
2674     onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2675     if (!onfalse)
2676         return false;
2677     else
2678     {
2679         /* enter the block */
2680         func->curblock = onfalse;
2681
2682         /* generate */
2683         cgen = self->on_false->codegen;
2684         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2685             return false;
2686
2687         onfalse_out = func->curblock;
2688     }
2689
2690     /* create merge block */
2691     merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2692     if (!merge)
2693         return false;
2694     /* jump to merge block */
2695     if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2696         return false;
2697     if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2698         return false;
2699
2700     /* create if instruction */
2701     if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2702         return false;
2703
2704     /* Now enter the merge block */
2705     func->curblock = merge;
2706
2707     /* Here, now, we need a PHI node
2708      * but first some sanity checking...
2709      */
2710     if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2711         /* error("ternary with different types on the two sides"); */
2712         compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2713         return false;
2714     }
2715
2716     /* create PHI */
2717     phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2718     if (!phi) {
2719         compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2720         return false;
2721     }
2722     ir_phi_add(phi, ontrue_out,  trueval);
2723     ir_phi_add(phi, onfalse_out, falseval);
2724
2725     self->expression.outr = ir_phi_value(phi);
2726     *out = self->expression.outr;
2727
2728     codegen_output_type(self, *out);
2729
2730     return true;
2731 }
2732
2733 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2734 {
2735     ast_expression_codegen *cgen;
2736
2737     ir_value *dummy      = NULL;
2738     ir_value *precond    = NULL;
2739     ir_value *postcond   = NULL;
2740
2741     /* Since we insert some jumps "late" so we have blocks
2742      * ordered "nicely", we need to keep track of the actual end-blocks
2743      * of expressions to add the jumps to.
2744      */
2745     ir_block *bbody      = NULL, *end_bbody      = NULL;
2746     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2747     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2748     ir_block *bincrement = NULL, *end_bincrement = NULL;
2749     ir_block *bout       = NULL, *bin            = NULL;
2750
2751     /* let's at least move the outgoing block to the end */
2752     size_t    bout_id;
2753
2754     /* 'break' and 'continue' need to be able to find the right blocks */
2755     ir_block *bcontinue     = NULL;
2756     ir_block *bbreak        = NULL;
2757
2758     ir_block *tmpblock      = NULL;
2759
2760     (void)lvalue;
2761     (void)out;
2762
2763     if (self->expression.outr) {
2764         compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2765         return false;
2766     }
2767     self->expression.outr = (ir_value*)1;
2768
2769     /* NOTE:
2770      * Should we ever need some kind of block ordering, better make this function
2771      * move blocks around than write a block ordering algorithm later... after all
2772      * the ast and ir should work together, not against each other.
2773      */
2774
2775     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2776      * anyway if for example it contains a ternary.
2777      */
2778     if (self->initexpr)
2779     {
2780         cgen = self->initexpr->codegen;
2781         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2782             return false;
2783     }
2784
2785     /* Store the block from which we enter this chaos */
2786     bin = func->curblock;
2787
2788     /* The pre-loop condition needs its own block since we
2789      * need to be able to jump to the start of that expression.
2790      */
2791     if (self->precond)
2792     {
2793         bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2794         if (!bprecond)
2795             return false;
2796
2797         /* the pre-loop-condition the least important place to 'continue' at */
2798         bcontinue = bprecond;
2799
2800         /* enter */
2801         func->curblock = bprecond;
2802
2803         /* generate */
2804         cgen = self->precond->codegen;
2805         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2806             return false;
2807
2808         end_bprecond = func->curblock;
2809     } else {
2810         bprecond = end_bprecond = NULL;
2811     }
2812
2813     /* Now the next blocks won't be ordered nicely, but we need to
2814      * generate them this early for 'break' and 'continue'.
2815      */
2816     if (self->increment) {
2817         bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2818         if (!bincrement)
2819             return false;
2820         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2821     } else {
2822         bincrement = end_bincrement = NULL;
2823     }
2824
2825     if (self->postcond) {
2826         bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2827         if (!bpostcond)
2828             return false;
2829         bcontinue = bpostcond; /* postcond comes before the increment */
2830     } else {
2831         bpostcond = end_bpostcond = NULL;
2832     }
2833
2834     bout_id = vec_size(func->ir_func->blocks);
2835     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2836     if (!bout)
2837         return false;
2838     bbreak = bout;
2839
2840     /* The loop body... */
2841     /* if (self->body) */
2842     {
2843         bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2844         if (!bbody)
2845             return false;
2846
2847         /* enter */
2848         func->curblock = bbody;
2849
2850         vec_push(func->breakblocks,    bbreak);
2851         if (bcontinue)
2852             vec_push(func->continueblocks, bcontinue);
2853         else
2854             vec_push(func->continueblocks, bbody);
2855
2856         /* generate */
2857         if (self->body) {
2858             cgen = self->body->codegen;
2859             if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2860                 return false;
2861         }
2862
2863         end_bbody = func->curblock;
2864         vec_pop(func->breakblocks);
2865         vec_pop(func->continueblocks);
2866     }
2867
2868     /* post-loop-condition */
2869     if (self->postcond)
2870     {
2871         /* enter */
2872         func->curblock = bpostcond;
2873
2874         /* generate */
2875         cgen = self->postcond->codegen;
2876         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2877             return false;
2878
2879         end_bpostcond = func->curblock;
2880     }
2881
2882     /* The incrementor */
2883     if (self->increment)
2884     {
2885         /* enter */
2886         func->curblock = bincrement;
2887
2888         /* generate */
2889         cgen = self->increment->codegen;
2890         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2891             return false;
2892
2893         end_bincrement = func->curblock;
2894     }
2895
2896     /* In any case now, we continue from the outgoing block */
2897     func->curblock = bout;
2898
2899     /* Now all blocks are in place */
2900     /* From 'bin' we jump to whatever comes first */
2901     if      (bprecond)   tmpblock = bprecond;
2902     else                 tmpblock = bbody;    /* can never be null */
2903
2904     /* DEAD CODE
2905     else if (bpostcond)  tmpblock = bpostcond;
2906     else                 tmpblock = bout;
2907     */
2908
2909     if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2910         return false;
2911
2912     /* From precond */
2913     if (bprecond)
2914     {
2915         ir_block *ontrue, *onfalse;
2916         ontrue = bbody; /* can never be null */
2917
2918         /* all of this is dead code
2919         else if (bincrement) ontrue = bincrement;
2920         else                 ontrue = bpostcond;
2921         */
2922
2923         onfalse = bout;
2924         if (self->pre_not) {
2925             tmpblock = ontrue;
2926             ontrue   = onfalse;
2927             onfalse  = tmpblock;
2928         }
2929         if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2930             return false;
2931     }
2932
2933     /* from body */
2934     if (bbody)
2935     {
2936         if      (bincrement) tmpblock = bincrement;
2937         else if (bpostcond)  tmpblock = bpostcond;
2938         else if (bprecond)   tmpblock = bprecond;
2939         else                 tmpblock = bbody;
2940         if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2941             return false;
2942     }
2943
2944     /* from increment */
2945     if (bincrement)
2946     {
2947         if      (bpostcond)  tmpblock = bpostcond;
2948         else if (bprecond)   tmpblock = bprecond;
2949         else if (bbody)      tmpblock = bbody;
2950         else                 tmpblock = bout;
2951         if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2952             return false;
2953     }
2954
2955     /* from postcond */
2956     if (bpostcond)
2957     {
2958         ir_block *ontrue, *onfalse;
2959         if      (bprecond)   ontrue = bprecond;
2960         else                 ontrue = bbody; /* can never be null */
2961
2962         /* all of this is dead code
2963         else if (bincrement) ontrue = bincrement;
2964         else                 ontrue = bpostcond;
2965         */
2966
2967         onfalse = bout;
2968         if (self->post_not) {
2969             tmpblock = ontrue;
2970             ontrue   = onfalse;
2971             onfalse  = tmpblock;
2972         }
2973         if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2974             return false;
2975     }
2976
2977     /* Move 'bout' to the end */
2978     vec_remove(func->ir_func->blocks, bout_id, 1);
2979     vec_push(func->ir_func->blocks, bout);
2980
2981     return true;
2982 }
2983
2984 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2985 {
2986     ir_block *target;
2987
2988     *out = NULL;
2989
2990     if (lvalue) {
2991         compile_error(ast_ctx(self), "break/continue expression is not an l-value");
2992         return false;
2993     }
2994
2995     if (self->expression.outr) {
2996         compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2997         return false;
2998     }
2999     self->expression.outr = (ir_value*)1;
3000
3001     if (self->is_continue)
3002         target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3003     else
3004         target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3005
3006     if (!target) {
3007         compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3008         return false;
3009     }
3010
3011     if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3012         return false;
3013     return true;
3014 }
3015
3016 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3017 {
3018     ast_expression_codegen *cgen;
3019
3020     ast_switch_case *def_case     = NULL;
3021     ir_block        *def_bfall    = NULL;
3022     ir_block        *def_bfall_to = NULL;
3023     bool set_def_bfall_to = false;
3024
3025     ir_value *dummy     = NULL;
3026     ir_value *irop      = NULL;
3027     ir_block *bout      = NULL;
3028     ir_block *bfall     = NULL;
3029     size_t    bout_id;
3030     size_t    c;
3031
3032     char      typestr[1024];
3033     uint16_t  cmpinstr;
3034
3035     if (lvalue) {
3036         compile_error(ast_ctx(self), "switch expression is not an l-value");
3037         return false;
3038     }
3039
3040     if (self->expression.outr) {
3041         compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3042         return false;
3043     }
3044     self->expression.outr = (ir_value*)1;
3045
3046     (void)lvalue;
3047     (void)out;
3048
3049     cgen = self->operand->codegen;
3050     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3051         return false;
3052
3053     if (!vec_size(self->cases))
3054         return true;
3055
3056     cmpinstr = type_eq_instr[irop->vtype];
3057     if (cmpinstr >= VINSTR_END) {
3058         ast_type_to_string(self->operand, typestr, sizeof(typestr));
3059         compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3060         return false;
3061     }
3062
3063     bout_id = vec_size(func->ir_func->blocks);
3064     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3065     if (!bout)
3066         return false;
3067
3068     /* setup the break block */
3069     vec_push(func->breakblocks, bout);
3070
3071     /* Now create all cases */
3072     for (c = 0; c < vec_size(self->cases); ++c) {
3073         ir_value *cond, *val;
3074         ir_block *bcase, *bnot;
3075         size_t bnot_id;
3076
3077         ast_switch_case *swcase = &self->cases[c];
3078
3079         if (swcase->value) {
3080             /* A regular case */
3081             /* generate the condition operand */
3082             cgen = swcase->value->codegen;
3083             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3084                 return false;
3085             /* generate the condition */
3086             cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3087             if (!cond)
3088                 return false;
3089
3090             bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3091             bnot_id = vec_size(func->ir_func->blocks);
3092             bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3093             if (!bcase || !bnot)
3094                 return false;
3095             if (set_def_bfall_to) {
3096                 set_def_bfall_to = false;
3097                 def_bfall_to = bcase;
3098             }
3099             if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3100                 return false;
3101
3102             /* Make the previous case-end fall through */
3103             if (bfall && !bfall->final) {
3104                 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3105                     return false;
3106             }
3107
3108             /* enter the case */
3109             func->curblock = bcase;
3110             cgen = swcase->code->codegen;
3111             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3112                 return false;
3113
3114             /* remember this block to fall through from */
3115             bfall = func->curblock;
3116
3117             /* enter the else and move it down */
3118             func->curblock = bnot;
3119             vec_remove(func->ir_func->blocks, bnot_id, 1);
3120             vec_push(func->ir_func->blocks, bnot);
3121         } else {
3122             /* The default case */
3123             /* Remember where to fall through from: */
3124             def_bfall = bfall;
3125             bfall     = NULL;
3126             /* remember which case it was */
3127             def_case  = swcase;
3128             /* And the next case will be remembered */
3129             set_def_bfall_to = true;
3130         }
3131     }
3132
3133     /* Jump from the last bnot to bout */
3134     if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3135         /*
3136         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3137         */
3138         return false;
3139     }
3140
3141     /* If there was a default case, put it down here */
3142     if (def_case) {
3143         ir_block *bcase;
3144
3145         /* No need to create an extra block */
3146         bcase = func->curblock;
3147
3148         /* Insert the fallthrough jump */
3149         if (def_bfall && !def_bfall->final) {
3150             if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3151                 return false;
3152         }
3153
3154         /* Now generate the default code */
3155         cgen = def_case->code->codegen;
3156         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3157             return false;
3158
3159         /* see if we need to fall through */
3160         if (def_bfall_to && !func->curblock->final)
3161         {
3162             if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3163                 return false;
3164         }
3165     }
3166
3167     /* Jump from the last bnot to bout */
3168     if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3169         return false;
3170     /* enter the outgoing block */
3171     func->curblock = bout;
3172
3173     /* restore the break block */
3174     vec_pop(func->breakblocks);
3175
3176     /* Move 'bout' to the end, it's nicer */
3177     vec_remove(func->ir_func->blocks, bout_id, 1);
3178     vec_push(func->ir_func->blocks, bout);
3179
3180     return true;
3181 }
3182
3183 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3184 {
3185     size_t i;
3186     ir_value *dummy;
3187
3188     if (self->undefined) {
3189         compile_error(ast_ctx(self), "internal error: ast_label never defined");
3190         return false;
3191     }
3192
3193     *out = NULL;
3194     if (lvalue) {
3195         compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3196         return false;
3197     }
3198
3199     /* simply create a new block and jump to it */
3200     self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3201     if (!self->irblock) {
3202         compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3203         return false;
3204     }
3205     if (!func->curblock->final) {
3206         if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3207             return false;
3208     }
3209
3210     /* enter the new block */
3211     func->curblock = self->irblock;
3212
3213     /* Generate all the leftover gotos */
3214     for (i = 0; i < vec_size(self->gotos); ++i) {
3215         if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3216             return false;
3217     }
3218
3219     return true;
3220 }
3221
3222 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3223 {
3224     *out = NULL;
3225     if (lvalue) {
3226         compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3227         return false;
3228     }
3229
3230     if (self->target->irblock) {
3231         if (self->irblock_from) {
3232             /* we already tried once, this is the callback */
3233             self->irblock_from->final = false;
3234             if (!ir_block_create_goto(self->irblock_from, 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         else
3240         {
3241             if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3242                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3243                 return false;
3244             }
3245         }
3246     }
3247     else
3248     {
3249         /* the target has not yet been created...
3250          * close this block in a sneaky way:
3251          */
3252         func->curblock->final = true;
3253         self->irblock_from = func->curblock;
3254         ast_label_register_goto(self->target, self);
3255     }
3256
3257     return true;
3258 }
3259
3260 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3261 {
3262     ast_expression_codegen *cgen;
3263     ir_value              **params;
3264     ir_instr               *callinstr;
3265     size_t i;
3266
3267     ir_value *funval = NULL;
3268
3269     /* return values are never lvalues */
3270     if (lvalue) {
3271         compile_error(ast_ctx(self), "not an l-value (function call)");
3272         return false;
3273     }
3274
3275     if (self->expression.outr) {
3276         *out = self->expression.outr;
3277         return true;
3278     }
3279
3280     cgen = self->func->codegen;
3281     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3282         return false;
3283     if (!funval)
3284         return false;
3285
3286     params = NULL;
3287
3288     /* parameters */
3289     for (i = 0; i < vec_size(self->params); ++i)
3290     {
3291         ir_value *param;
3292         ast_expression *expr = self->params[i];
3293
3294         cgen = expr->codegen;
3295         if (!(*cgen)(expr, func, false, &param))
3296             goto error;
3297         if (!param)
3298             goto error;
3299         vec_push(params, param);
3300     }
3301
3302     /* varargs counter */
3303     if (self->va_count) {
3304         ir_value   *va_count;
3305         ir_builder *builder = func->curblock->owner->owner;
3306         cgen = self->va_count->codegen;
3307         if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3308             return false;
3309         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3310                                       ir_builder_get_va_count(builder), va_count))
3311         {
3312             return false;
3313         }
3314     }
3315
3316     callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3317                                      ast_function_label(func, "call"),
3318                                      funval, !!(self->func->flags & AST_FLAG_NORETURN));
3319     if (!callinstr)
3320         goto error;
3321
3322     for (i = 0; i < vec_size(params); ++i) {
3323         ir_call_param(callinstr, params[i]);
3324     }
3325
3326     *out = ir_call_value(callinstr);
3327     self->expression.outr = *out;
3328
3329     codegen_output_type(self, *out);
3330
3331     vec_free(params);
3332     return true;
3333 error:
3334     vec_free(params);
3335     return false;
3336 }