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