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