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