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