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