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