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