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