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