2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 #define ast_instantiate(T, ctx, destroyfn) \
32 T* self = (T*)mem_a(sizeof(T)); \
36 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
37 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
40 * forward declarations, these need not be in ast.h for obvious
43 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
44 static void ast_array_index_delete(ast_array_index*);
45 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
46 static void ast_argpipe_delete(ast_argpipe*);
47 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
48 static void ast_store_delete(ast_store*);
49 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
50 static void ast_ifthen_delete(ast_ifthen*);
51 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
52 static void ast_ternary_delete(ast_ternary*);
53 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
54 static void ast_loop_delete(ast_loop*);
55 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
56 static void ast_breakcont_delete(ast_breakcont*);
57 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
58 static void ast_switch_delete(ast_switch*);
59 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
60 static void ast_label_delete(ast_label*);
61 static void ast_label_register_goto(ast_label*, ast_goto*);
62 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
63 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
64 static void ast_goto_delete(ast_goto*);
65 static void ast_call_delete(ast_call*);
66 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
67 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
68 static void ast_unary_delete(ast_unary*);
69 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
70 static void ast_entfield_delete(ast_entfield*);
71 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
72 static void ast_return_delete(ast_return*);
73 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
74 static void ast_binstore_delete(ast_binstore*);
75 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
76 static void ast_binary_delete(ast_binary*);
77 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
79 /* It must not be possible to get here. */
80 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
83 con_err("ast node missing destroy()\n");
87 /* Initialize main ast node aprts */
88 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
91 self->destroy = &_ast_node_destroy;
93 self->nodetype = nodetype;
94 self->side_effects = false;
97 /* weight and side effects */
98 static void _ast_propagate_effects(ast_node *self, ast_node *other)
100 if (ast_side_effects(other))
101 ast_side_effects(self) = true;
103 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
105 /* General expression initialization */
106 static void ast_expression_init(ast_expression *self,
107 ast_expression_codegen *codegen)
109 self->codegen = codegen;
110 self->vtype = TYPE_VOID;
117 self->varparam = NULL;
120 static void ast_expression_delete(ast_expression *self)
124 ast_delete(self->next);
125 for (i = 0; i < vec_size(self->params); ++i) {
126 ast_delete(self->params[i]);
128 vec_free(self->params);
130 ast_delete(self->varparam);
133 static void ast_expression_delete_full(ast_expression *self)
135 ast_expression_delete(self);
139 ast_value* ast_value_copy(const ast_value *self)
142 const ast_expression *fromex;
143 ast_expression *selfex;
144 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
145 if (self->expression.next) {
146 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
148 fromex = &self->expression;
149 selfex = &cp->expression;
150 selfex->count = fromex->count;
151 selfex->flags = fromex->flags;
152 for (i = 0; i < vec_size(fromex->params); ++i) {
153 ast_value *v = ast_value_copy(fromex->params[i]);
154 vec_push(selfex->params, v);
159 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
162 const ast_expression *fromex;
163 ast_expression *selfex;
164 self->vtype = other->vtype;
166 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
170 selfex->count = fromex->count;
171 selfex->flags = fromex->flags;
172 for (i = 0; i < vec_size(fromex->params); ++i) {
173 ast_value *v = ast_value_copy(fromex->params[i]);
174 vec_push(selfex->params, v);
178 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
180 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
181 ast_expression_init(self, NULL);
182 self->codegen = NULL;
188 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
191 const ast_expression *fromex;
192 ast_expression *selfex;
198 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
199 ast_expression_init(self, NULL);
204 /* This may never be codegen()d */
205 selfex->codegen = NULL;
207 selfex->vtype = fromex->vtype;
209 selfex->next = ast_type_copy(ctx, fromex->next);
213 selfex->count = fromex->count;
214 selfex->flags = fromex->flags;
215 for (i = 0; i < vec_size(fromex->params); ++i) {
216 ast_value *v = ast_value_copy(fromex->params[i]);
217 vec_push(selfex->params, v);
224 bool ast_compare_type(ast_expression *a, ast_expression *b)
226 if (a->vtype == TYPE_NIL ||
227 b->vtype == TYPE_NIL)
229 if (a->vtype != b->vtype)
231 if (!a->next != !b->next)
233 if (vec_size(a->params) != vec_size(b->params))
235 if ((a->flags & AST_FLAG_TYPE_MASK) !=
236 (b->flags & AST_FLAG_TYPE_MASK) )
240 if (vec_size(a->params)) {
242 for (i = 0; i < vec_size(a->params); ++i) {
243 if (!ast_compare_type((ast_expression*)a->params[i],
244 (ast_expression*)b->params[i]))
249 return ast_compare_type(a->next, b->next);
253 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
260 if (pos + 6 >= bufsize)
262 util_strncpy(buf + pos, "(null)", 6);
266 if (pos + 1 >= bufsize)
271 util_strncpy(buf + pos, "(variant)", 9);
276 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
279 if (pos + 3 >= bufsize)
283 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
284 if (pos + 1 >= bufsize)
290 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
291 if (pos + 2 >= bufsize)
293 if (!vec_size(e->params)) {
299 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
300 for (i = 1; i < vec_size(e->params); ++i) {
301 if (pos + 2 >= bufsize)
305 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
307 if (pos + 1 >= bufsize)
313 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
314 if (pos + 1 >= bufsize)
317 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
318 if (pos + 1 >= bufsize)
324 typestr = type_name[e->vtype];
325 typelen = strlen(typestr);
326 if (pos + typelen >= bufsize)
328 util_strncpy(buf + pos, typestr, typelen);
329 return pos + typelen;
333 buf[bufsize-3] = '.';
334 buf[bufsize-2] = '.';
335 buf[bufsize-1] = '.';
339 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
341 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
345 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
346 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
348 ast_instantiate(ast_value, ctx, ast_value_delete);
349 ast_expression_init((ast_expression*)self,
350 (ast_expression_codegen*)&ast_value_codegen);
351 self->expression.node.keep = true; /* keep */
353 self->name = name ? util_strdup(name) : NULL;
354 self->expression.vtype = t;
355 self->expression.next = NULL;
356 self->isfield = false;
358 self->hasvalue = false;
361 memset(&self->constval, 0, sizeof(self->constval));
362 self->initlist = NULL;
365 self->ir_values = NULL;
366 self->ir_value_count = 0;
372 self->argcounter = NULL;
373 self->intrinsic = false;
378 void ast_value_delete(ast_value* self)
381 mem_d((void*)self->name);
382 if (self->argcounter)
383 mem_d((void*)self->argcounter);
384 if (self->hasvalue) {
385 switch (self->expression.vtype)
388 mem_d((void*)self->constval.vstring);
391 /* unlink us from the function node */
392 self->constval.vfunc->vtype = NULL;
394 /* NOTE: delete function? currently collected in
395 * the parser structure
402 mem_d(self->ir_values);
407 if (self->initlist) {
408 if (self->expression.next->vtype == TYPE_STRING) {
409 /* strings are allocated, free them */
410 size_t i, len = vec_size(self->initlist);
411 /* in theory, len should be expression.count
412 * but let's not take any chances */
413 for (i = 0; i < len; ++i) {
414 if (self->initlist[i].vstring)
415 mem_d(self->initlist[i].vstring);
418 vec_free(self->initlist);
421 ast_expression_delete((ast_expression*)self);
425 void ast_value_params_add(ast_value *self, ast_value *p)
427 vec_push(self->expression.params, p);
430 bool ast_value_set_name(ast_value *self, const char *name)
433 mem_d((void*)self->name);
434 self->name = util_strdup(name);
438 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
439 ast_expression* left, ast_expression* right)
441 ast_instantiate(ast_binary, ctx, ast_binary_delete);
442 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
447 self->right_first = false;
449 ast_propagate_effects(self, left);
450 ast_propagate_effects(self, right);
452 if (op >= INSTR_EQ_F && op <= INSTR_GT)
453 self->expression.vtype = TYPE_FLOAT;
454 else if (op == INSTR_AND || op == INSTR_OR) {
455 if (OPTS_FLAG(PERL_LOGIC))
456 ast_type_adopt(self, right);
458 self->expression.vtype = TYPE_FLOAT;
460 else if (op == INSTR_BITAND || op == INSTR_BITOR)
461 self->expression.vtype = TYPE_FLOAT;
462 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
463 self->expression.vtype = TYPE_VECTOR;
464 else if (op == INSTR_MUL_V)
465 self->expression.vtype = TYPE_FLOAT;
467 self->expression.vtype = left->vtype;
470 self->refs = AST_REF_ALL;
475 void ast_binary_delete(ast_binary *self)
477 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
478 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
480 ast_expression_delete((ast_expression*)self);
484 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
485 ast_expression* left, ast_expression* right)
487 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
488 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
490 ast_side_effects(self) = true;
492 self->opstore = storop;
495 self->source = right;
497 self->keep_dest = false;
499 ast_type_adopt(self, left);
503 void ast_binstore_delete(ast_binstore *self)
505 if (!self->keep_dest)
506 ast_unref(self->dest);
507 ast_unref(self->source);
508 ast_expression_delete((ast_expression*)self);
512 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
513 ast_expression *expr)
515 ast_instantiate(ast_unary, ctx, ast_unary_delete);
516 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
519 self->operand = expr;
521 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
522 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
523 if (ast_istype(prev, ast_unary)) {
524 ast_expression_delete((ast_expression*)self);
526 ++opts_optimizationcount[OPTIM_PEEPHOLE];
531 ast_propagate_effects(self, expr);
533 if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
534 self->expression.vtype = TYPE_FLOAT;
535 } else if (op >= VINSTR_NEG_F && op <= VINSTR_NEG_V) {
536 self->expression.vtype = TYPE_FLOAT;
538 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
544 void ast_unary_delete(ast_unary *self)
546 if (self->operand) ast_unref(self->operand);
547 ast_expression_delete((ast_expression*)self);
551 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
553 ast_instantiate(ast_return, ctx, ast_return_delete);
554 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
556 self->operand = expr;
559 ast_propagate_effects(self, expr);
564 void ast_return_delete(ast_return *self)
567 ast_unref(self->operand);
568 ast_expression_delete((ast_expression*)self);
572 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
574 if (field->vtype != TYPE_FIELD) {
575 compile_error(ctx, "ast_entfield_new with expression not of type field");
578 return ast_entfield_new_force(ctx, entity, field, field->next);
581 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
583 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
587 /* Error: field has no type... */
591 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
593 self->entity = entity;
595 ast_propagate_effects(self, entity);
596 ast_propagate_effects(self, field);
598 ast_type_adopt(self, outtype);
602 void ast_entfield_delete(ast_entfield *self)
604 ast_unref(self->entity);
605 ast_unref(self->field);
606 ast_expression_delete((ast_expression*)self);
610 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
612 ast_instantiate(ast_member, ctx, ast_member_delete);
618 if (owner->vtype != TYPE_VECTOR &&
619 owner->vtype != TYPE_FIELD) {
620 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
625 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
626 self->expression.node.keep = true; /* keep */
628 if (owner->vtype == TYPE_VECTOR) {
629 self->expression.vtype = TYPE_FLOAT;
630 self->expression.next = NULL;
632 self->expression.vtype = TYPE_FIELD;
633 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
636 self->rvalue = false;
638 ast_propagate_effects(self, owner);
642 self->name = util_strdup(name);
649 void ast_member_delete(ast_member *self)
651 /* The owner is always an ast_value, which has .keep=true,
652 * also: ast_members are usually deleted after the owner, thus
653 * this will cause invalid access
654 ast_unref(self->owner);
655 * once we allow (expression).x to access a vector-member, we need
656 * to change this: preferably by creating an alternate ast node for this
657 * purpose that is not garbage-collected.
659 ast_expression_delete((ast_expression*)self);
664 bool ast_member_set_name(ast_member *self, const char *name)
667 mem_d((void*)self->name);
668 self->name = util_strdup(name);
672 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
674 ast_expression *outtype;
675 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
677 outtype = array->next;
680 /* Error: field has no type... */
684 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
688 ast_propagate_effects(self, array);
689 ast_propagate_effects(self, index);
691 ast_type_adopt(self, outtype);
692 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
693 if (self->expression.vtype != TYPE_ARRAY) {
694 compile_error(ast_ctx(self), "array_index node on type");
695 ast_array_index_delete(self);
698 self->array = outtype;
699 self->expression.vtype = TYPE_FIELD;
705 void ast_array_index_delete(ast_array_index *self)
708 ast_unref(self->array);
710 ast_unref(self->index);
711 ast_expression_delete((ast_expression*)self);
715 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
717 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
718 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
720 self->expression.vtype = TYPE_NOEXPR;
724 void ast_argpipe_delete(ast_argpipe *self)
727 ast_unref(self->index);
728 ast_expression_delete((ast_expression*)self);
732 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
734 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
735 if (!ontrue && !onfalse) {
736 /* because it is invalid */
740 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
743 self->on_true = ontrue;
744 self->on_false = onfalse;
745 ast_propagate_effects(self, cond);
747 ast_propagate_effects(self, ontrue);
749 ast_propagate_effects(self, onfalse);
754 void ast_ifthen_delete(ast_ifthen *self)
756 ast_unref(self->cond);
758 ast_unref(self->on_true);
760 ast_unref(self->on_false);
761 ast_expression_delete((ast_expression*)self);
765 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
767 ast_expression *exprtype = ontrue;
768 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
769 /* This time NEITHER must be NULL */
770 if (!ontrue || !onfalse) {
774 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
777 self->on_true = ontrue;
778 self->on_false = onfalse;
779 ast_propagate_effects(self, cond);
780 ast_propagate_effects(self, ontrue);
781 ast_propagate_effects(self, onfalse);
783 if (ontrue->vtype == TYPE_NIL)
785 ast_type_adopt(self, exprtype);
790 void ast_ternary_delete(ast_ternary *self)
792 /* the if()s are only there because computed-gotos can set them
795 if (self->cond) ast_unref(self->cond);
796 if (self->on_true) ast_unref(self->on_true);
797 if (self->on_false) ast_unref(self->on_false);
798 ast_expression_delete((ast_expression*)self);
802 ast_loop* ast_loop_new(lex_ctx_t ctx,
803 ast_expression *initexpr,
804 ast_expression *precond, bool pre_not,
805 ast_expression *postcond, bool post_not,
806 ast_expression *increment,
807 ast_expression *body)
809 ast_instantiate(ast_loop, ctx, ast_loop_delete);
810 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
812 self->initexpr = initexpr;
813 self->precond = precond;
814 self->postcond = postcond;
815 self->increment = increment;
818 self->pre_not = pre_not;
819 self->post_not = post_not;
822 ast_propagate_effects(self, initexpr);
824 ast_propagate_effects(self, precond);
826 ast_propagate_effects(self, postcond);
828 ast_propagate_effects(self, increment);
830 ast_propagate_effects(self, body);
835 void ast_loop_delete(ast_loop *self)
838 ast_unref(self->initexpr);
840 ast_unref(self->precond);
842 ast_unref(self->postcond);
844 ast_unref(self->increment);
846 ast_unref(self->body);
847 ast_expression_delete((ast_expression*)self);
851 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
853 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
854 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
856 self->is_continue = iscont;
857 self->levels = levels;
862 void ast_breakcont_delete(ast_breakcont *self)
864 ast_expression_delete((ast_expression*)self);
868 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
870 ast_instantiate(ast_switch, ctx, ast_switch_delete);
871 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
876 ast_propagate_effects(self, op);
881 void ast_switch_delete(ast_switch *self)
884 ast_unref(self->operand);
886 for (i = 0; i < vec_size(self->cases); ++i) {
887 if (self->cases[i].value)
888 ast_unref(self->cases[i].value);
889 ast_unref(self->cases[i].code);
891 vec_free(self->cases);
893 ast_expression_delete((ast_expression*)self);
897 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
899 ast_instantiate(ast_label, ctx, ast_label_delete);
900 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
902 self->expression.vtype = TYPE_NOEXPR;
904 self->name = util_strdup(name);
905 self->irblock = NULL;
907 self->undefined = undefined;
912 void ast_label_delete(ast_label *self)
914 mem_d((void*)self->name);
915 vec_free(self->gotos);
916 ast_expression_delete((ast_expression*)self);
920 static void ast_label_register_goto(ast_label *self, ast_goto *g)
922 vec_push(self->gotos, g);
925 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
927 ast_instantiate(ast_goto, ctx, ast_goto_delete);
928 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
930 self->name = util_strdup(name);
932 self->irblock_from = NULL;
937 void ast_goto_delete(ast_goto *self)
939 mem_d((void*)self->name);
940 ast_expression_delete((ast_expression*)self);
944 void ast_goto_set_label(ast_goto *self, ast_label *label)
946 self->target = label;
949 ast_call* ast_call_new(lex_ctx_t ctx,
950 ast_expression *funcexpr)
952 ast_instantiate(ast_call, ctx, ast_call_delete);
953 if (!funcexpr->next) {
954 compile_error(ctx, "not a function");
958 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
960 ast_side_effects(self) = true;
963 self->func = funcexpr;
964 self->va_count = NULL;
966 ast_type_adopt(self, funcexpr->next);
971 void ast_call_delete(ast_call *self)
974 for (i = 0; i < vec_size(self->params); ++i)
975 ast_unref(self->params[i]);
976 vec_free(self->params);
979 ast_unref(self->func);
982 ast_unref(self->va_count);
984 ast_expression_delete((ast_expression*)self);
988 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
994 if (!va_type || !ast_compare_type(va_type, exp_type))
996 if (va_type && exp_type)
998 ast_type_to_string(va_type, tgot, sizeof(tgot));
999 ast_type_to_string(exp_type, texp, sizeof(texp));
1000 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1001 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1002 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1006 compile_error(ast_ctx(self),
1007 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1014 ast_type_to_string(exp_type, texp, sizeof(texp));
1015 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1016 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1017 "piped variadic argument may differ in type: expected type %s",
1021 compile_error(ast_ctx(self),
1022 "piped variadic argument may differ in type: expected type %s",
1031 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1037 const ast_expression *func = self->func;
1038 size_t count = vec_size(self->params);
1039 if (count > vec_size(func->params))
1040 count = vec_size(func->params);
1042 for (i = 0; i < count; ++i) {
1043 if (ast_istype(self->params[i], ast_argpipe)) {
1044 /* warn about type safety instead */
1046 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1049 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1052 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1054 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1055 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1056 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1057 (unsigned int)(i+1), texp, tgot);
1058 /* we don't immediately return */
1062 count = vec_size(self->params);
1063 if (count > vec_size(func->params) && func->varparam) {
1064 for (; i < count; ++i) {
1065 if (ast_istype(self->params[i], ast_argpipe)) {
1066 /* warn about type safety instead */
1068 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1071 if (!ast_call_check_vararg(self, va_type, func->varparam))
1074 else if (!ast_compare_type(self->params[i], func->varparam))
1076 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1077 ast_type_to_string(func->varparam, texp, sizeof(texp));
1078 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1079 (unsigned int)(i+1), texp, tgot);
1080 /* we don't immediately return */
1088 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1089 ast_expression *dest, ast_expression *source)
1091 ast_instantiate(ast_store, ctx, ast_store_delete);
1092 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1094 ast_side_effects(self) = true;
1098 self->source = source;
1100 ast_type_adopt(self, dest);
1105 void ast_store_delete(ast_store *self)
1107 ast_unref(self->dest);
1108 ast_unref(self->source);
1109 ast_expression_delete((ast_expression*)self);
1113 ast_block* ast_block_new(lex_ctx_t ctx)
1115 ast_instantiate(ast_block, ctx, ast_block_delete);
1116 ast_expression_init((ast_expression*)self,
1117 (ast_expression_codegen*)&ast_block_codegen);
1119 self->locals = NULL;
1121 self->collect = NULL;
1126 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1128 ast_propagate_effects(self, e);
1129 vec_push(self->exprs, e);
1130 if (self->expression.next) {
1131 ast_delete(self->expression.next);
1132 self->expression.next = NULL;
1134 ast_type_adopt(self, e);
1138 void ast_block_collect(ast_block *self, ast_expression *expr)
1140 vec_push(self->collect, expr);
1141 expr->node.keep = true;
1144 void ast_block_delete(ast_block *self)
1147 for (i = 0; i < vec_size(self->exprs); ++i)
1148 ast_unref(self->exprs[i]);
1149 vec_free(self->exprs);
1150 for (i = 0; i < vec_size(self->locals); ++i)
1151 ast_delete(self->locals[i]);
1152 vec_free(self->locals);
1153 for (i = 0; i < vec_size(self->collect); ++i)
1154 ast_delete(self->collect[i]);
1155 vec_free(self->collect);
1156 ast_expression_delete((ast_expression*)self);
1160 void ast_block_set_type(ast_block *self, ast_expression *from)
1162 if (self->expression.next)
1163 ast_delete(self->expression.next);
1164 ast_type_adopt(self, from);
1167 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1169 ast_instantiate(ast_function, ctx, ast_function_delete);
1172 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1174 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1175 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1177 (int)vtype->hasvalue,
1178 vtype->expression.vtype);
1182 self->vtype = vtype;
1183 self->name = name ? util_strdup(name) : NULL;
1184 self->blocks = NULL;
1186 self->labelcount = 0;
1189 self->ir_func = NULL;
1190 self->curblock = NULL;
1192 self->breakblocks = NULL;
1193 self->continueblocks = NULL;
1195 vtype->hasvalue = true;
1196 vtype->constval.vfunc = self;
1198 self->varargs = NULL;
1200 self->fixedparams = NULL;
1201 self->return_value = NULL;
1210 void ast_function_delete(ast_function *self)
1214 mem_d((void*)self->name);
1216 /* ast_value_delete(self->vtype); */
1217 self->vtype->hasvalue = false;
1218 self->vtype->constval.vfunc = NULL;
1219 /* We use unref - if it was stored in a global table it is supposed
1220 * to be deleted from *there*
1222 ast_unref(self->vtype);
1224 for (i = 0; i < vec_size(self->blocks); ++i)
1225 ast_delete(self->blocks[i]);
1226 vec_free(self->blocks);
1227 vec_free(self->breakblocks);
1228 vec_free(self->continueblocks);
1230 ast_delete(self->varargs);
1232 ast_delete(self->argc);
1233 if (self->fixedparams)
1234 ast_unref(self->fixedparams);
1235 if (self->return_value)
1236 ast_unref(self->return_value);
1240 const char* ast_function_label(ast_function *self, const char *prefix)
1246 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1247 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1248 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1253 id = (self->labelcount++);
1254 len = strlen(prefix);
1256 from = self->labelbuf + sizeof(self->labelbuf)-1;
1259 *from-- = (id%10) + '0';
1263 memcpy(from - len, prefix, len);
1267 /*********************************************************************/
1269 * by convention you must never pass NULL to the 'ir_value **out'
1270 * parameter. If you really don't care about the output, pass a dummy.
1271 * But I can't imagine a pituation where the output is truly unnecessary.
1274 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1276 if (out->vtype == TYPE_FIELD)
1277 out->fieldtype = self->next->vtype;
1278 if (out->vtype == TYPE_FUNCTION)
1279 out->outtype = self->next->vtype;
1282 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1284 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1288 if (self->expression.vtype == TYPE_NIL) {
1289 *out = func->ir_func->owner->nil;
1292 /* NOTE: This is the codegen for a variable used in an expression.
1293 * It is not the codegen to generate the value. For this purpose,
1294 * ast_local_codegen and ast_global_codegen are to be used before this
1295 * is executed. ast_function_codegen should take care of its locals,
1296 * and the ast-user should take care of ast_global_codegen to be used
1297 * on all the globals.
1300 char tname[1024]; /* typename is reserved in C++ */
1301 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1302 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1309 static bool ast_global_array_set(ast_value *self)
1311 size_t count = vec_size(self->initlist);
1314 if (count > self->expression.count) {
1315 compile_error(ast_ctx(self), "too many elements in initializer");
1316 count = self->expression.count;
1318 else if (count < self->expression.count) {
1320 compile_warning(ast_ctx(self), "not all elements are initialized");
1324 for (i = 0; i != count; ++i) {
1325 switch (self->expression.next->vtype) {
1327 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1331 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1335 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1339 /* we don't support them in any other place yet either */
1340 compile_error(ast_ctx(self), "TODO: nested arrays");
1343 /* this requiers a bit more work - similar to the fields I suppose */
1344 compile_error(ast_ctx(self), "global of type function not properly generated");
1347 if (!self->initlist[i].vfield) {
1348 compile_error(ast_ctx(self), "field constant without vfield set");
1351 if (!self->initlist[i].vfield->ir_v) {
1352 compile_error(ast_ctx(self), "field constant generated before its field");
1355 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1359 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1366 static bool check_array(ast_value *self, ast_value *array)
1368 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1369 compile_error(ast_ctx(self), "array without size: %s", self->name);
1372 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1373 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1374 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1380 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1384 if (self->expression.vtype == TYPE_NIL) {
1385 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1389 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1391 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1394 func->context = ast_ctx(self);
1395 func->value->context = ast_ctx(self);
1397 self->constval.vfunc->ir_func = func;
1398 self->ir_v = func->value;
1399 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1400 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1401 if (self->expression.flags & AST_FLAG_ERASEABLE)
1402 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1403 /* The function is filled later on ast_function_codegen... */
1407 if (isfield && self->expression.vtype == TYPE_FIELD) {
1408 ast_expression *fieldtype = self->expression.next;
1410 if (self->hasvalue) {
1411 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1415 if (fieldtype->vtype == TYPE_ARRAY) {
1420 ast_expression *elemtype;
1422 ast_value *array = (ast_value*)fieldtype;
1424 if (!ast_istype(fieldtype, ast_value)) {
1425 compile_error(ast_ctx(self), "internal error: ast_value required");
1429 if (!check_array(self, array))
1432 elemtype = array->expression.next;
1433 vtype = elemtype->vtype;
1435 v = ir_builder_create_field(ir, self->name, vtype);
1437 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1440 v->context = ast_ctx(self);
1441 v->unique_life = true;
1443 array->ir_v = self->ir_v = v;
1445 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1446 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1447 if (self->expression.flags & AST_FLAG_ERASEABLE)
1448 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1450 namelen = strlen(self->name);
1451 name = (char*)mem_a(namelen + 16);
1452 util_strncpy(name, self->name, namelen);
1454 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1455 array->ir_values[0] = v;
1456 for (ai = 1; ai < array->expression.count; ++ai) {
1457 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1458 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1459 if (!array->ir_values[ai]) {
1461 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1464 array->ir_values[ai]->context = ast_ctx(self);
1465 array->ir_values[ai]->unique_life = true;
1466 array->ir_values[ai]->locked = true;
1467 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1468 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1474 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1477 v->context = ast_ctx(self);
1479 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1480 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1482 if (self->expression.flags & AST_FLAG_ERASEABLE)
1483 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1488 if (self->expression.vtype == TYPE_ARRAY) {
1493 ast_expression *elemtype = self->expression.next;
1494 int vtype = elemtype->vtype;
1496 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1497 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1501 /* same as with field arrays */
1502 if (!check_array(self, self))
1505 v = ir_builder_create_global(ir, self->name, vtype);
1507 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1510 v->context = ast_ctx(self);
1511 v->unique_life = true;
1514 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1515 v->flags |= IR_FLAG_INCLUDE_DEF;
1516 if (self->expression.flags & AST_FLAG_ERASEABLE)
1517 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1519 namelen = strlen(self->name);
1520 name = (char*)mem_a(namelen + 16);
1521 util_strncpy(name, self->name, namelen);
1523 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1524 self->ir_values[0] = v;
1525 for (ai = 1; ai < self->expression.count; ++ai) {
1526 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1527 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1528 if (!self->ir_values[ai]) {
1530 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1533 self->ir_values[ai]->context = ast_ctx(self);
1534 self->ir_values[ai]->unique_life = true;
1535 self->ir_values[ai]->locked = true;
1536 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1537 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1543 /* Arrays don't do this since there's no "array" value which spans across the
1546 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1548 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1551 codegen_output_type(self, v);
1552 v->context = ast_ctx(self);
1555 /* link us to the ir_value */
1559 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1560 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1561 if (self->expression.flags & AST_FLAG_ERASEABLE)
1562 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1565 if (self->hasvalue) {
1566 switch (self->expression.vtype)
1569 if (!ir_value_set_float(v, self->constval.vfloat))
1573 if (!ir_value_set_vector(v, self->constval.vvec))
1577 if (!ir_value_set_string(v, self->constval.vstring))
1581 ast_global_array_set(self);
1584 compile_error(ast_ctx(self), "global of type function not properly generated");
1586 /* Cannot generate an IR value for a function,
1587 * need a pointer pointing to a function rather.
1590 if (!self->constval.vfield) {
1591 compile_error(ast_ctx(self), "field constant without vfield set");
1594 if (!self->constval.vfield->ir_v) {
1595 compile_error(ast_ctx(self), "field constant generated before its field");
1598 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1602 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1608 error: /* clean up */
1609 if(v) ir_value_delete(v);
1613 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1617 if (self->expression.vtype == TYPE_NIL) {
1618 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1622 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1624 /* Do we allow local functions? I think not...
1625 * this is NOT a function pointer atm.
1630 if (self->expression.vtype == TYPE_ARRAY) {
1635 ast_expression *elemtype = self->expression.next;
1636 int vtype = elemtype->vtype;
1638 func->flags |= IR_FLAG_HAS_ARRAYS;
1640 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1641 compile_error(ast_ctx(self), "array-parameters are not supported");
1645 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1646 if (!check_array(self, self))
1649 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1650 if (!self->ir_values) {
1651 compile_error(ast_ctx(self), "failed to allocate array values");
1655 v = ir_function_create_local(func, self->name, vtype, param);
1657 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1660 v->context = ast_ctx(self);
1661 v->unique_life = true;
1664 namelen = strlen(self->name);
1665 name = (char*)mem_a(namelen + 16);
1666 util_strncpy(name, self->name, namelen);
1668 self->ir_values[0] = v;
1669 for (ai = 1; ai < self->expression.count; ++ai) {
1670 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1671 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1672 if (!self->ir_values[ai]) {
1673 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1676 self->ir_values[ai]->context = ast_ctx(self);
1677 self->ir_values[ai]->unique_life = true;
1678 self->ir_values[ai]->locked = true;
1684 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1687 codegen_output_type(self, v);
1688 v->context = ast_ctx(self);
1691 /* A constant local... hmmm...
1692 * I suppose the IR will have to deal with this
1694 if (self->hasvalue) {
1695 switch (self->expression.vtype)
1698 if (!ir_value_set_float(v, self->constval.vfloat))
1702 if (!ir_value_set_vector(v, self->constval.vvec))
1706 if (!ir_value_set_string(v, self->constval.vstring))
1710 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1715 /* link us to the ir_value */
1719 if (!ast_generate_accessors(self, func->owner))
1723 error: /* clean up */
1728 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1731 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1732 if (!self->setter || !self->getter)
1734 for (i = 0; i < self->expression.count; ++i) {
1735 if (!self->ir_values) {
1736 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1739 if (!self->ir_values[i]) {
1740 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1743 if (self->ir_values[i]->life) {
1744 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1749 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1751 if (!ast_global_codegen (self->setter, ir, false) ||
1752 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1753 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1755 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1756 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1761 if (!ast_global_codegen (self->getter, ir, false) ||
1762 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1763 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1765 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1766 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1770 for (i = 0; i < self->expression.count; ++i) {
1771 vec_free(self->ir_values[i]->life);
1773 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1777 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1782 ast_expression_codegen *cgen;
1787 irf = self->ir_func;
1789 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1793 /* fill the parameter list */
1794 ec = &self->vtype->expression;
1795 for (i = 0; i < vec_size(ec->params); ++i)
1797 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1798 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1800 vec_push(irf->params, ec->params[i]->expression.vtype);
1801 if (!self->builtin) {
1802 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1807 if (self->varargs) {
1808 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1810 irf->max_varargs = self->varargs->expression.count;
1813 if (self->builtin) {
1814 irf->builtin = self->builtin;
1818 /* have a local return value variable? */
1819 if (self->return_value) {
1820 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1824 if (!vec_size(self->blocks)) {
1825 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1829 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1830 if (!self->curblock) {
1831 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1839 if (!ast_local_codegen(self->argc, self->ir_func, true))
1841 cgen = self->argc->expression.codegen;
1842 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1844 cgen = self->fixedparams->expression.codegen;
1845 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1847 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1848 ast_function_label(self, "va_count"), INSTR_SUB_F,
1849 ir_builder_get_va_count(ir), fixed);
1852 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1859 for (i = 0; i < vec_size(self->blocks); ++i) {
1860 cgen = self->blocks[i]->expression.codegen;
1861 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1865 /* TODO: check return types */
1866 if (!self->curblock->final)
1868 if (!self->vtype->expression.next ||
1869 self->vtype->expression.next->vtype == TYPE_VOID)
1871 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1873 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1875 if (self->return_value) {
1876 cgen = self->return_value->expression.codegen;
1877 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1879 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1881 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1882 "control reaches end of non-void function (`%s`) via %s",
1883 self->name, self->curblock->label))
1887 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1893 static bool starts_a_label(ast_expression *ex)
1895 while (ex && ast_istype(ex, ast_block)) {
1896 ast_block *b = (ast_block*)ex;
1901 return ast_istype(ex, ast_label);
1904 /* Note, you will not see ast_block_codegen generate ir_blocks.
1905 * To the AST and the IR, blocks are 2 different things.
1906 * In the AST it represents a block of code, usually enclosed in
1907 * curly braces {...}.
1908 * While in the IR it represents a block in terms of control-flow.
1910 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1914 /* We don't use this
1915 * Note: an ast-representation using the comma-operator
1916 * of the form: (a, b, c) = x should not assign to c...
1919 compile_error(ast_ctx(self), "not an l-value (code-block)");
1923 if (self->expression.outr) {
1924 *out = self->expression.outr;
1928 /* output is NULL at first, we'll have each expression
1929 * assign to out output, thus, a comma-operator represention
1930 * using an ast_block will return the last generated value,
1931 * so: (b, c) + a executed both b and c, and returns c,
1932 * which is then added to a.
1936 /* generate locals */
1937 for (i = 0; i < vec_size(self->locals); ++i)
1939 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1940 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1941 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1946 for (i = 0; i < vec_size(self->exprs); ++i)
1948 ast_expression_codegen *gen;
1949 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1950 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1954 gen = self->exprs[i]->codegen;
1955 if (!(*gen)(self->exprs[i], func, false, out))
1959 self->expression.outr = *out;
1964 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1966 ast_expression_codegen *cgen;
1967 ir_value *left = NULL;
1968 ir_value *right = NULL;
1972 ast_array_index *ai = NULL;
1974 if (lvalue && self->expression.outl) {
1975 *out = self->expression.outl;
1979 if (!lvalue && self->expression.outr) {
1980 *out = self->expression.outr;
1984 if (ast_istype(self->dest, ast_array_index))
1987 ai = (ast_array_index*)self->dest;
1988 idx = (ast_value*)ai->index;
1990 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1995 /* we need to call the setter */
1996 ir_value *iridx, *funval;
2000 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2004 arr = (ast_value*)ai->array;
2005 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2006 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2010 cgen = idx->expression.codegen;
2011 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2014 cgen = arr->setter->expression.codegen;
2015 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2018 cgen = self->source->codegen;
2019 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2022 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2025 ir_call_param(call, iridx);
2026 ir_call_param(call, right);
2027 self->expression.outr = right;
2033 cgen = self->dest->codegen;
2035 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2037 self->expression.outl = left;
2039 cgen = self->source->codegen;
2041 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2044 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2046 self->expression.outr = right;
2049 /* Theoretically, an assinment returns its left side as an
2050 * lvalue, if we don't need an lvalue though, we return
2051 * the right side as an rvalue, otherwise we have to
2052 * somehow know whether or not we need to dereference the pointer
2053 * on the left side - that is: OP_LOAD if it was an address.
2054 * Also: in original QC we cannot OP_LOADP *anyway*.
2056 *out = (lvalue ? left : right);
2061 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2063 ast_expression_codegen *cgen;
2064 ir_value *left, *right;
2066 /* A binary operation cannot yield an l-value */
2068 compile_error(ast_ctx(self), "not an l-value (binop)");
2072 if (self->expression.outr) {
2073 *out = self->expression.outr;
2077 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2078 (self->op == INSTR_AND || self->op == INSTR_OR))
2080 /* NOTE: The short-logic path will ignore right_first */
2082 /* short circuit evaluation */
2083 ir_block *other, *merge;
2084 ir_block *from_left, *from_right;
2088 /* prepare end-block */
2089 merge_id = vec_size(func->ir_func->blocks);
2090 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2092 /* generate the left expression */
2093 cgen = self->left->codegen;
2094 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2096 /* remember the block */
2097 from_left = func->curblock;
2099 /* create a new block for the right expression */
2100 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2101 if (self->op == INSTR_AND) {
2102 /* on AND: left==true -> other */
2103 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2106 /* on OR: left==false -> other */
2107 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2110 /* use the likely flag */
2111 vec_last(func->curblock->instr)->likely = true;
2113 /* enter the right-expression's block */
2114 func->curblock = other;
2116 cgen = self->right->codegen;
2117 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2119 /* remember block */
2120 from_right = func->curblock;
2122 /* jump to the merge block */
2123 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2126 vec_remove(func->ir_func->blocks, merge_id, 1);
2127 vec_push(func->ir_func->blocks, merge);
2129 func->curblock = merge;
2130 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2131 ast_function_label(func, "sce_value"),
2132 self->expression.vtype);
2133 ir_phi_add(phi, from_left, left);
2134 ir_phi_add(phi, from_right, right);
2135 *out = ir_phi_value(phi);
2139 if (!OPTS_FLAG(PERL_LOGIC)) {
2141 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2142 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2143 ast_function_label(func, "sce_bool_v"),
2147 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2148 ast_function_label(func, "sce_bool"),
2153 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2154 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2155 ast_function_label(func, "sce_bool_s"),
2159 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2160 ast_function_label(func, "sce_bool"),
2166 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2167 ast_function_label(func, "sce_bool"),
2168 INSTR_AND, *out, *out);
2174 self->expression.outr = *out;
2175 codegen_output_type(self, *out);
2179 if (self->right_first) {
2180 cgen = self->right->codegen;
2181 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2183 cgen = self->left->codegen;
2184 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2187 cgen = self->left->codegen;
2188 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2190 cgen = self->right->codegen;
2191 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2195 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2196 self->op, left, right);
2199 self->expression.outr = *out;
2200 codegen_output_type(self, *out);
2205 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2207 ast_expression_codegen *cgen;
2208 ir_value *leftl = NULL, *leftr, *right, *bin;
2212 ast_array_index *ai = NULL;
2213 ir_value *iridx = NULL;
2215 if (lvalue && self->expression.outl) {
2216 *out = self->expression.outl;
2220 if (!lvalue && self->expression.outr) {
2221 *out = self->expression.outr;
2225 if (ast_istype(self->dest, ast_array_index))
2228 ai = (ast_array_index*)self->dest;
2229 idx = (ast_value*)ai->index;
2231 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2235 /* for a binstore we need both an lvalue and an rvalue for the left side */
2236 /* rvalue of destination! */
2238 cgen = idx->expression.codegen;
2239 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2242 cgen = self->dest->codegen;
2243 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2246 /* source as rvalue only */
2247 cgen = self->source->codegen;
2248 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2251 /* now the binary */
2252 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2253 self->opbin, leftr, right);
2254 self->expression.outr = bin;
2258 /* we need to call the setter */
2263 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2267 arr = (ast_value*)ai->array;
2268 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2269 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2273 cgen = arr->setter->expression.codegen;
2274 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2277 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2280 ir_call_param(call, iridx);
2281 ir_call_param(call, bin);
2282 self->expression.outr = bin;
2284 /* now store them */
2285 cgen = self->dest->codegen;
2286 /* lvalue of destination */
2287 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2289 self->expression.outl = leftl;
2291 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2293 self->expression.outr = bin;
2296 /* Theoretically, an assinment returns its left side as an
2297 * lvalue, if we don't need an lvalue though, we return
2298 * the right side as an rvalue, otherwise we have to
2299 * somehow know whether or not we need to dereference the pointer
2300 * on the left side - that is: OP_LOAD if it was an address.
2301 * Also: in original QC we cannot OP_LOADP *anyway*.
2303 *out = (lvalue ? leftl : bin);
2308 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2310 ast_expression_codegen *cgen;
2313 /* An unary operation cannot yield an l-value */
2315 compile_error(ast_ctx(self), "not an l-value (binop)");
2319 if (self->expression.outr) {
2320 *out = self->expression.outr;
2324 cgen = self->operand->codegen;
2326 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2329 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2333 self->expression.outr = *out;
2338 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2340 ast_expression_codegen *cgen;
2345 /* In the context of a return operation, we don't actually return
2349 compile_error(ast_ctx(self), "return-expression is not an l-value");
2353 if (self->expression.outr) {
2354 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2357 self->expression.outr = (ir_value*)1;
2359 if (self->operand) {
2360 cgen = self->operand->codegen;
2362 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2365 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2368 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2375 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2377 ast_expression_codegen *cgen;
2378 ir_value *ent, *field;
2380 /* This function needs to take the 'lvalue' flag into account!
2381 * As lvalue we provide a field-pointer, as rvalue we provide the
2385 if (lvalue && self->expression.outl) {
2386 *out = self->expression.outl;
2390 if (!lvalue && self->expression.outr) {
2391 *out = self->expression.outr;
2395 cgen = self->entity->codegen;
2396 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2399 cgen = self->field->codegen;
2400 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2405 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2408 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2409 ent, field, self->expression.vtype);
2410 /* Done AFTER error checking:
2411 codegen_output_type(self, *out);
2415 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2416 (lvalue ? "ADDRESS" : "FIELD"),
2417 type_name[self->expression.vtype]);
2421 codegen_output_type(self, *out);
2424 self->expression.outl = *out;
2426 self->expression.outr = *out;
2428 /* Hm that should be it... */
2432 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2434 ast_expression_codegen *cgen;
2437 /* in QC this is always an lvalue */
2438 if (lvalue && self->rvalue) {
2439 compile_error(ast_ctx(self), "not an l-value (member access)");
2442 if (self->expression.outl) {
2443 *out = self->expression.outl;
2447 cgen = self->owner->codegen;
2448 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2451 if (vec->vtype != TYPE_VECTOR &&
2452 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2457 *out = ir_value_vector_member(vec, self->field);
2458 self->expression.outl = *out;
2460 return (*out != NULL);
2463 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2468 if (!lvalue && self->expression.outr) {
2469 *out = self->expression.outr;
2472 if (lvalue && self->expression.outl) {
2473 *out = self->expression.outl;
2477 if (!ast_istype(self->array, ast_value)) {
2478 compile_error(ast_ctx(self), "array indexing this way is not supported");
2479 /* note this would actually be pointer indexing because the left side is
2480 * not an actual array but (hopefully) an indexable expression.
2481 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2482 * support this path will be filled.
2487 arr = (ast_value*)self->array;
2488 idx = (ast_value*)self->index;
2490 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2491 /* Time to use accessor functions */
2492 ast_expression_codegen *cgen;
2493 ir_value *iridx, *funval;
2497 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2502 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2506 cgen = self->index->codegen;
2507 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2510 cgen = arr->getter->expression.codegen;
2511 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2514 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2517 ir_call_param(call, iridx);
2519 *out = ir_call_value(call);
2520 self->expression.outr = *out;
2521 (*out)->vtype = self->expression.vtype;
2522 codegen_output_type(self, *out);
2526 if (idx->expression.vtype == TYPE_FLOAT) {
2527 unsigned int arridx = idx->constval.vfloat;
2528 if (arridx >= self->array->count)
2530 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2533 *out = arr->ir_values[arridx];
2535 else if (idx->expression.vtype == TYPE_INTEGER) {
2536 unsigned int arridx = idx->constval.vint;
2537 if (arridx >= self->array->count)
2539 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2542 *out = arr->ir_values[arridx];
2545 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2548 (*out)->vtype = self->expression.vtype;
2549 codegen_output_type(self, *out);
2553 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2557 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2562 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2566 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2568 ast_expression_codegen *cgen;
2576 ir_block *ontrue_endblock = NULL;
2577 ir_block *onfalse_endblock = NULL;
2578 ir_block *merge = NULL;
2581 /* We don't output any value, thus also don't care about r/lvalue */
2585 if (self->expression.outr) {
2586 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2589 self->expression.outr = (ir_value*)1;
2591 /* generate the condition */
2592 cgen = self->cond->codegen;
2593 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2595 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2596 cond = func->curblock;
2598 /* try constant folding away the condition */
2599 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2602 if (self->on_true) {
2603 /* create on-true block */
2604 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2608 /* enter the block */
2609 func->curblock = ontrue;
2612 cgen = self->on_true->codegen;
2613 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2616 /* we now need to work from the current endpoint */
2617 ontrue_endblock = func->curblock;
2622 if (self->on_false) {
2623 /* create on-false block */
2624 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2628 /* enter the block */
2629 func->curblock = onfalse;
2632 cgen = self->on_false->codegen;
2633 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2636 /* we now need to work from the current endpoint */
2637 onfalse_endblock = func->curblock;
2641 /* Merge block were they all merge in to */
2642 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2644 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2647 /* add jumps ot the merge block */
2648 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2650 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2653 /* Now enter the merge block */
2654 func->curblock = merge;
2657 /* we create the if here, that way all blocks are ordered :)
2659 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2660 (ontrue ? ontrue : merge),
2661 (onfalse ? onfalse : merge)))
2669 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2671 ast_expression_codegen *cgen;
2674 ir_value *trueval, *falseval;
2677 ir_block *cond = func->curblock;
2678 ir_block *cond_out = NULL;
2679 ir_block *ontrue, *ontrue_out = NULL;
2680 ir_block *onfalse, *onfalse_out = NULL;
2684 /* Ternary can never create an lvalue... */
2688 /* In theory it shouldn't be possible to pass through a node twice, but
2689 * in case we add any kind of optimization pass for the AST itself, it
2690 * may still happen, thus we remember a created ir_value and simply return one
2691 * if it already exists.
2693 if (self->expression.outr) {
2694 *out = self->expression.outr;
2698 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2700 /* generate the condition */
2701 func->curblock = cond;
2702 cgen = self->cond->codegen;
2703 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2705 cond_out = func->curblock;
2707 /* try constant folding away the condition */
2708 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2711 /* create on-true block */
2712 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2717 /* enter the block */
2718 func->curblock = ontrue;
2721 cgen = self->on_true->codegen;
2722 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2725 ontrue_out = func->curblock;
2728 /* create on-false block */
2729 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2734 /* enter the block */
2735 func->curblock = onfalse;
2738 cgen = self->on_false->codegen;
2739 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2742 onfalse_out = func->curblock;
2745 /* create merge block */
2746 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2749 /* jump to merge block */
2750 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2752 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2755 /* create if instruction */
2756 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2759 /* Now enter the merge block */
2760 func->curblock = merge;
2762 /* Here, now, we need a PHI node
2763 * but first some sanity checking...
2765 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2766 /* error("ternary with different types on the two sides"); */
2767 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2772 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2774 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2777 ir_phi_add(phi, ontrue_out, trueval);
2778 ir_phi_add(phi, onfalse_out, falseval);
2780 self->expression.outr = ir_phi_value(phi);
2781 *out = self->expression.outr;
2783 codegen_output_type(self, *out);
2788 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2790 ast_expression_codegen *cgen;
2792 ir_value *dummy = NULL;
2793 ir_value *precond = NULL;
2794 ir_value *postcond = NULL;
2796 /* Since we insert some jumps "late" so we have blocks
2797 * ordered "nicely", we need to keep track of the actual end-blocks
2798 * of expressions to add the jumps to.
2800 ir_block *bbody = NULL, *end_bbody = NULL;
2801 ir_block *bprecond = NULL, *end_bprecond = NULL;
2802 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2803 ir_block *bincrement = NULL, *end_bincrement = NULL;
2804 ir_block *bout = NULL, *bin = NULL;
2806 /* let's at least move the outgoing block to the end */
2809 /* 'break' and 'continue' need to be able to find the right blocks */
2810 ir_block *bcontinue = NULL;
2811 ir_block *bbreak = NULL;
2813 ir_block *tmpblock = NULL;
2818 if (self->expression.outr) {
2819 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2822 self->expression.outr = (ir_value*)1;
2825 * Should we ever need some kind of block ordering, better make this function
2826 * move blocks around than write a block ordering algorithm later... after all
2827 * the ast and ir should work together, not against each other.
2830 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2831 * anyway if for example it contains a ternary.
2835 cgen = self->initexpr->codegen;
2836 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2840 /* Store the block from which we enter this chaos */
2841 bin = func->curblock;
2843 /* The pre-loop condition needs its own block since we
2844 * need to be able to jump to the start of that expression.
2848 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2852 /* the pre-loop-condition the least important place to 'continue' at */
2853 bcontinue = bprecond;
2856 func->curblock = bprecond;
2859 cgen = self->precond->codegen;
2860 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2863 end_bprecond = func->curblock;
2865 bprecond = end_bprecond = NULL;
2868 /* Now the next blocks won't be ordered nicely, but we need to
2869 * generate them this early for 'break' and 'continue'.
2871 if (self->increment) {
2872 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2875 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2877 bincrement = end_bincrement = NULL;
2880 if (self->postcond) {
2881 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2884 bcontinue = bpostcond; /* postcond comes before the increment */
2886 bpostcond = end_bpostcond = NULL;
2889 bout_id = vec_size(func->ir_func->blocks);
2890 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2895 /* The loop body... */
2896 /* if (self->body) */
2898 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2903 func->curblock = bbody;
2905 vec_push(func->breakblocks, bbreak);
2907 vec_push(func->continueblocks, bcontinue);
2909 vec_push(func->continueblocks, bbody);
2913 cgen = self->body->codegen;
2914 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2918 end_bbody = func->curblock;
2919 vec_pop(func->breakblocks);
2920 vec_pop(func->continueblocks);
2923 /* post-loop-condition */
2927 func->curblock = bpostcond;
2930 cgen = self->postcond->codegen;
2931 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2934 end_bpostcond = func->curblock;
2937 /* The incrementor */
2938 if (self->increment)
2941 func->curblock = bincrement;
2944 cgen = self->increment->codegen;
2945 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2948 end_bincrement = func->curblock;
2951 /* In any case now, we continue from the outgoing block */
2952 func->curblock = bout;
2954 /* Now all blocks are in place */
2955 /* From 'bin' we jump to whatever comes first */
2956 if (bprecond) tmpblock = bprecond;
2957 else tmpblock = bbody; /* can never be null */
2960 else if (bpostcond) tmpblock = bpostcond;
2961 else tmpblock = bout;
2964 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2970 ir_block *ontrue, *onfalse;
2971 ontrue = bbody; /* can never be null */
2973 /* all of this is dead code
2974 else if (bincrement) ontrue = bincrement;
2975 else ontrue = bpostcond;
2979 if (self->pre_not) {
2984 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2991 if (bincrement) tmpblock = bincrement;
2992 else if (bpostcond) tmpblock = bpostcond;
2993 else if (bprecond) tmpblock = bprecond;
2994 else tmpblock = bbody;
2995 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2999 /* from increment */
3002 if (bpostcond) tmpblock = bpostcond;
3003 else if (bprecond) tmpblock = bprecond;
3004 else if (bbody) tmpblock = bbody;
3005 else tmpblock = bout;
3006 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3013 ir_block *ontrue, *onfalse;
3014 if (bprecond) ontrue = bprecond;
3015 else ontrue = bbody; /* can never be null */
3017 /* all of this is dead code
3018 else if (bincrement) ontrue = bincrement;
3019 else ontrue = bpostcond;
3023 if (self->post_not) {
3028 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3032 /* Move 'bout' to the end */
3033 vec_remove(func->ir_func->blocks, bout_id, 1);
3034 vec_push(func->ir_func->blocks, bout);
3039 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3046 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3050 if (self->expression.outr) {
3051 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3054 self->expression.outr = (ir_value*)1;
3056 if (self->is_continue)
3057 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3059 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3062 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3066 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3071 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3073 ast_expression_codegen *cgen;
3075 ast_switch_case *def_case = NULL;
3076 ir_block *def_bfall = NULL;
3077 ir_block *def_bfall_to = NULL;
3078 bool set_def_bfall_to = false;
3080 ir_value *dummy = NULL;
3081 ir_value *irop = NULL;
3082 ir_block *bout = NULL;
3083 ir_block *bfall = NULL;
3091 compile_error(ast_ctx(self), "switch expression is not an l-value");
3095 if (self->expression.outr) {
3096 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3099 self->expression.outr = (ir_value*)1;
3104 cgen = self->operand->codegen;
3105 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3108 if (!vec_size(self->cases))
3111 cmpinstr = type_eq_instr[irop->vtype];
3112 if (cmpinstr >= VINSTR_END) {
3113 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3114 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3118 bout_id = vec_size(func->ir_func->blocks);
3119 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3123 /* setup the break block */
3124 vec_push(func->breakblocks, bout);
3126 /* Now create all cases */
3127 for (c = 0; c < vec_size(self->cases); ++c) {
3128 ir_value *cond, *val;
3129 ir_block *bcase, *bnot;
3132 ast_switch_case *swcase = &self->cases[c];
3134 if (swcase->value) {
3135 /* A regular case */
3136 /* generate the condition operand */
3137 cgen = swcase->value->codegen;
3138 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3140 /* generate the condition */
3141 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3145 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3146 bnot_id = vec_size(func->ir_func->blocks);
3147 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3148 if (!bcase || !bnot)
3150 if (set_def_bfall_to) {
3151 set_def_bfall_to = false;
3152 def_bfall_to = bcase;
3154 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3157 /* Make the previous case-end fall through */
3158 if (bfall && !bfall->final) {
3159 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3163 /* enter the case */
3164 func->curblock = bcase;
3165 cgen = swcase->code->codegen;
3166 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3169 /* remember this block to fall through from */
3170 bfall = func->curblock;
3172 /* enter the else and move it down */
3173 func->curblock = bnot;
3174 vec_remove(func->ir_func->blocks, bnot_id, 1);
3175 vec_push(func->ir_func->blocks, bnot);
3177 /* The default case */
3178 /* Remember where to fall through from: */
3181 /* remember which case it was */
3183 /* And the next case will be remembered */
3184 set_def_bfall_to = true;
3188 /* Jump from the last bnot to bout */
3189 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3191 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3196 /* If there was a default case, put it down here */
3200 /* No need to create an extra block */
3201 bcase = func->curblock;
3203 /* Insert the fallthrough jump */
3204 if (def_bfall && !def_bfall->final) {
3205 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3209 /* Now generate the default code */
3210 cgen = def_case->code->codegen;
3211 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3214 /* see if we need to fall through */
3215 if (def_bfall_to && !func->curblock->final)
3217 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3222 /* Jump from the last bnot to bout */
3223 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3225 /* enter the outgoing block */
3226 func->curblock = bout;
3228 /* restore the break block */
3229 vec_pop(func->breakblocks);
3231 /* Move 'bout' to the end, it's nicer */
3232 vec_remove(func->ir_func->blocks, bout_id, 1);
3233 vec_push(func->ir_func->blocks, bout);
3238 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3243 if (self->undefined) {
3244 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3250 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3254 /* simply create a new block and jump to it */
3255 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3256 if (!self->irblock) {
3257 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3260 if (!func->curblock->final) {
3261 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3265 /* enter the new block */
3266 func->curblock = self->irblock;
3268 /* Generate all the leftover gotos */
3269 for (i = 0; i < vec_size(self->gotos); ++i) {
3270 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3277 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3281 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3285 if (self->target->irblock) {
3286 if (self->irblock_from) {
3287 /* we already tried once, this is the callback */
3288 self->irblock_from->final = false;
3289 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3290 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3296 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3297 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3304 /* the target has not yet been created...
3305 * close this block in a sneaky way:
3307 func->curblock->final = true;
3308 self->irblock_from = func->curblock;
3309 ast_label_register_goto(self->target, self);
3315 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3317 ast_expression_codegen *cgen;
3319 ir_instr *callinstr;
3322 ir_value *funval = NULL;
3324 /* return values are never lvalues */
3326 compile_error(ast_ctx(self), "not an l-value (function call)");
3330 if (self->expression.outr) {
3331 *out = self->expression.outr;
3335 cgen = self->func->codegen;
3336 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3344 for (i = 0; i < vec_size(self->params); ++i)
3347 ast_expression *expr = self->params[i];
3349 cgen = expr->codegen;
3350 if (!(*cgen)(expr, func, false, ¶m))
3354 vec_push(params, param);
3357 /* varargs counter */
3358 if (self->va_count) {
3360 ir_builder *builder = func->curblock->owner->owner;
3361 cgen = self->va_count->codegen;
3362 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3364 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3365 ir_builder_get_va_count(builder), va_count))
3371 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3372 ast_function_label(func, "call"),
3373 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3377 for (i = 0; i < vec_size(params); ++i) {
3378 ir_call_param(callinstr, params[i]);
3381 *out = ir_call_value(callinstr);
3382 self->expression.outr = *out;
3384 codegen_output_type(self, *out);