]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
ast_type_adopt - ast_entfield now adopts the full type of the field
[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     cvprintmsg(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     fprintf(stderr, "ast node missing destroy()\n");
51     abort();
52 }
53
54 /* Initialize main ast node aprts */
55 static void ast_node_init(ast_node *self, lex_ctx ctx, int nodetype)
56 {
57     self->node.context = ctx;
58     self->node.destroy = &_ast_node_destroy;
59     self->node.keep    = false;
60     self->node.nodetype = nodetype;
61 }
62
63 /* General expression initialization */
64 static void ast_expression_init(ast_expression *self,
65                                 ast_expression_codegen *codegen)
66 {
67     self->expression.codegen = codegen;
68     self->expression.vtype   = TYPE_VOID;
69     self->expression.next    = NULL;
70     self->expression.outl    = NULL;
71     self->expression.outr    = NULL;
72     MEM_VECTOR_INIT(&self->expression, params);
73 }
74
75 static void ast_expression_delete(ast_expression *self)
76 {
77     size_t i;
78     if (self->expression.next)
79         ast_delete(self->expression.next);
80     for (i = 0; i < self->expression.params_count; ++i) {
81         ast_delete(self->expression.params[i]);
82     }
83     MEM_VECTOR_CLEAR(&self->expression, params);
84 }
85
86 static void ast_expression_delete_full(ast_expression *self)
87 {
88     ast_expression_delete(self);
89     mem_d(self);
90 }
91
92 MEM_VEC_FUNCTIONS(ast_expression_common, ast_value*, params)
93
94 static ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex);
95 ast_value* ast_value_copy(const ast_value *self)
96 {
97     size_t i;
98     const ast_expression_common *fromex;
99     ast_expression_common *selfex;
100     ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
101     if (self->expression.next) {
102         cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
103         if (!cp->expression.next) {
104             ast_value_delete(cp);
105             return NULL;
106         }
107     }
108     fromex   = &self->expression;
109     selfex = &cp->expression;
110     for (i = 0; i < fromex->params_count; ++i) {
111         ast_value *v = ast_value_copy(fromex->params[i]);
112         if (!v || !ast_expression_common_params_add(selfex, v)) {
113             ast_value_delete(cp);
114             return NULL;
115         }
116     }
117     return cp;
118 }
119
120 #define ast_type_adopt(a, b) ast_type_adopt_impl((ast_expression*)(a), (ast_expression*)(b))
121 static 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     for (i = 0; i < fromex->params_count; ++i) {
135         ast_value *v = ast_value_copy(fromex->params[i]);
136         if (!v || !ast_expression_common_params_add(selfex, v))
137             return false;
138     }
139     return true;
140 }
141
142 static ast_expression* ast_shallow_type(lex_ctx ctx, int vtype)
143 {
144     ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
145     ast_expression_init(self, NULL);
146     self->expression.codegen = NULL;
147     self->expression.next    = NULL;
148     self->expression.vtype   = vtype;
149     return self;
150 }
151
152 static ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
153 {
154     size_t i;
155     const ast_expression_common *fromex;
156     ast_expression_common *selfex;
157
158     if (!ex)
159         return NULL;
160     else
161     {
162         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
163         ast_expression_init(self, NULL);
164
165         fromex   = &ex->expression;
166         selfex = &self->expression;
167
168         /* This may never be codegen()d */
169         selfex->codegen = NULL;
170
171         selfex->vtype = fromex->vtype;
172         if (fromex->next)
173         {
174             selfex->next = ast_type_copy(ctx, fromex->next);
175             if (!selfex->next) {
176                 ast_expression_delete_full(self);
177                 return NULL;
178             }
179         }
180         else
181             selfex->next = NULL;
182
183         for (i = 0; i < fromex->params_count; ++i) {
184             ast_value *v = ast_value_copy(fromex->params[i]);
185             if (!v || !ast_expression_common_params_add(selfex, v)) {
186                 ast_expression_delete_full(self);
187                 return NULL;
188             }
189         }
190
191         return self;
192     }
193 }
194
195 bool ast_compare_type(ast_expression *a, ast_expression *b)
196 {
197     if (a->expression.vtype != b->expression.vtype)
198         return false;
199     if (!a->expression.next != !b->expression.next)
200         return false;
201     if (a->expression.params_count != b->expression.params_count)
202         return false;
203     if (a->expression.params_count) {
204         size_t i;
205         for (i = 0; i < a->expression.params_count; ++i) {
206             if (!ast_compare_type((ast_expression*)a->expression.params[i],
207                                   (ast_expression*)b->expression.params[i]))
208                 return false;
209         }
210     }
211     if (a->expression.next)
212         return ast_compare_type(a->expression.next, b->expression.next);
213     return true;
214 }
215
216 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
217 {
218     ast_instantiate(ast_value, ctx, ast_value_delete);
219     ast_expression_init((ast_expression*)self,
220                         (ast_expression_codegen*)&ast_value_codegen);
221     self->expression.node.keep = true; /* keep */
222
223     self->name = name ? util_strdup(name) : NULL;
224     self->expression.vtype = t;
225     self->expression.next  = NULL;
226     self->isconst = false;
227     memset(&self->constval, 0, sizeof(self->constval));
228
229     self->ir_v    = NULL;
230
231     return self;
232 }
233
234 void ast_value_delete(ast_value* self)
235 {
236     if (self->name)
237         mem_d((void*)self->name);
238     if (self->isconst) {
239         switch (self->expression.vtype)
240         {
241         case TYPE_STRING:
242             mem_d((void*)self->constval.vstring);
243             break;
244         case TYPE_FUNCTION:
245             /* unlink us from the function node */
246             self->constval.vfunc->vtype = NULL;
247             break;
248         /* NOTE: delete function? currently collected in
249          * the parser structure
250          */
251         default:
252             break;
253         }
254     }
255     ast_expression_delete((ast_expression*)self);
256     mem_d(self);
257 }
258
259 bool GMQCC_WARN ast_value_params_add(ast_value *self, ast_value *p)
260 {
261     return ast_expression_common_params_add(&self->expression, p);
262 }
263
264 bool ast_value_set_name(ast_value *self, const char *name)
265 {
266     if (self->name)
267         mem_d((void*)self->name);
268     self->name = util_strdup(name);
269     return !!self->name;
270 }
271
272 ast_binary* ast_binary_new(lex_ctx ctx, int op,
273                            ast_expression* left, ast_expression* right)
274 {
275     ast_instantiate(ast_binary, ctx, ast_binary_delete);
276     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
277
278     self->op = op;
279     self->left = left;
280     self->right = right;
281
282     if (op >= INSTR_EQ_F && op <= INSTR_GT)
283         self->expression.vtype = TYPE_FLOAT;
284     else if (op == INSTR_AND || op == INSTR_OR ||
285              op == INSTR_BITAND || op == INSTR_BITOR)
286         self->expression.vtype = TYPE_FLOAT;
287     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
288         self->expression.vtype = TYPE_VECTOR;
289     else if (op == INSTR_MUL_V)
290         self->expression.vtype = TYPE_FLOAT;
291     else
292         self->expression.vtype = left->expression.vtype;
293
294     return self;
295 }
296
297 void ast_binary_delete(ast_binary *self)
298 {
299     ast_unref(self->left);
300     ast_unref(self->right);
301     ast_expression_delete((ast_expression*)self);
302     mem_d(self);
303 }
304
305 ast_binstore* ast_binstore_new(lex_ctx ctx, int storop, int op,
306                                ast_expression* left, ast_expression* right)
307 {
308     ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
309     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
310
311     self->opstore = storop;
312     self->opbin   = op;
313     self->dest    = left;
314     self->source  = right;
315
316     self->expression.vtype = left->expression.vtype;
317     if (left->expression.next) {
318         self->expression.next = ast_type_copy(ctx, left);
319         if (!self->expression.next) {
320             ast_delete(self);
321             return NULL;
322         }
323     }
324     else
325         self->expression.next = NULL;
326
327     return self;
328 }
329
330 void ast_binstore_delete(ast_binstore *self)
331 {
332     ast_unref(self->dest);
333     ast_unref(self->source);
334     ast_expression_delete((ast_expression*)self);
335     mem_d(self);
336 }
337
338 ast_unary* ast_unary_new(lex_ctx ctx, int op,
339                          ast_expression *expr)
340 {
341     ast_instantiate(ast_unary, ctx, ast_unary_delete);
342     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
343
344     self->op = op;
345     self->operand = expr;
346
347     if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
348         self->expression.vtype = TYPE_FLOAT;
349     } else
350         asterror(ctx, "cannot determine type of unary operation %s", asm_instr[op].m);
351
352     return self;
353 }
354
355 void ast_unary_delete(ast_unary *self)
356 {
357     ast_unref(self->operand);
358     ast_expression_delete((ast_expression*)self);
359     mem_d(self);
360 }
361
362 ast_return* ast_return_new(lex_ctx ctx, ast_expression *expr)
363 {
364     ast_instantiate(ast_return, ctx, ast_return_delete);
365     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
366
367     self->operand = expr;
368
369     return self;
370 }
371
372 void ast_return_delete(ast_return *self)
373 {
374     if (self->operand)
375         ast_unref(self->operand);
376     ast_expression_delete((ast_expression*)self);
377     mem_d(self);
378 }
379
380 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
381 {
382     const ast_expression *outtype;
383
384     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
385
386     if (field->expression.vtype != TYPE_FIELD) {
387         mem_d(self);
388         return NULL;
389     }
390
391     outtype = field->expression.next;
392     if (!outtype) {
393         mem_d(self);
394         /* Error: field has no type... */
395         return NULL;
396     }
397
398     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
399
400     self->entity = entity;
401     self->field  = field;
402
403     if (!ast_type_adopt(self, outtype)) {
404         ast_entfield_delete(self);
405         return NULL;
406     }
407
408     return self;
409 }
410
411 void ast_entfield_delete(ast_entfield *self)
412 {
413     ast_unref(self->entity);
414     ast_unref(self->field);
415     ast_expression_delete((ast_expression*)self);
416     mem_d(self);
417 }
418
419 ast_member* ast_member_new(lex_ctx ctx, ast_expression *owner, unsigned int field)
420 {
421     ast_instantiate(ast_member, ctx, ast_member_delete);
422     if (field >= 3) {
423         mem_d(self);
424         return NULL;
425     }
426
427     if (owner->expression.vtype != TYPE_VECTOR &&
428         owner->expression.vtype != TYPE_FIELD) {
429         asterror(ctx, "member-access on an invalid owner of type %s\n", type_name[owner->expression.vtype]);
430         mem_d(self);
431         return NULL;
432     }
433
434     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
435     self->expression.node.keep = true; /* keep */
436
437     if (owner->expression.vtype == TYPE_VECTOR) {
438         self->expression.vtype = TYPE_FLOAT;
439         self->expression.next  = NULL;
440     } else {
441         self->expression.vtype = TYPE_FIELD;
442         self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
443     }
444
445     self->owner = owner;
446     self->field = field;
447
448     return self;
449 }
450
451 void ast_member_delete(ast_member *self)
452 {
453     /* The owner is always an ast_value, which has .keep=true,
454      * also: ast_members are usually deleted after the owner, thus
455      * this will cause invalid access
456     ast_unref(self->owner);
457      * once we allow (expression).x to access a vector-member, we need
458      * to change this: preferably by creating an alternate ast node for this
459      * purpose that is not garbage-collected.
460     */
461     ast_expression_delete((ast_expression*)self);
462     mem_d(self);
463 }
464
465 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
466 {
467     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
468     if (!ontrue && !onfalse) {
469         /* because it is invalid */
470         mem_d(self);
471         return NULL;
472     }
473     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
474
475     self->cond     = cond;
476     self->on_true  = ontrue;
477     self->on_false = onfalse;
478
479     return self;
480 }
481
482 void ast_ifthen_delete(ast_ifthen *self)
483 {
484     ast_unref(self->cond);
485     if (self->on_true)
486         ast_unref(self->on_true);
487     if (self->on_false)
488         ast_unref(self->on_false);
489     ast_expression_delete((ast_expression*)self);
490     mem_d(self);
491 }
492
493 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
494 {
495     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
496     /* This time NEITHER must be NULL */
497     if (!ontrue || !onfalse) {
498         mem_d(self);
499         return NULL;
500     }
501     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
502
503     self->cond     = cond;
504     self->on_true  = ontrue;
505     self->on_false = onfalse;
506     self->phi_out  = NULL;
507
508     return self;
509 }
510
511 void ast_ternary_delete(ast_ternary *self)
512 {
513     ast_unref(self->cond);
514     ast_unref(self->on_true);
515     ast_unref(self->on_false);
516     ast_expression_delete((ast_expression*)self);
517     mem_d(self);
518 }
519
520 ast_loop* ast_loop_new(lex_ctx ctx,
521                        ast_expression *initexpr,
522                        ast_expression *precond,
523                        ast_expression *postcond,
524                        ast_expression *increment,
525                        ast_expression *body)
526 {
527     ast_instantiate(ast_loop, ctx, ast_loop_delete);
528     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
529
530     self->initexpr  = initexpr;
531     self->precond   = precond;
532     self->postcond  = postcond;
533     self->increment = increment;
534     self->body      = body;
535
536     return self;
537 }
538
539 void ast_loop_delete(ast_loop *self)
540 {
541     if (self->initexpr)
542         ast_unref(self->initexpr);
543     if (self->precond)
544         ast_unref(self->precond);
545     if (self->postcond)
546         ast_unref(self->postcond);
547     if (self->increment)
548         ast_unref(self->increment);
549     if (self->body)
550         ast_unref(self->body);
551     ast_expression_delete((ast_expression*)self);
552     mem_d(self);
553 }
554
555 ast_call* ast_call_new(lex_ctx ctx,
556                        ast_expression *funcexpr)
557 {
558     ast_instantiate(ast_call, ctx, ast_call_delete);
559     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
560
561     MEM_VECTOR_INIT(self, params);
562
563     self->func = funcexpr;
564
565     self->expression.vtype = funcexpr->expression.next->expression.vtype;
566     if (funcexpr->expression.next->expression.next)
567         self->expression.next = ast_type_copy(ctx, funcexpr->expression.next->expression.next);
568
569     return self;
570 }
571 MEM_VEC_FUNCTIONS(ast_call, ast_expression*, params)
572
573 void ast_call_delete(ast_call *self)
574 {
575     size_t i;
576     for (i = 0; i < self->params_count; ++i)
577         ast_unref(self->params[i]);
578     MEM_VECTOR_CLEAR(self, params);
579
580     if (self->func)
581         ast_unref(self->func);
582
583     ast_expression_delete((ast_expression*)self);
584     mem_d(self);
585 }
586
587 ast_store* ast_store_new(lex_ctx ctx, int op,
588                          ast_expression *dest, ast_expression *source)
589 {
590     ast_instantiate(ast_store, ctx, ast_store_delete);
591     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
592
593     self->op = op;
594     self->dest = dest;
595     self->source = source;
596
597     return self;
598 }
599
600 void ast_store_delete(ast_store *self)
601 {
602     ast_unref(self->dest);
603     ast_unref(self->source);
604     ast_expression_delete((ast_expression*)self);
605     mem_d(self);
606 }
607
608 ast_block* ast_block_new(lex_ctx ctx)
609 {
610     ast_instantiate(ast_block, ctx, ast_block_delete);
611     ast_expression_init((ast_expression*)self,
612                         (ast_expression_codegen*)&ast_block_codegen);
613
614     MEM_VECTOR_INIT(self, locals);
615     MEM_VECTOR_INIT(self, exprs);
616     MEM_VECTOR_INIT(self, collect);
617
618     return self;
619 }
620 MEM_VEC_FUNCTIONS(ast_block, ast_value*, locals)
621 MEM_VEC_FUNCTIONS(ast_block, ast_expression*, exprs)
622 MEM_VEC_FUNCTIONS(ast_block, ast_expression*, collect)
623
624 bool ast_block_collect(ast_block *self, ast_expression *expr)
625 {
626     if (!ast_block_collect_add(self, expr))
627         return false;
628     expr->expression.node.keep = true;
629     return true;
630 }
631
632 void ast_block_delete(ast_block *self)
633 {
634     size_t i;
635     for (i = 0; i < self->exprs_count; ++i)
636         ast_unref(self->exprs[i]);
637     MEM_VECTOR_CLEAR(self, exprs);
638     for (i = 0; i < self->locals_count; ++i)
639         ast_delete(self->locals[i]);
640     MEM_VECTOR_CLEAR(self, locals);
641     for (i = 0; i < self->collect_count; ++i)
642         ast_delete(self->collect[i]);
643     MEM_VECTOR_CLEAR(self, collect);
644     ast_expression_delete((ast_expression*)self);
645     mem_d(self);
646 }
647
648 bool ast_block_set_type(ast_block *self, ast_expression *from)
649 {
650     if (self->expression.next)
651         ast_delete(self->expression.next);
652     self->expression.vtype = from->expression.vtype;
653     if (from->expression.next) {
654         self->expression.next = ast_type_copy(self->expression.node.context, from->expression.next);
655         if (!self->expression.next)
656             return false;
657     }
658     else
659         self->expression.next = NULL;
660     return true;
661 }
662
663 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
664 {
665     ast_instantiate(ast_function, ctx, ast_function_delete);
666
667     if (!vtype ||
668         vtype->isconst ||
669         vtype->expression.vtype != TYPE_FUNCTION)
670     {
671         mem_d(self);
672         return NULL;
673     }
674
675     self->vtype = vtype;
676     self->name = name ? util_strdup(name) : NULL;
677     MEM_VECTOR_INIT(self, blocks);
678
679     self->labelcount = 0;
680     self->builtin = 0;
681
682     self->ir_func = NULL;
683     self->curblock = NULL;
684
685     self->breakblock    = NULL;
686     self->continueblock = NULL;
687
688     vtype->isconst = true;
689     vtype->constval.vfunc = self;
690
691     return self;
692 }
693
694 MEM_VEC_FUNCTIONS(ast_function, ast_block*, blocks)
695
696 void ast_function_delete(ast_function *self)
697 {
698     size_t i;
699     if (self->name)
700         mem_d((void*)self->name);
701     if (self->vtype) {
702         /* ast_value_delete(self->vtype); */
703         self->vtype->isconst = false;
704         self->vtype->constval.vfunc = NULL;
705         /* We use unref - if it was stored in a global table it is supposed
706          * to be deleted from *there*
707          */
708         ast_unref(self->vtype);
709     }
710     for (i = 0; i < self->blocks_count; ++i)
711         ast_delete(self->blocks[i]);
712     MEM_VECTOR_CLEAR(self, blocks);
713     mem_d(self);
714 }
715
716 static void ast_util_hexitoa(char *buf, size_t size, unsigned int num)
717 {
718     unsigned int base = 10;
719 #define checknul() do { if (size == 1) { *buf = 0; return; } } while (0)
720 #define addch(x) do { *buf++ = (x); --size; checknul(); } while (0)
721     if (size < 1)
722         return;
723     checknul();
724     if (!num)
725         addch('0');
726     else {
727         while (num)
728         {
729             int digit = num % base;
730             num /= base;
731             addch('0' + digit);
732         }
733     }
734
735     *buf = 0;
736 #undef addch
737 #undef checknul
738 }
739
740 const char* ast_function_label(ast_function *self, const char *prefix)
741 {
742     size_t id = (self->labelcount++);
743     size_t len = strlen(prefix);
744     strncpy(self->labelbuf, prefix, sizeof(self->labelbuf));
745     ast_util_hexitoa(self->labelbuf + len, sizeof(self->labelbuf)-len, id);
746     return self->labelbuf;
747 }
748
749 /*********************************************************************/
750 /* AST codegen part
751  * by convention you must never pass NULL to the 'ir_value **out'
752  * parameter. If you really don't care about the output, pass a dummy.
753  * But I can't imagine a pituation where the output is truly unnecessary.
754  */
755
756 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
757 {
758     /* NOTE: This is the codegen for a variable used in an expression.
759      * It is not the codegen to generate the value. For this purpose,
760      * ast_local_codegen and ast_global_codegen are to be used before this
761      * is executed. ast_function_codegen should take care of its locals,
762      * and the ast-user should take care of ast_global_codegen to be used
763      * on all the globals.
764      */
765     if (!self->ir_v) {
766         asterror(ast_ctx(self), "ast_value used before generated (%s)\n", self->name);
767         return false;
768     }
769     *out = self->ir_v;
770     return true;
771 }
772
773 bool ast_global_codegen(ast_value *self, ir_builder *ir)
774 {
775     ir_value *v = NULL;
776     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
777     {
778         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
779         if (!func)
780             return false;
781
782         self->constval.vfunc->ir_func = func;
783         self->ir_v = func->value;
784         /* The function is filled later on ast_function_codegen... */
785         return true;
786     }
787
788     if (self->expression.vtype == TYPE_FIELD) {
789         v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
790         if (!v)
791             return false;
792         if (self->isconst) {
793             asterror(ast_ctx(self), "TODO: constant field pointers with value\n");
794             goto error;
795         }
796         self->ir_v = v;
797         return true;
798     }
799
800     v = ir_builder_create_global(ir, self->name, self->expression.vtype);
801     if (!v) {
802         asterror(ast_ctx(self), "ir_builder_create_global failed\n");
803         return false;
804     }
805
806     if (self->isconst) {
807         switch (self->expression.vtype)
808         {
809             case TYPE_FLOAT:
810                 if (!ir_value_set_float(v, self->constval.vfloat))
811                     goto error;
812                 break;
813             case TYPE_VECTOR:
814                 if (!ir_value_set_vector(v, self->constval.vvec))
815                     goto error;
816                 break;
817             case TYPE_STRING:
818                 if (!ir_value_set_string(v, self->constval.vstring))
819                     goto error;
820                 break;
821             case TYPE_FUNCTION:
822                 asterror(ast_ctx(self), "global of type function not properly generated\n");
823                 goto error;
824                 /* Cannot generate an IR value for a function,
825                  * need a pointer pointing to a function rather.
826                  */
827             default:
828                 asterror(ast_ctx(self), "TODO: global constant type %i\n", self->expression.vtype);
829                 break;
830         }
831     }
832
833     /* link us to the ir_value */
834     self->ir_v = v;
835     return true;
836
837 error: /* clean up */
838     ir_value_delete(v);
839     return false;
840 }
841
842 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
843 {
844     ir_value *v = NULL;
845     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
846     {
847         /* Do we allow local functions? I think not...
848          * this is NOT a function pointer atm.
849          */
850         return false;
851     }
852
853     v = ir_function_create_local(func, self->name, self->expression.vtype, param);
854     if (!v)
855         return false;
856
857     /* A constant local... hmmm...
858      * I suppose the IR will have to deal with this
859      */
860     if (self->isconst) {
861         switch (self->expression.vtype)
862         {
863             case TYPE_FLOAT:
864                 if (!ir_value_set_float(v, self->constval.vfloat))
865                     goto error;
866                 break;
867             case TYPE_VECTOR:
868                 if (!ir_value_set_vector(v, self->constval.vvec))
869                     goto error;
870                 break;
871             case TYPE_STRING:
872                 if (!ir_value_set_string(v, self->constval.vstring))
873                     goto error;
874                 break;
875             default:
876                 asterror(ast_ctx(self), "TODO: global constant type %i\n", self->expression.vtype);
877                 break;
878         }
879     }
880
881     /* link us to the ir_value */
882     self->ir_v = v;
883     return true;
884
885 error: /* clean up */
886     ir_value_delete(v);
887     return false;
888 }
889
890 bool ast_function_codegen(ast_function *self, ir_builder *ir)
891 {
892     ir_function *irf;
893     ir_value    *dummy;
894     ast_expression_common *ec;
895     size_t    i;
896
897     irf = self->ir_func;
898     if (!irf) {
899         asterror(ast_ctx(self), "ast_function's related ast_value was not generated yet\n");
900         return false;
901     }
902
903     /* fill the parameter list */
904     ec = &self->vtype->expression;
905     for (i = 0; i < ec->params_count; ++i)
906     {
907         if (!ir_function_params_add(irf, ec->params[i]->expression.vtype))
908             return false;
909         if (!self->builtin) {
910             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
911                 return false;
912         }
913     }
914
915     if (self->builtin) {
916         irf->builtin = self->builtin;
917         return true;
918     }
919
920     if (!self->blocks_count) {
921         asterror(ast_ctx(self), "function `%s` has no body", self->name);
922         return false;
923     }
924
925     self->curblock = ir_function_create_block(irf, "entry");
926     if (!self->curblock)
927         return false;
928
929     for (i = 0; i < self->blocks_count; ++i) {
930         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
931         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
932             return false;
933     }
934
935     /* TODO: check return types */
936     if (!self->curblock->is_return)
937     {
938         if (!self->vtype->expression.next ||
939             self->vtype->expression.next->expression.vtype == TYPE_VOID)
940         {
941             return ir_block_create_return(self->curblock, NULL);
942         }
943         else
944         {
945             /* error("missing return"); */
946             asterror(ast_ctx(self), "function `%s` missing return value", self->name);
947             return false;
948         }
949     }
950     return true;
951 }
952
953 /* Note, you will not see ast_block_codegen generate ir_blocks.
954  * To the AST and the IR, blocks are 2 different things.
955  * In the AST it represents a block of code, usually enclosed in
956  * curly braces {...}.
957  * While in the IR it represents a block in terms of control-flow.
958  */
959 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
960 {
961     size_t i;
962
963     /* We don't use this
964      * Note: an ast-representation using the comma-operator
965      * of the form: (a, b, c) = x should not assign to c...
966      */
967     (void)lvalue;
968     if (self->expression.outr) {
969         *out = self->expression.outr;
970         return true;
971     }
972
973     /* output is NULL at first, we'll have each expression
974      * assign to out output, thus, a comma-operator represention
975      * using an ast_block will return the last generated value,
976      * so: (b, c) + a  executed both b and c, and returns c,
977      * which is then added to a.
978      */
979     *out = NULL;
980
981     /* generate locals */
982     for (i = 0; i < self->locals_count; ++i)
983     {
984         if (!ast_local_codegen(self->locals[i], func->ir_func, false))
985             return false;
986     }
987
988     for (i = 0; i < self->exprs_count; ++i)
989     {
990         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
991         if (!(*gen)(self->exprs[i], func, false, out))
992             return false;
993     }
994
995     self->expression.outr = *out;
996
997     return true;
998 }
999
1000 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1001 {
1002     ast_expression_codegen *cgen;
1003     ir_value *left, *right;
1004
1005     if (lvalue && self->expression.outl) {
1006         *out = self->expression.outl;
1007         return true;
1008     }
1009
1010     if (!lvalue && self->expression.outr) {
1011         *out = self->expression.outr;
1012         return true;
1013     }
1014
1015     cgen = self->dest->expression.codegen;
1016     /* lvalue! */
1017     if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1018         return false;
1019     self->expression.outl = left;
1020
1021     cgen = self->source->expression.codegen;
1022     /* rvalue! */
1023     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1024         return false;
1025
1026     if (!ir_block_create_store_op(func->curblock, self->op, left, right))
1027         return false;
1028     self->expression.outr = right;
1029
1030     /* Theoretically, an assinment returns its left side as an
1031      * lvalue, if we don't need an lvalue though, we return
1032      * the right side as an rvalue, otherwise we have to
1033      * somehow know whether or not we need to dereference the pointer
1034      * on the left side - that is: OP_LOAD if it was an address.
1035      * Also: in original QC we cannot OP_LOADP *anyway*.
1036      */
1037     *out = (lvalue ? left : right);
1038
1039     return true;
1040 }
1041
1042 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1043 {
1044     ast_expression_codegen *cgen;
1045     ir_value *left, *right;
1046
1047     /* In the context of a binary operation, we can disregard
1048      * the lvalue flag.
1049      */
1050     (void)lvalue;
1051     if (self->expression.outr) {
1052         *out = self->expression.outr;
1053         return true;
1054     }
1055
1056     cgen = self->left->expression.codegen;
1057     /* lvalue! */
1058     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1059         return false;
1060
1061     cgen = self->right->expression.codegen;
1062     /* rvalue! */
1063     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1064         return false;
1065
1066     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
1067                                  self->op, left, right);
1068     if (!*out)
1069         return false;
1070     self->expression.outr = *out;
1071
1072     return true;
1073 }
1074
1075 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1076 {
1077     ast_expression_codegen *cgen;
1078     ir_value *leftl, *leftr, *right, *bin;
1079
1080     if (lvalue && self->expression.outl) {
1081         *out = self->expression.outl;
1082         return true;
1083     }
1084
1085     if (!lvalue && self->expression.outr) {
1086         *out = self->expression.outr;
1087         return true;
1088     }
1089
1090     /* for a binstore we need both an lvalue and an rvalue for the left side */
1091     /* rvalue of destination! */
1092     cgen = self->dest->expression.codegen;
1093     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
1094         return false;
1095
1096     /* source as rvalue only */
1097     cgen = self->source->expression.codegen;
1098     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1099         return false;
1100
1101     /* now the binary */
1102     bin = ir_block_create_binop(func->curblock, ast_function_label(func, "binst"),
1103                                 self->opbin, leftr, right);
1104     self->expression.outr = bin;
1105
1106     /* now store them */
1107     cgen = self->dest->expression.codegen;
1108     /* lvalue of destination */
1109     if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
1110         return false;
1111     self->expression.outl = leftl;
1112
1113     if (!ir_block_create_store_op(func->curblock, self->opstore, leftl, bin))
1114         return false;
1115     self->expression.outr = bin;
1116
1117     /* Theoretically, an assinment returns its left side as an
1118      * lvalue, if we don't need an lvalue though, we return
1119      * the right side as an rvalue, otherwise we have to
1120      * somehow know whether or not we need to dereference the pointer
1121      * on the left side - that is: OP_LOAD if it was an address.
1122      * Also: in original QC we cannot OP_LOADP *anyway*.
1123      */
1124     *out = (lvalue ? leftl : bin);
1125
1126     return true;
1127 }
1128
1129 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
1130 {
1131     ast_expression_codegen *cgen;
1132     ir_value *operand;
1133
1134     /* In the context of a unary operation, we can disregard
1135      * the lvalue flag.
1136      */
1137     (void)lvalue;
1138     if (self->expression.outr) {
1139         *out = self->expression.outr;
1140         return true;
1141     }
1142
1143     cgen = self->operand->expression.codegen;
1144     /* lvalue! */
1145     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1146         return false;
1147
1148     *out = ir_block_create_unary(func->curblock, ast_function_label(func, "unary"),
1149                                  self->op, operand);
1150     if (!*out)
1151         return false;
1152     self->expression.outr = *out;
1153
1154     return true;
1155 }
1156
1157 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
1158 {
1159     ast_expression_codegen *cgen;
1160     ir_value *operand;
1161
1162     /* In the context of a return operation, we can disregard
1163      * the lvalue flag.
1164      */
1165     (void)lvalue;
1166     if (self->expression.outr) {
1167         asterror(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!\n");
1168         return false;
1169     }
1170     self->expression.outr = (ir_value*)1;
1171
1172     if (self->operand) {
1173         cgen = self->operand->expression.codegen;
1174         /* lvalue! */
1175         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1176             return false;
1177
1178         if (!ir_block_create_return(func->curblock, operand))
1179             return false;
1180     } else {
1181         if (!ir_block_create_return(func->curblock, NULL))
1182             return false;
1183     }
1184
1185     return true;
1186 }
1187
1188 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
1189 {
1190     ast_expression_codegen *cgen;
1191     ir_value *ent, *field;
1192
1193     /* This function needs to take the 'lvalue' flag into account!
1194      * As lvalue we provide a field-pointer, as rvalue we provide the
1195      * value in a temp.
1196      */
1197
1198     if (lvalue && self->expression.outl) {
1199         *out = self->expression.outl;
1200         return true;
1201     }
1202
1203     if (!lvalue && self->expression.outr) {
1204         *out = self->expression.outr;
1205         return true;
1206     }
1207
1208     cgen = self->entity->expression.codegen;
1209     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
1210         return false;
1211
1212     cgen = self->field->expression.codegen;
1213     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
1214         return false;
1215
1216     if (lvalue) {
1217         /* address! */
1218         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
1219                                             ent, field);
1220     } else {
1221         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
1222                                              ent, field, self->expression.vtype);
1223     }
1224     if (!*out) {
1225         asterror(ast_ctx(self), "failed to create %s instruction (output type %s)",
1226                  (lvalue ? "ADDRESS" : "FIELD"),
1227                  type_name[self->expression.vtype]);
1228         return false;
1229     }
1230
1231     if (lvalue)
1232         self->expression.outl = *out;
1233     else
1234         self->expression.outr = *out;
1235
1236     /* Hm that should be it... */
1237     return true;
1238 }
1239
1240 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
1241 {
1242     ast_expression_codegen *cgen;
1243     ir_value *vec;
1244
1245     /* in QC this is always an lvalue */
1246     (void)lvalue;
1247     if (self->expression.outl) {
1248         *out = self->expression.outl;
1249         return true;
1250     }
1251
1252     cgen = self->owner->expression.codegen;
1253     if (!(*cgen)((ast_expression*)(self->owner), func, true, &vec))
1254         return false;
1255
1256     if (vec->vtype != TYPE_VECTOR &&
1257         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
1258     {
1259         return false;
1260     }
1261
1262     *out = ir_value_vector_member(vec, self->field);
1263     self->expression.outl = *out;
1264
1265     return (*out != NULL);
1266 }
1267
1268 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
1269 {
1270     ast_expression_codegen *cgen;
1271
1272     ir_value *condval;
1273     ir_value *dummy;
1274
1275     ir_block *cond = func->curblock;
1276     ir_block *ontrue;
1277     ir_block *onfalse;
1278     ir_block *merge;
1279
1280     /* We don't output any value, thus also don't care about r/lvalue */
1281     (void)out;
1282     (void)lvalue;
1283
1284     if (self->expression.outr) {
1285         asterror(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!\n");
1286         return false;
1287     }
1288     self->expression.outr = (ir_value*)1;
1289
1290     /* generate the condition */
1291     func->curblock = cond;
1292     cgen = self->cond->expression.codegen;
1293     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1294         return false;
1295
1296     /* on-true path */
1297
1298     if (self->on_true) {
1299         /* create on-true block */
1300         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
1301         if (!ontrue)
1302             return false;
1303
1304         /* enter the block */
1305         func->curblock = ontrue;
1306
1307         /* generate */
1308         cgen = self->on_true->expression.codegen;
1309         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
1310             return false;
1311     } else
1312         ontrue = NULL;
1313
1314     /* on-false path */
1315     if (self->on_false) {
1316         /* create on-false block */
1317         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
1318         if (!onfalse)
1319             return false;
1320
1321         /* enter the block */
1322         func->curblock = onfalse;
1323
1324         /* generate */
1325         cgen = self->on_false->expression.codegen;
1326         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
1327             return false;
1328     } else
1329         onfalse = NULL;
1330
1331     /* Merge block were they all merge in to */
1332     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
1333     if (!merge)
1334         return false;
1335
1336     /* add jumps ot the merge block */
1337     if (ontrue && !ir_block_create_jump(ontrue, merge))
1338         return false;
1339     if (onfalse && !ir_block_create_jump(onfalse, merge))
1340         return false;
1341
1342     /* we create the if here, that way all blocks are ordered :)
1343      */
1344     if (!ir_block_create_if(cond, condval,
1345                             (ontrue  ? ontrue  : merge),
1346                             (onfalse ? onfalse : merge)))
1347     {
1348         return false;
1349     }
1350
1351     /* Now enter the merge block */
1352     func->curblock = merge;
1353
1354     return true;
1355 }
1356
1357 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
1358 {
1359     ast_expression_codegen *cgen;
1360
1361     ir_value *condval;
1362     ir_value *trueval, *falseval;
1363     ir_instr *phi;
1364
1365     ir_block *cond = func->curblock;
1366     ir_block *ontrue;
1367     ir_block *onfalse;
1368     ir_block *merge;
1369
1370     /* Ternary can never create an lvalue... */
1371     if (lvalue)
1372         return false;
1373
1374     /* In theory it shouldn't be possible to pass through a node twice, but
1375      * in case we add any kind of optimization pass for the AST itself, it
1376      * may still happen, thus we remember a created ir_value and simply return one
1377      * if it already exists.
1378      */
1379     if (self->phi_out) {
1380         *out = self->phi_out;
1381         return true;
1382     }
1383
1384     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
1385
1386     /* generate the condition */
1387     func->curblock = cond;
1388     cgen = self->cond->expression.codegen;
1389     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1390         return false;
1391
1392     /* create on-true block */
1393     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
1394     if (!ontrue)
1395         return false;
1396     else
1397     {
1398         /* enter the block */
1399         func->curblock = ontrue;
1400
1401         /* generate */
1402         cgen = self->on_true->expression.codegen;
1403         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
1404             return false;
1405     }
1406
1407     /* create on-false block */
1408     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
1409     if (!onfalse)
1410         return false;
1411     else
1412     {
1413         /* enter the block */
1414         func->curblock = onfalse;
1415
1416         /* generate */
1417         cgen = self->on_false->expression.codegen;
1418         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
1419             return false;
1420     }
1421
1422     /* create merge block */
1423     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
1424     if (!merge)
1425         return false;
1426     /* jump to merge block */
1427     if (!ir_block_create_jump(ontrue, merge))
1428         return false;
1429     if (!ir_block_create_jump(onfalse, merge))
1430         return false;
1431
1432     /* create if instruction */
1433     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
1434         return false;
1435
1436     /* Now enter the merge block */
1437     func->curblock = merge;
1438
1439     /* Here, now, we need a PHI node
1440      * but first some sanity checking...
1441      */
1442     if (trueval->vtype != falseval->vtype) {
1443         /* error("ternary with different types on the two sides"); */
1444         return false;
1445     }
1446
1447     /* create PHI */
1448     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
1449     if (!phi ||
1450         !ir_phi_add(phi, ontrue,  trueval) ||
1451         !ir_phi_add(phi, onfalse, falseval))
1452     {
1453         return false;
1454     }
1455
1456     self->phi_out = ir_phi_value(phi);
1457     *out = self->phi_out;
1458
1459     return true;
1460 }
1461
1462 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
1463 {
1464     ast_expression_codegen *cgen;
1465
1466     ir_value *dummy      = NULL;
1467     ir_value *precond    = NULL;
1468     ir_value *postcond   = NULL;
1469
1470     /* Since we insert some jumps "late" so we have blocks
1471      * ordered "nicely", we need to keep track of the actual end-blocks
1472      * of expressions to add the jumps to.
1473      */
1474     ir_block *bbody      = NULL, *end_bbody      = NULL;
1475     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
1476     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
1477     ir_block *bincrement = NULL, *end_bincrement = NULL;
1478     ir_block *bout       = NULL, *bin            = NULL;
1479
1480     /* let's at least move the outgoing block to the end */
1481     size_t    bout_id;
1482
1483     /* 'break' and 'continue' need to be able to find the right blocks */
1484     ir_block *bcontinue     = NULL;
1485     ir_block *bbreak        = NULL;
1486
1487     ir_block *old_bcontinue = NULL;
1488     ir_block *old_bbreak    = NULL;
1489
1490     ir_block *tmpblock      = NULL;
1491
1492     (void)lvalue;
1493     (void)out;
1494
1495     if (self->expression.outr) {
1496         asterror(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!\n");
1497         return false;
1498     }
1499     self->expression.outr = (ir_value*)1;
1500
1501     /* NOTE:
1502      * Should we ever need some kind of block ordering, better make this function
1503      * move blocks around than write a block ordering algorithm later... after all
1504      * the ast and ir should work together, not against each other.
1505      */
1506
1507     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
1508      * anyway if for example it contains a ternary.
1509      */
1510     if (self->initexpr)
1511     {
1512         cgen = self->initexpr->expression.codegen;
1513         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
1514             return false;
1515     }
1516
1517     /* Store the block from which we enter this chaos */
1518     bin = func->curblock;
1519
1520     /* The pre-loop condition needs its own block since we
1521      * need to be able to jump to the start of that expression.
1522      */
1523     if (self->precond)
1524     {
1525         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
1526         if (!bprecond)
1527             return false;
1528
1529         /* the pre-loop-condition the least important place to 'continue' at */
1530         bcontinue = bprecond;
1531
1532         /* enter */
1533         func->curblock = bprecond;
1534
1535         /* generate */
1536         cgen = self->precond->expression.codegen;
1537         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
1538             return false;
1539
1540         end_bprecond = func->curblock;
1541     } else {
1542         bprecond = end_bprecond = NULL;
1543     }
1544
1545     /* Now the next blocks won't be ordered nicely, but we need to
1546      * generate them this early for 'break' and 'continue'.
1547      */
1548     if (self->increment) {
1549         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
1550         if (!bincrement)
1551             return false;
1552         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
1553     } else {
1554         bincrement = end_bincrement = NULL;
1555     }
1556
1557     if (self->postcond) {
1558         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
1559         if (!bpostcond)
1560             return false;
1561         bcontinue = bpostcond; /* postcond comes before the increment */
1562     } else {
1563         bpostcond = end_bpostcond = NULL;
1564     }
1565
1566     bout_id = func->ir_func->blocks_count;
1567     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
1568     if (!bout)
1569         return false;
1570     bbreak = bout;
1571
1572     /* The loop body... */
1573     if (self->body)
1574     {
1575         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
1576         if (!bbody)
1577             return false;
1578
1579         /* enter */
1580         func->curblock = bbody;
1581
1582         old_bbreak          = func->breakblock;
1583         old_bcontinue       = func->continueblock;
1584         func->breakblock    = bbreak;
1585         func->continueblock = bcontinue;
1586
1587         /* generate */
1588         cgen = self->body->expression.codegen;
1589         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
1590             return false;
1591
1592         end_bbody = func->curblock;
1593         func->breakblock    = old_bbreak;
1594         func->continueblock = old_bcontinue;
1595     }
1596
1597     /* post-loop-condition */
1598     if (self->postcond)
1599     {
1600         /* enter */
1601         func->curblock = bpostcond;
1602
1603         /* generate */
1604         cgen = self->postcond->expression.codegen;
1605         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
1606             return false;
1607
1608         end_bpostcond = func->curblock;
1609     }
1610
1611     /* The incrementor */
1612     if (self->increment)
1613     {
1614         /* enter */
1615         func->curblock = bincrement;
1616
1617         /* generate */
1618         cgen = self->increment->expression.codegen;
1619         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
1620             return false;
1621
1622         end_bincrement = func->curblock;
1623     }
1624
1625     /* In any case now, we continue from the outgoing block */
1626     func->curblock = bout;
1627
1628     /* Now all blocks are in place */
1629     /* From 'bin' we jump to whatever comes first */
1630     if      (bprecond)   tmpblock = bprecond;
1631     else if (bbody)      tmpblock = bbody;
1632     else if (bpostcond)  tmpblock = bpostcond;
1633     else                 tmpblock = bout;
1634     if (!ir_block_create_jump(bin, tmpblock))
1635         return false;
1636
1637     /* From precond */
1638     if (bprecond)
1639     {
1640         ir_block *ontrue, *onfalse;
1641         if      (bbody)      ontrue = bbody;
1642         else if (bincrement) ontrue = bincrement;
1643         else if (bpostcond)  ontrue = bpostcond;
1644         else                 ontrue = bprecond;
1645         onfalse = bout;
1646         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
1647             return false;
1648     }
1649
1650     /* from body */
1651     if (bbody)
1652     {
1653         if      (bincrement) tmpblock = bincrement;
1654         else if (bpostcond)  tmpblock = bpostcond;
1655         else if (bprecond)   tmpblock = bprecond;
1656         else                 tmpblock = bout;
1657         if (!ir_block_create_jump(end_bbody, tmpblock))
1658             return false;
1659     }
1660
1661     /* from increment */
1662     if (bincrement)
1663     {
1664         if      (bpostcond)  tmpblock = bpostcond;
1665         else if (bprecond)   tmpblock = bprecond;
1666         else if (bbody)      tmpblock = bbody;
1667         else                 tmpblock = bout;
1668         if (!ir_block_create_jump(end_bincrement, tmpblock))
1669             return false;
1670     }
1671
1672     /* from postcond */
1673     if (bpostcond)
1674     {
1675         ir_block *ontrue, *onfalse;
1676         if      (bprecond)   ontrue = bprecond;
1677         else if (bbody)      ontrue = bbody;
1678         else if (bincrement) ontrue = bincrement;
1679         else                 ontrue = bpostcond;
1680         onfalse = bout;
1681         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
1682             return false;
1683     }
1684
1685     /* Move 'bout' to the end */
1686     if (!ir_function_blocks_remove(func->ir_func, bout_id) ||
1687         !ir_function_blocks_add(func->ir_func, bout))
1688     {
1689         ir_block_delete(bout);
1690         return false;
1691     }
1692
1693     return true;
1694 }
1695
1696 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
1697 {
1698     ast_expression_codegen *cgen;
1699     ir_value_vector         params;
1700     ir_instr               *callinstr;
1701     size_t i;
1702
1703     ir_value *funval = NULL;
1704
1705     /* return values are never lvalues */
1706     (void)lvalue;
1707
1708     if (self->expression.outr) {
1709         *out = self->expression.outr;
1710         return true;
1711     }
1712
1713     cgen = self->func->expression.codegen;
1714     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
1715         return false;
1716     if (!funval)
1717         return false;
1718
1719     MEM_VECTOR_INIT(&params, v);
1720
1721     /* parameters */
1722     for (i = 0; i < self->params_count; ++i)
1723     {
1724         ir_value *param;
1725         ast_expression *expr = self->params[i];
1726
1727         cgen = expr->expression.codegen;
1728         if (!(*cgen)(expr, func, false, &param))
1729             goto error;
1730         if (!param)
1731             goto error;
1732         if (!ir_value_vector_v_add(&params, param))
1733             goto error;
1734     }
1735
1736     callinstr = ir_block_create_call(func->curblock, ast_function_label(func, "call"), funval);
1737     if (!callinstr)
1738         goto error;
1739
1740     for (i = 0; i < params.v_count; ++i) {
1741         if (!ir_call_param(callinstr, params.v[i]))
1742             goto error;
1743     }
1744
1745     *out = ir_call_value(callinstr);
1746     self->expression.outr = *out;
1747
1748     MEM_VECTOR_CLEAR(&params, v);
1749     return true;
1750 error:
1751     MEM_VECTOR_CLEAR(&params, v);
1752     return false;
1753 }