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