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);
444 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
445 ast_expression *normal = ((ast_unary*)right)->operand;
447 /* make a-(-b) => a + b */
448 if (op == INSTR_SUB_F) {
451 ++opts_optimizationcount[OPTIM_PEEPHOLE];
452 } else if (op == INSTR_SUB_V) {
455 ++opts_optimizationcount[OPTIM_PEEPHOLE];
462 self->right_first = false;
464 ast_propagate_effects(self, left);
465 ast_propagate_effects(self, right);
467 if (op >= INSTR_EQ_F && op <= INSTR_GT)
468 self->expression.vtype = TYPE_FLOAT;
469 else if (op == INSTR_AND || op == INSTR_OR) {
470 if (OPTS_FLAG(PERL_LOGIC))
471 ast_type_adopt(self, right);
473 self->expression.vtype = TYPE_FLOAT;
475 else if (op == INSTR_BITAND || op == INSTR_BITOR)
476 self->expression.vtype = TYPE_FLOAT;
477 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
478 self->expression.vtype = TYPE_VECTOR;
479 else if (op == INSTR_MUL_V)
480 self->expression.vtype = TYPE_FLOAT;
482 self->expression.vtype = left->vtype;
485 self->refs = AST_REF_ALL;
490 void ast_binary_delete(ast_binary *self)
492 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
493 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
495 ast_expression_delete((ast_expression*)self);
499 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
500 ast_expression* left, ast_expression* right)
502 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
503 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
505 ast_side_effects(self) = true;
507 self->opstore = storop;
510 self->source = right;
512 self->keep_dest = false;
514 ast_type_adopt(self, left);
518 void ast_binstore_delete(ast_binstore *self)
520 if (!self->keep_dest)
521 ast_unref(self->dest);
522 ast_unref(self->source);
523 ast_expression_delete((ast_expression*)self);
527 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
528 ast_expression *expr)
530 ast_instantiate(ast_unary, ctx, ast_unary_delete);
531 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
534 self->operand = expr;
537 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
538 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
540 /* Handle for double negation */
541 if (((ast_unary*)expr)->op == op)
542 prev = (ast_unary*)((ast_unary*)expr)->operand;
544 if (ast_istype(prev, ast_unary)) {
545 ast_expression_delete((ast_expression*)self);
547 ++opts_optimizationcount[OPTIM_PEEPHOLE];
552 ast_propagate_effects(self, expr);
554 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
555 self->expression.vtype = TYPE_FLOAT;
556 } else if (op == VINSTR_NEG_V) {
557 self->expression.vtype = TYPE_VECTOR;
559 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
565 void ast_unary_delete(ast_unary *self)
567 if (self->operand) ast_unref(self->operand);
568 ast_expression_delete((ast_expression*)self);
572 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
574 ast_instantiate(ast_return, ctx, ast_return_delete);
575 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
577 self->operand = expr;
580 ast_propagate_effects(self, expr);
585 void ast_return_delete(ast_return *self)
588 ast_unref(self->operand);
589 ast_expression_delete((ast_expression*)self);
593 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
595 if (field->vtype != TYPE_FIELD) {
596 compile_error(ctx, "ast_entfield_new with expression not of type field");
599 return ast_entfield_new_force(ctx, entity, field, field->next);
602 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
604 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
608 /* Error: field has no type... */
612 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
614 self->entity = entity;
616 ast_propagate_effects(self, entity);
617 ast_propagate_effects(self, field);
619 ast_type_adopt(self, outtype);
623 void ast_entfield_delete(ast_entfield *self)
625 ast_unref(self->entity);
626 ast_unref(self->field);
627 ast_expression_delete((ast_expression*)self);
631 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
633 ast_instantiate(ast_member, ctx, ast_member_delete);
639 if (owner->vtype != TYPE_VECTOR &&
640 owner->vtype != TYPE_FIELD) {
641 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
646 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
647 self->expression.node.keep = true; /* keep */
649 if (owner->vtype == TYPE_VECTOR) {
650 self->expression.vtype = TYPE_FLOAT;
651 self->expression.next = NULL;
653 self->expression.vtype = TYPE_FIELD;
654 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
657 self->rvalue = false;
659 ast_propagate_effects(self, owner);
663 self->name = util_strdup(name);
670 void ast_member_delete(ast_member *self)
672 /* The owner is always an ast_value, which has .keep=true,
673 * also: ast_members are usually deleted after the owner, thus
674 * this will cause invalid access
675 ast_unref(self->owner);
676 * once we allow (expression).x to access a vector-member, we need
677 * to change this: preferably by creating an alternate ast node for this
678 * purpose that is not garbage-collected.
680 ast_expression_delete((ast_expression*)self);
685 bool ast_member_set_name(ast_member *self, const char *name)
688 mem_d((void*)self->name);
689 self->name = util_strdup(name);
693 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
695 ast_expression *outtype;
696 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
698 outtype = array->next;
701 /* Error: field has no type... */
705 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
709 ast_propagate_effects(self, array);
710 ast_propagate_effects(self, index);
712 ast_type_adopt(self, outtype);
713 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
714 if (self->expression.vtype != TYPE_ARRAY) {
715 compile_error(ast_ctx(self), "array_index node on type");
716 ast_array_index_delete(self);
719 self->array = outtype;
720 self->expression.vtype = TYPE_FIELD;
726 void ast_array_index_delete(ast_array_index *self)
729 ast_unref(self->array);
731 ast_unref(self->index);
732 ast_expression_delete((ast_expression*)self);
736 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
738 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
739 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
741 self->expression.vtype = TYPE_NOEXPR;
745 void ast_argpipe_delete(ast_argpipe *self)
748 ast_unref(self->index);
749 ast_expression_delete((ast_expression*)self);
753 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
755 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
756 if (!ontrue && !onfalse) {
757 /* because it is invalid */
761 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
764 self->on_true = ontrue;
765 self->on_false = onfalse;
766 ast_propagate_effects(self, cond);
768 ast_propagate_effects(self, ontrue);
770 ast_propagate_effects(self, onfalse);
775 void ast_ifthen_delete(ast_ifthen *self)
777 ast_unref(self->cond);
779 ast_unref(self->on_true);
781 ast_unref(self->on_false);
782 ast_expression_delete((ast_expression*)self);
786 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
788 ast_expression *exprtype = ontrue;
789 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
790 /* This time NEITHER must be NULL */
791 if (!ontrue || !onfalse) {
795 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
798 self->on_true = ontrue;
799 self->on_false = onfalse;
800 ast_propagate_effects(self, cond);
801 ast_propagate_effects(self, ontrue);
802 ast_propagate_effects(self, onfalse);
804 if (ontrue->vtype == TYPE_NIL)
806 ast_type_adopt(self, exprtype);
811 void ast_ternary_delete(ast_ternary *self)
813 /* the if()s are only there because computed-gotos can set them
816 if (self->cond) ast_unref(self->cond);
817 if (self->on_true) ast_unref(self->on_true);
818 if (self->on_false) ast_unref(self->on_false);
819 ast_expression_delete((ast_expression*)self);
823 ast_loop* ast_loop_new(lex_ctx_t ctx,
824 ast_expression *initexpr,
825 ast_expression *precond, bool pre_not,
826 ast_expression *postcond, bool post_not,
827 ast_expression *increment,
828 ast_expression *body)
830 ast_instantiate(ast_loop, ctx, ast_loop_delete);
831 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
833 self->initexpr = initexpr;
834 self->precond = precond;
835 self->postcond = postcond;
836 self->increment = increment;
839 self->pre_not = pre_not;
840 self->post_not = post_not;
843 ast_propagate_effects(self, initexpr);
845 ast_propagate_effects(self, precond);
847 ast_propagate_effects(self, postcond);
849 ast_propagate_effects(self, increment);
851 ast_propagate_effects(self, body);
856 void ast_loop_delete(ast_loop *self)
859 ast_unref(self->initexpr);
861 ast_unref(self->precond);
863 ast_unref(self->postcond);
865 ast_unref(self->increment);
867 ast_unref(self->body);
868 ast_expression_delete((ast_expression*)self);
872 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
874 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
875 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
877 self->is_continue = iscont;
878 self->levels = levels;
883 void ast_breakcont_delete(ast_breakcont *self)
885 ast_expression_delete((ast_expression*)self);
889 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
891 ast_instantiate(ast_switch, ctx, ast_switch_delete);
892 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
897 ast_propagate_effects(self, op);
902 void ast_switch_delete(ast_switch *self)
905 ast_unref(self->operand);
907 for (i = 0; i < vec_size(self->cases); ++i) {
908 if (self->cases[i].value)
909 ast_unref(self->cases[i].value);
910 ast_unref(self->cases[i].code);
912 vec_free(self->cases);
914 ast_expression_delete((ast_expression*)self);
918 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
920 ast_instantiate(ast_label, ctx, ast_label_delete);
921 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
923 self->expression.vtype = TYPE_NOEXPR;
925 self->name = util_strdup(name);
926 self->irblock = NULL;
928 self->undefined = undefined;
933 void ast_label_delete(ast_label *self)
935 mem_d((void*)self->name);
936 vec_free(self->gotos);
937 ast_expression_delete((ast_expression*)self);
941 static void ast_label_register_goto(ast_label *self, ast_goto *g)
943 vec_push(self->gotos, g);
946 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
948 ast_instantiate(ast_goto, ctx, ast_goto_delete);
949 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
951 self->name = util_strdup(name);
953 self->irblock_from = NULL;
958 void ast_goto_delete(ast_goto *self)
960 mem_d((void*)self->name);
961 ast_expression_delete((ast_expression*)self);
965 void ast_goto_set_label(ast_goto *self, ast_label *label)
967 self->target = label;
970 ast_call* ast_call_new(lex_ctx_t ctx,
971 ast_expression *funcexpr)
973 ast_instantiate(ast_call, ctx, ast_call_delete);
974 if (!funcexpr->next) {
975 compile_error(ctx, "not a function");
979 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
981 ast_side_effects(self) = true;
984 self->func = funcexpr;
985 self->va_count = NULL;
987 ast_type_adopt(self, funcexpr->next);
992 void ast_call_delete(ast_call *self)
995 for (i = 0; i < vec_size(self->params); ++i)
996 ast_unref(self->params[i]);
997 vec_free(self->params);
1000 ast_unref(self->func);
1003 ast_unref(self->va_count);
1005 ast_expression_delete((ast_expression*)self);
1009 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1015 if (!va_type || !ast_compare_type(va_type, exp_type))
1017 if (va_type && exp_type)
1019 ast_type_to_string(va_type, tgot, sizeof(tgot));
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 differs in type: constrained to type %s, expected type %s",
1027 compile_error(ast_ctx(self),
1028 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1035 ast_type_to_string(exp_type, texp, sizeof(texp));
1036 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1037 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1038 "piped variadic argument may differ in type: expected type %s",
1042 compile_error(ast_ctx(self),
1043 "piped variadic argument may differ in type: expected type %s",
1052 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1058 const ast_expression *func = self->func;
1059 size_t count = vec_size(self->params);
1060 if (count > vec_size(func->params))
1061 count = vec_size(func->params);
1063 for (i = 0; i < count; ++i) {
1064 if (ast_istype(self->params[i], ast_argpipe)) {
1065 /* warn about type safety instead */
1067 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1070 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1073 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1075 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1076 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1077 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1078 (unsigned int)(i+1), texp, tgot);
1079 /* we don't immediately return */
1083 count = vec_size(self->params);
1084 if (count > vec_size(func->params) && func->varparam) {
1085 for (; i < count; ++i) {
1086 if (ast_istype(self->params[i], ast_argpipe)) {
1087 /* warn about type safety instead */
1089 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1092 if (!ast_call_check_vararg(self, va_type, func->varparam))
1095 else if (!ast_compare_type(self->params[i], func->varparam))
1097 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1098 ast_type_to_string(func->varparam, texp, sizeof(texp));
1099 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1100 (unsigned int)(i+1), texp, tgot);
1101 /* we don't immediately return */
1109 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1110 ast_expression *dest, ast_expression *source)
1112 ast_instantiate(ast_store, ctx, ast_store_delete);
1113 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1115 ast_side_effects(self) = true;
1119 self->source = source;
1121 ast_type_adopt(self, dest);
1126 void ast_store_delete(ast_store *self)
1128 ast_unref(self->dest);
1129 ast_unref(self->source);
1130 ast_expression_delete((ast_expression*)self);
1134 ast_block* ast_block_new(lex_ctx_t ctx)
1136 ast_instantiate(ast_block, ctx, ast_block_delete);
1137 ast_expression_init((ast_expression*)self,
1138 (ast_expression_codegen*)&ast_block_codegen);
1140 self->locals = NULL;
1142 self->collect = NULL;
1147 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1149 ast_propagate_effects(self, e);
1150 vec_push(self->exprs, e);
1151 if (self->expression.next) {
1152 ast_delete(self->expression.next);
1153 self->expression.next = NULL;
1155 ast_type_adopt(self, e);
1159 void ast_block_collect(ast_block *self, ast_expression *expr)
1161 vec_push(self->collect, expr);
1162 expr->node.keep = true;
1165 void ast_block_delete(ast_block *self)
1168 for (i = 0; i < vec_size(self->exprs); ++i)
1169 ast_unref(self->exprs[i]);
1170 vec_free(self->exprs);
1171 for (i = 0; i < vec_size(self->locals); ++i)
1172 ast_delete(self->locals[i]);
1173 vec_free(self->locals);
1174 for (i = 0; i < vec_size(self->collect); ++i)
1175 ast_delete(self->collect[i]);
1176 vec_free(self->collect);
1177 ast_expression_delete((ast_expression*)self);
1181 void ast_block_set_type(ast_block *self, ast_expression *from)
1183 if (self->expression.next)
1184 ast_delete(self->expression.next);
1185 ast_type_adopt(self, from);
1188 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1190 ast_instantiate(ast_function, ctx, ast_function_delete);
1193 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1195 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1196 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1198 (int)vtype->hasvalue,
1199 vtype->expression.vtype);
1203 self->vtype = vtype;
1204 self->name = name ? util_strdup(name) : NULL;
1205 self->blocks = NULL;
1207 self->labelcount = 0;
1210 self->ir_func = NULL;
1211 self->curblock = NULL;
1213 self->breakblocks = NULL;
1214 self->continueblocks = NULL;
1216 vtype->hasvalue = true;
1217 vtype->constval.vfunc = self;
1219 self->varargs = NULL;
1221 self->fixedparams = NULL;
1222 self->return_value = NULL;
1224 self->static_names = NULL;
1225 self->static_count = 0;
1234 void ast_function_delete(ast_function *self)
1238 mem_d((void*)self->name);
1240 /* ast_value_delete(self->vtype); */
1241 self->vtype->hasvalue = false;
1242 self->vtype->constval.vfunc = NULL;
1243 /* We use unref - if it was stored in a global table it is supposed
1244 * to be deleted from *there*
1246 ast_unref(self->vtype);
1248 for (i = 0; i < vec_size(self->static_names); ++i)
1249 mem_d(self->static_names[i]);
1250 vec_free(self->static_names);
1251 for (i = 0; i < vec_size(self->blocks); ++i)
1252 ast_delete(self->blocks[i]);
1253 vec_free(self->blocks);
1254 vec_free(self->breakblocks);
1255 vec_free(self->continueblocks);
1257 ast_delete(self->varargs);
1259 ast_delete(self->argc);
1260 if (self->fixedparams)
1261 ast_unref(self->fixedparams);
1262 if (self->return_value)
1263 ast_unref(self->return_value);
1267 const char* ast_function_label(ast_function *self, const char *prefix)
1273 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1274 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1275 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1280 id = (self->labelcount++);
1281 len = strlen(prefix);
1283 from = self->labelbuf + sizeof(self->labelbuf)-1;
1286 *from-- = (id%10) + '0';
1290 memcpy(from - len, prefix, len);
1294 /*********************************************************************/
1296 * by convention you must never pass NULL to the 'ir_value **out'
1297 * parameter. If you really don't care about the output, pass a dummy.
1298 * But I can't imagine a pituation where the output is truly unnecessary.
1301 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1303 if (out->vtype == TYPE_FIELD)
1304 out->fieldtype = self->next->vtype;
1305 if (out->vtype == TYPE_FUNCTION)
1306 out->outtype = self->next->vtype;
1309 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1311 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1315 if (self->expression.vtype == TYPE_NIL) {
1316 *out = func->ir_func->owner->nil;
1319 /* NOTE: This is the codegen for a variable used in an expression.
1320 * It is not the codegen to generate the value. For this purpose,
1321 * ast_local_codegen and ast_global_codegen are to be used before this
1322 * is executed. ast_function_codegen should take care of its locals,
1323 * and the ast-user should take care of ast_global_codegen to be used
1324 * on all the globals.
1327 char tname[1024]; /* typename is reserved in C++ */
1328 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1329 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1336 static bool ast_global_array_set(ast_value *self)
1338 size_t count = vec_size(self->initlist);
1341 if (count > self->expression.count) {
1342 compile_error(ast_ctx(self), "too many elements in initializer");
1343 count = self->expression.count;
1345 else if (count < self->expression.count) {
1347 compile_warning(ast_ctx(self), "not all elements are initialized");
1351 for (i = 0; i != count; ++i) {
1352 switch (self->expression.next->vtype) {
1354 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1358 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1362 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1366 /* we don't support them in any other place yet either */
1367 compile_error(ast_ctx(self), "TODO: nested arrays");
1370 /* this requiers a bit more work - similar to the fields I suppose */
1371 compile_error(ast_ctx(self), "global of type function not properly generated");
1374 if (!self->initlist[i].vfield) {
1375 compile_error(ast_ctx(self), "field constant without vfield set");
1378 if (!self->initlist[i].vfield->ir_v) {
1379 compile_error(ast_ctx(self), "field constant generated before its field");
1382 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1386 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1393 static bool check_array(ast_value *self, ast_value *array)
1395 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1396 compile_error(ast_ctx(self), "array without size: %s", self->name);
1399 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1400 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1401 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1407 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1411 if (self->expression.vtype == TYPE_NIL) {
1412 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1416 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1418 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1421 func->context = ast_ctx(self);
1422 func->value->context = ast_ctx(self);
1424 self->constval.vfunc->ir_func = func;
1425 self->ir_v = func->value;
1426 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1427 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1428 if (self->expression.flags & AST_FLAG_ERASEABLE)
1429 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1430 /* The function is filled later on ast_function_codegen... */
1434 if (isfield && self->expression.vtype == TYPE_FIELD) {
1435 ast_expression *fieldtype = self->expression.next;
1437 if (self->hasvalue) {
1438 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1442 if (fieldtype->vtype == TYPE_ARRAY) {
1447 ast_expression *elemtype;
1449 ast_value *array = (ast_value*)fieldtype;
1451 if (!ast_istype(fieldtype, ast_value)) {
1452 compile_error(ast_ctx(self), "internal error: ast_value required");
1456 if (!check_array(self, array))
1459 elemtype = array->expression.next;
1460 vtype = elemtype->vtype;
1462 v = ir_builder_create_field(ir, self->name, vtype);
1464 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1467 v->context = ast_ctx(self);
1468 v->unique_life = true;
1470 array->ir_v = self->ir_v = v;
1472 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1473 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1474 if (self->expression.flags & AST_FLAG_ERASEABLE)
1475 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1477 namelen = strlen(self->name);
1478 name = (char*)mem_a(namelen + 16);
1479 util_strncpy(name, self->name, namelen);
1481 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1482 array->ir_values[0] = v;
1483 for (ai = 1; ai < array->expression.count; ++ai) {
1484 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1485 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1486 if (!array->ir_values[ai]) {
1488 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1491 array->ir_values[ai]->context = ast_ctx(self);
1492 array->ir_values[ai]->unique_life = true;
1493 array->ir_values[ai]->locked = true;
1494 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1495 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1501 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1504 v->context = ast_ctx(self);
1506 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1507 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1509 if (self->expression.flags & AST_FLAG_ERASEABLE)
1510 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1515 if (self->expression.vtype == TYPE_ARRAY) {
1520 ast_expression *elemtype = self->expression.next;
1521 int vtype = elemtype->vtype;
1523 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1524 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1528 /* same as with field arrays */
1529 if (!check_array(self, self))
1532 v = ir_builder_create_global(ir, self->name, vtype);
1534 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1537 v->context = ast_ctx(self);
1538 v->unique_life = true;
1541 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1542 v->flags |= IR_FLAG_INCLUDE_DEF;
1543 if (self->expression.flags & AST_FLAG_ERASEABLE)
1544 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1546 namelen = strlen(self->name);
1547 name = (char*)mem_a(namelen + 16);
1548 util_strncpy(name, self->name, namelen);
1550 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1551 self->ir_values[0] = v;
1552 for (ai = 1; ai < self->expression.count; ++ai) {
1553 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1554 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1555 if (!self->ir_values[ai]) {
1557 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1560 self->ir_values[ai]->context = ast_ctx(self);
1561 self->ir_values[ai]->unique_life = true;
1562 self->ir_values[ai]->locked = true;
1563 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1564 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1570 /* Arrays don't do this since there's no "array" value which spans across the
1573 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1575 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1578 codegen_output_type(self, v);
1579 v->context = ast_ctx(self);
1582 /* link us to the ir_value */
1586 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1587 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1588 if (self->expression.flags & AST_FLAG_ERASEABLE)
1589 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1592 if (self->hasvalue) {
1593 switch (self->expression.vtype)
1596 if (!ir_value_set_float(v, self->constval.vfloat))
1600 if (!ir_value_set_vector(v, self->constval.vvec))
1604 if (!ir_value_set_string(v, self->constval.vstring))
1608 ast_global_array_set(self);
1611 compile_error(ast_ctx(self), "global of type function not properly generated");
1613 /* Cannot generate an IR value for a function,
1614 * need a pointer pointing to a function rather.
1617 if (!self->constval.vfield) {
1618 compile_error(ast_ctx(self), "field constant without vfield set");
1621 if (!self->constval.vfield->ir_v) {
1622 compile_error(ast_ctx(self), "field constant generated before its field");
1625 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1629 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1635 error: /* clean up */
1636 if(v) ir_value_delete(v);
1640 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1644 if (self->expression.vtype == TYPE_NIL) {
1645 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1649 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1651 /* Do we allow local functions? I think not...
1652 * this is NOT a function pointer atm.
1657 if (self->expression.vtype == TYPE_ARRAY) {
1662 ast_expression *elemtype = self->expression.next;
1663 int vtype = elemtype->vtype;
1665 func->flags |= IR_FLAG_HAS_ARRAYS;
1667 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1668 compile_error(ast_ctx(self), "array-parameters are not supported");
1672 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1673 if (!check_array(self, self))
1676 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1677 if (!self->ir_values) {
1678 compile_error(ast_ctx(self), "failed to allocate array values");
1682 v = ir_function_create_local(func, self->name, vtype, param);
1684 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1687 v->context = ast_ctx(self);
1688 v->unique_life = true;
1691 namelen = strlen(self->name);
1692 name = (char*)mem_a(namelen + 16);
1693 util_strncpy(name, self->name, namelen);
1695 self->ir_values[0] = v;
1696 for (ai = 1; ai < self->expression.count; ++ai) {
1697 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1698 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1699 if (!self->ir_values[ai]) {
1700 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1703 self->ir_values[ai]->context = ast_ctx(self);
1704 self->ir_values[ai]->unique_life = true;
1705 self->ir_values[ai]->locked = true;
1711 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1714 codegen_output_type(self, v);
1715 v->context = ast_ctx(self);
1718 /* A constant local... hmmm...
1719 * I suppose the IR will have to deal with this
1721 if (self->hasvalue) {
1722 switch (self->expression.vtype)
1725 if (!ir_value_set_float(v, self->constval.vfloat))
1729 if (!ir_value_set_vector(v, self->constval.vvec))
1733 if (!ir_value_set_string(v, self->constval.vstring))
1737 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1742 /* link us to the ir_value */
1746 if (!ast_generate_accessors(self, func->owner))
1750 error: /* clean up */
1755 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1758 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1759 if (!self->setter || !self->getter)
1761 for (i = 0; i < self->expression.count; ++i) {
1762 if (!self->ir_values) {
1763 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1766 if (!self->ir_values[i]) {
1767 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1770 if (self->ir_values[i]->life) {
1771 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1776 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1778 if (!ast_global_codegen (self->setter, ir, false) ||
1779 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1780 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1782 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1783 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1788 if (!ast_global_codegen (self->getter, ir, false) ||
1789 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1790 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1792 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1793 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1797 for (i = 0; i < self->expression.count; ++i) {
1798 vec_free(self->ir_values[i]->life);
1800 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1804 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1809 ast_expression_codegen *cgen;
1815 irf = self->ir_func;
1817 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1821 /* fill the parameter list */
1822 ec = &self->vtype->expression;
1823 for (i = 0; i < vec_size(ec->params); ++i)
1825 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1826 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1828 vec_push(irf->params, ec->params[i]->expression.vtype);
1829 if (!self->builtin) {
1830 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1835 if (self->varargs) {
1836 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1838 irf->max_varargs = self->varargs->expression.count;
1841 if (self->builtin) {
1842 irf->builtin = self->builtin;
1846 /* have a local return value variable? */
1847 if (self->return_value) {
1848 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1852 if (!vec_size(self->blocks)) {
1853 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1857 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1858 if (!self->curblock) {
1859 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1867 if (!ast_local_codegen(self->argc, self->ir_func, true))
1869 cgen = self->argc->expression.codegen;
1870 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1872 cgen = self->fixedparams->expression.codegen;
1873 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1875 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1876 ast_function_label(self, "va_count"), INSTR_SUB_F,
1877 ir_builder_get_va_count(ir), fixed);
1880 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1887 for (i = 0; i < vec_size(self->blocks); ++i) {
1888 cgen = self->blocks[i]->expression.codegen;
1889 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1893 /* TODO: check return types */
1894 if (!self->curblock->final)
1896 if (!self->vtype->expression.next ||
1897 self->vtype->expression.next->vtype == TYPE_VOID)
1899 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1901 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1903 if (self->return_value) {
1904 cgen = self->return_value->expression.codegen;
1905 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1907 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1909 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1910 "control reaches end of non-void function (`%s`) via %s",
1911 self->name, self->curblock->label))
1915 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1921 static bool starts_a_label(ast_expression *ex)
1923 while (ex && ast_istype(ex, ast_block)) {
1924 ast_block *b = (ast_block*)ex;
1929 return ast_istype(ex, ast_label);
1932 /* Note, you will not see ast_block_codegen generate ir_blocks.
1933 * To the AST and the IR, blocks are 2 different things.
1934 * In the AST it represents a block of code, usually enclosed in
1935 * curly braces {...}.
1936 * While in the IR it represents a block in terms of control-flow.
1938 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1942 /* We don't use this
1943 * Note: an ast-representation using the comma-operator
1944 * of the form: (a, b, c) = x should not assign to c...
1947 compile_error(ast_ctx(self), "not an l-value (code-block)");
1951 if (self->expression.outr) {
1952 *out = self->expression.outr;
1956 /* output is NULL at first, we'll have each expression
1957 * assign to out output, thus, a comma-operator represention
1958 * using an ast_block will return the last generated value,
1959 * so: (b, c) + a executed both b and c, and returns c,
1960 * which is then added to a.
1964 /* generate locals */
1965 for (i = 0; i < vec_size(self->locals); ++i)
1967 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1968 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1969 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1974 for (i = 0; i < vec_size(self->exprs); ++i)
1976 ast_expression_codegen *gen;
1977 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1978 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1982 gen = self->exprs[i]->codegen;
1983 if (!(*gen)(self->exprs[i], func, false, out))
1987 self->expression.outr = *out;
1992 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1994 ast_expression_codegen *cgen;
1995 ir_value *left = NULL;
1996 ir_value *right = NULL;
2000 ast_array_index *ai = NULL;
2002 if (lvalue && self->expression.outl) {
2003 *out = self->expression.outl;
2007 if (!lvalue && self->expression.outr) {
2008 *out = self->expression.outr;
2012 if (ast_istype(self->dest, ast_array_index))
2015 ai = (ast_array_index*)self->dest;
2016 idx = (ast_value*)ai->index;
2018 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2023 /* we need to call the setter */
2024 ir_value *iridx, *funval;
2028 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2032 arr = (ast_value*)ai->array;
2033 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2034 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2038 cgen = idx->expression.codegen;
2039 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2042 cgen = arr->setter->expression.codegen;
2043 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2046 cgen = self->source->codegen;
2047 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2050 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2053 ir_call_param(call, iridx);
2054 ir_call_param(call, right);
2055 self->expression.outr = right;
2061 cgen = self->dest->codegen;
2063 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2065 self->expression.outl = left;
2067 cgen = self->source->codegen;
2069 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2072 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2074 self->expression.outr = right;
2077 /* Theoretically, an assinment returns its left side as an
2078 * lvalue, if we don't need an lvalue though, we return
2079 * the right side as an rvalue, otherwise we have to
2080 * somehow know whether or not we need to dereference the pointer
2081 * on the left side - that is: OP_LOAD if it was an address.
2082 * Also: in original QC we cannot OP_LOADP *anyway*.
2084 *out = (lvalue ? left : right);
2089 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2091 ast_expression_codegen *cgen;
2092 ir_value *left, *right;
2094 /* A binary operation cannot yield an l-value */
2096 compile_error(ast_ctx(self), "not an l-value (binop)");
2100 if (self->expression.outr) {
2101 *out = self->expression.outr;
2105 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2106 (self->op == INSTR_AND || self->op == INSTR_OR))
2108 /* NOTE: The short-logic path will ignore right_first */
2110 /* short circuit evaluation */
2111 ir_block *other, *merge;
2112 ir_block *from_left, *from_right;
2116 /* prepare end-block */
2117 merge_id = vec_size(func->ir_func->blocks);
2118 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2120 /* generate the left expression */
2121 cgen = self->left->codegen;
2122 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2124 /* remember the block */
2125 from_left = func->curblock;
2127 /* create a new block for the right expression */
2128 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2129 if (self->op == INSTR_AND) {
2130 /* on AND: left==true -> other */
2131 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2134 /* on OR: left==false -> other */
2135 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2138 /* use the likely flag */
2139 vec_last(func->curblock->instr)->likely = true;
2141 /* enter the right-expression's block */
2142 func->curblock = other;
2144 cgen = self->right->codegen;
2145 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2147 /* remember block */
2148 from_right = func->curblock;
2150 /* jump to the merge block */
2151 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2154 vec_remove(func->ir_func->blocks, merge_id, 1);
2155 vec_push(func->ir_func->blocks, merge);
2157 func->curblock = merge;
2158 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2159 ast_function_label(func, "sce_value"),
2160 self->expression.vtype);
2161 ir_phi_add(phi, from_left, left);
2162 ir_phi_add(phi, from_right, right);
2163 *out = ir_phi_value(phi);
2167 if (!OPTS_FLAG(PERL_LOGIC)) {
2169 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2170 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2171 ast_function_label(func, "sce_bool_v"),
2175 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2176 ast_function_label(func, "sce_bool"),
2181 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2182 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2183 ast_function_label(func, "sce_bool_s"),
2187 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2188 ast_function_label(func, "sce_bool"),
2194 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2195 ast_function_label(func, "sce_bool"),
2196 INSTR_AND, *out, *out);
2202 self->expression.outr = *out;
2203 codegen_output_type(self, *out);
2207 if (self->right_first) {
2208 cgen = self->right->codegen;
2209 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2211 cgen = self->left->codegen;
2212 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2215 cgen = self->left->codegen;
2216 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2218 cgen = self->right->codegen;
2219 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2223 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2224 self->op, left, right);
2227 self->expression.outr = *out;
2228 codegen_output_type(self, *out);
2233 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2235 ast_expression_codegen *cgen;
2236 ir_value *leftl = NULL, *leftr, *right, *bin;
2240 ast_array_index *ai = NULL;
2241 ir_value *iridx = NULL;
2243 if (lvalue && self->expression.outl) {
2244 *out = self->expression.outl;
2248 if (!lvalue && self->expression.outr) {
2249 *out = self->expression.outr;
2253 if (ast_istype(self->dest, ast_array_index))
2256 ai = (ast_array_index*)self->dest;
2257 idx = (ast_value*)ai->index;
2259 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2263 /* for a binstore we need both an lvalue and an rvalue for the left side */
2264 /* rvalue of destination! */
2266 cgen = idx->expression.codegen;
2267 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2270 cgen = self->dest->codegen;
2271 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2274 /* source as rvalue only */
2275 cgen = self->source->codegen;
2276 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2279 /* now the binary */
2280 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2281 self->opbin, leftr, right);
2282 self->expression.outr = bin;
2286 /* we need to call the setter */
2291 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2295 arr = (ast_value*)ai->array;
2296 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2297 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2301 cgen = arr->setter->expression.codegen;
2302 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2305 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2308 ir_call_param(call, iridx);
2309 ir_call_param(call, bin);
2310 self->expression.outr = bin;
2312 /* now store them */
2313 cgen = self->dest->codegen;
2314 /* lvalue of destination */
2315 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2317 self->expression.outl = leftl;
2319 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2321 self->expression.outr = bin;
2324 /* Theoretically, an assinment returns its left side as an
2325 * lvalue, if we don't need an lvalue though, we return
2326 * the right side as an rvalue, otherwise we have to
2327 * somehow know whether or not we need to dereference the pointer
2328 * on the left side - that is: OP_LOAD if it was an address.
2329 * Also: in original QC we cannot OP_LOADP *anyway*.
2331 *out = (lvalue ? leftl : bin);
2336 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2338 ast_expression_codegen *cgen;
2341 /* An unary operation cannot yield an l-value */
2343 compile_error(ast_ctx(self), "not an l-value (binop)");
2347 if (self->expression.outr) {
2348 *out = self->expression.outr;
2352 cgen = self->operand->codegen;
2354 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2357 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2361 self->expression.outr = *out;
2366 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2368 ast_expression_codegen *cgen;
2373 /* In the context of a return operation, we don't actually return
2377 compile_error(ast_ctx(self), "return-expression is not an l-value");
2381 if (self->expression.outr) {
2382 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2385 self->expression.outr = (ir_value*)1;
2387 if (self->operand) {
2388 cgen = self->operand->codegen;
2390 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2393 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2396 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2403 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2405 ast_expression_codegen *cgen;
2406 ir_value *ent, *field;
2408 /* This function needs to take the 'lvalue' flag into account!
2409 * As lvalue we provide a field-pointer, as rvalue we provide the
2413 if (lvalue && self->expression.outl) {
2414 *out = self->expression.outl;
2418 if (!lvalue && self->expression.outr) {
2419 *out = self->expression.outr;
2423 cgen = self->entity->codegen;
2424 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2427 cgen = self->field->codegen;
2428 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2433 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2436 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2437 ent, field, self->expression.vtype);
2438 /* Done AFTER error checking:
2439 codegen_output_type(self, *out);
2443 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2444 (lvalue ? "ADDRESS" : "FIELD"),
2445 type_name[self->expression.vtype]);
2449 codegen_output_type(self, *out);
2452 self->expression.outl = *out;
2454 self->expression.outr = *out;
2456 /* Hm that should be it... */
2460 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2462 ast_expression_codegen *cgen;
2465 /* in QC this is always an lvalue */
2466 if (lvalue && self->rvalue) {
2467 compile_error(ast_ctx(self), "not an l-value (member access)");
2470 if (self->expression.outl) {
2471 *out = self->expression.outl;
2475 cgen = self->owner->codegen;
2476 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2479 if (vec->vtype != TYPE_VECTOR &&
2480 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2485 *out = ir_value_vector_member(vec, self->field);
2486 self->expression.outl = *out;
2488 return (*out != NULL);
2491 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2496 if (!lvalue && self->expression.outr) {
2497 *out = self->expression.outr;
2500 if (lvalue && self->expression.outl) {
2501 *out = self->expression.outl;
2505 if (!ast_istype(self->array, ast_value)) {
2506 compile_error(ast_ctx(self), "array indexing this way is not supported");
2507 /* note this would actually be pointer indexing because the left side is
2508 * not an actual array but (hopefully) an indexable expression.
2509 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2510 * support this path will be filled.
2515 arr = (ast_value*)self->array;
2516 idx = (ast_value*)self->index;
2518 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2519 /* Time to use accessor functions */
2520 ast_expression_codegen *cgen;
2521 ir_value *iridx, *funval;
2525 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2530 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2534 cgen = self->index->codegen;
2535 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2538 cgen = arr->getter->expression.codegen;
2539 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2542 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2545 ir_call_param(call, iridx);
2547 *out = ir_call_value(call);
2548 self->expression.outr = *out;
2549 (*out)->vtype = self->expression.vtype;
2550 codegen_output_type(self, *out);
2554 if (idx->expression.vtype == TYPE_FLOAT) {
2555 unsigned int arridx = idx->constval.vfloat;
2556 if (arridx >= self->array->count)
2558 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2561 *out = arr->ir_values[arridx];
2563 else if (idx->expression.vtype == TYPE_INTEGER) {
2564 unsigned int arridx = idx->constval.vint;
2565 if (arridx >= self->array->count)
2567 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2570 *out = arr->ir_values[arridx];
2573 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2576 (*out)->vtype = self->expression.vtype;
2577 codegen_output_type(self, *out);
2581 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2585 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2590 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2594 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2596 ast_expression_codegen *cgen;
2604 ir_block *ontrue_endblock = NULL;
2605 ir_block *onfalse_endblock = NULL;
2606 ir_block *merge = NULL;
2609 /* We don't output any value, thus also don't care about r/lvalue */
2613 if (self->expression.outr) {
2614 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2617 self->expression.outr = (ir_value*)1;
2619 /* generate the condition */
2620 cgen = self->cond->codegen;
2621 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2623 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2624 cond = func->curblock;
2626 /* try constant folding away the condition */
2627 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2630 if (self->on_true) {
2631 /* create on-true block */
2632 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2636 /* enter the block */
2637 func->curblock = ontrue;
2640 cgen = self->on_true->codegen;
2641 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2644 /* we now need to work from the current endpoint */
2645 ontrue_endblock = func->curblock;
2650 if (self->on_false) {
2651 /* create on-false block */
2652 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2656 /* enter the block */
2657 func->curblock = onfalse;
2660 cgen = self->on_false->codegen;
2661 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2664 /* we now need to work from the current endpoint */
2665 onfalse_endblock = func->curblock;
2669 /* Merge block were they all merge in to */
2670 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2672 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2675 /* add jumps ot the merge block */
2676 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2678 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2681 /* Now enter the merge block */
2682 func->curblock = merge;
2685 /* we create the if here, that way all blocks are ordered :)
2687 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2688 (ontrue ? ontrue : merge),
2689 (onfalse ? onfalse : merge)))
2697 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2699 ast_expression_codegen *cgen;
2702 ir_value *trueval, *falseval;
2705 ir_block *cond = func->curblock;
2706 ir_block *cond_out = NULL;
2707 ir_block *ontrue, *ontrue_out = NULL;
2708 ir_block *onfalse, *onfalse_out = NULL;
2712 /* Ternary can never create an lvalue... */
2716 /* In theory it shouldn't be possible to pass through a node twice, but
2717 * in case we add any kind of optimization pass for the AST itself, it
2718 * may still happen, thus we remember a created ir_value and simply return one
2719 * if it already exists.
2721 if (self->expression.outr) {
2722 *out = self->expression.outr;
2726 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2728 /* generate the condition */
2729 func->curblock = cond;
2730 cgen = self->cond->codegen;
2731 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2733 cond_out = func->curblock;
2735 /* try constant folding away the condition */
2736 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2739 /* create on-true block */
2740 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2745 /* enter the block */
2746 func->curblock = ontrue;
2749 cgen = self->on_true->codegen;
2750 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2753 ontrue_out = func->curblock;
2756 /* create on-false block */
2757 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2762 /* enter the block */
2763 func->curblock = onfalse;
2766 cgen = self->on_false->codegen;
2767 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2770 onfalse_out = func->curblock;
2773 /* create merge block */
2774 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2777 /* jump to merge block */
2778 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2780 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2783 /* create if instruction */
2784 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2787 /* Now enter the merge block */
2788 func->curblock = merge;
2790 /* Here, now, we need a PHI node
2791 * but first some sanity checking...
2793 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2794 /* error("ternary with different types on the two sides"); */
2795 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2800 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2802 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2805 ir_phi_add(phi, ontrue_out, trueval);
2806 ir_phi_add(phi, onfalse_out, falseval);
2808 self->expression.outr = ir_phi_value(phi);
2809 *out = self->expression.outr;
2811 codegen_output_type(self, *out);
2816 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2818 ast_expression_codegen *cgen;
2820 ir_value *dummy = NULL;
2821 ir_value *precond = NULL;
2822 ir_value *postcond = NULL;
2824 /* Since we insert some jumps "late" so we have blocks
2825 * ordered "nicely", we need to keep track of the actual end-blocks
2826 * of expressions to add the jumps to.
2828 ir_block *bbody = NULL, *end_bbody = NULL;
2829 ir_block *bprecond = NULL, *end_bprecond = NULL;
2830 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2831 ir_block *bincrement = NULL, *end_bincrement = NULL;
2832 ir_block *bout = NULL, *bin = NULL;
2834 /* let's at least move the outgoing block to the end */
2837 /* 'break' and 'continue' need to be able to find the right blocks */
2838 ir_block *bcontinue = NULL;
2839 ir_block *bbreak = NULL;
2841 ir_block *tmpblock = NULL;
2846 if (self->expression.outr) {
2847 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2850 self->expression.outr = (ir_value*)1;
2853 * Should we ever need some kind of block ordering, better make this function
2854 * move blocks around than write a block ordering algorithm later... after all
2855 * the ast and ir should work together, not against each other.
2858 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2859 * anyway if for example it contains a ternary.
2863 cgen = self->initexpr->codegen;
2864 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2868 /* Store the block from which we enter this chaos */
2869 bin = func->curblock;
2871 /* The pre-loop condition needs its own block since we
2872 * need to be able to jump to the start of that expression.
2876 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2880 /* the pre-loop-condition the least important place to 'continue' at */
2881 bcontinue = bprecond;
2884 func->curblock = bprecond;
2887 cgen = self->precond->codegen;
2888 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2891 end_bprecond = func->curblock;
2893 bprecond = end_bprecond = NULL;
2896 /* Now the next blocks won't be ordered nicely, but we need to
2897 * generate them this early for 'break' and 'continue'.
2899 if (self->increment) {
2900 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2903 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2905 bincrement = end_bincrement = NULL;
2908 if (self->postcond) {
2909 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2912 bcontinue = bpostcond; /* postcond comes before the increment */
2914 bpostcond = end_bpostcond = NULL;
2917 bout_id = vec_size(func->ir_func->blocks);
2918 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2923 /* The loop body... */
2924 /* if (self->body) */
2926 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2931 func->curblock = bbody;
2933 vec_push(func->breakblocks, bbreak);
2935 vec_push(func->continueblocks, bcontinue);
2937 vec_push(func->continueblocks, bbody);
2941 cgen = self->body->codegen;
2942 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2946 end_bbody = func->curblock;
2947 vec_pop(func->breakblocks);
2948 vec_pop(func->continueblocks);
2951 /* post-loop-condition */
2955 func->curblock = bpostcond;
2958 cgen = self->postcond->codegen;
2959 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2962 end_bpostcond = func->curblock;
2965 /* The incrementor */
2966 if (self->increment)
2969 func->curblock = bincrement;
2972 cgen = self->increment->codegen;
2973 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2976 end_bincrement = func->curblock;
2979 /* In any case now, we continue from the outgoing block */
2980 func->curblock = bout;
2982 /* Now all blocks are in place */
2983 /* From 'bin' we jump to whatever comes first */
2984 if (bprecond) tmpblock = bprecond;
2985 else tmpblock = bbody; /* can never be null */
2988 else if (bpostcond) tmpblock = bpostcond;
2989 else tmpblock = bout;
2992 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2998 ir_block *ontrue, *onfalse;
2999 ontrue = bbody; /* can never be null */
3001 /* all of this is dead code
3002 else if (bincrement) ontrue = bincrement;
3003 else ontrue = bpostcond;
3007 if (self->pre_not) {
3012 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3019 if (bincrement) tmpblock = bincrement;
3020 else if (bpostcond) tmpblock = bpostcond;
3021 else if (bprecond) tmpblock = bprecond;
3022 else tmpblock = bbody;
3023 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3027 /* from increment */
3030 if (bpostcond) tmpblock = bpostcond;
3031 else if (bprecond) tmpblock = bprecond;
3032 else if (bbody) tmpblock = bbody;
3033 else tmpblock = bout;
3034 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3041 ir_block *ontrue, *onfalse;
3042 if (bprecond) ontrue = bprecond;
3043 else ontrue = bbody; /* can never be null */
3045 /* all of this is dead code
3046 else if (bincrement) ontrue = bincrement;
3047 else ontrue = bpostcond;
3051 if (self->post_not) {
3056 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3060 /* Move 'bout' to the end */
3061 vec_remove(func->ir_func->blocks, bout_id, 1);
3062 vec_push(func->ir_func->blocks, bout);
3067 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3074 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3078 if (self->expression.outr) {
3079 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3082 self->expression.outr = (ir_value*)1;
3084 if (self->is_continue)
3085 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3087 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3090 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3094 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3099 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3101 ast_expression_codegen *cgen;
3103 ast_switch_case *def_case = NULL;
3104 ir_block *def_bfall = NULL;
3105 ir_block *def_bfall_to = NULL;
3106 bool set_def_bfall_to = false;
3108 ir_value *dummy = NULL;
3109 ir_value *irop = NULL;
3110 ir_block *bout = NULL;
3111 ir_block *bfall = NULL;
3119 compile_error(ast_ctx(self), "switch expression is not an l-value");
3123 if (self->expression.outr) {
3124 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3127 self->expression.outr = (ir_value*)1;
3132 cgen = self->operand->codegen;
3133 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3136 if (!vec_size(self->cases))
3139 cmpinstr = type_eq_instr[irop->vtype];
3140 if (cmpinstr >= VINSTR_END) {
3141 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3142 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3146 bout_id = vec_size(func->ir_func->blocks);
3147 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3151 /* setup the break block */
3152 vec_push(func->breakblocks, bout);
3154 /* Now create all cases */
3155 for (c = 0; c < vec_size(self->cases); ++c) {
3156 ir_value *cond, *val;
3157 ir_block *bcase, *bnot;
3160 ast_switch_case *swcase = &self->cases[c];
3162 if (swcase->value) {
3163 /* A regular case */
3164 /* generate the condition operand */
3165 cgen = swcase->value->codegen;
3166 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3168 /* generate the condition */
3169 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3173 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3174 bnot_id = vec_size(func->ir_func->blocks);
3175 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3176 if (!bcase || !bnot)
3178 if (set_def_bfall_to) {
3179 set_def_bfall_to = false;
3180 def_bfall_to = bcase;
3182 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3185 /* Make the previous case-end fall through */
3186 if (bfall && !bfall->final) {
3187 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3191 /* enter the case */
3192 func->curblock = bcase;
3193 cgen = swcase->code->codegen;
3194 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3197 /* remember this block to fall through from */
3198 bfall = func->curblock;
3200 /* enter the else and move it down */
3201 func->curblock = bnot;
3202 vec_remove(func->ir_func->blocks, bnot_id, 1);
3203 vec_push(func->ir_func->blocks, bnot);
3205 /* The default case */
3206 /* Remember where to fall through from: */
3209 /* remember which case it was */
3211 /* And the next case will be remembered */
3212 set_def_bfall_to = true;
3216 /* Jump from the last bnot to bout */
3217 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3219 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3224 /* If there was a default case, put it down here */
3228 /* No need to create an extra block */
3229 bcase = func->curblock;
3231 /* Insert the fallthrough jump */
3232 if (def_bfall && !def_bfall->final) {
3233 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3237 /* Now generate the default code */
3238 cgen = def_case->code->codegen;
3239 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3242 /* see if we need to fall through */
3243 if (def_bfall_to && !func->curblock->final)
3245 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3250 /* Jump from the last bnot to bout */
3251 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3253 /* enter the outgoing block */
3254 func->curblock = bout;
3256 /* restore the break block */
3257 vec_pop(func->breakblocks);
3259 /* Move 'bout' to the end, it's nicer */
3260 vec_remove(func->ir_func->blocks, bout_id, 1);
3261 vec_push(func->ir_func->blocks, bout);
3266 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3271 if (self->undefined) {
3272 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3278 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3282 /* simply create a new block and jump to it */
3283 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3284 if (!self->irblock) {
3285 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3288 if (!func->curblock->final) {
3289 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3293 /* enter the new block */
3294 func->curblock = self->irblock;
3296 /* Generate all the leftover gotos */
3297 for (i = 0; i < vec_size(self->gotos); ++i) {
3298 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3305 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3309 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3313 if (self->target->irblock) {
3314 if (self->irblock_from) {
3315 /* we already tried once, this is the callback */
3316 self->irblock_from->final = false;
3317 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3318 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3324 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3325 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3332 /* the target has not yet been created...
3333 * close this block in a sneaky way:
3335 func->curblock->final = true;
3336 self->irblock_from = func->curblock;
3337 ast_label_register_goto(self->target, self);
3343 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3345 ast_expression_codegen *cgen;
3347 ir_instr *callinstr;
3350 ir_value *funval = NULL;
3352 /* return values are never lvalues */
3354 compile_error(ast_ctx(self), "not an l-value (function call)");
3358 if (self->expression.outr) {
3359 *out = self->expression.outr;
3363 cgen = self->func->codegen;
3364 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3372 for (i = 0; i < vec_size(self->params); ++i)
3375 ast_expression *expr = self->params[i];
3377 cgen = expr->codegen;
3378 if (!(*cgen)(expr, func, false, ¶m))
3382 vec_push(params, param);
3385 /* varargs counter */
3386 if (self->va_count) {
3388 ir_builder *builder = func->curblock->owner->owner;
3389 cgen = self->va_count->codegen;
3390 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3392 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3393 ir_builder_get_va_count(builder), va_count))
3399 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3400 ast_function_label(func, "call"),
3401 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3405 for (i = 0; i < vec_size(params); ++i) {
3406 ir_call_param(callinstr, params[i]);
3409 *out = ir_call_value(callinstr);
3410 self->expression.outr = *out;
3412 codegen_output_type(self, *out);