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