]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
d6f231c45d7d77935988da8b16dd337dc17171d5
[xonotic/gmqcc.git] / ast.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "gmqcc.h"
28 #include "ast.h"
29
30 #define ast_instantiate(T, ctx, destroyfn)                          \
31     T* self = (T*)mem_a(sizeof(T));                                 \
32     if (!self) {                                                    \
33         return NULL;                                                \
34     }                                                               \
35     ast_node_init((ast_node*)self, ctx, TYPE_##T);                  \
36     ( (ast_node*)self )->node.destroy = (ast_node_delete*)destroyfn
37
38 /* error handling */
39 static void asterror(lex_ctx ctx, const char *msg, ...)
40 {
41     va_list ap;
42     va_start(ap, msg);
43     con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", msg, ap);
44     va_end(ap);
45 }
46
47 /* It must not be possible to get here. */
48 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
49 {
50     (void)self;
51     con_err("ast node missing destroy()\n");
52     abort();
53 }
54
55 /* Initialize main ast node aprts */
56 static void ast_node_init(ast_node *self, lex_ctx ctx, int nodetype)
57 {
58     self->node.context = ctx;
59     self->node.destroy = &_ast_node_destroy;
60     self->node.keep    = false;
61     self->node.nodetype = nodetype;
62 }
63
64 /* General expression initialization */
65 static void ast_expression_init(ast_expression *self,
66                                 ast_expression_codegen *codegen)
67 {
68     self->expression.codegen  = codegen;
69     self->expression.vtype    = TYPE_VOID;
70     self->expression.next     = NULL;
71     self->expression.outl     = NULL;
72     self->expression.outr     = NULL;
73     self->expression.variadic = false;
74     self->expression.params   = NULL;
75 }
76
77 static void ast_expression_delete(ast_expression *self)
78 {
79     size_t i;
80     if (self->expression.next)
81         ast_delete(self->expression.next);
82     for (i = 0; i < vec_size(self->expression.params); ++i) {
83         ast_delete(self->expression.params[i]);
84     }
85     vec_free(self->expression.params);
86 }
87
88 static void ast_expression_delete_full(ast_expression *self)
89 {
90     ast_expression_delete(self);
91     mem_d(self);
92 }
93
94 ast_value* ast_value_copy(const ast_value *self)
95 {
96     size_t i;
97     const ast_expression_common *fromex;
98     ast_expression_common *selfex;
99     ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
100     if (self->expression.next) {
101         cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
102         if (!cp->expression.next) {
103             ast_value_delete(cp);
104             return NULL;
105         }
106     }
107     fromex   = &self->expression;
108     selfex = &cp->expression;
109     selfex->variadic = fromex->variadic;
110     for (i = 0; i < vec_size(fromex->params); ++i) {
111         ast_value *v = ast_value_copy(fromex->params[i]);
112         if (!v) {
113             ast_value_delete(cp);
114             return NULL;
115         }
116         vec_push(selfex->params, v);
117     }
118     return cp;
119 }
120
121 bool ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
122 {
123     size_t i;
124     const ast_expression_common *fromex;
125     ast_expression_common *selfex;
126     self->expression.vtype = other->expression.vtype;
127     if (other->expression.next) {
128         self->expression.next = (ast_expression*)ast_type_copy(ast_ctx(self), other->expression.next);
129         if (!self->expression.next)
130             return false;
131     }
132     fromex   = &other->expression;
133     selfex = &self->expression;
134     selfex->variadic = fromex->variadic;
135     for (i = 0; i < vec_size(fromex->params); ++i) {
136         ast_value *v = ast_value_copy(fromex->params[i]);
137         if (!v)
138             return false;
139         vec_push(selfex->params, v);
140     }
141     return true;
142 }
143
144 static ast_expression* ast_shallow_type(lex_ctx ctx, int vtype)
145 {
146     ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
147     ast_expression_init(self, NULL);
148     self->expression.codegen = NULL;
149     self->expression.next    = NULL;
150     self->expression.vtype   = vtype;
151     return self;
152 }
153
154 ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
155 {
156     size_t i;
157     const ast_expression_common *fromex;
158     ast_expression_common *selfex;
159
160     if (!ex)
161         return NULL;
162     else
163     {
164         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
165         ast_expression_init(self, NULL);
166
167         fromex   = &ex->expression;
168         selfex = &self->expression;
169
170         /* This may never be codegen()d */
171         selfex->codegen = NULL;
172
173         selfex->vtype = fromex->vtype;
174         if (fromex->next)
175         {
176             selfex->next = ast_type_copy(ctx, fromex->next);
177             if (!selfex->next) {
178                 ast_expression_delete_full(self);
179                 return NULL;
180             }
181         }
182         else
183             selfex->next = NULL;
184
185         selfex->variadic = fromex->variadic;
186         for (i = 0; i < vec_size(fromex->params); ++i) {
187             ast_value *v = ast_value_copy(fromex->params[i]);
188             if (!v) {
189                 ast_expression_delete_full(self);
190                 return NULL;
191             }
192             vec_push(selfex->params, v);
193         }
194
195         return self;
196     }
197 }
198
199 bool ast_compare_type(ast_expression *a, ast_expression *b)
200 {
201     if (a->expression.vtype != b->expression.vtype)
202         return false;
203     if (!a->expression.next != !b->expression.next)
204         return false;
205     if (vec_size(a->expression.params) != vec_size(b->expression.params))
206         return false;
207     if (a->expression.variadic != b->expression.variadic)
208         return false;
209     if (vec_size(a->expression.params)) {
210         size_t i;
211         for (i = 0; i < vec_size(a->expression.params); ++i) {
212             if (!ast_compare_type((ast_expression*)a->expression.params[i],
213                                   (ast_expression*)b->expression.params[i]))
214                 return false;
215         }
216     }
217     if (a->expression.next)
218         return ast_compare_type(a->expression.next, b->expression.next);
219     return true;
220 }
221
222 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
223 {
224     const char *typestr;
225     size_t typelen;
226     size_t i;
227
228     if (!e) {
229         if (pos + 6 >= bufsize)
230             goto full;
231         strcpy(buf + pos, "(null)");
232         return pos + 6;
233     }
234
235     if (pos + 1 >= bufsize)
236         goto full;
237
238     switch (e->expression.vtype) {
239         case TYPE_VARIANT:
240             strcpy(buf + pos, "(variant)");
241             return pos + 9;
242
243         case TYPE_FIELD:
244             buf[pos++] = '.';
245             return ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
246
247         case TYPE_POINTER:
248             if (pos + 3 >= bufsize)
249                 goto full;
250             buf[pos++] = '*';
251             buf[pos++] = '(';
252             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
253             if (pos + 1 >= bufsize)
254                 goto full;
255             buf[pos++] = ')';
256             return pos;
257
258         case TYPE_FUNCTION:
259             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
260             if (pos + 2 >= bufsize)
261                 goto full;
262             if (!vec_size(e->expression.params)) {
263                 buf[pos++] = '(';
264                 buf[pos++] = ')';
265                 return pos;
266             }
267             buf[pos++] = '(';
268             pos = ast_type_to_string_impl((ast_expression*)(e->expression.params[0]), buf, bufsize, pos);
269             for (i = 1; i < vec_size(e->expression.params); ++i) {
270                 if (pos + 2 >= bufsize)
271                     goto full;
272                 buf[pos++] = ',';
273                 buf[pos++] = ' ';
274                 pos = ast_type_to_string_impl((ast_expression*)(e->expression.params[i]), buf, bufsize, pos);
275             }
276             if (pos + 1 >= bufsize)
277                 goto full;
278             buf[pos++] = ')';
279             return pos;
280
281         case TYPE_ARRAY:
282             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
283             if (pos + 1 >= bufsize)
284                 goto full;
285             buf[pos++] = '[';
286             pos += snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->expression.count);
287             if (pos + 1 >= bufsize)
288                 goto full;
289             buf[pos++] = ']';
290             return pos;
291
292         default:
293             typestr = type_name[e->expression.vtype];
294             typelen = strlen(typestr);
295             if (pos + typelen >= bufsize)
296                 goto full;
297             strcpy(buf + pos, typestr);
298             return pos + typelen;
299     }
300
301 full:
302     buf[bufsize-3] = '.';
303     buf[bufsize-2] = '.';
304     buf[bufsize-1] = '.';
305     return bufsize;
306 }
307
308 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
309 {
310     size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
311     buf[pos] = 0;
312 }
313
314 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
315 {
316     ast_instantiate(ast_value, ctx, ast_value_delete);
317     ast_expression_init((ast_expression*)self,
318                         (ast_expression_codegen*)&ast_value_codegen);
319     self->expression.node.keep = true; /* keep */
320
321     self->name = name ? util_strdup(name) : NULL;
322     self->expression.vtype = t;
323     self->expression.next  = NULL;
324     self->isconst = false;
325     self->uses    = 0;
326     memset(&self->constval, 0, sizeof(self->constval));
327
328     self->ir_v           = NULL;
329     self->ir_values      = NULL;
330     self->ir_value_count = 0;
331
332     self->setter = NULL;
333     self->getter = NULL;
334
335     return self;
336 }
337
338 void ast_value_delete(ast_value* self)
339 {
340     if (self->name)
341         mem_d((void*)self->name);
342     if (self->isconst) {
343         switch (self->expression.vtype)
344         {
345         case TYPE_STRING:
346             mem_d((void*)self->constval.vstring);
347             break;
348         case TYPE_FUNCTION:
349             /* unlink us from the function node */
350             self->constval.vfunc->vtype = NULL;
351             break;
352         /* NOTE: delete function? currently collected in
353          * the parser structure
354          */
355         default:
356             break;
357         }
358     }
359     if (self->ir_values)
360         mem_d(self->ir_values);
361     ast_expression_delete((ast_expression*)self);
362     mem_d(self);
363 }
364
365 void ast_value_params_add(ast_value *self, ast_value *p)
366 {
367     vec_push(self->expression.params, p);
368 }
369
370 bool ast_value_set_name(ast_value *self, const char *name)
371 {
372     if (self->name)
373         mem_d((void*)self->name);
374     self->name = util_strdup(name);
375     return !!self->name;
376 }
377
378 ast_binary* ast_binary_new(lex_ctx ctx, int op,
379                            ast_expression* left, ast_expression* right)
380 {
381     ast_instantiate(ast_binary, ctx, ast_binary_delete);
382     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
383
384     self->op = op;
385     self->left = left;
386     self->right = right;
387
388     if (op >= INSTR_EQ_F && op <= INSTR_GT)
389         self->expression.vtype = TYPE_FLOAT;
390     else if (op == INSTR_AND || op == INSTR_OR ||
391              op == INSTR_BITAND || op == INSTR_BITOR)
392         self->expression.vtype = TYPE_FLOAT;
393     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
394         self->expression.vtype = TYPE_VECTOR;
395     else if (op == INSTR_MUL_V)
396         self->expression.vtype = TYPE_FLOAT;
397     else
398         self->expression.vtype = left->expression.vtype;
399
400     return self;
401 }
402
403 void ast_binary_delete(ast_binary *self)
404 {
405     ast_unref(self->left);
406     ast_unref(self->right);
407     ast_expression_delete((ast_expression*)self);
408     mem_d(self);
409 }
410
411 ast_binstore* ast_binstore_new(lex_ctx ctx, int storop, int op,
412                                ast_expression* left, ast_expression* right)
413 {
414     ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
415     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
416
417     self->opstore = storop;
418     self->opbin   = op;
419     self->dest    = left;
420     self->source  = right;
421
422     self->expression.vtype = left->expression.vtype;
423     if (left->expression.next) {
424         self->expression.next = ast_type_copy(ctx, left);
425         if (!self->expression.next) {
426             ast_delete(self);
427             return NULL;
428         }
429     }
430     else
431         self->expression.next = NULL;
432
433     return self;
434 }
435
436 void ast_binstore_delete(ast_binstore *self)
437 {
438     ast_unref(self->dest);
439     ast_unref(self->source);
440     ast_expression_delete((ast_expression*)self);
441     mem_d(self);
442 }
443
444 ast_unary* ast_unary_new(lex_ctx ctx, int op,
445                          ast_expression *expr)
446 {
447     ast_instantiate(ast_unary, ctx, ast_unary_delete);
448     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
449
450     self->op = op;
451     self->operand = expr;
452
453     if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
454         self->expression.vtype = TYPE_FLOAT;
455     } else
456         asterror(ctx, "cannot determine type of unary operation %s", asm_instr[op].m);
457
458     return self;
459 }
460
461 void ast_unary_delete(ast_unary *self)
462 {
463     ast_unref(self->operand);
464     ast_expression_delete((ast_expression*)self);
465     mem_d(self);
466 }
467
468 ast_return* ast_return_new(lex_ctx ctx, ast_expression *expr)
469 {
470     ast_instantiate(ast_return, ctx, ast_return_delete);
471     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
472
473     self->operand = expr;
474
475     return self;
476 }
477
478 void ast_return_delete(ast_return *self)
479 {
480     if (self->operand)
481         ast_unref(self->operand);
482     ast_expression_delete((ast_expression*)self);
483     mem_d(self);
484 }
485
486 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
487 {
488     if (field->expression.vtype != TYPE_FIELD) {
489         asterror(ctx, "ast_entfield_new with expression not of type field");
490         return NULL;
491     }
492     return ast_entfield_new_force(ctx, entity, field, field->expression.next);
493 }
494
495 ast_entfield* ast_entfield_new_force(lex_ctx ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
496 {
497     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
498
499     if (!outtype) {
500         mem_d(self);
501         /* Error: field has no type... */
502         return NULL;
503     }
504
505     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
506
507     self->entity = entity;
508     self->field  = field;
509
510     if (!ast_type_adopt(self, outtype)) {
511         ast_entfield_delete(self);
512         return NULL;
513     }
514
515     return self;
516 }
517
518 void ast_entfield_delete(ast_entfield *self)
519 {
520     ast_unref(self->entity);
521     ast_unref(self->field);
522     ast_expression_delete((ast_expression*)self);
523     mem_d(self);
524 }
525
526 ast_member* ast_member_new(lex_ctx ctx, ast_expression *owner, unsigned int field)
527 {
528     ast_instantiate(ast_member, ctx, ast_member_delete);
529     if (field >= 3) {
530         mem_d(self);
531         return NULL;
532     }
533
534     if (owner->expression.vtype != TYPE_VECTOR &&
535         owner->expression.vtype != TYPE_FIELD) {
536         asterror(ctx, "member-access on an invalid owner of type %s", type_name[owner->expression.vtype]);
537         mem_d(self);
538         return NULL;
539     }
540
541     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
542     self->expression.node.keep = true; /* keep */
543
544     if (owner->expression.vtype == TYPE_VECTOR) {
545         self->expression.vtype = TYPE_FLOAT;
546         self->expression.next  = NULL;
547     } else {
548         self->expression.vtype = TYPE_FIELD;
549         self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
550     }
551
552     self->owner = owner;
553     self->field = field;
554
555     return self;
556 }
557
558 void ast_member_delete(ast_member *self)
559 {
560     /* The owner is always an ast_value, which has .keep=true,
561      * also: ast_members are usually deleted after the owner, thus
562      * this will cause invalid access
563     ast_unref(self->owner);
564      * once we allow (expression).x to access a vector-member, we need
565      * to change this: preferably by creating an alternate ast node for this
566      * purpose that is not garbage-collected.
567     */
568     ast_expression_delete((ast_expression*)self);
569     mem_d(self);
570 }
571
572 ast_array_index* ast_array_index_new(lex_ctx ctx, ast_expression *array, ast_expression *index)
573 {
574     ast_expression *outtype;
575     ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
576
577     outtype = array->expression.next;
578     if (!outtype) {
579         mem_d(self);
580         /* Error: field has no type... */
581         return NULL;
582     }
583
584     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
585
586     self->array = array;
587     self->index = index;
588
589     if (!ast_type_adopt(self, outtype)) {
590         ast_array_index_delete(self);
591         return NULL;
592     }
593     if (array->expression.vtype == TYPE_FIELD && outtype->expression.vtype == TYPE_ARRAY) {
594         if (self->expression.vtype != TYPE_ARRAY) {
595             asterror(ast_ctx(self), "array_index node on type");
596             ast_array_index_delete(self);
597             return NULL;
598         }
599         self->array = outtype;
600         self->expression.vtype = TYPE_FIELD;
601     }
602
603     return self;
604 }
605
606 void ast_array_index_delete(ast_array_index *self)
607 {
608     ast_unref(self->array);
609     ast_unref(self->index);
610     ast_expression_delete((ast_expression*)self);
611     mem_d(self);
612 }
613
614 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
615 {
616     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
617     if (!ontrue && !onfalse) {
618         /* because it is invalid */
619         mem_d(self);
620         return NULL;
621     }
622     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
623
624     self->cond     = cond;
625     self->on_true  = ontrue;
626     self->on_false = onfalse;
627
628     return self;
629 }
630
631 void ast_ifthen_delete(ast_ifthen *self)
632 {
633     ast_unref(self->cond);
634     if (self->on_true)
635         ast_unref(self->on_true);
636     if (self->on_false)
637         ast_unref(self->on_false);
638     ast_expression_delete((ast_expression*)self);
639     mem_d(self);
640 }
641
642 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
643 {
644     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
645     /* This time NEITHER must be NULL */
646     if (!ontrue || !onfalse) {
647         mem_d(self);
648         return NULL;
649     }
650     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
651
652     self->cond     = cond;
653     self->on_true  = ontrue;
654     self->on_false = onfalse;
655
656     if (!ast_type_adopt(self, ontrue)) {
657         ast_ternary_delete(self);
658         return NULL;
659     }
660
661     return self;
662 }
663
664 void ast_ternary_delete(ast_ternary *self)
665 {
666     ast_unref(self->cond);
667     ast_unref(self->on_true);
668     ast_unref(self->on_false);
669     ast_expression_delete((ast_expression*)self);
670     mem_d(self);
671 }
672
673 ast_loop* ast_loop_new(lex_ctx ctx,
674                        ast_expression *initexpr,
675                        ast_expression *precond,
676                        ast_expression *postcond,
677                        ast_expression *increment,
678                        ast_expression *body)
679 {
680     ast_instantiate(ast_loop, ctx, ast_loop_delete);
681     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
682
683     self->initexpr  = initexpr;
684     self->precond   = precond;
685     self->postcond  = postcond;
686     self->increment = increment;
687     self->body      = body;
688
689     return self;
690 }
691
692 void ast_loop_delete(ast_loop *self)
693 {
694     if (self->initexpr)
695         ast_unref(self->initexpr);
696     if (self->precond)
697         ast_unref(self->precond);
698     if (self->postcond)
699         ast_unref(self->postcond);
700     if (self->increment)
701         ast_unref(self->increment);
702     if (self->body)
703         ast_unref(self->body);
704     ast_expression_delete((ast_expression*)self);
705     mem_d(self);
706 }
707
708 ast_breakcont* ast_breakcont_new(lex_ctx ctx, bool iscont)
709 {
710     ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
711     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
712
713     self->is_continue = iscont;
714
715     return self;
716 }
717
718 void ast_breakcont_delete(ast_breakcont *self)
719 {
720     ast_expression_delete((ast_expression*)self);
721     mem_d(self);
722 }
723
724 ast_switch* ast_switch_new(lex_ctx ctx, ast_expression *op)
725 {
726     ast_instantiate(ast_switch, ctx, ast_switch_delete);
727     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
728
729     self->operand = op;
730     self->cases   = NULL;
731
732     return self;
733 }
734
735 void ast_switch_delete(ast_switch *self)
736 {
737     size_t i;
738     ast_unref(self->operand);
739
740     for (i = 0; i < vec_size(self->cases); ++i) {
741         if (self->cases[i].value)
742             ast_unref(self->cases[i].value);
743         ast_unref(self->cases[i].code);
744     }
745     vec_free(self->cases);
746
747     ast_expression_delete((ast_expression*)self);
748     mem_d(self);
749 }
750
751 ast_call* ast_call_new(lex_ctx ctx,
752                        ast_expression *funcexpr)
753 {
754     ast_instantiate(ast_call, ctx, ast_call_delete);
755     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
756
757     self->params = NULL;
758     self->func   = funcexpr;
759
760     self->expression.vtype = funcexpr->expression.next->expression.vtype;
761     if (funcexpr->expression.next->expression.next)
762         self->expression.next = ast_type_copy(ctx, funcexpr->expression.next->expression.next);
763
764     return self;
765 }
766
767 void ast_call_delete(ast_call *self)
768 {
769     size_t i;
770     for (i = 0; i < vec_size(self->params); ++i)
771         ast_unref(self->params[i]);
772     vec_free(self->params);
773
774     if (self->func)
775         ast_unref(self->func);
776
777     ast_expression_delete((ast_expression*)self);
778     mem_d(self);
779 }
780
781 bool ast_call_check_types(ast_call *self)
782 {
783     size_t i;
784     bool   retval = true;
785     const  ast_expression *func = self->func;
786     size_t count = vec_size(self->params);
787     if (count > vec_size(func->expression.params))
788         count = vec_size(func->expression.params);
789
790     for (i = 0; i < count; ++i) {
791         if (!ast_compare_type(self->params[i], (ast_expression*)(func->expression.params[i]))) {
792             char texp[1024];
793             char tgot[1024];
794             ast_type_to_string(self->params[i], tgot, sizeof(tgot));
795             ast_type_to_string((ast_expression*)func->expression.params[i], texp, sizeof(texp));
796             asterror(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
797                      (unsigned int)(i+1), texp, tgot);
798             /* we don't immediately return */
799             retval = false;
800         }
801     }
802     return retval;
803 }
804
805 ast_store* ast_store_new(lex_ctx ctx, int op,
806                          ast_expression *dest, ast_expression *source)
807 {
808     ast_instantiate(ast_store, ctx, ast_store_delete);
809     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
810
811     self->op = op;
812     self->dest = dest;
813     self->source = source;
814
815     self->expression.vtype = dest->expression.vtype;
816     if (dest->expression.next) {
817         self->expression.next = ast_type_copy(ctx, dest);
818         if (!self->expression.next) {
819             ast_delete(self);
820             return NULL;
821         }
822     }
823     else
824         self->expression.next = NULL;
825
826     return self;
827 }
828
829 void ast_store_delete(ast_store *self)
830 {
831     ast_unref(self->dest);
832     ast_unref(self->source);
833     ast_expression_delete((ast_expression*)self);
834     mem_d(self);
835 }
836
837 ast_block* ast_block_new(lex_ctx ctx)
838 {
839     ast_instantiate(ast_block, ctx, ast_block_delete);
840     ast_expression_init((ast_expression*)self,
841                         (ast_expression_codegen*)&ast_block_codegen);
842
843     self->locals  = NULL;
844     self->exprs   = NULL;
845     self->collect = NULL;
846
847     return self;
848 }
849
850 void ast_block_collect(ast_block *self, ast_expression *expr)
851 {
852     vec_push(self->collect, expr);
853     expr->expression.node.keep = true;
854 }
855
856 void ast_block_delete(ast_block *self)
857 {
858     size_t i;
859     for (i = 0; i < vec_size(self->exprs); ++i)
860         ast_unref(self->exprs[i]);
861     vec_free(self->exprs);
862     for (i = 0; i < vec_size(self->locals); ++i)
863         ast_delete(self->locals[i]);
864     vec_free(self->locals);
865     for (i = 0; i < vec_size(self->collect); ++i)
866         ast_delete(self->collect[i]);
867     vec_free(self->collect);
868     ast_expression_delete((ast_expression*)self);
869     mem_d(self);
870 }
871
872 bool ast_block_set_type(ast_block *self, ast_expression *from)
873 {
874     if (self->expression.next)
875         ast_delete(self->expression.next);
876     self->expression.vtype = from->expression.vtype;
877     if (from->expression.next) {
878         self->expression.next = ast_type_copy(self->expression.node.context, from->expression.next);
879         if (!self->expression.next)
880             return false;
881     }
882     else
883         self->expression.next = NULL;
884     return true;
885 }
886
887 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
888 {
889     ast_instantiate(ast_function, ctx, ast_function_delete);
890
891     if (!vtype ||
892         vtype->isconst ||
893         vtype->expression.vtype != TYPE_FUNCTION)
894     {
895         asterror(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i",
896                  (int)!vtype,
897                  (int)vtype->isconst,
898                  vtype->expression.vtype);
899         mem_d(self);
900         return NULL;
901     }
902
903     self->vtype  = vtype;
904     self->name   = name ? util_strdup(name) : NULL;
905     self->blocks = NULL;
906
907     self->labelcount = 0;
908     self->builtin = 0;
909
910     self->ir_func = NULL;
911     self->curblock = NULL;
912
913     self->breakblock    = NULL;
914     self->continueblock = NULL;
915
916     vtype->isconst = true;
917     vtype->constval.vfunc = self;
918
919     return self;
920 }
921
922 void ast_function_delete(ast_function *self)
923 {
924     size_t i;
925     if (self->name)
926         mem_d((void*)self->name);
927     if (self->vtype) {
928         /* ast_value_delete(self->vtype); */
929         self->vtype->isconst = false;
930         self->vtype->constval.vfunc = NULL;
931         /* We use unref - if it was stored in a global table it is supposed
932          * to be deleted from *there*
933          */
934         ast_unref(self->vtype);
935     }
936     for (i = 0; i < vec_size(self->blocks); ++i)
937         ast_delete(self->blocks[i]);
938     vec_free(self->blocks);
939     mem_d(self);
940 }
941
942 const char* ast_function_label(ast_function *self, const char *prefix)
943 {
944     size_t id;
945     size_t len;
946     char  *from;
947
948     if (!opts_dump && !opts_dumpfin)
949         return NULL;
950
951     id  = (self->labelcount++);
952     len = strlen(prefix);
953
954     from = self->labelbuf + sizeof(self->labelbuf)-1;
955     *from-- = 0;
956     do {
957         unsigned int digit = id % 10;
958         *from = digit + '0';
959         id /= 10;
960     } while (id);
961     memcpy(from - len, prefix, len);
962     return from - len;
963 }
964
965 /*********************************************************************/
966 /* AST codegen part
967  * by convention you must never pass NULL to the 'ir_value **out'
968  * parameter. If you really don't care about the output, pass a dummy.
969  * But I can't imagine a pituation where the output is truly unnecessary.
970  */
971
972 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
973 {
974     (void)func;
975     (void)lvalue;
976     /* NOTE: This is the codegen for a variable used in an expression.
977      * It is not the codegen to generate the value. For this purpose,
978      * ast_local_codegen and ast_global_codegen are to be used before this
979      * is executed. ast_function_codegen should take care of its locals,
980      * and the ast-user should take care of ast_global_codegen to be used
981      * on all the globals.
982      */
983     if (!self->ir_v) {
984         char typename[1024];
985         ast_type_to_string((ast_expression*)self, typename, sizeof(typename));
986         asterror(ast_ctx(self), "ast_value used before generated %s %s", typename, self->name);
987         return false;
988     }
989     *out = self->ir_v;
990     return true;
991 }
992
993 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
994 {
995     ir_value *v = NULL;
996
997     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
998     {
999         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
1000         if (!func)
1001             return false;
1002         func->context = ast_ctx(self);
1003         func->value->context = ast_ctx(self);
1004
1005         self->constval.vfunc->ir_func = func;
1006         self->ir_v = func->value;
1007         /* The function is filled later on ast_function_codegen... */
1008         return true;
1009     }
1010
1011     if (isfield && self->expression.vtype == TYPE_FIELD) {
1012         ast_expression *fieldtype = self->expression.next;
1013
1014         if (self->isconst) {
1015             asterror(ast_ctx(self), "TODO: constant field pointers with value");
1016             goto error;
1017         }
1018
1019         if (fieldtype->expression.vtype == TYPE_ARRAY) {
1020             size_t ai;
1021             char   *name;
1022             size_t  namelen;
1023
1024             ast_expression_common *elemtype;
1025             int                    vtype;
1026             ast_value             *array = (ast_value*)fieldtype;
1027
1028             if (!ast_istype(fieldtype, ast_value)) {
1029                 asterror(ast_ctx(self), "internal error: ast_value required");
1030                 return false;
1031             }
1032
1033             /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1034             if (!array->expression.count || array->expression.count > opts_max_array_size)
1035                 asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1036
1037             elemtype = &array->expression.next->expression;
1038             vtype = elemtype->vtype;
1039
1040             v = ir_builder_create_field(ir, self->name, vtype);
1041             if (!v) {
1042                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1043                 return false;
1044             }
1045             if (vtype == TYPE_FIELD)
1046                 v->fieldtype = elemtype->next->expression.vtype;
1047             v->context = ast_ctx(self);
1048             array->ir_v = self->ir_v = v;
1049
1050             namelen = strlen(self->name);
1051             name    = (char*)mem_a(namelen + 16);
1052             strcpy(name, self->name);
1053
1054             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1055             array->ir_values[0] = v;
1056             for (ai = 1; ai < array->expression.count; ++ai) {
1057                 snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1058                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1059                 if (!array->ir_values[ai]) {
1060                     mem_d(name);
1061                     asterror(ast_ctx(self), "ir_builder_create_global failed");
1062                     return false;
1063                 }
1064                 if (vtype == TYPE_FIELD)
1065                     array->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1066                 array->ir_values[ai]->context = ast_ctx(self);
1067             }
1068             mem_d(name);
1069         }
1070         else
1071         {
1072             v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
1073             if (!v)
1074                 return false;
1075             v->context = ast_ctx(self);
1076             self->ir_v = v;
1077         }
1078         return true;
1079     }
1080
1081     if (self->expression.vtype == TYPE_ARRAY) {
1082         size_t ai;
1083         char   *name;
1084         size_t  namelen;
1085
1086         ast_expression_common *elemtype = &self->expression.next->expression;
1087         int vtype = elemtype->vtype;
1088
1089         /* same as with field arrays */
1090         if (!self->expression.count || self->expression.count > opts_max_array_size)
1091             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1092
1093         v = ir_builder_create_global(ir, self->name, vtype);
1094         if (!v) {
1095             asterror(ast_ctx(self), "ir_builder_create_global failed");
1096             return false;
1097         }
1098         if (vtype == TYPE_FIELD)
1099             v->fieldtype = elemtype->next->expression.vtype;
1100         v->context = ast_ctx(self);
1101
1102         namelen = strlen(self->name);
1103         name    = (char*)mem_a(namelen + 16);
1104         strcpy(name, self->name);
1105
1106         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1107         self->ir_values[0] = v;
1108         for (ai = 1; ai < self->expression.count; ++ai) {
1109             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1110             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1111             if (!self->ir_values[ai]) {
1112                 mem_d(name);
1113                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1114                 return false;
1115             }
1116             if (vtype == TYPE_FIELD)
1117                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1118             self->ir_values[ai]->context = ast_ctx(self);
1119         }
1120         mem_d(name);
1121     }
1122     else
1123     {
1124         /* Arrays don't do this since there's no "array" value which spans across the
1125          * whole thing.
1126          */
1127         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1128         if (!v) {
1129             asterror(ast_ctx(self), "ir_builder_create_global failed");
1130             return false;
1131         }
1132         if (self->expression.vtype == TYPE_FIELD)
1133             v->fieldtype = self->expression.next->expression.vtype;
1134         v->context = ast_ctx(self);
1135     }
1136
1137     if (self->isconst) {
1138         switch (self->expression.vtype)
1139         {
1140             case TYPE_FLOAT:
1141                 if (!ir_value_set_float(v, self->constval.vfloat))
1142                     goto error;
1143                 break;
1144             case TYPE_VECTOR:
1145                 if (!ir_value_set_vector(v, self->constval.vvec))
1146                     goto error;
1147                 break;
1148             case TYPE_STRING:
1149                 if (!ir_value_set_string(v, self->constval.vstring))
1150                     goto error;
1151                 break;
1152             case TYPE_ARRAY:
1153                 asterror(ast_ctx(self), "TODO: global constant array");
1154                 break;
1155             case TYPE_FUNCTION:
1156                 asterror(ast_ctx(self), "global of type function not properly generated");
1157                 goto error;
1158                 /* Cannot generate an IR value for a function,
1159                  * need a pointer pointing to a function rather.
1160                  */
1161             default:
1162                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1163                 break;
1164         }
1165     }
1166
1167     /* link us to the ir_value */
1168     self->ir_v = v;
1169     return true;
1170
1171 error: /* clean up */
1172     ir_value_delete(v);
1173     return false;
1174 }
1175
1176 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1177 {
1178     ir_value *v = NULL;
1179     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
1180     {
1181         /* Do we allow local functions? I think not...
1182          * this is NOT a function pointer atm.
1183          */
1184         return false;
1185     }
1186
1187     if (self->expression.vtype == TYPE_ARRAY) {
1188         size_t ai;
1189         char   *name;
1190         size_t  namelen;
1191
1192         ast_expression_common *elemtype = &self->expression.next->expression;
1193         int vtype = elemtype->vtype;
1194
1195         if (param) {
1196             asterror(ast_ctx(self), "array-parameters are not supported");
1197             return false;
1198         }
1199
1200         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1201         if (!self->expression.count || self->expression.count > opts_max_array_size) {
1202             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1203         }
1204
1205         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1206         if (!self->ir_values) {
1207             asterror(ast_ctx(self), "failed to allocate array values");
1208             return false;
1209         }
1210
1211         v = ir_function_create_local(func, self->name, vtype, param);
1212         if (!v) {
1213             asterror(ast_ctx(self), "ir_function_create_local failed");
1214             return false;
1215         }
1216         if (vtype == TYPE_FIELD)
1217             v->fieldtype = elemtype->next->expression.vtype;
1218         v->context = ast_ctx(self);
1219
1220         namelen = strlen(self->name);
1221         name    = (char*)mem_a(namelen + 16);
1222         strcpy(name, self->name);
1223
1224         self->ir_values[0] = v;
1225         for (ai = 1; ai < self->expression.count; ++ai) {
1226             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1227             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1228             if (!self->ir_values[ai]) {
1229                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1230                 return false;
1231             }
1232             if (vtype == TYPE_FIELD)
1233                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1234             self->ir_values[ai]->context = ast_ctx(self);
1235         }
1236     }
1237     else
1238     {
1239         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1240         if (!v)
1241             return false;
1242         if (self->expression.vtype == TYPE_FIELD)
1243             v->fieldtype = self->expression.next->expression.vtype;
1244         v->context = ast_ctx(self);
1245     }
1246
1247     /* A constant local... hmmm...
1248      * I suppose the IR will have to deal with this
1249      */
1250     if (self->isconst) {
1251         switch (self->expression.vtype)
1252         {
1253             case TYPE_FLOAT:
1254                 if (!ir_value_set_float(v, self->constval.vfloat))
1255                     goto error;
1256                 break;
1257             case TYPE_VECTOR:
1258                 if (!ir_value_set_vector(v, self->constval.vvec))
1259                     goto error;
1260                 break;
1261             case TYPE_STRING:
1262                 if (!ir_value_set_string(v, self->constval.vstring))
1263                     goto error;
1264                 break;
1265             default:
1266                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1267                 break;
1268         }
1269     }
1270
1271     /* link us to the ir_value */
1272     self->ir_v = v;
1273
1274     if (self->setter) {
1275         if (!ast_global_codegen(self->setter, func->owner, false) ||
1276             !ast_function_codegen(self->setter->constval.vfunc, func->owner) ||
1277             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1278             return false;
1279     }
1280     if (self->getter) {
1281         if (!ast_global_codegen(self->getter, func->owner, false) ||
1282             !ast_function_codegen(self->getter->constval.vfunc, func->owner) ||
1283             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1284             return false;
1285     }
1286     return true;
1287
1288 error: /* clean up */
1289     ir_value_delete(v);
1290     return false;
1291 }
1292
1293 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1294 {
1295     ir_function *irf;
1296     ir_value    *dummy;
1297     ast_expression_common *ec;
1298     size_t    i;
1299
1300     (void)ir;
1301
1302     irf = self->ir_func;
1303     if (!irf) {
1304         asterror(ast_ctx(self), "ast_function's related ast_value was not generated yet");
1305         return false;
1306     }
1307
1308     /* fill the parameter list */
1309     ec = &self->vtype->expression;
1310     for (i = 0; i < vec_size(ec->params); ++i)
1311     {
1312         vec_push(irf->params, ec->params[i]->expression.vtype);
1313         if (!self->builtin) {
1314             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1315                 return false;
1316         }
1317     }
1318
1319     if (self->builtin) {
1320         irf->builtin = self->builtin;
1321         return true;
1322     }
1323
1324     if (!vec_size(self->blocks)) {
1325         asterror(ast_ctx(self), "function `%s` has no body", self->name);
1326         return false;
1327     }
1328
1329     self->curblock = ir_function_create_block(irf, "entry");
1330     if (!self->curblock) {
1331         asterror(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1332         return false;
1333     }
1334
1335     for (i = 0; i < vec_size(self->blocks); ++i) {
1336         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
1337         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
1338             return false;
1339     }
1340
1341     /* TODO: check return types */
1342     if (!self->curblock->is_return)
1343     {
1344         return ir_block_create_return(self->curblock, NULL);
1345         /* From now on the parser has to handle this situation */
1346 #if 0
1347         if (!self->vtype->expression.next ||
1348             self->vtype->expression.next->expression.vtype == TYPE_VOID)
1349         {
1350             return ir_block_create_return(self->curblock, NULL);
1351         }
1352         else
1353         {
1354             /* error("missing return"); */
1355             asterror(ast_ctx(self), "function `%s` missing return value", self->name);
1356             return false;
1357         }
1358 #endif
1359     }
1360     return true;
1361 }
1362
1363 /* Note, you will not see ast_block_codegen generate ir_blocks.
1364  * To the AST and the IR, blocks are 2 different things.
1365  * In the AST it represents a block of code, usually enclosed in
1366  * curly braces {...}.
1367  * While in the IR it represents a block in terms of control-flow.
1368  */
1369 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1370 {
1371     size_t i;
1372
1373     /* We don't use this
1374      * Note: an ast-representation using the comma-operator
1375      * of the form: (a, b, c) = x should not assign to c...
1376      */
1377     if (lvalue) {
1378         asterror(ast_ctx(self), "not an l-value (code-block)");
1379         return false;
1380     }
1381
1382     if (self->expression.outr) {
1383         *out = self->expression.outr;
1384         return true;
1385     }
1386
1387     /* output is NULL at first, we'll have each expression
1388      * assign to out output, thus, a comma-operator represention
1389      * using an ast_block will return the last generated value,
1390      * so: (b, c) + a  executed both b and c, and returns c,
1391      * which is then added to a.
1392      */
1393     *out = NULL;
1394
1395     /* generate locals */
1396     for (i = 0; i < vec_size(self->locals); ++i)
1397     {
1398         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1399             if (opts_debug)
1400                 asterror(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1401             return false;
1402         }
1403     }
1404
1405     for (i = 0; i < vec_size(self->exprs); ++i)
1406     {
1407         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
1408         if (func->curblock->final) {
1409             asterror(ast_ctx(self->exprs[i]), "unreachable statement");
1410             return false;
1411         }
1412         if (!(*gen)(self->exprs[i], func, false, out))
1413             return false;
1414     }
1415
1416     self->expression.outr = *out;
1417
1418     return true;
1419 }
1420
1421 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1422 {
1423     ast_expression_codegen *cgen;
1424     ir_value *left  = NULL;
1425     ir_value *right = NULL;
1426
1427     ast_value       *arr;
1428     ast_value       *idx = 0;
1429     ast_array_index *ai = NULL;
1430
1431     if (lvalue && self->expression.outl) {
1432         *out = self->expression.outl;
1433         return true;
1434     }
1435
1436     if (!lvalue && self->expression.outr) {
1437         *out = self->expression.outr;
1438         return true;
1439     }
1440
1441     if (ast_istype(self->dest, ast_array_index))
1442     {
1443
1444         ai = (ast_array_index*)self->dest;
1445         idx = (ast_value*)ai->index;
1446
1447         if (ast_istype(ai->index, ast_value) && idx->isconst)
1448             ai = NULL;
1449     }
1450
1451     if (ai) {
1452         /* we need to call the setter */
1453         ir_value  *iridx, *funval;
1454         ir_instr  *call;
1455
1456         if (lvalue) {
1457             asterror(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1458             return false;
1459         }
1460
1461         arr = (ast_value*)ai->array;
1462         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1463             asterror(ast_ctx(self), "value has no setter (%s)", arr->name);
1464             return false;
1465         }
1466
1467         cgen = idx->expression.codegen;
1468         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1469             return false;
1470
1471         cgen = arr->setter->expression.codegen;
1472         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1473             return false;
1474
1475         cgen = self->source->expression.codegen;
1476         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1477             return false;
1478
1479         call = ir_block_create_call(func->curblock, ast_function_label(func, "store"), funval);
1480         if (!call)
1481             return false;
1482         ir_call_param(call, iridx);
1483         ir_call_param(call, right);
1484         self->expression.outr = right;
1485     }
1486     else
1487     {
1488         /* regular code */
1489
1490         cgen = self->dest->expression.codegen;
1491         /* lvalue! */
1492         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1493             return false;
1494         self->expression.outl = left;
1495
1496         cgen = self->source->expression.codegen;
1497         /* rvalue! */
1498         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1499             return false;
1500
1501         if (!ir_block_create_store_op(func->curblock, self->op, left, right))
1502             return false;
1503         self->expression.outr = right;
1504     }
1505
1506     /* Theoretically, an assinment returns its left side as an
1507      * lvalue, if we don't need an lvalue though, we return
1508      * the right side as an rvalue, otherwise we have to
1509      * somehow know whether or not we need to dereference the pointer
1510      * on the left side - that is: OP_LOAD if it was an address.
1511      * Also: in original QC we cannot OP_LOADP *anyway*.
1512      */
1513     *out = (lvalue ? left : right);
1514
1515     return true;
1516 }
1517
1518 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1519 {
1520     ast_expression_codegen *cgen;
1521     ir_value *left, *right;
1522
1523     /* A binary operation cannot yield an l-value */
1524     if (lvalue) {
1525         asterror(ast_ctx(self), "not an l-value (binop)");
1526         return false;
1527     }
1528
1529     if (self->expression.outr) {
1530         *out = self->expression.outr;
1531         return true;
1532     }
1533
1534     if (OPTS_FLAG(SHORT_LOGIC) &&
1535         (self->op == INSTR_AND || self->op == INSTR_OR))
1536     {
1537         /* short circuit evaluation */
1538         ir_block *other, *merge;
1539         ir_block *from_left, *from_right;
1540         ir_instr *phi;
1541         size_t    merge_id;
1542         uint16_t  notop;
1543
1544         /* Note about casting to true boolean values:
1545          * We use a single NOT for sub expressions, and an
1546          * overall NOT at the end, and for that purpose swap
1547          * all the jump conditions in order for the NOT to get
1548          * doubled.
1549          * ie: (a && b) usually becomes (!!a ? !!b : !!a)
1550          * but we translate this to (!(!a ? !a : !b))
1551          */
1552
1553         merge_id = vec_size(func->ir_func->blocks);
1554         merge = ir_function_create_block(func->ir_func, ast_function_label(func, "sce_merge"));
1555
1556         cgen = self->left->expression.codegen;
1557         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1558             return false;
1559         if (!OPTS_FLAG(PERL_LOGIC)) {
1560             notop = type_not_instr[left->vtype];
1561             if (notop == AINSTR_END) {
1562                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1563                 return false;
1564             }
1565             left = ir_block_create_unary(func->curblock,
1566                                          ast_function_label(func, "sce_not"),
1567                                          notop,
1568                                          left);
1569         }
1570         from_left = func->curblock;
1571
1572         other = ir_function_create_block(func->ir_func, ast_function_label(func, "sce_other"));
1573         if ( !(self->op == INSTR_OR) != !OPTS_FLAG(PERL_LOGIC) ) {
1574             if (!ir_block_create_if(func->curblock, left, other, merge))
1575                 return false;
1576         } else {
1577             if (!ir_block_create_if(func->curblock, left, merge, other))
1578                 return false;
1579         }
1580         /* use the likely flag */
1581         vec_last(func->curblock->instr)->likely = true;
1582
1583         func->curblock = other;
1584         cgen = self->right->expression.codegen;
1585         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1586             return false;
1587         if (!OPTS_FLAG(PERL_LOGIC)) {
1588             notop = type_not_instr[right->vtype];
1589             if (notop == AINSTR_END) {
1590                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1591                 return false;
1592             }
1593             right = ir_block_create_unary(func->curblock,
1594                                           ast_function_label(func, "sce_not"),
1595                                           notop,
1596                                           right);
1597         }
1598         from_right = func->curblock;
1599
1600         if (!ir_block_create_jump(func->curblock, merge))
1601             return false;
1602
1603         vec_remove(func->ir_func->blocks, merge_id, 1);
1604         vec_push(func->ir_func->blocks, merge);
1605
1606         func->curblock = merge;
1607         phi = ir_block_create_phi(func->curblock, ast_function_label(func, "sce_value"), TYPE_FLOAT);
1608         ir_phi_add(phi, from_left, left);
1609         ir_phi_add(phi, from_right, right);
1610         *out = ir_phi_value(phi);
1611         if (!OPTS_FLAG(PERL_LOGIC)) {
1612             notop = type_not_instr[(*out)->vtype];
1613             if (notop == AINSTR_END) {
1614                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1615                 return false;
1616             }
1617             *out = ir_block_create_unary(func->curblock,
1618                                          ast_function_label(func, "sce_final_not"),
1619                                          notop,
1620                                          *out);
1621         }
1622         if (!*out)
1623             return false;
1624         self->expression.outr = *out;
1625         return true;
1626     }
1627
1628     cgen = self->left->expression.codegen;
1629     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1630         return false;
1631
1632     cgen = self->right->expression.codegen;
1633     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1634         return false;
1635
1636     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
1637                                  self->op, left, right);
1638     if (!*out)
1639         return false;
1640     self->expression.outr = *out;
1641
1642     return true;
1643 }
1644
1645 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1646 {
1647     ast_expression_codegen *cgen;
1648     ir_value *leftl = NULL, *leftr, *right, *bin;
1649
1650     ast_value       *arr;
1651     ast_value       *idx = 0;
1652     ast_array_index *ai = NULL;
1653     ir_value        *iridx = NULL;
1654
1655     if (lvalue && self->expression.outl) {
1656         *out = self->expression.outl;
1657         return true;
1658     }
1659
1660     if (!lvalue && self->expression.outr) {
1661         *out = self->expression.outr;
1662         return true;
1663     }
1664
1665     if (ast_istype(self->dest, ast_array_index))
1666     {
1667
1668         ai = (ast_array_index*)self->dest;
1669         idx = (ast_value*)ai->index;
1670
1671         if (ast_istype(ai->index, ast_value) && idx->isconst)
1672             ai = NULL;
1673     }
1674
1675     /* for a binstore we need both an lvalue and an rvalue for the left side */
1676     /* rvalue of destination! */
1677     if (ai) {
1678         cgen = idx->expression.codegen;
1679         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1680             return false;
1681     }
1682     cgen = self->dest->expression.codegen;
1683     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
1684         return false;
1685
1686     /* source as rvalue only */
1687     cgen = self->source->expression.codegen;
1688     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1689         return false;
1690
1691     /* now the binary */
1692     bin = ir_block_create_binop(func->curblock, ast_function_label(func, "binst"),
1693                                 self->opbin, leftr, right);
1694     self->expression.outr = bin;
1695
1696
1697     if (ai) {
1698         /* we need to call the setter */
1699         ir_value  *funval;
1700         ir_instr  *call;
1701
1702         if (lvalue) {
1703             asterror(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1704             return false;
1705         }
1706
1707         arr = (ast_value*)ai->array;
1708         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1709             asterror(ast_ctx(self), "value has no setter (%s)", arr->name);
1710             return false;
1711         }
1712
1713         cgen = arr->setter->expression.codegen;
1714         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1715             return false;
1716
1717         call = ir_block_create_call(func->curblock, ast_function_label(func, "store"), funval);
1718         if (!call)
1719             return false;
1720         ir_call_param(call, iridx);
1721         ir_call_param(call, bin);
1722         self->expression.outr = bin;
1723     } else {
1724         /* now store them */
1725         cgen = self->dest->expression.codegen;
1726         /* lvalue of destination */
1727         if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
1728             return false;
1729         self->expression.outl = leftl;
1730
1731         if (!ir_block_create_store_op(func->curblock, self->opstore, leftl, bin))
1732             return false;
1733         self->expression.outr = bin;
1734     }
1735
1736     /* Theoretically, an assinment returns its left side as an
1737      * lvalue, if we don't need an lvalue though, we return
1738      * the right side as an rvalue, otherwise we have to
1739      * somehow know whether or not we need to dereference the pointer
1740      * on the left side - that is: OP_LOAD if it was an address.
1741      * Also: in original QC we cannot OP_LOADP *anyway*.
1742      */
1743     *out = (lvalue ? leftl : bin);
1744
1745     return true;
1746 }
1747
1748 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
1749 {
1750     ast_expression_codegen *cgen;
1751     ir_value *operand;
1752
1753     /* An unary operation cannot yield an l-value */
1754     if (lvalue) {
1755         asterror(ast_ctx(self), "not an l-value (binop)");
1756         return false;
1757     }
1758
1759     if (self->expression.outr) {
1760         *out = self->expression.outr;
1761         return true;
1762     }
1763
1764     cgen = self->operand->expression.codegen;
1765     /* lvalue! */
1766     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1767         return false;
1768
1769     *out = ir_block_create_unary(func->curblock, ast_function_label(func, "unary"),
1770                                  self->op, operand);
1771     if (!*out)
1772         return false;
1773     self->expression.outr = *out;
1774
1775     return true;
1776 }
1777
1778 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
1779 {
1780     ast_expression_codegen *cgen;
1781     ir_value *operand;
1782
1783     *out = NULL;
1784
1785     /* In the context of a return operation, we don't actually return
1786      * anything...
1787      */
1788     if (lvalue) {
1789         asterror(ast_ctx(self), "return-expression is not an l-value");
1790         return false;
1791     }
1792
1793     if (self->expression.outr) {
1794         asterror(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
1795         return false;
1796     }
1797     self->expression.outr = (ir_value*)1;
1798
1799     if (self->operand) {
1800         cgen = self->operand->expression.codegen;
1801         /* lvalue! */
1802         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1803             return false;
1804
1805         if (!ir_block_create_return(func->curblock, operand))
1806             return false;
1807     } else {
1808         if (!ir_block_create_return(func->curblock, NULL))
1809             return false;
1810     }
1811
1812     return true;
1813 }
1814
1815 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
1816 {
1817     ast_expression_codegen *cgen;
1818     ir_value *ent, *field;
1819
1820     /* This function needs to take the 'lvalue' flag into account!
1821      * As lvalue we provide a field-pointer, as rvalue we provide the
1822      * value in a temp.
1823      */
1824
1825     if (lvalue && self->expression.outl) {
1826         *out = self->expression.outl;
1827         return true;
1828     }
1829
1830     if (!lvalue && self->expression.outr) {
1831         *out = self->expression.outr;
1832         return true;
1833     }
1834
1835     cgen = self->entity->expression.codegen;
1836     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
1837         return false;
1838
1839     cgen = self->field->expression.codegen;
1840     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
1841         return false;
1842
1843     if (lvalue) {
1844         /* address! */
1845         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
1846                                             ent, field);
1847     } else {
1848         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
1849                                              ent, field, self->expression.vtype);
1850     }
1851     if (!*out) {
1852         asterror(ast_ctx(self), "failed to create %s instruction (output type %s)",
1853                  (lvalue ? "ADDRESS" : "FIELD"),
1854                  type_name[self->expression.vtype]);
1855         return false;
1856     }
1857
1858     if (lvalue)
1859         self->expression.outl = *out;
1860     else
1861         self->expression.outr = *out;
1862
1863     /* Hm that should be it... */
1864     return true;
1865 }
1866
1867 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
1868 {
1869     ast_expression_codegen *cgen;
1870     ir_value *vec;
1871
1872     /* in QC this is always an lvalue */
1873     (void)lvalue;
1874     if (self->expression.outl) {
1875         *out = self->expression.outl;
1876         return true;
1877     }
1878
1879     cgen = self->owner->expression.codegen;
1880     if (!(*cgen)((ast_expression*)(self->owner), func, true, &vec))
1881         return false;
1882
1883     if (vec->vtype != TYPE_VECTOR &&
1884         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
1885     {
1886         return false;
1887     }
1888
1889     *out = ir_value_vector_member(vec, self->field);
1890     self->expression.outl = *out;
1891
1892     return (*out != NULL);
1893 }
1894
1895 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
1896 {
1897     ast_value *arr;
1898     ast_value *idx;
1899
1900     if (!lvalue && self->expression.outr) {
1901         *out = self->expression.outr;
1902     }
1903     if (lvalue && self->expression.outl) {
1904         *out = self->expression.outl;
1905     }
1906
1907     if (!ast_istype(self->array, ast_value)) {
1908         asterror(ast_ctx(self), "array indexing this way is not supported");
1909         /* note this would actually be pointer indexing because the left side is
1910          * not an actual array but (hopefully) an indexable expression.
1911          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
1912          * support this path will be filled.
1913          */
1914         return false;
1915     }
1916
1917     arr = (ast_value*)self->array;
1918     idx = (ast_value*)self->index;
1919
1920     if (!ast_istype(self->index, ast_value) || !idx->isconst) {
1921         /* Time to use accessor functions */
1922         ast_expression_codegen *cgen;
1923         ir_value               *iridx, *funval;
1924         ir_instr               *call;
1925
1926         if (lvalue) {
1927             asterror(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
1928             return false;
1929         }
1930
1931         if (!arr->getter) {
1932             asterror(ast_ctx(self), "value has no getter, don't know how to index it");
1933             return false;
1934         }
1935
1936         cgen = self->index->expression.codegen;
1937         if (!(*cgen)((ast_expression*)(self->index), func, true, &iridx))
1938             return false;
1939
1940         cgen = arr->getter->expression.codegen;
1941         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
1942             return false;
1943
1944         call = ir_block_create_call(func->curblock, ast_function_label(func, "fetch"), funval);
1945         if (!call)
1946             return false;
1947         ir_call_param(call, iridx);
1948
1949         *out = ir_call_value(call);
1950         self->expression.outr = *out;
1951         return true;
1952     }
1953
1954     if (idx->expression.vtype == TYPE_FLOAT)
1955         *out = arr->ir_values[(int)idx->constval.vfloat];
1956     else if (idx->expression.vtype == TYPE_INTEGER)
1957         *out = arr->ir_values[idx->constval.vint];
1958     else {
1959         asterror(ast_ctx(self), "array indexing here needs an integer constant");
1960         return false;
1961     }
1962     return true;
1963 }
1964
1965 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
1966 {
1967     ast_expression_codegen *cgen;
1968
1969     ir_value *condval;
1970     ir_value *dummy;
1971
1972     ir_block *cond = func->curblock;
1973     ir_block *ontrue;
1974     ir_block *onfalse;
1975     ir_block *ontrue_endblock = NULL;
1976     ir_block *onfalse_endblock = NULL;
1977     ir_block *merge;
1978
1979     /* We don't output any value, thus also don't care about r/lvalue */
1980     (void)out;
1981     (void)lvalue;
1982
1983     if (self->expression.outr) {
1984         asterror(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
1985         return false;
1986     }
1987     self->expression.outr = (ir_value*)1;
1988
1989     /* generate the condition */
1990     cgen = self->cond->expression.codegen;
1991     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1992         return false;
1993     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
1994     cond = func->curblock;
1995
1996     /* on-true path */
1997
1998     if (self->on_true) {
1999         /* create on-true block */
2000         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
2001         if (!ontrue)
2002             return false;
2003
2004         /* enter the block */
2005         func->curblock = ontrue;
2006
2007         /* generate */
2008         cgen = self->on_true->expression.codegen;
2009         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2010             return false;
2011
2012         /* we now need to work from the current endpoint */
2013         ontrue_endblock = func->curblock;
2014     } else
2015         ontrue = NULL;
2016
2017     /* on-false path */
2018     if (self->on_false) {
2019         /* create on-false block */
2020         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
2021         if (!onfalse)
2022             return false;
2023
2024         /* enter the block */
2025         func->curblock = onfalse;
2026
2027         /* generate */
2028         cgen = self->on_false->expression.codegen;
2029         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2030             return false;
2031
2032         /* we now need to work from the current endpoint */
2033         onfalse_endblock = func->curblock;
2034     } else
2035         onfalse = NULL;
2036
2037     /* Merge block were they all merge in to */
2038     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
2039     if (!merge)
2040         return false;
2041     /* add jumps ot the merge block */
2042     if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, merge))
2043         return false;
2044     if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, merge))
2045         return false;
2046
2047     /* we create the if here, that way all blocks are ordered :)
2048      */
2049     if (!ir_block_create_if(cond, condval,
2050                             (ontrue  ? ontrue  : merge),
2051                             (onfalse ? onfalse : merge)))
2052     {
2053         return false;
2054     }
2055
2056     /* Now enter the merge block */
2057     func->curblock = merge;
2058
2059     return true;
2060 }
2061
2062 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2063 {
2064     ast_expression_codegen *cgen;
2065
2066     ir_value *condval;
2067     ir_value *trueval, *falseval;
2068     ir_instr *phi;
2069
2070     ir_block *cond = func->curblock;
2071     ir_block *ontrue;
2072     ir_block *onfalse;
2073     ir_block *merge;
2074
2075     /* Ternary can never create an lvalue... */
2076     if (lvalue)
2077         return false;
2078
2079     /* In theory it shouldn't be possible to pass through a node twice, but
2080      * in case we add any kind of optimization pass for the AST itself, it
2081      * may still happen, thus we remember a created ir_value and simply return one
2082      * if it already exists.
2083      */
2084     if (self->expression.outr) {
2085         *out = self->expression.outr;
2086         return true;
2087     }
2088
2089     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2090
2091     /* generate the condition */
2092     func->curblock = cond;
2093     cgen = self->cond->expression.codegen;
2094     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2095         return false;
2096
2097     /* create on-true block */
2098     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
2099     if (!ontrue)
2100         return false;
2101     else
2102     {
2103         /* enter the block */
2104         func->curblock = ontrue;
2105
2106         /* generate */
2107         cgen = self->on_true->expression.codegen;
2108         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2109             return false;
2110     }
2111
2112     /* create on-false block */
2113     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
2114     if (!onfalse)
2115         return false;
2116     else
2117     {
2118         /* enter the block */
2119         func->curblock = onfalse;
2120
2121         /* generate */
2122         cgen = self->on_false->expression.codegen;
2123         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2124             return false;
2125     }
2126
2127     /* create merge block */
2128     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
2129     if (!merge)
2130         return false;
2131     /* jump to merge block */
2132     if (!ir_block_create_jump(ontrue, merge))
2133         return false;
2134     if (!ir_block_create_jump(onfalse, merge))
2135         return false;
2136
2137     /* create if instruction */
2138     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
2139         return false;
2140
2141     /* Now enter the merge block */
2142     func->curblock = merge;
2143
2144     /* Here, now, we need a PHI node
2145      * but first some sanity checking...
2146      */
2147     if (trueval->vtype != falseval->vtype) {
2148         /* error("ternary with different types on the two sides"); */
2149         return false;
2150     }
2151
2152     /* create PHI */
2153     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
2154     if (!phi)
2155         return false;
2156     ir_phi_add(phi, ontrue,  trueval);
2157     ir_phi_add(phi, onfalse, falseval);
2158
2159     self->expression.outr = ir_phi_value(phi);
2160     *out = self->expression.outr;
2161
2162     return true;
2163 }
2164
2165 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2166 {
2167     ast_expression_codegen *cgen;
2168
2169     ir_value *dummy      = NULL;
2170     ir_value *precond    = NULL;
2171     ir_value *postcond   = NULL;
2172
2173     /* Since we insert some jumps "late" so we have blocks
2174      * ordered "nicely", we need to keep track of the actual end-blocks
2175      * of expressions to add the jumps to.
2176      */
2177     ir_block *bbody      = NULL, *end_bbody      = NULL;
2178     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2179     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2180     ir_block *bincrement = NULL, *end_bincrement = NULL;
2181     ir_block *bout       = NULL, *bin            = NULL;
2182
2183     /* let's at least move the outgoing block to the end */
2184     size_t    bout_id;
2185
2186     /* 'break' and 'continue' need to be able to find the right blocks */
2187     ir_block *bcontinue     = NULL;
2188     ir_block *bbreak        = NULL;
2189
2190     ir_block *old_bcontinue = NULL;
2191     ir_block *old_bbreak    = NULL;
2192
2193     ir_block *tmpblock      = NULL;
2194
2195     (void)lvalue;
2196     (void)out;
2197
2198     if (self->expression.outr) {
2199         asterror(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2200         return false;
2201     }
2202     self->expression.outr = (ir_value*)1;
2203
2204     /* NOTE:
2205      * Should we ever need some kind of block ordering, better make this function
2206      * move blocks around than write a block ordering algorithm later... after all
2207      * the ast and ir should work together, not against each other.
2208      */
2209
2210     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2211      * anyway if for example it contains a ternary.
2212      */
2213     if (self->initexpr)
2214     {
2215         cgen = self->initexpr->expression.codegen;
2216         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2217             return false;
2218     }
2219
2220     /* Store the block from which we enter this chaos */
2221     bin = func->curblock;
2222
2223     /* The pre-loop condition needs its own block since we
2224      * need to be able to jump to the start of that expression.
2225      */
2226     if (self->precond)
2227     {
2228         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
2229         if (!bprecond)
2230             return false;
2231
2232         /* the pre-loop-condition the least important place to 'continue' at */
2233         bcontinue = bprecond;
2234
2235         /* enter */
2236         func->curblock = bprecond;
2237
2238         /* generate */
2239         cgen = self->precond->expression.codegen;
2240         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2241             return false;
2242
2243         end_bprecond = func->curblock;
2244     } else {
2245         bprecond = end_bprecond = NULL;
2246     }
2247
2248     /* Now the next blocks won't be ordered nicely, but we need to
2249      * generate them this early for 'break' and 'continue'.
2250      */
2251     if (self->increment) {
2252         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
2253         if (!bincrement)
2254             return false;
2255         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2256     } else {
2257         bincrement = end_bincrement = NULL;
2258     }
2259
2260     if (self->postcond) {
2261         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
2262         if (!bpostcond)
2263             return false;
2264         bcontinue = bpostcond; /* postcond comes before the increment */
2265     } else {
2266         bpostcond = end_bpostcond = NULL;
2267     }
2268
2269     bout_id = vec_size(func->ir_func->blocks);
2270     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
2271     if (!bout)
2272         return false;
2273     bbreak = bout;
2274
2275     /* The loop body... */
2276     if (self->body)
2277     {
2278         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
2279         if (!bbody)
2280             return false;
2281
2282         /* enter */
2283         func->curblock = bbody;
2284
2285         old_bbreak          = func->breakblock;
2286         old_bcontinue       = func->continueblock;
2287         func->breakblock    = bbreak;
2288         func->continueblock = bcontinue;
2289
2290         /* generate */
2291         cgen = self->body->expression.codegen;
2292         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2293             return false;
2294
2295         end_bbody = func->curblock;
2296         func->breakblock    = old_bbreak;
2297         func->continueblock = old_bcontinue;
2298     }
2299
2300     /* post-loop-condition */
2301     if (self->postcond)
2302     {
2303         /* enter */
2304         func->curblock = bpostcond;
2305
2306         /* generate */
2307         cgen = self->postcond->expression.codegen;
2308         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2309             return false;
2310
2311         end_bpostcond = func->curblock;
2312     }
2313
2314     /* The incrementor */
2315     if (self->increment)
2316     {
2317         /* enter */
2318         func->curblock = bincrement;
2319
2320         /* generate */
2321         cgen = self->increment->expression.codegen;
2322         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2323             return false;
2324
2325         end_bincrement = func->curblock;
2326     }
2327
2328     /* In any case now, we continue from the outgoing block */
2329     func->curblock = bout;
2330
2331     /* Now all blocks are in place */
2332     /* From 'bin' we jump to whatever comes first */
2333     if      (bprecond)   tmpblock = bprecond;
2334     else if (bbody)      tmpblock = bbody;
2335     else if (bpostcond)  tmpblock = bpostcond;
2336     else                 tmpblock = bout;
2337     if (!ir_block_create_jump(bin, tmpblock))
2338         return false;
2339
2340     /* From precond */
2341     if (bprecond)
2342     {
2343         ir_block *ontrue, *onfalse;
2344         if      (bbody)      ontrue = bbody;
2345         else if (bincrement) ontrue = bincrement;
2346         else if (bpostcond)  ontrue = bpostcond;
2347         else                 ontrue = bprecond;
2348         onfalse = bout;
2349         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
2350             return false;
2351     }
2352
2353     /* from body */
2354     if (bbody)
2355     {
2356         if      (bincrement) tmpblock = bincrement;
2357         else if (bpostcond)  tmpblock = bpostcond;
2358         else if (bprecond)   tmpblock = bprecond;
2359         else                 tmpblock = bout;
2360         if (!end_bbody->final && !ir_block_create_jump(end_bbody, tmpblock))
2361             return false;
2362     }
2363
2364     /* from increment */
2365     if (bincrement)
2366     {
2367         if      (bpostcond)  tmpblock = bpostcond;
2368         else if (bprecond)   tmpblock = bprecond;
2369         else if (bbody)      tmpblock = bbody;
2370         else                 tmpblock = bout;
2371         if (!ir_block_create_jump(end_bincrement, tmpblock))
2372             return false;
2373     }
2374
2375     /* from postcond */
2376     if (bpostcond)
2377     {
2378         ir_block *ontrue, *onfalse;
2379         if      (bprecond)   ontrue = bprecond;
2380         else if (bbody)      ontrue = bbody;
2381         else if (bincrement) ontrue = bincrement;
2382         else                 ontrue = bpostcond;
2383         onfalse = bout;
2384         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
2385             return false;
2386     }
2387
2388     /* Move 'bout' to the end */
2389     vec_remove(func->ir_func->blocks, bout_id, 1);
2390     vec_push(func->ir_func->blocks, bout);
2391
2392     return true;
2393 }
2394
2395 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2396 {
2397     ir_block *target;
2398
2399     *out = NULL;
2400
2401     if (lvalue) {
2402         asterror(ast_ctx(self), "break/continue expression is not an l-value");
2403         return false;
2404     }
2405
2406     if (self->expression.outr) {
2407         asterror(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2408         return false;
2409     }
2410     self->expression.outr = (ir_value*)1;
2411
2412     if (self->is_continue)
2413         target = func->continueblock;
2414     else
2415         target = func->breakblock;
2416
2417     if (!ir_block_create_jump(func->curblock, target))
2418         return false;
2419     return true;
2420 }
2421
2422 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
2423 {
2424     ast_expression_codegen *cgen;
2425
2426     ast_switch_case *def_case  = NULL;
2427     ir_block        *def_bfall = NULL;
2428
2429     ir_value *dummy     = NULL;
2430     ir_value *irop      = NULL;
2431     ir_block *old_break = NULL;
2432     ir_block *bout      = NULL;
2433     ir_block *bfall     = NULL;
2434     size_t    bout_id;
2435     size_t    c;
2436
2437     char      typestr[1024];
2438     uint16_t  cmpinstr;
2439
2440     if (lvalue) {
2441         asterror(ast_ctx(self), "switch expression is not an l-value");
2442         return false;
2443     }
2444
2445     if (self->expression.outr) {
2446         asterror(ast_ctx(self), "internal error: ast_switch cannot be reused!");
2447         return false;
2448     }
2449     self->expression.outr = (ir_value*)1;
2450
2451     (void)lvalue;
2452     (void)out;
2453
2454     cgen = self->operand->expression.codegen;
2455     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
2456         return false;
2457
2458     if (!vec_size(self->cases))
2459         return true;
2460
2461     cmpinstr = type_eq_instr[irop->vtype];
2462     if (cmpinstr >= AINSTR_END) {
2463         ast_type_to_string(self->operand, typestr, sizeof(typestr));
2464         asterror(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
2465         return false;
2466     }
2467
2468     bout_id = vec_size(func->ir_func->blocks);
2469     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_switch"));
2470     if (!bout)
2471         return false;
2472
2473     /* setup the break block */
2474     old_break        = func->breakblock;
2475     func->breakblock = bout;
2476
2477     /* Now create all cases */
2478     for (c = 0; c < vec_size(self->cases); ++c) {
2479         ir_value *cond, *val;
2480         ir_block *bcase, *bnot;
2481         size_t bnot_id;
2482
2483         ast_switch_case *swcase = &self->cases[c];
2484
2485         if (swcase->value) {
2486             /* A regular case */
2487             /* generate the condition operand */
2488             cgen = swcase->value->expression.codegen;
2489             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
2490                 return false;
2491             /* generate the condition */
2492             cond = ir_block_create_binop(func->curblock, ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
2493             if (!cond)
2494                 return false;
2495
2496             bcase = ir_function_create_block(func->ir_func, ast_function_label(func, "case"));
2497             bnot_id = vec_size(func->ir_func->blocks);
2498             bnot = ir_function_create_block(func->ir_func, ast_function_label(func, "not_case"));
2499             if (!bcase || !bnot)
2500                 return false;
2501             if (!ir_block_create_if(func->curblock, cond, bcase, bnot))
2502                 return false;
2503
2504             /* Make the previous case-end fall through */
2505             if (bfall && !bfall->final) {
2506                 if (!ir_block_create_jump(bfall, bcase))
2507                     return false;
2508             }
2509
2510             /* enter the case */
2511             func->curblock = bcase;
2512             cgen = swcase->code->expression.codegen;
2513             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
2514                 return false;
2515
2516             /* remember this block to fall through from */
2517             bfall = func->curblock;
2518
2519             /* enter the else and move it down */
2520             func->curblock = bnot;
2521             vec_remove(func->ir_func->blocks, bnot_id, 1);
2522             vec_push(func->ir_func->blocks, bnot);
2523         } else {
2524             /* The default case */
2525             /* Remember where to fall through from: */
2526             def_bfall = bfall;
2527             bfall     = NULL;
2528             /* remember which case it was */
2529             def_case  = swcase;
2530         }
2531     }
2532
2533     /* Jump from the last bnot to bout */
2534     if (bfall && !bfall->final && !ir_block_create_jump(bfall, bout)) {
2535         /*
2536         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
2537         */
2538         return false;
2539     }
2540
2541     /* If there was a default case, put it down here */
2542     if (def_case) {
2543         ir_block *bcase;
2544
2545         /* No need to create an extra block */
2546         bcase = func->curblock;
2547
2548         /* Insert the fallthrough jump */
2549         if (def_bfall && !def_bfall->final) {
2550             if (!ir_block_create_jump(def_bfall, bcase))
2551                 return false;
2552         }
2553
2554         /* Now generate the default code */
2555         cgen = def_case->code->expression.codegen;
2556         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
2557             return false;
2558     }
2559
2560     /* Jump from the last bnot to bout */
2561     if (!func->curblock->final && !ir_block_create_jump(func->curblock, bout))
2562         return false;
2563     /* enter the outgoing block */
2564     func->curblock = bout;
2565
2566     /* restore the break block */
2567     func->breakblock = old_break;
2568
2569     /* Move 'bout' to the end, it's nicer */
2570     vec_remove(func->ir_func->blocks, bout_id, 1);
2571     vec_push(func->ir_func->blocks, bout);
2572
2573     return true;
2574 }
2575
2576 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
2577 {
2578     ast_expression_codegen *cgen;
2579     ir_value              **params;
2580     ir_instr               *callinstr;
2581     size_t i;
2582
2583     ir_value *funval = NULL;
2584
2585     /* return values are never lvalues */
2586     if (lvalue) {
2587         asterror(ast_ctx(self), "not an l-value (function call)");
2588         return false;
2589     }
2590
2591     if (self->expression.outr) {
2592         *out = self->expression.outr;
2593         return true;
2594     }
2595
2596     cgen = self->func->expression.codegen;
2597     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
2598         return false;
2599     if (!funval)
2600         return false;
2601
2602     params = NULL;
2603
2604     /* parameters */
2605     for (i = 0; i < vec_size(self->params); ++i)
2606     {
2607         ir_value *param;
2608         ast_expression *expr = self->params[i];
2609
2610         cgen = expr->expression.codegen;
2611         if (!(*cgen)(expr, func, false, &param))
2612             goto error;
2613         if (!param)
2614             goto error;
2615         vec_push(params, param);
2616     }
2617
2618     callinstr = ir_block_create_call(func->curblock, ast_function_label(func, "call"), funval);
2619     if (!callinstr)
2620         goto error;
2621
2622     for (i = 0; i < vec_size(params); ++i) {
2623         ir_call_param(callinstr, params[i]);
2624     }
2625
2626     *out = ir_call_value(callinstr);
2627     self->expression.outr = *out;
2628
2629     vec_free(params);
2630     return true;
2631 error:
2632     vec_free(params);
2633     return false;
2634 }