]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
Support codegen of ast_label and ast_goto in any order
[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
39 /* error handling */
40 static void asterror(lex_ctx ctx, const char *msg, ...)
41 {
42     va_list ap;
43     va_start(ap, msg);
44     con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", msg, ap);
45     va_end(ap);
46 }
47
48 /* It must not be possible to get here. */
49 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
50 {
51     (void)self;
52     con_err("ast node missing destroy()\n");
53     abort();
54 }
55
56 /* Initialize main ast node aprts */
57 static void ast_node_init(ast_node *self, lex_ctx ctx, int nodetype)
58 {
59     self->node.context = ctx;
60     self->node.destroy = &_ast_node_destroy;
61     self->node.keep    = false;
62     self->node.nodetype = nodetype;
63     self->node.side_effects = false;
64 }
65
66 /* weight and side effects */
67 static void _ast_propagate_effects(ast_node *self, ast_node *other)
68 {
69     if (ast_side_effects(other))
70         ast_side_effects(self) = true;
71 }
72 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
73
74 /* General expression initialization */
75 static void ast_expression_init(ast_expression *self,
76                                 ast_expression_codegen *codegen)
77 {
78     self->expression.codegen  = codegen;
79     self->expression.vtype    = TYPE_VOID;
80     self->expression.next     = NULL;
81     self->expression.outl     = NULL;
82     self->expression.outr     = NULL;
83     self->expression.variadic = false;
84     self->expression.params   = NULL;
85 }
86
87 static void ast_expression_delete(ast_expression *self)
88 {
89     size_t i;
90     if (self->expression.next)
91         ast_delete(self->expression.next);
92     for (i = 0; i < vec_size(self->expression.params); ++i) {
93         ast_delete(self->expression.params[i]);
94     }
95     vec_free(self->expression.params);
96 }
97
98 static void ast_expression_delete_full(ast_expression *self)
99 {
100     ast_expression_delete(self);
101     mem_d(self);
102 }
103
104 ast_value* ast_value_copy(const ast_value *self)
105 {
106     size_t i;
107     const ast_expression_common *fromex;
108     ast_expression_common *selfex;
109     ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
110     if (self->expression.next) {
111         cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
112         if (!cp->expression.next) {
113             ast_value_delete(cp);
114             return NULL;
115         }
116     }
117     fromex   = &self->expression;
118     selfex = &cp->expression;
119     selfex->variadic = fromex->variadic;
120     for (i = 0; i < vec_size(fromex->params); ++i) {
121         ast_value *v = ast_value_copy(fromex->params[i]);
122         if (!v) {
123             ast_value_delete(cp);
124             return NULL;
125         }
126         vec_push(selfex->params, v);
127     }
128     return cp;
129 }
130
131 bool ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
132 {
133     size_t i;
134     const ast_expression_common *fromex;
135     ast_expression_common *selfex;
136     self->expression.vtype = other->expression.vtype;
137     if (other->expression.next) {
138         self->expression.next = (ast_expression*)ast_type_copy(ast_ctx(self), other->expression.next);
139         if (!self->expression.next)
140             return false;
141     }
142     fromex   = &other->expression;
143     selfex = &self->expression;
144     selfex->variadic = fromex->variadic;
145     for (i = 0; i < vec_size(fromex->params); ++i) {
146         ast_value *v = ast_value_copy(fromex->params[i]);
147         if (!v)
148             return false;
149         vec_push(selfex->params, v);
150     }
151     return true;
152 }
153
154 static ast_expression* ast_shallow_type(lex_ctx ctx, int vtype)
155 {
156     ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
157     ast_expression_init(self, NULL);
158     self->expression.codegen = NULL;
159     self->expression.next    = NULL;
160     self->expression.vtype   = vtype;
161     return self;
162 }
163
164 ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
165 {
166     size_t i;
167     const ast_expression_common *fromex;
168     ast_expression_common *selfex;
169
170     if (!ex)
171         return NULL;
172     else
173     {
174         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
175         ast_expression_init(self, NULL);
176
177         fromex   = &ex->expression;
178         selfex = &self->expression;
179
180         /* This may never be codegen()d */
181         selfex->codegen = NULL;
182
183         selfex->vtype = fromex->vtype;
184         if (fromex->next)
185         {
186             selfex->next = ast_type_copy(ctx, fromex->next);
187             if (!selfex->next) {
188                 ast_expression_delete_full(self);
189                 return NULL;
190             }
191         }
192         else
193             selfex->next = NULL;
194
195         selfex->variadic = fromex->variadic;
196         for (i = 0; i < vec_size(fromex->params); ++i) {
197             ast_value *v = ast_value_copy(fromex->params[i]);
198             if (!v) {
199                 ast_expression_delete_full(self);
200                 return NULL;
201             }
202             vec_push(selfex->params, v);
203         }
204
205         return self;
206     }
207 }
208
209 bool ast_compare_type(ast_expression *a, ast_expression *b)
210 {
211     if (a->expression.vtype != b->expression.vtype)
212         return false;
213     if (!a->expression.next != !b->expression.next)
214         return false;
215     if (vec_size(a->expression.params) != vec_size(b->expression.params))
216         return false;
217     if (a->expression.variadic != b->expression.variadic)
218         return false;
219     if (vec_size(a->expression.params)) {
220         size_t i;
221         for (i = 0; i < vec_size(a->expression.params); ++i) {
222             if (!ast_compare_type((ast_expression*)a->expression.params[i],
223                                   (ast_expression*)b->expression.params[i]))
224                 return false;
225         }
226     }
227     if (a->expression.next)
228         return ast_compare_type(a->expression.next, b->expression.next);
229     return true;
230 }
231
232 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
233 {
234     const char *typestr;
235     size_t typelen;
236     size_t i;
237
238     if (!e) {
239         if (pos + 6 >= bufsize)
240             goto full;
241         strcpy(buf + pos, "(null)");
242         return pos + 6;
243     }
244
245     if (pos + 1 >= bufsize)
246         goto full;
247
248     switch (e->expression.vtype) {
249         case TYPE_VARIANT:
250             strcpy(buf + pos, "(variant)");
251             return pos + 9;
252
253         case TYPE_FIELD:
254             buf[pos++] = '.';
255             return ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
256
257         case TYPE_POINTER:
258             if (pos + 3 >= bufsize)
259                 goto full;
260             buf[pos++] = '*';
261             buf[pos++] = '(';
262             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
263             if (pos + 1 >= bufsize)
264                 goto full;
265             buf[pos++] = ')';
266             return pos;
267
268         case TYPE_FUNCTION:
269             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
270             if (pos + 2 >= bufsize)
271                 goto full;
272             if (!vec_size(e->expression.params)) {
273                 buf[pos++] = '(';
274                 buf[pos++] = ')';
275                 return pos;
276             }
277             buf[pos++] = '(';
278             pos = ast_type_to_string_impl((ast_expression*)(e->expression.params[0]), buf, bufsize, pos);
279             for (i = 1; i < vec_size(e->expression.params); ++i) {
280                 if (pos + 2 >= bufsize)
281                     goto full;
282                 buf[pos++] = ',';
283                 buf[pos++] = ' ';
284                 pos = ast_type_to_string_impl((ast_expression*)(e->expression.params[i]), buf, bufsize, pos);
285             }
286             if (pos + 1 >= bufsize)
287                 goto full;
288             buf[pos++] = ')';
289             return pos;
290
291         case TYPE_ARRAY:
292             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
293             if (pos + 1 >= bufsize)
294                 goto full;
295             buf[pos++] = '[';
296             pos += snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->expression.count);
297             if (pos + 1 >= bufsize)
298                 goto full;
299             buf[pos++] = ']';
300             return pos;
301
302         default:
303             typestr = type_name[e->expression.vtype];
304             typelen = strlen(typestr);
305             if (pos + typelen >= bufsize)
306                 goto full;
307             strcpy(buf + pos, typestr);
308             return pos + typelen;
309     }
310
311 full:
312     buf[bufsize-3] = '.';
313     buf[bufsize-2] = '.';
314     buf[bufsize-1] = '.';
315     return bufsize;
316 }
317
318 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
319 {
320     size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
321     buf[pos] = 0;
322 }
323
324 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
325 {
326     ast_instantiate(ast_value, ctx, ast_value_delete);
327     ast_expression_init((ast_expression*)self,
328                         (ast_expression_codegen*)&ast_value_codegen);
329     self->expression.node.keep = true; /* keep */
330
331     self->name = name ? util_strdup(name) : NULL;
332     self->expression.vtype = t;
333     self->expression.next  = NULL;
334     self->constant = false;
335     self->hasvalue = false;
336     self->uses    = 0;
337     memset(&self->constval, 0, sizeof(self->constval));
338
339     self->ir_v           = NULL;
340     self->ir_values      = NULL;
341     self->ir_value_count = 0;
342
343     self->setter = NULL;
344     self->getter = NULL;
345
346     return self;
347 }
348
349 void ast_value_delete(ast_value* self)
350 {
351     if (self->name)
352         mem_d((void*)self->name);
353     if (self->hasvalue) {
354         switch (self->expression.vtype)
355         {
356         case TYPE_STRING:
357             mem_d((void*)self->constval.vstring);
358             break;
359         case TYPE_FUNCTION:
360             /* unlink us from the function node */
361             self->constval.vfunc->vtype = NULL;
362             break;
363         /* NOTE: delete function? currently collected in
364          * the parser structure
365          */
366         default:
367             break;
368         }
369     }
370     if (self->ir_values)
371         mem_d(self->ir_values);
372     ast_expression_delete((ast_expression*)self);
373     mem_d(self);
374 }
375
376 void ast_value_params_add(ast_value *self, ast_value *p)
377 {
378     vec_push(self->expression.params, p);
379 }
380
381 bool ast_value_set_name(ast_value *self, const char *name)
382 {
383     if (self->name)
384         mem_d((void*)self->name);
385     self->name = util_strdup(name);
386     return !!self->name;
387 }
388
389 ast_binary* ast_binary_new(lex_ctx ctx, int op,
390                            ast_expression* left, ast_expression* right)
391 {
392     ast_instantiate(ast_binary, ctx, ast_binary_delete);
393     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
394
395     self->op = op;
396     self->left = left;
397     self->right = right;
398
399     ast_propagate_effects(self, left);
400     ast_propagate_effects(self, right);
401
402     if (op >= INSTR_EQ_F && op <= INSTR_GT)
403         self->expression.vtype = TYPE_FLOAT;
404     else if (op == INSTR_AND || op == INSTR_OR ||
405              op == INSTR_BITAND || op == INSTR_BITOR)
406         self->expression.vtype = TYPE_FLOAT;
407     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
408         self->expression.vtype = TYPE_VECTOR;
409     else if (op == INSTR_MUL_V)
410         self->expression.vtype = TYPE_FLOAT;
411     else
412         self->expression.vtype = left->expression.vtype;
413
414     return self;
415 }
416
417 void ast_binary_delete(ast_binary *self)
418 {
419     ast_unref(self->left);
420     ast_unref(self->right);
421     ast_expression_delete((ast_expression*)self);
422     mem_d(self);
423 }
424
425 ast_binstore* ast_binstore_new(lex_ctx ctx, int storop, int op,
426                                ast_expression* left, ast_expression* right)
427 {
428     ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
429     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
430
431     ast_side_effects(self) = true;
432
433     self->opstore = storop;
434     self->opbin   = op;
435     self->dest    = left;
436     self->source  = right;
437
438     self->expression.vtype = left->expression.vtype;
439     if (left->expression.next) {
440         self->expression.next = ast_type_copy(ctx, left);
441         if (!self->expression.next) {
442             ast_delete(self);
443             return NULL;
444         }
445     }
446     else
447         self->expression.next = NULL;
448
449     return self;
450 }
451
452 void ast_binstore_delete(ast_binstore *self)
453 {
454     ast_unref(self->dest);
455     ast_unref(self->source);
456     ast_expression_delete((ast_expression*)self);
457     mem_d(self);
458 }
459
460 ast_unary* ast_unary_new(lex_ctx ctx, int op,
461                          ast_expression *expr)
462 {
463     ast_instantiate(ast_unary, ctx, ast_unary_delete);
464     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
465
466     self->op = op;
467     self->operand = expr;
468
469     ast_propagate_effects(self, expr);
470
471     if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
472         self->expression.vtype = TYPE_FLOAT;
473     } else
474         asterror(ctx, "cannot determine type of unary operation %s", asm_instr[op].m);
475
476     return self;
477 }
478
479 void ast_unary_delete(ast_unary *self)
480 {
481     ast_unref(self->operand);
482     ast_expression_delete((ast_expression*)self);
483     mem_d(self);
484 }
485
486 ast_return* ast_return_new(lex_ctx ctx, ast_expression *expr)
487 {
488     ast_instantiate(ast_return, ctx, ast_return_delete);
489     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
490
491     self->operand = expr;
492
493     if (expr)
494         ast_propagate_effects(self, expr);
495
496     return self;
497 }
498
499 void ast_return_delete(ast_return *self)
500 {
501     if (self->operand)
502         ast_unref(self->operand);
503     ast_expression_delete((ast_expression*)self);
504     mem_d(self);
505 }
506
507 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
508 {
509     if (field->expression.vtype != TYPE_FIELD) {
510         asterror(ctx, "ast_entfield_new with expression not of type field");
511         return NULL;
512     }
513     return ast_entfield_new_force(ctx, entity, field, field->expression.next);
514 }
515
516 ast_entfield* ast_entfield_new_force(lex_ctx ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
517 {
518     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
519
520     if (!outtype) {
521         mem_d(self);
522         /* Error: field has no type... */
523         return NULL;
524     }
525
526     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
527
528     self->entity = entity;
529     self->field  = field;
530     ast_propagate_effects(self, entity);
531     ast_propagate_effects(self, field);
532
533     if (!ast_type_adopt(self, outtype)) {
534         ast_entfield_delete(self);
535         return NULL;
536     }
537
538     return self;
539 }
540
541 void ast_entfield_delete(ast_entfield *self)
542 {
543     ast_unref(self->entity);
544     ast_unref(self->field);
545     ast_expression_delete((ast_expression*)self);
546     mem_d(self);
547 }
548
549 ast_member* ast_member_new(lex_ctx ctx, ast_expression *owner, unsigned int field, const char *name)
550 {
551     ast_instantiate(ast_member, ctx, ast_member_delete);
552     if (field >= 3) {
553         mem_d(self);
554         return NULL;
555     }
556
557     if (owner->expression.vtype != TYPE_VECTOR &&
558         owner->expression.vtype != TYPE_FIELD) {
559         asterror(ctx, "member-access on an invalid owner of type %s", type_name[owner->expression.vtype]);
560         mem_d(self);
561         return NULL;
562     }
563
564     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
565     self->expression.node.keep = true; /* keep */
566
567     if (owner->expression.vtype == TYPE_VECTOR) {
568         self->expression.vtype = TYPE_FLOAT;
569         self->expression.next  = NULL;
570     } else {
571         self->expression.vtype = TYPE_FIELD;
572         self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
573     }
574
575     self->owner = owner;
576     ast_propagate_effects(self, owner);
577
578     self->field = field;
579     if (name)
580         self->name = util_strdup(name);
581     else
582         self->name = NULL;
583
584     return self;
585 }
586
587 void ast_member_delete(ast_member *self)
588 {
589     /* The owner is always an ast_value, which has .keep=true,
590      * also: ast_members are usually deleted after the owner, thus
591      * this will cause invalid access
592     ast_unref(self->owner);
593      * once we allow (expression).x to access a vector-member, we need
594      * to change this: preferably by creating an alternate ast node for this
595      * purpose that is not garbage-collected.
596     */
597     ast_expression_delete((ast_expression*)self);
598     mem_d(self);
599 }
600
601 ast_array_index* ast_array_index_new(lex_ctx ctx, ast_expression *array, ast_expression *index)
602 {
603     ast_expression *outtype;
604     ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
605
606     outtype = array->expression.next;
607     if (!outtype) {
608         mem_d(self);
609         /* Error: field has no type... */
610         return NULL;
611     }
612
613     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
614
615     self->array = array;
616     self->index = index;
617     ast_propagate_effects(self, array);
618     ast_propagate_effects(self, index);
619
620     if (!ast_type_adopt(self, outtype)) {
621         ast_array_index_delete(self);
622         return NULL;
623     }
624     if (array->expression.vtype == TYPE_FIELD && outtype->expression.vtype == TYPE_ARRAY) {
625         if (self->expression.vtype != TYPE_ARRAY) {
626             asterror(ast_ctx(self), "array_index node on type");
627             ast_array_index_delete(self);
628             return NULL;
629         }
630         self->array = outtype;
631         self->expression.vtype = TYPE_FIELD;
632     }
633
634     return self;
635 }
636
637 void ast_array_index_delete(ast_array_index *self)
638 {
639     ast_unref(self->array);
640     ast_unref(self->index);
641     ast_expression_delete((ast_expression*)self);
642     mem_d(self);
643 }
644
645 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
646 {
647     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
648     if (!ontrue && !onfalse) {
649         /* because it is invalid */
650         mem_d(self);
651         return NULL;
652     }
653     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
654
655     self->cond     = cond;
656     self->on_true  = ontrue;
657     self->on_false = onfalse;
658     ast_propagate_effects(self, cond);
659     if (ontrue)
660         ast_propagate_effects(self, ontrue);
661     if (onfalse)
662         ast_propagate_effects(self, onfalse);
663
664     return self;
665 }
666
667 void ast_ifthen_delete(ast_ifthen *self)
668 {
669     ast_unref(self->cond);
670     if (self->on_true)
671         ast_unref(self->on_true);
672     if (self->on_false)
673         ast_unref(self->on_false);
674     ast_expression_delete((ast_expression*)self);
675     mem_d(self);
676 }
677
678 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
679 {
680     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
681     /* This time NEITHER must be NULL */
682     if (!ontrue || !onfalse) {
683         mem_d(self);
684         return NULL;
685     }
686     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
687
688     self->cond     = cond;
689     self->on_true  = ontrue;
690     self->on_false = onfalse;
691     ast_propagate_effects(self, cond);
692     ast_propagate_effects(self, ontrue);
693     ast_propagate_effects(self, onfalse);
694
695     if (!ast_type_adopt(self, ontrue)) {
696         ast_ternary_delete(self);
697         return NULL;
698     }
699
700     return self;
701 }
702
703 void ast_ternary_delete(ast_ternary *self)
704 {
705     ast_unref(self->cond);
706     ast_unref(self->on_true);
707     ast_unref(self->on_false);
708     ast_expression_delete((ast_expression*)self);
709     mem_d(self);
710 }
711
712 ast_loop* ast_loop_new(lex_ctx ctx,
713                        ast_expression *initexpr,
714                        ast_expression *precond,
715                        ast_expression *postcond,
716                        ast_expression *increment,
717                        ast_expression *body)
718 {
719     ast_instantiate(ast_loop, ctx, ast_loop_delete);
720     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
721
722     self->initexpr  = initexpr;
723     self->precond   = precond;
724     self->postcond  = postcond;
725     self->increment = increment;
726     self->body      = body;
727
728     if (initexpr)
729         ast_propagate_effects(self, initexpr);
730     if (precond)
731         ast_propagate_effects(self, precond);
732     if (postcond)
733         ast_propagate_effects(self, postcond);
734     if (increment)
735         ast_propagate_effects(self, increment);
736     if (body)
737         ast_propagate_effects(self, body);
738
739     return self;
740 }
741
742 void ast_loop_delete(ast_loop *self)
743 {
744     if (self->initexpr)
745         ast_unref(self->initexpr);
746     if (self->precond)
747         ast_unref(self->precond);
748     if (self->postcond)
749         ast_unref(self->postcond);
750     if (self->increment)
751         ast_unref(self->increment);
752     if (self->body)
753         ast_unref(self->body);
754     ast_expression_delete((ast_expression*)self);
755     mem_d(self);
756 }
757
758 ast_breakcont* ast_breakcont_new(lex_ctx ctx, bool iscont)
759 {
760     ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
761     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
762
763     self->is_continue = iscont;
764
765     return self;
766 }
767
768 void ast_breakcont_delete(ast_breakcont *self)
769 {
770     ast_expression_delete((ast_expression*)self);
771     mem_d(self);
772 }
773
774 ast_switch* ast_switch_new(lex_ctx ctx, ast_expression *op)
775 {
776     ast_instantiate(ast_switch, ctx, ast_switch_delete);
777     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
778
779     self->operand = op;
780     self->cases   = NULL;
781
782     ast_propagate_effects(self, op);
783
784     return self;
785 }
786
787 void ast_switch_delete(ast_switch *self)
788 {
789     size_t i;
790     ast_unref(self->operand);
791
792     for (i = 0; i < vec_size(self->cases); ++i) {
793         if (self->cases[i].value)
794             ast_unref(self->cases[i].value);
795         ast_unref(self->cases[i].code);
796     }
797     vec_free(self->cases);
798
799     ast_expression_delete((ast_expression*)self);
800     mem_d(self);
801 }
802
803 ast_label* ast_label_new(lex_ctx ctx, const char *name)
804 {
805     ast_instantiate(ast_label, ctx, ast_label_delete);
806     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
807
808     self->name    = util_strdup(name);
809     self->irblock = NULL;
810     self->gotos   = NULL;
811
812     return self;
813 }
814
815 void ast_label_delete(ast_label *self)
816 {
817     mem_d((void*)self->name);
818     vec_free(self->gotos);
819     ast_expression_delete((ast_expression*)self);
820     mem_d(self);
821 }
822
823 void ast_label_register_goto(ast_label *self, ast_goto *g)
824 {
825     vec_push(self->gotos, g);
826 }
827
828 ast_goto* ast_goto_new(lex_ctx ctx, const char *name)
829 {
830     ast_instantiate(ast_goto, ctx, ast_goto_delete);
831     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
832
833     self->name    = util_strdup(name);
834     self->target  = NULL;
835     self->irblock_from = NULL;
836
837     return self;
838 }
839
840 void ast_goto_delete(ast_goto *self)
841 {
842     mem_d((void*)self->name);
843     ast_expression_delete((ast_expression*)self);
844     mem_d(self);
845 }
846
847 ast_call* ast_call_new(lex_ctx ctx,
848                        ast_expression *funcexpr)
849 {
850     ast_instantiate(ast_call, ctx, ast_call_delete);
851     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
852
853     ast_side_effects(self) = true;
854
855     self->params = NULL;
856     self->func   = funcexpr;
857
858     self->expression.vtype = funcexpr->expression.next->expression.vtype;
859     if (funcexpr->expression.next->expression.next)
860         self->expression.next = ast_type_copy(ctx, funcexpr->expression.next->expression.next);
861
862     return self;
863 }
864
865 void ast_call_delete(ast_call *self)
866 {
867     size_t i;
868     for (i = 0; i < vec_size(self->params); ++i)
869         ast_unref(self->params[i]);
870     vec_free(self->params);
871
872     if (self->func)
873         ast_unref(self->func);
874
875     ast_expression_delete((ast_expression*)self);
876     mem_d(self);
877 }
878
879 bool ast_call_check_types(ast_call *self)
880 {
881     size_t i;
882     bool   retval = true;
883     const  ast_expression *func = self->func;
884     size_t count = vec_size(self->params);
885     if (count > vec_size(func->expression.params))
886         count = vec_size(func->expression.params);
887
888     for (i = 0; i < count; ++i) {
889         if (!ast_compare_type(self->params[i], (ast_expression*)(func->expression.params[i]))) {
890             char texp[1024];
891             char tgot[1024];
892             ast_type_to_string(self->params[i], tgot, sizeof(tgot));
893             ast_type_to_string((ast_expression*)func->expression.params[i], texp, sizeof(texp));
894             asterror(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
895                      (unsigned int)(i+1), texp, tgot);
896             /* we don't immediately return */
897             retval = false;
898         }
899     }
900     return retval;
901 }
902
903 ast_store* ast_store_new(lex_ctx ctx, int op,
904                          ast_expression *dest, ast_expression *source)
905 {
906     ast_instantiate(ast_store, ctx, ast_store_delete);
907     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
908
909     ast_side_effects(self) = true;
910
911     self->op = op;
912     self->dest = dest;
913     self->source = source;
914
915     self->expression.vtype = dest->expression.vtype;
916     if (dest->expression.next) {
917         self->expression.next = ast_type_copy(ctx, dest);
918         if (!self->expression.next) {
919             ast_delete(self);
920             return NULL;
921         }
922     }
923     else
924         self->expression.next = NULL;
925
926     return self;
927 }
928
929 void ast_store_delete(ast_store *self)
930 {
931     ast_unref(self->dest);
932     ast_unref(self->source);
933     ast_expression_delete((ast_expression*)self);
934     mem_d(self);
935 }
936
937 ast_block* ast_block_new(lex_ctx ctx)
938 {
939     ast_instantiate(ast_block, ctx, ast_block_delete);
940     ast_expression_init((ast_expression*)self,
941                         (ast_expression_codegen*)&ast_block_codegen);
942
943     self->locals  = NULL;
944     self->exprs   = NULL;
945     self->collect = NULL;
946
947     return self;
948 }
949
950 void ast_block_add_expr(ast_block *self, ast_expression *e)
951 {
952     ast_propagate_effects(self, e);
953     vec_push(self->exprs, e);
954 }
955
956 void ast_block_collect(ast_block *self, ast_expression *expr)
957 {
958     vec_push(self->collect, expr);
959     expr->expression.node.keep = true;
960 }
961
962 void ast_block_delete(ast_block *self)
963 {
964     size_t i;
965     for (i = 0; i < vec_size(self->exprs); ++i)
966         ast_unref(self->exprs[i]);
967     vec_free(self->exprs);
968     for (i = 0; i < vec_size(self->locals); ++i)
969         ast_delete(self->locals[i]);
970     vec_free(self->locals);
971     for (i = 0; i < vec_size(self->collect); ++i)
972         ast_delete(self->collect[i]);
973     vec_free(self->collect);
974     ast_expression_delete((ast_expression*)self);
975     mem_d(self);
976 }
977
978 bool ast_block_set_type(ast_block *self, ast_expression *from)
979 {
980     if (self->expression.next)
981         ast_delete(self->expression.next);
982     self->expression.vtype = from->expression.vtype;
983     if (from->expression.next) {
984         self->expression.next = ast_type_copy(self->expression.node.context, from->expression.next);
985         if (!self->expression.next)
986             return false;
987     }
988     else
989         self->expression.next = NULL;
990     return true;
991 }
992
993 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
994 {
995     ast_instantiate(ast_function, ctx, ast_function_delete);
996
997     if (!vtype ||
998         vtype->hasvalue ||
999         vtype->expression.vtype != TYPE_FUNCTION)
1000     {
1001         asterror(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i",
1002                  (int)!vtype,
1003                  (int)vtype->hasvalue,
1004                  vtype->expression.vtype);
1005         mem_d(self);
1006         return NULL;
1007     }
1008
1009     self->vtype  = vtype;
1010     self->name   = name ? util_strdup(name) : NULL;
1011     self->blocks = NULL;
1012
1013     self->labelcount = 0;
1014     self->builtin = 0;
1015
1016     self->ir_func = NULL;
1017     self->curblock = NULL;
1018
1019     self->breakblock    = NULL;
1020     self->continueblock = NULL;
1021
1022     vtype->hasvalue = true;
1023     vtype->constval.vfunc = self;
1024
1025     return self;
1026 }
1027
1028 void ast_function_delete(ast_function *self)
1029 {
1030     size_t i;
1031     if (self->name)
1032         mem_d((void*)self->name);
1033     if (self->vtype) {
1034         /* ast_value_delete(self->vtype); */
1035         self->vtype->hasvalue = false;
1036         self->vtype->constval.vfunc = NULL;
1037         /* We use unref - if it was stored in a global table it is supposed
1038          * to be deleted from *there*
1039          */
1040         ast_unref(self->vtype);
1041     }
1042     for (i = 0; i < vec_size(self->blocks); ++i)
1043         ast_delete(self->blocks[i]);
1044     vec_free(self->blocks);
1045     mem_d(self);
1046 }
1047
1048 const char* ast_function_label(ast_function *self, const char *prefix)
1049 {
1050     size_t id;
1051     size_t len;
1052     char  *from;
1053
1054     if (!opts_dump && !opts_dumpfin)
1055         return NULL;
1056
1057     id  = (self->labelcount++);
1058     len = strlen(prefix);
1059
1060     from = self->labelbuf + sizeof(self->labelbuf)-1;
1061     *from-- = 0;
1062     do {
1063         unsigned int digit = id % 10;
1064         *from = digit + '0';
1065         id /= 10;
1066     } while (id);
1067     memcpy(from - len, prefix, len);
1068     return from - len;
1069 }
1070
1071 /*********************************************************************/
1072 /* AST codegen part
1073  * by convention you must never pass NULL to the 'ir_value **out'
1074  * parameter. If you really don't care about the output, pass a dummy.
1075  * But I can't imagine a pituation where the output is truly unnecessary.
1076  */
1077
1078 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1079 {
1080     (void)func;
1081     (void)lvalue;
1082     /* NOTE: This is the codegen for a variable used in an expression.
1083      * It is not the codegen to generate the value. For this purpose,
1084      * ast_local_codegen and ast_global_codegen are to be used before this
1085      * is executed. ast_function_codegen should take care of its locals,
1086      * and the ast-user should take care of ast_global_codegen to be used
1087      * on all the globals.
1088      */
1089     if (!self->ir_v) {
1090         char typename[1024];
1091         ast_type_to_string((ast_expression*)self, typename, sizeof(typename));
1092         asterror(ast_ctx(self), "ast_value used before generated %s %s", typename, self->name);
1093         return false;
1094     }
1095     *out = self->ir_v;
1096     return true;
1097 }
1098
1099 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1100 {
1101     ir_value *v = NULL;
1102
1103     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1104     {
1105         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
1106         if (!func)
1107             return false;
1108         func->context = ast_ctx(self);
1109         func->value->context = ast_ctx(self);
1110
1111         self->constval.vfunc->ir_func = func;
1112         self->ir_v = func->value;
1113         /* The function is filled later on ast_function_codegen... */
1114         return true;
1115     }
1116
1117     if (isfield && self->expression.vtype == TYPE_FIELD) {
1118         ast_expression *fieldtype = self->expression.next;
1119
1120         if (self->hasvalue) {
1121             asterror(ast_ctx(self), "TODO: constant field pointers with value");
1122             goto error;
1123         }
1124
1125         if (fieldtype->expression.vtype == TYPE_ARRAY) {
1126             size_t ai;
1127             char   *name;
1128             size_t  namelen;
1129
1130             ast_expression_common *elemtype;
1131             int                    vtype;
1132             ast_value             *array = (ast_value*)fieldtype;
1133
1134             if (!ast_istype(fieldtype, ast_value)) {
1135                 asterror(ast_ctx(self), "internal error: ast_value required");
1136                 return false;
1137             }
1138
1139             /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1140             if (!array->expression.count || array->expression.count > opts_max_array_size)
1141                 asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1142
1143             elemtype = &array->expression.next->expression;
1144             vtype = elemtype->vtype;
1145
1146             v = ir_builder_create_field(ir, self->name, vtype);
1147             if (!v) {
1148                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1149                 return false;
1150             }
1151             if (vtype == TYPE_FIELD)
1152                 v->fieldtype = elemtype->next->expression.vtype;
1153             v->context = ast_ctx(self);
1154             array->ir_v = self->ir_v = v;
1155
1156             namelen = strlen(self->name);
1157             name    = (char*)mem_a(namelen + 16);
1158             strcpy(name, self->name);
1159
1160             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1161             array->ir_values[0] = v;
1162             for (ai = 1; ai < array->expression.count; ++ai) {
1163                 snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1164                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1165                 if (!array->ir_values[ai]) {
1166                     mem_d(name);
1167                     asterror(ast_ctx(self), "ir_builder_create_global failed");
1168                     return false;
1169                 }
1170                 if (vtype == TYPE_FIELD)
1171                     array->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1172                 array->ir_values[ai]->context = ast_ctx(self);
1173             }
1174             mem_d(name);
1175         }
1176         else
1177         {
1178             v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
1179             if (!v)
1180                 return false;
1181             v->context = ast_ctx(self);
1182             self->ir_v = v;
1183         }
1184         return true;
1185     }
1186
1187     if (self->expression.vtype == TYPE_ARRAY) {
1188         size_t ai;
1189         char   *name;
1190         size_t  namelen;
1191
1192         ast_expression_common *elemtype = &self->expression.next->expression;
1193         int vtype = elemtype->vtype;
1194
1195         /* same as with field arrays */
1196         if (!self->expression.count || self->expression.count > opts_max_array_size)
1197             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1198
1199         v = ir_builder_create_global(ir, self->name, vtype);
1200         if (!v) {
1201             asterror(ast_ctx(self), "ir_builder_create_global failed");
1202             return false;
1203         }
1204         if (vtype == TYPE_FIELD)
1205             v->fieldtype = elemtype->next->expression.vtype;
1206         v->context = ast_ctx(self);
1207
1208         namelen = strlen(self->name);
1209         name    = (char*)mem_a(namelen + 16);
1210         strcpy(name, self->name);
1211
1212         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1213         self->ir_values[0] = v;
1214         for (ai = 1; ai < self->expression.count; ++ai) {
1215             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1216             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1217             if (!self->ir_values[ai]) {
1218                 mem_d(name);
1219                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1220                 return false;
1221             }
1222             if (vtype == TYPE_FIELD)
1223                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1224             self->ir_values[ai]->context = ast_ctx(self);
1225         }
1226         mem_d(name);
1227     }
1228     else
1229     {
1230         /* Arrays don't do this since there's no "array" value which spans across the
1231          * whole thing.
1232          */
1233         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1234         if (!v) {
1235             asterror(ast_ctx(self), "ir_builder_create_global failed");
1236             return false;
1237         }
1238         if (self->expression.vtype == TYPE_FIELD)
1239             v->fieldtype = self->expression.next->expression.vtype;
1240         v->context = ast_ctx(self);
1241     }
1242
1243     if (self->hasvalue) {
1244         switch (self->expression.vtype)
1245         {
1246             case TYPE_FLOAT:
1247                 if (!ir_value_set_float(v, self->constval.vfloat))
1248                     goto error;
1249                 break;
1250             case TYPE_VECTOR:
1251                 if (!ir_value_set_vector(v, self->constval.vvec))
1252                     goto error;
1253                 break;
1254             case TYPE_STRING:
1255                 if (!ir_value_set_string(v, self->constval.vstring))
1256                     goto error;
1257                 break;
1258             case TYPE_ARRAY:
1259                 asterror(ast_ctx(self), "TODO: global constant array");
1260                 break;
1261             case TYPE_FUNCTION:
1262                 asterror(ast_ctx(self), "global of type function not properly generated");
1263                 goto error;
1264                 /* Cannot generate an IR value for a function,
1265                  * need a pointer pointing to a function rather.
1266                  */
1267             default:
1268                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1269                 break;
1270         }
1271     }
1272
1273     /* link us to the ir_value */
1274     self->ir_v = v;
1275     return true;
1276
1277 error: /* clean up */
1278     ir_value_delete(v);
1279     return false;
1280 }
1281
1282 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1283 {
1284     ir_value *v = NULL;
1285     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1286     {
1287         /* Do we allow local functions? I think not...
1288          * this is NOT a function pointer atm.
1289          */
1290         return false;
1291     }
1292
1293     if (self->expression.vtype == TYPE_ARRAY) {
1294         size_t ai;
1295         char   *name;
1296         size_t  namelen;
1297
1298         ast_expression_common *elemtype = &self->expression.next->expression;
1299         int vtype = elemtype->vtype;
1300
1301         if (param) {
1302             asterror(ast_ctx(self), "array-parameters are not supported");
1303             return false;
1304         }
1305
1306         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1307         if (!self->expression.count || self->expression.count > opts_max_array_size) {
1308             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1309         }
1310
1311         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1312         if (!self->ir_values) {
1313             asterror(ast_ctx(self), "failed to allocate array values");
1314             return false;
1315         }
1316
1317         v = ir_function_create_local(func, self->name, vtype, param);
1318         if (!v) {
1319             asterror(ast_ctx(self), "ir_function_create_local failed");
1320             return false;
1321         }
1322         if (vtype == TYPE_FIELD)
1323             v->fieldtype = elemtype->next->expression.vtype;
1324         v->context = ast_ctx(self);
1325
1326         namelen = strlen(self->name);
1327         name    = (char*)mem_a(namelen + 16);
1328         strcpy(name, self->name);
1329
1330         self->ir_values[0] = v;
1331         for (ai = 1; ai < self->expression.count; ++ai) {
1332             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1333             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1334             if (!self->ir_values[ai]) {
1335                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1336                 return false;
1337             }
1338             if (vtype == TYPE_FIELD)
1339                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1340             self->ir_values[ai]->context = ast_ctx(self);
1341         }
1342     }
1343     else
1344     {
1345         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1346         if (!v)
1347             return false;
1348         if (self->expression.vtype == TYPE_FIELD)
1349             v->fieldtype = self->expression.next->expression.vtype;
1350         v->context = ast_ctx(self);
1351     }
1352
1353     /* A constant local... hmmm...
1354      * I suppose the IR will have to deal with this
1355      */
1356     if (self->hasvalue) {
1357         switch (self->expression.vtype)
1358         {
1359             case TYPE_FLOAT:
1360                 if (!ir_value_set_float(v, self->constval.vfloat))
1361                     goto error;
1362                 break;
1363             case TYPE_VECTOR:
1364                 if (!ir_value_set_vector(v, self->constval.vvec))
1365                     goto error;
1366                 break;
1367             case TYPE_STRING:
1368                 if (!ir_value_set_string(v, self->constval.vstring))
1369                     goto error;
1370                 break;
1371             default:
1372                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1373                 break;
1374         }
1375     }
1376
1377     /* link us to the ir_value */
1378     self->ir_v = v;
1379
1380     if (self->setter) {
1381         if (!ast_global_codegen(self->setter, func->owner, false) ||
1382             !ast_function_codegen(self->setter->constval.vfunc, func->owner) ||
1383             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1384             return false;
1385     }
1386     if (self->getter) {
1387         if (!ast_global_codegen(self->getter, func->owner, false) ||
1388             !ast_function_codegen(self->getter->constval.vfunc, func->owner) ||
1389             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1390             return false;
1391     }
1392     return true;
1393
1394 error: /* clean up */
1395     ir_value_delete(v);
1396     return false;
1397 }
1398
1399 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1400 {
1401     ir_function *irf;
1402     ir_value    *dummy;
1403     ast_expression_common *ec;
1404     size_t    i;
1405
1406     (void)ir;
1407
1408     irf = self->ir_func;
1409     if (!irf) {
1410         asterror(ast_ctx(self), "ast_function's related ast_value was not generated yet");
1411         return false;
1412     }
1413
1414     /* fill the parameter list */
1415     ec = &self->vtype->expression;
1416     for (i = 0; i < vec_size(ec->params); ++i)
1417     {
1418         vec_push(irf->params, ec->params[i]->expression.vtype);
1419         if (!self->builtin) {
1420             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1421                 return false;
1422         }
1423     }
1424
1425     if (self->builtin) {
1426         irf->builtin = self->builtin;
1427         return true;
1428     }
1429
1430     if (!vec_size(self->blocks)) {
1431         asterror(ast_ctx(self), "function `%s` has no body", self->name);
1432         return false;
1433     }
1434
1435     self->curblock = ir_function_create_block(irf, "entry");
1436     if (!self->curblock) {
1437         asterror(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1438         return false;
1439     }
1440
1441     for (i = 0; i < vec_size(self->blocks); ++i) {
1442         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
1443         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
1444             return false;
1445     }
1446
1447     /* TODO: check return types */
1448     if (!self->curblock->is_return)
1449     {
1450         return ir_block_create_return(self->curblock, NULL);
1451         /* From now on the parser has to handle this situation */
1452 #if 0
1453         if (!self->vtype->expression.next ||
1454             self->vtype->expression.next->expression.vtype == TYPE_VOID)
1455         {
1456             return ir_block_create_return(self->curblock, NULL);
1457         }
1458         else
1459         {
1460             /* error("missing return"); */
1461             asterror(ast_ctx(self), "function `%s` missing return value", self->name);
1462             return false;
1463         }
1464 #endif
1465     }
1466     return true;
1467 }
1468
1469 /* Note, you will not see ast_block_codegen generate ir_blocks.
1470  * To the AST and the IR, blocks are 2 different things.
1471  * In the AST it represents a block of code, usually enclosed in
1472  * curly braces {...}.
1473  * While in the IR it represents a block in terms of control-flow.
1474  */
1475 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1476 {
1477     size_t i;
1478
1479     /* We don't use this
1480      * Note: an ast-representation using the comma-operator
1481      * of the form: (a, b, c) = x should not assign to c...
1482      */
1483     if (lvalue) {
1484         asterror(ast_ctx(self), "not an l-value (code-block)");
1485         return false;
1486     }
1487
1488     if (self->expression.outr) {
1489         *out = self->expression.outr;
1490         return true;
1491     }
1492
1493     /* output is NULL at first, we'll have each expression
1494      * assign to out output, thus, a comma-operator represention
1495      * using an ast_block will return the last generated value,
1496      * so: (b, c) + a  executed both b and c, and returns c,
1497      * which is then added to a.
1498      */
1499     *out = NULL;
1500
1501     /* generate locals */
1502     for (i = 0; i < vec_size(self->locals); ++i)
1503     {
1504         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1505             if (opts_debug)
1506                 asterror(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1507             return false;
1508         }
1509     }
1510
1511     for (i = 0; i < vec_size(self->exprs); ++i)
1512     {
1513         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
1514         if (func->curblock->final) {
1515             asterror(ast_ctx(self->exprs[i]), "unreachable statement");
1516             return false;
1517         }
1518         if (!(*gen)(self->exprs[i], func, false, out))
1519             return false;
1520     }
1521
1522     self->expression.outr = *out;
1523
1524     return true;
1525 }
1526
1527 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1528 {
1529     ast_expression_codegen *cgen;
1530     ir_value *left  = NULL;
1531     ir_value *right = NULL;
1532
1533     ast_value       *arr;
1534     ast_value       *idx = 0;
1535     ast_array_index *ai = NULL;
1536
1537     if (lvalue && self->expression.outl) {
1538         *out = self->expression.outl;
1539         return true;
1540     }
1541
1542     if (!lvalue && self->expression.outr) {
1543         *out = self->expression.outr;
1544         return true;
1545     }
1546
1547     if (ast_istype(self->dest, ast_array_index))
1548     {
1549
1550         ai = (ast_array_index*)self->dest;
1551         idx = (ast_value*)ai->index;
1552
1553         if (ast_istype(ai->index, ast_value) && idx->hasvalue)
1554             ai = NULL;
1555     }
1556
1557     if (ai) {
1558         /* we need to call the setter */
1559         ir_value  *iridx, *funval;
1560         ir_instr  *call;
1561
1562         if (lvalue) {
1563             asterror(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1564             return false;
1565         }
1566
1567         arr = (ast_value*)ai->array;
1568         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1569             asterror(ast_ctx(self), "value has no setter (%s)", arr->name);
1570             return false;
1571         }
1572
1573         cgen = idx->expression.codegen;
1574         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1575             return false;
1576
1577         cgen = arr->setter->expression.codegen;
1578         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1579             return false;
1580
1581         cgen = self->source->expression.codegen;
1582         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1583             return false;
1584
1585         call = ir_block_create_call(func->curblock, ast_function_label(func, "store"), funval);
1586         if (!call)
1587             return false;
1588         ir_call_param(call, iridx);
1589         ir_call_param(call, right);
1590         self->expression.outr = right;
1591     }
1592     else
1593     {
1594         /* regular code */
1595
1596         cgen = self->dest->expression.codegen;
1597         /* lvalue! */
1598         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1599             return false;
1600         self->expression.outl = left;
1601
1602         cgen = self->source->expression.codegen;
1603         /* rvalue! */
1604         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1605             return false;
1606
1607         if (!ir_block_create_store_op(func->curblock, self->op, left, right))
1608             return false;
1609         self->expression.outr = right;
1610     }
1611
1612     /* Theoretically, an assinment returns its left side as an
1613      * lvalue, if we don't need an lvalue though, we return
1614      * the right side as an rvalue, otherwise we have to
1615      * somehow know whether or not we need to dereference the pointer
1616      * on the left side - that is: OP_LOAD if it was an address.
1617      * Also: in original QC we cannot OP_LOADP *anyway*.
1618      */
1619     *out = (lvalue ? left : right);
1620
1621     return true;
1622 }
1623
1624 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1625 {
1626     ast_expression_codegen *cgen;
1627     ir_value *left, *right;
1628
1629     /* A binary operation cannot yield an l-value */
1630     if (lvalue) {
1631         asterror(ast_ctx(self), "not an l-value (binop)");
1632         return false;
1633     }
1634
1635     if (self->expression.outr) {
1636         *out = self->expression.outr;
1637         return true;
1638     }
1639
1640     if (OPTS_FLAG(SHORT_LOGIC) &&
1641         (self->op == INSTR_AND || self->op == INSTR_OR))
1642     {
1643         /* short circuit evaluation */
1644         ir_block *other, *merge;
1645         ir_block *from_left, *from_right;
1646         ir_instr *phi;
1647         size_t    merge_id;
1648         uint16_t  notop;
1649
1650         /* Note about casting to true boolean values:
1651          * We use a single NOT for sub expressions, and an
1652          * overall NOT at the end, and for that purpose swap
1653          * all the jump conditions in order for the NOT to get
1654          * doubled.
1655          * ie: (a && b) usually becomes (!!a ? !!b : !!a)
1656          * but we translate this to (!(!a ? !a : !b))
1657          */
1658
1659         merge_id = vec_size(func->ir_func->blocks);
1660         merge = ir_function_create_block(func->ir_func, ast_function_label(func, "sce_merge"));
1661
1662         cgen = self->left->expression.codegen;
1663         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1664             return false;
1665         if (!OPTS_FLAG(PERL_LOGIC)) {
1666             notop = type_not_instr[left->vtype];
1667             if (notop == AINSTR_END) {
1668                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1669                 return false;
1670             }
1671             left = ir_block_create_unary(func->curblock,
1672                                          ast_function_label(func, "sce_not"),
1673                                          notop,
1674                                          left);
1675         }
1676         from_left = func->curblock;
1677
1678         other = ir_function_create_block(func->ir_func, ast_function_label(func, "sce_other"));
1679         if ( !(self->op == INSTR_OR) != !OPTS_FLAG(PERL_LOGIC) ) {
1680             if (!ir_block_create_if(func->curblock, left, other, merge))
1681                 return false;
1682         } else {
1683             if (!ir_block_create_if(func->curblock, left, merge, other))
1684                 return false;
1685         }
1686         /* use the likely flag */
1687         vec_last(func->curblock->instr)->likely = true;
1688
1689         func->curblock = other;
1690         cgen = self->right->expression.codegen;
1691         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1692             return false;
1693         if (!OPTS_FLAG(PERL_LOGIC)) {
1694             notop = type_not_instr[right->vtype];
1695             if (notop == AINSTR_END) {
1696                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1697                 return false;
1698             }
1699             right = ir_block_create_unary(func->curblock,
1700                                           ast_function_label(func, "sce_not"),
1701                                           notop,
1702                                           right);
1703         }
1704         from_right = func->curblock;
1705
1706         if (!ir_block_create_jump(func->curblock, merge))
1707             return false;
1708
1709         vec_remove(func->ir_func->blocks, merge_id, 1);
1710         vec_push(func->ir_func->blocks, merge);
1711
1712         func->curblock = merge;
1713         phi = ir_block_create_phi(func->curblock, ast_function_label(func, "sce_value"), TYPE_FLOAT);
1714         ir_phi_add(phi, from_left, left);
1715         ir_phi_add(phi, from_right, right);
1716         *out = ir_phi_value(phi);
1717         if (!OPTS_FLAG(PERL_LOGIC)) {
1718             notop = type_not_instr[(*out)->vtype];
1719             if (notop == AINSTR_END) {
1720                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1721                 return false;
1722             }
1723             *out = ir_block_create_unary(func->curblock,
1724                                          ast_function_label(func, "sce_final_not"),
1725                                          notop,
1726                                          *out);
1727         }
1728         if (!*out)
1729             return false;
1730         self->expression.outr = *out;
1731         return true;
1732     }
1733
1734     cgen = self->left->expression.codegen;
1735     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1736         return false;
1737
1738     cgen = self->right->expression.codegen;
1739     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1740         return false;
1741
1742     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
1743                                  self->op, left, right);
1744     if (!*out)
1745         return false;
1746     self->expression.outr = *out;
1747
1748     return true;
1749 }
1750
1751 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1752 {
1753     ast_expression_codegen *cgen;
1754     ir_value *leftl = NULL, *leftr, *right, *bin;
1755
1756     ast_value       *arr;
1757     ast_value       *idx = 0;
1758     ast_array_index *ai = NULL;
1759     ir_value        *iridx = NULL;
1760
1761     if (lvalue && self->expression.outl) {
1762         *out = self->expression.outl;
1763         return true;
1764     }
1765
1766     if (!lvalue && self->expression.outr) {
1767         *out = self->expression.outr;
1768         return true;
1769     }
1770
1771     if (ast_istype(self->dest, ast_array_index))
1772     {
1773
1774         ai = (ast_array_index*)self->dest;
1775         idx = (ast_value*)ai->index;
1776
1777         if (ast_istype(ai->index, ast_value) && idx->hasvalue)
1778             ai = NULL;
1779     }
1780
1781     /* for a binstore we need both an lvalue and an rvalue for the left side */
1782     /* rvalue of destination! */
1783     if (ai) {
1784         cgen = idx->expression.codegen;
1785         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1786             return false;
1787     }
1788     cgen = self->dest->expression.codegen;
1789     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
1790         return false;
1791
1792     /* source as rvalue only */
1793     cgen = self->source->expression.codegen;
1794     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1795         return false;
1796
1797     /* now the binary */
1798     bin = ir_block_create_binop(func->curblock, ast_function_label(func, "binst"),
1799                                 self->opbin, leftr, right);
1800     self->expression.outr = bin;
1801
1802
1803     if (ai) {
1804         /* we need to call the setter */
1805         ir_value  *funval;
1806         ir_instr  *call;
1807
1808         if (lvalue) {
1809             asterror(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1810             return false;
1811         }
1812
1813         arr = (ast_value*)ai->array;
1814         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1815             asterror(ast_ctx(self), "value has no setter (%s)", arr->name);
1816             return false;
1817         }
1818
1819         cgen = arr->setter->expression.codegen;
1820         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1821             return false;
1822
1823         call = ir_block_create_call(func->curblock, ast_function_label(func, "store"), funval);
1824         if (!call)
1825             return false;
1826         ir_call_param(call, iridx);
1827         ir_call_param(call, bin);
1828         self->expression.outr = bin;
1829     } else {
1830         /* now store them */
1831         cgen = self->dest->expression.codegen;
1832         /* lvalue of destination */
1833         if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
1834             return false;
1835         self->expression.outl = leftl;
1836
1837         if (!ir_block_create_store_op(func->curblock, self->opstore, leftl, bin))
1838             return false;
1839         self->expression.outr = bin;
1840     }
1841
1842     /* Theoretically, an assinment returns its left side as an
1843      * lvalue, if we don't need an lvalue though, we return
1844      * the right side as an rvalue, otherwise we have to
1845      * somehow know whether or not we need to dereference the pointer
1846      * on the left side - that is: OP_LOAD if it was an address.
1847      * Also: in original QC we cannot OP_LOADP *anyway*.
1848      */
1849     *out = (lvalue ? leftl : bin);
1850
1851     return true;
1852 }
1853
1854 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
1855 {
1856     ast_expression_codegen *cgen;
1857     ir_value *operand;
1858
1859     /* An unary operation cannot yield an l-value */
1860     if (lvalue) {
1861         asterror(ast_ctx(self), "not an l-value (binop)");
1862         return false;
1863     }
1864
1865     if (self->expression.outr) {
1866         *out = self->expression.outr;
1867         return true;
1868     }
1869
1870     cgen = self->operand->expression.codegen;
1871     /* lvalue! */
1872     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1873         return false;
1874
1875     *out = ir_block_create_unary(func->curblock, ast_function_label(func, "unary"),
1876                                  self->op, operand);
1877     if (!*out)
1878         return false;
1879     self->expression.outr = *out;
1880
1881     return true;
1882 }
1883
1884 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
1885 {
1886     ast_expression_codegen *cgen;
1887     ir_value *operand;
1888
1889     *out = NULL;
1890
1891     /* In the context of a return operation, we don't actually return
1892      * anything...
1893      */
1894     if (lvalue) {
1895         asterror(ast_ctx(self), "return-expression is not an l-value");
1896         return false;
1897     }
1898
1899     if (self->expression.outr) {
1900         asterror(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
1901         return false;
1902     }
1903     self->expression.outr = (ir_value*)1;
1904
1905     if (self->operand) {
1906         cgen = self->operand->expression.codegen;
1907         /* lvalue! */
1908         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1909             return false;
1910
1911         if (!ir_block_create_return(func->curblock, operand))
1912             return false;
1913     } else {
1914         if (!ir_block_create_return(func->curblock, NULL))
1915             return false;
1916     }
1917
1918     return true;
1919 }
1920
1921 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
1922 {
1923     ast_expression_codegen *cgen;
1924     ir_value *ent, *field;
1925
1926     /* This function needs to take the 'lvalue' flag into account!
1927      * As lvalue we provide a field-pointer, as rvalue we provide the
1928      * value in a temp.
1929      */
1930
1931     if (lvalue && self->expression.outl) {
1932         *out = self->expression.outl;
1933         return true;
1934     }
1935
1936     if (!lvalue && self->expression.outr) {
1937         *out = self->expression.outr;
1938         return true;
1939     }
1940
1941     cgen = self->entity->expression.codegen;
1942     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
1943         return false;
1944
1945     cgen = self->field->expression.codegen;
1946     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
1947         return false;
1948
1949     if (lvalue) {
1950         /* address! */
1951         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
1952                                             ent, field);
1953     } else {
1954         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
1955                                              ent, field, self->expression.vtype);
1956     }
1957     if (!*out) {
1958         asterror(ast_ctx(self), "failed to create %s instruction (output type %s)",
1959                  (lvalue ? "ADDRESS" : "FIELD"),
1960                  type_name[self->expression.vtype]);
1961         return false;
1962     }
1963
1964     if (lvalue)
1965         self->expression.outl = *out;
1966     else
1967         self->expression.outr = *out;
1968
1969     /* Hm that should be it... */
1970     return true;
1971 }
1972
1973 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
1974 {
1975     ast_expression_codegen *cgen;
1976     ir_value *vec;
1977
1978     /* in QC this is always an lvalue */
1979     (void)lvalue;
1980     if (self->expression.outl) {
1981         *out = self->expression.outl;
1982         return true;
1983     }
1984
1985     cgen = self->owner->expression.codegen;
1986     if (!(*cgen)((ast_expression*)(self->owner), func, true, &vec))
1987         return false;
1988
1989     if (vec->vtype != TYPE_VECTOR &&
1990         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
1991     {
1992         return false;
1993     }
1994
1995     *out = ir_value_vector_member(vec, self->field);
1996     self->expression.outl = *out;
1997
1998     return (*out != NULL);
1999 }
2000
2001 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2002 {
2003     ast_value *arr;
2004     ast_value *idx;
2005
2006     if (!lvalue && self->expression.outr) {
2007         *out = self->expression.outr;
2008     }
2009     if (lvalue && self->expression.outl) {
2010         *out = self->expression.outl;
2011     }
2012
2013     if (!ast_istype(self->array, ast_value)) {
2014         asterror(ast_ctx(self), "array indexing this way is not supported");
2015         /* note this would actually be pointer indexing because the left side is
2016          * not an actual array but (hopefully) an indexable expression.
2017          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2018          * support this path will be filled.
2019          */
2020         return false;
2021     }
2022
2023     arr = (ast_value*)self->array;
2024     idx = (ast_value*)self->index;
2025
2026     if (!ast_istype(self->index, ast_value) || !idx->hasvalue) {
2027         /* Time to use accessor functions */
2028         ast_expression_codegen *cgen;
2029         ir_value               *iridx, *funval;
2030         ir_instr               *call;
2031
2032         if (lvalue) {
2033             asterror(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2034             return false;
2035         }
2036
2037         if (!arr->getter) {
2038             asterror(ast_ctx(self), "value has no getter, don't know how to index it");
2039             return false;
2040         }
2041
2042         cgen = self->index->expression.codegen;
2043         if (!(*cgen)((ast_expression*)(self->index), func, true, &iridx))
2044             return false;
2045
2046         cgen = arr->getter->expression.codegen;
2047         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2048             return false;
2049
2050         call = ir_block_create_call(func->curblock, ast_function_label(func, "fetch"), funval);
2051         if (!call)
2052             return false;
2053         ir_call_param(call, iridx);
2054
2055         *out = ir_call_value(call);
2056         self->expression.outr = *out;
2057         return true;
2058     }
2059
2060     if (idx->expression.vtype == TYPE_FLOAT)
2061         *out = arr->ir_values[(int)idx->constval.vfloat];
2062     else if (idx->expression.vtype == TYPE_INTEGER)
2063         *out = arr->ir_values[idx->constval.vint];
2064     else {
2065         asterror(ast_ctx(self), "array indexing here needs an integer constant");
2066         return false;
2067     }
2068     return true;
2069 }
2070
2071 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2072 {
2073     ast_expression_codegen *cgen;
2074
2075     ir_value *condval;
2076     ir_value *dummy;
2077
2078     ir_block *cond = func->curblock;
2079     ir_block *ontrue;
2080     ir_block *onfalse;
2081     ir_block *ontrue_endblock = NULL;
2082     ir_block *onfalse_endblock = NULL;
2083     ir_block *merge;
2084
2085     /* We don't output any value, thus also don't care about r/lvalue */
2086     (void)out;
2087     (void)lvalue;
2088
2089     if (self->expression.outr) {
2090         asterror(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2091         return false;
2092     }
2093     self->expression.outr = (ir_value*)1;
2094
2095     /* generate the condition */
2096     cgen = self->cond->expression.codegen;
2097     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2098         return false;
2099     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2100     cond = func->curblock;
2101
2102     /* on-true path */
2103
2104     if (self->on_true) {
2105         /* create on-true block */
2106         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
2107         if (!ontrue)
2108             return false;
2109
2110         /* enter the block */
2111         func->curblock = ontrue;
2112
2113         /* generate */
2114         cgen = self->on_true->expression.codegen;
2115         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2116             return false;
2117
2118         /* we now need to work from the current endpoint */
2119         ontrue_endblock = func->curblock;
2120     } else
2121         ontrue = NULL;
2122
2123     /* on-false path */
2124     if (self->on_false) {
2125         /* create on-false block */
2126         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
2127         if (!onfalse)
2128             return false;
2129
2130         /* enter the block */
2131         func->curblock = onfalse;
2132
2133         /* generate */
2134         cgen = self->on_false->expression.codegen;
2135         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2136             return false;
2137
2138         /* we now need to work from the current endpoint */
2139         onfalse_endblock = func->curblock;
2140     } else
2141         onfalse = NULL;
2142
2143     /* Merge block were they all merge in to */
2144     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
2145     if (!merge)
2146         return false;
2147     /* add jumps ot the merge block */
2148     if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, merge))
2149         return false;
2150     if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, merge))
2151         return false;
2152
2153     /* we create the if here, that way all blocks are ordered :)
2154      */
2155     if (!ir_block_create_if(cond, condval,
2156                             (ontrue  ? ontrue  : merge),
2157                             (onfalse ? onfalse : merge)))
2158     {
2159         return false;
2160     }
2161
2162     /* Now enter the merge block */
2163     func->curblock = merge;
2164
2165     return true;
2166 }
2167
2168 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2169 {
2170     ast_expression_codegen *cgen;
2171
2172     ir_value *condval;
2173     ir_value *trueval, *falseval;
2174     ir_instr *phi;
2175
2176     ir_block *cond = func->curblock;
2177     ir_block *ontrue;
2178     ir_block *onfalse;
2179     ir_block *merge;
2180
2181     /* Ternary can never create an lvalue... */
2182     if (lvalue)
2183         return false;
2184
2185     /* In theory it shouldn't be possible to pass through a node twice, but
2186      * in case we add any kind of optimization pass for the AST itself, it
2187      * may still happen, thus we remember a created ir_value and simply return one
2188      * if it already exists.
2189      */
2190     if (self->expression.outr) {
2191         *out = self->expression.outr;
2192         return true;
2193     }
2194
2195     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2196
2197     /* generate the condition */
2198     func->curblock = cond;
2199     cgen = self->cond->expression.codegen;
2200     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2201         return false;
2202
2203     /* create on-true block */
2204     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
2205     if (!ontrue)
2206         return false;
2207     else
2208     {
2209         /* enter the block */
2210         func->curblock = ontrue;
2211
2212         /* generate */
2213         cgen = self->on_true->expression.codegen;
2214         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2215             return false;
2216     }
2217
2218     /* create on-false block */
2219     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
2220     if (!onfalse)
2221         return false;
2222     else
2223     {
2224         /* enter the block */
2225         func->curblock = onfalse;
2226
2227         /* generate */
2228         cgen = self->on_false->expression.codegen;
2229         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2230             return false;
2231     }
2232
2233     /* create merge block */
2234     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
2235     if (!merge)
2236         return false;
2237     /* jump to merge block */
2238     if (!ir_block_create_jump(ontrue, merge))
2239         return false;
2240     if (!ir_block_create_jump(onfalse, merge))
2241         return false;
2242
2243     /* create if instruction */
2244     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
2245         return false;
2246
2247     /* Now enter the merge block */
2248     func->curblock = merge;
2249
2250     /* Here, now, we need a PHI node
2251      * but first some sanity checking...
2252      */
2253     if (trueval->vtype != falseval->vtype) {
2254         /* error("ternary with different types on the two sides"); */
2255         return false;
2256     }
2257
2258     /* create PHI */
2259     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
2260     if (!phi)
2261         return false;
2262     ir_phi_add(phi, ontrue,  trueval);
2263     ir_phi_add(phi, onfalse, falseval);
2264
2265     self->expression.outr = ir_phi_value(phi);
2266     *out = self->expression.outr;
2267
2268     return true;
2269 }
2270
2271 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2272 {
2273     ast_expression_codegen *cgen;
2274
2275     ir_value *dummy      = NULL;
2276     ir_value *precond    = NULL;
2277     ir_value *postcond   = NULL;
2278
2279     /* Since we insert some jumps "late" so we have blocks
2280      * ordered "nicely", we need to keep track of the actual end-blocks
2281      * of expressions to add the jumps to.
2282      */
2283     ir_block *bbody      = NULL, *end_bbody      = NULL;
2284     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2285     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2286     ir_block *bincrement = NULL, *end_bincrement = NULL;
2287     ir_block *bout       = NULL, *bin            = NULL;
2288
2289     /* let's at least move the outgoing block to the end */
2290     size_t    bout_id;
2291
2292     /* 'break' and 'continue' need to be able to find the right blocks */
2293     ir_block *bcontinue     = NULL;
2294     ir_block *bbreak        = NULL;
2295
2296     ir_block *old_bcontinue = NULL;
2297     ir_block *old_bbreak    = NULL;
2298
2299     ir_block *tmpblock      = NULL;
2300
2301     (void)lvalue;
2302     (void)out;
2303
2304     if (self->expression.outr) {
2305         asterror(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2306         return false;
2307     }
2308     self->expression.outr = (ir_value*)1;
2309
2310     /* NOTE:
2311      * Should we ever need some kind of block ordering, better make this function
2312      * move blocks around than write a block ordering algorithm later... after all
2313      * the ast and ir should work together, not against each other.
2314      */
2315
2316     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2317      * anyway if for example it contains a ternary.
2318      */
2319     if (self->initexpr)
2320     {
2321         cgen = self->initexpr->expression.codegen;
2322         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2323             return false;
2324     }
2325
2326     /* Store the block from which we enter this chaos */
2327     bin = func->curblock;
2328
2329     /* The pre-loop condition needs its own block since we
2330      * need to be able to jump to the start of that expression.
2331      */
2332     if (self->precond)
2333     {
2334         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
2335         if (!bprecond)
2336             return false;
2337
2338         /* the pre-loop-condition the least important place to 'continue' at */
2339         bcontinue = bprecond;
2340
2341         /* enter */
2342         func->curblock = bprecond;
2343
2344         /* generate */
2345         cgen = self->precond->expression.codegen;
2346         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2347             return false;
2348
2349         end_bprecond = func->curblock;
2350     } else {
2351         bprecond = end_bprecond = NULL;
2352     }
2353
2354     /* Now the next blocks won't be ordered nicely, but we need to
2355      * generate them this early for 'break' and 'continue'.
2356      */
2357     if (self->increment) {
2358         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
2359         if (!bincrement)
2360             return false;
2361         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2362     } else {
2363         bincrement = end_bincrement = NULL;
2364     }
2365
2366     if (self->postcond) {
2367         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
2368         if (!bpostcond)
2369             return false;
2370         bcontinue = bpostcond; /* postcond comes before the increment */
2371     } else {
2372         bpostcond = end_bpostcond = NULL;
2373     }
2374
2375     bout_id = vec_size(func->ir_func->blocks);
2376     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
2377     if (!bout)
2378         return false;
2379     bbreak = bout;
2380
2381     /* The loop body... */
2382     if (self->body)
2383     {
2384         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
2385         if (!bbody)
2386             return false;
2387
2388         /* enter */
2389         func->curblock = bbody;
2390
2391         old_bbreak          = func->breakblock;
2392         old_bcontinue       = func->continueblock;
2393         func->breakblock    = bbreak;
2394         func->continueblock = bcontinue;
2395
2396         /* generate */
2397         cgen = self->body->expression.codegen;
2398         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2399             return false;
2400
2401         end_bbody = func->curblock;
2402         func->breakblock    = old_bbreak;
2403         func->continueblock = old_bcontinue;
2404     }
2405
2406     /* post-loop-condition */
2407     if (self->postcond)
2408     {
2409         /* enter */
2410         func->curblock = bpostcond;
2411
2412         /* generate */
2413         cgen = self->postcond->expression.codegen;
2414         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2415             return false;
2416
2417         end_bpostcond = func->curblock;
2418     }
2419
2420     /* The incrementor */
2421     if (self->increment)
2422     {
2423         /* enter */
2424         func->curblock = bincrement;
2425
2426         /* generate */
2427         cgen = self->increment->expression.codegen;
2428         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2429             return false;
2430
2431         end_bincrement = func->curblock;
2432     }
2433
2434     /* In any case now, we continue from the outgoing block */
2435     func->curblock = bout;
2436
2437     /* Now all blocks are in place */
2438     /* From 'bin' we jump to whatever comes first */
2439     if      (bprecond)   tmpblock = bprecond;
2440     else if (bbody)      tmpblock = bbody;
2441     else if (bpostcond)  tmpblock = bpostcond;
2442     else                 tmpblock = bout;
2443     if (!ir_block_create_jump(bin, tmpblock))
2444         return false;
2445
2446     /* From precond */
2447     if (bprecond)
2448     {
2449         ir_block *ontrue, *onfalse;
2450         if      (bbody)      ontrue = bbody;
2451         else if (bincrement) ontrue = bincrement;
2452         else if (bpostcond)  ontrue = bpostcond;
2453         else                 ontrue = bprecond;
2454         onfalse = bout;
2455         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
2456             return false;
2457     }
2458
2459     /* from body */
2460     if (bbody)
2461     {
2462         if      (bincrement) tmpblock = bincrement;
2463         else if (bpostcond)  tmpblock = bpostcond;
2464         else if (bprecond)   tmpblock = bprecond;
2465         else                 tmpblock = bout;
2466         if (!end_bbody->final && !ir_block_create_jump(end_bbody, tmpblock))
2467             return false;
2468     }
2469
2470     /* from increment */
2471     if (bincrement)
2472     {
2473         if      (bpostcond)  tmpblock = bpostcond;
2474         else if (bprecond)   tmpblock = bprecond;
2475         else if (bbody)      tmpblock = bbody;
2476         else                 tmpblock = bout;
2477         if (!ir_block_create_jump(end_bincrement, tmpblock))
2478             return false;
2479     }
2480
2481     /* from postcond */
2482     if (bpostcond)
2483     {
2484         ir_block *ontrue, *onfalse;
2485         if      (bprecond)   ontrue = bprecond;
2486         else if (bbody)      ontrue = bbody;
2487         else if (bincrement) ontrue = bincrement;
2488         else                 ontrue = bpostcond;
2489         onfalse = bout;
2490         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
2491             return false;
2492     }
2493
2494     /* Move 'bout' to the end */
2495     vec_remove(func->ir_func->blocks, bout_id, 1);
2496     vec_push(func->ir_func->blocks, bout);
2497
2498     return true;
2499 }
2500
2501 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2502 {
2503     ir_block *target;
2504
2505     *out = NULL;
2506
2507     if (lvalue) {
2508         asterror(ast_ctx(self), "break/continue expression is not an l-value");
2509         return false;
2510     }
2511
2512     if (self->expression.outr) {
2513         asterror(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2514         return false;
2515     }
2516     self->expression.outr = (ir_value*)1;
2517
2518     if (self->is_continue)
2519         target = func->continueblock;
2520     else
2521         target = func->breakblock;
2522
2523     if (!ir_block_create_jump(func->curblock, target))
2524         return false;
2525     return true;
2526 }
2527
2528 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
2529 {
2530     ast_expression_codegen *cgen;
2531
2532     ast_switch_case *def_case  = NULL;
2533     ir_block        *def_bfall = NULL;
2534
2535     ir_value *dummy     = NULL;
2536     ir_value *irop      = NULL;
2537     ir_block *old_break = NULL;
2538     ir_block *bout      = NULL;
2539     ir_block *bfall     = NULL;
2540     size_t    bout_id;
2541     size_t    c;
2542
2543     char      typestr[1024];
2544     uint16_t  cmpinstr;
2545
2546     if (lvalue) {
2547         asterror(ast_ctx(self), "switch expression is not an l-value");
2548         return false;
2549     }
2550
2551     if (self->expression.outr) {
2552         asterror(ast_ctx(self), "internal error: ast_switch cannot be reused!");
2553         return false;
2554     }
2555     self->expression.outr = (ir_value*)1;
2556
2557     (void)lvalue;
2558     (void)out;
2559
2560     cgen = self->operand->expression.codegen;
2561     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
2562         return false;
2563
2564     if (!vec_size(self->cases))
2565         return true;
2566
2567     cmpinstr = type_eq_instr[irop->vtype];
2568     if (cmpinstr >= AINSTR_END) {
2569         ast_type_to_string(self->operand, typestr, sizeof(typestr));
2570         asterror(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
2571         return false;
2572     }
2573
2574     bout_id = vec_size(func->ir_func->blocks);
2575     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_switch"));
2576     if (!bout)
2577         return false;
2578
2579     /* setup the break block */
2580     old_break        = func->breakblock;
2581     func->breakblock = bout;
2582
2583     /* Now create all cases */
2584     for (c = 0; c < vec_size(self->cases); ++c) {
2585         ir_value *cond, *val;
2586         ir_block *bcase, *bnot;
2587         size_t bnot_id;
2588
2589         ast_switch_case *swcase = &self->cases[c];
2590
2591         if (swcase->value) {
2592             /* A regular case */
2593             /* generate the condition operand */
2594             cgen = swcase->value->expression.codegen;
2595             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
2596                 return false;
2597             /* generate the condition */
2598             cond = ir_block_create_binop(func->curblock, ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
2599             if (!cond)
2600                 return false;
2601
2602             bcase = ir_function_create_block(func->ir_func, ast_function_label(func, "case"));
2603             bnot_id = vec_size(func->ir_func->blocks);
2604             bnot = ir_function_create_block(func->ir_func, ast_function_label(func, "not_case"));
2605             if (!bcase || !bnot)
2606                 return false;
2607             if (!ir_block_create_if(func->curblock, cond, bcase, bnot))
2608                 return false;
2609
2610             /* Make the previous case-end fall through */
2611             if (bfall && !bfall->final) {
2612                 if (!ir_block_create_jump(bfall, bcase))
2613                     return false;
2614             }
2615
2616             /* enter the case */
2617             func->curblock = bcase;
2618             cgen = swcase->code->expression.codegen;
2619             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
2620                 return false;
2621
2622             /* remember this block to fall through from */
2623             bfall = func->curblock;
2624
2625             /* enter the else and move it down */
2626             func->curblock = bnot;
2627             vec_remove(func->ir_func->blocks, bnot_id, 1);
2628             vec_push(func->ir_func->blocks, bnot);
2629         } else {
2630             /* The default case */
2631             /* Remember where to fall through from: */
2632             def_bfall = bfall;
2633             bfall     = NULL;
2634             /* remember which case it was */
2635             def_case  = swcase;
2636         }
2637     }
2638
2639     /* Jump from the last bnot to bout */
2640     if (bfall && !bfall->final && !ir_block_create_jump(bfall, bout)) {
2641         /*
2642         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
2643         */
2644         return false;
2645     }
2646
2647     /* If there was a default case, put it down here */
2648     if (def_case) {
2649         ir_block *bcase;
2650
2651         /* No need to create an extra block */
2652         bcase = func->curblock;
2653
2654         /* Insert the fallthrough jump */
2655         if (def_bfall && !def_bfall->final) {
2656             if (!ir_block_create_jump(def_bfall, bcase))
2657                 return false;
2658         }
2659
2660         /* Now generate the default code */
2661         cgen = def_case->code->expression.codegen;
2662         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
2663             return false;
2664     }
2665
2666     /* Jump from the last bnot to bout */
2667     if (!func->curblock->final && !ir_block_create_jump(func->curblock, bout))
2668         return false;
2669     /* enter the outgoing block */
2670     func->curblock = bout;
2671
2672     /* restore the break block */
2673     func->breakblock = old_break;
2674
2675     /* Move 'bout' to the end, it's nicer */
2676     vec_remove(func->ir_func->blocks, bout_id, 1);
2677     vec_push(func->ir_func->blocks, bout);
2678
2679     return true;
2680 }
2681
2682 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
2683 {
2684     size_t i;
2685     ir_value *dummy;
2686
2687     *out = NULL;
2688     if (lvalue) {
2689         asterror(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
2690         return false;
2691     }
2692
2693     /* simply create a new block and jump to it */
2694     self->irblock = ir_function_create_block(func->ir_func, self->name);
2695     if (!self->irblock) {
2696         asterror(ast_ctx(self), "failed to allocate label block `%s`", self->name);
2697         return false;
2698     }
2699     if (!func->curblock->final) {
2700         if (!ir_block_create_jump(func->curblock, self->irblock))
2701             return false;
2702     }
2703
2704     /* enter the new block */
2705     func->curblock = self->irblock;
2706
2707     /* Generate all the leftover gotos */
2708     for (i = 0; i < vec_size(self->gotos); ++i) {
2709         if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
2710             return false;
2711     }
2712
2713     return true;
2714 }
2715
2716 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
2717 {
2718     *out = NULL;
2719     if (lvalue) {
2720         asterror(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
2721         return false;
2722     }
2723
2724     if (self->target->irblock) {
2725         if (self->irblock_from) {
2726             /* we already tried once, this is the callback */
2727             self->irblock_from->final = false;
2728             if (!ir_block_create_jump(self->irblock_from, self->target->irblock)) {
2729                 asterror(ast_ctx(self), "failed to generate goto to `%s`", self->name);
2730                 return false;
2731             }
2732         }
2733         else
2734         {
2735             if (!ir_block_create_jump(func->curblock, self->target->irblock)) {
2736                 asterror(ast_ctx(self), "failed to generate goto to `%s`", self->name);
2737                 return false;
2738             }
2739         }
2740     }
2741     else
2742     {
2743         /* the target has not yet been created...
2744          * close this block in a sneaky way:
2745          */
2746         func->curblock->final = true;
2747         self->irblock_from = func->curblock;
2748         ast_label_register_goto(self->target, self);
2749     }
2750
2751     return true;
2752 }
2753
2754 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
2755 {
2756     ast_expression_codegen *cgen;
2757     ir_value              **params;
2758     ir_instr               *callinstr;
2759     size_t i;
2760
2761     ir_value *funval = NULL;
2762
2763     /* return values are never lvalues */
2764     if (lvalue) {
2765         asterror(ast_ctx(self), "not an l-value (function call)");
2766         return false;
2767     }
2768
2769     if (self->expression.outr) {
2770         *out = self->expression.outr;
2771         return true;
2772     }
2773
2774     cgen = self->func->expression.codegen;
2775     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
2776         return false;
2777     if (!funval)
2778         return false;
2779
2780     params = NULL;
2781
2782     /* parameters */
2783     for (i = 0; i < vec_size(self->params); ++i)
2784     {
2785         ir_value *param;
2786         ast_expression *expr = self->params[i];
2787
2788         cgen = expr->expression.codegen;
2789         if (!(*cgen)(expr, func, false, &param))
2790             goto error;
2791         if (!param)
2792             goto error;
2793         vec_push(params, param);
2794     }
2795
2796     callinstr = ir_block_create_call(func->curblock, ast_function_label(func, "call"), funval);
2797     if (!callinstr)
2798         goto error;
2799
2800     for (i = 0; i < vec_size(params); ++i) {
2801         ir_call_param(callinstr, params[i]);
2802     }
2803
2804     *out = ir_call_value(callinstr);
2805     self->expression.outr = *out;
2806
2807     vec_free(params);
2808     return true;
2809 error:
2810     vec_free(params);
2811     return false;
2812 }