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