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