11 #define ast_instantiate(T, ctx, destroyfn) \
12 T* self = (T*)mem_a(sizeof(T)); \
17 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
18 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
21 * forward declarations, these need not be in ast.h for obvious
24 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
25 static void ast_array_index_delete(ast_array_index*);
26 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
27 static void ast_argpipe_delete(ast_argpipe*);
28 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
29 static void ast_store_delete(ast_store*);
30 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
31 static void ast_ifthen_delete(ast_ifthen*);
32 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
33 static void ast_ternary_delete(ast_ternary*);
34 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
35 static void ast_loop_delete(ast_loop*);
36 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
37 static void ast_breakcont_delete(ast_breakcont*);
38 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
39 static void ast_switch_delete(ast_switch*);
40 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
41 static void ast_label_delete(ast_label*);
42 static void ast_label_register_goto(ast_label*, ast_goto*);
43 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
44 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
45 static void ast_goto_delete(ast_goto*);
46 static void ast_call_delete(ast_call*);
47 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
48 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
49 static void ast_unary_delete(ast_unary*);
50 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
51 static void ast_entfield_delete(ast_entfield*);
52 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
53 static void ast_return_delete(ast_return*);
54 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
55 static void ast_binstore_delete(ast_binstore*);
56 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
57 static void ast_binary_delete(ast_binary*);
58 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
59 static bool ast_state_codegen(ast_state*, ast_function*, bool lvalue, ir_value**);
61 /* It must not be possible to get here. */
62 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
65 con_err("ast node missing destroy()\n");
69 /* Initialize main ast node aprts */
70 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int node_type)
73 self->destroy = &_ast_node_destroy;
74 self->keep_node = false;
75 self->node_type = node_type;
76 self->side_effects = false;
79 /* weight and side effects */
80 static void _ast_propagate_effects(ast_node *self, ast_node *other)
82 if (ast_side_effects(other))
83 ast_side_effects(self) = true;
85 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
87 /* General expression initialization */
88 static void ast_expression_init(ast_expression *self,
89 ast_expression_codegen *codegen)
91 self->codegen = codegen;
92 self->vtype = TYPE_VOID;
97 self->varparam = nullptr;
99 if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
100 self->flags |= AST_FLAG_BLOCK_COVERAGE;
103 static void ast_expression_delete(ast_expression *self)
106 ast_delete(self->next);
107 for (auto &it : self->type_params)
110 ast_delete(self->varparam);
113 static void ast_expression_delete_full(ast_expression *self)
115 ast_expression_delete(self);
119 ast_value* ast_value_copy(const ast_value *self)
121 ast_value *cp = ast_value_new(self->context, self->name, self->vtype);
123 cp->next = ast_type_copy(self->context, self->next);
125 const ast_expression *fromex = self;
126 ast_expression *selfex = cp;
127 selfex->count = fromex->count;
128 selfex->flags = fromex->flags;
129 for (auto &it : fromex->type_params) {
130 ast_value *v = ast_value_copy(it);
131 selfex->type_params.push_back(v);
136 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
138 const ast_expression *fromex;
139 ast_expression *selfex;
140 self->vtype = other->vtype;
142 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
146 selfex->count = fromex->count;
147 selfex->flags = fromex->flags;
148 for (auto &it : fromex->type_params) {
149 ast_value *v = ast_value_copy(it);
150 selfex->type_params.push_back(v);
154 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
156 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
157 ast_expression_init(self, nullptr);
158 self->codegen = nullptr;
159 self->next = nullptr;
164 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
166 const ast_expression *fromex;
167 ast_expression *selfex;
173 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
174 ast_expression_init(self, nullptr);
179 /* This may never be codegen()d */
180 selfex->codegen = nullptr;
182 selfex->vtype = fromex->vtype;
184 selfex->next = ast_type_copy(ctx, fromex->next);
186 selfex->next = nullptr;
188 selfex->count = fromex->count;
189 selfex->flags = fromex->flags;
190 for (auto &it : fromex->type_params) {
191 ast_value *v = ast_value_copy(it);
192 selfex->type_params.push_back(v);
199 bool ast_compare_type(ast_expression *a, ast_expression *b)
201 if (a->vtype == TYPE_NIL ||
202 b->vtype == TYPE_NIL)
204 if (a->vtype != b->vtype)
206 if (!a->next != !b->next)
208 if (a->type_params.size() != b->type_params.size())
210 if ((a->flags & AST_FLAG_TYPE_MASK) !=
211 (b->flags & AST_FLAG_TYPE_MASK) )
215 if (a->type_params.size()) {
217 for (i = 0; i < a->type_params.size(); ++i) {
218 if (!ast_compare_type((ast_expression*)a->type_params[i],
219 (ast_expression*)b->type_params[i]))
224 return ast_compare_type(a->next, b->next);
228 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
235 if (pos + 6 >= bufsize)
237 util_strncpy(buf + pos, "(null)", 6);
241 if (pos + 1 >= bufsize)
246 util_strncpy(buf + pos, "(variant)", 9);
251 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
254 if (pos + 3 >= bufsize)
258 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
259 if (pos + 1 >= bufsize)
265 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
266 if (pos + 2 >= bufsize)
268 if (e->type_params.empty()) {
274 pos = ast_type_to_string_impl((ast_expression*)(e->type_params[0]), buf, bufsize, pos);
275 for (i = 1; i < e->type_params.size(); ++i) {
276 if (pos + 2 >= bufsize)
280 pos = ast_type_to_string_impl((ast_expression*)(e->type_params[i]), buf, bufsize, pos);
282 if (pos + 1 >= bufsize)
288 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
289 if (pos + 1 >= bufsize)
292 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
293 if (pos + 1 >= bufsize)
299 typestr = type_name[e->vtype];
300 typelen = strlen(typestr);
301 if (pos + typelen >= bufsize)
303 util_strncpy(buf + pos, typestr, typelen);
304 return pos + typelen;
308 buf[bufsize-3] = '.';
309 buf[bufsize-2] = '.';
310 buf[bufsize-1] = '.';
314 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
316 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
320 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
321 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
323 ast_instantiate(ast_value, ctx, ast_value_delete);
324 ast_expression_init((ast_expression*)self,
325 (ast_expression_codegen*)&ast_value_codegen);
326 self->keep_node = true; /* keep */
328 self->name = name ? util_strdup(name) : nullptr;
330 self->next = nullptr;
331 self->isfield = false;
333 self->hasvalue = false;
335 self->inexact = false;
337 memset(&self->constval, 0, sizeof(self->constval));
339 self->ir_v = nullptr;
340 self->ir_values = nullptr;
341 self->ir_value_count = 0;
343 self->setter = nullptr;
344 self->getter = nullptr;
345 self->desc = nullptr;
347 self->argcounter = nullptr;
348 self->intrinsic = false;
353 void ast_value_delete(ast_value* self)
356 mem_d((void*)self->name);
357 if (self->argcounter)
358 mem_d((void*)self->argcounter);
359 if (self->hasvalue) {
363 mem_d((void*)self->constval.vstring);
366 /* unlink us from the function node */
367 self->constval.vfunc->function_type = nullptr;
369 /* NOTE: delete function? currently collected in
370 * the parser structure
377 mem_d(self->ir_values);
382 // initlist imples an array which implies .next in the expression exists.
383 if (self->initlist.size() && self->next->vtype == TYPE_STRING) {
384 for (auto &it : self->initlist)
389 ast_expression_delete((ast_expression*)self);
393 void ast_value_params_add(ast_value *self, ast_value *p)
395 self->type_params.push_back(p);
398 bool ast_value_set_name(ast_value *self, const char *name)
401 mem_d((void*)self->name);
402 self->name = util_strdup(name);
406 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
407 ast_expression* left, ast_expression* right)
409 ast_instantiate(ast_binary, ctx, ast_binary_delete);
410 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
412 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
413 ast_unary *unary = ((ast_unary*)right);
414 ast_expression *normal = unary->operand;
416 /* make a-(-b) => a + b */
417 if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
418 if (op == INSTR_SUB_F) {
421 ++opts_optimizationcount[OPTIM_PEEPHOLE];
422 } else if (op == INSTR_SUB_V) {
425 ++opts_optimizationcount[OPTIM_PEEPHOLE];
433 self->right_first = false;
435 ast_propagate_effects(self, left);
436 ast_propagate_effects(self, right);
438 if (op >= INSTR_EQ_F && op <= INSTR_GT)
439 self->vtype = TYPE_FLOAT;
440 else if (op == INSTR_AND || op == INSTR_OR) {
441 if (OPTS_FLAG(PERL_LOGIC))
442 ast_type_adopt(self, right);
444 self->vtype = TYPE_FLOAT;
446 else if (op == INSTR_BITAND || op == INSTR_BITOR)
447 self->vtype = TYPE_FLOAT;
448 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
449 self->vtype = TYPE_VECTOR;
450 else if (op == INSTR_MUL_V)
451 self->vtype = TYPE_FLOAT;
453 self->vtype = left->vtype;
456 self->refs = AST_REF_ALL;
461 void ast_binary_delete(ast_binary *self)
463 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
464 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
466 ast_expression_delete((ast_expression*)self);
470 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
471 ast_expression* left, ast_expression* right)
473 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
474 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
476 ast_side_effects(self) = true;
478 self->opstore = storop;
481 self->source = right;
483 self->keep_dest = false;
485 ast_type_adopt(self, left);
489 void ast_binstore_delete(ast_binstore *self)
491 if (!self->keep_dest)
492 ast_unref(self->dest);
493 ast_unref(self->source);
494 ast_expression_delete((ast_expression*)self);
498 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
499 ast_expression *expr)
501 ast_instantiate(ast_unary, ctx, ast_unary_delete);
502 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
505 self->operand = expr;
508 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
509 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
511 /* Handle for double negation */
512 if (((ast_unary*)expr)->op == op)
513 prev = (ast_unary*)((ast_unary*)expr)->operand;
515 if (ast_istype(prev, ast_unary)) {
516 ast_expression_delete((ast_expression*)self);
518 ++opts_optimizationcount[OPTIM_PEEPHOLE];
523 ast_propagate_effects(self, expr);
525 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
526 self->vtype = TYPE_FLOAT;
527 } else if (op == VINSTR_NEG_V) {
528 self->vtype = TYPE_VECTOR;
530 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
536 void ast_unary_delete(ast_unary *self)
538 if (self->operand) ast_unref(self->operand);
539 ast_expression_delete((ast_expression*)self);
543 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
545 ast_instantiate(ast_return, ctx, ast_return_delete);
546 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
548 self->operand = expr;
551 ast_propagate_effects(self, expr);
556 void ast_return_delete(ast_return *self)
559 ast_unref(self->operand);
560 ast_expression_delete((ast_expression*)self);
564 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
566 if (field->vtype != TYPE_FIELD) {
567 compile_error(ctx, "ast_entfield_new with expression not of type field");
570 return ast_entfield_new_force(ctx, entity, field, field->next);
573 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
575 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
579 /* Error: field has no type... */
583 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
585 self->entity = entity;
587 ast_propagate_effects(self, entity);
588 ast_propagate_effects(self, field);
590 ast_type_adopt(self, outtype);
594 void ast_entfield_delete(ast_entfield *self)
596 ast_unref(self->entity);
597 ast_unref(self->field);
598 ast_expression_delete((ast_expression*)self);
602 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
604 ast_instantiate(ast_member, ctx, ast_member_delete);
610 if (owner->vtype != TYPE_VECTOR &&
611 owner->vtype != TYPE_FIELD) {
612 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
617 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
618 self->keep_node = true; /* keep */
620 if (owner->vtype == TYPE_VECTOR) {
621 self->vtype = TYPE_FLOAT;
622 self->next = nullptr;
624 self->vtype = TYPE_FIELD;
625 self->next = ast_shallow_type(ctx, TYPE_FLOAT);
628 self->rvalue = false;
630 ast_propagate_effects(self, owner);
634 self->name = util_strdup(name);
636 self->name = nullptr;
641 void ast_member_delete(ast_member *self)
643 /* The owner is always an ast_value, which has .keep_node=true,
644 * also: ast_members are usually deleted after the owner, thus
645 * this will cause invalid access
646 ast_unref(self->owner);
647 * once we allow (expression).x to access a vector-member, we need
648 * to change this: preferably by creating an alternate ast node for this
649 * purpose that is not garbage-collected.
651 ast_expression_delete((ast_expression*)self);
656 bool ast_member_set_name(ast_member *self, const char *name)
659 mem_d((void*)self->name);
660 self->name = util_strdup(name);
664 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
666 ast_expression *outtype;
667 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
669 outtype = array->next;
672 /* Error: field has no type... */
676 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
680 ast_propagate_effects(self, array);
681 ast_propagate_effects(self, index);
683 ast_type_adopt(self, outtype);
684 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
685 if (self->vtype != TYPE_ARRAY) {
686 compile_error(ast_ctx(self), "array_index node on type");
687 ast_array_index_delete(self);
690 self->array = outtype;
691 self->vtype = TYPE_FIELD;
697 void ast_array_index_delete(ast_array_index *self)
700 ast_unref(self->array);
702 ast_unref(self->index);
703 ast_expression_delete((ast_expression*)self);
707 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
709 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
710 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
712 self->vtype = TYPE_NOEXPR;
716 void ast_argpipe_delete(ast_argpipe *self)
719 ast_unref(self->index);
720 ast_expression_delete((ast_expression*)self);
724 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
726 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
727 if (!ontrue && !onfalse) {
728 /* because it is invalid */
732 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
735 self->on_true = ontrue;
736 self->on_false = onfalse;
737 ast_propagate_effects(self, cond);
739 ast_propagate_effects(self, ontrue);
741 ast_propagate_effects(self, onfalse);
746 void ast_ifthen_delete(ast_ifthen *self)
748 ast_unref(self->cond);
750 ast_unref(self->on_true);
752 ast_unref(self->on_false);
753 ast_expression_delete((ast_expression*)self);
757 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
759 ast_expression *exprtype = ontrue;
760 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
761 /* This time NEITHER must be nullptr */
762 if (!ontrue || !onfalse) {
766 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
769 self->on_true = ontrue;
770 self->on_false = onfalse;
771 ast_propagate_effects(self, cond);
772 ast_propagate_effects(self, ontrue);
773 ast_propagate_effects(self, onfalse);
775 if (ontrue->vtype == TYPE_NIL)
777 ast_type_adopt(self, exprtype);
782 void ast_ternary_delete(ast_ternary *self)
784 /* the if()s are only there because computed-gotos can set them
787 if (self->cond) ast_unref(self->cond);
788 if (self->on_true) ast_unref(self->on_true);
789 if (self->on_false) ast_unref(self->on_false);
790 ast_expression_delete((ast_expression*)self);
794 ast_loop* ast_loop_new(lex_ctx_t ctx,
795 ast_expression *initexpr,
796 ast_expression *precond, bool pre_not,
797 ast_expression *postcond, bool post_not,
798 ast_expression *increment,
799 ast_expression *body)
801 ast_instantiate(ast_loop, ctx, ast_loop_delete);
802 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
804 self->initexpr = initexpr;
805 self->precond = precond;
806 self->postcond = postcond;
807 self->increment = increment;
810 self->pre_not = pre_not;
811 self->post_not = post_not;
814 ast_propagate_effects(self, initexpr);
816 ast_propagate_effects(self, precond);
818 ast_propagate_effects(self, postcond);
820 ast_propagate_effects(self, increment);
822 ast_propagate_effects(self, body);
827 void ast_loop_delete(ast_loop *self)
830 ast_unref(self->initexpr);
832 ast_unref(self->precond);
834 ast_unref(self->postcond);
836 ast_unref(self->increment);
838 ast_unref(self->body);
839 ast_expression_delete((ast_expression*)self);
843 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
845 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
846 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
848 self->is_continue = iscont;
849 self->levels = levels;
854 void ast_breakcont_delete(ast_breakcont *self)
856 ast_expression_delete((ast_expression*)self);
860 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
862 ast_instantiate(ast_switch, ctx, ast_switch_delete);
863 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
867 ast_propagate_effects(self, op);
872 void ast_switch_delete(ast_switch *self)
874 ast_unref(self->operand);
876 for (auto &it : self->cases) {
882 ast_expression_delete((ast_expression*)self);
886 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
888 ast_instantiate(ast_label, ctx, ast_label_delete);
889 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
891 self->vtype = TYPE_NOEXPR;
893 self->name = util_strdup(name);
894 self->irblock = nullptr;
895 self->undefined = undefined;
900 void ast_label_delete(ast_label *self)
902 mem_d((void*)self->name);
903 ast_expression_delete((ast_expression*)self);
907 static void ast_label_register_goto(ast_label *self, ast_goto *g)
909 self->gotos.push_back(g);
912 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
914 ast_instantiate(ast_goto, ctx, ast_goto_delete);
915 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
917 self->name = util_strdup(name);
918 self->target = nullptr;
919 self->irblock_from = nullptr;
924 void ast_goto_delete(ast_goto *self)
926 mem_d((void*)self->name);
927 ast_expression_delete((ast_expression*)self);
931 void ast_goto_set_label(ast_goto *self, ast_label *label)
933 self->target = label;
936 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
938 ast_instantiate(ast_state, ctx, ast_state_delete);
939 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_state_codegen);
940 self->framenum = frame;
941 self->nextthink = think;
945 void ast_state_delete(ast_state *self)
948 ast_unref(self->framenum);
950 ast_unref(self->nextthink);
952 ast_expression_delete((ast_expression*)self);
956 ast_call* ast_call_new(lex_ctx_t ctx,
957 ast_expression *funcexpr)
959 ast_instantiate(ast_call, ctx, ast_call_delete);
960 if (!funcexpr->next) {
961 compile_error(ctx, "not a function");
965 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
967 ast_side_effects(self) = true;
969 self->func = funcexpr;
970 self->va_count = nullptr;
972 ast_type_adopt(self, funcexpr->next);
977 void ast_call_delete(ast_call *self)
979 for (auto &it : self->params)
983 ast_unref(self->func);
986 ast_unref(self->va_count);
988 ast_expression_delete((ast_expression*)self);
992 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
998 if (!va_type || !ast_compare_type(va_type, exp_type))
1000 if (va_type && exp_type)
1002 ast_type_to_string(va_type, tgot, sizeof(tgot));
1003 ast_type_to_string(exp_type, texp, sizeof(texp));
1004 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1005 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1006 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1010 compile_error(ast_ctx(self),
1011 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1018 ast_type_to_string(exp_type, texp, sizeof(texp));
1019 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1020 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1021 "piped variadic argument may differ in type: expected type %s",
1025 compile_error(ast_ctx(self),
1026 "piped variadic argument may differ in type: expected type %s",
1035 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1041 const ast_expression *func = self->func;
1042 size_t count = self->params.size();
1043 if (count > func->type_params.size())
1044 count = func->type_params.size();
1046 for (i = 0; i < count; ++i) {
1047 if (ast_istype(self->params[i], ast_argpipe)) {
1048 /* warn about type safety instead */
1050 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1053 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->type_params[i]))
1056 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->type_params[i])))
1058 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1059 ast_type_to_string((ast_expression*)func->type_params[i], texp, sizeof(texp));
1060 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1061 (unsigned int)(i+1), texp, tgot);
1062 /* we don't immediately return */
1066 count = self->params.size();
1067 if (count > func->type_params.size() && func->varparam) {
1068 for (; i < count; ++i) {
1069 if (ast_istype(self->params[i], ast_argpipe)) {
1070 /* warn about type safety instead */
1072 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1075 if (!ast_call_check_vararg(self, va_type, func->varparam))
1078 else if (!ast_compare_type(self->params[i], func->varparam))
1080 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1081 ast_type_to_string(func->varparam, texp, sizeof(texp));
1082 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1083 (unsigned int)(i+1), texp, tgot);
1084 /* we don't immediately return */
1092 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1093 ast_expression *dest, ast_expression *source)
1095 ast_instantiate(ast_store, ctx, ast_store_delete);
1096 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1098 ast_side_effects(self) = true;
1102 self->source = source;
1104 ast_type_adopt(self, dest);
1109 void ast_store_delete(ast_store *self)
1111 ast_unref(self->dest);
1112 ast_unref(self->source);
1113 ast_expression_delete((ast_expression*)self);
1117 ast_block* ast_block_new(lex_ctx_t ctx)
1119 ast_instantiate(ast_block, ctx, ast_block_delete);
1120 ast_expression_init((ast_expression*)self,
1121 (ast_expression_codegen*)&ast_block_codegen);
1125 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1127 ast_propagate_effects(self, e);
1128 self->exprs.push_back(e);
1130 ast_delete(self->next);
1131 self->next = nullptr;
1133 ast_type_adopt(self, e);
1137 void ast_block_collect(ast_block *self, ast_expression *expr)
1139 self->collect.push_back(expr);
1140 expr->keep_node = true;
1143 void ast_block_delete(ast_block *self)
1145 for (auto &it : self->exprs) ast_unref(it);
1146 for (auto &it : self->locals) ast_delete(it);
1147 for (auto &it : self->collect) ast_delete(it);
1148 ast_expression_delete((ast_expression*)self);
1152 void ast_block_set_type(ast_block *self, ast_expression *from)
1155 ast_delete(self->next);
1156 ast_type_adopt(self, from);
1159 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1161 ast_instantiate(ast_function, ctx, ast_function_delete);
1164 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1166 } else if (vtype->hasvalue || vtype->vtype != TYPE_FUNCTION) {
1167 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1169 (int)vtype->hasvalue,
1174 self->function_type = vtype;
1175 self->name = name ? util_strdup(name) : nullptr;
1177 self->labelcount = 0;
1180 self->ir_func = nullptr;
1181 self->curblock = nullptr;
1183 vtype->hasvalue = true;
1184 vtype->constval.vfunc = self;
1186 self->varargs = nullptr;
1187 self->argc = nullptr;
1188 self->fixedparams = nullptr;
1189 self->return_value = nullptr;
1190 self->static_count = 0;
1199 void ast_function_delete(ast_function *self)
1202 mem_d((void*)self->name);
1203 if (self->function_type) {
1204 /* ast_value_delete(self->function_type); */
1205 self->function_type->hasvalue = false;
1206 self->function_type->constval.vfunc = nullptr;
1207 /* We use unref - if it was stored in a global table it is supposed
1208 * to be deleted from *there*
1210 ast_unref(self->function_type);
1212 for (auto &it : self->static_names)
1214 for (auto &it : self->blocks)
1217 ast_delete(self->varargs);
1219 ast_delete(self->argc);
1220 if (self->fixedparams)
1221 ast_unref(self->fixedparams);
1222 if (self->return_value)
1223 ast_unref(self->return_value);
1227 const char* ast_function_label(ast_function *self, const char *prefix)
1233 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1234 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1235 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1240 id = (self->labelcount++);
1241 len = strlen(prefix);
1243 from = self->labelbuf + sizeof(self->labelbuf)-1;
1246 *from-- = (id%10) + '0';
1250 memcpy(from - len, prefix, len);
1254 /*********************************************************************/
1256 * by convention you must never pass nullptr to the 'ir_value **out'
1257 * parameter. If you really don't care about the output, pass a dummy.
1258 * But I can't imagine a pituation where the output is truly unnecessary.
1261 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1263 if (out->vtype == TYPE_FIELD)
1264 out->fieldtype = self->next->vtype;
1265 if (out->vtype == TYPE_FUNCTION)
1266 out->outtype = self->next->vtype;
1269 #define codegen_output_type(a,o) (_ast_codegen_output_type(static_cast<ast_expression*>((a)),(o)))
1271 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1275 if (self->vtype == TYPE_NIL) {
1276 *out = func->ir_func->owner->nil;
1279 /* NOTE: This is the codegen for a variable used in an
1280 * It is not the codegen to generate the value. For this purpose,
1281 * ast_local_codegen and ast_global_codegen are to be used before this
1282 * is executed. ast_function_codegen should take care of its locals,
1283 * and the ast-user should take care of ast_global_codegen to be used
1284 * on all the globals.
1287 char tname[1024]; /* typename is reserved in C++ */
1288 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1289 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1296 static bool ast_global_array_set(ast_value *self)
1298 size_t count = self->initlist.size();
1301 if (count > self->count) {
1302 compile_error(ast_ctx(self), "too many elements in initializer");
1303 count = self->count;
1305 else if (count < self->count) {
1307 compile_warning(ast_ctx(self), "not all elements are initialized");
1311 for (i = 0; i != count; ++i) {
1312 switch (self->next->vtype) {
1314 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1318 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1322 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1326 /* we don't support them in any other place yet either */
1327 compile_error(ast_ctx(self), "TODO: nested arrays");
1330 /* this requiers a bit more work - similar to the fields I suppose */
1331 compile_error(ast_ctx(self), "global of type function not properly generated");
1334 if (!self->initlist[i].vfield) {
1335 compile_error(ast_ctx(self), "field constant without vfield set");
1338 if (!self->initlist[i].vfield->ir_v) {
1339 compile_error(ast_ctx(self), "field constant generated before its field");
1342 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1346 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1353 static bool check_array(ast_value *self, ast_value *array)
1355 if (array->flags & AST_FLAG_ARRAY_INIT && array->initlist.empty()) {
1356 compile_error(ast_ctx(self), "array without size: %s", self->name);
1359 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1360 if (!array->count || array->count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1361 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->count);
1367 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1369 ir_value *v = nullptr;
1371 if (self->vtype == TYPE_NIL) {
1372 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1376 if (self->hasvalue && self->vtype == TYPE_FUNCTION)
1378 ir_function *func = ir_builder_create_function(ir, self->name, self->next->vtype);
1381 func->context = ast_ctx(self);
1382 func->value->context = ast_ctx(self);
1384 self->constval.vfunc->ir_func = func;
1385 self->ir_v = func->value;
1386 if (self->flags & AST_FLAG_INCLUDE_DEF)
1387 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1388 if (self->flags & AST_FLAG_ERASEABLE)
1389 self->ir_v->flags |= IR_FLAG_ERASABLE;
1390 if (self->flags & AST_FLAG_BLOCK_COVERAGE)
1391 func->flags |= IR_FLAG_BLOCK_COVERAGE;
1392 /* The function is filled later on ast_function_codegen... */
1396 if (isfield && self->vtype == TYPE_FIELD) {
1397 ast_expression *fieldtype = self->next;
1399 if (self->hasvalue) {
1400 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1404 if (fieldtype->vtype == TYPE_ARRAY) {
1409 ast_expression *elemtype;
1411 ast_value *array = (ast_value*)fieldtype;
1413 if (!ast_istype(fieldtype, ast_value)) {
1414 compile_error(ast_ctx(self), "internal error: ast_value required");
1418 if (!check_array(self, array))
1421 elemtype = array->next;
1422 vtype = elemtype->vtype;
1424 v = ir_builder_create_field(ir, self->name, vtype);
1426 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1429 v->context = ast_ctx(self);
1430 v->unique_life = true;
1432 array->ir_v = self->ir_v = v;
1434 if (self->flags & AST_FLAG_INCLUDE_DEF)
1435 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1436 if (self->flags & AST_FLAG_ERASEABLE)
1437 self->ir_v->flags |= IR_FLAG_ERASABLE;
1439 namelen = strlen(self->name);
1440 name = (char*)mem_a(namelen + 16);
1441 util_strncpy(name, self->name, namelen);
1443 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->count);
1444 array->ir_values[0] = v;
1445 for (ai = 1; ai < array->count; ++ai) {
1446 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1447 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1448 if (!array->ir_values[ai]) {
1450 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1453 array->ir_values[ai]->context = ast_ctx(self);
1454 array->ir_values[ai]->unique_life = true;
1455 array->ir_values[ai]->locked = true;
1456 if (self->flags & AST_FLAG_INCLUDE_DEF)
1457 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1463 v = ir_builder_create_field(ir, self->name, self->next->vtype);
1466 v->context = ast_ctx(self);
1468 if (self->flags & AST_FLAG_INCLUDE_DEF)
1469 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1471 if (self->flags & AST_FLAG_ERASEABLE)
1472 self->ir_v->flags |= IR_FLAG_ERASABLE;
1477 if (self->vtype == TYPE_ARRAY) {
1482 ast_expression *elemtype = self->next;
1483 int vtype = elemtype->vtype;
1485 if (self->flags & AST_FLAG_ARRAY_INIT && !self->count) {
1486 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1490 /* same as with field arrays */
1491 if (!check_array(self, self))
1494 v = ir_builder_create_global(ir, self->name, vtype);
1496 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1499 v->context = ast_ctx(self);
1500 v->unique_life = true;
1503 if (self->flags & AST_FLAG_INCLUDE_DEF)
1504 v->flags |= IR_FLAG_INCLUDE_DEF;
1505 if (self->flags & AST_FLAG_ERASEABLE)
1506 self->ir_v->flags |= IR_FLAG_ERASABLE;
1508 namelen = strlen(self->name);
1509 name = (char*)mem_a(namelen + 16);
1510 util_strncpy(name, self->name, namelen);
1512 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->count);
1513 self->ir_values[0] = v;
1514 for (ai = 1; ai < self->count; ++ai) {
1515 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1516 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1517 if (!self->ir_values[ai]) {
1519 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1522 self->ir_values[ai]->context = ast_ctx(self);
1523 self->ir_values[ai]->unique_life = true;
1524 self->ir_values[ai]->locked = true;
1525 if (self->flags & AST_FLAG_INCLUDE_DEF)
1526 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1532 /* Arrays don't do this since there's no "array" value which spans across the
1535 v = ir_builder_create_global(ir, self->name, self->vtype);
1537 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1540 codegen_output_type(self, v);
1541 v->context = ast_ctx(self);
1544 /* link us to the ir_value */
1548 if (self->flags & AST_FLAG_INCLUDE_DEF)
1549 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1550 if (self->flags & AST_FLAG_ERASEABLE)
1551 self->ir_v->flags |= IR_FLAG_ERASABLE;
1554 if (self->hasvalue) {
1555 switch (self->vtype)
1558 if (!ir_value_set_float(v, self->constval.vfloat))
1562 if (!ir_value_set_vector(v, self->constval.vvec))
1566 if (!ir_value_set_string(v, self->constval.vstring))
1570 ast_global_array_set(self);
1573 compile_error(ast_ctx(self), "global of type function not properly generated");
1575 /* Cannot generate an IR value for a function,
1576 * need a pointer pointing to a function rather.
1579 if (!self->constval.vfield) {
1580 compile_error(ast_ctx(self), "field constant without vfield set");
1583 if (!self->constval.vfield->ir_v) {
1584 compile_error(ast_ctx(self), "field constant generated before its field");
1587 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1591 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1597 error: /* clean up */
1598 if(v) ir_value_delete(v);
1602 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1604 ir_value *v = nullptr;
1606 if (self->vtype == TYPE_NIL) {
1607 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1611 if (self->hasvalue && self->vtype == TYPE_FUNCTION)
1613 /* Do we allow local functions? I think not...
1614 * this is NOT a function pointer atm.
1619 if (self->vtype == TYPE_ARRAY) {
1624 ast_expression *elemtype = self->next;
1625 int vtype = elemtype->vtype;
1627 func->flags |= IR_FLAG_HAS_ARRAYS;
1629 if (param && !(self->flags & AST_FLAG_IS_VARARG)) {
1630 compile_error(ast_ctx(self), "array-parameters are not supported");
1634 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1635 if (!check_array(self, self))
1638 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->count);
1639 if (!self->ir_values) {
1640 compile_error(ast_ctx(self), "failed to allocate array values");
1644 v = ir_function_create_local(func, self->name, vtype, param);
1646 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1649 v->context = ast_ctx(self);
1650 v->unique_life = true;
1653 namelen = strlen(self->name);
1654 name = (char*)mem_a(namelen + 16);
1655 util_strncpy(name, self->name, namelen);
1657 self->ir_values[0] = v;
1658 for (ai = 1; ai < self->count; ++ai) {
1659 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1660 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1661 if (!self->ir_values[ai]) {
1662 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1665 self->ir_values[ai]->context = ast_ctx(self);
1666 self->ir_values[ai]->unique_life = true;
1667 self->ir_values[ai]->locked = true;
1673 v = ir_function_create_local(func, self->name, self->vtype, param);
1676 codegen_output_type(self, v);
1677 v->context = ast_ctx(self);
1680 /* A constant local... hmmm...
1681 * I suppose the IR will have to deal with this
1683 if (self->hasvalue) {
1684 switch (self->vtype)
1687 if (!ir_value_set_float(v, self->constval.vfloat))
1691 if (!ir_value_set_vector(v, self->constval.vvec))
1695 if (!ir_value_set_string(v, self->constval.vstring))
1699 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1704 /* link us to the ir_value */
1708 if (!ast_generate_accessors(self, func->owner))
1712 error: /* clean up */
1717 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1720 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1721 if (!self->setter || !self->getter)
1723 for (i = 0; i < self->count; ++i) {
1724 if (!self->ir_values) {
1725 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1728 if (!self->ir_values[i]) {
1729 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1732 if (self->ir_values[i]->life) {
1733 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1738 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1740 if (!ast_global_codegen (self->setter, ir, false) ||
1741 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1742 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1744 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1745 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1750 if (!ast_global_codegen (self->getter, ir, false) ||
1751 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1752 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1754 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1755 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1759 for (i = 0; i < self->count; ++i) {
1760 vec_free(self->ir_values[i]->life);
1762 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1766 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1771 ast_expression_codegen *cgen;
1775 irf = self->ir_func;
1777 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1781 /* fill the parameter list */
1782 ec = self->function_type;
1783 for (auto &it : ec->type_params) {
1784 if (it->vtype == TYPE_FIELD)
1785 vec_push(irf->params, it->next->vtype);
1787 vec_push(irf->params, it->vtype);
1788 if (!self->builtin) {
1789 if (!ast_local_codegen(it, self->ir_func, true))
1794 if (self->varargs) {
1795 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1797 irf->max_varargs = self->varargs->count;
1800 if (self->builtin) {
1801 irf->builtin = self->builtin;
1805 /* have a local return value variable? */
1806 if (self->return_value) {
1807 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1811 if (self->blocks.empty()) {
1812 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1816 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1817 if (!self->curblock) {
1818 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1826 if (!ast_local_codegen(self->argc, self->ir_func, true))
1828 cgen = self->argc->codegen;
1829 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1831 cgen = self->fixedparams->codegen;
1832 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1834 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1835 ast_function_label(self, "va_count"), INSTR_SUB_F,
1836 ir_builder_get_va_count(ir), fixed);
1839 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1846 for (auto &it : self->blocks) {
1848 if (!(*cgen)((ast_expression*)it, self, false, &dummy))
1852 /* TODO: check return types */
1853 if (!self->curblock->final)
1855 if (!self->function_type->next ||
1856 self->function_type->next->vtype == TYPE_VOID)
1858 return ir_block_create_return(self->curblock, ast_ctx(self), nullptr);
1860 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1862 if (self->return_value) {
1863 cgen = self->return_value->codegen;
1864 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1866 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1868 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1869 "control reaches end of non-void function (`%s`) via %s",
1870 self->name, self->curblock->label))
1874 return ir_block_create_return(self->curblock, ast_ctx(self), nullptr);
1880 static bool starts_a_label(ast_expression *ex)
1882 while (ex && ast_istype(ex, ast_block)) {
1883 ast_block *b = (ast_block*)ex;
1888 return ast_istype(ex, ast_label);
1891 /* Note, you will not see ast_block_codegen generate ir_blocks.
1892 * To the AST and the IR, blocks are 2 different things.
1893 * In the AST it represents a block of code, usually enclosed in
1894 * curly braces {...}.
1895 * While in the IR it represents a block in terms of control-flow.
1897 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1899 /* We don't use this
1900 * Note: an ast-representation using the comma-operator
1901 * of the form: (a, b, c) = x should not assign to c...
1904 compile_error(ast_ctx(self), "not an l-value (code-block)");
1913 /* output is nullptr at first, we'll have each expression
1914 * assign to out output, thus, a comma-operator represention
1915 * using an ast_block will return the last generated value,
1916 * so: (b, c) + a executed both b and c, and returns c,
1917 * which is then added to a.
1921 /* generate locals */
1922 for (auto &it : self->locals) {
1923 if (!ast_local_codegen(it, func->ir_func, false)) {
1924 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1925 compile_error(ast_ctx(self), "failed to generate local `%s`", it->name);
1930 for (auto &it : self->exprs) {
1931 ast_expression_codegen *gen;
1932 if (func->curblock->final && !starts_a_label(it)) {
1933 if (compile_warning(ast_ctx(it), WARN_UNREACHABLE_CODE, "unreachable statement"))
1938 if (!(*gen)(it, func, false, out))
1947 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1949 ast_expression_codegen *cgen;
1950 ir_value *left = nullptr;
1951 ir_value *right = nullptr;
1955 ast_array_index *ai = nullptr;
1957 if (lvalue && self->outl) {
1962 if (!lvalue && self->outr) {
1967 if (ast_istype(self->dest, ast_array_index))
1970 ai = (ast_array_index*)self->dest;
1971 idx = (ast_value*)ai->index;
1973 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1978 /* we need to call the setter */
1979 ir_value *iridx, *funval;
1983 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1987 arr = (ast_value*)ai->array;
1988 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1989 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1993 cgen = idx->codegen;
1994 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1997 cgen = arr->setter->codegen;
1998 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2001 cgen = self->source->codegen;
2002 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2005 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2008 ir_call_param(call, iridx);
2009 ir_call_param(call, right);
2016 cgen = self->dest->codegen;
2018 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2022 cgen = self->source->codegen;
2024 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2027 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2032 /* Theoretically, an assinment returns its left side as an
2033 * lvalue, if we don't need an lvalue though, we return
2034 * the right side as an rvalue, otherwise we have to
2035 * somehow know whether or not we need to dereference the pointer
2036 * on the left side - that is: OP_LOAD if it was an address.
2037 * Also: in original QC we cannot OP_LOADP *anyway*.
2039 *out = (lvalue ? left : right);
2044 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2046 ast_expression_codegen *cgen;
2047 ir_value *left, *right;
2049 /* A binary operation cannot yield an l-value */
2051 compile_error(ast_ctx(self), "not an l-value (binop)");
2060 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2061 (self->op == INSTR_AND || self->op == INSTR_OR))
2063 /* NOTE: The short-logic path will ignore right_first */
2065 /* short circuit evaluation */
2066 ir_block *other, *merge;
2067 ir_block *from_left, *from_right;
2071 /* prepare end-block */
2072 merge_id = vec_size(func->ir_func->blocks);
2073 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2075 /* generate the left expression */
2076 cgen = self->left->codegen;
2077 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2079 /* remember the block */
2080 from_left = func->curblock;
2082 /* create a new block for the right expression */
2083 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2084 if (self->op == INSTR_AND) {
2085 /* on AND: left==true -> other */
2086 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2089 /* on OR: left==false -> other */
2090 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2093 /* use the likely flag */
2094 vec_last(func->curblock->instr)->likely = true;
2096 /* enter the right-expression's block */
2097 func->curblock = other;
2099 cgen = self->right->codegen;
2100 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2102 /* remember block */
2103 from_right = func->curblock;
2105 /* jump to the merge block */
2106 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2109 vec_remove(func->ir_func->blocks, merge_id, 1);
2110 vec_push(func->ir_func->blocks, merge);
2112 func->curblock = merge;
2113 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2114 ast_function_label(func, "sce_value"),
2116 ir_phi_add(phi, from_left, left);
2117 ir_phi_add(phi, from_right, right);
2118 *out = ir_phi_value(phi);
2122 if (!OPTS_FLAG(PERL_LOGIC)) {
2124 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2125 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2126 ast_function_label(func, "sce_bool_v"),
2130 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2131 ast_function_label(func, "sce_bool"),
2136 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2137 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2138 ast_function_label(func, "sce_bool_s"),
2142 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2143 ast_function_label(func, "sce_bool"),
2149 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2150 ast_function_label(func, "sce_bool"),
2151 INSTR_AND, *out, *out);
2158 codegen_output_type(self, *out);
2162 if (self->right_first) {
2163 cgen = self->right->codegen;
2164 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2166 cgen = self->left->codegen;
2167 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2170 cgen = self->left->codegen;
2171 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2173 cgen = self->right->codegen;
2174 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2178 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2179 self->op, left, right);
2183 codegen_output_type(self, *out);
2188 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2190 ast_expression_codegen *cgen;
2191 ir_value *leftl = nullptr, *leftr, *right, *bin;
2195 ast_array_index *ai = nullptr;
2196 ir_value *iridx = nullptr;
2198 if (lvalue && self->outl) {
2203 if (!lvalue && self->outr) {
2208 if (ast_istype(self->dest, ast_array_index))
2211 ai = (ast_array_index*)self->dest;
2212 idx = (ast_value*)ai->index;
2214 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2218 /* for a binstore we need both an lvalue and an rvalue for the left side */
2219 /* rvalue of destination! */
2221 cgen = idx->codegen;
2222 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2225 cgen = self->dest->codegen;
2226 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2229 /* source as rvalue only */
2230 cgen = self->source->codegen;
2231 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2234 /* now the binary */
2235 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2236 self->opbin, leftr, right);
2240 /* we need to call the setter */
2245 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2249 arr = (ast_value*)ai->array;
2250 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2251 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2255 cgen = arr->setter->codegen;
2256 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2259 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2262 ir_call_param(call, iridx);
2263 ir_call_param(call, bin);
2266 /* now store them */
2267 cgen = self->dest->codegen;
2268 /* lvalue of destination */
2269 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2273 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2278 /* Theoretically, an assinment returns its left side as an
2279 * lvalue, if we don't need an lvalue though, we return
2280 * the right side as an rvalue, otherwise we have to
2281 * somehow know whether or not we need to dereference the pointer
2282 * on the left side - that is: OP_LOAD if it was an address.
2283 * Also: in original QC we cannot OP_LOADP *anyway*.
2285 *out = (lvalue ? leftl : bin);
2290 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2292 ast_expression_codegen *cgen;
2295 /* An unary operation cannot yield an l-value */
2297 compile_error(ast_ctx(self), "not an l-value (binop)");
2306 cgen = self->operand->codegen;
2308 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2311 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2320 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2322 ast_expression_codegen *cgen;
2327 /* In the context of a return operation, we don't actually return
2331 compile_error(ast_ctx(self), "return-expression is not an l-value");
2336 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2339 self->outr = (ir_value*)1;
2341 if (self->operand) {
2342 cgen = self->operand->codegen;
2344 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2347 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2350 if (!ir_block_create_return(func->curblock, ast_ctx(self), nullptr))
2357 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2359 ast_expression_codegen *cgen;
2360 ir_value *ent, *field;
2362 /* This function needs to take the 'lvalue' flag into account!
2363 * As lvalue we provide a field-pointer, as rvalue we provide the
2367 if (lvalue && self->outl) {
2372 if (!lvalue && self->outr) {
2377 cgen = self->entity->codegen;
2378 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2381 cgen = self->field->codegen;
2382 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2387 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2390 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2391 ent, field, self->vtype);
2392 /* Done AFTER error checking:
2393 codegen_output_type(self, *out);
2397 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2398 (lvalue ? "ADDRESS" : "FIELD"),
2399 type_name[self->vtype]);
2403 codegen_output_type(self, *out);
2410 /* Hm that should be it... */
2414 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2416 ast_expression_codegen *cgen;
2419 /* in QC this is always an lvalue */
2420 if (lvalue && self->rvalue) {
2421 compile_error(ast_ctx(self), "not an l-value (member access)");
2429 cgen = self->owner->codegen;
2430 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2433 if (vec->vtype != TYPE_VECTOR &&
2434 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2439 *out = ir_value_vector_member(vec, self->field);
2442 return (*out != nullptr);
2445 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2450 if (!lvalue && self->outr) {
2454 if (lvalue && self->outl) {
2459 if (!ast_istype(self->array, ast_value)) {
2460 compile_error(ast_ctx(self), "array indexing this way is not supported");
2461 /* note this would actually be pointer indexing because the left side is
2462 * not an actual array but (hopefully) an indexable expression.
2463 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2464 * support this path will be filled.
2469 arr = (ast_value*)self->array;
2470 idx = (ast_value*)self->index;
2472 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2473 /* Time to use accessor functions */
2474 ast_expression_codegen *cgen;
2475 ir_value *iridx, *funval;
2479 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2484 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2488 cgen = self->index->codegen;
2489 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2492 cgen = arr->getter->codegen;
2493 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2496 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2499 ir_call_param(call, iridx);
2501 *out = ir_call_value(call);
2503 (*out)->vtype = self->vtype;
2504 codegen_output_type(self, *out);
2508 if (idx->vtype == TYPE_FLOAT) {
2509 unsigned int arridx = idx->constval.vfloat;
2510 if (arridx >= self->array->count)
2512 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2515 *out = arr->ir_values[arridx];
2517 else if (idx->vtype == TYPE_INTEGER) {
2518 unsigned int arridx = idx->constval.vint;
2519 if (arridx >= self->array->count)
2521 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2524 *out = arr->ir_values[arridx];
2527 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2530 (*out)->vtype = self->vtype;
2531 codegen_output_type(self, *out);
2535 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2539 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2544 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2548 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2550 ast_expression_codegen *cgen;
2558 ir_block *ontrue_endblock = nullptr;
2559 ir_block *onfalse_endblock = nullptr;
2560 ir_block *merge = nullptr;
2563 /* We don't output any value, thus also don't care about r/lvalue */
2568 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2571 self->outr = (ir_value*)1;
2573 /* generate the condition */
2574 cgen = self->cond->codegen;
2575 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2577 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2578 cond = func->curblock;
2580 /* try constant folding away the condition */
2581 if ((folded = fold::cond_ifthen(condval, func, self)) != -1)
2584 if (self->on_true) {
2585 /* create on-true block */
2586 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2590 /* enter the block */
2591 func->curblock = ontrue;
2594 cgen = self->on_true->codegen;
2595 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2598 /* we now need to work from the current endpoint */
2599 ontrue_endblock = func->curblock;
2604 if (self->on_false) {
2605 /* create on-false block */
2606 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2610 /* enter the block */
2611 func->curblock = onfalse;
2614 cgen = self->on_false->codegen;
2615 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2618 /* we now need to work from the current endpoint */
2619 onfalse_endblock = func->curblock;
2623 /* Merge block were they all merge in to */
2624 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2626 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2629 /* add jumps ot the merge block */
2630 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2632 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2635 /* Now enter the merge block */
2636 func->curblock = merge;
2639 /* we create the if here, that way all blocks are ordered :)
2641 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2642 (ontrue ? ontrue : merge),
2643 (onfalse ? onfalse : merge)))
2651 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2653 ast_expression_codegen *cgen;
2656 ir_value *trueval, *falseval;
2659 ir_block *cond = func->curblock;
2660 ir_block *cond_out = nullptr;
2661 ir_block *ontrue, *ontrue_out = nullptr;
2662 ir_block *onfalse, *onfalse_out = nullptr;
2666 /* Ternary can never create an lvalue... */
2670 /* In theory it shouldn't be possible to pass through a node twice, but
2671 * in case we add any kind of optimization pass for the AST itself, it
2672 * may still happen, thus we remember a created ir_value and simply return one
2673 * if it already exists.
2680 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2682 /* generate the condition */
2683 func->curblock = cond;
2684 cgen = self->cond->codegen;
2685 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2687 cond_out = func->curblock;
2689 /* try constant folding away the condition */
2690 if ((folded = fold::cond_ternary(condval, func, self)) != -1)
2693 /* create on-true block */
2694 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2699 /* enter the block */
2700 func->curblock = ontrue;
2703 cgen = self->on_true->codegen;
2704 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2707 ontrue_out = func->curblock;
2710 /* create on-false block */
2711 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2716 /* enter the block */
2717 func->curblock = onfalse;
2720 cgen = self->on_false->codegen;
2721 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2724 onfalse_out = func->curblock;
2727 /* create merge block */
2728 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2731 /* jump to merge block */
2732 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2734 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2737 /* create if instruction */
2738 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2741 /* Now enter the merge block */
2742 func->curblock = merge;
2744 /* Here, now, we need a PHI node
2745 * but first some sanity checking...
2747 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2748 /* error("ternary with different types on the two sides"); */
2749 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2754 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->vtype);
2756 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2759 ir_phi_add(phi, ontrue_out, trueval);
2760 ir_phi_add(phi, onfalse_out, falseval);
2762 self->outr = ir_phi_value(phi);
2765 codegen_output_type(self, *out);
2770 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2772 ast_expression_codegen *cgen;
2774 ir_value *dummy = nullptr;
2775 ir_value *precond = nullptr;
2776 ir_value *postcond = nullptr;
2778 /* Since we insert some jumps "late" so we have blocks
2779 * ordered "nicely", we need to keep track of the actual end-blocks
2780 * of expressions to add the jumps to.
2782 ir_block *bbody = nullptr, *end_bbody = nullptr;
2783 ir_block *bprecond = nullptr, *end_bprecond = nullptr;
2784 ir_block *bpostcond = nullptr, *end_bpostcond = nullptr;
2785 ir_block *bincrement = nullptr, *end_bincrement = nullptr;
2786 ir_block *bout = nullptr, *bin = nullptr;
2788 /* let's at least move the outgoing block to the end */
2791 /* 'break' and 'continue' need to be able to find the right blocks */
2792 ir_block *bcontinue = nullptr;
2793 ir_block *bbreak = nullptr;
2795 ir_block *tmpblock = nullptr;
2801 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2804 self->outr = (ir_value*)1;
2807 * Should we ever need some kind of block ordering, better make this function
2808 * move blocks around than write a block ordering algorithm later... after all
2809 * the ast and ir should work together, not against each other.
2812 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2813 * anyway if for example it contains a ternary.
2817 cgen = self->initexpr->codegen;
2818 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2822 /* Store the block from which we enter this chaos */
2823 bin = func->curblock;
2825 /* The pre-loop condition needs its own block since we
2826 * need to be able to jump to the start of that expression.
2830 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2834 /* the pre-loop-condition the least important place to 'continue' at */
2835 bcontinue = bprecond;
2838 func->curblock = bprecond;
2841 cgen = self->precond->codegen;
2842 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2845 end_bprecond = func->curblock;
2847 bprecond = end_bprecond = nullptr;
2850 /* Now the next blocks won't be ordered nicely, but we need to
2851 * generate them this early for 'break' and 'continue'.
2853 if (self->increment) {
2854 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2857 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2859 bincrement = end_bincrement = nullptr;
2862 if (self->postcond) {
2863 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2866 bcontinue = bpostcond; /* postcond comes before the increment */
2868 bpostcond = end_bpostcond = nullptr;
2871 bout_id = vec_size(func->ir_func->blocks);
2872 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2877 /* The loop body... */
2878 /* if (self->body) */
2880 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2885 func->curblock = bbody;
2887 func->breakblocks.push_back(bbreak);
2889 func->continueblocks.push_back(bcontinue);
2891 func->continueblocks.push_back(bbody);
2895 cgen = self->body->codegen;
2896 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2900 end_bbody = func->curblock;
2901 func->breakblocks.pop_back();
2902 func->continueblocks.pop_back();
2905 /* post-loop-condition */
2909 func->curblock = bpostcond;
2912 cgen = self->postcond->codegen;
2913 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2916 end_bpostcond = func->curblock;
2919 /* The incrementor */
2920 if (self->increment)
2923 func->curblock = bincrement;
2926 cgen = self->increment->codegen;
2927 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2930 end_bincrement = func->curblock;
2933 /* In any case now, we continue from the outgoing block */
2934 func->curblock = bout;
2936 /* Now all blocks are in place */
2937 /* From 'bin' we jump to whatever comes first */
2938 if (bprecond) tmpblock = bprecond;
2939 else tmpblock = bbody; /* can never be null */
2942 else if (bpostcond) tmpblock = bpostcond;
2943 else tmpblock = bout;
2946 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2952 ir_block *ontrue, *onfalse;
2953 ontrue = bbody; /* can never be null */
2955 /* all of this is dead code
2956 else if (bincrement) ontrue = bincrement;
2957 else ontrue = bpostcond;
2961 if (self->pre_not) {
2966 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2973 if (bincrement) tmpblock = bincrement;
2974 else if (bpostcond) tmpblock = bpostcond;
2975 else if (bprecond) tmpblock = bprecond;
2976 else tmpblock = bbody;
2977 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2981 /* from increment */
2984 if (bpostcond) tmpblock = bpostcond;
2985 else if (bprecond) tmpblock = bprecond;
2986 else if (bbody) tmpblock = bbody;
2987 else tmpblock = bout;
2988 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2995 ir_block *ontrue, *onfalse;
2996 if (bprecond) ontrue = bprecond;
2997 else ontrue = bbody; /* can never be null */
2999 /* all of this is dead code
3000 else if (bincrement) ontrue = bincrement;
3001 else ontrue = bpostcond;
3005 if (self->post_not) {
3010 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3014 /* Move 'bout' to the end */
3015 vec_remove(func->ir_func->blocks, bout_id, 1);
3016 vec_push(func->ir_func->blocks, bout);
3021 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3028 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3033 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3036 self->outr = (ir_value*)1;
3038 if (self->is_continue)
3039 target = func->continueblocks[func->continueblocks.size()-1-self->levels];
3041 target = func->breakblocks[func->breakblocks.size()-1-self->levels];
3044 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3048 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3053 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3055 ast_expression_codegen *cgen;
3057 ast_switch_case *def_case = nullptr;
3058 ir_block *def_bfall = nullptr;
3059 ir_block *def_bfall_to = nullptr;
3060 bool set_def_bfall_to = false;
3062 ir_value *dummy = nullptr;
3063 ir_value *irop = nullptr;
3064 ir_block *bout = nullptr;
3065 ir_block *bfall = nullptr;
3072 compile_error(ast_ctx(self), "switch expression is not an l-value");
3077 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3080 self->outr = (ir_value*)1;
3085 cgen = self->operand->codegen;
3086 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3089 if (self->cases.empty())
3092 cmpinstr = type_eq_instr[irop->vtype];
3093 if (cmpinstr >= VINSTR_END) {
3094 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3095 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3099 bout_id = vec_size(func->ir_func->blocks);
3100 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3104 /* setup the break block */
3105 func->breakblocks.push_back(bout);
3107 /* Now create all cases */
3108 for (auto &it : self->cases) {
3109 ir_value *cond, *val;
3110 ir_block *bcase, *bnot;
3113 ast_switch_case *swcase = ⁢
3115 if (swcase->value) {
3116 /* A regular case */
3117 /* generate the condition operand */
3118 cgen = swcase->value->codegen;
3119 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3121 /* generate the condition */
3122 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3126 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3127 bnot_id = vec_size(func->ir_func->blocks);
3128 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3129 if (!bcase || !bnot)
3131 if (set_def_bfall_to) {
3132 set_def_bfall_to = false;
3133 def_bfall_to = bcase;
3135 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3138 /* Make the previous case-end fall through */
3139 if (bfall && !bfall->final) {
3140 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3144 /* enter the case */
3145 func->curblock = bcase;
3146 cgen = swcase->code->codegen;
3147 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3150 /* remember this block to fall through from */
3151 bfall = func->curblock;
3153 /* enter the else and move it down */
3154 func->curblock = bnot;
3155 vec_remove(func->ir_func->blocks, bnot_id, 1);
3156 vec_push(func->ir_func->blocks, bnot);
3158 /* The default case */
3159 /* Remember where to fall through from: */
3162 /* remember which case it was */
3164 /* And the next case will be remembered */
3165 set_def_bfall_to = true;
3169 /* Jump from the last bnot to bout */
3170 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3172 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3177 /* If there was a default case, put it down here */
3181 /* No need to create an extra block */
3182 bcase = func->curblock;
3184 /* Insert the fallthrough jump */
3185 if (def_bfall && !def_bfall->final) {
3186 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3190 /* Now generate the default code */
3191 cgen = def_case->code->codegen;
3192 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3195 /* see if we need to fall through */
3196 if (def_bfall_to && !func->curblock->final)
3198 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3203 /* Jump from the last bnot to bout */
3204 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3206 /* enter the outgoing block */
3207 func->curblock = bout;
3209 /* restore the break block */
3210 func->breakblocks.pop_back();
3212 /* Move 'bout' to the end, it's nicer */
3213 vec_remove(func->ir_func->blocks, bout_id, 1);
3214 vec_push(func->ir_func->blocks, bout);
3219 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3223 if (self->undefined) {
3224 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3230 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3234 /* simply create a new block and jump to it */
3235 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3236 if (!self->irblock) {
3237 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3240 if (!func->curblock->final) {
3241 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3245 /* enter the new block */
3246 func->curblock = self->irblock;
3248 /* Generate all the leftover gotos */
3249 for (auto &it : self->gotos) {
3250 if (!ast_goto_codegen(it, func, false, &dummy))
3257 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3261 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3265 if (self->target->irblock) {
3266 if (self->irblock_from) {
3267 /* we already tried once, this is the callback */
3268 self->irblock_from->final = false;
3269 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3270 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3276 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3277 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3284 /* the target has not yet been created...
3285 * close this block in a sneaky way:
3287 func->curblock->final = true;
3288 self->irblock_from = func->curblock;
3289 ast_label_register_goto(self->target, self);
3296 bool ast_state_codegen(ast_state *self, ast_function *func, bool lvalue, ir_value **out)
3298 ast_expression_codegen *cgen;
3300 ir_value *frameval, *thinkval;
3303 compile_error(ast_ctx(self), "not an l-value (state operation)");
3307 compile_error(ast_ctx(self), "internal error: ast_state cannot be reused!");
3312 cgen = self->framenum->codegen;
3313 if (!(*cgen)((ast_expression*)(self->framenum), func, false, &frameval))
3318 cgen = self->nextthink->codegen;
3319 if (!(*cgen)((ast_expression*)(self->nextthink), func, false, &thinkval))
3324 if (!ir_block_create_state_op(func->curblock, ast_ctx(self), frameval, thinkval)) {
3325 compile_error(ast_ctx(self), "failed to create STATE instruction");
3329 self->outr = (ir_value*)1;
3333 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3335 ast_expression_codegen *cgen;
3336 std::vector<ir_value*> params;
3337 ir_instr *callinstr;
3339 ir_value *funval = nullptr;
3341 /* return values are never lvalues */
3343 compile_error(ast_ctx(self), "not an l-value (function call)");
3352 cgen = self->func->codegen;
3353 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3359 for (auto &it : self->params) {
3362 if (!(*cgen)(it, func, false, ¶m))
3366 params.push_back(param);
3369 /* varargs counter */
3370 if (self->va_count) {
3372 ir_builder *builder = func->curblock->owner->owner;
3373 cgen = self->va_count->codegen;
3374 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3376 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3377 ir_builder_get_va_count(builder), va_count))
3383 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3384 ast_function_label(func, "call"),
3385 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3389 for (auto &it : params)
3390 ir_call_param(callinstr, it);
3392 *out = ir_call_value(callinstr);
3395 codegen_output_type(self, *out);