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