]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
More verbose error for invalid parameter types
[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     return self;
656 }
657
658 void ast_ternary_delete(ast_ternary *self)
659 {
660     ast_unref(self->cond);
661     ast_unref(self->on_true);
662     ast_unref(self->on_false);
663     ast_expression_delete((ast_expression*)self);
664     mem_d(self);
665 }
666
667 ast_loop* ast_loop_new(lex_ctx ctx,
668                        ast_expression *initexpr,
669                        ast_expression *precond,
670                        ast_expression *postcond,
671                        ast_expression *increment,
672                        ast_expression *body)
673 {
674     ast_instantiate(ast_loop, ctx, ast_loop_delete);
675     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
676
677     self->initexpr  = initexpr;
678     self->precond   = precond;
679     self->postcond  = postcond;
680     self->increment = increment;
681     self->body      = body;
682
683     return self;
684 }
685
686 void ast_loop_delete(ast_loop *self)
687 {
688     if (self->initexpr)
689         ast_unref(self->initexpr);
690     if (self->precond)
691         ast_unref(self->precond);
692     if (self->postcond)
693         ast_unref(self->postcond);
694     if (self->increment)
695         ast_unref(self->increment);
696     if (self->body)
697         ast_unref(self->body);
698     ast_expression_delete((ast_expression*)self);
699     mem_d(self);
700 }
701
702 ast_breakcont* ast_breakcont_new(lex_ctx ctx, bool iscont)
703 {
704     ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
705     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
706
707     self->is_continue = iscont;
708
709     return self;
710 }
711
712 void ast_breakcont_delete(ast_breakcont *self)
713 {
714     ast_expression_delete((ast_expression*)self);
715     mem_d(self);
716 }
717
718 ast_switch* ast_switch_new(lex_ctx ctx, ast_expression *op)
719 {
720     ast_instantiate(ast_switch, ctx, ast_switch_delete);
721     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
722
723     self->operand = op;
724     self->cases   = NULL;
725
726     return self;
727 }
728
729 void ast_switch_delete(ast_switch *self)
730 {
731     size_t i;
732     ast_unref(self->operand);
733
734     for (i = 0; i < vec_size(self->cases); ++i) {
735         if (self->cases[i].value)
736             ast_unref(self->cases[i].value);
737         ast_unref(self->cases[i].code);
738     }
739     vec_free(self->cases);
740
741     ast_expression_delete((ast_expression*)self);
742     mem_d(self);
743 }
744
745 ast_call* ast_call_new(lex_ctx ctx,
746                        ast_expression *funcexpr)
747 {
748     ast_instantiate(ast_call, ctx, ast_call_delete);
749     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
750
751     self->params = NULL;
752     self->func   = funcexpr;
753
754     self->expression.vtype = funcexpr->expression.next->expression.vtype;
755     if (funcexpr->expression.next->expression.next)
756         self->expression.next = ast_type_copy(ctx, funcexpr->expression.next->expression.next);
757
758     return self;
759 }
760
761 void ast_call_delete(ast_call *self)
762 {
763     size_t i;
764     for (i = 0; i < vec_size(self->params); ++i)
765         ast_unref(self->params[i]);
766     vec_free(self->params);
767
768     if (self->func)
769         ast_unref(self->func);
770
771     ast_expression_delete((ast_expression*)self);
772     mem_d(self);
773 }
774
775 bool ast_call_check_types(ast_call *self)
776 {
777     size_t i;
778     bool   retval = true;
779     const  ast_expression *func = self->func;
780     size_t count = vec_size(self->params);
781     if (count > vec_size(func->expression.params))
782         count = vec_size(func->expression.params);
783
784     for (i = 0; i < count; ++i) {
785         if (!ast_compare_type(self->params[i], (ast_expression*)(func->expression.params[i]))) {
786             char texp[1024];
787             char tgot[1024];
788             ast_type_to_string(self->params[i], tgot, sizeof(tgot));
789             ast_type_to_string((ast_expression*)func->expression.params[i], texp, sizeof(texp));
790             asterror(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
791                      (unsigned int)(i+1), texp, tgot);
792             /* we don't immediately return */
793             retval = false;
794         }
795     }
796     return retval;
797 }
798
799 ast_store* ast_store_new(lex_ctx ctx, int op,
800                          ast_expression *dest, ast_expression *source)
801 {
802     ast_instantiate(ast_store, ctx, ast_store_delete);
803     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
804
805     self->op = op;
806     self->dest = dest;
807     self->source = source;
808
809     self->expression.vtype = dest->expression.vtype;
810     if (dest->expression.next) {
811         self->expression.next = ast_type_copy(ctx, dest);
812         if (!self->expression.next) {
813             ast_delete(self);
814             return NULL;
815         }
816     }
817     else
818         self->expression.next = NULL;
819
820     return self;
821 }
822
823 void ast_store_delete(ast_store *self)
824 {
825     ast_unref(self->dest);
826     ast_unref(self->source);
827     ast_expression_delete((ast_expression*)self);
828     mem_d(self);
829 }
830
831 ast_block* ast_block_new(lex_ctx ctx)
832 {
833     ast_instantiate(ast_block, ctx, ast_block_delete);
834     ast_expression_init((ast_expression*)self,
835                         (ast_expression_codegen*)&ast_block_codegen);
836
837     self->locals  = NULL;
838     self->exprs   = NULL;
839     self->collect = NULL;
840
841     return self;
842 }
843
844 void ast_block_collect(ast_block *self, ast_expression *expr)
845 {
846     vec_push(self->collect, expr);
847     expr->expression.node.keep = true;
848 }
849
850 void ast_block_delete(ast_block *self)
851 {
852     size_t i;
853     for (i = 0; i < vec_size(self->exprs); ++i)
854         ast_unref(self->exprs[i]);
855     vec_free(self->exprs);
856     for (i = 0; i < vec_size(self->locals); ++i)
857         ast_delete(self->locals[i]);
858     vec_free(self->locals);
859     for (i = 0; i < vec_size(self->collect); ++i)
860         ast_delete(self->collect[i]);
861     vec_free(self->collect);
862     ast_expression_delete((ast_expression*)self);
863     mem_d(self);
864 }
865
866 bool ast_block_set_type(ast_block *self, ast_expression *from)
867 {
868     if (self->expression.next)
869         ast_delete(self->expression.next);
870     self->expression.vtype = from->expression.vtype;
871     if (from->expression.next) {
872         self->expression.next = ast_type_copy(self->expression.node.context, from->expression.next);
873         if (!self->expression.next)
874             return false;
875     }
876     else
877         self->expression.next = NULL;
878     return true;
879 }
880
881 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
882 {
883     ast_instantiate(ast_function, ctx, ast_function_delete);
884
885     if (!vtype ||
886         vtype->isconst ||
887         vtype->expression.vtype != TYPE_FUNCTION)
888     {
889         mem_d(self);
890         return NULL;
891     }
892
893     self->vtype  = vtype;
894     self->name   = name ? util_strdup(name) : NULL;
895     self->blocks = NULL;
896
897     self->labelcount = 0;
898     self->builtin = 0;
899
900     self->ir_func = NULL;
901     self->curblock = NULL;
902
903     self->breakblock    = NULL;
904     self->continueblock = NULL;
905
906     vtype->isconst = true;
907     vtype->constval.vfunc = self;
908
909     return self;
910 }
911
912 void ast_function_delete(ast_function *self)
913 {
914     size_t i;
915     if (self->name)
916         mem_d((void*)self->name);
917     if (self->vtype) {
918         /* ast_value_delete(self->vtype); */
919         self->vtype->isconst = false;
920         self->vtype->constval.vfunc = NULL;
921         /* We use unref - if it was stored in a global table it is supposed
922          * to be deleted from *there*
923          */
924         ast_unref(self->vtype);
925     }
926     for (i = 0; i < vec_size(self->blocks); ++i)
927         ast_delete(self->blocks[i]);
928     vec_free(self->blocks);
929     mem_d(self);
930 }
931
932 const char* ast_function_label(ast_function *self, const char *prefix)
933 {
934     size_t id;
935     size_t len;
936     char  *from;
937
938     if (!opts_dump)
939         return NULL;
940
941     id  = (self->labelcount++);
942     len = strlen(prefix);
943
944     from = self->labelbuf + sizeof(self->labelbuf)-1;
945     *from-- = 0;
946     do {
947         unsigned int digit = id % 10;
948         *from = digit + '0';
949         id /= 10;
950     } while (id);
951     memcpy(from - len, prefix, len);
952     return from - len;
953 }
954
955 /*********************************************************************/
956 /* AST codegen part
957  * by convention you must never pass NULL to the 'ir_value **out'
958  * parameter. If you really don't care about the output, pass a dummy.
959  * But I can't imagine a pituation where the output is truly unnecessary.
960  */
961
962 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
963 {
964     /* NOTE: This is the codegen for a variable used in an expression.
965      * It is not the codegen to generate the value. For this purpose,
966      * ast_local_codegen and ast_global_codegen are to be used before this
967      * is executed. ast_function_codegen should take care of its locals,
968      * and the ast-user should take care of ast_global_codegen to be used
969      * on all the globals.
970      */
971     if (!self->ir_v) {
972         char typename[1024];
973         ast_type_to_string((ast_expression*)self, typename, sizeof(typename));
974         asterror(ast_ctx(self), "ast_value used before generated %s %s", typename, self->name);
975         return false;
976     }
977     *out = self->ir_v;
978     return true;
979 }
980
981 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
982 {
983     ir_value *v = NULL;
984
985     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
986     {
987         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
988         if (!func)
989             return false;
990         func->context = ast_ctx(self);
991         func->value->context = ast_ctx(self);
992
993         self->constval.vfunc->ir_func = func;
994         self->ir_v = func->value;
995         /* The function is filled later on ast_function_codegen... */
996         return true;
997     }
998
999     if (isfield && self->expression.vtype == TYPE_FIELD) {
1000         ast_expression *fieldtype = self->expression.next;
1001
1002         if (self->isconst) {
1003             asterror(ast_ctx(self), "TODO: constant field pointers with value");
1004             goto error;
1005         }
1006
1007         if (fieldtype->expression.vtype == TYPE_ARRAY) {
1008             size_t ai;
1009             char   *name;
1010             size_t  namelen;
1011
1012             ast_expression_common *elemtype;
1013             int                    vtype;
1014             ast_value             *array = (ast_value*)fieldtype;
1015
1016             if (!ast_istype(fieldtype, ast_value)) {
1017                 asterror(ast_ctx(self), "internal error: ast_value required");
1018                 return false;
1019             }
1020
1021             /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1022             if (!array->expression.count || array->expression.count > opts_max_array_size)
1023                 asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1024
1025             elemtype = &array->expression.next->expression;
1026             vtype = elemtype->vtype;
1027
1028             v = ir_builder_create_field(ir, self->name, vtype);
1029             if (!v) {
1030                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1031                 return false;
1032             }
1033             if (vtype == TYPE_FIELD)
1034                 v->fieldtype = elemtype->next->expression.vtype;
1035             v->context = ast_ctx(self);
1036             array->ir_v = self->ir_v = v;
1037
1038             namelen = strlen(self->name);
1039             name    = (char*)mem_a(namelen + 16);
1040             strcpy(name, self->name);
1041
1042             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1043             array->ir_values[0] = v;
1044             for (ai = 1; ai < array->expression.count; ++ai) {
1045                 snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1046                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1047                 if (!array->ir_values[ai]) {
1048                     mem_d(name);
1049                     asterror(ast_ctx(self), "ir_builder_create_global failed");
1050                     return false;
1051                 }
1052                 if (vtype == TYPE_FIELD)
1053                     array->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1054                 array->ir_values[ai]->context = ast_ctx(self);
1055             }
1056             mem_d(name);
1057         }
1058         else
1059         {
1060             v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
1061             if (!v)
1062                 return false;
1063             v->context = ast_ctx(self);
1064             self->ir_v = v;
1065         }
1066         return true;
1067     }
1068
1069     if (self->expression.vtype == TYPE_ARRAY) {
1070         size_t ai;
1071         char   *name;
1072         size_t  namelen;
1073
1074         ast_expression_common *elemtype = &self->expression.next->expression;
1075         int vtype = elemtype->vtype;
1076
1077         /* same as with field arrays */
1078         if (!self->expression.count || self->expression.count > opts_max_array_size)
1079             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1080
1081         v = ir_builder_create_global(ir, self->name, vtype);
1082         if (!v) {
1083             asterror(ast_ctx(self), "ir_builder_create_global failed");
1084             return false;
1085         }
1086         if (vtype == TYPE_FIELD)
1087             v->fieldtype = elemtype->next->expression.vtype;
1088         v->context = ast_ctx(self);
1089
1090         namelen = strlen(self->name);
1091         name    = (char*)mem_a(namelen + 16);
1092         strcpy(name, self->name);
1093
1094         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1095         self->ir_values[0] = v;
1096         for (ai = 1; ai < self->expression.count; ++ai) {
1097             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1098             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1099             if (!self->ir_values[ai]) {
1100                 mem_d(name);
1101                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1102                 return false;
1103             }
1104             if (vtype == TYPE_FIELD)
1105                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1106             self->ir_values[ai]->context = ast_ctx(self);
1107         }
1108         mem_d(name);
1109     }
1110     else
1111     {
1112         /* Arrays don't do this since there's no "array" value which spans across the
1113          * whole thing.
1114          */
1115         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1116         if (!v) {
1117             asterror(ast_ctx(self), "ir_builder_create_global failed");
1118             return false;
1119         }
1120         if (self->expression.vtype == TYPE_FIELD)
1121             v->fieldtype = self->expression.next->expression.vtype;
1122         v->context = ast_ctx(self);
1123     }
1124
1125     if (self->isconst) {
1126         switch (self->expression.vtype)
1127         {
1128             case TYPE_FLOAT:
1129                 if (!ir_value_set_float(v, self->constval.vfloat))
1130                     goto error;
1131                 break;
1132             case TYPE_VECTOR:
1133                 if (!ir_value_set_vector(v, self->constval.vvec))
1134                     goto error;
1135                 break;
1136             case TYPE_STRING:
1137                 if (!ir_value_set_string(v, self->constval.vstring))
1138                     goto error;
1139                 break;
1140             case TYPE_ARRAY:
1141                 asterror(ast_ctx(self), "TODO: global constant array");
1142                 break;
1143             case TYPE_FUNCTION:
1144                 asterror(ast_ctx(self), "global of type function not properly generated");
1145                 goto error;
1146                 /* Cannot generate an IR value for a function,
1147                  * need a pointer pointing to a function rather.
1148                  */
1149             default:
1150                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1151                 break;
1152         }
1153     }
1154
1155     /* link us to the ir_value */
1156     self->ir_v = v;
1157     return true;
1158
1159 error: /* clean up */
1160     ir_value_delete(v);
1161     return false;
1162 }
1163
1164 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1165 {
1166     ir_value *v = NULL;
1167     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
1168     {
1169         /* Do we allow local functions? I think not...
1170          * this is NOT a function pointer atm.
1171          */
1172         return false;
1173     }
1174
1175     if (self->expression.vtype == TYPE_ARRAY) {
1176         size_t ai;
1177         char   *name;
1178         size_t  namelen;
1179
1180         ast_expression_common *elemtype = &self->expression.next->expression;
1181         int vtype = elemtype->vtype;
1182
1183         if (param) {
1184             asterror(ast_ctx(self), "array-parameters are not supported");
1185             return false;
1186         }
1187
1188         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1189         if (!self->expression.count || self->expression.count > opts_max_array_size) {
1190             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1191         }
1192
1193         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1194         if (!self->ir_values) {
1195             asterror(ast_ctx(self), "failed to allocate array values");
1196             return false;
1197         }
1198
1199         v = ir_function_create_local(func, self->name, vtype, param);
1200         if (!v) {
1201             asterror(ast_ctx(self), "ir_function_create_local failed");
1202             return false;
1203         }
1204         if (vtype == TYPE_FIELD)
1205             v->fieldtype = elemtype->next->expression.vtype;
1206         v->context = ast_ctx(self);
1207
1208         namelen = strlen(self->name);
1209         name    = (char*)mem_a(namelen + 16);
1210         strcpy(name, self->name);
1211
1212         self->ir_values[0] = v;
1213         for (ai = 1; ai < self->expression.count; ++ai) {
1214             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1215             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1216             if (!self->ir_values[ai]) {
1217                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1218                 return false;
1219             }
1220             if (vtype == TYPE_FIELD)
1221                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1222             self->ir_values[ai]->context = ast_ctx(self);
1223         }
1224     }
1225     else
1226     {
1227         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1228         if (!v)
1229             return false;
1230         if (self->expression.vtype == TYPE_FIELD)
1231             v->fieldtype = self->expression.next->expression.vtype;
1232         v->context = ast_ctx(self);
1233     }
1234
1235     /* A constant local... hmmm...
1236      * I suppose the IR will have to deal with this
1237      */
1238     if (self->isconst) {
1239         switch (self->expression.vtype)
1240         {
1241             case TYPE_FLOAT:
1242                 if (!ir_value_set_float(v, self->constval.vfloat))
1243                     goto error;
1244                 break;
1245             case TYPE_VECTOR:
1246                 if (!ir_value_set_vector(v, self->constval.vvec))
1247                     goto error;
1248                 break;
1249             case TYPE_STRING:
1250                 if (!ir_value_set_string(v, self->constval.vstring))
1251                     goto error;
1252                 break;
1253             default:
1254                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1255                 break;
1256         }
1257     }
1258
1259     /* link us to the ir_value */
1260     self->ir_v = v;
1261
1262     if (self->setter) {
1263         if (!ast_global_codegen(self->setter, func->owner, false) ||
1264             !ast_function_codegen(self->setter->constval.vfunc, func->owner) ||
1265             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1266             return false;
1267     }
1268     if (self->getter) {
1269         if (!ast_global_codegen(self->getter, func->owner, false) ||
1270             !ast_function_codegen(self->getter->constval.vfunc, func->owner) ||
1271             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1272             return false;
1273     }
1274     return true;
1275
1276 error: /* clean up */
1277     ir_value_delete(v);
1278     return false;
1279 }
1280
1281 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1282 {
1283     ir_function *irf;
1284     ir_value    *dummy;
1285     ast_expression_common *ec;
1286     size_t    i;
1287
1288     irf = self->ir_func;
1289     if (!irf) {
1290         asterror(ast_ctx(self), "ast_function's related ast_value was not generated yet");
1291         return false;
1292     }
1293
1294     /* fill the parameter list */
1295     ec = &self->vtype->expression;
1296     for (i = 0; i < vec_size(ec->params); ++i)
1297     {
1298         vec_push(irf->params, ec->params[i]->expression.vtype);
1299         if (!self->builtin) {
1300             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1301                 return false;
1302         }
1303     }
1304
1305     if (self->builtin) {
1306         irf->builtin = self->builtin;
1307         return true;
1308     }
1309
1310     if (!vec_size(self->blocks)) {
1311         asterror(ast_ctx(self), "function `%s` has no body", self->name);
1312         return false;
1313     }
1314
1315     self->curblock = ir_function_create_block(irf, "entry");
1316     if (!self->curblock) {
1317         asterror(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1318         return false;
1319     }
1320
1321     for (i = 0; i < vec_size(self->blocks); ++i) {
1322         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
1323         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
1324             return false;
1325     }
1326
1327     /* TODO: check return types */
1328     if (!self->curblock->is_return)
1329     {
1330         return ir_block_create_return(self->curblock, NULL);
1331         /* From now on the parser has to handle this situation */
1332 #if 0
1333         if (!self->vtype->expression.next ||
1334             self->vtype->expression.next->expression.vtype == TYPE_VOID)
1335         {
1336             return ir_block_create_return(self->curblock, NULL);
1337         }
1338         else
1339         {
1340             /* error("missing return"); */
1341             asterror(ast_ctx(self), "function `%s` missing return value", self->name);
1342             return false;
1343         }
1344 #endif
1345     }
1346     return true;
1347 }
1348
1349 /* Note, you will not see ast_block_codegen generate ir_blocks.
1350  * To the AST and the IR, blocks are 2 different things.
1351  * In the AST it represents a block of code, usually enclosed in
1352  * curly braces {...}.
1353  * While in the IR it represents a block in terms of control-flow.
1354  */
1355 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1356 {
1357     size_t i;
1358
1359     /* We don't use this
1360      * Note: an ast-representation using the comma-operator
1361      * of the form: (a, b, c) = x should not assign to c...
1362      */
1363     if (lvalue) {
1364         asterror(ast_ctx(self), "not an l-value (code-block)");
1365         return false;
1366     }
1367
1368     if (self->expression.outr) {
1369         *out = self->expression.outr;
1370         return true;
1371     }
1372
1373     /* output is NULL at first, we'll have each expression
1374      * assign to out output, thus, a comma-operator represention
1375      * using an ast_block will return the last generated value,
1376      * so: (b, c) + a  executed both b and c, and returns c,
1377      * which is then added to a.
1378      */
1379     *out = NULL;
1380
1381     /* generate locals */
1382     for (i = 0; i < vec_size(self->locals); ++i)
1383     {
1384         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1385             if (opts_debug)
1386                 asterror(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1387             return false;
1388         }
1389     }
1390
1391     for (i = 0; i < vec_size(self->exprs); ++i)
1392     {
1393         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
1394         if (func->curblock->final) {
1395             asterror(ast_ctx(self->exprs[i]), "unreachable statement");
1396             return false;
1397         }
1398         if (!(*gen)(self->exprs[i], func, false, out))
1399             return false;
1400     }
1401
1402     self->expression.outr = *out;
1403
1404     return true;
1405 }
1406
1407 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1408 {
1409     ast_expression_codegen *cgen;
1410     ir_value *left, *right;
1411
1412     ast_value       *arr;
1413     ast_value       *idx;
1414     ast_array_index *ai = NULL;
1415
1416     if (lvalue && self->expression.outl) {
1417         *out = self->expression.outl;
1418         return true;
1419     }
1420
1421     if (!lvalue && self->expression.outr) {
1422         *out = self->expression.outr;
1423         return true;
1424     }
1425
1426     if (ast_istype(self->dest, ast_array_index))
1427     {
1428
1429         ai = (ast_array_index*)self->dest;
1430         idx = (ast_value*)ai->index;
1431
1432         if (ast_istype(ai->index, ast_value) && idx->isconst)
1433             ai = NULL;
1434     }
1435
1436     if (ai) {
1437         /* we need to call the setter */
1438         ir_value  *iridx, *funval;
1439         ir_instr  *call;
1440
1441         if (lvalue) {
1442             asterror(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1443             return false;
1444         }
1445
1446         arr = (ast_value*)ai->array;
1447         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1448             asterror(ast_ctx(self), "value has no setter (%s)", arr->name);
1449             return false;
1450         }
1451
1452         cgen = idx->expression.codegen;
1453         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1454             return false;
1455
1456         cgen = arr->setter->expression.codegen;
1457         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1458             return false;
1459
1460         cgen = self->source->expression.codegen;
1461         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1462             return false;
1463
1464         call = ir_block_create_call(func->curblock, ast_function_label(func, "store"), funval);
1465         if (!call)
1466             return false;
1467         ir_call_param(call, iridx);
1468         ir_call_param(call, right);
1469         self->expression.outr = right;
1470     }
1471     else
1472     {
1473         /* regular code */
1474
1475         cgen = self->dest->expression.codegen;
1476         /* lvalue! */
1477         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1478             return false;
1479         self->expression.outl = left;
1480
1481         cgen = self->source->expression.codegen;
1482         /* rvalue! */
1483         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1484             return false;
1485
1486         if (!ir_block_create_store_op(func->curblock, self->op, left, right))
1487             return false;
1488         self->expression.outr = right;
1489     }
1490
1491     /* Theoretically, an assinment returns its left side as an
1492      * lvalue, if we don't need an lvalue though, we return
1493      * the right side as an rvalue, otherwise we have to
1494      * somehow know whether or not we need to dereference the pointer
1495      * on the left side - that is: OP_LOAD if it was an address.
1496      * Also: in original QC we cannot OP_LOADP *anyway*.
1497      */
1498     *out = (lvalue ? left : right);
1499
1500     return true;
1501 }
1502
1503 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1504 {
1505     ast_expression_codegen *cgen;
1506     ir_value *left, *right;
1507
1508     /* A binary operation cannot yield an l-value */
1509     if (lvalue) {
1510         asterror(ast_ctx(self), "not an l-value (binop)");
1511         return false;
1512     }
1513
1514     if (self->expression.outr) {
1515         *out = self->expression.outr;
1516         return true;
1517     }
1518
1519     if (OPTS_FLAG(SHORT_LOGIC) &&
1520         (self->op == INSTR_AND || self->op == INSTR_OR))
1521     {
1522         /* short circuit evaluation */
1523         ir_block *other, *merge;
1524         ir_block *from_left, *from_right;
1525         ir_instr *phi;
1526         size_t    merge_id;
1527         uint16_t  notop;
1528
1529         /* Note about casting to true boolean values:
1530          * We use a single NOT for sub expressions, and an
1531          * overall NOT at the end, and for that purpose swap
1532          * all the jump conditions in order for the NOT to get
1533          * doubled.
1534          * ie: (a && b) usually becomes (!!a ? !!b : !!a)
1535          * but we translate this to (!(!a ? !a : !b))
1536          */
1537
1538         merge_id = vec_size(func->ir_func->blocks);
1539         merge = ir_function_create_block(func->ir_func, ast_function_label(func, "sce_merge"));
1540
1541         cgen = self->left->expression.codegen;
1542         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1543             return false;
1544         if (!OPTS_FLAG(PERL_LOGIC)) {
1545             notop = type_not_instr[left->vtype];
1546             if (notop == AINSTR_END) {
1547                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1548                 return false;
1549             }
1550             left = ir_block_create_unary(func->curblock,
1551                                          ast_function_label(func, "sce_not"),
1552                                          notop,
1553                                          left);
1554         }
1555         from_left = func->curblock;
1556
1557         other = ir_function_create_block(func->ir_func, ast_function_label(func, "sce_other"));
1558         if ( !(self->op == INSTR_OR) != !OPTS_FLAG(PERL_LOGIC) ) {
1559             if (!ir_block_create_if(func->curblock, left, other, merge))
1560                 return false;
1561         } else {
1562             if (!ir_block_create_if(func->curblock, left, merge, other))
1563                 return false;
1564         }
1565         /* use the likely flag */
1566         vec_last(func->curblock->instr)->likely = true;
1567
1568         func->curblock = other;
1569         cgen = self->right->expression.codegen;
1570         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1571             return false;
1572         if (!OPTS_FLAG(PERL_LOGIC)) {
1573             notop = type_not_instr[right->vtype];
1574             if (notop == AINSTR_END) {
1575                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1576                 return false;
1577             }
1578             right = ir_block_create_unary(func->curblock,
1579                                           ast_function_label(func, "sce_not"),
1580                                           notop,
1581                                           right);
1582         }
1583         from_right = func->curblock;
1584
1585         if (!ir_block_create_jump(func->curblock, merge))
1586             return false;
1587
1588         vec_remove(func->ir_func->blocks, merge_id, 1);
1589         vec_push(func->ir_func->blocks, merge);
1590
1591         func->curblock = merge;
1592         phi = ir_block_create_phi(func->curblock, ast_function_label(func, "sce_value"), TYPE_FLOAT);
1593         ir_phi_add(phi, from_left, left);
1594         ir_phi_add(phi, from_right, right);
1595         *out = ir_phi_value(phi);
1596         if (!OPTS_FLAG(PERL_LOGIC)) {
1597             notop = type_not_instr[(*out)->vtype];
1598             if (notop == AINSTR_END) {
1599                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1600                 return false;
1601             }
1602             *out = ir_block_create_unary(func->curblock,
1603                                          ast_function_label(func, "sce_final_not"),
1604                                          notop,
1605                                          *out);
1606         }
1607         if (!*out)
1608             return false;
1609         self->expression.outr = *out;
1610         return true;
1611     }
1612
1613     cgen = self->left->expression.codegen;
1614     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1615         return false;
1616
1617     cgen = self->right->expression.codegen;
1618     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1619         return false;
1620
1621     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
1622                                  self->op, left, right);
1623     if (!*out)
1624         return false;
1625     self->expression.outr = *out;
1626
1627     return true;
1628 }
1629
1630 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1631 {
1632     ast_expression_codegen *cgen;
1633     ir_value *leftl, *leftr, *right, *bin;
1634
1635     if (lvalue && self->expression.outl) {
1636         *out = self->expression.outl;
1637         return true;
1638     }
1639
1640     if (!lvalue && self->expression.outr) {
1641         *out = self->expression.outr;
1642         return true;
1643     }
1644
1645     /* for a binstore we need both an lvalue and an rvalue for the left side */
1646     /* rvalue of destination! */
1647     cgen = self->dest->expression.codegen;
1648     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
1649         return false;
1650
1651     /* source as rvalue only */
1652     cgen = self->source->expression.codegen;
1653     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1654         return false;
1655
1656     /* now the binary */
1657     bin = ir_block_create_binop(func->curblock, ast_function_label(func, "binst"),
1658                                 self->opbin, leftr, right);
1659     self->expression.outr = bin;
1660
1661     /* now store them */
1662     cgen = self->dest->expression.codegen;
1663     /* lvalue of destination */
1664     if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
1665         return false;
1666     self->expression.outl = leftl;
1667
1668     if (!ir_block_create_store_op(func->curblock, self->opstore, leftl, bin))
1669         return false;
1670     self->expression.outr = bin;
1671
1672     /* Theoretically, an assinment returns its left side as an
1673      * lvalue, if we don't need an lvalue though, we return
1674      * the right side as an rvalue, otherwise we have to
1675      * somehow know whether or not we need to dereference the pointer
1676      * on the left side - that is: OP_LOAD if it was an address.
1677      * Also: in original QC we cannot OP_LOADP *anyway*.
1678      */
1679     *out = (lvalue ? leftl : bin);
1680
1681     return true;
1682 }
1683
1684 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
1685 {
1686     ast_expression_codegen *cgen;
1687     ir_value *operand;
1688
1689     /* An unary operation cannot yield an l-value */
1690     if (lvalue) {
1691         asterror(ast_ctx(self), "not an l-value (binop)");
1692         return false;
1693     }
1694
1695     if (self->expression.outr) {
1696         *out = self->expression.outr;
1697         return true;
1698     }
1699
1700     cgen = self->operand->expression.codegen;
1701     /* lvalue! */
1702     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1703         return false;
1704
1705     *out = ir_block_create_unary(func->curblock, ast_function_label(func, "unary"),
1706                                  self->op, operand);
1707     if (!*out)
1708         return false;
1709     self->expression.outr = *out;
1710
1711     return true;
1712 }
1713
1714 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
1715 {
1716     ast_expression_codegen *cgen;
1717     ir_value *operand;
1718
1719     /* In the context of a return operation, we don't actually return
1720      * anything...
1721      */
1722     if (lvalue) {
1723         asterror(ast_ctx(self), "return-expression is not an l-value");
1724         return false;
1725     }
1726
1727     if (self->expression.outr) {
1728         asterror(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
1729         return false;
1730     }
1731     self->expression.outr = (ir_value*)1;
1732
1733     if (self->operand) {
1734         cgen = self->operand->expression.codegen;
1735         /* lvalue! */
1736         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1737             return false;
1738
1739         if (!ir_block_create_return(func->curblock, operand))
1740             return false;
1741     } else {
1742         if (!ir_block_create_return(func->curblock, NULL))
1743             return false;
1744     }
1745
1746     return true;
1747 }
1748
1749 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
1750 {
1751     ast_expression_codegen *cgen;
1752     ir_value *ent, *field;
1753
1754     /* This function needs to take the 'lvalue' flag into account!
1755      * As lvalue we provide a field-pointer, as rvalue we provide the
1756      * value in a temp.
1757      */
1758
1759     if (lvalue && self->expression.outl) {
1760         *out = self->expression.outl;
1761         return true;
1762     }
1763
1764     if (!lvalue && self->expression.outr) {
1765         *out = self->expression.outr;
1766         return true;
1767     }
1768
1769     cgen = self->entity->expression.codegen;
1770     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
1771         return false;
1772
1773     cgen = self->field->expression.codegen;
1774     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
1775         return false;
1776
1777     if (lvalue) {
1778         /* address! */
1779         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
1780                                             ent, field);
1781     } else {
1782         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
1783                                              ent, field, self->expression.vtype);
1784     }
1785     if (!*out) {
1786         asterror(ast_ctx(self), "failed to create %s instruction (output type %s)",
1787                  (lvalue ? "ADDRESS" : "FIELD"),
1788                  type_name[self->expression.vtype]);
1789         return false;
1790     }
1791
1792     if (lvalue)
1793         self->expression.outl = *out;
1794     else
1795         self->expression.outr = *out;
1796
1797     /* Hm that should be it... */
1798     return true;
1799 }
1800
1801 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
1802 {
1803     ast_expression_codegen *cgen;
1804     ir_value *vec;
1805
1806     /* in QC this is always an lvalue */
1807     (void)lvalue;
1808     if (self->expression.outl) {
1809         *out = self->expression.outl;
1810         return true;
1811     }
1812
1813     cgen = self->owner->expression.codegen;
1814     if (!(*cgen)((ast_expression*)(self->owner), func, true, &vec))
1815         return false;
1816
1817     if (vec->vtype != TYPE_VECTOR &&
1818         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
1819     {
1820         return false;
1821     }
1822
1823     *out = ir_value_vector_member(vec, self->field);
1824     self->expression.outl = *out;
1825
1826     return (*out != NULL);
1827 }
1828
1829 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
1830 {
1831     ast_value *arr;
1832     ast_value *idx;
1833
1834     if (!lvalue && self->expression.outr) {
1835         *out = self->expression.outr;
1836     }
1837     if (lvalue && self->expression.outl) {
1838         *out = self->expression.outl;
1839     }
1840
1841     if (!ast_istype(self->array, ast_value)) {
1842         asterror(ast_ctx(self), "array indexing this way is not supported");
1843         /* note this would actually be pointer indexing because the left side is
1844          * not an actual array but (hopefully) an indexable expression.
1845          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
1846          * support this path will be filled.
1847          */
1848         return false;
1849     }
1850
1851     arr = (ast_value*)self->array;
1852     idx = (ast_value*)self->index;
1853
1854     if (!ast_istype(self->index, ast_value) || !idx->isconst) {
1855         /* Time to use accessor functions */
1856         ast_expression_codegen *cgen;
1857         ir_value               *iridx, *funval;
1858         ir_instr               *call;
1859
1860         if (lvalue) {
1861             asterror(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
1862             return false;
1863         }
1864
1865         if (!arr->getter) {
1866             asterror(ast_ctx(self), "value has no getter, don't know how to index it");
1867             return false;
1868         }
1869
1870         cgen = self->index->expression.codegen;
1871         if (!(*cgen)((ast_expression*)(self->index), func, true, &iridx))
1872             return false;
1873
1874         cgen = arr->getter->expression.codegen;
1875         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
1876             return false;
1877
1878         call = ir_block_create_call(func->curblock, ast_function_label(func, "fetch"), funval);
1879         if (!call)
1880             return false;
1881         ir_call_param(call, iridx);
1882
1883         *out = ir_call_value(call);
1884         self->expression.outr = *out;
1885         return true;
1886     }
1887
1888     if (idx->expression.vtype == TYPE_FLOAT)
1889         *out = arr->ir_values[(int)idx->constval.vfloat];
1890     else if (idx->expression.vtype == TYPE_INTEGER)
1891         *out = arr->ir_values[idx->constval.vint];
1892     else {
1893         asterror(ast_ctx(self), "array indexing here needs an integer constant");
1894         return false;
1895     }
1896     return true;
1897 }
1898
1899 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
1900 {
1901     ast_expression_codegen *cgen;
1902
1903     ir_value *condval;
1904     ir_value *dummy;
1905
1906     ir_block *cond = func->curblock;
1907     ir_block *ontrue;
1908     ir_block *onfalse;
1909     ir_block *ontrue_endblock = NULL;
1910     ir_block *onfalse_endblock = NULL;
1911     ir_block *merge;
1912
1913     /* We don't output any value, thus also don't care about r/lvalue */
1914     (void)out;
1915     (void)lvalue;
1916
1917     if (self->expression.outr) {
1918         asterror(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
1919         return false;
1920     }
1921     self->expression.outr = (ir_value*)1;
1922
1923     /* generate the condition */
1924     func->curblock = cond;
1925     cgen = self->cond->expression.codegen;
1926     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1927         return false;
1928
1929     /* on-true path */
1930
1931     if (self->on_true) {
1932         /* create on-true block */
1933         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
1934         if (!ontrue)
1935             return false;
1936
1937         /* enter the block */
1938         func->curblock = ontrue;
1939
1940         /* generate */
1941         cgen = self->on_true->expression.codegen;
1942         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
1943             return false;
1944
1945         /* we now need to work from the current endpoint */
1946         ontrue_endblock = func->curblock;
1947     } else
1948         ontrue = NULL;
1949
1950     /* on-false path */
1951     if (self->on_false) {
1952         /* create on-false block */
1953         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
1954         if (!onfalse)
1955             return false;
1956
1957         /* enter the block */
1958         func->curblock = onfalse;
1959
1960         /* generate */
1961         cgen = self->on_false->expression.codegen;
1962         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
1963             return false;
1964
1965         /* we now need to work from the current endpoint */
1966         onfalse_endblock = func->curblock;
1967     } else
1968         onfalse = NULL;
1969
1970     /* Merge block were they all merge in to */
1971     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
1972     if (!merge)
1973         return false;
1974
1975     /* add jumps ot the merge block */
1976     if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, merge))
1977         return false;
1978     if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, merge))
1979         return false;
1980
1981     /* we create the if here, that way all blocks are ordered :)
1982      */
1983     if (!ir_block_create_if(cond, condval,
1984                             (ontrue  ? ontrue  : merge),
1985                             (onfalse ? onfalse : merge)))
1986     {
1987         return false;
1988     }
1989
1990     /* Now enter the merge block */
1991     func->curblock = merge;
1992
1993     return true;
1994 }
1995
1996 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
1997 {
1998     ast_expression_codegen *cgen;
1999
2000     ir_value *condval;
2001     ir_value *trueval, *falseval;
2002     ir_instr *phi;
2003
2004     ir_block *cond = func->curblock;
2005     ir_block *ontrue;
2006     ir_block *onfalse;
2007     ir_block *merge;
2008
2009     /* Ternary can never create an lvalue... */
2010     if (lvalue)
2011         return false;
2012
2013     /* In theory it shouldn't be possible to pass through a node twice, but
2014      * in case we add any kind of optimization pass for the AST itself, it
2015      * may still happen, thus we remember a created ir_value and simply return one
2016      * if it already exists.
2017      */
2018     if (self->expression.outr) {
2019         *out = self->expression.outr;
2020         return true;
2021     }
2022
2023     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2024
2025     /* generate the condition */
2026     func->curblock = cond;
2027     cgen = self->cond->expression.codegen;
2028     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2029         return false;
2030
2031     /* create on-true block */
2032     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
2033     if (!ontrue)
2034         return false;
2035     else
2036     {
2037         /* enter the block */
2038         func->curblock = ontrue;
2039
2040         /* generate */
2041         cgen = self->on_true->expression.codegen;
2042         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2043             return false;
2044     }
2045
2046     /* create on-false block */
2047     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
2048     if (!onfalse)
2049         return false;
2050     else
2051     {
2052         /* enter the block */
2053         func->curblock = onfalse;
2054
2055         /* generate */
2056         cgen = self->on_false->expression.codegen;
2057         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2058             return false;
2059     }
2060
2061     /* create merge block */
2062     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
2063     if (!merge)
2064         return false;
2065     /* jump to merge block */
2066     if (!ir_block_create_jump(ontrue, merge))
2067         return false;
2068     if (!ir_block_create_jump(onfalse, merge))
2069         return false;
2070
2071     /* create if instruction */
2072     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
2073         return false;
2074
2075     /* Now enter the merge block */
2076     func->curblock = merge;
2077
2078     /* Here, now, we need a PHI node
2079      * but first some sanity checking...
2080      */
2081     if (trueval->vtype != falseval->vtype) {
2082         /* error("ternary with different types on the two sides"); */
2083         return false;
2084     }
2085
2086     /* create PHI */
2087     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
2088     if (!phi)
2089         return false;
2090     ir_phi_add(phi, ontrue,  trueval);
2091     ir_phi_add(phi, onfalse, falseval);
2092
2093     self->expression.outr = ir_phi_value(phi);
2094     *out = self->expression.outr;
2095
2096     return true;
2097 }
2098
2099 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2100 {
2101     ast_expression_codegen *cgen;
2102
2103     ir_value *dummy      = NULL;
2104     ir_value *precond    = NULL;
2105     ir_value *postcond   = NULL;
2106
2107     /* Since we insert some jumps "late" so we have blocks
2108      * ordered "nicely", we need to keep track of the actual end-blocks
2109      * of expressions to add the jumps to.
2110      */
2111     ir_block *bbody      = NULL, *end_bbody      = NULL;
2112     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2113     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2114     ir_block *bincrement = NULL, *end_bincrement = NULL;
2115     ir_block *bout       = NULL, *bin            = NULL;
2116
2117     /* let's at least move the outgoing block to the end */
2118     size_t    bout_id;
2119
2120     /* 'break' and 'continue' need to be able to find the right blocks */
2121     ir_block *bcontinue     = NULL;
2122     ir_block *bbreak        = NULL;
2123
2124     ir_block *old_bcontinue = NULL;
2125     ir_block *old_bbreak    = NULL;
2126
2127     ir_block *tmpblock      = NULL;
2128
2129     (void)lvalue;
2130     (void)out;
2131
2132     if (self->expression.outr) {
2133         asterror(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2134         return false;
2135     }
2136     self->expression.outr = (ir_value*)1;
2137
2138     /* NOTE:
2139      * Should we ever need some kind of block ordering, better make this function
2140      * move blocks around than write a block ordering algorithm later... after all
2141      * the ast and ir should work together, not against each other.
2142      */
2143
2144     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2145      * anyway if for example it contains a ternary.
2146      */
2147     if (self->initexpr)
2148     {
2149         cgen = self->initexpr->expression.codegen;
2150         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2151             return false;
2152     }
2153
2154     /* Store the block from which we enter this chaos */
2155     bin = func->curblock;
2156
2157     /* The pre-loop condition needs its own block since we
2158      * need to be able to jump to the start of that expression.
2159      */
2160     if (self->precond)
2161     {
2162         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
2163         if (!bprecond)
2164             return false;
2165
2166         /* the pre-loop-condition the least important place to 'continue' at */
2167         bcontinue = bprecond;
2168
2169         /* enter */
2170         func->curblock = bprecond;
2171
2172         /* generate */
2173         cgen = self->precond->expression.codegen;
2174         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2175             return false;
2176
2177         end_bprecond = func->curblock;
2178     } else {
2179         bprecond = end_bprecond = NULL;
2180     }
2181
2182     /* Now the next blocks won't be ordered nicely, but we need to
2183      * generate them this early for 'break' and 'continue'.
2184      */
2185     if (self->increment) {
2186         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
2187         if (!bincrement)
2188             return false;
2189         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2190     } else {
2191         bincrement = end_bincrement = NULL;
2192     }
2193
2194     if (self->postcond) {
2195         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
2196         if (!bpostcond)
2197             return false;
2198         bcontinue = bpostcond; /* postcond comes before the increment */
2199     } else {
2200         bpostcond = end_bpostcond = NULL;
2201     }
2202
2203     bout_id = vec_size(func->ir_func->blocks);
2204     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
2205     if (!bout)
2206         return false;
2207     bbreak = bout;
2208
2209     /* The loop body... */
2210     if (self->body)
2211     {
2212         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
2213         if (!bbody)
2214             return false;
2215
2216         /* enter */
2217         func->curblock = bbody;
2218
2219         old_bbreak          = func->breakblock;
2220         old_bcontinue       = func->continueblock;
2221         func->breakblock    = bbreak;
2222         func->continueblock = bcontinue;
2223
2224         /* generate */
2225         cgen = self->body->expression.codegen;
2226         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2227             return false;
2228
2229         end_bbody = func->curblock;
2230         func->breakblock    = old_bbreak;
2231         func->continueblock = old_bcontinue;
2232     }
2233
2234     /* post-loop-condition */
2235     if (self->postcond)
2236     {
2237         /* enter */
2238         func->curblock = bpostcond;
2239
2240         /* generate */
2241         cgen = self->postcond->expression.codegen;
2242         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2243             return false;
2244
2245         end_bpostcond = func->curblock;
2246     }
2247
2248     /* The incrementor */
2249     if (self->increment)
2250     {
2251         /* enter */
2252         func->curblock = bincrement;
2253
2254         /* generate */
2255         cgen = self->increment->expression.codegen;
2256         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2257             return false;
2258
2259         end_bincrement = func->curblock;
2260     }
2261
2262     /* In any case now, we continue from the outgoing block */
2263     func->curblock = bout;
2264
2265     /* Now all blocks are in place */
2266     /* From 'bin' we jump to whatever comes first */
2267     if      (bprecond)   tmpblock = bprecond;
2268     else if (bbody)      tmpblock = bbody;
2269     else if (bpostcond)  tmpblock = bpostcond;
2270     else                 tmpblock = bout;
2271     if (!ir_block_create_jump(bin, tmpblock))
2272         return false;
2273
2274     /* From precond */
2275     if (bprecond)
2276     {
2277         ir_block *ontrue, *onfalse;
2278         if      (bbody)      ontrue = bbody;
2279         else if (bincrement) ontrue = bincrement;
2280         else if (bpostcond)  ontrue = bpostcond;
2281         else                 ontrue = bprecond;
2282         onfalse = bout;
2283         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
2284             return false;
2285     }
2286
2287     /* from body */
2288     if (bbody)
2289     {
2290         if      (bincrement) tmpblock = bincrement;
2291         else if (bpostcond)  tmpblock = bpostcond;
2292         else if (bprecond)   tmpblock = bprecond;
2293         else                 tmpblock = bout;
2294         if (!end_bbody->final && !ir_block_create_jump(end_bbody, tmpblock))
2295             return false;
2296     }
2297
2298     /* from increment */
2299     if (bincrement)
2300     {
2301         if      (bpostcond)  tmpblock = bpostcond;
2302         else if (bprecond)   tmpblock = bprecond;
2303         else if (bbody)      tmpblock = bbody;
2304         else                 tmpblock = bout;
2305         if (!ir_block_create_jump(end_bincrement, tmpblock))
2306             return false;
2307     }
2308
2309     /* from postcond */
2310     if (bpostcond)
2311     {
2312         ir_block *ontrue, *onfalse;
2313         if      (bprecond)   ontrue = bprecond;
2314         else if (bbody)      ontrue = bbody;
2315         else if (bincrement) ontrue = bincrement;
2316         else                 ontrue = bpostcond;
2317         onfalse = bout;
2318         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
2319             return false;
2320     }
2321
2322     /* Move 'bout' to the end */
2323     vec_remove(func->ir_func->blocks, bout_id, 1);
2324     vec_push(func->ir_func->blocks, bout);
2325
2326     return true;
2327 }
2328
2329 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2330 {
2331     ir_block *target;
2332
2333     if (lvalue) {
2334         asterror(ast_ctx(self), "break/continue expression is not an l-value");
2335         return false;
2336     }
2337
2338     if (self->expression.outr) {
2339         asterror(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2340         return false;
2341     }
2342     self->expression.outr = (ir_value*)1;
2343
2344     if (self->is_continue)
2345         target = func->continueblock;
2346     else
2347         target = func->breakblock;
2348
2349     if (!ir_block_create_jump(func->curblock, target))
2350         return false;
2351     return true;
2352 }
2353
2354 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
2355 {
2356     ast_expression_codegen *cgen;
2357
2358     ast_switch_case *def_case  = NULL;
2359     ir_block        *def_bfall = NULL;
2360
2361     ir_value *dummy     = NULL;
2362     ir_value *irop      = NULL;
2363     ir_block *old_break = NULL;
2364     ir_block *bout      = NULL;
2365     ir_block *bfall     = NULL;
2366     size_t    bout_id;
2367     size_t    c;
2368
2369     char      typestr[1024];
2370     uint16_t  cmpinstr;
2371
2372     if (lvalue) {
2373         asterror(ast_ctx(self), "switch expression is not an l-value");
2374         return false;
2375     }
2376
2377     if (self->expression.outr) {
2378         asterror(ast_ctx(self), "internal error: ast_switch cannot be reused!");
2379         return false;
2380     }
2381     self->expression.outr = (ir_value*)1;
2382
2383     (void)lvalue;
2384     (void)out;
2385
2386     cgen = self->operand->expression.codegen;
2387     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
2388         return false;
2389
2390     if (!vec_size(self->cases))
2391         return true;
2392
2393     cmpinstr = type_eq_instr[irop->vtype];
2394     if (cmpinstr >= AINSTR_END) {
2395         ast_type_to_string(self->operand, typestr, sizeof(typestr));
2396         asterror(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
2397         return false;
2398     }
2399
2400     bout_id = vec_size(func->ir_func->blocks);
2401     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_switch"));
2402     if (!bout)
2403         return false;
2404
2405     /* setup the break block */
2406     old_break        = func->breakblock;
2407     func->breakblock = bout;
2408
2409     /* Now create all cases */
2410     for (c = 0; c < vec_size(self->cases); ++c) {
2411         ir_value *cond, *val;
2412         ir_block *bcase, *bnot;
2413         size_t bnot_id;
2414
2415         ast_switch_case *swcase = &self->cases[c];
2416
2417         if (swcase->value) {
2418             /* A regular case */
2419             /* generate the condition operand */
2420             cgen = swcase->value->expression.codegen;
2421             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
2422                 return false;
2423             /* generate the condition */
2424             cond = ir_block_create_binop(func->curblock, ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
2425             if (!cond)
2426                 return false;
2427
2428             bcase = ir_function_create_block(func->ir_func, ast_function_label(func, "case"));
2429             bnot_id = vec_size(func->ir_func->blocks);
2430             bnot = ir_function_create_block(func->ir_func, ast_function_label(func, "not_case"));
2431             if (!bcase || !bnot)
2432                 return false;
2433             if (!ir_block_create_if(func->curblock, cond, bcase, bnot))
2434                 return false;
2435
2436             /* Make the previous case-end fall through */
2437             if (bfall && !bfall->final) {
2438                 if (!ir_block_create_jump(bfall, bcase))
2439                     return false;
2440             }
2441
2442             /* enter the case */
2443             func->curblock = bcase;
2444             cgen = swcase->code->expression.codegen;
2445             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
2446                 return false;
2447
2448             /* remember this block to fall through from */
2449             bfall = func->curblock;
2450
2451             /* enter the else and move it down */
2452             func->curblock = bnot;
2453             vec_remove(func->ir_func->blocks, bnot_id, 1);
2454             vec_push(func->ir_func->blocks, bnot);
2455         } else {
2456             /* The default case */
2457             /* Remember where to fall through from: */
2458             def_bfall = bfall;
2459             bfall     = NULL;
2460             /* remember which case it was */
2461             def_case  = swcase;
2462         }
2463     }
2464
2465     /* Jump from the last bnot to bout */
2466     if (bfall && !bfall->final && !ir_block_create_jump(bfall, bout)) {
2467         /*
2468         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
2469         */
2470         return false;
2471     }
2472
2473     /* If there was a default case, put it down here */
2474     if (def_case) {
2475         ir_block *bcase;
2476
2477         /* No need to create an extra block */
2478         bcase = func->curblock;
2479
2480         /* Insert the fallthrough jump */
2481         if (def_bfall && !def_bfall->final) {
2482             if (!ir_block_create_jump(def_bfall, bcase))
2483                 return false;
2484         }
2485
2486         /* Now generate the default code */
2487         cgen = def_case->code->expression.codegen;
2488         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
2489             return false;
2490     }
2491
2492     /* Jump from the last bnot to bout */
2493     if (!func->curblock->final && !ir_block_create_jump(func->curblock, bout))
2494         return false;
2495     /* enter the outgoing block */
2496     func->curblock = bout;
2497
2498     /* restore the break block */
2499     func->breakblock = old_break;
2500
2501     /* Move 'bout' to the end, it's nicer */
2502     vec_remove(func->ir_func->blocks, bout_id, 1);
2503     vec_push(func->ir_func->blocks, bout);
2504
2505     return true;
2506 }
2507
2508 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
2509 {
2510     ast_expression_codegen *cgen;
2511     ir_value              **params;
2512     ir_instr               *callinstr;
2513     size_t i;
2514
2515     ir_value *funval = NULL;
2516
2517     /* return values are never lvalues */
2518     if (lvalue) {
2519         asterror(ast_ctx(self), "not an l-value (function call)");
2520         return false;
2521     }
2522
2523     if (self->expression.outr) {
2524         *out = self->expression.outr;
2525         return true;
2526     }
2527
2528     cgen = self->func->expression.codegen;
2529     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
2530         return false;
2531     if (!funval)
2532         return false;
2533
2534     params = NULL;
2535
2536     /* parameters */
2537     for (i = 0; i < vec_size(self->params); ++i)
2538     {
2539         ir_value *param;
2540         ast_expression *expr = self->params[i];
2541
2542         cgen = expr->expression.codegen;
2543         if (!(*cgen)(expr, func, false, &param))
2544             goto error;
2545         if (!param)
2546             goto error;
2547         vec_push(params, param);
2548     }
2549
2550     callinstr = ir_block_create_call(func->curblock, ast_function_label(func, "call"), funval);
2551     if (!callinstr)
2552         goto error;
2553
2554     for (i = 0; i < vec_size(params); ++i) {
2555         ir_call_param(callinstr, params[i]);
2556     }
2557
2558     *out = ir_call_value(callinstr);
2559     self->expression.outr = *out;
2560
2561     vec_free(params);
2562     return true;
2563 error:
2564     vec_free(params);
2565     return false;
2566 }