13 #define ast_instantiate(T, ctx, destroyfn) \
14 T* self = (T*)mem_a(sizeof(T)); \
19 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
20 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
23 * forward declarations, these need not be in ast.h for obvious
26 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
27 static void ast_array_index_delete(ast_array_index*);
28 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
29 static void ast_argpipe_delete(ast_argpipe*);
30 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
31 static void ast_store_delete(ast_store*);
32 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
33 static void ast_ifthen_delete(ast_ifthen*);
34 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
35 static void ast_ternary_delete(ast_ternary*);
36 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
37 static void ast_loop_delete(ast_loop*);
38 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
39 static void ast_breakcont_delete(ast_breakcont*);
40 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
41 static void ast_switch_delete(ast_switch*);
42 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
43 static void ast_label_delete(ast_label*);
44 static void ast_label_register_goto(ast_label*, ast_goto*);
45 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
46 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
47 static void ast_goto_delete(ast_goto*);
48 static void ast_call_delete(ast_call*);
49 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
50 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
51 static void ast_unary_delete(ast_unary*);
52 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
53 static void ast_entfield_delete(ast_entfield*);
54 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
55 static void ast_return_delete(ast_return*);
56 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
57 static void ast_binstore_delete(ast_binstore*);
58 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
59 static void ast_binary_delete(ast_binary*);
60 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
61 static bool ast_state_codegen(ast_state*, ast_function*, bool lvalue, ir_value**);
63 /* It must not be possible to get here. */
64 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
67 con_err("ast node missing destroy()\n");
71 /* Initialize main ast node aprts */
72 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int node_type)
75 self->destroy = &_ast_node_destroy;
76 self->keep_node = false;
77 self->node_type = node_type;
78 self->side_effects = false;
81 /* weight and side effects */
82 static void _ast_propagate_effects(ast_node *self, ast_node *other)
84 if (ast_side_effects(other))
85 ast_side_effects(self) = true;
87 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
89 /* General expression initialization */
90 static void ast_expression_init(ast_expression *self,
91 ast_expression_codegen *codegen)
93 self->codegen = codegen;
94 self->vtype = TYPE_VOID;
99 self->varparam = nullptr;
101 if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
102 self->flags |= AST_FLAG_BLOCK_COVERAGE;
105 static void ast_expression_delete(ast_expression *self)
108 ast_delete(self->next);
109 for (auto &it : self->type_params)
112 ast_delete(self->varparam);
115 static void ast_expression_delete_full(ast_expression *self)
117 ast_expression_delete(self);
121 ast_value* ast_value_copy(const ast_value *self)
123 ast_value *cp = ast_value_new(self->context, self->name, self->vtype);
125 cp->next = ast_type_copy(self->context, self->next);
127 const ast_expression *fromex = self;
128 ast_expression *selfex = cp;
129 selfex->count = fromex->count;
130 selfex->flags = fromex->flags;
131 for (auto &it : fromex->type_params) {
132 ast_value *v = ast_value_copy(it);
133 selfex->type_params.push_back(v);
138 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
140 const ast_expression *fromex;
141 ast_expression *selfex;
142 self->vtype = other->vtype;
144 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
148 selfex->count = fromex->count;
149 selfex->flags = fromex->flags;
150 for (auto &it : fromex->type_params) {
151 ast_value *v = ast_value_copy(it);
152 selfex->type_params.push_back(v);
156 static ast_expression* ast_shallow_type(lex_ctx_t ctx, qc_type vtype)
158 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
159 ast_expression_init(self, nullptr);
160 self->codegen = nullptr;
161 self->next = nullptr;
166 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
168 const ast_expression *fromex;
169 ast_expression *selfex;
175 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
176 ast_expression_init(self, nullptr);
181 /* This may never be codegen()d */
182 selfex->codegen = nullptr;
184 selfex->vtype = fromex->vtype;
186 selfex->next = ast_type_copy(ctx, fromex->next);
188 selfex->next = nullptr;
190 selfex->count = fromex->count;
191 selfex->flags = fromex->flags;
192 for (auto &it : fromex->type_params) {
193 ast_value *v = ast_value_copy(it);
194 selfex->type_params.push_back(v);
201 bool ast_compare_type(ast_expression *a, ast_expression *b)
203 if (a->vtype == TYPE_NIL ||
204 b->vtype == TYPE_NIL)
206 if (a->vtype != b->vtype)
208 if (!a->next != !b->next)
210 if (a->type_params.size() != b->type_params.size())
212 if ((a->flags & AST_FLAG_TYPE_MASK) !=
213 (b->flags & AST_FLAG_TYPE_MASK) )
217 if (a->type_params.size()) {
219 for (i = 0; i < a->type_params.size(); ++i) {
220 if (!ast_compare_type((ast_expression*)a->type_params[i],
221 (ast_expression*)b->type_params[i]))
226 return ast_compare_type(a->next, b->next);
230 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
237 if (pos + 6 >= bufsize)
239 util_strncpy(buf + pos, "(null)", 6);
243 if (pos + 1 >= bufsize)
248 util_strncpy(buf + pos, "(variant)", 9);
253 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
256 if (pos + 3 >= bufsize)
260 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
261 if (pos + 1 >= bufsize)
267 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
268 if (pos + 2 >= bufsize)
270 if (e->type_params.empty()) {
276 pos = ast_type_to_string_impl((ast_expression*)(e->type_params[0]), buf, bufsize, pos);
277 for (i = 1; i < e->type_params.size(); ++i) {
278 if (pos + 2 >= bufsize)
282 pos = ast_type_to_string_impl((ast_expression*)(e->type_params[i]), buf, bufsize, pos);
284 if (pos + 1 >= bufsize)
290 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
291 if (pos + 1 >= bufsize)
294 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
295 if (pos + 1 >= bufsize)
301 typestr = type_name[e->vtype];
302 typelen = strlen(typestr);
303 if (pos + typelen >= bufsize)
305 util_strncpy(buf + pos, typestr, typelen);
306 return pos + typelen;
310 buf[bufsize-3] = '.';
311 buf[bufsize-2] = '.';
312 buf[bufsize-1] = '.';
316 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
318 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
322 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
323 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, qc_type t)
325 ast_instantiate(ast_value, ctx, ast_value_delete);
326 ast_expression_init((ast_expression*)self,
327 (ast_expression_codegen*)&ast_value_codegen);
328 self->keep_node = true; /* keep */
330 self->name = name ? util_strdup(name) : nullptr;
332 self->next = nullptr;
333 self->isfield = false;
335 self->hasvalue = false;
337 self->inexact = false;
339 memset(&self->constval, 0, sizeof(self->constval));
341 self->ir_v = nullptr;
342 self->ir_values = nullptr;
343 self->ir_value_count = 0;
345 self->setter = nullptr;
346 self->getter = nullptr;
347 self->desc = nullptr;
349 self->argcounter = nullptr;
350 self->intrinsic = false;
355 void ast_value_delete(ast_value* self)
358 mem_d((void*)self->name);
359 if (self->argcounter)
360 mem_d((void*)self->argcounter);
361 if (self->hasvalue) {
365 mem_d((void*)self->constval.vstring);
368 /* unlink us from the function node */
369 self->constval.vfunc->function_type = nullptr;
371 /* NOTE: delete function? currently collected in
372 * the parser structure
379 mem_d(self->ir_values);
384 // initlist imples an array which implies .next in the expression exists.
385 if (self->initlist.size() && self->next->vtype == TYPE_STRING) {
386 for (auto &it : self->initlist)
391 ast_expression_delete((ast_expression*)self);
396 void ast_value_params_add(ast_value *self, ast_value *p)
398 self->type_params.push_back(p);
401 bool ast_value_set_name(ast_value *self, const char *name)
404 mem_d((void*)self->name);
405 self->name = util_strdup(name);
409 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
410 ast_expression* left, ast_expression* right)
412 ast_instantiate(ast_binary, ctx, ast_binary_delete);
413 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
415 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
416 ast_unary *unary = ((ast_unary*)right);
417 ast_expression *normal = unary->operand;
419 /* make a-(-b) => a + b */
420 if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
421 if (op == INSTR_SUB_F) {
424 ++opts_optimizationcount[OPTIM_PEEPHOLE];
425 } else if (op == INSTR_SUB_V) {
428 ++opts_optimizationcount[OPTIM_PEEPHOLE];
436 self->right_first = false;
438 ast_propagate_effects(self, left);
439 ast_propagate_effects(self, right);
441 if (op >= INSTR_EQ_F && op <= INSTR_GT)
442 self->vtype = TYPE_FLOAT;
443 else if (op == INSTR_AND || op == INSTR_OR) {
444 if (OPTS_FLAG(PERL_LOGIC))
445 ast_type_adopt(self, right);
447 self->vtype = TYPE_FLOAT;
449 else if (op == INSTR_BITAND || op == INSTR_BITOR)
450 self->vtype = TYPE_FLOAT;
451 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
452 self->vtype = TYPE_VECTOR;
453 else if (op == INSTR_MUL_V)
454 self->vtype = TYPE_FLOAT;
456 self->vtype = left->vtype;
459 self->refs = AST_REF_ALL;
464 void ast_binary_delete(ast_binary *self)
466 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
467 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
469 ast_expression_delete((ast_expression*)self);
473 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
474 ast_expression* left, ast_expression* right)
476 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
477 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
479 ast_side_effects(self) = true;
481 self->opstore = storop;
484 self->source = right;
486 self->keep_dest = false;
488 ast_type_adopt(self, left);
492 void ast_binstore_delete(ast_binstore *self)
494 if (!self->keep_dest)
495 ast_unref(self->dest);
496 ast_unref(self->source);
497 ast_expression_delete((ast_expression*)self);
501 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
502 ast_expression *expr)
504 ast_instantiate(ast_unary, ctx, ast_unary_delete);
505 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
508 self->operand = expr;
511 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
512 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
514 /* Handle for double negation */
515 if (((ast_unary*)expr)->op == op)
516 prev = (ast_unary*)((ast_unary*)expr)->operand;
518 if (ast_istype(prev, ast_unary)) {
519 ast_expression_delete((ast_expression*)self);
521 ++opts_optimizationcount[OPTIM_PEEPHOLE];
526 ast_propagate_effects(self, expr);
528 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
529 self->vtype = TYPE_FLOAT;
530 } else if (op == VINSTR_NEG_V) {
531 self->vtype = TYPE_VECTOR;
533 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
539 void ast_unary_delete(ast_unary *self)
541 if (self->operand) ast_unref(self->operand);
542 ast_expression_delete((ast_expression*)self);
546 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
548 ast_instantiate(ast_return, ctx, ast_return_delete);
549 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
551 self->operand = expr;
554 ast_propagate_effects(self, expr);
559 void ast_return_delete(ast_return *self)
562 ast_unref(self->operand);
563 ast_expression_delete((ast_expression*)self);
567 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
569 if (field->vtype != TYPE_FIELD) {
570 compile_error(ctx, "ast_entfield_new with expression not of type field");
573 return ast_entfield_new_force(ctx, entity, field, field->next);
576 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
578 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
582 /* Error: field has no type... */
586 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
588 self->entity = entity;
590 ast_propagate_effects(self, entity);
591 ast_propagate_effects(self, field);
593 ast_type_adopt(self, outtype);
597 void ast_entfield_delete(ast_entfield *self)
599 ast_unref(self->entity);
600 ast_unref(self->field);
601 ast_expression_delete((ast_expression*)self);
605 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
607 ast_instantiate(ast_member, ctx, ast_member_delete);
613 if (owner->vtype != TYPE_VECTOR &&
614 owner->vtype != TYPE_FIELD) {
615 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
620 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
621 self->keep_node = true; /* keep */
623 if (owner->vtype == TYPE_VECTOR) {
624 self->vtype = TYPE_FLOAT;
625 self->next = nullptr;
627 self->vtype = TYPE_FIELD;
628 self->next = ast_shallow_type(ctx, TYPE_FLOAT);
631 self->rvalue = false;
633 ast_propagate_effects(self, owner);
637 self->name = util_strdup(name);
639 self->name = nullptr;
644 void ast_member_delete(ast_member *self)
646 /* The owner is always an ast_value, which has .keep_node=true,
647 * also: ast_members are usually deleted after the owner, thus
648 * this will cause invalid access
649 ast_unref(self->owner);
650 * once we allow (expression).x to access a vector-member, we need
651 * to change this: preferably by creating an alternate ast node for this
652 * purpose that is not garbage-collected.
654 ast_expression_delete((ast_expression*)self);
659 bool ast_member_set_name(ast_member *self, const char *name)
662 mem_d((void*)self->name);
663 self->name = util_strdup(name);
667 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
669 ast_expression *outtype;
670 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
672 outtype = array->next;
675 /* Error: field has no type... */
679 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
683 ast_propagate_effects(self, array);
684 ast_propagate_effects(self, index);
686 ast_type_adopt(self, outtype);
687 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
688 if (self->vtype != TYPE_ARRAY) {
689 compile_error(ast_ctx(self), "array_index node on type");
690 ast_array_index_delete(self);
693 self->array = outtype;
694 self->vtype = TYPE_FIELD;
700 void ast_array_index_delete(ast_array_index *self)
703 ast_unref(self->array);
705 ast_unref(self->index);
706 ast_expression_delete((ast_expression*)self);
710 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
712 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
713 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
715 self->vtype = TYPE_NOEXPR;
719 void ast_argpipe_delete(ast_argpipe *self)
722 ast_unref(self->index);
723 ast_expression_delete((ast_expression*)self);
727 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
729 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
730 if (!ontrue && !onfalse) {
731 /* because it is invalid */
735 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
738 self->on_true = ontrue;
739 self->on_false = onfalse;
740 ast_propagate_effects(self, cond);
742 ast_propagate_effects(self, ontrue);
744 ast_propagate_effects(self, onfalse);
749 void ast_ifthen_delete(ast_ifthen *self)
751 ast_unref(self->cond);
753 ast_unref(self->on_true);
755 ast_unref(self->on_false);
756 ast_expression_delete((ast_expression*)self);
760 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
762 ast_expression *exprtype = ontrue;
763 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
764 /* This time NEITHER must be nullptr */
765 if (!ontrue || !onfalse) {
769 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
772 self->on_true = ontrue;
773 self->on_false = onfalse;
774 ast_propagate_effects(self, cond);
775 ast_propagate_effects(self, ontrue);
776 ast_propagate_effects(self, onfalse);
778 if (ontrue->vtype == TYPE_NIL)
780 ast_type_adopt(self, exprtype);
785 void ast_ternary_delete(ast_ternary *self)
787 /* the if()s are only there because computed-gotos can set them
790 if (self->cond) ast_unref(self->cond);
791 if (self->on_true) ast_unref(self->on_true);
792 if (self->on_false) ast_unref(self->on_false);
793 ast_expression_delete((ast_expression*)self);
797 ast_loop* ast_loop_new(lex_ctx_t ctx,
798 ast_expression *initexpr,
799 ast_expression *precond, bool pre_not,
800 ast_expression *postcond, bool post_not,
801 ast_expression *increment,
802 ast_expression *body)
804 ast_instantiate(ast_loop, ctx, ast_loop_delete);
805 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
807 self->initexpr = initexpr;
808 self->precond = precond;
809 self->postcond = postcond;
810 self->increment = increment;
813 self->pre_not = pre_not;
814 self->post_not = post_not;
817 ast_propagate_effects(self, initexpr);
819 ast_propagate_effects(self, precond);
821 ast_propagate_effects(self, postcond);
823 ast_propagate_effects(self, increment);
825 ast_propagate_effects(self, body);
830 void ast_loop_delete(ast_loop *self)
833 ast_unref(self->initexpr);
835 ast_unref(self->precond);
837 ast_unref(self->postcond);
839 ast_unref(self->increment);
841 ast_unref(self->body);
842 ast_expression_delete((ast_expression*)self);
846 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
848 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
849 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
851 self->is_continue = iscont;
852 self->levels = levels;
857 void ast_breakcont_delete(ast_breakcont *self)
859 ast_expression_delete((ast_expression*)self);
863 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
865 ast_instantiate(ast_switch, ctx, ast_switch_delete);
866 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
870 ast_propagate_effects(self, op);
875 void ast_switch_delete(ast_switch *self)
877 ast_unref(self->operand);
879 for (auto &it : self->cases) {
885 ast_expression_delete((ast_expression*)self);
889 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
891 ast_instantiate(ast_label, ctx, ast_label_delete);
892 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
894 self->vtype = TYPE_NOEXPR;
896 self->name = util_strdup(name);
897 self->irblock = nullptr;
898 self->undefined = undefined;
903 void ast_label_delete(ast_label *self)
905 mem_d((void*)self->name);
906 ast_expression_delete((ast_expression*)self);
910 static void ast_label_register_goto(ast_label *self, ast_goto *g)
912 self->gotos.push_back(g);
915 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
917 ast_instantiate(ast_goto, ctx, ast_goto_delete);
918 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
920 self->name = util_strdup(name);
921 self->target = nullptr;
922 self->irblock_from = nullptr;
927 void ast_goto_delete(ast_goto *self)
929 mem_d((void*)self->name);
930 ast_expression_delete((ast_expression*)self);
934 void ast_goto_set_label(ast_goto *self, ast_label *label)
936 self->target = label;
939 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
941 ast_instantiate(ast_state, ctx, ast_state_delete);
942 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_state_codegen);
943 self->framenum = frame;
944 self->nextthink = think;
948 void ast_state_delete(ast_state *self)
951 ast_unref(self->framenum);
953 ast_unref(self->nextthink);
955 ast_expression_delete((ast_expression*)self);
959 ast_call* ast_call_new(lex_ctx_t ctx,
960 ast_expression *funcexpr)
962 ast_instantiate(ast_call, ctx, ast_call_delete);
963 if (!funcexpr->next) {
964 compile_error(ctx, "not a function");
968 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
970 ast_side_effects(self) = true;
972 self->func = funcexpr;
973 self->va_count = nullptr;
975 ast_type_adopt(self, funcexpr->next);
980 void ast_call_delete(ast_call *self)
982 for (auto &it : self->params)
986 ast_unref(self->func);
989 ast_unref(self->va_count);
991 ast_expression_delete((ast_expression*)self);
995 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1001 if (!va_type || !ast_compare_type(va_type, exp_type))
1003 if (va_type && exp_type)
1005 ast_type_to_string(va_type, tgot, sizeof(tgot));
1006 ast_type_to_string(exp_type, texp, sizeof(texp));
1007 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1008 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1009 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1013 compile_error(ast_ctx(self),
1014 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1021 ast_type_to_string(exp_type, texp, sizeof(texp));
1022 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1023 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1024 "piped variadic argument may differ in type: expected type %s",
1028 compile_error(ast_ctx(self),
1029 "piped variadic argument may differ in type: expected type %s",
1038 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1044 const ast_expression *func = self->func;
1045 size_t count = self->params.size();
1046 if (count > func->type_params.size())
1047 count = func->type_params.size();
1049 for (i = 0; i < count; ++i) {
1050 if (ast_istype(self->params[i], ast_argpipe)) {
1051 /* warn about type safety instead */
1053 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1056 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->type_params[i]))
1059 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->type_params[i])))
1061 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1062 ast_type_to_string((ast_expression*)func->type_params[i], texp, sizeof(texp));
1063 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1064 (unsigned int)(i+1), texp, tgot);
1065 /* we don't immediately return */
1069 count = self->params.size();
1070 if (count > func->type_params.size() && func->varparam) {
1071 for (; i < count; ++i) {
1072 if (ast_istype(self->params[i], ast_argpipe)) {
1073 /* warn about type safety instead */
1075 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1078 if (!ast_call_check_vararg(self, va_type, func->varparam))
1081 else if (!ast_compare_type(self->params[i], func->varparam))
1083 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1084 ast_type_to_string(func->varparam, texp, sizeof(texp));
1085 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1086 (unsigned int)(i+1), texp, tgot);
1087 /* we don't immediately return */
1095 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1096 ast_expression *dest, ast_expression *source)
1098 ast_instantiate(ast_store, ctx, ast_store_delete);
1099 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1101 ast_side_effects(self) = true;
1105 self->source = source;
1107 ast_type_adopt(self, dest);
1112 void ast_store_delete(ast_store *self)
1114 ast_unref(self->dest);
1115 ast_unref(self->source);
1116 ast_expression_delete((ast_expression*)self);
1120 ast_block* ast_block_new(lex_ctx_t ctx)
1122 ast_instantiate(ast_block, ctx, ast_block_delete);
1123 ast_expression_init((ast_expression*)self,
1124 (ast_expression_codegen*)&ast_block_codegen);
1128 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1130 ast_propagate_effects(self, e);
1131 self->exprs.push_back(e);
1133 ast_delete(self->next);
1134 self->next = nullptr;
1136 ast_type_adopt(self, e);
1140 void ast_block_collect(ast_block *self, ast_expression *expr)
1142 self->collect.push_back(expr);
1143 expr->keep_node = true;
1146 void ast_block_delete(ast_block *self)
1148 for (auto &it : self->exprs) ast_unref(it);
1149 for (auto &it : self->locals) ast_delete(it);
1150 for (auto &it : self->collect) ast_delete(it);
1151 ast_expression_delete((ast_expression*)self);
1155 void ast_block_set_type(ast_block *self, ast_expression *from)
1158 ast_delete(self->next);
1159 ast_type_adopt(self, from);
1162 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1164 ast_instantiate(ast_function, ctx, ast_function_delete);
1167 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1169 } else if (vtype->hasvalue || vtype->vtype != TYPE_FUNCTION) {
1170 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1172 (int)vtype->hasvalue,
1177 self->function_type = vtype;
1178 self->name = name ? util_strdup(name) : nullptr;
1180 self->labelcount = 0;
1183 self->ir_func = nullptr;
1184 self->curblock = nullptr;
1186 vtype->hasvalue = true;
1187 vtype->constval.vfunc = self;
1189 self->varargs = nullptr;
1190 self->argc = nullptr;
1191 self->fixedparams = nullptr;
1192 self->return_value = nullptr;
1193 self->static_count = 0;
1202 void ast_function_delete(ast_function *self)
1205 mem_d((void*)self->name);
1206 if (self->function_type) {
1207 /* ast_value_delete(self->function_type); */
1208 self->function_type->hasvalue = false;
1209 self->function_type->constval.vfunc = nullptr;
1210 /* We use unref - if it was stored in a global table it is supposed
1211 * to be deleted from *there*
1213 ast_unref(self->function_type);
1215 for (auto &it : self->static_names)
1217 // FIXME::DELME:: unique_ptr used on ast_block
1218 //for (auto &it : self->blocks)
1221 ast_delete(self->varargs);
1223 ast_delete(self->argc);
1224 if (self->fixedparams)
1225 ast_unref(self->fixedparams);
1226 if (self->return_value)
1227 ast_unref(self->return_value);
1231 const char* ast_function_label(ast_function *self, const char *prefix)
1237 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1238 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1239 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1244 id = (self->labelcount++);
1245 len = strlen(prefix);
1247 from = self->labelbuf + sizeof(self->labelbuf)-1;
1250 *from-- = (id%10) + '0';
1254 memcpy(from - len, prefix, len);
1258 /*********************************************************************/
1260 * by convention you must never pass nullptr to the 'ir_value **out'
1261 * parameter. If you really don't care about the output, pass a dummy.
1262 * But I can't imagine a pituation where the output is truly unnecessary.
1265 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1267 if (out->vtype == TYPE_FIELD)
1268 out->fieldtype = self->next->vtype;
1269 if (out->vtype == TYPE_FUNCTION)
1270 out->outtype = self->next->vtype;
1273 #define codegen_output_type(a,o) (_ast_codegen_output_type(static_cast<ast_expression*>((a)),(o)))
1275 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1279 if (self->vtype == TYPE_NIL) {
1280 *out = func->ir_func->owner->nil;
1283 /* NOTE: This is the codegen for a variable used in an
1284 * It is not the codegen to generate the value. For this purpose,
1285 * ast_local_codegen and ast_global_codegen are to be used before this
1286 * is executed. ast_function_codegen should take care of its locals,
1287 * and the ast-user should take care of ast_global_codegen to be used
1288 * on all the globals.
1291 char tname[1024]; /* typename is reserved in C++ */
1292 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1293 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1300 static bool ast_global_array_set(ast_value *self)
1302 size_t count = self->initlist.size();
1305 if (count > self->count) {
1306 compile_error(ast_ctx(self), "too many elements in initializer");
1307 count = self->count;
1309 else if (count < self->count) {
1311 compile_warning(ast_ctx(self), "not all elements are initialized");
1315 for (i = 0; i != count; ++i) {
1316 switch (self->next->vtype) {
1318 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1322 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1326 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1330 /* we don't support them in any other place yet either */
1331 compile_error(ast_ctx(self), "TODO: nested arrays");
1334 /* this requiers a bit more work - similar to the fields I suppose */
1335 compile_error(ast_ctx(self), "global of type function not properly generated");
1338 if (!self->initlist[i].vfield) {
1339 compile_error(ast_ctx(self), "field constant without vfield set");
1342 if (!self->initlist[i].vfield->ir_v) {
1343 compile_error(ast_ctx(self), "field constant generated before its field");
1346 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1350 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1357 static bool check_array(ast_value *self, ast_value *array)
1359 if (array->flags & AST_FLAG_ARRAY_INIT && array->initlist.empty()) {
1360 compile_error(ast_ctx(self), "array without size: %s", self->name);
1363 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1364 if (!array->count || array->count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1365 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->count);
1371 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1373 ir_value *v = nullptr;
1375 if (self->vtype == TYPE_NIL) {
1376 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1380 if (self->hasvalue && self->vtype == TYPE_FUNCTION)
1382 ir_function *func = ir_builder_create_function(ir, self->name, self->next->vtype);
1385 func->context = ast_ctx(self);
1386 func->value->context = ast_ctx(self);
1388 self->constval.vfunc->ir_func = func;
1389 self->ir_v = func->value;
1390 if (self->flags & AST_FLAG_INCLUDE_DEF)
1391 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1392 if (self->flags & AST_FLAG_ERASEABLE)
1393 self->ir_v->flags |= IR_FLAG_ERASABLE;
1394 if (self->flags & AST_FLAG_BLOCK_COVERAGE)
1395 func->flags |= IR_FLAG_BLOCK_COVERAGE;
1396 /* The function is filled later on ast_function_codegen... */
1400 if (isfield && self->vtype == TYPE_FIELD) {
1401 ast_expression *fieldtype = self->next;
1403 if (self->hasvalue) {
1404 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1408 if (fieldtype->vtype == TYPE_ARRAY) {
1413 ast_expression *elemtype;
1415 ast_value *array = (ast_value*)fieldtype;
1417 if (!ast_istype(fieldtype, ast_value)) {
1418 compile_error(ast_ctx(self), "internal error: ast_value required");
1422 if (!check_array(self, array))
1425 elemtype = array->next;
1426 vtype = elemtype->vtype;
1428 v = ir_builder_create_field(ir, self->name, vtype);
1430 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1433 v->context = ast_ctx(self);
1434 v->unique_life = true;
1436 array->ir_v = self->ir_v = v;
1438 if (self->flags & AST_FLAG_INCLUDE_DEF)
1439 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1440 if (self->flags & AST_FLAG_ERASEABLE)
1441 self->ir_v->flags |= IR_FLAG_ERASABLE;
1443 namelen = strlen(self->name);
1444 name = (char*)mem_a(namelen + 16);
1445 util_strncpy(name, self->name, namelen);
1447 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->count);
1448 array->ir_values[0] = v;
1449 for (ai = 1; ai < array->count; ++ai) {
1450 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1451 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1452 if (!array->ir_values[ai]) {
1454 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1457 array->ir_values[ai]->context = ast_ctx(self);
1458 array->ir_values[ai]->unique_life = true;
1459 array->ir_values[ai]->locked = true;
1460 if (self->flags & AST_FLAG_INCLUDE_DEF)
1461 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1467 v = ir_builder_create_field(ir, self->name, self->next->vtype);
1470 v->context = ast_ctx(self);
1472 if (self->flags & AST_FLAG_INCLUDE_DEF)
1473 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1475 if (self->flags & AST_FLAG_ERASEABLE)
1476 self->ir_v->flags |= IR_FLAG_ERASABLE;
1481 if (self->vtype == TYPE_ARRAY) {
1486 ast_expression *elemtype = self->next;
1487 qc_type vtype = elemtype->vtype;
1489 if (self->flags & AST_FLAG_ARRAY_INIT && !self->count) {
1490 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1494 /* same as with field arrays */
1495 if (!check_array(self, self))
1498 v = ir_builder_create_global(ir, self->name, vtype);
1500 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1503 v->context = ast_ctx(self);
1504 v->unique_life = true;
1507 if (self->flags & AST_FLAG_INCLUDE_DEF)
1508 v->flags |= IR_FLAG_INCLUDE_DEF;
1509 if (self->flags & AST_FLAG_ERASEABLE)
1510 self->ir_v->flags |= IR_FLAG_ERASABLE;
1512 namelen = strlen(self->name);
1513 name = (char*)mem_a(namelen + 16);
1514 util_strncpy(name, self->name, namelen);
1516 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->count);
1517 self->ir_values[0] = v;
1518 for (ai = 1; ai < self->count; ++ai) {
1519 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1520 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1521 if (!self->ir_values[ai]) {
1523 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1526 self->ir_values[ai]->context = ast_ctx(self);
1527 self->ir_values[ai]->unique_life = true;
1528 self->ir_values[ai]->locked = true;
1529 if (self->flags & AST_FLAG_INCLUDE_DEF)
1530 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1536 /* Arrays don't do this since there's no "array" value which spans across the
1539 v = ir_builder_create_global(ir, self->name, self->vtype);
1541 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1544 codegen_output_type(self, v);
1545 v->context = ast_ctx(self);
1548 /* link us to the ir_value */
1552 if (self->flags & AST_FLAG_INCLUDE_DEF)
1553 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1554 if (self->flags & AST_FLAG_ERASEABLE)
1555 self->ir_v->flags |= IR_FLAG_ERASABLE;
1558 if (self->hasvalue) {
1559 switch (self->vtype)
1562 if (!ir_value_set_float(v, self->constval.vfloat))
1566 if (!ir_value_set_vector(v, self->constval.vvec))
1570 if (!ir_value_set_string(v, self->constval.vstring))
1574 ast_global_array_set(self);
1577 compile_error(ast_ctx(self), "global of type function not properly generated");
1579 /* Cannot generate an IR value for a function,
1580 * need a pointer pointing to a function rather.
1583 if (!self->constval.vfield) {
1584 compile_error(ast_ctx(self), "field constant without vfield set");
1587 if (!self->constval.vfield->ir_v) {
1588 compile_error(ast_ctx(self), "field constant generated before its field");
1591 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1595 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1601 error: /* clean up */
1606 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1608 ir_value *v = nullptr;
1610 if (self->vtype == TYPE_NIL) {
1611 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1615 if (self->hasvalue && self->vtype == TYPE_FUNCTION)
1617 /* Do we allow local functions? I think not...
1618 * this is NOT a function pointer atm.
1623 if (self->vtype == TYPE_ARRAY) {
1628 ast_expression *elemtype = self->next;
1629 qc_type vtype = elemtype->vtype;
1631 func->flags |= IR_FLAG_HAS_ARRAYS;
1633 if (param && !(self->flags & AST_FLAG_IS_VARARG)) {
1634 compile_error(ast_ctx(self), "array-parameters are not supported");
1638 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1639 if (!check_array(self, self))
1642 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->count);
1643 if (!self->ir_values) {
1644 compile_error(ast_ctx(self), "failed to allocate array values");
1648 v = ir_function_create_local(func, self->name, vtype, param);
1650 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1653 v->context = ast_ctx(self);
1654 v->unique_life = true;
1657 namelen = strlen(self->name);
1658 name = (char*)mem_a(namelen + 16);
1659 util_strncpy(name, self->name, namelen);
1661 self->ir_values[0] = v;
1662 for (ai = 1; ai < self->count; ++ai) {
1663 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1664 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1665 if (!self->ir_values[ai]) {
1666 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1669 self->ir_values[ai]->context = ast_ctx(self);
1670 self->ir_values[ai]->unique_life = true;
1671 self->ir_values[ai]->locked = true;
1677 v = ir_function_create_local(func, self->name, self->vtype, param);
1680 codegen_output_type(self, v);
1681 v->context = ast_ctx(self);
1684 /* A constant local... hmmm...
1685 * I suppose the IR will have to deal with this
1687 if (self->hasvalue) {
1688 switch (self->vtype)
1691 if (!ir_value_set_float(v, self->constval.vfloat))
1695 if (!ir_value_set_vector(v, self->constval.vvec))
1699 if (!ir_value_set_string(v, self->constval.vstring))
1703 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1708 /* link us to the ir_value */
1712 if (!ast_generate_accessors(self, func->owner))
1716 error: /* clean up */
1721 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1724 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1725 if (!self->setter || !self->getter)
1727 for (i = 0; i < self->count; ++i) {
1728 if (!self->ir_values) {
1729 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1732 if (!self->ir_values[i]) {
1733 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1736 if (!self->ir_values[i]->life.empty()) {
1737 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1742 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1744 if (!ast_global_codegen (self->setter, ir, false) ||
1745 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1746 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1748 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1749 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1754 if (!ast_global_codegen (self->getter, ir, false) ||
1755 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1756 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1758 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1759 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1763 for (i = 0; i < self->count; ++i)
1764 self->ir_values[i]->life.clear();
1765 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1769 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1774 ast_expression_codegen *cgen;
1778 irf = self->ir_func;
1780 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1784 /* fill the parameter list */
1785 ec = self->function_type;
1786 for (auto &it : ec->type_params) {
1787 if (it->vtype == TYPE_FIELD)
1788 vec_push(irf->params, it->next->vtype);
1790 vec_push(irf->params, it->vtype);
1791 if (!self->builtin) {
1792 if (!ast_local_codegen(it, self->ir_func, true))
1797 if (self->varargs) {
1798 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1800 irf->max_varargs = self->varargs->count;
1803 if (self->builtin) {
1804 irf->builtin = self->builtin;
1808 /* have a local return value variable? */
1809 if (self->return_value) {
1810 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1814 if (self->blocks.empty()) {
1815 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1819 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1820 if (!self->curblock) {
1821 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1829 if (!ast_local_codegen(self->argc, self->ir_func, true))
1831 cgen = self->argc->codegen;
1832 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1834 cgen = self->fixedparams->codegen;
1835 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1837 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1838 ast_function_label(self, "va_count"), INSTR_SUB_F,
1839 ir_builder_get_va_count(ir), fixed);
1842 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1849 for (auto &it : self->blocks) {
1851 if (!(*cgen)(it.get(), self, false, &dummy))
1855 /* TODO: check return types */
1856 if (!self->curblock->final)
1858 if (!self->function_type->next ||
1859 self->function_type->next->vtype == TYPE_VOID)
1861 return ir_block_create_return(self->curblock, ast_ctx(self), nullptr);
1863 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1865 if (self->return_value) {
1866 cgen = self->return_value->codegen;
1867 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1869 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1871 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1872 "control reaches end of non-void function (`%s`) via %s",
1873 self->name, self->curblock->label.c_str()))
1877 return ir_block_create_return(self->curblock, ast_ctx(self), nullptr);
1883 static bool starts_a_label(ast_expression *ex)
1885 while (ex && ast_istype(ex, ast_block)) {
1886 ast_block *b = (ast_block*)ex;
1891 return ast_istype(ex, ast_label);
1894 /* Note, you will not see ast_block_codegen generate ir_blocks.
1895 * To the AST and the IR, blocks are 2 different things.
1896 * In the AST it represents a block of code, usually enclosed in
1897 * curly braces {...}.
1898 * While in the IR it represents a block in terms of control-flow.
1900 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1902 /* We don't use this
1903 * Note: an ast-representation using the comma-operator
1904 * of the form: (a, b, c) = x should not assign to c...
1907 compile_error(ast_ctx(self), "not an l-value (code-block)");
1916 /* output is nullptr at first, we'll have each expression
1917 * assign to out output, thus, a comma-operator represention
1918 * using an ast_block will return the last generated value,
1919 * so: (b, c) + a executed both b and c, and returns c,
1920 * which is then added to a.
1924 /* generate locals */
1925 for (auto &it : self->locals) {
1926 if (!ast_local_codegen(it, func->ir_func, false)) {
1927 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1928 compile_error(ast_ctx(self), "failed to generate local `%s`", it->name);
1933 for (auto &it : self->exprs) {
1934 ast_expression_codegen *gen;
1935 if (func->curblock->final && !starts_a_label(it)) {
1936 if (compile_warning(ast_ctx(it), WARN_UNREACHABLE_CODE, "unreachable statement"))
1941 if (!(*gen)(it, func, false, out))
1950 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1952 ast_expression_codegen *cgen;
1953 ir_value *left = nullptr;
1954 ir_value *right = nullptr;
1958 ast_array_index *ai = nullptr;
1960 if (lvalue && self->outl) {
1965 if (!lvalue && self->outr) {
1970 if (ast_istype(self->dest, ast_array_index))
1973 ai = (ast_array_index*)self->dest;
1974 idx = (ast_value*)ai->index;
1976 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1981 /* we need to call the setter */
1982 ir_value *iridx, *funval;
1986 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1990 arr = (ast_value*)ai->array;
1991 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1992 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1996 cgen = idx->codegen;
1997 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2000 cgen = arr->setter->codegen;
2001 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2004 cgen = self->source->codegen;
2005 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2008 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2011 ir_call_param(call, iridx);
2012 ir_call_param(call, right);
2019 cgen = self->dest->codegen;
2021 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2025 cgen = self->source->codegen;
2027 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2030 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2035 /* Theoretically, an assinment returns its left side as an
2036 * lvalue, if we don't need an lvalue though, we return
2037 * the right side as an rvalue, otherwise we have to
2038 * somehow know whether or not we need to dereference the pointer
2039 * on the left side - that is: OP_LOAD if it was an address.
2040 * Also: in original QC we cannot OP_LOADP *anyway*.
2042 *out = (lvalue ? left : right);
2047 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2049 ast_expression_codegen *cgen;
2050 ir_value *left, *right;
2052 /* A binary operation cannot yield an l-value */
2054 compile_error(ast_ctx(self), "not an l-value (binop)");
2063 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2064 (self->op == INSTR_AND || self->op == INSTR_OR))
2066 /* NOTE: The short-logic path will ignore right_first */
2068 /* short circuit evaluation */
2069 ir_block *other, *merge;
2070 ir_block *from_left, *from_right;
2074 /* prepare end-block */
2075 merge_id = func->ir_func->blocks.size();
2076 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2078 /* generate the left expression */
2079 cgen = self->left->codegen;
2080 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2082 /* remember the block */
2083 from_left = func->curblock;
2085 /* create a new block for the right expression */
2086 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2087 if (self->op == INSTR_AND) {
2088 /* on AND: left==true -> other */
2089 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2092 /* on OR: left==false -> other */
2093 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2096 /* use the likely flag */
2097 vec_last(func->curblock->instr)->likely = true;
2099 /* enter the right-expression's block */
2100 func->curblock = other;
2102 cgen = self->right->codegen;
2103 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2105 /* remember block */
2106 from_right = func->curblock;
2108 /* jump to the merge block */
2109 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2112 algo::shiftback(func->ir_func->blocks.begin() + merge_id,
2113 func->ir_func->blocks.end());
2115 //func->ir_func->blocks[merge_id].release();
2116 //func->ir_func->blocks.erase(func->ir_func->blocks.begin() + merge_id);
2117 //func->ir_func->blocks.emplace_back(merge);
2119 func->curblock = merge;
2120 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2121 ast_function_label(func, "sce_value"),
2123 ir_phi_add(phi, from_left, left);
2124 ir_phi_add(phi, from_right, right);
2125 *out = ir_phi_value(phi);
2129 if (!OPTS_FLAG(PERL_LOGIC)) {
2131 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2132 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2133 ast_function_label(func, "sce_bool_v"),
2137 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2138 ast_function_label(func, "sce_bool"),
2143 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2144 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2145 ast_function_label(func, "sce_bool_s"),
2149 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2150 ast_function_label(func, "sce_bool"),
2156 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2157 ast_function_label(func, "sce_bool"),
2158 INSTR_AND, *out, *out);
2165 codegen_output_type(self, *out);
2169 if (self->right_first) {
2170 cgen = self->right->codegen;
2171 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2173 cgen = self->left->codegen;
2174 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2177 cgen = self->left->codegen;
2178 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2180 cgen = self->right->codegen;
2181 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2185 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2186 self->op, left, right);
2190 codegen_output_type(self, *out);
2195 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2197 ast_expression_codegen *cgen;
2198 ir_value *leftl = nullptr, *leftr, *right, *bin;
2202 ast_array_index *ai = nullptr;
2203 ir_value *iridx = nullptr;
2205 if (lvalue && self->outl) {
2210 if (!lvalue && self->outr) {
2215 if (ast_istype(self->dest, ast_array_index))
2218 ai = (ast_array_index*)self->dest;
2219 idx = (ast_value*)ai->index;
2221 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2225 /* for a binstore we need both an lvalue and an rvalue for the left side */
2226 /* rvalue of destination! */
2228 cgen = idx->codegen;
2229 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2232 cgen = self->dest->codegen;
2233 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2236 /* source as rvalue only */
2237 cgen = self->source->codegen;
2238 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2241 /* now the binary */
2242 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2243 self->opbin, leftr, right);
2247 /* we need to call the setter */
2252 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2256 arr = (ast_value*)ai->array;
2257 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2258 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2262 cgen = arr->setter->codegen;
2263 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2266 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2269 ir_call_param(call, iridx);
2270 ir_call_param(call, bin);
2273 /* now store them */
2274 cgen = self->dest->codegen;
2275 /* lvalue of destination */
2276 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2280 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2285 /* Theoretically, an assinment returns its left side as an
2286 * lvalue, if we don't need an lvalue though, we return
2287 * the right side as an rvalue, otherwise we have to
2288 * somehow know whether or not we need to dereference the pointer
2289 * on the left side - that is: OP_LOAD if it was an address.
2290 * Also: in original QC we cannot OP_LOADP *anyway*.
2292 *out = (lvalue ? leftl : bin);
2297 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2299 ast_expression_codegen *cgen;
2302 /* An unary operation cannot yield an l-value */
2304 compile_error(ast_ctx(self), "not an l-value (binop)");
2313 cgen = self->operand->codegen;
2315 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2318 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2327 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2329 ast_expression_codegen *cgen;
2334 /* In the context of a return operation, we don't actually return
2338 compile_error(ast_ctx(self), "return-expression is not an l-value");
2343 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2346 self->outr = (ir_value*)1;
2348 if (self->operand) {
2349 cgen = self->operand->codegen;
2351 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2354 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2357 if (!ir_block_create_return(func->curblock, ast_ctx(self), nullptr))
2364 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2366 ast_expression_codegen *cgen;
2367 ir_value *ent, *field;
2369 /* This function needs to take the 'lvalue' flag into account!
2370 * As lvalue we provide a field-pointer, as rvalue we provide the
2374 if (lvalue && self->outl) {
2379 if (!lvalue && self->outr) {
2384 cgen = self->entity->codegen;
2385 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2388 cgen = self->field->codegen;
2389 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2394 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2397 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2398 ent, field, self->vtype);
2399 /* Done AFTER error checking:
2400 codegen_output_type(self, *out);
2404 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2405 (lvalue ? "ADDRESS" : "FIELD"),
2406 type_name[self->vtype]);
2410 codegen_output_type(self, *out);
2417 /* Hm that should be it... */
2421 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2423 ast_expression_codegen *cgen;
2426 /* in QC this is always an lvalue */
2427 if (lvalue && self->rvalue) {
2428 compile_error(ast_ctx(self), "not an l-value (member access)");
2436 cgen = self->owner->codegen;
2437 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2440 if (vec->vtype != TYPE_VECTOR &&
2441 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2446 *out = ir_value_vector_member(vec, self->field);
2449 return (*out != nullptr);
2452 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2457 if (!lvalue && self->outr) {
2461 if (lvalue && self->outl) {
2466 if (!ast_istype(self->array, ast_value)) {
2467 compile_error(ast_ctx(self), "array indexing this way is not supported");
2468 /* note this would actually be pointer indexing because the left side is
2469 * not an actual array but (hopefully) an indexable expression.
2470 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2471 * support this path will be filled.
2476 arr = (ast_value*)self->array;
2477 idx = (ast_value*)self->index;
2479 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2480 /* Time to use accessor functions */
2481 ast_expression_codegen *cgen;
2482 ir_value *iridx, *funval;
2486 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2491 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2495 cgen = self->index->codegen;
2496 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2499 cgen = arr->getter->codegen;
2500 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2503 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2506 ir_call_param(call, iridx);
2508 *out = ir_call_value(call);
2510 (*out)->vtype = self->vtype;
2511 codegen_output_type(self, *out);
2515 if (idx->vtype == TYPE_FLOAT) {
2516 unsigned int arridx = idx->constval.vfloat;
2517 if (arridx >= self->array->count)
2519 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2522 *out = arr->ir_values[arridx];
2524 else if (idx->vtype == TYPE_INTEGER) {
2525 unsigned int arridx = idx->constval.vint;
2526 if (arridx >= self->array->count)
2528 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2531 *out = arr->ir_values[arridx];
2534 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2537 (*out)->vtype = self->vtype;
2538 codegen_output_type(self, *out);
2542 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2546 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2551 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2555 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2557 ast_expression_codegen *cgen;
2565 ir_block *ontrue_endblock = nullptr;
2566 ir_block *onfalse_endblock = nullptr;
2567 ir_block *merge = nullptr;
2570 /* We don't output any value, thus also don't care about r/lvalue */
2575 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2578 self->outr = (ir_value*)1;
2580 /* generate the condition */
2581 cgen = self->cond->codegen;
2582 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2584 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2585 cond = func->curblock;
2587 /* try constant folding away the condition */
2588 if ((folded = fold::cond_ifthen(condval, func, self)) != -1)
2591 if (self->on_true) {
2592 /* create on-true block */
2593 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2597 /* enter the block */
2598 func->curblock = ontrue;
2601 cgen = self->on_true->codegen;
2602 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2605 /* we now need to work from the current endpoint */
2606 ontrue_endblock = func->curblock;
2611 if (self->on_false) {
2612 /* create on-false block */
2613 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2617 /* enter the block */
2618 func->curblock = onfalse;
2621 cgen = self->on_false->codegen;
2622 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2625 /* we now need to work from the current endpoint */
2626 onfalse_endblock = func->curblock;
2630 /* Merge block were they all merge in to */
2631 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2633 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2636 /* add jumps ot the merge block */
2637 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2639 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2642 /* Now enter the merge block */
2643 func->curblock = merge;
2646 /* we create the if here, that way all blocks are ordered :)
2648 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2649 (ontrue ? ontrue : merge),
2650 (onfalse ? onfalse : merge)))
2658 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2660 ast_expression_codegen *cgen;
2663 ir_value *trueval, *falseval;
2666 ir_block *cond = func->curblock;
2667 ir_block *cond_out = nullptr;
2668 ir_block *ontrue, *ontrue_out = nullptr;
2669 ir_block *onfalse, *onfalse_out = nullptr;
2673 /* Ternary can never create an lvalue... */
2677 /* In theory it shouldn't be possible to pass through a node twice, but
2678 * in case we add any kind of optimization pass for the AST itself, it
2679 * may still happen, thus we remember a created ir_value and simply return one
2680 * if it already exists.
2687 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2689 /* generate the condition */
2690 func->curblock = cond;
2691 cgen = self->cond->codegen;
2692 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2694 cond_out = func->curblock;
2696 /* try constant folding away the condition */
2697 if ((folded = fold::cond_ternary(condval, func, self)) != -1)
2700 /* create on-true block */
2701 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2706 /* enter the block */
2707 func->curblock = ontrue;
2710 cgen = self->on_true->codegen;
2711 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2714 ontrue_out = func->curblock;
2717 /* create on-false block */
2718 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2723 /* enter the block */
2724 func->curblock = onfalse;
2727 cgen = self->on_false->codegen;
2728 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2731 onfalse_out = func->curblock;
2734 /* create merge block */
2735 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2738 /* jump to merge block */
2739 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2741 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2744 /* create if instruction */
2745 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2748 /* Now enter the merge block */
2749 func->curblock = merge;
2751 /* Here, now, we need a PHI node
2752 * but first some sanity checking...
2754 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2755 /* error("ternary with different types on the two sides"); */
2756 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2761 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->vtype);
2763 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2766 ir_phi_add(phi, ontrue_out, trueval);
2767 ir_phi_add(phi, onfalse_out, falseval);
2769 self->outr = ir_phi_value(phi);
2772 codegen_output_type(self, *out);
2777 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2779 ast_expression_codegen *cgen;
2781 ir_value *dummy = nullptr;
2782 ir_value *precond = nullptr;
2783 ir_value *postcond = nullptr;
2785 /* Since we insert some jumps "late" so we have blocks
2786 * ordered "nicely", we need to keep track of the actual end-blocks
2787 * of expressions to add the jumps to.
2789 ir_block *bbody = nullptr, *end_bbody = nullptr;
2790 ir_block *bprecond = nullptr, *end_bprecond = nullptr;
2791 ir_block *bpostcond = nullptr, *end_bpostcond = nullptr;
2792 ir_block *bincrement = nullptr, *end_bincrement = nullptr;
2793 ir_block *bout = nullptr, *bin = nullptr;
2795 /* let's at least move the outgoing block to the end */
2798 /* 'break' and 'continue' need to be able to find the right blocks */
2799 ir_block *bcontinue = nullptr;
2800 ir_block *bbreak = nullptr;
2802 ir_block *tmpblock = nullptr;
2808 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2811 self->outr = (ir_value*)1;
2814 * Should we ever need some kind of block ordering, better make this function
2815 * move blocks around than write a block ordering algorithm later... after all
2816 * the ast and ir should work together, not against each other.
2819 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2820 * anyway if for example it contains a ternary.
2824 cgen = self->initexpr->codegen;
2825 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2829 /* Store the block from which we enter this chaos */
2830 bin = func->curblock;
2832 /* The pre-loop condition needs its own block since we
2833 * need to be able to jump to the start of that expression.
2837 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2841 /* the pre-loop-condition the least important place to 'continue' at */
2842 bcontinue = bprecond;
2845 func->curblock = bprecond;
2848 cgen = self->precond->codegen;
2849 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2852 end_bprecond = func->curblock;
2854 bprecond = end_bprecond = nullptr;
2857 /* Now the next blocks won't be ordered nicely, but we need to
2858 * generate them this early for 'break' and 'continue'.
2860 if (self->increment) {
2861 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2864 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2866 bincrement = end_bincrement = nullptr;
2869 if (self->postcond) {
2870 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2873 bcontinue = bpostcond; /* postcond comes before the increment */
2875 bpostcond = end_bpostcond = nullptr;
2878 bout_id = func->ir_func->blocks.size();
2879 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2884 /* The loop body... */
2885 /* if (self->body) */
2887 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2892 func->curblock = bbody;
2894 func->breakblocks.push_back(bbreak);
2896 func->continueblocks.push_back(bcontinue);
2898 func->continueblocks.push_back(bbody);
2902 cgen = self->body->codegen;
2903 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2907 end_bbody = func->curblock;
2908 func->breakblocks.pop_back();
2909 func->continueblocks.pop_back();
2912 /* post-loop-condition */
2916 func->curblock = bpostcond;
2919 cgen = self->postcond->codegen;
2920 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2923 end_bpostcond = func->curblock;
2926 /* The incrementor */
2927 if (self->increment)
2930 func->curblock = bincrement;
2933 cgen = self->increment->codegen;
2934 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2937 end_bincrement = func->curblock;
2940 /* In any case now, we continue from the outgoing block */
2941 func->curblock = bout;
2943 /* Now all blocks are in place */
2944 /* From 'bin' we jump to whatever comes first */
2945 if (bprecond) tmpblock = bprecond;
2946 else tmpblock = bbody; /* can never be null */
2949 else if (bpostcond) tmpblock = bpostcond;
2950 else tmpblock = bout;
2953 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2959 ir_block *ontrue, *onfalse;
2960 ontrue = bbody; /* can never be null */
2962 /* all of this is dead code
2963 else if (bincrement) ontrue = bincrement;
2964 else ontrue = bpostcond;
2968 if (self->pre_not) {
2973 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2980 if (bincrement) tmpblock = bincrement;
2981 else if (bpostcond) tmpblock = bpostcond;
2982 else if (bprecond) tmpblock = bprecond;
2983 else tmpblock = bbody;
2984 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2988 /* from increment */
2991 if (bpostcond) tmpblock = bpostcond;
2992 else if (bprecond) tmpblock = bprecond;
2993 else if (bbody) tmpblock = bbody;
2994 else tmpblock = bout;
2995 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3002 ir_block *ontrue, *onfalse;
3003 if (bprecond) ontrue = bprecond;
3004 else ontrue = bbody; /* can never be null */
3006 /* all of this is dead code
3007 else if (bincrement) ontrue = bincrement;
3008 else ontrue = bpostcond;
3012 if (self->post_not) {
3017 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3021 /* Move 'bout' to the end */
3022 algo::shiftback(func->ir_func->blocks.begin() + bout_id,
3023 func->ir_func->blocks.end());
3025 //func->ir_func->blocks[bout_id].release(); // it's a vector<unique_ptr<>>
3026 //func->ir_func->blocks.erase(func->ir_func->blocks.begin() + bout_id);
3027 //func->ir_func->blocks.emplace_back(bout);
3032 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3039 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3044 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3047 self->outr = (ir_value*)1;
3049 if (self->is_continue)
3050 target = func->continueblocks[func->continueblocks.size()-1-self->levels];
3052 target = func->breakblocks[func->breakblocks.size()-1-self->levels];
3055 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3059 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3064 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3066 ast_expression_codegen *cgen;
3068 ast_switch_case *def_case = nullptr;
3069 ir_block *def_bfall = nullptr;
3070 ir_block *def_bfall_to = nullptr;
3071 bool set_def_bfall_to = false;
3073 ir_value *dummy = nullptr;
3074 ir_value *irop = nullptr;
3075 ir_block *bout = nullptr;
3076 ir_block *bfall = nullptr;
3083 compile_error(ast_ctx(self), "switch expression is not an l-value");
3088 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3091 self->outr = (ir_value*)1;
3096 cgen = self->operand->codegen;
3097 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3100 if (self->cases.empty())
3103 cmpinstr = type_eq_instr[irop->vtype];
3104 if (cmpinstr >= VINSTR_END) {
3105 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3106 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3110 bout_id = func->ir_func->blocks.size();
3111 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3115 /* setup the break block */
3116 func->breakblocks.push_back(bout);
3118 /* Now create all cases */
3119 for (auto &it : self->cases) {
3120 ir_value *cond, *val;
3121 ir_block *bcase, *bnot;
3124 ast_switch_case *swcase = ⁢
3126 if (swcase->value) {
3127 /* A regular case */
3128 /* generate the condition operand */
3129 cgen = swcase->value->codegen;
3130 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3132 /* generate the condition */
3133 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3137 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3138 bnot_id = func->ir_func->blocks.size();
3139 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3140 if (!bcase || !bnot)
3142 if (set_def_bfall_to) {
3143 set_def_bfall_to = false;
3144 def_bfall_to = bcase;
3146 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3149 /* Make the previous case-end fall through */
3150 if (bfall && !bfall->final) {
3151 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3155 /* enter the case */
3156 func->curblock = bcase;
3157 cgen = swcase->code->codegen;
3158 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3161 /* remember this block to fall through from */
3162 bfall = func->curblock;
3164 /* enter the else and move it down */
3165 func->curblock = bnot;
3166 algo::shiftback(func->ir_func->blocks.begin() + bnot_id,
3167 func->ir_func->blocks.end());
3169 //func->ir_func->blocks[bnot_id].release();
3170 //func->ir_func->blocks.erase(func->ir_func->blocks.begin() + bnot_id);
3171 //func->ir_func->blocks.emplace_back(bnot);
3173 /* The default case */
3174 /* Remember where to fall through from: */
3177 /* remember which case it was */
3179 /* And the next case will be remembered */
3180 set_def_bfall_to = true;
3184 /* Jump from the last bnot to bout */
3185 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3187 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3192 /* If there was a default case, put it down here */
3196 /* No need to create an extra block */
3197 bcase = func->curblock;
3199 /* Insert the fallthrough jump */
3200 if (def_bfall && !def_bfall->final) {
3201 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3205 /* Now generate the default code */
3206 cgen = def_case->code->codegen;
3207 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3210 /* see if we need to fall through */
3211 if (def_bfall_to && !func->curblock->final)
3213 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3218 /* Jump from the last bnot to bout */
3219 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3221 /* enter the outgoing block */
3222 func->curblock = bout;
3224 /* restore the break block */
3225 func->breakblocks.pop_back();
3227 /* Move 'bout' to the end, it's nicer */
3228 algo::shiftback(func->ir_func->blocks.begin() + bout_id,
3229 func->ir_func->blocks.end());
3231 //func->ir_func->blocks[bout_id].release();
3232 //func->ir_func->blocks.erase(func->ir_func->blocks.begin() + bout_id);
3233 //func->ir_func->blocks.emplace_back(bout);
3238 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3242 if (self->undefined) {
3243 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3249 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3253 /* simply create a new block and jump to it */
3254 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3255 if (!self->irblock) {
3256 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3259 if (!func->curblock->final) {
3260 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3264 /* enter the new block */
3265 func->curblock = self->irblock;
3267 /* Generate all the leftover gotos */
3268 for (auto &it : self->gotos) {
3269 if (!ast_goto_codegen(it, func, false, &dummy))
3276 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3280 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3284 if (self->target->irblock) {
3285 if (self->irblock_from) {
3286 /* we already tried once, this is the callback */
3287 self->irblock_from->final = false;
3288 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3289 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3295 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3296 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3303 /* the target has not yet been created...
3304 * close this block in a sneaky way:
3306 func->curblock->final = true;
3307 self->irblock_from = func->curblock;
3308 ast_label_register_goto(self->target, self);
3315 bool ast_state_codegen(ast_state *self, ast_function *func, bool lvalue, ir_value **out)
3317 ast_expression_codegen *cgen;
3319 ir_value *frameval, *thinkval;
3322 compile_error(ast_ctx(self), "not an l-value (state operation)");
3326 compile_error(ast_ctx(self), "internal error: ast_state cannot be reused!");
3331 cgen = self->framenum->codegen;
3332 if (!(*cgen)((ast_expression*)(self->framenum), func, false, &frameval))
3337 cgen = self->nextthink->codegen;
3338 if (!(*cgen)((ast_expression*)(self->nextthink), func, false, &thinkval))
3343 if (!ir_block_create_state_op(func->curblock, ast_ctx(self), frameval, thinkval)) {
3344 compile_error(ast_ctx(self), "failed to create STATE instruction");
3348 self->outr = (ir_value*)1;
3352 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3354 ast_expression_codegen *cgen;
3355 std::vector<ir_value*> params;
3356 ir_instr *callinstr;
3358 ir_value *funval = nullptr;
3360 /* return values are never lvalues */
3362 compile_error(ast_ctx(self), "not an l-value (function call)");
3371 cgen = self->func->codegen;
3372 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3378 for (auto &it : self->params) {
3381 if (!(*cgen)(it, func, false, ¶m))
3385 params.push_back(param);
3388 /* varargs counter */
3389 if (self->va_count) {
3391 ir_builder *builder = func->curblock->owner->owner;
3392 cgen = self->va_count->codegen;
3393 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3395 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3396 ir_builder_get_va_count(builder), va_count))
3402 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3403 ast_function_label(func, "call"),
3404 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3408 for (auto &it : params)
3409 ir_call_param(callinstr, it);
3411 *out = ir_call_value(callinstr);
3414 codegen_output_type(self, *out);