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;
522 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
523 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
525 /* Handle for double negation */
526 if (((ast_unary*)expr)->op == op)
527 prev = (ast_unary*)((ast_unary*)expr)->operand;
529 if (ast_istype(prev, ast_unary)) {
530 ast_expression_delete((ast_expression*)self);
532 ++opts_optimizationcount[OPTIM_PEEPHOLE];
537 ast_propagate_effects(self, expr);
539 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
540 self->expression.vtype = TYPE_FLOAT;
541 } else if (op == VINSTR_NEG_V) {
542 self->expression.vtype = TYPE_VECTOR;
544 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
550 void ast_unary_delete(ast_unary *self)
552 if (self->operand) ast_unref(self->operand);
553 ast_expression_delete((ast_expression*)self);
557 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
559 ast_instantiate(ast_return, ctx, ast_return_delete);
560 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
562 self->operand = expr;
565 ast_propagate_effects(self, expr);
570 void ast_return_delete(ast_return *self)
573 ast_unref(self->operand);
574 ast_expression_delete((ast_expression*)self);
578 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
580 if (field->vtype != TYPE_FIELD) {
581 compile_error(ctx, "ast_entfield_new with expression not of type field");
584 return ast_entfield_new_force(ctx, entity, field, field->next);
587 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
589 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
593 /* Error: field has no type... */
597 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
599 self->entity = entity;
601 ast_propagate_effects(self, entity);
602 ast_propagate_effects(self, field);
604 ast_type_adopt(self, outtype);
608 void ast_entfield_delete(ast_entfield *self)
610 ast_unref(self->entity);
611 ast_unref(self->field);
612 ast_expression_delete((ast_expression*)self);
616 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
618 ast_instantiate(ast_member, ctx, ast_member_delete);
624 if (owner->vtype != TYPE_VECTOR &&
625 owner->vtype != TYPE_FIELD) {
626 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
631 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
632 self->expression.node.keep = true; /* keep */
634 if (owner->vtype == TYPE_VECTOR) {
635 self->expression.vtype = TYPE_FLOAT;
636 self->expression.next = NULL;
638 self->expression.vtype = TYPE_FIELD;
639 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
642 self->rvalue = false;
644 ast_propagate_effects(self, owner);
648 self->name = util_strdup(name);
655 void ast_member_delete(ast_member *self)
657 /* The owner is always an ast_value, which has .keep=true,
658 * also: ast_members are usually deleted after the owner, thus
659 * this will cause invalid access
660 ast_unref(self->owner);
661 * once we allow (expression).x to access a vector-member, we need
662 * to change this: preferably by creating an alternate ast node for this
663 * purpose that is not garbage-collected.
665 ast_expression_delete((ast_expression*)self);
670 bool ast_member_set_name(ast_member *self, const char *name)
673 mem_d((void*)self->name);
674 self->name = util_strdup(name);
678 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
680 ast_expression *outtype;
681 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
683 outtype = array->next;
686 /* Error: field has no type... */
690 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
694 ast_propagate_effects(self, array);
695 ast_propagate_effects(self, index);
697 ast_type_adopt(self, outtype);
698 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
699 if (self->expression.vtype != TYPE_ARRAY) {
700 compile_error(ast_ctx(self), "array_index node on type");
701 ast_array_index_delete(self);
704 self->array = outtype;
705 self->expression.vtype = TYPE_FIELD;
711 void ast_array_index_delete(ast_array_index *self)
714 ast_unref(self->array);
716 ast_unref(self->index);
717 ast_expression_delete((ast_expression*)self);
721 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
723 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
724 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
726 self->expression.vtype = TYPE_NOEXPR;
730 void ast_argpipe_delete(ast_argpipe *self)
733 ast_unref(self->index);
734 ast_expression_delete((ast_expression*)self);
738 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
740 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
741 if (!ontrue && !onfalse) {
742 /* because it is invalid */
746 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
749 self->on_true = ontrue;
750 self->on_false = onfalse;
751 ast_propagate_effects(self, cond);
753 ast_propagate_effects(self, ontrue);
755 ast_propagate_effects(self, onfalse);
760 void ast_ifthen_delete(ast_ifthen *self)
762 ast_unref(self->cond);
764 ast_unref(self->on_true);
766 ast_unref(self->on_false);
767 ast_expression_delete((ast_expression*)self);
771 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
773 ast_expression *exprtype = ontrue;
774 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
775 /* This time NEITHER must be NULL */
776 if (!ontrue || !onfalse) {
780 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
783 self->on_true = ontrue;
784 self->on_false = onfalse;
785 ast_propagate_effects(self, cond);
786 ast_propagate_effects(self, ontrue);
787 ast_propagate_effects(self, onfalse);
789 if (ontrue->vtype == TYPE_NIL)
791 ast_type_adopt(self, exprtype);
796 void ast_ternary_delete(ast_ternary *self)
798 /* the if()s are only there because computed-gotos can set them
801 if (self->cond) ast_unref(self->cond);
802 if (self->on_true) ast_unref(self->on_true);
803 if (self->on_false) ast_unref(self->on_false);
804 ast_expression_delete((ast_expression*)self);
808 ast_loop* ast_loop_new(lex_ctx_t ctx,
809 ast_expression *initexpr,
810 ast_expression *precond, bool pre_not,
811 ast_expression *postcond, bool post_not,
812 ast_expression *increment,
813 ast_expression *body)
815 ast_instantiate(ast_loop, ctx, ast_loop_delete);
816 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
818 self->initexpr = initexpr;
819 self->precond = precond;
820 self->postcond = postcond;
821 self->increment = increment;
824 self->pre_not = pre_not;
825 self->post_not = post_not;
828 ast_propagate_effects(self, initexpr);
830 ast_propagate_effects(self, precond);
832 ast_propagate_effects(self, postcond);
834 ast_propagate_effects(self, increment);
836 ast_propagate_effects(self, body);
841 void ast_loop_delete(ast_loop *self)
844 ast_unref(self->initexpr);
846 ast_unref(self->precond);
848 ast_unref(self->postcond);
850 ast_unref(self->increment);
852 ast_unref(self->body);
853 ast_expression_delete((ast_expression*)self);
857 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
859 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
860 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
862 self->is_continue = iscont;
863 self->levels = levels;
868 void ast_breakcont_delete(ast_breakcont *self)
870 ast_expression_delete((ast_expression*)self);
874 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
876 ast_instantiate(ast_switch, ctx, ast_switch_delete);
877 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
882 ast_propagate_effects(self, op);
887 void ast_switch_delete(ast_switch *self)
890 ast_unref(self->operand);
892 for (i = 0; i < vec_size(self->cases); ++i) {
893 if (self->cases[i].value)
894 ast_unref(self->cases[i].value);
895 ast_unref(self->cases[i].code);
897 vec_free(self->cases);
899 ast_expression_delete((ast_expression*)self);
903 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
905 ast_instantiate(ast_label, ctx, ast_label_delete);
906 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
908 self->expression.vtype = TYPE_NOEXPR;
910 self->name = util_strdup(name);
911 self->irblock = NULL;
913 self->undefined = undefined;
918 void ast_label_delete(ast_label *self)
920 mem_d((void*)self->name);
921 vec_free(self->gotos);
922 ast_expression_delete((ast_expression*)self);
926 static void ast_label_register_goto(ast_label *self, ast_goto *g)
928 vec_push(self->gotos, g);
931 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
933 ast_instantiate(ast_goto, ctx, ast_goto_delete);
934 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
936 self->name = util_strdup(name);
938 self->irblock_from = NULL;
943 void ast_goto_delete(ast_goto *self)
945 mem_d((void*)self->name);
946 ast_expression_delete((ast_expression*)self);
950 void ast_goto_set_label(ast_goto *self, ast_label *label)
952 self->target = label;
955 ast_call* ast_call_new(lex_ctx_t ctx,
956 ast_expression *funcexpr)
958 ast_instantiate(ast_call, ctx, ast_call_delete);
959 if (!funcexpr->next) {
960 compile_error(ctx, "not a function");
964 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
966 ast_side_effects(self) = true;
969 self->func = funcexpr;
970 self->va_count = NULL;
972 ast_type_adopt(self, funcexpr->next);
977 void ast_call_delete(ast_call *self)
980 for (i = 0; i < vec_size(self->params); ++i)
981 ast_unref(self->params[i]);
982 vec_free(self->params);
985 ast_unref(self->func);
988 ast_unref(self->va_count);
990 ast_expression_delete((ast_expression*)self);
994 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1000 if (!va_type || !ast_compare_type(va_type, exp_type))
1002 if (va_type && exp_type)
1004 ast_type_to_string(va_type, tgot, sizeof(tgot));
1005 ast_type_to_string(exp_type, texp, sizeof(texp));
1006 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1007 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1008 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1012 compile_error(ast_ctx(self),
1013 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1020 ast_type_to_string(exp_type, texp, sizeof(texp));
1021 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1022 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1023 "piped variadic argument may differ in type: expected type %s",
1027 compile_error(ast_ctx(self),
1028 "piped variadic argument may differ in type: expected type %s",
1037 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1043 const ast_expression *func = self->func;
1044 size_t count = vec_size(self->params);
1045 if (count > vec_size(func->params))
1046 count = vec_size(func->params);
1048 for (i = 0; i < count; ++i) {
1049 if (ast_istype(self->params[i], ast_argpipe)) {
1050 /* warn about type safety instead */
1052 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1055 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1058 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1060 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1061 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1062 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1063 (unsigned int)(i+1), texp, tgot);
1064 /* we don't immediately return */
1068 count = vec_size(self->params);
1069 if (count > vec_size(func->params) && func->varparam) {
1070 for (; i < count; ++i) {
1071 if (ast_istype(self->params[i], ast_argpipe)) {
1072 /* warn about type safety instead */
1074 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1077 if (!ast_call_check_vararg(self, va_type, func->varparam))
1080 else if (!ast_compare_type(self->params[i], func->varparam))
1082 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1083 ast_type_to_string(func->varparam, texp, sizeof(texp));
1084 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1085 (unsigned int)(i+1), texp, tgot);
1086 /* we don't immediately return */
1094 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1095 ast_expression *dest, ast_expression *source)
1097 ast_instantiate(ast_store, ctx, ast_store_delete);
1098 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1100 ast_side_effects(self) = true;
1104 self->source = source;
1106 ast_type_adopt(self, dest);
1111 void ast_store_delete(ast_store *self)
1113 ast_unref(self->dest);
1114 ast_unref(self->source);
1115 ast_expression_delete((ast_expression*)self);
1119 ast_block* ast_block_new(lex_ctx_t ctx)
1121 ast_instantiate(ast_block, ctx, ast_block_delete);
1122 ast_expression_init((ast_expression*)self,
1123 (ast_expression_codegen*)&ast_block_codegen);
1125 self->locals = NULL;
1127 self->collect = NULL;
1132 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1134 ast_propagate_effects(self, e);
1135 vec_push(self->exprs, e);
1136 if (self->expression.next) {
1137 ast_delete(self->expression.next);
1138 self->expression.next = NULL;
1140 ast_type_adopt(self, e);
1144 void ast_block_collect(ast_block *self, ast_expression *expr)
1146 vec_push(self->collect, expr);
1147 expr->node.keep = true;
1150 void ast_block_delete(ast_block *self)
1153 for (i = 0; i < vec_size(self->exprs); ++i)
1154 ast_unref(self->exprs[i]);
1155 vec_free(self->exprs);
1156 for (i = 0; i < vec_size(self->locals); ++i)
1157 ast_delete(self->locals[i]);
1158 vec_free(self->locals);
1159 for (i = 0; i < vec_size(self->collect); ++i)
1160 ast_delete(self->collect[i]);
1161 vec_free(self->collect);
1162 ast_expression_delete((ast_expression*)self);
1166 void ast_block_set_type(ast_block *self, ast_expression *from)
1168 if (self->expression.next)
1169 ast_delete(self->expression.next);
1170 ast_type_adopt(self, from);
1173 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1175 ast_instantiate(ast_function, ctx, ast_function_delete);
1178 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1180 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1181 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1182 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1184 (int)vtype->hasvalue,
1185 vtype->expression.vtype);
1189 self->vtype = vtype;
1190 self->name = name ? util_strdup(name) : NULL;
1191 self->blocks = NULL;
1193 self->labelcount = 0;
1196 self->ir_func = NULL;
1197 self->curblock = NULL;
1199 self->breakblocks = NULL;
1200 self->continueblocks = NULL;
1202 vtype->hasvalue = true;
1203 vtype->constval.vfunc = self;
1205 self->varargs = NULL;
1207 self->fixedparams = NULL;
1208 self->return_value = NULL;
1217 void ast_function_delete(ast_function *self)
1221 mem_d((void*)self->name);
1223 /* ast_value_delete(self->vtype); */
1224 self->vtype->hasvalue = false;
1225 self->vtype->constval.vfunc = NULL;
1226 /* We use unref - if it was stored in a global table it is supposed
1227 * to be deleted from *there*
1229 ast_unref(self->vtype);
1231 for (i = 0; i < vec_size(self->blocks); ++i)
1232 ast_delete(self->blocks[i]);
1233 vec_free(self->blocks);
1234 vec_free(self->breakblocks);
1235 vec_free(self->continueblocks);
1237 ast_delete(self->varargs);
1239 ast_delete(self->argc);
1240 if (self->fixedparams)
1241 ast_unref(self->fixedparams);
1242 if (self->return_value)
1243 ast_unref(self->return_value);
1247 const char* ast_function_label(ast_function *self, const char *prefix)
1253 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1254 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1255 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1260 id = (self->labelcount++);
1261 len = strlen(prefix);
1263 from = self->labelbuf + sizeof(self->labelbuf)-1;
1266 *from-- = (id%10) + '0';
1270 memcpy(from - len, prefix, len);
1274 /*********************************************************************/
1276 * by convention you must never pass NULL to the 'ir_value **out'
1277 * parameter. If you really don't care about the output, pass a dummy.
1278 * But I can't imagine a pituation where the output is truly unnecessary.
1281 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1283 if (out->vtype == TYPE_FIELD)
1284 out->fieldtype = self->next->vtype;
1285 if (out->vtype == TYPE_FUNCTION)
1286 out->outtype = self->next->vtype;
1289 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1291 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1295 if (self->expression.vtype == TYPE_NIL) {
1296 *out = func->ir_func->owner->nil;
1299 /* NOTE: This is the codegen for a variable used in an expression.
1300 * It is not the codegen to generate the value. For this purpose,
1301 * ast_local_codegen and ast_global_codegen are to be used before this
1302 * is executed. ast_function_codegen should take care of its locals,
1303 * and the ast-user should take care of ast_global_codegen to be used
1304 * on all the globals.
1307 char tname[1024]; /* typename is reserved in C++ */
1308 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1309 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1316 static bool ast_global_array_set(ast_value *self)
1318 size_t count = vec_size(self->initlist);
1321 if (count > self->expression.count) {
1322 compile_error(ast_ctx(self), "too many elements in initializer");
1323 count = self->expression.count;
1325 else if (count < self->expression.count) {
1327 compile_warning(ast_ctx(self), "not all elements are initialized");
1331 for (i = 0; i != count; ++i) {
1332 switch (self->expression.next->vtype) {
1334 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1338 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1342 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1346 /* we don't support them in any other place yet either */
1347 compile_error(ast_ctx(self), "TODO: nested arrays");
1350 /* this requiers a bit more work - similar to the fields I suppose */
1351 compile_error(ast_ctx(self), "global of type function not properly generated");
1354 if (!self->initlist[i].vfield) {
1355 compile_error(ast_ctx(self), "field constant without vfield set");
1358 if (!self->initlist[i].vfield->ir_v) {
1359 compile_error(ast_ctx(self), "field constant generated before its field");
1362 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1366 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1373 static bool check_array(ast_value *self, ast_value *array)
1375 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1376 compile_error(ast_ctx(self), "array without size: %s", self->name);
1379 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1380 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1381 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1387 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1391 if (self->expression.vtype == TYPE_NIL) {
1392 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1396 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1398 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1401 func->context = ast_ctx(self);
1402 func->value->context = ast_ctx(self);
1404 self->constval.vfunc->ir_func = func;
1405 self->ir_v = func->value;
1406 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1407 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1408 if (self->expression.flags & AST_FLAG_ERASEABLE)
1409 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1410 /* The function is filled later on ast_function_codegen... */
1414 if (isfield && self->expression.vtype == TYPE_FIELD) {
1415 ast_expression *fieldtype = self->expression.next;
1417 if (self->hasvalue) {
1418 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1422 if (fieldtype->vtype == TYPE_ARRAY) {
1427 ast_expression *elemtype;
1429 ast_value *array = (ast_value*)fieldtype;
1431 if (!ast_istype(fieldtype, ast_value)) {
1432 compile_error(ast_ctx(self), "internal error: ast_value required");
1436 if (!check_array(self, array))
1439 elemtype = array->expression.next;
1440 vtype = elemtype->vtype;
1442 v = ir_builder_create_field(ir, self->name, vtype);
1444 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1447 v->context = ast_ctx(self);
1448 v->unique_life = true;
1450 array->ir_v = self->ir_v = v;
1452 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1453 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1454 if (self->expression.flags & AST_FLAG_ERASEABLE)
1455 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1457 namelen = strlen(self->name);
1458 name = (char*)mem_a(namelen + 16);
1459 util_strncpy(name, self->name, namelen);
1461 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1462 array->ir_values[0] = v;
1463 for (ai = 1; ai < array->expression.count; ++ai) {
1464 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1465 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1466 if (!array->ir_values[ai]) {
1468 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1471 array->ir_values[ai]->context = ast_ctx(self);
1472 array->ir_values[ai]->unique_life = true;
1473 array->ir_values[ai]->locked = true;
1474 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1475 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1481 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1484 v->context = ast_ctx(self);
1486 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1487 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1489 if (self->expression.flags & AST_FLAG_ERASEABLE)
1490 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1495 if (self->expression.vtype == TYPE_ARRAY) {
1500 ast_expression *elemtype = self->expression.next;
1501 int vtype = elemtype->vtype;
1503 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1504 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1508 /* same as with field arrays */
1509 if (!check_array(self, self))
1512 v = ir_builder_create_global(ir, self->name, vtype);
1514 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1517 v->context = ast_ctx(self);
1518 v->unique_life = true;
1521 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1522 v->flags |= IR_FLAG_INCLUDE_DEF;
1523 if (self->expression.flags & AST_FLAG_ERASEABLE)
1524 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1526 namelen = strlen(self->name);
1527 name = (char*)mem_a(namelen + 16);
1528 util_strncpy(name, self->name, namelen);
1530 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1531 self->ir_values[0] = v;
1532 for (ai = 1; ai < self->expression.count; ++ai) {
1533 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1534 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1535 if (!self->ir_values[ai]) {
1537 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1540 self->ir_values[ai]->context = ast_ctx(self);
1541 self->ir_values[ai]->unique_life = true;
1542 self->ir_values[ai]->locked = true;
1543 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1544 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1550 /* Arrays don't do this since there's no "array" value which spans across the
1553 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1555 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1558 codegen_output_type(self, v);
1559 v->context = ast_ctx(self);
1562 /* link us to the ir_value */
1566 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1567 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1568 if (self->expression.flags & AST_FLAG_ERASEABLE)
1569 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1572 if (self->hasvalue) {
1573 switch (self->expression.vtype)
1576 if (!ir_value_set_float(v, self->constval.vfloat))
1580 if (!ir_value_set_vector(v, self->constval.vvec))
1584 if (!ir_value_set_string(v, self->constval.vstring))
1588 ast_global_array_set(self);
1591 compile_error(ast_ctx(self), "global of type function not properly generated");
1593 /* Cannot generate an IR value for a function,
1594 * need a pointer pointing to a function rather.
1597 if (!self->constval.vfield) {
1598 compile_error(ast_ctx(self), "field constant without vfield set");
1601 if (!self->constval.vfield->ir_v) {
1602 compile_error(ast_ctx(self), "field constant generated before its field");
1605 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1609 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1615 error: /* clean up */
1616 if(v) ir_value_delete(v);
1620 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1624 if (self->expression.vtype == TYPE_NIL) {
1625 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1629 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1631 /* Do we allow local functions? I think not...
1632 * this is NOT a function pointer atm.
1637 if (self->expression.vtype == TYPE_ARRAY) {
1642 ast_expression *elemtype = self->expression.next;
1643 int vtype = elemtype->vtype;
1645 func->flags |= IR_FLAG_HAS_ARRAYS;
1647 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1648 compile_error(ast_ctx(self), "array-parameters are not supported");
1652 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1653 if (!check_array(self, self))
1656 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1657 if (!self->ir_values) {
1658 compile_error(ast_ctx(self), "failed to allocate array values");
1662 v = ir_function_create_local(func, self->name, vtype, param);
1664 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1667 v->context = ast_ctx(self);
1668 v->unique_life = true;
1671 namelen = strlen(self->name);
1672 name = (char*)mem_a(namelen + 16);
1673 util_strncpy(name, self->name, namelen);
1675 self->ir_values[0] = v;
1676 for (ai = 1; ai < self->expression.count; ++ai) {
1677 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1678 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1679 if (!self->ir_values[ai]) {
1680 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1683 self->ir_values[ai]->context = ast_ctx(self);
1684 self->ir_values[ai]->unique_life = true;
1685 self->ir_values[ai]->locked = true;
1691 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1694 codegen_output_type(self, v);
1695 v->context = ast_ctx(self);
1698 /* A constant local... hmmm...
1699 * I suppose the IR will have to deal with this
1701 if (self->hasvalue) {
1702 switch (self->expression.vtype)
1705 if (!ir_value_set_float(v, self->constval.vfloat))
1709 if (!ir_value_set_vector(v, self->constval.vvec))
1713 if (!ir_value_set_string(v, self->constval.vstring))
1717 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1722 /* link us to the ir_value */
1726 if (!ast_generate_accessors(self, func->owner))
1730 error: /* clean up */
1735 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1738 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1739 if (!self->setter || !self->getter)
1741 for (i = 0; i < self->expression.count; ++i) {
1742 if (!self->ir_values) {
1743 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1746 if (!self->ir_values[i]) {
1747 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1750 if (self->ir_values[i]->life) {
1751 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1756 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1758 if (!ast_global_codegen (self->setter, ir, false) ||
1759 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1760 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1762 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1763 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1768 if (!ast_global_codegen (self->getter, ir, false) ||
1769 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1770 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1772 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1773 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1777 for (i = 0; i < self->expression.count; ++i) {
1778 vec_free(self->ir_values[i]->life);
1780 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1784 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1789 ast_expression_codegen *cgen;
1795 irf = self->ir_func;
1797 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1801 /* fill the parameter list */
1802 ec = &self->vtype->expression;
1803 for (i = 0; i < vec_size(ec->params); ++i)
1805 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1806 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1808 vec_push(irf->params, ec->params[i]->expression.vtype);
1809 if (!self->builtin) {
1810 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1815 if (self->varargs) {
1816 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1818 irf->max_varargs = self->varargs->expression.count;
1821 if (self->builtin) {
1822 irf->builtin = self->builtin;
1826 /* have a local return value variable? */
1827 if (self->return_value) {
1828 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1832 if (!vec_size(self->blocks)) {
1833 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1837 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1838 if (!self->curblock) {
1839 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1847 if (!ast_local_codegen(self->argc, self->ir_func, true))
1849 cgen = self->argc->expression.codegen;
1850 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1852 cgen = self->fixedparams->expression.codegen;
1853 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1855 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1856 ast_function_label(self, "va_count"), INSTR_SUB_F,
1857 ir_builder_get_va_count(ir), fixed);
1860 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1867 for (i = 0; i < vec_size(self->blocks); ++i) {
1868 cgen = self->blocks[i]->expression.codegen;
1869 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1873 /* TODO: check return types */
1874 if (!self->curblock->final)
1876 if (!self->vtype->expression.next ||
1877 self->vtype->expression.next->vtype == TYPE_VOID)
1879 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1881 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1883 if (self->return_value) {
1884 cgen = self->return_value->expression.codegen;
1885 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1887 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1889 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1890 "control reaches end of non-void function (`%s`) via %s",
1891 self->name, self->curblock->label))
1895 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1901 static bool starts_a_label(ast_expression *ex)
1903 while (ex && ast_istype(ex, ast_block)) {
1904 ast_block *b = (ast_block*)ex;
1909 return ast_istype(ex, ast_label);
1912 /* Note, you will not see ast_block_codegen generate ir_blocks.
1913 * To the AST and the IR, blocks are 2 different things.
1914 * In the AST it represents a block of code, usually enclosed in
1915 * curly braces {...}.
1916 * While in the IR it represents a block in terms of control-flow.
1918 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1922 /* We don't use this
1923 * Note: an ast-representation using the comma-operator
1924 * of the form: (a, b, c) = x should not assign to c...
1927 compile_error(ast_ctx(self), "not an l-value (code-block)");
1931 if (self->expression.outr) {
1932 *out = self->expression.outr;
1936 /* output is NULL at first, we'll have each expression
1937 * assign to out output, thus, a comma-operator represention
1938 * using an ast_block will return the last generated value,
1939 * so: (b, c) + a executed both b and c, and returns c,
1940 * which is then added to a.
1944 /* generate locals */
1945 for (i = 0; i < vec_size(self->locals); ++i)
1947 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1948 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1949 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1954 for (i = 0; i < vec_size(self->exprs); ++i)
1956 ast_expression_codegen *gen;
1957 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1958 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1962 gen = self->exprs[i]->codegen;
1963 if (!(*gen)(self->exprs[i], func, false, out))
1967 self->expression.outr = *out;
1972 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1974 ast_expression_codegen *cgen;
1975 ir_value *left = NULL;
1976 ir_value *right = NULL;
1980 ast_array_index *ai = NULL;
1982 if (lvalue && self->expression.outl) {
1983 *out = self->expression.outl;
1987 if (!lvalue && self->expression.outr) {
1988 *out = self->expression.outr;
1992 if (ast_istype(self->dest, ast_array_index))
1995 ai = (ast_array_index*)self->dest;
1996 idx = (ast_value*)ai->index;
1998 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2003 /* we need to call the setter */
2004 ir_value *iridx, *funval;
2008 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2012 arr = (ast_value*)ai->array;
2013 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2014 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2018 cgen = idx->expression.codegen;
2019 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2022 cgen = arr->setter->expression.codegen;
2023 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2026 cgen = self->source->codegen;
2027 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2030 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2033 ir_call_param(call, iridx);
2034 ir_call_param(call, right);
2035 self->expression.outr = right;
2041 cgen = self->dest->codegen;
2043 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2045 self->expression.outl = left;
2047 cgen = self->source->codegen;
2049 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2052 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2054 self->expression.outr = right;
2057 /* Theoretically, an assinment returns its left side as an
2058 * lvalue, if we don't need an lvalue though, we return
2059 * the right side as an rvalue, otherwise we have to
2060 * somehow know whether or not we need to dereference the pointer
2061 * on the left side - that is: OP_LOAD if it was an address.
2062 * Also: in original QC we cannot OP_LOADP *anyway*.
2064 *out = (lvalue ? left : right);
2069 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2071 ast_expression_codegen *cgen;
2072 ir_value *left, *right;
2074 /* A binary operation cannot yield an l-value */
2076 compile_error(ast_ctx(self), "not an l-value (binop)");
2080 if (self->expression.outr) {
2081 *out = self->expression.outr;
2085 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2086 (self->op == INSTR_AND || self->op == INSTR_OR))
2088 /* NOTE: The short-logic path will ignore right_first */
2090 /* short circuit evaluation */
2091 ir_block *other, *merge;
2092 ir_block *from_left, *from_right;
2096 /* prepare end-block */
2097 merge_id = vec_size(func->ir_func->blocks);
2098 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2100 /* generate the left expression */
2101 cgen = self->left->codegen;
2102 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2104 /* remember the block */
2105 from_left = func->curblock;
2107 /* create a new block for the right expression */
2108 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2109 if (self->op == INSTR_AND) {
2110 /* on AND: left==true -> other */
2111 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2114 /* on OR: left==false -> other */
2115 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2118 /* use the likely flag */
2119 vec_last(func->curblock->instr)->likely = true;
2121 /* enter the right-expression's block */
2122 func->curblock = other;
2124 cgen = self->right->codegen;
2125 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2127 /* remember block */
2128 from_right = func->curblock;
2130 /* jump to the merge block */
2131 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2134 vec_remove(func->ir_func->blocks, merge_id, 1);
2135 vec_push(func->ir_func->blocks, merge);
2137 func->curblock = merge;
2138 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2139 ast_function_label(func, "sce_value"),
2140 self->expression.vtype);
2141 ir_phi_add(phi, from_left, left);
2142 ir_phi_add(phi, from_right, right);
2143 *out = ir_phi_value(phi);
2147 if (!OPTS_FLAG(PERL_LOGIC)) {
2149 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2150 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2151 ast_function_label(func, "sce_bool_v"),
2155 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2156 ast_function_label(func, "sce_bool"),
2161 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2162 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2163 ast_function_label(func, "sce_bool_s"),
2167 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2168 ast_function_label(func, "sce_bool"),
2174 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2175 ast_function_label(func, "sce_bool"),
2176 INSTR_AND, *out, *out);
2182 self->expression.outr = *out;
2183 codegen_output_type(self, *out);
2187 if (self->right_first) {
2188 cgen = self->right->codegen;
2189 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2191 cgen = self->left->codegen;
2192 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2195 cgen = self->left->codegen;
2196 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2198 cgen = self->right->codegen;
2199 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2203 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2204 self->op, left, right);
2207 self->expression.outr = *out;
2208 codegen_output_type(self, *out);
2213 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2215 ast_expression_codegen *cgen;
2216 ir_value *leftl = NULL, *leftr, *right, *bin;
2220 ast_array_index *ai = NULL;
2221 ir_value *iridx = NULL;
2223 if (lvalue && self->expression.outl) {
2224 *out = self->expression.outl;
2228 if (!lvalue && self->expression.outr) {
2229 *out = self->expression.outr;
2233 if (ast_istype(self->dest, ast_array_index))
2236 ai = (ast_array_index*)self->dest;
2237 idx = (ast_value*)ai->index;
2239 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2243 /* for a binstore we need both an lvalue and an rvalue for the left side */
2244 /* rvalue of destination! */
2246 cgen = idx->expression.codegen;
2247 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2250 cgen = self->dest->codegen;
2251 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2254 /* source as rvalue only */
2255 cgen = self->source->codegen;
2256 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2259 /* now the binary */
2260 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2261 self->opbin, leftr, right);
2262 self->expression.outr = bin;
2266 /* we need to call the setter */
2271 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2275 arr = (ast_value*)ai->array;
2276 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2277 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2281 cgen = arr->setter->expression.codegen;
2282 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2285 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2288 ir_call_param(call, iridx);
2289 ir_call_param(call, bin);
2290 self->expression.outr = bin;
2292 /* now store them */
2293 cgen = self->dest->codegen;
2294 /* lvalue of destination */
2295 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2297 self->expression.outl = leftl;
2299 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2301 self->expression.outr = bin;
2304 /* Theoretically, an assinment returns its left side as an
2305 * lvalue, if we don't need an lvalue though, we return
2306 * the right side as an rvalue, otherwise we have to
2307 * somehow know whether or not we need to dereference the pointer
2308 * on the left side - that is: OP_LOAD if it was an address.
2309 * Also: in original QC we cannot OP_LOADP *anyway*.
2311 *out = (lvalue ? leftl : bin);
2316 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2318 ast_expression_codegen *cgen;
2321 /* An unary operation cannot yield an l-value */
2323 compile_error(ast_ctx(self), "not an l-value (binop)");
2327 if (self->expression.outr) {
2328 *out = self->expression.outr;
2332 cgen = self->operand->codegen;
2334 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2337 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2341 self->expression.outr = *out;
2346 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2348 ast_expression_codegen *cgen;
2353 /* In the context of a return operation, we don't actually return
2357 compile_error(ast_ctx(self), "return-expression is not an l-value");
2361 if (self->expression.outr) {
2362 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2365 self->expression.outr = (ir_value*)1;
2367 if (self->operand) {
2368 cgen = self->operand->codegen;
2370 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2373 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2376 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2383 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2385 ast_expression_codegen *cgen;
2386 ir_value *ent, *field;
2388 /* This function needs to take the 'lvalue' flag into account!
2389 * As lvalue we provide a field-pointer, as rvalue we provide the
2393 if (lvalue && self->expression.outl) {
2394 *out = self->expression.outl;
2398 if (!lvalue && self->expression.outr) {
2399 *out = self->expression.outr;
2403 cgen = self->entity->codegen;
2404 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2407 cgen = self->field->codegen;
2408 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2413 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2416 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2417 ent, field, self->expression.vtype);
2418 /* Done AFTER error checking:
2419 codegen_output_type(self, *out);
2423 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2424 (lvalue ? "ADDRESS" : "FIELD"),
2425 type_name[self->expression.vtype]);
2429 codegen_output_type(self, *out);
2432 self->expression.outl = *out;
2434 self->expression.outr = *out;
2436 /* Hm that should be it... */
2440 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2442 ast_expression_codegen *cgen;
2445 /* in QC this is always an lvalue */
2446 if (lvalue && self->rvalue) {
2447 compile_error(ast_ctx(self), "not an l-value (member access)");
2450 if (self->expression.outl) {
2451 *out = self->expression.outl;
2455 cgen = self->owner->codegen;
2456 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2459 if (vec->vtype != TYPE_VECTOR &&
2460 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2465 *out = ir_value_vector_member(vec, self->field);
2466 self->expression.outl = *out;
2468 return (*out != NULL);
2471 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2476 if (!lvalue && self->expression.outr) {
2477 *out = self->expression.outr;
2480 if (lvalue && self->expression.outl) {
2481 *out = self->expression.outl;
2485 if (!ast_istype(self->array, ast_value)) {
2486 compile_error(ast_ctx(self), "array indexing this way is not supported");
2487 /* note this would actually be pointer indexing because the left side is
2488 * not an actual array but (hopefully) an indexable expression.
2489 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2490 * support this path will be filled.
2495 arr = (ast_value*)self->array;
2496 idx = (ast_value*)self->index;
2498 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2499 /* Time to use accessor functions */
2500 ast_expression_codegen *cgen;
2501 ir_value *iridx, *funval;
2505 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2510 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2514 cgen = self->index->codegen;
2515 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2518 cgen = arr->getter->expression.codegen;
2519 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2522 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2525 ir_call_param(call, iridx);
2527 *out = ir_call_value(call);
2528 self->expression.outr = *out;
2529 (*out)->vtype = self->expression.vtype;
2530 codegen_output_type(self, *out);
2534 if (idx->expression.vtype == TYPE_FLOAT) {
2535 unsigned int arridx = idx->constval.vfloat;
2536 if (arridx >= self->array->count)
2538 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2541 *out = arr->ir_values[arridx];
2543 else if (idx->expression.vtype == TYPE_INTEGER) {
2544 unsigned int arridx = idx->constval.vint;
2545 if (arridx >= self->array->count)
2547 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2550 *out = arr->ir_values[arridx];
2553 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2556 (*out)->vtype = self->expression.vtype;
2557 codegen_output_type(self, *out);
2561 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2565 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2570 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2574 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2576 ast_expression_codegen *cgen;
2584 ir_block *ontrue_endblock = NULL;
2585 ir_block *onfalse_endblock = NULL;
2586 ir_block *merge = NULL;
2589 /* We don't output any value, thus also don't care about r/lvalue */
2593 if (self->expression.outr) {
2594 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2597 self->expression.outr = (ir_value*)1;
2599 /* generate the condition */
2600 cgen = self->cond->codegen;
2601 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2603 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2604 cond = func->curblock;
2606 /* try constant folding away the condition */
2607 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2610 if (self->on_true) {
2611 /* create on-true block */
2612 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2616 /* enter the block */
2617 func->curblock = ontrue;
2620 cgen = self->on_true->codegen;
2621 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2624 /* we now need to work from the current endpoint */
2625 ontrue_endblock = func->curblock;
2630 if (self->on_false) {
2631 /* create on-false block */
2632 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2636 /* enter the block */
2637 func->curblock = onfalse;
2640 cgen = self->on_false->codegen;
2641 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2644 /* we now need to work from the current endpoint */
2645 onfalse_endblock = func->curblock;
2649 /* Merge block were they all merge in to */
2650 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2652 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2655 /* add jumps ot the merge block */
2656 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2658 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2661 /* Now enter the merge block */
2662 func->curblock = merge;
2665 /* we create the if here, that way all blocks are ordered :)
2667 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2668 (ontrue ? ontrue : merge),
2669 (onfalse ? onfalse : merge)))
2677 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2679 ast_expression_codegen *cgen;
2682 ir_value *trueval, *falseval;
2685 ir_block *cond = func->curblock;
2686 ir_block *cond_out = NULL;
2687 ir_block *ontrue, *ontrue_out = NULL;
2688 ir_block *onfalse, *onfalse_out = NULL;
2692 /* Ternary can never create an lvalue... */
2696 /* In theory it shouldn't be possible to pass through a node twice, but
2697 * in case we add any kind of optimization pass for the AST itself, it
2698 * may still happen, thus we remember a created ir_value and simply return one
2699 * if it already exists.
2701 if (self->expression.outr) {
2702 *out = self->expression.outr;
2706 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2708 /* generate the condition */
2709 func->curblock = cond;
2710 cgen = self->cond->codegen;
2711 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2713 cond_out = func->curblock;
2715 /* try constant folding away the condition */
2716 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2719 /* create on-true block */
2720 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2725 /* enter the block */
2726 func->curblock = ontrue;
2729 cgen = self->on_true->codegen;
2730 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2733 ontrue_out = func->curblock;
2736 /* create on-false block */
2737 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2742 /* enter the block */
2743 func->curblock = onfalse;
2746 cgen = self->on_false->codegen;
2747 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2750 onfalse_out = func->curblock;
2753 /* create merge block */
2754 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2757 /* jump to merge block */
2758 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2760 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2763 /* create if instruction */
2764 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2767 /* Now enter the merge block */
2768 func->curblock = merge;
2770 /* Here, now, we need a PHI node
2771 * but first some sanity checking...
2773 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2774 /* error("ternary with different types on the two sides"); */
2775 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2780 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2782 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2785 ir_phi_add(phi, ontrue_out, trueval);
2786 ir_phi_add(phi, onfalse_out, falseval);
2788 self->expression.outr = ir_phi_value(phi);
2789 *out = self->expression.outr;
2791 codegen_output_type(self, *out);
2796 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2798 ast_expression_codegen *cgen;
2800 ir_value *dummy = NULL;
2801 ir_value *precond = NULL;
2802 ir_value *postcond = NULL;
2804 /* Since we insert some jumps "late" so we have blocks
2805 * ordered "nicely", we need to keep track of the actual end-blocks
2806 * of expressions to add the jumps to.
2808 ir_block *bbody = NULL, *end_bbody = NULL;
2809 ir_block *bprecond = NULL, *end_bprecond = NULL;
2810 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2811 ir_block *bincrement = NULL, *end_bincrement = NULL;
2812 ir_block *bout = NULL, *bin = NULL;
2814 /* let's at least move the outgoing block to the end */
2817 /* 'break' and 'continue' need to be able to find the right blocks */
2818 ir_block *bcontinue = NULL;
2819 ir_block *bbreak = NULL;
2821 ir_block *tmpblock = NULL;
2826 if (self->expression.outr) {
2827 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2830 self->expression.outr = (ir_value*)1;
2833 * Should we ever need some kind of block ordering, better make this function
2834 * move blocks around than write a block ordering algorithm later... after all
2835 * the ast and ir should work together, not against each other.
2838 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2839 * anyway if for example it contains a ternary.
2843 cgen = self->initexpr->codegen;
2844 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2848 /* Store the block from which we enter this chaos */
2849 bin = func->curblock;
2851 /* The pre-loop condition needs its own block since we
2852 * need to be able to jump to the start of that expression.
2856 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2860 /* the pre-loop-condition the least important place to 'continue' at */
2861 bcontinue = bprecond;
2864 func->curblock = bprecond;
2867 cgen = self->precond->codegen;
2868 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2871 end_bprecond = func->curblock;
2873 bprecond = end_bprecond = NULL;
2876 /* Now the next blocks won't be ordered nicely, but we need to
2877 * generate them this early for 'break' and 'continue'.
2879 if (self->increment) {
2880 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2883 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2885 bincrement = end_bincrement = NULL;
2888 if (self->postcond) {
2889 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2892 bcontinue = bpostcond; /* postcond comes before the increment */
2894 bpostcond = end_bpostcond = NULL;
2897 bout_id = vec_size(func->ir_func->blocks);
2898 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2903 /* The loop body... */
2904 /* if (self->body) */
2906 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2911 func->curblock = bbody;
2913 vec_push(func->breakblocks, bbreak);
2915 vec_push(func->continueblocks, bcontinue);
2917 vec_push(func->continueblocks, bbody);
2921 cgen = self->body->codegen;
2922 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2926 end_bbody = func->curblock;
2927 vec_pop(func->breakblocks);
2928 vec_pop(func->continueblocks);
2931 /* post-loop-condition */
2935 func->curblock = bpostcond;
2938 cgen = self->postcond->codegen;
2939 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2942 end_bpostcond = func->curblock;
2945 /* The incrementor */
2946 if (self->increment)
2949 func->curblock = bincrement;
2952 cgen = self->increment->codegen;
2953 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2956 end_bincrement = func->curblock;
2959 /* In any case now, we continue from the outgoing block */
2960 func->curblock = bout;
2962 /* Now all blocks are in place */
2963 /* From 'bin' we jump to whatever comes first */
2964 if (bprecond) tmpblock = bprecond;
2965 else tmpblock = bbody; /* can never be null */
2968 else if (bpostcond) tmpblock = bpostcond;
2969 else tmpblock = bout;
2972 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2978 ir_block *ontrue, *onfalse;
2979 ontrue = bbody; /* can never be null */
2981 /* all of this is dead code
2982 else if (bincrement) ontrue = bincrement;
2983 else ontrue = bpostcond;
2987 if (self->pre_not) {
2992 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2999 if (bincrement) tmpblock = bincrement;
3000 else if (bpostcond) tmpblock = bpostcond;
3001 else if (bprecond) tmpblock = bprecond;
3002 else tmpblock = bbody;
3003 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3007 /* from increment */
3010 if (bpostcond) tmpblock = bpostcond;
3011 else if (bprecond) tmpblock = bprecond;
3012 else if (bbody) tmpblock = bbody;
3013 else tmpblock = bout;
3014 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3021 ir_block *ontrue, *onfalse;
3022 if (bprecond) ontrue = bprecond;
3023 else ontrue = bbody; /* can never be null */
3025 /* all of this is dead code
3026 else if (bincrement) ontrue = bincrement;
3027 else ontrue = bpostcond;
3031 if (self->post_not) {
3036 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3040 /* Move 'bout' to the end */
3041 vec_remove(func->ir_func->blocks, bout_id, 1);
3042 vec_push(func->ir_func->blocks, bout);
3047 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3054 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3058 if (self->expression.outr) {
3059 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3062 self->expression.outr = (ir_value*)1;
3064 if (self->is_continue)
3065 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3067 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3070 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3074 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3079 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3081 ast_expression_codegen *cgen;
3083 ast_switch_case *def_case = NULL;
3084 ir_block *def_bfall = NULL;
3085 ir_block *def_bfall_to = NULL;
3086 bool set_def_bfall_to = false;
3088 ir_value *dummy = NULL;
3089 ir_value *irop = NULL;
3090 ir_block *bout = NULL;
3091 ir_block *bfall = NULL;
3099 compile_error(ast_ctx(self), "switch expression is not an l-value");
3103 if (self->expression.outr) {
3104 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3107 self->expression.outr = (ir_value*)1;
3112 cgen = self->operand->codegen;
3113 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3116 if (!vec_size(self->cases))
3119 cmpinstr = type_eq_instr[irop->vtype];
3120 if (cmpinstr >= VINSTR_END) {
3121 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3122 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3126 bout_id = vec_size(func->ir_func->blocks);
3127 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3131 /* setup the break block */
3132 vec_push(func->breakblocks, bout);
3134 /* Now create all cases */
3135 for (c = 0; c < vec_size(self->cases); ++c) {
3136 ir_value *cond, *val;
3137 ir_block *bcase, *bnot;
3140 ast_switch_case *swcase = &self->cases[c];
3142 if (swcase->value) {
3143 /* A regular case */
3144 /* generate the condition operand */
3145 cgen = swcase->value->codegen;
3146 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3148 /* generate the condition */
3149 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3153 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3154 bnot_id = vec_size(func->ir_func->blocks);
3155 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3156 if (!bcase || !bnot)
3158 if (set_def_bfall_to) {
3159 set_def_bfall_to = false;
3160 def_bfall_to = bcase;
3162 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3165 /* Make the previous case-end fall through */
3166 if (bfall && !bfall->final) {
3167 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3171 /* enter the case */
3172 func->curblock = bcase;
3173 cgen = swcase->code->codegen;
3174 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3177 /* remember this block to fall through from */
3178 bfall = func->curblock;
3180 /* enter the else and move it down */
3181 func->curblock = bnot;
3182 vec_remove(func->ir_func->blocks, bnot_id, 1);
3183 vec_push(func->ir_func->blocks, bnot);
3185 /* The default case */
3186 /* Remember where to fall through from: */
3189 /* remember which case it was */
3191 /* And the next case will be remembered */
3192 set_def_bfall_to = true;
3196 /* Jump from the last bnot to bout */
3197 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3199 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3204 /* If there was a default case, put it down here */
3208 /* No need to create an extra block */
3209 bcase = func->curblock;
3211 /* Insert the fallthrough jump */
3212 if (def_bfall && !def_bfall->final) {
3213 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3217 /* Now generate the default code */
3218 cgen = def_case->code->codegen;
3219 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3222 /* see if we need to fall through */
3223 if (def_bfall_to && !func->curblock->final)
3225 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3230 /* Jump from the last bnot to bout */
3231 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3233 /* enter the outgoing block */
3234 func->curblock = bout;
3236 /* restore the break block */
3237 vec_pop(func->breakblocks);
3239 /* Move 'bout' to the end, it's nicer */
3240 vec_remove(func->ir_func->blocks, bout_id, 1);
3241 vec_push(func->ir_func->blocks, bout);
3246 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3251 if (self->undefined) {
3252 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3258 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3262 /* simply create a new block and jump to it */
3263 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3264 if (!self->irblock) {
3265 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3268 if (!func->curblock->final) {
3269 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3273 /* enter the new block */
3274 func->curblock = self->irblock;
3276 /* Generate all the leftover gotos */
3277 for (i = 0; i < vec_size(self->gotos); ++i) {
3278 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3285 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3289 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3293 if (self->target->irblock) {
3294 if (self->irblock_from) {
3295 /* we already tried once, this is the callback */
3296 self->irblock_from->final = false;
3297 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3298 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3304 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3305 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3312 /* the target has not yet been created...
3313 * close this block in a sneaky way:
3315 func->curblock->final = true;
3316 self->irblock_from = func->curblock;
3317 ast_label_register_goto(self->target, self);
3323 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3325 ast_expression_codegen *cgen;
3327 ir_instr *callinstr;
3330 ir_value *funval = NULL;
3332 /* return values are never lvalues */
3334 compile_error(ast_ctx(self), "not an l-value (function call)");
3338 if (self->expression.outr) {
3339 *out = self->expression.outr;
3343 cgen = self->func->codegen;
3344 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3352 for (i = 0; i < vec_size(self->params); ++i)
3355 ast_expression *expr = self->params[i];
3357 cgen = expr->codegen;
3358 if (!(*cgen)(expr, func, false, ¶m))
3362 vec_push(params, param);
3365 /* varargs counter */
3366 if (self->va_count) {
3368 ir_builder *builder = func->curblock->owner->owner;
3369 cgen = self->va_count->codegen;
3370 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3372 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3373 ir_builder_get_va_count(builder), va_count))
3379 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3380 ast_function_label(func, "call"),
3381 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3385 for (i = 0; i < vec_size(params); ++i) {
3386 ir_call_param(callinstr, params[i]);
3389 *out = ir_call_value(callinstr);
3390 self->expression.outr = *out;
3392 codegen_output_type(self, *out);