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