]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
array accessor function genaration
[xonotic/gmqcc.git] / ast.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "gmqcc.h"
28 #include "ast.h"
29
30 #define ast_instantiate(T, ctx, destroyfn)                          \
31     T* self = (T*)mem_a(sizeof(T));                                 \
32     if (!self) {                                                    \
33         return NULL;                                                \
34     }                                                               \
35     ast_node_init((ast_node*)self, ctx, TYPE_##T);                  \
36     ( (ast_node*)self )->node.destroy = (ast_node_delete*)destroyfn
37
38 /* error handling */
39 static void asterror(lex_ctx ctx, const char *msg, ...)
40 {
41     va_list ap;
42     va_start(ap, msg);
43     cvprintmsg(ctx, LVL_ERROR, "error", msg, ap);
44     va_end(ap);
45 }
46
47 /* It must not be possible to get here. */
48 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
49 {
50     fprintf(stderr, "ast node missing destroy()\n");
51     abort();
52 }
53
54 /* Initialize main ast node aprts */
55 static void ast_node_init(ast_node *self, lex_ctx ctx, int nodetype)
56 {
57     self->node.context = ctx;
58     self->node.destroy = &_ast_node_destroy;
59     self->node.keep    = false;
60     self->node.nodetype = nodetype;
61 }
62
63 /* General expression initialization */
64 static void ast_expression_init(ast_expression *self,
65                                 ast_expression_codegen *codegen)
66 {
67     self->expression.codegen  = codegen;
68     self->expression.vtype    = TYPE_VOID;
69     self->expression.next     = NULL;
70     self->expression.outl     = NULL;
71     self->expression.outr     = NULL;
72     self->expression.variadic = false;
73     MEM_VECTOR_INIT(&self->expression, params);
74 }
75
76 static void ast_expression_delete(ast_expression *self)
77 {
78     size_t i;
79     if (self->expression.next)
80         ast_delete(self->expression.next);
81     for (i = 0; i < self->expression.params_count; ++i) {
82         ast_delete(self->expression.params[i]);
83     }
84     MEM_VECTOR_CLEAR(&self->expression, params);
85 }
86
87 static void ast_expression_delete_full(ast_expression *self)
88 {
89     ast_expression_delete(self);
90     mem_d(self);
91 }
92
93 MEM_VEC_FUNCTIONS(ast_expression_common, ast_value*, params)
94
95 ast_value* ast_value_copy(const ast_value *self)
96 {
97     size_t i;
98     const ast_expression_common *fromex;
99     ast_expression_common *selfex;
100     ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
101     if (self->expression.next) {
102         cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
103         if (!cp->expression.next) {
104             ast_value_delete(cp);
105             return NULL;
106         }
107     }
108     fromex   = &self->expression;
109     selfex = &cp->expression;
110     selfex->variadic = fromex->variadic;
111     for (i = 0; i < fromex->params_count; ++i) {
112         ast_value *v = ast_value_copy(fromex->params[i]);
113         if (!v || !ast_expression_common_params_add(selfex, v)) {
114             ast_value_delete(cp);
115             return NULL;
116         }
117     }
118     return cp;
119 }
120
121 bool ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
122 {
123     size_t i;
124     const ast_expression_common *fromex;
125     ast_expression_common *selfex;
126     self->expression.vtype = other->expression.vtype;
127     if (other->expression.next) {
128         self->expression.next = (ast_expression*)ast_type_copy(ast_ctx(self), other->expression.next);
129         if (!self->expression.next)
130             return false;
131     }
132     fromex   = &other->expression;
133     selfex = &self->expression;
134     selfex->variadic = fromex->variadic;
135     for (i = 0; i < fromex->params_count; ++i) {
136         ast_value *v = ast_value_copy(fromex->params[i]);
137         if (!v || !ast_expression_common_params_add(selfex, v))
138             return false;
139     }
140     return true;
141 }
142
143 static ast_expression* ast_shallow_type(lex_ctx ctx, int vtype)
144 {
145     ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
146     ast_expression_init(self, NULL);
147     self->expression.codegen = NULL;
148     self->expression.next    = NULL;
149     self->expression.vtype   = vtype;
150     return self;
151 }
152
153 ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
154 {
155     size_t i;
156     const ast_expression_common *fromex;
157     ast_expression_common *selfex;
158
159     if (!ex)
160         return NULL;
161     else
162     {
163         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
164         ast_expression_init(self, NULL);
165
166         fromex   = &ex->expression;
167         selfex = &self->expression;
168
169         /* This may never be codegen()d */
170         selfex->codegen = NULL;
171
172         selfex->vtype = fromex->vtype;
173         if (fromex->next)
174         {
175             selfex->next = ast_type_copy(ctx, fromex->next);
176             if (!selfex->next) {
177                 ast_expression_delete_full(self);
178                 return NULL;
179             }
180         }
181         else
182             selfex->next = NULL;
183
184         selfex->variadic = fromex->variadic;
185         for (i = 0; i < fromex->params_count; ++i) {
186             ast_value *v = ast_value_copy(fromex->params[i]);
187             if (!v || !ast_expression_common_params_add(selfex, v)) {
188                 ast_expression_delete_full(self);
189                 return NULL;
190             }
191         }
192
193         return self;
194     }
195 }
196
197 bool ast_compare_type(ast_expression *a, ast_expression *b)
198 {
199     if (a->expression.vtype != b->expression.vtype)
200         return false;
201     if (!a->expression.next != !b->expression.next)
202         return false;
203     if (a->expression.params_count != b->expression.params_count)
204         return false;
205     if (a->expression.variadic != b->expression.variadic)
206         return false;
207     if (a->expression.params_count) {
208         size_t i;
209         for (i = 0; i < a->expression.params_count; ++i) {
210             if (!ast_compare_type((ast_expression*)a->expression.params[i],
211                                   (ast_expression*)b->expression.params[i]))
212                 return false;
213         }
214     }
215     if (a->expression.next)
216         return ast_compare_type(a->expression.next, b->expression.next);
217     return true;
218 }
219
220 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
221 {
222     const char *typestr;
223     size_t typelen;
224     size_t i;
225
226     if (!e) {
227         if (pos + 6 >= bufsize)
228             goto full;
229         strcpy(buf + pos, "(null)");
230         return pos + 6;
231     }
232
233     if (pos + 1 >= bufsize)
234         goto full;
235
236     switch (e->expression.vtype) {
237         case TYPE_VARIANT:
238             strcpy(buf + pos, "(variant)");
239             return pos + 9;
240
241         case TYPE_FIELD:
242             buf[pos++] = '.';
243             return ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
244
245         case TYPE_POINTER:
246             if (pos + 3 >= bufsize)
247                 goto full;
248             buf[pos++] = '*';
249             buf[pos++] = '(';
250             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
251             if (pos + 1 >= bufsize)
252                 goto full;
253             buf[pos++] = ')';
254             return pos;
255
256         case TYPE_FUNCTION:
257             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
258             if (pos + 2 >= bufsize)
259                 goto full;
260             if (e->expression.params_count == 0) {
261                 buf[pos++] = '(';
262                 buf[pos++] = ')';
263                 return pos;
264             }
265             buf[pos++] = '(';
266             pos = ast_type_to_string_impl((ast_expression*)(e->expression.params[0]), buf, bufsize, pos);
267             for (i = 1; i < e->expression.params_count; ++i) {
268                 if (pos + 2 >= bufsize)
269                     goto full;
270                 buf[pos++] = ',';
271                 buf[pos++] = ' ';
272                 pos = ast_type_to_string_impl((ast_expression*)(e->expression.params[i]), buf, bufsize, pos);
273             }
274             if (pos + 1 >= bufsize)
275                 goto full;
276             buf[pos++] = ')';
277             return pos;
278
279         case TYPE_ARRAY:
280             pos = ast_type_to_string_impl(e->expression.next, buf, bufsize, pos);
281             if (pos + 1 >= bufsize)
282                 goto full;
283             buf[pos++] = '[';
284             pos += snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->expression.count);
285             if (pos + 1 >= bufsize)
286                 goto full;
287             buf[pos++] = ']';
288             return pos;
289
290         default:
291             typestr = type_name[e->expression.vtype];
292             typelen = strlen(typestr);
293             if (pos + typelen >= bufsize)
294                 goto full;
295             strcpy(buf + pos, typestr);
296             return pos + typelen;
297     }
298
299 full:
300     buf[bufsize-3] = '.';
301     buf[bufsize-2] = '.';
302     buf[bufsize-1] = '.';
303     return bufsize;
304 }
305
306 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
307 {
308     size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
309     buf[pos] = 0;
310 }
311
312 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
313 {
314     ast_instantiate(ast_value, ctx, ast_value_delete);
315     ast_expression_init((ast_expression*)self,
316                         (ast_expression_codegen*)&ast_value_codegen);
317     self->expression.node.keep = true; /* keep */
318
319     self->name = name ? util_strdup(name) : NULL;
320     self->expression.vtype = t;
321     self->expression.next  = NULL;
322     self->isconst = false;
323     self->uses    = 0;
324     memset(&self->constval, 0, sizeof(self->constval));
325
326     self->ir_v           = NULL;
327     self->ir_values      = NULL;
328     self->ir_value_count = 0;
329
330     return self;
331 }
332
333 void ast_value_delete(ast_value* self)
334 {
335     if (self->name)
336         mem_d((void*)self->name);
337     if (self->isconst) {
338         switch (self->expression.vtype)
339         {
340         case TYPE_STRING:
341             mem_d((void*)self->constval.vstring);
342             break;
343         case TYPE_FUNCTION:
344             /* unlink us from the function node */
345             self->constval.vfunc->vtype = NULL;
346             break;
347         /* NOTE: delete function? currently collected in
348          * the parser structure
349          */
350         default:
351             break;
352         }
353     }
354     if (self->ir_values)
355         mem_d(self->ir_values);
356     ast_expression_delete((ast_expression*)self);
357     mem_d(self);
358 }
359
360 bool GMQCC_WARN ast_value_params_add(ast_value *self, ast_value *p)
361 {
362     return ast_expression_common_params_add(&self->expression, p);
363 }
364
365 bool ast_value_set_name(ast_value *self, const char *name)
366 {
367     if (self->name)
368         mem_d((void*)self->name);
369     self->name = util_strdup(name);
370     return !!self->name;
371 }
372
373 ast_binary* ast_binary_new(lex_ctx ctx, int op,
374                            ast_expression* left, ast_expression* right)
375 {
376     ast_instantiate(ast_binary, ctx, ast_binary_delete);
377     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
378
379     self->op = op;
380     self->left = left;
381     self->right = right;
382
383     if (op >= INSTR_EQ_F && op <= INSTR_GT)
384         self->expression.vtype = TYPE_FLOAT;
385     else if (op == INSTR_AND || op == INSTR_OR ||
386              op == INSTR_BITAND || op == INSTR_BITOR)
387         self->expression.vtype = TYPE_FLOAT;
388     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
389         self->expression.vtype = TYPE_VECTOR;
390     else if (op == INSTR_MUL_V)
391         self->expression.vtype = TYPE_FLOAT;
392     else
393         self->expression.vtype = left->expression.vtype;
394
395     return self;
396 }
397
398 void ast_binary_delete(ast_binary *self)
399 {
400     ast_unref(self->left);
401     ast_unref(self->right);
402     ast_expression_delete((ast_expression*)self);
403     mem_d(self);
404 }
405
406 ast_binstore* ast_binstore_new(lex_ctx ctx, int storop, int op,
407                                ast_expression* left, ast_expression* right)
408 {
409     ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
410     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
411
412     self->opstore = storop;
413     self->opbin   = op;
414     self->dest    = left;
415     self->source  = right;
416
417     self->expression.vtype = left->expression.vtype;
418     if (left->expression.next) {
419         self->expression.next = ast_type_copy(ctx, left);
420         if (!self->expression.next) {
421             ast_delete(self);
422             return NULL;
423         }
424     }
425     else
426         self->expression.next = NULL;
427
428     return self;
429 }
430
431 void ast_binstore_delete(ast_binstore *self)
432 {
433     ast_unref(self->dest);
434     ast_unref(self->source);
435     ast_expression_delete((ast_expression*)self);
436     mem_d(self);
437 }
438
439 ast_unary* ast_unary_new(lex_ctx ctx, int op,
440                          ast_expression *expr)
441 {
442     ast_instantiate(ast_unary, ctx, ast_unary_delete);
443     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
444
445     self->op = op;
446     self->operand = expr;
447
448     if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
449         self->expression.vtype = TYPE_FLOAT;
450     } else
451         asterror(ctx, "cannot determine type of unary operation %s", asm_instr[op].m);
452
453     return self;
454 }
455
456 void ast_unary_delete(ast_unary *self)
457 {
458     ast_unref(self->operand);
459     ast_expression_delete((ast_expression*)self);
460     mem_d(self);
461 }
462
463 ast_return* ast_return_new(lex_ctx ctx, ast_expression *expr)
464 {
465     ast_instantiate(ast_return, ctx, ast_return_delete);
466     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
467
468     self->operand = expr;
469
470     return self;
471 }
472
473 void ast_return_delete(ast_return *self)
474 {
475     if (self->operand)
476         ast_unref(self->operand);
477     ast_expression_delete((ast_expression*)self);
478     mem_d(self);
479 }
480
481 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
482 {
483     const ast_expression *outtype;
484
485     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
486
487     if (field->expression.vtype != TYPE_FIELD) {
488         mem_d(self);
489         return NULL;
490     }
491
492     outtype = field->expression.next;
493     if (!outtype) {
494         mem_d(self);
495         /* Error: field has no type... */
496         return NULL;
497     }
498
499     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
500
501     self->entity = entity;
502     self->field  = field;
503
504     if (!ast_type_adopt(self, outtype)) {
505         ast_entfield_delete(self);
506         return NULL;
507     }
508
509     return self;
510 }
511
512 void ast_entfield_delete(ast_entfield *self)
513 {
514     ast_unref(self->entity);
515     ast_unref(self->field);
516     ast_expression_delete((ast_expression*)self);
517     mem_d(self);
518 }
519
520 ast_member* ast_member_new(lex_ctx ctx, ast_expression *owner, unsigned int field)
521 {
522     ast_instantiate(ast_member, ctx, ast_member_delete);
523     if (field >= 3) {
524         mem_d(self);
525         return NULL;
526     }
527
528     if (owner->expression.vtype != TYPE_VECTOR &&
529         owner->expression.vtype != TYPE_FIELD) {
530         asterror(ctx, "member-access on an invalid owner of type %s", type_name[owner->expression.vtype]);
531         mem_d(self);
532         return NULL;
533     }
534
535     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
536     self->expression.node.keep = true; /* keep */
537
538     if (owner->expression.vtype == TYPE_VECTOR) {
539         self->expression.vtype = TYPE_FLOAT;
540         self->expression.next  = NULL;
541     } else {
542         self->expression.vtype = TYPE_FIELD;
543         self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
544     }
545
546     self->owner = owner;
547     self->field = field;
548
549     return self;
550 }
551
552 void ast_member_delete(ast_member *self)
553 {
554     /* The owner is always an ast_value, which has .keep=true,
555      * also: ast_members are usually deleted after the owner, thus
556      * this will cause invalid access
557     ast_unref(self->owner);
558      * once we allow (expression).x to access a vector-member, we need
559      * to change this: preferably by creating an alternate ast node for this
560      * purpose that is not garbage-collected.
561     */
562     ast_expression_delete((ast_expression*)self);
563     mem_d(self);
564 }
565
566 ast_array_index* ast_array_index_new(lex_ctx ctx, ast_expression *array, ast_expression *index)
567 {
568     const ast_expression *outtype;
569     ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
570
571     outtype = array->expression.next;
572     if (!outtype) {
573         mem_d(self);
574         /* Error: field has no type... */
575         return NULL;
576     }
577
578     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
579
580     self->array = array;
581     self->index = index;
582
583     if (!ast_type_adopt(self, outtype)) {
584         ast_array_index_delete(self);
585         return NULL;
586     }
587
588     return self;
589 }
590
591 void ast_array_index_delete(ast_array_index *self)
592 {
593     ast_unref(self->array);
594     ast_unref(self->index);
595     ast_expression_delete((ast_expression*)self);
596     mem_d(self);
597 }
598
599 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
600 {
601     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
602     if (!ontrue && !onfalse) {
603         /* because it is invalid */
604         mem_d(self);
605         return NULL;
606     }
607     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
608
609     self->cond     = cond;
610     self->on_true  = ontrue;
611     self->on_false = onfalse;
612
613     return self;
614 }
615
616 void ast_ifthen_delete(ast_ifthen *self)
617 {
618     ast_unref(self->cond);
619     if (self->on_true)
620         ast_unref(self->on_true);
621     if (self->on_false)
622         ast_unref(self->on_false);
623     ast_expression_delete((ast_expression*)self);
624     mem_d(self);
625 }
626
627 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
628 {
629     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
630     /* This time NEITHER must be NULL */
631     if (!ontrue || !onfalse) {
632         mem_d(self);
633         return NULL;
634     }
635     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
636
637     self->cond     = cond;
638     self->on_true  = ontrue;
639     self->on_false = onfalse;
640     self->phi_out  = NULL;
641
642     return self;
643 }
644
645 void ast_ternary_delete(ast_ternary *self)
646 {
647     ast_unref(self->cond);
648     ast_unref(self->on_true);
649     ast_unref(self->on_false);
650     ast_expression_delete((ast_expression*)self);
651     mem_d(self);
652 }
653
654 ast_loop* ast_loop_new(lex_ctx ctx,
655                        ast_expression *initexpr,
656                        ast_expression *precond,
657                        ast_expression *postcond,
658                        ast_expression *increment,
659                        ast_expression *body)
660 {
661     ast_instantiate(ast_loop, ctx, ast_loop_delete);
662     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
663
664     self->initexpr  = initexpr;
665     self->precond   = precond;
666     self->postcond  = postcond;
667     self->increment = increment;
668     self->body      = body;
669
670     return self;
671 }
672
673 void ast_loop_delete(ast_loop *self)
674 {
675     if (self->initexpr)
676         ast_unref(self->initexpr);
677     if (self->precond)
678         ast_unref(self->precond);
679     if (self->postcond)
680         ast_unref(self->postcond);
681     if (self->increment)
682         ast_unref(self->increment);
683     if (self->body)
684         ast_unref(self->body);
685     ast_expression_delete((ast_expression*)self);
686     mem_d(self);
687 }
688
689 ast_call* ast_call_new(lex_ctx ctx,
690                        ast_expression *funcexpr)
691 {
692     ast_instantiate(ast_call, ctx, ast_call_delete);
693     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
694
695     MEM_VECTOR_INIT(self, params);
696
697     self->func = funcexpr;
698
699     self->expression.vtype = funcexpr->expression.next->expression.vtype;
700     if (funcexpr->expression.next->expression.next)
701         self->expression.next = ast_type_copy(ctx, funcexpr->expression.next->expression.next);
702
703     return self;
704 }
705 MEM_VEC_FUNCTIONS(ast_call, ast_expression*, params)
706
707 void ast_call_delete(ast_call *self)
708 {
709     size_t i;
710     for (i = 0; i < self->params_count; ++i)
711         ast_unref(self->params[i]);
712     MEM_VECTOR_CLEAR(self, params);
713
714     if (self->func)
715         ast_unref(self->func);
716
717     ast_expression_delete((ast_expression*)self);
718     mem_d(self);
719 }
720
721 bool ast_call_check_types(ast_call *self)
722 {
723     size_t i;
724     bool   retval = true;
725     const  ast_expression *func = self->func;
726     size_t count = self->params_count;
727     if (count > func->expression.params_count)
728         count = func->expression.params_count;
729
730     for (i = 0; i < count; ++i) {
731         if (!ast_compare_type(self->params[i], (ast_expression*)(func->expression.params[i]))) {
732             asterror(ast_ctx(self), "invalid type for parameter %u in function call",
733                      (unsigned int)(i+1));
734             /* we don't immediately return */
735             retval = false;
736         }
737     }
738     return retval;
739 }
740
741 ast_store* ast_store_new(lex_ctx ctx, int op,
742                          ast_expression *dest, ast_expression *source)
743 {
744     ast_instantiate(ast_store, ctx, ast_store_delete);
745     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
746
747     self->op = op;
748     self->dest = dest;
749     self->source = source;
750
751     self->expression.vtype = dest->expression.vtype;
752     if (dest->expression.next) {
753         self->expression.next = ast_type_copy(ctx, dest);
754         if (!self->expression.next) {
755             ast_delete(self);
756             return NULL;
757         }
758     }
759     else
760         self->expression.next = NULL;
761
762     return self;
763 }
764
765 void ast_store_delete(ast_store *self)
766 {
767     ast_unref(self->dest);
768     ast_unref(self->source);
769     ast_expression_delete((ast_expression*)self);
770     mem_d(self);
771 }
772
773 ast_block* ast_block_new(lex_ctx ctx)
774 {
775     ast_instantiate(ast_block, ctx, ast_block_delete);
776     ast_expression_init((ast_expression*)self,
777                         (ast_expression_codegen*)&ast_block_codegen);
778
779     MEM_VECTOR_INIT(self, locals);
780     MEM_VECTOR_INIT(self, exprs);
781     MEM_VECTOR_INIT(self, collect);
782
783     return self;
784 }
785 MEM_VEC_FUNCTIONS(ast_block, ast_value*, locals)
786 MEM_VEC_FUNCTIONS(ast_block, ast_expression*, exprs)
787 MEM_VEC_FUNCTIONS(ast_block, ast_expression*, collect)
788
789 bool ast_block_collect(ast_block *self, ast_expression *expr)
790 {
791     if (!ast_block_collect_add(self, expr))
792         return false;
793     expr->expression.node.keep = true;
794     return true;
795 }
796
797 void ast_block_delete(ast_block *self)
798 {
799     size_t i;
800     for (i = 0; i < self->exprs_count; ++i)
801         ast_unref(self->exprs[i]);
802     MEM_VECTOR_CLEAR(self, exprs);
803     for (i = 0; i < self->locals_count; ++i)
804         ast_delete(self->locals[i]);
805     MEM_VECTOR_CLEAR(self, locals);
806     for (i = 0; i < self->collect_count; ++i)
807         ast_delete(self->collect[i]);
808     MEM_VECTOR_CLEAR(self, collect);
809     ast_expression_delete((ast_expression*)self);
810     mem_d(self);
811 }
812
813 bool ast_block_set_type(ast_block *self, ast_expression *from)
814 {
815     if (self->expression.next)
816         ast_delete(self->expression.next);
817     self->expression.vtype = from->expression.vtype;
818     if (from->expression.next) {
819         self->expression.next = ast_type_copy(self->expression.node.context, from->expression.next);
820         if (!self->expression.next)
821             return false;
822     }
823     else
824         self->expression.next = NULL;
825     return true;
826 }
827
828 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
829 {
830     ast_instantiate(ast_function, ctx, ast_function_delete);
831
832     if (!vtype ||
833         vtype->isconst ||
834         vtype->expression.vtype != TYPE_FUNCTION)
835     {
836         mem_d(self);
837         return NULL;
838     }
839
840     self->vtype = vtype;
841     self->name = name ? util_strdup(name) : NULL;
842     MEM_VECTOR_INIT(self, blocks);
843
844     self->labelcount = 0;
845     self->builtin = 0;
846
847     self->ir_func = NULL;
848     self->curblock = NULL;
849
850     self->breakblock    = NULL;
851     self->continueblock = NULL;
852
853     vtype->isconst = true;
854     vtype->constval.vfunc = self;
855
856     return self;
857 }
858
859 MEM_VEC_FUNCTIONS(ast_function, ast_block*, blocks)
860
861 void ast_function_delete(ast_function *self)
862 {
863     size_t i;
864     if (self->name)
865         mem_d((void*)self->name);
866     if (self->vtype) {
867         /* ast_value_delete(self->vtype); */
868         self->vtype->isconst = false;
869         self->vtype->constval.vfunc = NULL;
870         /* We use unref - if it was stored in a global table it is supposed
871          * to be deleted from *there*
872          */
873         ast_unref(self->vtype);
874     }
875     for (i = 0; i < self->blocks_count; ++i)
876         ast_delete(self->blocks[i]);
877     MEM_VECTOR_CLEAR(self, blocks);
878     mem_d(self);
879 }
880
881 const char* ast_function_label(ast_function *self, const char *prefix)
882 {
883     size_t id;
884     size_t len;
885     char  *from;
886
887     if (!opts_dump)
888         return NULL;
889
890     id  = (self->labelcount++);
891     len = strlen(prefix);
892
893     from = self->labelbuf + sizeof(self->labelbuf)-1;
894     *from-- = 0;
895     do {
896         unsigned int digit = id % 10;
897         *from = digit + '0';
898         id /= 10;
899     } while (id);
900     memcpy(from - len, prefix, len);
901     return from - len;
902 }
903
904 /*********************************************************************/
905 /* AST codegen part
906  * by convention you must never pass NULL to the 'ir_value **out'
907  * parameter. If you really don't care about the output, pass a dummy.
908  * But I can't imagine a pituation where the output is truly unnecessary.
909  */
910
911 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
912 {
913     /* NOTE: This is the codegen for a variable used in an expression.
914      * It is not the codegen to generate the value. For this purpose,
915      * ast_local_codegen and ast_global_codegen are to be used before this
916      * is executed. ast_function_codegen should take care of its locals,
917      * and the ast-user should take care of ast_global_codegen to be used
918      * on all the globals.
919      */
920     if (!self->ir_v) {
921         asterror(ast_ctx(self), "ast_value used before generated (%s)", self->name);
922         return false;
923     }
924     *out = self->ir_v;
925     return true;
926 }
927
928 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
929 {
930     ir_value *v = NULL;
931     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
932     {
933         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
934         if (!func)
935             return false;
936         func->context = ast_ctx(self);
937         func->value->context = ast_ctx(self);
938
939         self->constval.vfunc->ir_func = func;
940         self->ir_v = func->value;
941         /* The function is filled later on ast_function_codegen... */
942         return true;
943     }
944
945     if (isfield && self->expression.vtype == TYPE_FIELD) {
946         v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
947         if (!v)
948             return false;
949         v->context = ast_ctx(self);
950         if (self->isconst) {
951             asterror(ast_ctx(self), "TODO: constant field pointers with value");
952             goto error;
953         }
954         self->ir_v = v;
955         return true;
956     }
957
958     if (self->expression.vtype == TYPE_ARRAY) {
959         size_t ai;
960         char   *name;
961         size_t  namelen;
962
963         ast_expression_common *elemtype = &self->expression.next->expression;
964         int vtype = elemtype->vtype;
965         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
966         if (!self->expression.count || self->expression.count > opts_max_array_size) {
967             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
968         }
969
970         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
971         if (!self->ir_values) {
972             asterror(ast_ctx(self), "failed to allocate array values");
973             return false;
974         }
975
976         v = ir_builder_create_global(ir, self->name, vtype);
977         if (!v) {
978             asterror(ast_ctx(self), "ir_builder_create_global failed");
979             return false;
980         }
981         if (vtype == TYPE_FIELD)
982             v->fieldtype = elemtype->next->expression.vtype;
983         v->context = ast_ctx(self);
984
985         namelen = strlen(self->name);
986         name    = (char*)mem_a(namelen + 16);
987         strcpy(name, self->name);
988
989         self->ir_values[0] = v;
990         for (ai = 1; ai < self->expression.count; ++ai) {
991             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
992             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
993             if (!self->ir_values[ai]) {
994                 asterror(ast_ctx(self), "ir_builder_create_global failed");
995                 return false;
996             }
997             if (vtype == TYPE_FIELD)
998                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
999             self->ir_values[ai]->context = ast_ctx(self);
1000         }
1001     }
1002     else
1003     {
1004         /* Arrays don't do this since there's no "array" value which spans across the
1005          * whole thing.
1006          */
1007         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1008         if (!v) {
1009             asterror(ast_ctx(self), "ir_builder_create_global failed");
1010             return false;
1011         }
1012         if (self->expression.vtype == TYPE_FIELD)
1013             v->fieldtype = self->expression.next->expression.vtype;
1014         v->context = ast_ctx(self);
1015     }
1016
1017     if (self->isconst) {
1018         switch (self->expression.vtype)
1019         {
1020             case TYPE_FLOAT:
1021                 if (!ir_value_set_float(v, self->constval.vfloat))
1022                     goto error;
1023                 break;
1024             case TYPE_VECTOR:
1025                 if (!ir_value_set_vector(v, self->constval.vvec))
1026                     goto error;
1027                 break;
1028             case TYPE_STRING:
1029                 if (!ir_value_set_string(v, self->constval.vstring))
1030                     goto error;
1031                 break;
1032             case TYPE_ARRAY:
1033                 asterror(ast_ctx(self), "TODO: global constant array");
1034                 break;
1035             case TYPE_FUNCTION:
1036                 asterror(ast_ctx(self), "global of type function not properly generated");
1037                 goto error;
1038                 /* Cannot generate an IR value for a function,
1039                  * need a pointer pointing to a function rather.
1040                  */
1041             default:
1042                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1043                 break;
1044         }
1045     }
1046
1047     /* link us to the ir_value */
1048     self->ir_v = v;
1049     return true;
1050
1051 error: /* clean up */
1052     ir_value_delete(v);
1053     return false;
1054 }
1055
1056 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1057 {
1058     ir_value *v = NULL;
1059     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
1060     {
1061         /* Do we allow local functions? I think not...
1062          * this is NOT a function pointer atm.
1063          */
1064         return false;
1065     }
1066
1067     if (self->expression.vtype == TYPE_ARRAY)
1068     {
1069         asterror(ast_ctx(self), "TODO: ast_local_codgen for TYPE_ARRAY");
1070         return false;
1071     }
1072
1073     v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1074     if (!v)
1075         return false;
1076     if (self->expression.vtype == TYPE_FIELD)
1077         v->fieldtype = self->expression.next->expression.vtype;
1078     v->context = ast_ctx(self);
1079
1080     /* A constant local... hmmm...
1081      * I suppose the IR will have to deal with this
1082      */
1083     if (self->isconst) {
1084         switch (self->expression.vtype)
1085         {
1086             case TYPE_FLOAT:
1087                 if (!ir_value_set_float(v, self->constval.vfloat))
1088                     goto error;
1089                 break;
1090             case TYPE_VECTOR:
1091                 if (!ir_value_set_vector(v, self->constval.vvec))
1092                     goto error;
1093                 break;
1094             case TYPE_STRING:
1095                 if (!ir_value_set_string(v, self->constval.vstring))
1096                     goto error;
1097                 break;
1098             default:
1099                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1100                 break;
1101         }
1102     }
1103
1104     /* link us to the ir_value */
1105     self->ir_v = v;
1106     return true;
1107
1108 error: /* clean up */
1109     ir_value_delete(v);
1110     return false;
1111 }
1112
1113 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1114 {
1115     ir_function *irf;
1116     ir_value    *dummy;
1117     ast_expression_common *ec;
1118     size_t    i;
1119
1120     irf = self->ir_func;
1121     if (!irf) {
1122         asterror(ast_ctx(self), "ast_function's related ast_value was not generated yet");
1123         return false;
1124     }
1125
1126     /* fill the parameter list */
1127     ec = &self->vtype->expression;
1128     for (i = 0; i < ec->params_count; ++i)
1129     {
1130         if (!ir_function_params_add(irf, ec->params[i]->expression.vtype))
1131             return false;
1132         if (!self->builtin) {
1133             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1134                 return false;
1135         }
1136     }
1137
1138     if (self->builtin) {
1139         irf->builtin = self->builtin;
1140         return true;
1141     }
1142
1143     if (!self->blocks_count) {
1144         asterror(ast_ctx(self), "function `%s` has no body", self->name);
1145         return false;
1146     }
1147
1148     self->curblock = ir_function_create_block(irf, "entry");
1149     if (!self->curblock) {
1150         asterror(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1151         return false;
1152     }
1153
1154     for (i = 0; i < self->blocks_count; ++i) {
1155         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
1156         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
1157             return false;
1158     }
1159
1160     /* TODO: check return types */
1161     if (!self->curblock->is_return)
1162     {
1163         return ir_block_create_return(self->curblock, NULL);
1164         /* From now on the parser has to handle this situation */
1165 #if 0
1166         if (!self->vtype->expression.next ||
1167             self->vtype->expression.next->expression.vtype == TYPE_VOID)
1168         {
1169             return ir_block_create_return(self->curblock, NULL);
1170         }
1171         else
1172         {
1173             /* error("missing return"); */
1174             asterror(ast_ctx(self), "function `%s` missing return value", self->name);
1175             return false;
1176         }
1177 #endif
1178     }
1179     return true;
1180 }
1181
1182 /* Note, you will not see ast_block_codegen generate ir_blocks.
1183  * To the AST and the IR, blocks are 2 different things.
1184  * In the AST it represents a block of code, usually enclosed in
1185  * curly braces {...}.
1186  * While in the IR it represents a block in terms of control-flow.
1187  */
1188 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1189 {
1190     size_t i;
1191
1192     /* We don't use this
1193      * Note: an ast-representation using the comma-operator
1194      * of the form: (a, b, c) = x should not assign to c...
1195      */
1196     if (lvalue) {
1197         asterror(ast_ctx(self), "not an l-value (code-block)");
1198         return false;
1199     }
1200
1201     if (self->expression.outr) {
1202         *out = self->expression.outr;
1203         return true;
1204     }
1205
1206     /* output is NULL at first, we'll have each expression
1207      * assign to out output, thus, a comma-operator represention
1208      * using an ast_block will return the last generated value,
1209      * so: (b, c) + a  executed both b and c, and returns c,
1210      * which is then added to a.
1211      */
1212     *out = NULL;
1213
1214     /* generate locals */
1215     for (i = 0; i < self->locals_count; ++i)
1216     {
1217         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1218             if (opts_debug)
1219                 asterror(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1220             return false;
1221         }
1222     }
1223
1224     for (i = 0; i < self->exprs_count; ++i)
1225     {
1226         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
1227         if (!(*gen)(self->exprs[i], func, false, out))
1228             return false;
1229     }
1230
1231     self->expression.outr = *out;
1232
1233     return true;
1234 }
1235
1236 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1237 {
1238     ast_expression_codegen *cgen;
1239     ir_value *left, *right;
1240
1241     if (lvalue && self->expression.outl) {
1242         *out = self->expression.outl;
1243         return true;
1244     }
1245
1246     if (!lvalue && self->expression.outr) {
1247         *out = self->expression.outr;
1248         return true;
1249     }
1250
1251     cgen = self->dest->expression.codegen;
1252     /* lvalue! */
1253     if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1254         return false;
1255     self->expression.outl = left;
1256
1257     cgen = self->source->expression.codegen;
1258     /* rvalue! */
1259     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1260         return false;
1261
1262     if (!ir_block_create_store_op(func->curblock, self->op, left, right))
1263         return false;
1264     self->expression.outr = right;
1265
1266     /* Theoretically, an assinment returns its left side as an
1267      * lvalue, if we don't need an lvalue though, we return
1268      * the right side as an rvalue, otherwise we have to
1269      * somehow know whether or not we need to dereference the pointer
1270      * on the left side - that is: OP_LOAD if it was an address.
1271      * Also: in original QC we cannot OP_LOADP *anyway*.
1272      */
1273     *out = (lvalue ? left : right);
1274
1275     return true;
1276 }
1277
1278 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1279 {
1280     ast_expression_codegen *cgen;
1281     ir_value *left, *right;
1282
1283     /* A binary operation cannot yield an l-value */
1284     if (lvalue) {
1285         asterror(ast_ctx(self), "not an l-value (binop)");
1286         return false;
1287     }
1288
1289     if (self->expression.outr) {
1290         *out = self->expression.outr;
1291         return true;
1292     }
1293
1294     cgen = self->left->expression.codegen;
1295     /* lvalue! */
1296     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1297         return false;
1298
1299     cgen = self->right->expression.codegen;
1300     /* rvalue! */
1301     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1302         return false;
1303
1304     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
1305                                  self->op, left, right);
1306     if (!*out)
1307         return false;
1308     self->expression.outr = *out;
1309
1310     return true;
1311 }
1312
1313 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1314 {
1315     ast_expression_codegen *cgen;
1316     ir_value *leftl, *leftr, *right, *bin;
1317
1318     if (lvalue && self->expression.outl) {
1319         *out = self->expression.outl;
1320         return true;
1321     }
1322
1323     if (!lvalue && self->expression.outr) {
1324         *out = self->expression.outr;
1325         return true;
1326     }
1327
1328     /* for a binstore we need both an lvalue and an rvalue for the left side */
1329     /* rvalue of destination! */
1330     cgen = self->dest->expression.codegen;
1331     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
1332         return false;
1333
1334     /* source as rvalue only */
1335     cgen = self->source->expression.codegen;
1336     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1337         return false;
1338
1339     /* now the binary */
1340     bin = ir_block_create_binop(func->curblock, ast_function_label(func, "binst"),
1341                                 self->opbin, leftr, right);
1342     self->expression.outr = bin;
1343
1344     /* now store them */
1345     cgen = self->dest->expression.codegen;
1346     /* lvalue of destination */
1347     if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
1348         return false;
1349     self->expression.outl = leftl;
1350
1351     if (!ir_block_create_store_op(func->curblock, self->opstore, leftl, bin))
1352         return false;
1353     self->expression.outr = bin;
1354
1355     /* Theoretically, an assinment returns its left side as an
1356      * lvalue, if we don't need an lvalue though, we return
1357      * the right side as an rvalue, otherwise we have to
1358      * somehow know whether or not we need to dereference the pointer
1359      * on the left side - that is: OP_LOAD if it was an address.
1360      * Also: in original QC we cannot OP_LOADP *anyway*.
1361      */
1362     *out = (lvalue ? leftl : bin);
1363
1364     return true;
1365 }
1366
1367 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
1368 {
1369     ast_expression_codegen *cgen;
1370     ir_value *operand;
1371
1372     /* An unary operation cannot yield an l-value */
1373     if (lvalue) {
1374         asterror(ast_ctx(self), "not an l-value (binop)");
1375         return false;
1376     }
1377
1378     if (self->expression.outr) {
1379         *out = self->expression.outr;
1380         return true;
1381     }
1382
1383     cgen = self->operand->expression.codegen;
1384     /* lvalue! */
1385     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1386         return false;
1387
1388     *out = ir_block_create_unary(func->curblock, ast_function_label(func, "unary"),
1389                                  self->op, operand);
1390     if (!*out)
1391         return false;
1392     self->expression.outr = *out;
1393
1394     return true;
1395 }
1396
1397 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
1398 {
1399     ast_expression_codegen *cgen;
1400     ir_value *operand;
1401
1402     /* In the context of a return operation, we don't actually return
1403      * anything...
1404      */
1405     if (lvalue) {
1406         asterror(ast_ctx(self), "return-expression is not an l-value");
1407         return false;
1408     }
1409
1410     if (self->expression.outr) {
1411         asterror(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
1412         return false;
1413     }
1414     self->expression.outr = (ir_value*)1;
1415
1416     if (self->operand) {
1417         cgen = self->operand->expression.codegen;
1418         /* lvalue! */
1419         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1420             return false;
1421
1422         if (!ir_block_create_return(func->curblock, operand))
1423             return false;
1424     } else {
1425         if (!ir_block_create_return(func->curblock, NULL))
1426             return false;
1427     }
1428
1429     return true;
1430 }
1431
1432 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
1433 {
1434     ast_expression_codegen *cgen;
1435     ir_value *ent, *field;
1436
1437     /* This function needs to take the 'lvalue' flag into account!
1438      * As lvalue we provide a field-pointer, as rvalue we provide the
1439      * value in a temp.
1440      */
1441
1442     if (lvalue && self->expression.outl) {
1443         *out = self->expression.outl;
1444         return true;
1445     }
1446
1447     if (!lvalue && self->expression.outr) {
1448         *out = self->expression.outr;
1449         return true;
1450     }
1451
1452     cgen = self->entity->expression.codegen;
1453     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
1454         return false;
1455
1456     cgen = self->field->expression.codegen;
1457     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
1458         return false;
1459
1460     if (lvalue) {
1461         /* address! */
1462         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
1463                                             ent, field);
1464     } else {
1465         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
1466                                              ent, field, self->expression.vtype);
1467     }
1468     if (!*out) {
1469         asterror(ast_ctx(self), "failed to create %s instruction (output type %s)",
1470                  (lvalue ? "ADDRESS" : "FIELD"),
1471                  type_name[self->expression.vtype]);
1472         return false;
1473     }
1474
1475     if (lvalue)
1476         self->expression.outl = *out;
1477     else
1478         self->expression.outr = *out;
1479
1480     /* Hm that should be it... */
1481     return true;
1482 }
1483
1484 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
1485 {
1486     ast_expression_codegen *cgen;
1487     ir_value *vec;
1488
1489     /* in QC this is always an lvalue */
1490     (void)lvalue;
1491     if (self->expression.outl) {
1492         *out = self->expression.outl;
1493         return true;
1494     }
1495
1496     cgen = self->owner->expression.codegen;
1497     if (!(*cgen)((ast_expression*)(self->owner), func, true, &vec))
1498         return false;
1499
1500     if (vec->vtype != TYPE_VECTOR &&
1501         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
1502     {
1503         return false;
1504     }
1505
1506     *out = ir_value_vector_member(vec, self->field);
1507     self->expression.outl = *out;
1508
1509     return (*out != NULL);
1510 }
1511
1512 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
1513 {
1514     ast_value *arr;
1515     ast_value *idx;
1516
1517     if (!ast_istype(self->array, ast_value)) {
1518         asterror(ast_ctx(self), "array indexing this way is not supported");
1519         return false;
1520     }
1521
1522     if (!ast_istype(self->index, ast_value)) {
1523         if (lvalue) {
1524             asterror(ast_ctx(self), "array indexing here needs a compile-time constant");
1525             return false;
1526         } else {
1527             /* Time to use accessor functions */
1528             /*
1529             ast_expression_codegen *cgen;
1530             ir_value               *iridx;
1531             */
1532         }
1533     }
1534
1535     arr = (ast_value*)self->array;
1536     idx = (ast_value*)self->index;
1537
1538     if (!idx->isconst) {
1539         asterror(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
1540         return false;
1541     }
1542
1543     if (idx->expression.vtype == TYPE_FLOAT)
1544         *out = arr->ir_values[(int)idx->constval.vfloat];
1545     else if (idx->expression.vtype == TYPE_INTEGER)
1546         *out = arr->ir_values[idx->constval.vint];
1547     else {
1548         asterror(ast_ctx(self), "array indexing here needs an integer constant");
1549         return false;
1550     }
1551     return true;
1552 }
1553
1554 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
1555 {
1556     ast_expression_codegen *cgen;
1557
1558     ir_value *condval;
1559     ir_value *dummy;
1560
1561     ir_block *cond = func->curblock;
1562     ir_block *ontrue;
1563     ir_block *onfalse;
1564     ir_block *ontrue_endblock = NULL;
1565     ir_block *onfalse_endblock = NULL;
1566     ir_block *merge;
1567
1568     /* We don't output any value, thus also don't care about r/lvalue */
1569     (void)out;
1570     (void)lvalue;
1571
1572     if (self->expression.outr) {
1573         asterror(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
1574         return false;
1575     }
1576     self->expression.outr = (ir_value*)1;
1577
1578     /* generate the condition */
1579     func->curblock = cond;
1580     cgen = self->cond->expression.codegen;
1581     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1582         return false;
1583
1584     /* on-true path */
1585
1586     if (self->on_true) {
1587         /* create on-true block */
1588         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
1589         if (!ontrue)
1590             return false;
1591
1592         /* enter the block */
1593         func->curblock = ontrue;
1594
1595         /* generate */
1596         cgen = self->on_true->expression.codegen;
1597         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
1598             return false;
1599
1600         /* we now need to work from the current endpoint */
1601         ontrue_endblock = func->curblock;
1602     } else
1603         ontrue = NULL;
1604
1605     /* on-false path */
1606     if (self->on_false) {
1607         /* create on-false block */
1608         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
1609         if (!onfalse)
1610             return false;
1611
1612         /* enter the block */
1613         func->curblock = onfalse;
1614
1615         /* generate */
1616         cgen = self->on_false->expression.codegen;
1617         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
1618             return false;
1619
1620         /* we now need to work from the current endpoint */
1621         onfalse_endblock = func->curblock;
1622     } else
1623         onfalse = NULL;
1624
1625     /* Merge block were they all merge in to */
1626     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
1627     if (!merge)
1628         return false;
1629
1630     /* add jumps ot the merge block */
1631     if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, merge))
1632         return false;
1633     if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, merge))
1634         return false;
1635
1636     /* we create the if here, that way all blocks are ordered :)
1637      */
1638     if (!ir_block_create_if(cond, condval,
1639                             (ontrue  ? ontrue  : merge),
1640                             (onfalse ? onfalse : merge)))
1641     {
1642         return false;
1643     }
1644
1645     /* Now enter the merge block */
1646     func->curblock = merge;
1647
1648     return true;
1649 }
1650
1651 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
1652 {
1653     ast_expression_codegen *cgen;
1654
1655     ir_value *condval;
1656     ir_value *trueval, *falseval;
1657     ir_instr *phi;
1658
1659     ir_block *cond = func->curblock;
1660     ir_block *ontrue;
1661     ir_block *onfalse;
1662     ir_block *merge;
1663
1664     /* Ternary can never create an lvalue... */
1665     if (lvalue)
1666         return false;
1667
1668     /* In theory it shouldn't be possible to pass through a node twice, but
1669      * in case we add any kind of optimization pass for the AST itself, it
1670      * may still happen, thus we remember a created ir_value and simply return one
1671      * if it already exists.
1672      */
1673     if (self->phi_out) {
1674         *out = self->phi_out;
1675         return true;
1676     }
1677
1678     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
1679
1680     /* generate the condition */
1681     func->curblock = cond;
1682     cgen = self->cond->expression.codegen;
1683     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1684         return false;
1685
1686     /* create on-true block */
1687     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
1688     if (!ontrue)
1689         return false;
1690     else
1691     {
1692         /* enter the block */
1693         func->curblock = ontrue;
1694
1695         /* generate */
1696         cgen = self->on_true->expression.codegen;
1697         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
1698             return false;
1699     }
1700
1701     /* create on-false block */
1702     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
1703     if (!onfalse)
1704         return false;
1705     else
1706     {
1707         /* enter the block */
1708         func->curblock = onfalse;
1709
1710         /* generate */
1711         cgen = self->on_false->expression.codegen;
1712         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
1713             return false;
1714     }
1715
1716     /* create merge block */
1717     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
1718     if (!merge)
1719         return false;
1720     /* jump to merge block */
1721     if (!ir_block_create_jump(ontrue, merge))
1722         return false;
1723     if (!ir_block_create_jump(onfalse, merge))
1724         return false;
1725
1726     /* create if instruction */
1727     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
1728         return false;
1729
1730     /* Now enter the merge block */
1731     func->curblock = merge;
1732
1733     /* Here, now, we need a PHI node
1734      * but first some sanity checking...
1735      */
1736     if (trueval->vtype != falseval->vtype) {
1737         /* error("ternary with different types on the two sides"); */
1738         return false;
1739     }
1740
1741     /* create PHI */
1742     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
1743     if (!phi ||
1744         !ir_phi_add(phi, ontrue,  trueval) ||
1745         !ir_phi_add(phi, onfalse, falseval))
1746     {
1747         return false;
1748     }
1749
1750     self->phi_out = ir_phi_value(phi);
1751     *out = self->phi_out;
1752
1753     return true;
1754 }
1755
1756 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
1757 {
1758     ast_expression_codegen *cgen;
1759
1760     ir_value *dummy      = NULL;
1761     ir_value *precond    = NULL;
1762     ir_value *postcond   = NULL;
1763
1764     /* Since we insert some jumps "late" so we have blocks
1765      * ordered "nicely", we need to keep track of the actual end-blocks
1766      * of expressions to add the jumps to.
1767      */
1768     ir_block *bbody      = NULL, *end_bbody      = NULL;
1769     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
1770     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
1771     ir_block *bincrement = NULL, *end_bincrement = NULL;
1772     ir_block *bout       = NULL, *bin            = NULL;
1773
1774     /* let's at least move the outgoing block to the end */
1775     size_t    bout_id;
1776
1777     /* 'break' and 'continue' need to be able to find the right blocks */
1778     ir_block *bcontinue     = NULL;
1779     ir_block *bbreak        = NULL;
1780
1781     ir_block *old_bcontinue = NULL;
1782     ir_block *old_bbreak    = NULL;
1783
1784     ir_block *tmpblock      = NULL;
1785
1786     (void)lvalue;
1787     (void)out;
1788
1789     if (self->expression.outr) {
1790         asterror(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
1791         return false;
1792     }
1793     self->expression.outr = (ir_value*)1;
1794
1795     /* NOTE:
1796      * Should we ever need some kind of block ordering, better make this function
1797      * move blocks around than write a block ordering algorithm later... after all
1798      * the ast and ir should work together, not against each other.
1799      */
1800
1801     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
1802      * anyway if for example it contains a ternary.
1803      */
1804     if (self->initexpr)
1805     {
1806         cgen = self->initexpr->expression.codegen;
1807         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
1808             return false;
1809     }
1810
1811     /* Store the block from which we enter this chaos */
1812     bin = func->curblock;
1813
1814     /* The pre-loop condition needs its own block since we
1815      * need to be able to jump to the start of that expression.
1816      */
1817     if (self->precond)
1818     {
1819         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
1820         if (!bprecond)
1821             return false;
1822
1823         /* the pre-loop-condition the least important place to 'continue' at */
1824         bcontinue = bprecond;
1825
1826         /* enter */
1827         func->curblock = bprecond;
1828
1829         /* generate */
1830         cgen = self->precond->expression.codegen;
1831         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
1832             return false;
1833
1834         end_bprecond = func->curblock;
1835     } else {
1836         bprecond = end_bprecond = NULL;
1837     }
1838
1839     /* Now the next blocks won't be ordered nicely, but we need to
1840      * generate them this early for 'break' and 'continue'.
1841      */
1842     if (self->increment) {
1843         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
1844         if (!bincrement)
1845             return false;
1846         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
1847     } else {
1848         bincrement = end_bincrement = NULL;
1849     }
1850
1851     if (self->postcond) {
1852         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
1853         if (!bpostcond)
1854             return false;
1855         bcontinue = bpostcond; /* postcond comes before the increment */
1856     } else {
1857         bpostcond = end_bpostcond = NULL;
1858     }
1859
1860     bout_id = func->ir_func->blocks_count;
1861     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
1862     if (!bout)
1863         return false;
1864     bbreak = bout;
1865
1866     /* The loop body... */
1867     if (self->body)
1868     {
1869         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
1870         if (!bbody)
1871             return false;
1872
1873         /* enter */
1874         func->curblock = bbody;
1875
1876         old_bbreak          = func->breakblock;
1877         old_bcontinue       = func->continueblock;
1878         func->breakblock    = bbreak;
1879         func->continueblock = bcontinue;
1880
1881         /* generate */
1882         cgen = self->body->expression.codegen;
1883         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
1884             return false;
1885
1886         end_bbody = func->curblock;
1887         func->breakblock    = old_bbreak;
1888         func->continueblock = old_bcontinue;
1889     }
1890
1891     /* post-loop-condition */
1892     if (self->postcond)
1893     {
1894         /* enter */
1895         func->curblock = bpostcond;
1896
1897         /* generate */
1898         cgen = self->postcond->expression.codegen;
1899         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
1900             return false;
1901
1902         end_bpostcond = func->curblock;
1903     }
1904
1905     /* The incrementor */
1906     if (self->increment)
1907     {
1908         /* enter */
1909         func->curblock = bincrement;
1910
1911         /* generate */
1912         cgen = self->increment->expression.codegen;
1913         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
1914             return false;
1915
1916         end_bincrement = func->curblock;
1917     }
1918
1919     /* In any case now, we continue from the outgoing block */
1920     func->curblock = bout;
1921
1922     /* Now all blocks are in place */
1923     /* From 'bin' we jump to whatever comes first */
1924     if      (bprecond)   tmpblock = bprecond;
1925     else if (bbody)      tmpblock = bbody;
1926     else if (bpostcond)  tmpblock = bpostcond;
1927     else                 tmpblock = bout;
1928     if (!ir_block_create_jump(bin, tmpblock))
1929         return false;
1930
1931     /* From precond */
1932     if (bprecond)
1933     {
1934         ir_block *ontrue, *onfalse;
1935         if      (bbody)      ontrue = bbody;
1936         else if (bincrement) ontrue = bincrement;
1937         else if (bpostcond)  ontrue = bpostcond;
1938         else                 ontrue = bprecond;
1939         onfalse = bout;
1940         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
1941             return false;
1942     }
1943
1944     /* from body */
1945     if (bbody)
1946     {
1947         if      (bincrement) tmpblock = bincrement;
1948         else if (bpostcond)  tmpblock = bpostcond;
1949         else if (bprecond)   tmpblock = bprecond;
1950         else                 tmpblock = bout;
1951         if (!end_bbody->final && !ir_block_create_jump(end_bbody, tmpblock))
1952             return false;
1953     }
1954
1955     /* from increment */
1956     if (bincrement)
1957     {
1958         if      (bpostcond)  tmpblock = bpostcond;
1959         else if (bprecond)   tmpblock = bprecond;
1960         else if (bbody)      tmpblock = bbody;
1961         else                 tmpblock = bout;
1962         if (!ir_block_create_jump(end_bincrement, tmpblock))
1963             return false;
1964     }
1965
1966     /* from postcond */
1967     if (bpostcond)
1968     {
1969         ir_block *ontrue, *onfalse;
1970         if      (bprecond)   ontrue = bprecond;
1971         else if (bbody)      ontrue = bbody;
1972         else if (bincrement) ontrue = bincrement;
1973         else                 ontrue = bpostcond;
1974         onfalse = bout;
1975         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
1976             return false;
1977     }
1978
1979     /* Move 'bout' to the end */
1980     if (!ir_function_blocks_remove(func->ir_func, bout_id) ||
1981         !ir_function_blocks_add(func->ir_func, bout))
1982     {
1983         ir_block_delete(bout);
1984         return false;
1985     }
1986
1987     return true;
1988 }
1989
1990 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
1991 {
1992     ast_expression_codegen *cgen;
1993     ir_value_vector         params;
1994     ir_instr               *callinstr;
1995     size_t i;
1996
1997     ir_value *funval = NULL;
1998
1999     /* return values are never lvalues */
2000     if (lvalue) {
2001         asterror(ast_ctx(self), "not an l-value (function call)");
2002         return false;
2003     }
2004
2005     if (self->expression.outr) {
2006         *out = self->expression.outr;
2007         return true;
2008     }
2009
2010     cgen = self->func->expression.codegen;
2011     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
2012         return false;
2013     if (!funval)
2014         return false;
2015
2016     MEM_VECTOR_INIT(&params, v);
2017
2018     /* parameters */
2019     for (i = 0; i < self->params_count; ++i)
2020     {
2021         ir_value *param;
2022         ast_expression *expr = self->params[i];
2023
2024         cgen = expr->expression.codegen;
2025         if (!(*cgen)(expr, func, false, &param))
2026             goto error;
2027         if (!param)
2028             goto error;
2029         if (!ir_value_vector_v_add(&params, param))
2030             goto error;
2031     }
2032
2033     callinstr = ir_block_create_call(func->curblock, ast_function_label(func, "call"), funval);
2034     if (!callinstr)
2035         goto error;
2036
2037     for (i = 0; i < params.v_count; ++i) {
2038         if (!ir_call_param(callinstr, params.v[i]))
2039             goto error;
2040     }
2041
2042     *out = ir_call_value(callinstr);
2043     self->expression.outr = *out;
2044
2045     MEM_VECTOR_CLEAR(&params, v);
2046     return true;
2047 error:
2048     MEM_VECTOR_CLEAR(&params, v);
2049     return false;
2050 }