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