]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
the IR won't create globals of the same name - make names starting with # an exception
[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);                            \
36     ( (ast_node*)self )->node.destroy = (ast_node_delete*)destroyfn
37
38 /* It must not be possible to get here. */
39 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
40 {
41     fprintf(stderr, "ast node missing destroy()\n");
42     abort();
43 }
44
45 /* Initialize main ast node aprts */
46 static void ast_node_init(ast_node *self, lex_ctx ctx)
47 {
48     self->node.context = ctx;
49     self->node.destroy = &_ast_node_destroy;
50     self->node.keep    = false;
51 }
52
53 /* General expression initialization */
54 static void ast_expression_init(ast_expression *self,
55                                 ast_expression_codegen *codegen)
56 {
57     self->expression.codegen = codegen;
58     self->expression.vtype   = TYPE_VOID;
59     self->expression.next    = NULL;
60 }
61
62 static void ast_expression_delete(ast_expression *self)
63 {
64     if (self->expression.next)
65         ast_delete(self->expression.next);
66 }
67
68 static void ast_expression_delete_full(ast_expression *self)
69 {
70     ast_expression_delete(self);
71     mem_d(self);
72 }
73
74 static ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
75 {
76     const ast_expression_common *cpex;
77     ast_expression_common *selfex;
78
79     if (!ex)
80         return NULL;
81     else
82     {
83         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
84
85         cpex   = &ex->expression;
86         selfex = &self->expression;
87
88         selfex->vtype = cpex->vtype;
89         if (cpex->next)
90         {
91             selfex->next = ast_type_copy(ctx, cpex->next);
92             if (!selfex->next) {
93                 mem_d(self);
94                 return NULL;
95             }
96         }
97         else
98             selfex->next = NULL;
99
100         /* This may never be codegen()d */
101         selfex->codegen = NULL;
102         return self;
103     }
104 }
105
106 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
107 {
108     ast_instantiate(ast_value, ctx, ast_value_delete);
109     ast_expression_init((ast_expression*)self,
110                         (ast_expression_codegen*)&ast_value_codegen);
111     self->expression.node.keep = true; /* keep */
112
113     self->name = name ? util_strdup(name) : NULL;
114     self->expression.vtype = t;
115     self->expression.next  = NULL;
116     MEM_VECTOR_INIT(self, params);
117     self->isconst = false;
118     memset(&self->constval, 0, sizeof(self->constval));
119
120     self->ir_v    = NULL;
121
122     return self;
123 }
124 MEM_VEC_FUNCTIONS(ast_value, ast_value*, params)
125
126 void ast_value_delete(ast_value* self)
127 {
128     size_t i;
129     if (self->name)
130         mem_d((void*)self->name);
131     for (i = 0; i < self->params_count; ++i)
132         ast_value_delete(self->params[i]); /* delete, the ast_function is expected to die first */
133     MEM_VECTOR_CLEAR(self, params);
134     if (self->isconst) {
135         switch (self->expression.vtype)
136         {
137         case TYPE_STRING:
138             mem_d((void*)self->constval.vstring);
139             break;
140         case TYPE_FUNCTION:
141             /* unlink us from the function node */
142             self->constval.vfunc->vtype = NULL;
143             break;
144         /* NOTE: delete function? currently collected in
145          * the parser structure
146          */
147         default:
148             break;
149         }
150     }
151     ast_expression_delete((ast_expression*)self);
152     mem_d(self);
153 }
154
155 bool ast_value_set_name(ast_value *self, const char *name)
156 {
157     if (self->name)
158         mem_d((void*)self->name);
159     self->name = util_strdup(name);
160     return !!self->name;
161 }
162
163 ast_binary* ast_binary_new(lex_ctx ctx, int op,
164                            ast_expression* left, ast_expression* right)
165 {
166     ast_instantiate(ast_binary, ctx, ast_binary_delete);
167     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
168
169     self->op = op;
170     self->left = left;
171     self->right = right;
172
173     return self;
174 }
175
176 void ast_binary_delete(ast_binary *self)
177 {
178     ast_unref(self->left);
179     ast_unref(self->right);
180     ast_expression_delete((ast_expression*)self);
181     mem_d(self);
182 }
183
184 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
185 {
186     const ast_expression *outtype;
187
188     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
189
190     if (field->expression.vtype != TYPE_FIELD) {
191         mem_d(self);
192         return NULL;
193     }
194
195     outtype = field->expression.next;
196     if (!outtype) {
197         mem_d(self);
198         /* Error: field has no type... */
199         return NULL;
200     }
201
202     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
203
204     self->expression.vtype = outtype->expression.vtype;
205     self->expression.next  = ast_type_copy(ctx, outtype->expression.next);
206
207     self->entity = entity;
208     self->field  = field;
209
210     return self;
211 }
212
213 void ast_entfield_delete(ast_entfield *self)
214 {
215     ast_unref(self->entity);
216     ast_unref(self->field);
217     ast_expression_delete((ast_expression*)self);
218     mem_d(self);
219 }
220
221 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
222 {
223     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
224     if (!ontrue && !onfalse) {
225         /* because it is invalid */
226         mem_d(self);
227         return NULL;
228     }
229     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
230
231     self->cond     = cond;
232     self->on_true  = ontrue;
233     self->on_false = onfalse;
234
235     return self;
236 }
237
238 void ast_ifthen_delete(ast_ifthen *self)
239 {
240     ast_unref(self->cond);
241     if (self->on_true)
242         ast_unref(self->on_true);
243     if (self->on_false)
244         ast_unref(self->on_false);
245     ast_expression_delete((ast_expression*)self);
246     mem_d(self);
247 }
248
249 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
250 {
251     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
252     /* This time NEITHER must be NULL */
253     if (!ontrue || !onfalse) {
254         mem_d(self);
255         return NULL;
256     }
257     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
258
259     self->cond     = cond;
260     self->on_true  = ontrue;
261     self->on_false = onfalse;
262     self->phi_out  = NULL;
263
264     return self;
265 }
266
267 void ast_ternary_delete(ast_ternary *self)
268 {
269     ast_unref(self->cond);
270     ast_unref(self->on_true);
271     ast_unref(self->on_false);
272     ast_expression_delete((ast_expression*)self);
273     mem_d(self);
274 }
275
276 ast_loop* ast_loop_new(lex_ctx ctx,
277                        ast_expression *initexpr,
278                        ast_expression *precond,
279                        ast_expression *postcond,
280                        ast_expression *increment,
281                        ast_expression *body)
282 {
283     ast_instantiate(ast_loop, ctx, ast_loop_delete);
284     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
285
286     self->initexpr  = initexpr;
287     self->precond   = precond;
288     self->postcond  = postcond;
289     self->increment = increment;
290     self->body      = body;
291
292     return self;
293 }
294
295 void ast_loop_delete(ast_loop *self)
296 {
297     if (self->initexpr)
298         ast_unref(self->initexpr);
299     if (self->precond)
300         ast_unref(self->precond);
301     if (self->postcond)
302         ast_unref(self->postcond);
303     if (self->increment)
304         ast_unref(self->increment);
305     if (self->body)
306         ast_unref(self->body);
307     ast_expression_delete((ast_expression*)self);
308     mem_d(self);
309 }
310
311 ast_call* ast_call_new(lex_ctx ctx,
312                        ast_expression *funcexpr)
313 {
314     ast_instantiate(ast_call, ctx, ast_call_delete);
315     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
316
317     MEM_VECTOR_INIT(self, params);
318
319     self->func = funcexpr;
320
321     return self;
322 }
323 MEM_VEC_FUNCTIONS(ast_call, ast_expression*, params)
324
325 void ast_call_delete(ast_call *self)
326 {
327     size_t i;
328     for (i = 0; i < self->params_count; ++i)
329         ast_unref(self->params[i]);
330     MEM_VECTOR_CLEAR(self, params);
331
332     if (self->func)
333         ast_unref(self->func);
334
335     ast_expression_delete((ast_expression*)self);
336     mem_d(self);
337 }
338
339 ast_store* ast_store_new(lex_ctx ctx, int op,
340                          ast_value *dest, ast_expression *source)
341 {
342     ast_instantiate(ast_store, ctx, ast_store_delete);
343     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
344
345     self->op = op;
346     self->dest = dest;
347     self->source = source;
348
349     return self;
350 }
351
352 void ast_store_delete(ast_store *self)
353 {
354     ast_unref(self->dest);
355     ast_unref(self->source);
356     ast_expression_delete((ast_expression*)self);
357     mem_d(self);
358 }
359
360 ast_block* ast_block_new(lex_ctx ctx)
361 {
362     ast_instantiate(ast_block, ctx, ast_block_delete);
363     ast_expression_init((ast_expression*)self,
364                         (ast_expression_codegen*)&ast_block_codegen);
365
366     MEM_VECTOR_INIT(self, locals);
367     MEM_VECTOR_INIT(self, exprs);
368
369     return self;
370 }
371 MEM_VEC_FUNCTIONS(ast_block, ast_value*, locals)
372 MEM_VEC_FUNCTIONS(ast_block, ast_expression*, exprs)
373
374 void ast_block_delete(ast_block *self)
375 {
376     size_t i;
377     for (i = 0; i < self->exprs_count; ++i)
378         ast_unref(self->exprs[i]);
379     MEM_VECTOR_CLEAR(self, exprs);
380     for (i = 0; i < self->locals_count; ++i)
381         ast_delete(self->locals[i]);
382     MEM_VECTOR_CLEAR(self, locals);
383     ast_expression_delete((ast_expression*)self);
384     mem_d(self);
385 }
386
387 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
388 {
389     ast_instantiate(ast_function, ctx, ast_function_delete);
390
391     if (!vtype ||
392         vtype->isconst ||
393         vtype->expression.vtype != TYPE_FUNCTION)
394     {
395         mem_d(self);
396         return NULL;
397     }
398
399     self->vtype = vtype;
400     self->name = name ? util_strdup(name) : NULL;
401     MEM_VECTOR_INIT(self, blocks);
402
403     self->labelcount = 0;
404     self->builtin = 0;
405
406     self->ir_func = NULL;
407     self->curblock = NULL;
408
409     self->breakblock    = NULL;
410     self->continueblock = NULL;
411
412     vtype->isconst = true;
413     vtype->constval.vfunc = self;
414
415     return self;
416 }
417
418 MEM_VEC_FUNCTIONS(ast_function, ast_block*, blocks)
419
420 void ast_function_delete(ast_function *self)
421 {
422     size_t i;
423     if (self->name)
424         mem_d((void*)self->name);
425     if (self->vtype) {
426         /* ast_value_delete(self->vtype); */
427         self->vtype->isconst = false;
428         self->vtype->constval.vfunc = NULL;
429         /* We use unref - if it was stored in a global table it is supposed
430          * to be deleted from *there*
431          */
432         ast_unref(self->vtype);
433     }
434     for (i = 0; i < self->blocks_count; ++i)
435         ast_delete(self->blocks[i]);
436     MEM_VECTOR_CLEAR(self, blocks);
437     mem_d(self);
438 }
439
440 static void ast_util_hexitoa(char *buf, size_t size, unsigned int num)
441 {
442     unsigned int base = 10;
443 #define checknul() do { if (size == 1) { *buf = 0; return; } } while (0)
444 #define addch(x) do { *buf++ = (x); --size; checknul(); } while (0)
445     if (size < 1)
446         return;
447     checknul();
448     if (!num)
449         addch('0');
450     else {
451         while (num)
452         {
453             int digit = num % base;
454             num /= base;
455             addch('0' + digit);
456         }
457     }
458
459     *buf = 0;
460 #undef addch
461 #undef checknul
462 }
463
464 const char* ast_function_label(ast_function *self, const char *prefix)
465 {
466     size_t id = (self->labelcount++);
467     size_t len = strlen(prefix);
468     strncpy(self->labelbuf, prefix, sizeof(self->labelbuf));
469     ast_util_hexitoa(self->labelbuf + len, sizeof(self->labelbuf)-len, id);
470     return self->labelbuf;
471 }
472
473 /*********************************************************************/
474 /* AST codegen part
475  * by convention you must never pass NULL to the 'ir_value **out'
476  * parameter. If you really don't care about the output, pass a dummy.
477  * But I can't imagine a pituation where the output is truly unnecessary.
478  */
479
480 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
481 {
482     /* NOTE: This is the codegen for a variable used in an expression.
483      * It is not the codegen to generate the value. For this purpose,
484      * ast_local_codegen and ast_global_codegen are to be used before this
485      * is executed. ast_function_codegen should take care of its locals,
486      * and the ast-user should take care of ast_global_codegen to be used
487      * on all the globals.
488      */
489     if (!self->ir_v) {
490         printf("ast_value used before generated (%s)\n", self->name);
491         return false;
492     }
493     *out = self->ir_v;
494     return true;
495 }
496
497 bool ast_global_codegen(ast_value *self, ir_builder *ir)
498 {
499     ir_value *v = NULL;
500     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
501     {
502         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
503         if (!func)
504             return false;
505
506         self->constval.vfunc->ir_func = func;
507         self->ir_v = func->value;
508         /* The function is filled later on ast_function_codegen... */
509         return true;
510     }
511
512     v = ir_builder_create_global(ir, self->name, self->expression.vtype);
513     if (!v) {
514         printf("ir_builder_create_global failed\n");
515         return false;
516     }
517
518     if (self->isconst) {
519         switch (self->expression.vtype)
520         {
521             case TYPE_FLOAT:
522                 if (!ir_value_set_float(v, self->constval.vfloat))
523                     goto error;
524                 break;
525             case TYPE_VECTOR:
526                 if (!ir_value_set_vector(v, self->constval.vvec))
527                     goto error;
528                 break;
529             case TYPE_STRING:
530                 if (!ir_value_set_string(v, self->constval.vstring))
531                     goto error;
532                 break;
533             case TYPE_FUNCTION:
534                 printf("global of type function not properly generated\n");
535                 goto error;
536                 /* Cannot generate an IR value for a function,
537                  * need a pointer pointing to a function rather.
538                  */
539             default:
540                 printf("TODO: global constant type %i\n", self->expression.vtype);
541                 break;
542         }
543     }
544
545     /* link us to the ir_value */
546     self->ir_v = v;
547     return true;
548
549 error: /* clean up */
550     ir_value_delete(v);
551     return false;
552 }
553
554 bool ast_local_codegen(ast_value *self, ir_function *func)
555 {
556     ir_value *v = NULL;
557     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
558     {
559         /* Do we allow local functions? I think not...
560          * this is NOT a function pointer atm.
561          */
562         return false;
563     }
564
565     v = ir_function_create_local(func, self->name, self->expression.vtype);
566     if (!v)
567         return false;
568
569     /* A constant local... hmmm...
570      * I suppose the IR will have to deal with this
571      */
572     if (self->isconst) {
573         switch (self->expression.vtype)
574         {
575             case TYPE_FLOAT:
576                 if (!ir_value_set_float(v, self->constval.vfloat))
577                     goto error;
578                 break;
579             case TYPE_VECTOR:
580                 if (!ir_value_set_vector(v, self->constval.vvec))
581                     goto error;
582                 break;
583             case TYPE_STRING:
584                 if (!ir_value_set_string(v, self->constval.vstring))
585                     goto error;
586                 break;
587             default:
588                 printf("TODO: global constant type %i\n", self->expression.vtype);
589                 break;
590         }
591     }
592
593     /* link us to the ir_value */
594     self->ir_v = v;
595     return true;
596
597 error: /* clean up */
598     ir_value_delete(v);
599     return false;
600 }
601
602 bool ast_function_codegen(ast_function *self, ir_builder *ir)
603 {
604     ir_function *irf;
605     ir_value    *dummy;
606     size_t    i;
607
608     irf = self->ir_func;
609     if (!irf) {
610         printf("ast_function's related ast_value was not generated yet\n");
611         return false;
612     }
613
614     for (i = 0; i < self->vtype->params_count; ++i)
615     {
616         if (!ir_function_params_add(irf, self->vtype->params[i]->expression.vtype))
617             return false;
618     }
619
620     if (self->builtin) {
621         irf->builtin = self->builtin;
622         return true;
623     }
624
625     self->curblock = ir_function_create_block(irf, "entry");
626     if (!self->curblock)
627         return false;
628
629     for (i = 0; i < self->blocks_count; ++i) {
630         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
631         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
632             return false;
633     }
634
635     /* TODO: check return types */
636     if (!self->curblock->is_return)
637     {
638         if (!self->vtype->expression.next ||
639             self->vtype->expression.next->expression.vtype == TYPE_VOID)
640         {
641             return ir_block_create_return(self->curblock, NULL);
642         }
643         else
644         {
645             /* error("missing return"); */
646             return false;
647         }
648     }
649     return true;
650 }
651
652 /* Note, you will not see ast_block_codegen generate ir_blocks.
653  * To the AST and the IR, blocks are 2 different things.
654  * In the AST it represents a block of code, usually enclosed in
655  * curly braces {...}.
656  * While in the IR it represents a block in terms of control-flow.
657  */
658 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
659 {
660     size_t i;
661
662     /* We don't use this
663      * Note: an ast-representation using the comma-operator
664      * of the form: (a, b, c) = x should not assign to c...
665      */
666     (void)lvalue;
667
668     /* output is NULL at first, we'll have each expression
669      * assign to out output, thus, a comma-operator represention
670      * using an ast_block will return the last generated value,
671      * so: (b, c) + a  executed both b and c, and returns c,
672      * which is then added to a.
673      */
674     *out = NULL;
675
676     /* generate locals */
677     for (i = 0; i < self->locals_count; ++i)
678     {
679         if (!ast_local_codegen(self->locals[i], func->ir_func))
680             return false;
681     }
682
683     for (i = 0; i < self->exprs_count; ++i)
684     {
685         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
686         if (!(*gen)(self->exprs[i], func, false, out))
687             return false;
688     }
689
690     return true;
691 }
692
693 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
694 {
695     ast_expression_codegen *cgen;
696     ir_value *left, *right;
697
698     cgen = self->dest->expression.codegen;
699     /* lvalue! */
700     if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
701         return false;
702
703     cgen = self->source->expression.codegen;
704     /* rvalue! */
705     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
706         return false;
707
708     if (!ir_block_create_store_op(func->curblock, self->op, left, right))
709         return false;
710
711     /* Theoretically, an assinment returns its left side as an
712      * lvalue, if we don't need an lvalue though, we return
713      * the right side as an rvalue, otherwise we have to
714      * somehow know whether or not we need to dereference the pointer
715      * on the left side - that is: OP_LOAD if it was an address.
716      * Also: in original QC we cannot OP_LOADP *anyway*.
717      */
718     *out = (lvalue ? left : right);
719
720     return true;
721 }
722
723 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
724 {
725     ast_expression_codegen *cgen;
726     ir_value *left, *right;
727
728     /* In the context of a binary operation, we can disregard
729      * the lvalue flag.
730      */
731      (void)lvalue;
732
733     cgen = self->left->expression.codegen;
734     /* lvalue! */
735     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
736         return false;
737
738     cgen = self->right->expression.codegen;
739     /* rvalue! */
740     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
741         return false;
742
743     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
744                                  self->op, left, right);
745     if (!*out)
746         return false;
747
748     return true;
749 }
750
751 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
752 {
753     ast_expression_codegen *cgen;
754     ir_value *ent, *field;
755
756     /* This function needs to take the 'lvalue' flag into account!
757      * As lvalue we provide a field-pointer, as rvalue we provide the
758      * value in a temp.
759      */
760
761     cgen = self->entity->expression.codegen;
762     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
763         return false;
764
765     cgen = self->field->expression.codegen;
766     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
767         return false;
768
769     if (lvalue) {
770         /* address! */
771         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
772                                             ent, field);
773     } else {
774         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
775                                              ent, field, self->expression.vtype);
776     }
777     if (!*out)
778         return false;
779
780     /* Hm that should be it... */
781     return true;
782 }
783
784 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
785 {
786     ast_expression_codegen *cgen;
787
788     ir_value *condval;
789     ir_value *dummy;
790
791     ir_block *cond = func->curblock;
792     ir_block *ontrue;
793     ir_block *onfalse;
794     ir_block *merge;
795
796     /* We don't output any value, thus also don't care about r/lvalue */
797     (void)out;
798     (void)lvalue;
799
800     /* generate the condition */
801     func->curblock = cond;
802     cgen = self->cond->expression.codegen;
803     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
804         return false;
805
806     /* on-true path */
807
808     if (self->on_true) {
809         /* create on-true block */
810         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
811         if (!ontrue)
812             return false;
813
814         /* enter the block */
815         func->curblock = ontrue;
816
817         /* generate */
818         cgen = self->on_true->expression.codegen;
819         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
820             return false;
821     } else
822         ontrue = NULL;
823
824     /* on-false path */
825     if (self->on_false) {
826         /* create on-false block */
827         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
828         if (!onfalse)
829             return false;
830
831         /* enter the block */
832         func->curblock = onfalse;
833
834         /* generate */
835         cgen = self->on_false->expression.codegen;
836         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
837             return false;
838     } else
839         onfalse = NULL;
840
841     /* Merge block were they all merge in to */
842     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
843     if (!merge)
844         return false;
845
846     /* add jumps ot the merge block */
847     if (ontrue && !ir_block_create_jump(ontrue, merge))
848         return false;
849     if (onfalse && !ir_block_create_jump(onfalse, merge))
850         return false;
851
852     /* we create the if here, that way all blocks are ordered :)
853      */
854     if (!ir_block_create_if(cond, condval,
855                             (ontrue  ? ontrue  : merge),
856                             (onfalse ? onfalse : merge)))
857     {
858         return false;
859     }
860
861     /* Now enter the merge block */
862     func->curblock = merge;
863
864     return true;
865 }
866
867 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
868 {
869     ast_expression_codegen *cgen;
870
871     ir_value *condval;
872     ir_value *trueval, *falseval;
873     ir_instr *phi;
874
875     ir_block *cond = func->curblock;
876     ir_block *ontrue;
877     ir_block *onfalse;
878     ir_block *merge;
879
880     /* In theory it shouldn't be possible to pass through a node twice, but
881      * in case we add any kind of optimization pass for the AST itself, it
882      * may still happen, thus we remember a created ir_value and simply return one
883      * if it already exists.
884      */
885     if (self->phi_out) {
886         *out = self->phi_out;
887         return true;
888     }
889
890     /* Ternary can never create an lvalue... */
891     if (lvalue)
892         return false;
893
894     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
895
896     /* generate the condition */
897     func->curblock = cond;
898     cgen = self->cond->expression.codegen;
899     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
900         return false;
901
902     /* create on-true block */
903     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
904     if (!ontrue)
905         return false;
906     else
907     {
908         /* enter the block */
909         func->curblock = ontrue;
910
911         /* generate */
912         cgen = self->on_true->expression.codegen;
913         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
914             return false;
915     }
916
917     /* create on-false block */
918     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
919     if (!onfalse)
920         return false;
921     else
922     {
923         /* enter the block */
924         func->curblock = onfalse;
925
926         /* generate */
927         cgen = self->on_false->expression.codegen;
928         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
929             return false;
930     }
931
932     /* create merge block */
933     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
934     if (!merge)
935         return false;
936     /* jump to merge block */
937     if (!ir_block_create_jump(ontrue, merge))
938         return false;
939     if (!ir_block_create_jump(onfalse, merge))
940         return false;
941
942     /* create if instruction */
943     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
944         return false;
945
946     /* Now enter the merge block */
947     func->curblock = merge;
948
949     /* Here, now, we need a PHI node
950      * but first some sanity checking...
951      */
952     if (trueval->vtype != falseval->vtype) {
953         /* error("ternary with different types on the two sides"); */
954         return false;
955     }
956
957     /* create PHI */
958     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
959     if (!phi ||
960         !ir_phi_add(phi, ontrue,  trueval) ||
961         !ir_phi_add(phi, onfalse, falseval))
962     {
963         return false;
964     }
965
966     self->phi_out = ir_phi_value(phi);
967     *out = self->phi_out;
968
969     return true;
970 }
971
972 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
973 {
974     ast_expression_codegen *cgen;
975
976     ir_value *dummy      = NULL;
977     ir_value *precond    = NULL;
978     ir_value *postcond   = NULL;
979
980     /* Since we insert some jumps "late" so we have blocks
981      * ordered "nicely", we need to keep track of the actual end-blocks
982      * of expressions to add the jumps to.
983      */
984     ir_block *bbody      = NULL, *end_bbody      = NULL;
985     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
986     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
987     ir_block *bincrement = NULL, *end_bincrement = NULL;
988     ir_block *bout       = NULL, *bin            = NULL;
989
990     /* let's at least move the outgoing block to the end */
991     size_t    bout_id;
992
993     /* 'break' and 'continue' need to be able to find the right blocks */
994     ir_block *bcontinue     = NULL;
995     ir_block *bbreak        = NULL;
996
997     ir_block *old_bcontinue = NULL;
998     ir_block *old_bbreak    = NULL;
999
1000     ir_block *tmpblock      = NULL;
1001
1002     (void)lvalue;
1003     (void)out;
1004
1005     /* NOTE:
1006      * Should we ever need some kind of block ordering, better make this function
1007      * move blocks around than write a block ordering algorithm later... after all
1008      * the ast and ir should work together, not against each other.
1009      */
1010
1011     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
1012      * anyway if for example it contains a ternary.
1013      */
1014     if (self->initexpr)
1015     {
1016         cgen = self->initexpr->expression.codegen;
1017         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
1018             return false;
1019     }
1020
1021     /* Store the block from which we enter this chaos */
1022     bin = func->curblock;
1023
1024     /* The pre-loop condition needs its own block since we
1025      * need to be able to jump to the start of that expression.
1026      */
1027     if (self->precond)
1028     {
1029         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
1030         if (!bprecond)
1031             return false;
1032
1033         /* the pre-loop-condition the least important place to 'continue' at */
1034         bcontinue = bprecond;
1035
1036         /* enter */
1037         func->curblock = bprecond;
1038
1039         /* generate */
1040         cgen = self->precond->expression.codegen;
1041         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
1042             return false;
1043
1044         end_bprecond = func->curblock;
1045     } else {
1046         bprecond = end_bprecond = NULL;
1047     }
1048
1049     /* Now the next blocks won't be ordered nicely, but we need to
1050      * generate them this early for 'break' and 'continue'.
1051      */
1052     if (self->increment) {
1053         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
1054         if (!bincrement)
1055             return false;
1056         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
1057     } else {
1058         bincrement = end_bincrement = NULL;
1059     }
1060
1061     if (self->postcond) {
1062         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
1063         if (!bpostcond)
1064             return false;
1065         bcontinue = bpostcond; /* postcond comes before the increment */
1066     } else {
1067         bpostcond = end_bpostcond = NULL;
1068     }
1069
1070     bout_id = func->ir_func->blocks_count;
1071     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
1072     if (!bout)
1073         return false;
1074     bbreak = bout;
1075
1076     /* The loop body... */
1077     if (self->body)
1078     {
1079         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
1080         if (!bbody)
1081             return false;
1082
1083         /* enter */
1084         func->curblock = bbody;
1085
1086         old_bbreak          = func->breakblock;
1087         old_bcontinue       = func->continueblock;
1088         func->breakblock    = bbreak;
1089         func->continueblock = bcontinue;
1090
1091         /* generate */
1092         cgen = self->body->expression.codegen;
1093         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
1094             return false;
1095
1096         end_bbody = func->curblock;
1097         func->breakblock    = old_bbreak;
1098         func->continueblock = old_bcontinue;
1099     }
1100
1101     /* post-loop-condition */
1102     if (self->postcond)
1103     {
1104         /* enter */
1105         func->curblock = bpostcond;
1106
1107         /* generate */
1108         cgen = self->postcond->expression.codegen;
1109         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
1110             return false;
1111
1112         end_bpostcond = func->curblock;
1113     }
1114
1115     /* The incrementor */
1116     if (self->increment)
1117     {
1118         /* enter */
1119         func->curblock = bincrement;
1120
1121         /* generate */
1122         cgen = self->increment->expression.codegen;
1123         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
1124             return false;
1125
1126         end_bincrement = func->curblock;
1127     }
1128
1129     /* In any case now, we continue from the outgoing block */
1130     func->curblock = bout;
1131
1132     /* Now all blocks are in place */
1133     /* From 'bin' we jump to whatever comes first */
1134     if      (bprecond)   tmpblock = bprecond;
1135     else if (bbody)      tmpblock = bbody;
1136     else if (bpostcond)  tmpblock = bpostcond;
1137     else                 tmpblock = bout;
1138     if (!ir_block_create_jump(bin, tmpblock))
1139         return false;
1140
1141     /* From precond */
1142     if (bprecond)
1143     {
1144         ir_block *ontrue, *onfalse;
1145         if      (bbody)      ontrue = bbody;
1146         else if (bincrement) ontrue = bincrement;
1147         else if (bpostcond)  ontrue = bpostcond;
1148         else                 ontrue = bprecond;
1149         onfalse = bout;
1150         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
1151             return false;
1152     }
1153
1154     /* from body */
1155     if (bbody)
1156     {
1157         if      (bincrement) tmpblock = bincrement;
1158         else if (bpostcond)  tmpblock = bpostcond;
1159         else if (bprecond)   tmpblock = bprecond;
1160         else                 tmpblock = bout;
1161         if (!ir_block_create_jump(end_bbody, tmpblock))
1162             return false;
1163     }
1164
1165     /* from increment */
1166     if (bincrement)
1167     {
1168         if      (bpostcond)  tmpblock = bpostcond;
1169         else if (bprecond)   tmpblock = bprecond;
1170         else if (bbody)      tmpblock = bbody;
1171         else                 tmpblock = bout;
1172         if (!ir_block_create_jump(end_bincrement, tmpblock))
1173             return false;
1174     }
1175
1176     /* from postcond */
1177     if (bpostcond)
1178     {
1179         ir_block *ontrue, *onfalse;
1180         if      (bprecond)   ontrue = bprecond;
1181         else if (bbody)      ontrue = bbody;
1182         else if (bincrement) ontrue = bincrement;
1183         else                 ontrue = bpostcond;
1184         onfalse = bout;
1185         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
1186             return false;
1187     }
1188
1189     /* Move 'bout' to the end */
1190     if (!ir_function_blocks_remove(func->ir_func, bout_id) ||
1191         !ir_function_blocks_add(func->ir_func, bout))
1192     {
1193         ir_block_delete(bout);
1194         return false;
1195     }
1196
1197     return true;
1198 }
1199
1200 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
1201 {
1202     ast_expression_codegen *cgen;
1203     ir_value_vector         params;
1204     ir_instr               *callinstr;
1205     size_t i;
1206
1207     ir_value *funval = NULL;
1208
1209     /* return values are never rvalues */
1210     (void)lvalue;
1211
1212     cgen = self->func->expression.codegen;
1213     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
1214         return false;
1215     if (!funval)
1216         return false;
1217
1218     MEM_VECTOR_INIT(&params, v);
1219
1220     /* parameters */
1221     for (i = 0; i < self->params_count; ++i)
1222     {
1223         ir_value *param;
1224         ast_expression *expr = self->params[i];
1225
1226         cgen = expr->expression.codegen;
1227         if (!(*cgen)(expr, func, false, &param))
1228             goto error;
1229         if (!param)
1230             goto error;
1231         if (!ir_value_vector_v_add(&params, param))
1232             goto error;
1233     }
1234
1235     callinstr = ir_block_create_call(func->curblock, ast_function_label(func, "call"), funval);
1236     if (!callinstr)
1237         goto error;
1238
1239     for (i = 0; i < params.v_count; ++i) {
1240         if (!ir_call_param(callinstr, params.v[i]))
1241             goto error;
1242     }
1243
1244     *out = ir_call_value(callinstr);
1245
1246     return true;
1247 error:
1248     MEM_VECTOR_CLEAR(&params, v);
1249     return false;
1250 }