10 #define ast_instantiate(T, ctx, destroyfn) \
11 T* self = (T*)mem_a(sizeof(T)); \
16 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
17 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
20 * forward declarations, these need not be in ast.h for obvious
23 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
24 static void ast_array_index_delete(ast_array_index*);
25 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
26 static void ast_argpipe_delete(ast_argpipe*);
27 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
28 static void ast_store_delete(ast_store*);
29 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
30 static void ast_ifthen_delete(ast_ifthen*);
31 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
32 static void ast_ternary_delete(ast_ternary*);
33 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
34 static void ast_loop_delete(ast_loop*);
35 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
36 static void ast_breakcont_delete(ast_breakcont*);
37 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
38 static void ast_switch_delete(ast_switch*);
39 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
40 static void ast_label_delete(ast_label*);
41 static void ast_label_register_goto(ast_label*, ast_goto*);
42 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
43 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
44 static void ast_goto_delete(ast_goto*);
45 static void ast_call_delete(ast_call*);
46 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
47 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
48 static void ast_unary_delete(ast_unary*);
49 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
50 static void ast_entfield_delete(ast_entfield*);
51 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
52 static void ast_return_delete(ast_return*);
53 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
54 static void ast_binstore_delete(ast_binstore*);
55 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
56 static void ast_binary_delete(ast_binary*);
57 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
58 static bool ast_state_codegen(ast_state*, ast_function*, bool lvalue, ir_value**);
60 /* It must not be possible to get here. */
61 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
64 con_err("ast node missing destroy()\n");
68 /* Initialize main ast node aprts */
69 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
72 self->destroy = &_ast_node_destroy;
74 self->nodetype = nodetype;
75 self->side_effects = false;
78 /* weight and side effects */
79 static void _ast_propagate_effects(ast_node *self, ast_node *other)
81 if (ast_side_effects(other))
82 ast_side_effects(self) = true;
84 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
86 /* General expression initialization */
87 static void ast_expression_init(ast_expression *self,
88 ast_expression_codegen *codegen)
90 self->codegen = codegen;
91 self->vtype = TYPE_VOID;
96 self->varparam = NULL;
98 if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
99 self->flags |= AST_FLAG_BLOCK_COVERAGE;
102 static void ast_expression_delete(ast_expression *self)
105 ast_delete(self->next);
106 for (auto &it : self->params)
109 ast_delete(self->varparam);
112 static void ast_expression_delete_full(ast_expression *self)
114 ast_expression_delete(self);
118 ast_value* ast_value_copy(const ast_value *self)
120 const ast_expression *fromex;
121 ast_expression *selfex;
122 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
123 if (self->expression.next) {
124 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
126 fromex = &self->expression;
127 selfex = &cp->expression;
128 selfex->count = fromex->count;
129 selfex->flags = fromex->flags;
130 for (auto &it : fromex->params) {
131 ast_value *v = ast_value_copy(it);
132 selfex->params.push_back(v);
137 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
139 const ast_expression *fromex;
140 ast_expression *selfex;
141 self->vtype = other->vtype;
143 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
147 selfex->count = fromex->count;
148 selfex->flags = fromex->flags;
149 for (auto &it : fromex->params) {
150 ast_value *v = ast_value_copy(it);
151 selfex->params.push_back(v);
155 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
157 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
158 ast_expression_init(self, NULL);
159 self->codegen = NULL;
165 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
167 const ast_expression *fromex;
168 ast_expression *selfex;
174 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
175 ast_expression_init(self, NULL);
180 /* This may never be codegen()d */
181 selfex->codegen = NULL;
183 selfex->vtype = fromex->vtype;
185 selfex->next = ast_type_copy(ctx, fromex->next);
189 selfex->count = fromex->count;
190 selfex->flags = fromex->flags;
191 for (auto &it : fromex->params) {
192 ast_value *v = ast_value_copy(it);
193 selfex->params.push_back(v);
200 bool ast_compare_type(ast_expression *a, ast_expression *b)
202 if (a->vtype == TYPE_NIL ||
203 b->vtype == TYPE_NIL)
205 if (a->vtype != b->vtype)
207 if (!a->next != !b->next)
209 if (a->params.size() != b->params.size())
211 if ((a->flags & AST_FLAG_TYPE_MASK) !=
212 (b->flags & AST_FLAG_TYPE_MASK) )
216 if (a->params.size()) {
218 for (i = 0; i < a->params.size(); ++i) {
219 if (!ast_compare_type((ast_expression*)a->params[i],
220 (ast_expression*)b->params[i]))
225 return ast_compare_type(a->next, b->next);
229 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
236 if (pos + 6 >= bufsize)
238 util_strncpy(buf + pos, "(null)", 6);
242 if (pos + 1 >= bufsize)
247 util_strncpy(buf + pos, "(variant)", 9);
252 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
255 if (pos + 3 >= bufsize)
259 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
260 if (pos + 1 >= bufsize)
266 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
267 if (pos + 2 >= bufsize)
269 if (e->params.empty()) {
275 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
276 for (i = 1; i < e->params.size(); ++i) {
277 if (pos + 2 >= bufsize)
281 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
283 if (pos + 1 >= bufsize)
289 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
290 if (pos + 1 >= bufsize)
293 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
294 if (pos + 1 >= bufsize)
300 typestr = type_name[e->vtype];
301 typelen = strlen(typestr);
302 if (pos + typelen >= bufsize)
304 util_strncpy(buf + pos, typestr, typelen);
305 return pos + typelen;
309 buf[bufsize-3] = '.';
310 buf[bufsize-2] = '.';
311 buf[bufsize-1] = '.';
315 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
317 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
321 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
322 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
324 ast_instantiate(ast_value, ctx, ast_value_delete);
325 ast_expression_init((ast_expression*)self,
326 (ast_expression_codegen*)&ast_value_codegen);
327 self->expression.node.keep = true; /* keep */
329 self->name = name ? util_strdup(name) : NULL;
330 self->expression.vtype = t;
331 self->expression.next = NULL;
332 self->isfield = false;
334 self->hasvalue = false;
336 self->inexact = false;
338 memset(&self->constval, 0, sizeof(self->constval));
341 self->ir_values = NULL;
342 self->ir_value_count = 0;
348 self->argcounter = NULL;
349 self->intrinsic = false;
354 void ast_value_delete(ast_value* self)
357 mem_d((void*)self->name);
358 if (self->argcounter)
359 mem_d((void*)self->argcounter);
360 if (self->hasvalue) {
361 switch (self->expression.vtype)
364 mem_d((void*)self->constval.vstring);
367 /* unlink us from the function node */
368 self->constval.vfunc->vtype = NULL;
370 /* NOTE: delete function? currently collected in
371 * the parser structure
378 mem_d(self->ir_values);
383 // initlist imples an array which implies .next in the expression exists.
384 if (self->initlist.size() && self->expression.next->vtype == TYPE_STRING) {
385 for (auto &it : self->initlist)
390 ast_expression_delete((ast_expression*)self);
394 void ast_value_params_add(ast_value *self, ast_value *p)
396 self->expression.params.push_back(p);
399 bool ast_value_set_name(ast_value *self, const char *name)
402 mem_d((void*)self->name);
403 self->name = util_strdup(name);
407 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
408 ast_expression* left, ast_expression* right)
410 ast_instantiate(ast_binary, ctx, ast_binary_delete);
411 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
413 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
414 ast_unary *unary = ((ast_unary*)right);
415 ast_expression *normal = unary->operand;
417 /* make a-(-b) => a + b */
418 if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
419 if (op == INSTR_SUB_F) {
422 ++opts_optimizationcount[OPTIM_PEEPHOLE];
423 } else if (op == INSTR_SUB_V) {
426 ++opts_optimizationcount[OPTIM_PEEPHOLE];
434 self->right_first = false;
436 ast_propagate_effects(self, left);
437 ast_propagate_effects(self, right);
439 if (op >= INSTR_EQ_F && op <= INSTR_GT)
440 self->expression.vtype = TYPE_FLOAT;
441 else if (op == INSTR_AND || op == INSTR_OR) {
442 if (OPTS_FLAG(PERL_LOGIC))
443 ast_type_adopt(self, right);
445 self->expression.vtype = TYPE_FLOAT;
447 else if (op == INSTR_BITAND || op == INSTR_BITOR)
448 self->expression.vtype = TYPE_FLOAT;
449 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
450 self->expression.vtype = TYPE_VECTOR;
451 else if (op == INSTR_MUL_V)
452 self->expression.vtype = TYPE_FLOAT;
454 self->expression.vtype = left->vtype;
457 self->refs = AST_REF_ALL;
462 void ast_binary_delete(ast_binary *self)
464 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
465 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
467 ast_expression_delete((ast_expression*)self);
471 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
472 ast_expression* left, ast_expression* right)
474 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
475 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
477 ast_side_effects(self) = true;
479 self->opstore = storop;
482 self->source = right;
484 self->keep_dest = false;
486 ast_type_adopt(self, left);
490 void ast_binstore_delete(ast_binstore *self)
492 if (!self->keep_dest)
493 ast_unref(self->dest);
494 ast_unref(self->source);
495 ast_expression_delete((ast_expression*)self);
499 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
500 ast_expression *expr)
502 ast_instantiate(ast_unary, ctx, ast_unary_delete);
503 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
506 self->operand = expr;
509 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
510 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
512 /* Handle for double negation */
513 if (((ast_unary*)expr)->op == op)
514 prev = (ast_unary*)((ast_unary*)expr)->operand;
516 if (ast_istype(prev, ast_unary)) {
517 ast_expression_delete((ast_expression*)self);
519 ++opts_optimizationcount[OPTIM_PEEPHOLE];
524 ast_propagate_effects(self, expr);
526 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
527 self->expression.vtype = TYPE_FLOAT;
528 } else if (op == VINSTR_NEG_V) {
529 self->expression.vtype = TYPE_VECTOR;
531 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
537 void ast_unary_delete(ast_unary *self)
539 if (self->operand) ast_unref(self->operand);
540 ast_expression_delete((ast_expression*)self);
544 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
546 ast_instantiate(ast_return, ctx, ast_return_delete);
547 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
549 self->operand = expr;
552 ast_propagate_effects(self, expr);
557 void ast_return_delete(ast_return *self)
560 ast_unref(self->operand);
561 ast_expression_delete((ast_expression*)self);
565 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
567 if (field->vtype != TYPE_FIELD) {
568 compile_error(ctx, "ast_entfield_new with expression not of type field");
571 return ast_entfield_new_force(ctx, entity, field, field->next);
574 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
576 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
580 /* Error: field has no type... */
584 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
586 self->entity = entity;
588 ast_propagate_effects(self, entity);
589 ast_propagate_effects(self, field);
591 ast_type_adopt(self, outtype);
595 void ast_entfield_delete(ast_entfield *self)
597 ast_unref(self->entity);
598 ast_unref(self->field);
599 ast_expression_delete((ast_expression*)self);
603 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
605 ast_instantiate(ast_member, ctx, ast_member_delete);
611 if (owner->vtype != TYPE_VECTOR &&
612 owner->vtype != TYPE_FIELD) {
613 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
618 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
619 self->expression.node.keep = true; /* keep */
621 if (owner->vtype == TYPE_VECTOR) {
622 self->expression.vtype = TYPE_FLOAT;
623 self->expression.next = NULL;
625 self->expression.vtype = TYPE_FIELD;
626 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
629 self->rvalue = false;
631 ast_propagate_effects(self, owner);
635 self->name = util_strdup(name);
642 void ast_member_delete(ast_member *self)
644 /* The owner is always an ast_value, which has .keep=true,
645 * also: ast_members are usually deleted after the owner, thus
646 * this will cause invalid access
647 ast_unref(self->owner);
648 * once we allow (expression).x to access a vector-member, we need
649 * to change this: preferably by creating an alternate ast node for this
650 * purpose that is not garbage-collected.
652 ast_expression_delete((ast_expression*)self);
657 bool ast_member_set_name(ast_member *self, const char *name)
660 mem_d((void*)self->name);
661 self->name = util_strdup(name);
665 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
667 ast_expression *outtype;
668 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
670 outtype = array->next;
673 /* Error: field has no type... */
677 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
681 ast_propagate_effects(self, array);
682 ast_propagate_effects(self, index);
684 ast_type_adopt(self, outtype);
685 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
686 if (self->expression.vtype != TYPE_ARRAY) {
687 compile_error(ast_ctx(self), "array_index node on type");
688 ast_array_index_delete(self);
691 self->array = outtype;
692 self->expression.vtype = TYPE_FIELD;
698 void ast_array_index_delete(ast_array_index *self)
701 ast_unref(self->array);
703 ast_unref(self->index);
704 ast_expression_delete((ast_expression*)self);
708 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
710 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
711 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
713 self->expression.vtype = TYPE_NOEXPR;
717 void ast_argpipe_delete(ast_argpipe *self)
720 ast_unref(self->index);
721 ast_expression_delete((ast_expression*)self);
725 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
727 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
728 if (!ontrue && !onfalse) {
729 /* because it is invalid */
733 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
736 self->on_true = ontrue;
737 self->on_false = onfalse;
738 ast_propagate_effects(self, cond);
740 ast_propagate_effects(self, ontrue);
742 ast_propagate_effects(self, onfalse);
747 void ast_ifthen_delete(ast_ifthen *self)
749 ast_unref(self->cond);
751 ast_unref(self->on_true);
753 ast_unref(self->on_false);
754 ast_expression_delete((ast_expression*)self);
758 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
760 ast_expression *exprtype = ontrue;
761 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
762 /* This time NEITHER must be NULL */
763 if (!ontrue || !onfalse) {
767 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
770 self->on_true = ontrue;
771 self->on_false = onfalse;
772 ast_propagate_effects(self, cond);
773 ast_propagate_effects(self, ontrue);
774 ast_propagate_effects(self, onfalse);
776 if (ontrue->vtype == TYPE_NIL)
778 ast_type_adopt(self, exprtype);
783 void ast_ternary_delete(ast_ternary *self)
785 /* the if()s are only there because computed-gotos can set them
788 if (self->cond) ast_unref(self->cond);
789 if (self->on_true) ast_unref(self->on_true);
790 if (self->on_false) ast_unref(self->on_false);
791 ast_expression_delete((ast_expression*)self);
795 ast_loop* ast_loop_new(lex_ctx_t ctx,
796 ast_expression *initexpr,
797 ast_expression *precond, bool pre_not,
798 ast_expression *postcond, bool post_not,
799 ast_expression *increment,
800 ast_expression *body)
802 ast_instantiate(ast_loop, ctx, ast_loop_delete);
803 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
805 self->initexpr = initexpr;
806 self->precond = precond;
807 self->postcond = postcond;
808 self->increment = increment;
811 self->pre_not = pre_not;
812 self->post_not = post_not;
815 ast_propagate_effects(self, initexpr);
817 ast_propagate_effects(self, precond);
819 ast_propagate_effects(self, postcond);
821 ast_propagate_effects(self, increment);
823 ast_propagate_effects(self, body);
828 void ast_loop_delete(ast_loop *self)
831 ast_unref(self->initexpr);
833 ast_unref(self->precond);
835 ast_unref(self->postcond);
837 ast_unref(self->increment);
839 ast_unref(self->body);
840 ast_expression_delete((ast_expression*)self);
844 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
846 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
847 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
849 self->is_continue = iscont;
850 self->levels = levels;
855 void ast_breakcont_delete(ast_breakcont *self)
857 ast_expression_delete((ast_expression*)self);
861 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
863 ast_instantiate(ast_switch, ctx, ast_switch_delete);
864 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
868 ast_propagate_effects(self, op);
873 void ast_switch_delete(ast_switch *self)
875 ast_unref(self->operand);
877 for (auto &it : self->cases) {
883 ast_expression_delete((ast_expression*)self);
887 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
889 ast_instantiate(ast_label, ctx, ast_label_delete);
890 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
892 self->expression.vtype = TYPE_NOEXPR;
894 self->name = util_strdup(name);
895 self->irblock = NULL;
896 self->undefined = undefined;
901 void ast_label_delete(ast_label *self)
903 mem_d((void*)self->name);
904 ast_expression_delete((ast_expression*)self);
908 static void ast_label_register_goto(ast_label *self, ast_goto *g)
910 self->gotos.push_back(g);
913 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
915 ast_instantiate(ast_goto, ctx, ast_goto_delete);
916 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
918 self->name = util_strdup(name);
920 self->irblock_from = NULL;
925 void ast_goto_delete(ast_goto *self)
927 mem_d((void*)self->name);
928 ast_expression_delete((ast_expression*)self);
932 void ast_goto_set_label(ast_goto *self, ast_label *label)
934 self->target = label;
937 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
939 ast_instantiate(ast_state, ctx, ast_state_delete);
940 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_state_codegen);
941 self->framenum = frame;
942 self->nextthink = think;
946 void ast_state_delete(ast_state *self)
949 ast_unref(self->framenum);
951 ast_unref(self->nextthink);
953 ast_expression_delete((ast_expression*)self);
957 ast_call* ast_call_new(lex_ctx_t ctx,
958 ast_expression *funcexpr)
960 ast_instantiate(ast_call, ctx, ast_call_delete);
961 if (!funcexpr->next) {
962 compile_error(ctx, "not a function");
966 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
968 ast_side_effects(self) = true;
970 self->func = funcexpr;
971 self->va_count = NULL;
973 ast_type_adopt(self, funcexpr->next);
978 void ast_call_delete(ast_call *self)
980 for (auto &it : self->params)
984 ast_unref(self->func);
987 ast_unref(self->va_count);
989 ast_expression_delete((ast_expression*)self);
993 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
999 if (!va_type || !ast_compare_type(va_type, exp_type))
1001 if (va_type && exp_type)
1003 ast_type_to_string(va_type, tgot, sizeof(tgot));
1004 ast_type_to_string(exp_type, texp, sizeof(texp));
1005 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1006 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1007 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1011 compile_error(ast_ctx(self),
1012 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1019 ast_type_to_string(exp_type, texp, sizeof(texp));
1020 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1021 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1022 "piped variadic argument may differ in type: expected type %s",
1026 compile_error(ast_ctx(self),
1027 "piped variadic argument may differ in type: expected type %s",
1036 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1042 const ast_expression *func = self->func;
1043 size_t count = self->params.size();
1044 if (count > func->params.size())
1045 count = func->params.size();
1047 for (i = 0; i < count; ++i) {
1048 if (ast_istype(self->params[i], ast_argpipe)) {
1049 /* warn about type safety instead */
1051 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1054 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1057 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1059 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1060 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1061 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1062 (unsigned int)(i+1), texp, tgot);
1063 /* we don't immediately return */
1067 count = self->params.size();
1068 if (count > func->params.size() && func->varparam) {
1069 for (; i < count; ++i) {
1070 if (ast_istype(self->params[i], ast_argpipe)) {
1071 /* warn about type safety instead */
1073 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1076 if (!ast_call_check_vararg(self, va_type, func->varparam))
1079 else if (!ast_compare_type(self->params[i], func->varparam))
1081 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1082 ast_type_to_string(func->varparam, texp, sizeof(texp));
1083 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1084 (unsigned int)(i+1), texp, tgot);
1085 /* we don't immediately return */
1093 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1094 ast_expression *dest, ast_expression *source)
1096 ast_instantiate(ast_store, ctx, ast_store_delete);
1097 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1099 ast_side_effects(self) = true;
1103 self->source = source;
1105 ast_type_adopt(self, dest);
1110 void ast_store_delete(ast_store *self)
1112 ast_unref(self->dest);
1113 ast_unref(self->source);
1114 ast_expression_delete((ast_expression*)self);
1118 ast_block* ast_block_new(lex_ctx_t ctx)
1120 ast_instantiate(ast_block, ctx, ast_block_delete);
1121 ast_expression_init((ast_expression*)self,
1122 (ast_expression_codegen*)&ast_block_codegen);
1126 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1128 ast_propagate_effects(self, e);
1129 self->exprs.push_back(e);
1130 if (self->expression.next) {
1131 ast_delete(self->expression.next);
1132 self->expression.next = NULL;
1134 ast_type_adopt(self, e);
1138 void ast_block_collect(ast_block *self, ast_expression *expr)
1140 self->collect.push_back(expr);
1141 expr->node.keep = true;
1144 void ast_block_delete(ast_block *self)
1146 for (auto &it : self->exprs) ast_unref(it);
1147 for (auto &it : self->locals) ast_delete(it);
1148 for (auto &it : self->collect) ast_delete(it);
1149 ast_expression_delete((ast_expression*)self);
1153 void ast_block_set_type(ast_block *self, ast_expression *from)
1155 if (self->expression.next)
1156 ast_delete(self->expression.next);
1157 ast_type_adopt(self, from);
1160 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1162 ast_instantiate(ast_function, ctx, ast_function_delete);
1165 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1167 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1168 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1170 (int)vtype->hasvalue,
1171 vtype->expression.vtype);
1175 self->vtype = vtype;
1176 self->name = name ? util_strdup(name) : NULL;
1178 self->labelcount = 0;
1181 self->ir_func = NULL;
1182 self->curblock = NULL;
1184 vtype->hasvalue = true;
1185 vtype->constval.vfunc = self;
1187 self->varargs = NULL;
1189 self->fixedparams = NULL;
1190 self->return_value = NULL;
1192 self->static_names = NULL;
1193 self->static_count = 0;
1202 void ast_function_delete(ast_function *self)
1206 mem_d((void*)self->name);
1208 /* ast_value_delete(self->vtype); */
1209 self->vtype->hasvalue = false;
1210 self->vtype->constval.vfunc = NULL;
1211 /* We use unref - if it was stored in a global table it is supposed
1212 * to be deleted from *there*
1214 ast_unref(self->vtype);
1216 for (i = 0; i < vec_size(self->static_names); ++i)
1217 mem_d(self->static_names[i]);
1218 vec_free(self->static_names);
1219 for (auto &it : self->blocks)
1222 ast_delete(self->varargs);
1224 ast_delete(self->argc);
1225 if (self->fixedparams)
1226 ast_unref(self->fixedparams);
1227 if (self->return_value)
1228 ast_unref(self->return_value);
1232 const char* ast_function_label(ast_function *self, const char *prefix)
1238 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1239 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1240 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1245 id = (self->labelcount++);
1246 len = strlen(prefix);
1248 from = self->labelbuf + sizeof(self->labelbuf)-1;
1251 *from-- = (id%10) + '0';
1255 memcpy(from - len, prefix, len);
1259 /*********************************************************************/
1261 * by convention you must never pass NULL to the 'ir_value **out'
1262 * parameter. If you really don't care about the output, pass a dummy.
1263 * But I can't imagine a pituation where the output is truly unnecessary.
1266 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1268 if (out->vtype == TYPE_FIELD)
1269 out->fieldtype = self->next->vtype;
1270 if (out->vtype == TYPE_FUNCTION)
1271 out->outtype = self->next->vtype;
1274 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1276 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1280 if (self->expression.vtype == TYPE_NIL) {
1281 *out = func->ir_func->owner->nil;
1284 /* NOTE: This is the codegen for a variable used in an expression.
1285 * It is not the codegen to generate the value. For this purpose,
1286 * ast_local_codegen and ast_global_codegen are to be used before this
1287 * is executed. ast_function_codegen should take care of its locals,
1288 * and the ast-user should take care of ast_global_codegen to be used
1289 * on all the globals.
1292 char tname[1024]; /* typename is reserved in C++ */
1293 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1294 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1301 static bool ast_global_array_set(ast_value *self)
1303 size_t count = self->initlist.size();
1306 if (count > self->expression.count) {
1307 compile_error(ast_ctx(self), "too many elements in initializer");
1308 count = self->expression.count;
1310 else if (count < self->expression.count) {
1312 compile_warning(ast_ctx(self), "not all elements are initialized");
1316 for (i = 0; i != count; ++i) {
1317 switch (self->expression.next->vtype) {
1319 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1323 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1327 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1331 /* we don't support them in any other place yet either */
1332 compile_error(ast_ctx(self), "TODO: nested arrays");
1335 /* this requiers a bit more work - similar to the fields I suppose */
1336 compile_error(ast_ctx(self), "global of type function not properly generated");
1339 if (!self->initlist[i].vfield) {
1340 compile_error(ast_ctx(self), "field constant without vfield set");
1343 if (!self->initlist[i].vfield->ir_v) {
1344 compile_error(ast_ctx(self), "field constant generated before its field");
1347 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1351 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1358 static bool check_array(ast_value *self, ast_value *array)
1360 if (array->expression.flags & AST_FLAG_ARRAY_INIT && array->initlist.empty()) {
1361 compile_error(ast_ctx(self), "array without size: %s", self->name);
1364 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1365 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1366 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1372 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1376 if (self->expression.vtype == TYPE_NIL) {
1377 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1381 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1383 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1386 func->context = ast_ctx(self);
1387 func->value->context = ast_ctx(self);
1389 self->constval.vfunc->ir_func = func;
1390 self->ir_v = func->value;
1391 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1392 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1393 if (self->expression.flags & AST_FLAG_ERASEABLE)
1394 self->ir_v->flags |= IR_FLAG_ERASABLE;
1395 if (self->expression.flags & AST_FLAG_BLOCK_COVERAGE)
1396 func->flags |= IR_FLAG_BLOCK_COVERAGE;
1397 /* The function is filled later on ast_function_codegen... */
1401 if (isfield && self->expression.vtype == TYPE_FIELD) {
1402 ast_expression *fieldtype = self->expression.next;
1404 if (self->hasvalue) {
1405 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1409 if (fieldtype->vtype == TYPE_ARRAY) {
1414 ast_expression *elemtype;
1416 ast_value *array = (ast_value*)fieldtype;
1418 if (!ast_istype(fieldtype, ast_value)) {
1419 compile_error(ast_ctx(self), "internal error: ast_value required");
1423 if (!check_array(self, array))
1426 elemtype = array->expression.next;
1427 vtype = elemtype->vtype;
1429 v = ir_builder_create_field(ir, self->name, vtype);
1431 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1434 v->context = ast_ctx(self);
1435 v->unique_life = true;
1437 array->ir_v = self->ir_v = v;
1439 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1440 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1441 if (self->expression.flags & AST_FLAG_ERASEABLE)
1442 self->ir_v->flags |= IR_FLAG_ERASABLE;
1444 namelen = strlen(self->name);
1445 name = (char*)mem_a(namelen + 16);
1446 util_strncpy(name, self->name, namelen);
1448 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1449 array->ir_values[0] = v;
1450 for (ai = 1; ai < array->expression.count; ++ai) {
1451 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1452 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1453 if (!array->ir_values[ai]) {
1455 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1458 array->ir_values[ai]->context = ast_ctx(self);
1459 array->ir_values[ai]->unique_life = true;
1460 array->ir_values[ai]->locked = true;
1461 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1462 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1468 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1471 v->context = ast_ctx(self);
1473 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1474 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1476 if (self->expression.flags & AST_FLAG_ERASEABLE)
1477 self->ir_v->flags |= IR_FLAG_ERASABLE;
1482 if (self->expression.vtype == TYPE_ARRAY) {
1487 ast_expression *elemtype = self->expression.next;
1488 int vtype = elemtype->vtype;
1490 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1491 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1495 /* same as with field arrays */
1496 if (!check_array(self, self))
1499 v = ir_builder_create_global(ir, self->name, vtype);
1501 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1504 v->context = ast_ctx(self);
1505 v->unique_life = true;
1508 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1509 v->flags |= IR_FLAG_INCLUDE_DEF;
1510 if (self->expression.flags & AST_FLAG_ERASEABLE)
1511 self->ir_v->flags |= IR_FLAG_ERASABLE;
1513 namelen = strlen(self->name);
1514 name = (char*)mem_a(namelen + 16);
1515 util_strncpy(name, self->name, namelen);
1517 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1518 self->ir_values[0] = v;
1519 for (ai = 1; ai < self->expression.count; ++ai) {
1520 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1521 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1522 if (!self->ir_values[ai]) {
1524 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1527 self->ir_values[ai]->context = ast_ctx(self);
1528 self->ir_values[ai]->unique_life = true;
1529 self->ir_values[ai]->locked = true;
1530 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1531 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1537 /* Arrays don't do this since there's no "array" value which spans across the
1540 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1542 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1545 codegen_output_type(self, v);
1546 v->context = ast_ctx(self);
1549 /* link us to the ir_value */
1553 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1554 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1555 if (self->expression.flags & AST_FLAG_ERASEABLE)
1556 self->ir_v->flags |= IR_FLAG_ERASABLE;
1559 if (self->hasvalue) {
1560 switch (self->expression.vtype)
1563 if (!ir_value_set_float(v, self->constval.vfloat))
1567 if (!ir_value_set_vector(v, self->constval.vvec))
1571 if (!ir_value_set_string(v, self->constval.vstring))
1575 ast_global_array_set(self);
1578 compile_error(ast_ctx(self), "global of type function not properly generated");
1580 /* Cannot generate an IR value for a function,
1581 * need a pointer pointing to a function rather.
1584 if (!self->constval.vfield) {
1585 compile_error(ast_ctx(self), "field constant without vfield set");
1588 if (!self->constval.vfield->ir_v) {
1589 compile_error(ast_ctx(self), "field constant generated before its field");
1592 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1596 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1602 error: /* clean up */
1603 if(v) ir_value_delete(v);
1607 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1611 if (self->expression.vtype == TYPE_NIL) {
1612 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1616 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1618 /* Do we allow local functions? I think not...
1619 * this is NOT a function pointer atm.
1624 if (self->expression.vtype == TYPE_ARRAY) {
1629 ast_expression *elemtype = self->expression.next;
1630 int vtype = elemtype->vtype;
1632 func->flags |= IR_FLAG_HAS_ARRAYS;
1634 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1635 compile_error(ast_ctx(self), "array-parameters are not supported");
1639 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1640 if (!check_array(self, self))
1643 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1644 if (!self->ir_values) {
1645 compile_error(ast_ctx(self), "failed to allocate array values");
1649 v = ir_function_create_local(func, self->name, vtype, param);
1651 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1654 v->context = ast_ctx(self);
1655 v->unique_life = true;
1658 namelen = strlen(self->name);
1659 name = (char*)mem_a(namelen + 16);
1660 util_strncpy(name, self->name, namelen);
1662 self->ir_values[0] = v;
1663 for (ai = 1; ai < self->expression.count; ++ai) {
1664 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1665 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1666 if (!self->ir_values[ai]) {
1667 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1670 self->ir_values[ai]->context = ast_ctx(self);
1671 self->ir_values[ai]->unique_life = true;
1672 self->ir_values[ai]->locked = true;
1678 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1681 codegen_output_type(self, v);
1682 v->context = ast_ctx(self);
1685 /* A constant local... hmmm...
1686 * I suppose the IR will have to deal with this
1688 if (self->hasvalue) {
1689 switch (self->expression.vtype)
1692 if (!ir_value_set_float(v, self->constval.vfloat))
1696 if (!ir_value_set_vector(v, self->constval.vvec))
1700 if (!ir_value_set_string(v, self->constval.vstring))
1704 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1709 /* link us to the ir_value */
1713 if (!ast_generate_accessors(self, func->owner))
1717 error: /* clean up */
1722 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1725 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1726 if (!self->setter || !self->getter)
1728 for (i = 0; i < self->expression.count; ++i) {
1729 if (!self->ir_values) {
1730 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1733 if (!self->ir_values[i]) {
1734 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1737 if (self->ir_values[i]->life) {
1738 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1743 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1745 if (!ast_global_codegen (self->setter, ir, false) ||
1746 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1747 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1749 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1750 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1755 if (!ast_global_codegen (self->getter, ir, false) ||
1756 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1757 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1759 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1760 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1764 for (i = 0; i < self->expression.count; ++i) {
1765 vec_free(self->ir_values[i]->life);
1767 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1771 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1776 ast_expression_codegen *cgen;
1780 irf = self->ir_func;
1782 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1786 /* fill the parameter list */
1787 ec = &self->vtype->expression;
1788 for (auto &it : ec->params) {
1789 if (it->expression.vtype == TYPE_FIELD)
1790 vec_push(irf->params, it->expression.next->vtype);
1792 vec_push(irf->params, it->expression.vtype);
1793 if (!self->builtin) {
1794 if (!ast_local_codegen(it, self->ir_func, true))
1799 if (self->varargs) {
1800 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1802 irf->max_varargs = self->varargs->expression.count;
1805 if (self->builtin) {
1806 irf->builtin = self->builtin;
1810 /* have a local return value variable? */
1811 if (self->return_value) {
1812 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1816 if (self->blocks.empty()) {
1817 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1821 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1822 if (!self->curblock) {
1823 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1831 if (!ast_local_codegen(self->argc, self->ir_func, true))
1833 cgen = self->argc->expression.codegen;
1834 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1836 cgen = self->fixedparams->expression.codegen;
1837 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1839 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1840 ast_function_label(self, "va_count"), INSTR_SUB_F,
1841 ir_builder_get_va_count(ir), fixed);
1844 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1851 for (auto &it : self->blocks) {
1852 cgen = it->expression.codegen;
1853 if (!(*cgen)((ast_expression*)it, self, false, &dummy))
1857 /* TODO: check return types */
1858 if (!self->curblock->final)
1860 if (!self->vtype->expression.next ||
1861 self->vtype->expression.next->vtype == TYPE_VOID)
1863 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1865 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1867 if (self->return_value) {
1868 cgen = self->return_value->expression.codegen;
1869 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1871 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1873 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1874 "control reaches end of non-void function (`%s`) via %s",
1875 self->name, self->curblock->label))
1879 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1885 static bool starts_a_label(ast_expression *ex)
1887 while (ex && ast_istype(ex, ast_block)) {
1888 ast_block *b = (ast_block*)ex;
1893 return ast_istype(ex, ast_label);
1896 /* Note, you will not see ast_block_codegen generate ir_blocks.
1897 * To the AST and the IR, blocks are 2 different things.
1898 * In the AST it represents a block of code, usually enclosed in
1899 * curly braces {...}.
1900 * While in the IR it represents a block in terms of control-flow.
1902 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1904 /* We don't use this
1905 * Note: an ast-representation using the comma-operator
1906 * of the form: (a, b, c) = x should not assign to c...
1909 compile_error(ast_ctx(self), "not an l-value (code-block)");
1913 if (self->expression.outr) {
1914 *out = self->expression.outr;
1918 /* output is NULL at first, we'll have each expression
1919 * assign to out output, thus, a comma-operator represention
1920 * using an ast_block will return the last generated value,
1921 * so: (b, c) + a executed both b and c, and returns c,
1922 * which is then added to a.
1926 /* generate locals */
1927 for (auto &it : self->locals) {
1928 if (!ast_local_codegen(it, func->ir_func, false)) {
1929 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1930 compile_error(ast_ctx(self), "failed to generate local `%s`", it->name);
1935 for (auto &it : self->exprs) {
1936 ast_expression_codegen *gen;
1937 if (func->curblock->final && !starts_a_label(it)) {
1938 if (compile_warning(ast_ctx(it), WARN_UNREACHABLE_CODE, "unreachable statement"))
1943 if (!(*gen)(it, func, false, out))
1947 self->expression.outr = *out;
1952 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1954 ast_expression_codegen *cgen;
1955 ir_value *left = NULL;
1956 ir_value *right = NULL;
1960 ast_array_index *ai = NULL;
1962 if (lvalue && self->expression.outl) {
1963 *out = self->expression.outl;
1967 if (!lvalue && self->expression.outr) {
1968 *out = self->expression.outr;
1972 if (ast_istype(self->dest, ast_array_index))
1975 ai = (ast_array_index*)self->dest;
1976 idx = (ast_value*)ai->index;
1978 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1983 /* we need to call the setter */
1984 ir_value *iridx, *funval;
1988 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1992 arr = (ast_value*)ai->array;
1993 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1994 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1998 cgen = idx->expression.codegen;
1999 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2002 cgen = arr->setter->expression.codegen;
2003 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2006 cgen = self->source->codegen;
2007 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2010 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2013 ir_call_param(call, iridx);
2014 ir_call_param(call, right);
2015 self->expression.outr = right;
2021 cgen = self->dest->codegen;
2023 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2025 self->expression.outl = left;
2027 cgen = self->source->codegen;
2029 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2032 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2034 self->expression.outr = right;
2037 /* Theoretically, an assinment returns its left side as an
2038 * lvalue, if we don't need an lvalue though, we return
2039 * the right side as an rvalue, otherwise we have to
2040 * somehow know whether or not we need to dereference the pointer
2041 * on the left side - that is: OP_LOAD if it was an address.
2042 * Also: in original QC we cannot OP_LOADP *anyway*.
2044 *out = (lvalue ? left : right);
2049 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2051 ast_expression_codegen *cgen;
2052 ir_value *left, *right;
2054 /* A binary operation cannot yield an l-value */
2056 compile_error(ast_ctx(self), "not an l-value (binop)");
2060 if (self->expression.outr) {
2061 *out = self->expression.outr;
2065 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2066 (self->op == INSTR_AND || self->op == INSTR_OR))
2068 /* NOTE: The short-logic path will ignore right_first */
2070 /* short circuit evaluation */
2071 ir_block *other, *merge;
2072 ir_block *from_left, *from_right;
2076 /* prepare end-block */
2077 merge_id = vec_size(func->ir_func->blocks);
2078 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2080 /* generate the left expression */
2081 cgen = self->left->codegen;
2082 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2084 /* remember the block */
2085 from_left = func->curblock;
2087 /* create a new block for the right expression */
2088 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2089 if (self->op == INSTR_AND) {
2090 /* on AND: left==true -> other */
2091 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2094 /* on OR: left==false -> other */
2095 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2098 /* use the likely flag */
2099 vec_last(func->curblock->instr)->likely = true;
2101 /* enter the right-expression's block */
2102 func->curblock = other;
2104 cgen = self->right->codegen;
2105 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2107 /* remember block */
2108 from_right = func->curblock;
2110 /* jump to the merge block */
2111 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2114 vec_remove(func->ir_func->blocks, merge_id, 1);
2115 vec_push(func->ir_func->blocks, merge);
2117 func->curblock = merge;
2118 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2119 ast_function_label(func, "sce_value"),
2120 self->expression.vtype);
2121 ir_phi_add(phi, from_left, left);
2122 ir_phi_add(phi, from_right, right);
2123 *out = ir_phi_value(phi);
2127 if (!OPTS_FLAG(PERL_LOGIC)) {
2129 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2130 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2131 ast_function_label(func, "sce_bool_v"),
2135 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2136 ast_function_label(func, "sce_bool"),
2141 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2142 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2143 ast_function_label(func, "sce_bool_s"),
2147 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2148 ast_function_label(func, "sce_bool"),
2154 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2155 ast_function_label(func, "sce_bool"),
2156 INSTR_AND, *out, *out);
2162 self->expression.outr = *out;
2163 codegen_output_type(self, *out);
2167 if (self->right_first) {
2168 cgen = self->right->codegen;
2169 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2171 cgen = self->left->codegen;
2172 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2175 cgen = self->left->codegen;
2176 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2178 cgen = self->right->codegen;
2179 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2183 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2184 self->op, left, right);
2187 self->expression.outr = *out;
2188 codegen_output_type(self, *out);
2193 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2195 ast_expression_codegen *cgen;
2196 ir_value *leftl = NULL, *leftr, *right, *bin;
2200 ast_array_index *ai = NULL;
2201 ir_value *iridx = NULL;
2203 if (lvalue && self->expression.outl) {
2204 *out = self->expression.outl;
2208 if (!lvalue && self->expression.outr) {
2209 *out = self->expression.outr;
2213 if (ast_istype(self->dest, ast_array_index))
2216 ai = (ast_array_index*)self->dest;
2217 idx = (ast_value*)ai->index;
2219 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2223 /* for a binstore we need both an lvalue and an rvalue for the left side */
2224 /* rvalue of destination! */
2226 cgen = idx->expression.codegen;
2227 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2230 cgen = self->dest->codegen;
2231 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2234 /* source as rvalue only */
2235 cgen = self->source->codegen;
2236 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2239 /* now the binary */
2240 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2241 self->opbin, leftr, right);
2242 self->expression.outr = bin;
2246 /* we need to call the setter */
2251 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2255 arr = (ast_value*)ai->array;
2256 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2257 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2261 cgen = arr->setter->expression.codegen;
2262 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2265 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2268 ir_call_param(call, iridx);
2269 ir_call_param(call, bin);
2270 self->expression.outr = bin;
2272 /* now store them */
2273 cgen = self->dest->codegen;
2274 /* lvalue of destination */
2275 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2277 self->expression.outl = leftl;
2279 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2281 self->expression.outr = bin;
2284 /* Theoretically, an assinment returns its left side as an
2285 * lvalue, if we don't need an lvalue though, we return
2286 * the right side as an rvalue, otherwise we have to
2287 * somehow know whether or not we need to dereference the pointer
2288 * on the left side - that is: OP_LOAD if it was an address.
2289 * Also: in original QC we cannot OP_LOADP *anyway*.
2291 *out = (lvalue ? leftl : bin);
2296 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2298 ast_expression_codegen *cgen;
2301 /* An unary operation cannot yield an l-value */
2303 compile_error(ast_ctx(self), "not an l-value (binop)");
2307 if (self->expression.outr) {
2308 *out = self->expression.outr;
2312 cgen = self->operand->codegen;
2314 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2317 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2321 self->expression.outr = *out;
2326 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2328 ast_expression_codegen *cgen;
2333 /* In the context of a return operation, we don't actually return
2337 compile_error(ast_ctx(self), "return-expression is not an l-value");
2341 if (self->expression.outr) {
2342 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2345 self->expression.outr = (ir_value*)1;
2347 if (self->operand) {
2348 cgen = self->operand->codegen;
2350 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2353 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2356 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2363 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2365 ast_expression_codegen *cgen;
2366 ir_value *ent, *field;
2368 /* This function needs to take the 'lvalue' flag into account!
2369 * As lvalue we provide a field-pointer, as rvalue we provide the
2373 if (lvalue && self->expression.outl) {
2374 *out = self->expression.outl;
2378 if (!lvalue && self->expression.outr) {
2379 *out = self->expression.outr;
2383 cgen = self->entity->codegen;
2384 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2387 cgen = self->field->codegen;
2388 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2393 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2396 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2397 ent, field, self->expression.vtype);
2398 /* Done AFTER error checking:
2399 codegen_output_type(self, *out);
2403 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2404 (lvalue ? "ADDRESS" : "FIELD"),
2405 type_name[self->expression.vtype]);
2409 codegen_output_type(self, *out);
2412 self->expression.outl = *out;
2414 self->expression.outr = *out;
2416 /* Hm that should be it... */
2420 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2422 ast_expression_codegen *cgen;
2425 /* in QC this is always an lvalue */
2426 if (lvalue && self->rvalue) {
2427 compile_error(ast_ctx(self), "not an l-value (member access)");
2430 if (self->expression.outl) {
2431 *out = self->expression.outl;
2435 cgen = self->owner->codegen;
2436 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2439 if (vec->vtype != TYPE_VECTOR &&
2440 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2445 *out = ir_value_vector_member(vec, self->field);
2446 self->expression.outl = *out;
2448 return (*out != NULL);
2451 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2456 if (!lvalue && self->expression.outr) {
2457 *out = self->expression.outr;
2460 if (lvalue && self->expression.outl) {
2461 *out = self->expression.outl;
2465 if (!ast_istype(self->array, ast_value)) {
2466 compile_error(ast_ctx(self), "array indexing this way is not supported");
2467 /* note this would actually be pointer indexing because the left side is
2468 * not an actual array but (hopefully) an indexable expression.
2469 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2470 * support this path will be filled.
2475 arr = (ast_value*)self->array;
2476 idx = (ast_value*)self->index;
2478 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2479 /* Time to use accessor functions */
2480 ast_expression_codegen *cgen;
2481 ir_value *iridx, *funval;
2485 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2490 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2494 cgen = self->index->codegen;
2495 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2498 cgen = arr->getter->expression.codegen;
2499 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2502 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2505 ir_call_param(call, iridx);
2507 *out = ir_call_value(call);
2508 self->expression.outr = *out;
2509 (*out)->vtype = self->expression.vtype;
2510 codegen_output_type(self, *out);
2514 if (idx->expression.vtype == TYPE_FLOAT) {
2515 unsigned int arridx = idx->constval.vfloat;
2516 if (arridx >= self->array->count)
2518 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2521 *out = arr->ir_values[arridx];
2523 else if (idx->expression.vtype == TYPE_INTEGER) {
2524 unsigned int arridx = idx->constval.vint;
2525 if (arridx >= self->array->count)
2527 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2530 *out = arr->ir_values[arridx];
2533 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2536 (*out)->vtype = self->expression.vtype;
2537 codegen_output_type(self, *out);
2541 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2545 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2550 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2554 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2556 ast_expression_codegen *cgen;
2564 ir_block *ontrue_endblock = NULL;
2565 ir_block *onfalse_endblock = NULL;
2566 ir_block *merge = NULL;
2569 /* We don't output any value, thus also don't care about r/lvalue */
2573 if (self->expression.outr) {
2574 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2577 self->expression.outr = (ir_value*)1;
2579 /* generate the condition */
2580 cgen = self->cond->codegen;
2581 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2583 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2584 cond = func->curblock;
2586 /* try constant folding away the condition */
2587 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2590 if (self->on_true) {
2591 /* create on-true block */
2592 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2596 /* enter the block */
2597 func->curblock = ontrue;
2600 cgen = self->on_true->codegen;
2601 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2604 /* we now need to work from the current endpoint */
2605 ontrue_endblock = func->curblock;
2610 if (self->on_false) {
2611 /* create on-false block */
2612 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2616 /* enter the block */
2617 func->curblock = onfalse;
2620 cgen = self->on_false->codegen;
2621 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2624 /* we now need to work from the current endpoint */
2625 onfalse_endblock = func->curblock;
2629 /* Merge block were they all merge in to */
2630 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2632 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2635 /* add jumps ot the merge block */
2636 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2638 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2641 /* Now enter the merge block */
2642 func->curblock = merge;
2645 /* we create the if here, that way all blocks are ordered :)
2647 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2648 (ontrue ? ontrue : merge),
2649 (onfalse ? onfalse : merge)))
2657 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2659 ast_expression_codegen *cgen;
2662 ir_value *trueval, *falseval;
2665 ir_block *cond = func->curblock;
2666 ir_block *cond_out = NULL;
2667 ir_block *ontrue, *ontrue_out = NULL;
2668 ir_block *onfalse, *onfalse_out = NULL;
2672 /* Ternary can never create an lvalue... */
2676 /* In theory it shouldn't be possible to pass through a node twice, but
2677 * in case we add any kind of optimization pass for the AST itself, it
2678 * may still happen, thus we remember a created ir_value and simply return one
2679 * if it already exists.
2681 if (self->expression.outr) {
2682 *out = self->expression.outr;
2686 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2688 /* generate the condition */
2689 func->curblock = cond;
2690 cgen = self->cond->codegen;
2691 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2693 cond_out = func->curblock;
2695 /* try constant folding away the condition */
2696 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2699 /* create on-true block */
2700 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2705 /* enter the block */
2706 func->curblock = ontrue;
2709 cgen = self->on_true->codegen;
2710 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2713 ontrue_out = func->curblock;
2716 /* create on-false block */
2717 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2722 /* enter the block */
2723 func->curblock = onfalse;
2726 cgen = self->on_false->codegen;
2727 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2730 onfalse_out = func->curblock;
2733 /* create merge block */
2734 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2737 /* jump to merge block */
2738 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2740 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2743 /* create if instruction */
2744 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2747 /* Now enter the merge block */
2748 func->curblock = merge;
2750 /* Here, now, we need a PHI node
2751 * but first some sanity checking...
2753 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2754 /* error("ternary with different types on the two sides"); */
2755 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2760 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2762 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2765 ir_phi_add(phi, ontrue_out, trueval);
2766 ir_phi_add(phi, onfalse_out, falseval);
2768 self->expression.outr = ir_phi_value(phi);
2769 *out = self->expression.outr;
2771 codegen_output_type(self, *out);
2776 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2778 ast_expression_codegen *cgen;
2780 ir_value *dummy = NULL;
2781 ir_value *precond = NULL;
2782 ir_value *postcond = NULL;
2784 /* Since we insert some jumps "late" so we have blocks
2785 * ordered "nicely", we need to keep track of the actual end-blocks
2786 * of expressions to add the jumps to.
2788 ir_block *bbody = NULL, *end_bbody = NULL;
2789 ir_block *bprecond = NULL, *end_bprecond = NULL;
2790 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2791 ir_block *bincrement = NULL, *end_bincrement = NULL;
2792 ir_block *bout = NULL, *bin = NULL;
2794 /* let's at least move the outgoing block to the end */
2797 /* 'break' and 'continue' need to be able to find the right blocks */
2798 ir_block *bcontinue = NULL;
2799 ir_block *bbreak = NULL;
2801 ir_block *tmpblock = NULL;
2806 if (self->expression.outr) {
2807 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2810 self->expression.outr = (ir_value*)1;
2813 * Should we ever need some kind of block ordering, better make this function
2814 * move blocks around than write a block ordering algorithm later... after all
2815 * the ast and ir should work together, not against each other.
2818 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2819 * anyway if for example it contains a ternary.
2823 cgen = self->initexpr->codegen;
2824 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2828 /* Store the block from which we enter this chaos */
2829 bin = func->curblock;
2831 /* The pre-loop condition needs its own block since we
2832 * need to be able to jump to the start of that expression.
2836 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2840 /* the pre-loop-condition the least important place to 'continue' at */
2841 bcontinue = bprecond;
2844 func->curblock = bprecond;
2847 cgen = self->precond->codegen;
2848 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2851 end_bprecond = func->curblock;
2853 bprecond = end_bprecond = NULL;
2856 /* Now the next blocks won't be ordered nicely, but we need to
2857 * generate them this early for 'break' and 'continue'.
2859 if (self->increment) {
2860 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2863 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2865 bincrement = end_bincrement = NULL;
2868 if (self->postcond) {
2869 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2872 bcontinue = bpostcond; /* postcond comes before the increment */
2874 bpostcond = end_bpostcond = NULL;
2877 bout_id = vec_size(func->ir_func->blocks);
2878 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2883 /* The loop body... */
2884 /* if (self->body) */
2886 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2891 func->curblock = bbody;
2893 func->breakblocks.push_back(bbreak);
2895 func->continueblocks.push_back(bcontinue);
2897 func->continueblocks.push_back(bbody);
2901 cgen = self->body->codegen;
2902 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2906 end_bbody = func->curblock;
2907 func->breakblocks.pop_back();
2908 func->continueblocks.pop_back();
2911 /* post-loop-condition */
2915 func->curblock = bpostcond;
2918 cgen = self->postcond->codegen;
2919 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2922 end_bpostcond = func->curblock;
2925 /* The incrementor */
2926 if (self->increment)
2929 func->curblock = bincrement;
2932 cgen = self->increment->codegen;
2933 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2936 end_bincrement = func->curblock;
2939 /* In any case now, we continue from the outgoing block */
2940 func->curblock = bout;
2942 /* Now all blocks are in place */
2943 /* From 'bin' we jump to whatever comes first */
2944 if (bprecond) tmpblock = bprecond;
2945 else tmpblock = bbody; /* can never be null */
2948 else if (bpostcond) tmpblock = bpostcond;
2949 else tmpblock = bout;
2952 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2958 ir_block *ontrue, *onfalse;
2959 ontrue = bbody; /* can never be null */
2961 /* all of this is dead code
2962 else if (bincrement) ontrue = bincrement;
2963 else ontrue = bpostcond;
2967 if (self->pre_not) {
2972 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2979 if (bincrement) tmpblock = bincrement;
2980 else if (bpostcond) tmpblock = bpostcond;
2981 else if (bprecond) tmpblock = bprecond;
2982 else tmpblock = bbody;
2983 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2987 /* from increment */
2990 if (bpostcond) tmpblock = bpostcond;
2991 else if (bprecond) tmpblock = bprecond;
2992 else if (bbody) tmpblock = bbody;
2993 else tmpblock = bout;
2994 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3001 ir_block *ontrue, *onfalse;
3002 if (bprecond) ontrue = bprecond;
3003 else ontrue = bbody; /* can never be null */
3005 /* all of this is dead code
3006 else if (bincrement) ontrue = bincrement;
3007 else ontrue = bpostcond;
3011 if (self->post_not) {
3016 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3020 /* Move 'bout' to the end */
3021 vec_remove(func->ir_func->blocks, bout_id, 1);
3022 vec_push(func->ir_func->blocks, bout);
3027 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3034 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3038 if (self->expression.outr) {
3039 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3042 self->expression.outr = (ir_value*)1;
3044 if (self->is_continue)
3045 target = func->continueblocks[func->continueblocks.size()-1-self->levels];
3047 target = func->breakblocks[func->breakblocks.size()-1-self->levels];
3050 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3054 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3059 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3061 ast_expression_codegen *cgen;
3063 ast_switch_case *def_case = NULL;
3064 ir_block *def_bfall = NULL;
3065 ir_block *def_bfall_to = NULL;
3066 bool set_def_bfall_to = false;
3068 ir_value *dummy = NULL;
3069 ir_value *irop = NULL;
3070 ir_block *bout = NULL;
3071 ir_block *bfall = NULL;
3078 compile_error(ast_ctx(self), "switch expression is not an l-value");
3082 if (self->expression.outr) {
3083 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3086 self->expression.outr = (ir_value*)1;
3091 cgen = self->operand->codegen;
3092 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3095 if (self->cases.empty())
3098 cmpinstr = type_eq_instr[irop->vtype];
3099 if (cmpinstr >= VINSTR_END) {
3100 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3101 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3105 bout_id = vec_size(func->ir_func->blocks);
3106 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3110 /* setup the break block */
3111 func->breakblocks.push_back(bout);
3113 /* Now create all cases */
3114 for (auto &it : self->cases) {
3115 ir_value *cond, *val;
3116 ir_block *bcase, *bnot;
3119 ast_switch_case *swcase = ⁢
3121 if (swcase->value) {
3122 /* A regular case */
3123 /* generate the condition operand */
3124 cgen = swcase->value->codegen;
3125 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3127 /* generate the condition */
3128 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3132 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3133 bnot_id = vec_size(func->ir_func->blocks);
3134 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3135 if (!bcase || !bnot)
3137 if (set_def_bfall_to) {
3138 set_def_bfall_to = false;
3139 def_bfall_to = bcase;
3141 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3144 /* Make the previous case-end fall through */
3145 if (bfall && !bfall->final) {
3146 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3150 /* enter the case */
3151 func->curblock = bcase;
3152 cgen = swcase->code->codegen;
3153 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3156 /* remember this block to fall through from */
3157 bfall = func->curblock;
3159 /* enter the else and move it down */
3160 func->curblock = bnot;
3161 vec_remove(func->ir_func->blocks, bnot_id, 1);
3162 vec_push(func->ir_func->blocks, bnot);
3164 /* The default case */
3165 /* Remember where to fall through from: */
3168 /* remember which case it was */
3170 /* And the next case will be remembered */
3171 set_def_bfall_to = true;
3175 /* Jump from the last bnot to bout */
3176 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3178 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3183 /* If there was a default case, put it down here */
3187 /* No need to create an extra block */
3188 bcase = func->curblock;
3190 /* Insert the fallthrough jump */
3191 if (def_bfall && !def_bfall->final) {
3192 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3196 /* Now generate the default code */
3197 cgen = def_case->code->codegen;
3198 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3201 /* see if we need to fall through */
3202 if (def_bfall_to && !func->curblock->final)
3204 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3209 /* Jump from the last bnot to bout */
3210 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3212 /* enter the outgoing block */
3213 func->curblock = bout;
3215 /* restore the break block */
3216 func->breakblocks.pop_back();
3218 /* Move 'bout' to the end, it's nicer */
3219 vec_remove(func->ir_func->blocks, bout_id, 1);
3220 vec_push(func->ir_func->blocks, bout);
3225 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3229 if (self->undefined) {
3230 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3236 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3240 /* simply create a new block and jump to it */
3241 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3242 if (!self->irblock) {
3243 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3246 if (!func->curblock->final) {
3247 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3251 /* enter the new block */
3252 func->curblock = self->irblock;
3254 /* Generate all the leftover gotos */
3255 for (auto &it : self->gotos) {
3256 if (!ast_goto_codegen(it, func, false, &dummy))
3263 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3267 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3271 if (self->target->irblock) {
3272 if (self->irblock_from) {
3273 /* we already tried once, this is the callback */
3274 self->irblock_from->final = false;
3275 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3276 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3282 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3283 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3290 /* the target has not yet been created...
3291 * close this block in a sneaky way:
3293 func->curblock->final = true;
3294 self->irblock_from = func->curblock;
3295 ast_label_register_goto(self->target, self);
3302 bool ast_state_codegen(ast_state *self, ast_function *func, bool lvalue, ir_value **out)
3304 ast_expression_codegen *cgen;
3306 ir_value *frameval, *thinkval;
3309 compile_error(ast_ctx(self), "not an l-value (state operation)");
3312 if (self->expression.outr) {
3313 compile_error(ast_ctx(self), "internal error: ast_state cannot be reused!");
3318 cgen = self->framenum->codegen;
3319 if (!(*cgen)((ast_expression*)(self->framenum), func, false, &frameval))
3324 cgen = self->nextthink->codegen;
3325 if (!(*cgen)((ast_expression*)(self->nextthink), func, false, &thinkval))
3330 if (!ir_block_create_state_op(func->curblock, ast_ctx(self), frameval, thinkval)) {
3331 compile_error(ast_ctx(self), "failed to create STATE instruction");
3335 self->expression.outr = (ir_value*)1;
3339 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3341 ast_expression_codegen *cgen;
3343 ir_instr *callinstr;
3346 ir_value *funval = NULL;
3348 /* return values are never lvalues */
3350 compile_error(ast_ctx(self), "not an l-value (function call)");
3354 if (self->expression.outr) {
3355 *out = self->expression.outr;
3359 cgen = self->func->codegen;
3360 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3368 for (auto &it : self->params) {
3371 if (!(*cgen)(it, func, false, ¶m))
3375 vec_push(params, param);
3378 /* varargs counter */
3379 if (self->va_count) {
3381 ir_builder *builder = func->curblock->owner->owner;
3382 cgen = self->va_count->codegen;
3383 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3385 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3386 ir_builder_get_va_count(builder), va_count))
3392 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3393 ast_function_label(func, "call"),
3394 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3398 for (i = 0; i < vec_size(params); ++i) {
3399 ir_call_param(callinstr, params[i]);
3402 *out = ir_call_value(callinstr);
3403 self->expression.outr = *out;
3405 codegen_output_type(self, *out);