2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 #define ast_instantiate(T, ctx, destroyfn) \
32 T* self = (T*)mem_a(sizeof(T)); \
36 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
37 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
40 * forward declarations, these need not be in ast.h for obvious
43 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
44 static void ast_array_index_delete(ast_array_index*);
45 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
46 static void ast_store_delete(ast_store*);
47 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
48 static void ast_ifthen_delete(ast_ifthen*);
49 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
50 static void ast_ternary_delete(ast_ternary*);
51 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
52 static void ast_loop_delete(ast_loop*);
53 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
54 static void ast_breakcont_delete(ast_breakcont*);
55 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
56 static void ast_switch_delete(ast_switch*);
57 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
58 static void ast_label_delete(ast_label*);
59 static void ast_label_register_goto(ast_label*, ast_goto*);
60 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
61 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
62 static void ast_goto_delete(ast_goto*);
63 static void ast_call_delete(ast_call*);
64 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
65 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
66 static void ast_unary_delete(ast_unary*);
67 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
68 static void ast_entfield_delete(ast_entfield*);
69 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
70 static void ast_return_delete(ast_return*);
71 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
72 static void ast_binstore_delete(ast_binstore*);
73 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
74 static void ast_binary_delete(ast_binary*);
75 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
77 /* It must not be possible to get here. */
78 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
81 con_err("ast node missing destroy()\n");
85 /* Initialize main ast node aprts */
86 static void ast_node_init(ast_node *self, lex_ctx ctx, int nodetype)
89 self->destroy = &_ast_node_destroy;
91 self->nodetype = nodetype;
92 self->side_effects = false;
95 /* weight and side effects */
96 static void _ast_propagate_effects(ast_node *self, ast_node *other)
98 if (ast_side_effects(other))
99 ast_side_effects(self) = true;
101 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
103 /* General expression initialization */
104 static void ast_expression_init(ast_expression *self,
105 ast_expression_codegen *codegen)
107 self->codegen = codegen;
108 self->vtype = TYPE_VOID;
115 self->varparam = NULL;
118 static void ast_expression_delete(ast_expression *self)
122 ast_delete(self->next);
123 for (i = 0; i < vec_size(self->params); ++i) {
124 ast_delete(self->params[i]);
126 vec_free(self->params);
128 ast_delete(self->varparam);
131 static void ast_expression_delete_full(ast_expression *self)
133 ast_expression_delete(self);
137 ast_value* ast_value_copy(const ast_value *self)
140 const ast_expression *fromex;
141 ast_expression *selfex;
142 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
143 if (self->expression.next) {
144 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
146 fromex = &self->expression;
147 selfex = &cp->expression;
148 selfex->count = fromex->count;
149 selfex->flags = fromex->flags;
150 for (i = 0; i < vec_size(fromex->params); ++i) {
151 ast_value *v = ast_value_copy(fromex->params[i]);
152 vec_push(selfex->params, v);
157 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
160 const ast_expression *fromex;
161 ast_expression *selfex;
162 self->vtype = other->vtype;
164 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
168 selfex->count = fromex->count;
169 selfex->flags = fromex->flags;
170 for (i = 0; i < vec_size(fromex->params); ++i) {
171 ast_value *v = ast_value_copy(fromex->params[i]);
172 vec_push(selfex->params, v);
176 static ast_expression* ast_shallow_type(lex_ctx ctx, int vtype)
178 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
179 ast_expression_init(self, NULL);
180 self->codegen = NULL;
186 ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
189 const ast_expression *fromex;
190 ast_expression *selfex;
196 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
197 ast_expression_init(self, NULL);
202 /* This may never be codegen()d */
203 selfex->codegen = NULL;
205 selfex->vtype = fromex->vtype;
207 selfex->next = ast_type_copy(ctx, fromex->next);
211 selfex->count = fromex->count;
212 selfex->flags = fromex->flags;
213 for (i = 0; i < vec_size(fromex->params); ++i) {
214 ast_value *v = ast_value_copy(fromex->params[i]);
215 vec_push(selfex->params, v);
222 bool ast_compare_type(ast_expression *a, ast_expression *b)
224 if (a->vtype == TYPE_NIL ||
225 b->vtype == TYPE_NIL)
227 if (a->vtype != b->vtype)
229 if (!a->next != !b->next)
231 if (vec_size(a->params) != vec_size(b->params))
233 if ((a->flags & AST_FLAG_TYPE_MASK) !=
234 (b->flags & AST_FLAG_TYPE_MASK) )
238 if (vec_size(a->params)) {
240 for (i = 0; i < vec_size(a->params); ++i) {
241 if (!ast_compare_type((ast_expression*)a->params[i],
242 (ast_expression*)b->params[i]))
247 return ast_compare_type(a->next, b->next);
251 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
258 if (pos + 6 >= bufsize)
260 util_strncpy(buf + pos, "(null)", 6);
264 if (pos + 1 >= bufsize)
269 util_strncpy(buf + pos, "(variant)", 9);
274 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
277 if (pos + 3 >= bufsize)
281 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
282 if (pos + 1 >= bufsize)
288 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
289 if (pos + 2 >= bufsize)
291 if (!vec_size(e->params)) {
297 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
298 for (i = 1; i < vec_size(e->params); ++i) {
299 if (pos + 2 >= bufsize)
303 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
305 if (pos + 1 >= bufsize)
311 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
312 if (pos + 1 >= bufsize)
315 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
316 if (pos + 1 >= bufsize)
322 typestr = type_name[e->vtype];
323 typelen = strlen(typestr);
324 if (pos + typelen >= bufsize)
326 util_strncpy(buf + pos, typestr, typelen);
327 return pos + typelen;
331 buf[bufsize-3] = '.';
332 buf[bufsize-2] = '.';
333 buf[bufsize-1] = '.';
337 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
339 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
343 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
344 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
346 ast_instantiate(ast_value, ctx, ast_value_delete);
347 ast_expression_init((ast_expression*)self,
348 (ast_expression_codegen*)&ast_value_codegen);
349 self->expression.node.keep = true; /* keep */
351 self->name = name ? util_strdup(name) : NULL;
352 self->expression.vtype = t;
353 self->expression.next = NULL;
354 self->isfield = false;
356 self->hasvalue = false;
359 memset(&self->constval, 0, sizeof(self->constval));
360 self->initlist = NULL;
363 self->ir_values = NULL;
364 self->ir_value_count = 0;
370 self->argcounter = NULL;
375 void ast_value_delete(ast_value* self)
378 mem_d((void*)self->name);
379 if (self->argcounter)
380 mem_d((void*)self->argcounter);
381 if (self->hasvalue) {
382 switch (self->expression.vtype)
385 mem_d((void*)self->constval.vstring);
388 /* unlink us from the function node */
389 self->constval.vfunc->vtype = NULL;
391 /* NOTE: delete function? currently collected in
392 * the parser structure
399 mem_d(self->ir_values);
404 if (self->initlist) {
405 if (self->expression.next->vtype == TYPE_STRING) {
406 /* strings are allocated, free them */
407 size_t i, len = vec_size(self->initlist);
408 /* in theory, len should be expression.count
409 * but let's not take any chances */
410 for (i = 0; i < len; ++i) {
411 if (self->initlist[i].vstring)
412 mem_d(self->initlist[i].vstring);
415 vec_free(self->initlist);
418 ast_expression_delete((ast_expression*)self);
422 void ast_value_params_add(ast_value *self, ast_value *p)
424 vec_push(self->expression.params, p);
427 bool ast_value_set_name(ast_value *self, const char *name)
430 mem_d((void*)self->name);
431 self->name = util_strdup(name);
435 ast_binary* ast_binary_new(lex_ctx ctx, int op,
436 ast_expression* left, ast_expression* right)
438 ast_instantiate(ast_binary, ctx, ast_binary_delete);
439 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
445 ast_propagate_effects(self, left);
446 ast_propagate_effects(self, right);
448 if (op >= INSTR_EQ_F && op <= INSTR_GT)
449 self->expression.vtype = TYPE_FLOAT;
450 else if (op == INSTR_AND || op == INSTR_OR) {
451 if (OPTS_FLAG(PERL_LOGIC))
452 ast_type_adopt(self, right);
454 self->expression.vtype = TYPE_FLOAT;
456 else if (op == INSTR_BITAND || op == INSTR_BITOR)
457 self->expression.vtype = TYPE_FLOAT;
458 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
459 self->expression.vtype = TYPE_VECTOR;
460 else if (op == INSTR_MUL_V)
461 self->expression.vtype = TYPE_FLOAT;
463 self->expression.vtype = left->vtype;
466 self->refs = AST_REF_ALL;
471 void ast_binary_delete(ast_binary *self)
473 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
474 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
476 ast_expression_delete((ast_expression*)self);
480 ast_binstore* ast_binstore_new(lex_ctx ctx, int storop, int op,
481 ast_expression* left, ast_expression* right)
483 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
484 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
486 ast_side_effects(self) = true;
488 self->opstore = storop;
491 self->source = right;
493 self->keep_dest = false;
495 ast_type_adopt(self, left);
499 void ast_binstore_delete(ast_binstore *self)
501 if (!self->keep_dest)
502 ast_unref(self->dest);
503 ast_unref(self->source);
504 ast_expression_delete((ast_expression*)self);
508 ast_unary* ast_unary_new(lex_ctx ctx, int op,
509 ast_expression *expr)
511 ast_instantiate(ast_unary, ctx, ast_unary_delete);
512 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
515 self->operand = expr;
517 ast_propagate_effects(self, expr);
519 if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
520 self->expression.vtype = TYPE_FLOAT;
522 compile_error(ctx, "cannot determine type of unary operation %s", asm_instr[op].m);
527 void ast_unary_delete(ast_unary *self)
529 if (self->operand) ast_unref(self->operand);
530 ast_expression_delete((ast_expression*)self);
534 ast_return* ast_return_new(lex_ctx ctx, ast_expression *expr)
536 ast_instantiate(ast_return, ctx, ast_return_delete);
537 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
539 self->operand = expr;
542 ast_propagate_effects(self, expr);
547 void ast_return_delete(ast_return *self)
550 ast_unref(self->operand);
551 ast_expression_delete((ast_expression*)self);
555 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
557 if (field->vtype != TYPE_FIELD) {
558 compile_error(ctx, "ast_entfield_new with expression not of type field");
561 return ast_entfield_new_force(ctx, entity, field, field->next);
564 ast_entfield* ast_entfield_new_force(lex_ctx ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
566 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
570 /* Error: field has no type... */
574 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
576 self->entity = entity;
578 ast_propagate_effects(self, entity);
579 ast_propagate_effects(self, field);
581 ast_type_adopt(self, outtype);
585 void ast_entfield_delete(ast_entfield *self)
587 ast_unref(self->entity);
588 ast_unref(self->field);
589 ast_expression_delete((ast_expression*)self);
593 ast_member* ast_member_new(lex_ctx ctx, ast_expression *owner, unsigned int field, const char *name)
595 ast_instantiate(ast_member, ctx, ast_member_delete);
601 if (owner->vtype != TYPE_VECTOR &&
602 owner->vtype != TYPE_FIELD) {
603 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
608 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
609 self->expression.node.keep = true; /* keep */
611 if (owner->vtype == TYPE_VECTOR) {
612 self->expression.vtype = TYPE_FLOAT;
613 self->expression.next = NULL;
615 self->expression.vtype = TYPE_FIELD;
616 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
619 self->rvalue = false;
621 ast_propagate_effects(self, owner);
625 self->name = util_strdup(name);
632 void ast_member_delete(ast_member *self)
634 /* The owner is always an ast_value, which has .keep=true,
635 * also: ast_members are usually deleted after the owner, thus
636 * this will cause invalid access
637 ast_unref(self->owner);
638 * once we allow (expression).x to access a vector-member, we need
639 * to change this: preferably by creating an alternate ast node for this
640 * purpose that is not garbage-collected.
642 ast_expression_delete((ast_expression*)self);
647 bool ast_member_set_name(ast_member *self, const char *name)
650 mem_d((void*)self->name);
651 self->name = util_strdup(name);
655 ast_array_index* ast_array_index_new(lex_ctx ctx, ast_expression *array, ast_expression *index)
657 ast_expression *outtype;
658 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
660 outtype = array->next;
663 /* Error: field has no type... */
667 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
671 ast_propagate_effects(self, array);
672 ast_propagate_effects(self, index);
674 ast_type_adopt(self, outtype);
675 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
676 if (self->expression.vtype != TYPE_ARRAY) {
677 compile_error(ast_ctx(self), "array_index node on type");
678 ast_array_index_delete(self);
681 self->array = outtype;
682 self->expression.vtype = TYPE_FIELD;
688 void ast_array_index_delete(ast_array_index *self)
691 ast_unref(self->array);
693 ast_unref(self->index);
694 ast_expression_delete((ast_expression*)self);
698 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
700 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
701 if (!ontrue && !onfalse) {
702 /* because it is invalid */
706 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
709 self->on_true = ontrue;
710 self->on_false = onfalse;
711 ast_propagate_effects(self, cond);
713 ast_propagate_effects(self, ontrue);
715 ast_propagate_effects(self, onfalse);
720 void ast_ifthen_delete(ast_ifthen *self)
722 ast_unref(self->cond);
724 ast_unref(self->on_true);
726 ast_unref(self->on_false);
727 ast_expression_delete((ast_expression*)self);
731 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
733 ast_expression *exprtype = ontrue;
734 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
735 /* This time NEITHER must be NULL */
736 if (!ontrue || !onfalse) {
740 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
743 self->on_true = ontrue;
744 self->on_false = onfalse;
745 ast_propagate_effects(self, cond);
746 ast_propagate_effects(self, ontrue);
747 ast_propagate_effects(self, onfalse);
749 if (ontrue->vtype == TYPE_NIL)
751 ast_type_adopt(self, exprtype);
756 void ast_ternary_delete(ast_ternary *self)
758 /* the if()s are only there because computed-gotos can set them
761 if (self->cond) ast_unref(self->cond);
762 if (self->on_true) ast_unref(self->on_true);
763 if (self->on_false) ast_unref(self->on_false);
764 ast_expression_delete((ast_expression*)self);
768 ast_loop* ast_loop_new(lex_ctx ctx,
769 ast_expression *initexpr,
770 ast_expression *precond, bool pre_not,
771 ast_expression *postcond, bool post_not,
772 ast_expression *increment,
773 ast_expression *body)
775 ast_instantiate(ast_loop, ctx, ast_loop_delete);
776 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
778 self->initexpr = initexpr;
779 self->precond = precond;
780 self->postcond = postcond;
781 self->increment = increment;
784 self->pre_not = pre_not;
785 self->post_not = post_not;
788 ast_propagate_effects(self, initexpr);
790 ast_propagate_effects(self, precond);
792 ast_propagate_effects(self, postcond);
794 ast_propagate_effects(self, increment);
796 ast_propagate_effects(self, body);
801 void ast_loop_delete(ast_loop *self)
804 ast_unref(self->initexpr);
806 ast_unref(self->precond);
808 ast_unref(self->postcond);
810 ast_unref(self->increment);
812 ast_unref(self->body);
813 ast_expression_delete((ast_expression*)self);
817 ast_breakcont* ast_breakcont_new(lex_ctx ctx, bool iscont, unsigned int levels)
819 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
820 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
822 self->is_continue = iscont;
823 self->levels = levels;
828 void ast_breakcont_delete(ast_breakcont *self)
830 ast_expression_delete((ast_expression*)self);
834 ast_switch* ast_switch_new(lex_ctx ctx, ast_expression *op)
836 ast_instantiate(ast_switch, ctx, ast_switch_delete);
837 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
842 ast_propagate_effects(self, op);
847 void ast_switch_delete(ast_switch *self)
850 ast_unref(self->operand);
852 for (i = 0; i < vec_size(self->cases); ++i) {
853 if (self->cases[i].value)
854 ast_unref(self->cases[i].value);
855 ast_unref(self->cases[i].code);
857 vec_free(self->cases);
859 ast_expression_delete((ast_expression*)self);
863 ast_label* ast_label_new(lex_ctx ctx, const char *name, bool undefined)
865 ast_instantiate(ast_label, ctx, ast_label_delete);
866 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
868 self->expression.vtype = TYPE_NOEXPR;
870 self->name = util_strdup(name);
871 self->irblock = NULL;
873 self->undefined = undefined;
878 void ast_label_delete(ast_label *self)
880 mem_d((void*)self->name);
881 vec_free(self->gotos);
882 ast_expression_delete((ast_expression*)self);
886 static void ast_label_register_goto(ast_label *self, ast_goto *g)
888 vec_push(self->gotos, g);
891 ast_goto* ast_goto_new(lex_ctx ctx, const char *name)
893 ast_instantiate(ast_goto, ctx, ast_goto_delete);
894 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
896 self->name = util_strdup(name);
898 self->irblock_from = NULL;
903 void ast_goto_delete(ast_goto *self)
905 mem_d((void*)self->name);
906 ast_expression_delete((ast_expression*)self);
910 void ast_goto_set_label(ast_goto *self, ast_label *label)
912 self->target = label;
915 ast_call* ast_call_new(lex_ctx ctx,
916 ast_expression *funcexpr)
918 ast_instantiate(ast_call, ctx, ast_call_delete);
919 if (!funcexpr->next) {
920 compile_error(ctx, "not a function");
924 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
926 ast_side_effects(self) = true;
929 self->func = funcexpr;
930 self->va_count = NULL;
932 ast_type_adopt(self, funcexpr->next);
937 void ast_call_delete(ast_call *self)
940 for (i = 0; i < vec_size(self->params); ++i)
941 ast_unref(self->params[i]);
942 vec_free(self->params);
945 ast_unref(self->func);
948 ast_unref(self->va_count);
950 ast_expression_delete((ast_expression*)self);
954 bool ast_call_check_types(ast_call *self)
960 const ast_expression *func = self->func;
961 size_t count = vec_size(self->params);
962 if (count > vec_size(func->params))
963 count = vec_size(func->params);
965 for (i = 0; i < count; ++i) {
966 if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
968 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
969 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
970 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
971 (unsigned int)(i+1), texp, tgot);
972 /* we don't immediately return */
976 count = vec_size(self->params);
977 if (count > vec_size(func->params) && func->varparam) {
978 for (; i < count; ++i) {
979 if (!ast_compare_type(self->params[i], func->varparam))
981 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
982 ast_type_to_string(func->varparam, texp, sizeof(texp));
983 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
984 (unsigned int)(i+1), texp, tgot);
985 /* we don't immediately return */
993 ast_store* ast_store_new(lex_ctx ctx, int op,
994 ast_expression *dest, ast_expression *source)
996 ast_instantiate(ast_store, ctx, ast_store_delete);
997 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
999 ast_side_effects(self) = true;
1003 self->source = source;
1005 ast_type_adopt(self, dest);
1010 void ast_store_delete(ast_store *self)
1012 ast_unref(self->dest);
1013 ast_unref(self->source);
1014 ast_expression_delete((ast_expression*)self);
1018 ast_block* ast_block_new(lex_ctx ctx)
1020 ast_instantiate(ast_block, ctx, ast_block_delete);
1021 ast_expression_init((ast_expression*)self,
1022 (ast_expression_codegen*)&ast_block_codegen);
1024 self->locals = NULL;
1026 self->collect = NULL;
1031 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1033 ast_propagate_effects(self, e);
1034 vec_push(self->exprs, e);
1035 if (self->expression.next) {
1036 ast_delete(self->expression.next);
1037 self->expression.next = NULL;
1039 ast_type_adopt(self, e);
1043 void ast_block_collect(ast_block *self, ast_expression *expr)
1045 vec_push(self->collect, expr);
1046 expr->node.keep = true;
1049 void ast_block_delete(ast_block *self)
1052 for (i = 0; i < vec_size(self->exprs); ++i)
1053 ast_unref(self->exprs[i]);
1054 vec_free(self->exprs);
1055 for (i = 0; i < vec_size(self->locals); ++i)
1056 ast_delete(self->locals[i]);
1057 vec_free(self->locals);
1058 for (i = 0; i < vec_size(self->collect); ++i)
1059 ast_delete(self->collect[i]);
1060 vec_free(self->collect);
1061 ast_expression_delete((ast_expression*)self);
1065 void ast_block_set_type(ast_block *self, ast_expression *from)
1067 if (self->expression.next)
1068 ast_delete(self->expression.next);
1069 ast_type_adopt(self, from);
1072 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
1074 ast_instantiate(ast_function, ctx, ast_function_delete);
1078 vtype->expression.vtype != TYPE_FUNCTION)
1080 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1082 (int)vtype->hasvalue,
1083 vtype->expression.vtype);
1088 self->vtype = vtype;
1089 self->name = name ? util_strdup(name) : NULL;
1090 self->blocks = NULL;
1092 self->labelcount = 0;
1095 self->ir_func = NULL;
1096 self->curblock = NULL;
1098 self->breakblocks = NULL;
1099 self->continueblocks = NULL;
1101 vtype->hasvalue = true;
1102 vtype->constval.vfunc = self;
1104 self->varargs = NULL;
1106 self->fixedparams = NULL;
1107 self->return_value = NULL;
1112 void ast_function_delete(ast_function *self)
1116 mem_d((void*)self->name);
1118 /* ast_value_delete(self->vtype); */
1119 self->vtype->hasvalue = false;
1120 self->vtype->constval.vfunc = NULL;
1121 /* We use unref - if it was stored in a global table it is supposed
1122 * to be deleted from *there*
1124 ast_unref(self->vtype);
1126 for (i = 0; i < vec_size(self->blocks); ++i)
1127 ast_delete(self->blocks[i]);
1128 vec_free(self->blocks);
1129 vec_free(self->breakblocks);
1130 vec_free(self->continueblocks);
1132 ast_delete(self->varargs);
1134 ast_delete(self->argc);
1135 if (self->fixedparams)
1136 ast_unref(self->fixedparams);
1137 if (self->return_value)
1138 ast_unref(self->return_value);
1142 static const char* ast_function_label(ast_function *self, const char *prefix)
1148 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1149 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1150 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1155 id = (self->labelcount++);
1156 len = strlen(prefix);
1158 from = self->labelbuf + sizeof(self->labelbuf)-1;
1161 *from-- = (id%10) + '0';
1165 memcpy(from - len, prefix, len);
1169 /*********************************************************************/
1171 * by convention you must never pass NULL to the 'ir_value **out'
1172 * parameter. If you really don't care about the output, pass a dummy.
1173 * But I can't imagine a pituation where the output is truly unnecessary.
1176 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1178 if (out->vtype == TYPE_FIELD)
1179 out->fieldtype = self->next->vtype;
1180 if (out->vtype == TYPE_FUNCTION)
1181 out->outtype = self->next->vtype;
1184 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1186 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1190 if (self->expression.vtype == TYPE_NIL) {
1191 *out = func->ir_func->owner->nil;
1194 /* NOTE: This is the codegen for a variable used in an expression.
1195 * It is not the codegen to generate the value. For this purpose,
1196 * ast_local_codegen and ast_global_codegen are to be used before this
1197 * is executed. ast_function_codegen should take care of its locals,
1198 * and the ast-user should take care of ast_global_codegen to be used
1199 * on all the globals.
1202 char tname[1024]; /* typename is reserved in C++ */
1203 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1204 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1211 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1215 if (self->expression.vtype == TYPE_NIL) {
1216 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1220 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1222 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1225 func->context = ast_ctx(self);
1226 func->value->context = ast_ctx(self);
1228 self->constval.vfunc->ir_func = func;
1229 self->ir_v = func->value;
1230 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1231 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1232 /* The function is filled later on ast_function_codegen... */
1236 if (isfield && self->expression.vtype == TYPE_FIELD) {
1237 ast_expression *fieldtype = self->expression.next;
1239 if (self->hasvalue) {
1240 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1244 if (fieldtype->vtype == TYPE_ARRAY) {
1249 ast_expression *elemtype;
1251 ast_value *array = (ast_value*)fieldtype;
1253 if (!ast_istype(fieldtype, ast_value)) {
1254 compile_error(ast_ctx(self), "internal error: ast_value required");
1258 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1259 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE))
1260 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1262 elemtype = array->expression.next;
1263 vtype = elemtype->vtype;
1265 v = ir_builder_create_field(ir, self->name, vtype);
1267 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1270 v->context = ast_ctx(self);
1271 v->unique_life = true;
1273 array->ir_v = self->ir_v = v;
1274 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1275 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1277 namelen = strlen(self->name);
1278 name = (char*)mem_a(namelen + 16);
1279 util_strncpy(name, self->name, namelen);
1281 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1282 array->ir_values[0] = v;
1283 for (ai = 1; ai < array->expression.count; ++ai) {
1284 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1285 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1286 if (!array->ir_values[ai]) {
1288 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1291 array->ir_values[ai]->context = ast_ctx(self);
1292 array->ir_values[ai]->unique_life = true;
1293 array->ir_values[ai]->locked = true;
1294 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1295 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1301 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1304 v->context = ast_ctx(self);
1306 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1307 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1312 if (self->expression.vtype == TYPE_ARRAY) {
1317 ast_expression *elemtype = self->expression.next;
1318 int vtype = elemtype->vtype;
1320 /* same as with field arrays */
1321 if (!self->expression.count || self->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE))
1322 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1324 v = ir_builder_create_global(ir, self->name, vtype);
1326 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1329 v->context = ast_ctx(self);
1330 v->unique_life = true;
1332 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1333 v->flags |= IR_FLAG_INCLUDE_DEF;
1335 namelen = strlen(self->name);
1336 name = (char*)mem_a(namelen + 16);
1337 util_strncpy(name, self->name, namelen);
1339 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1340 self->ir_values[0] = v;
1341 for (ai = 1; ai < self->expression.count; ++ai) {
1342 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1343 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1344 if (!self->ir_values[ai]) {
1346 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1349 self->ir_values[ai]->context = ast_ctx(self);
1350 self->ir_values[ai]->unique_life = true;
1351 self->ir_values[ai]->locked = true;
1352 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1353 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1359 /* Arrays don't do this since there's no "array" value which spans across the
1362 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1364 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1367 codegen_output_type(self, v);
1368 v->context = ast_ctx(self);
1371 if (self->hasvalue) {
1372 switch (self->expression.vtype)
1375 if (!ir_value_set_float(v, self->constval.vfloat))
1379 if (!ir_value_set_vector(v, self->constval.vvec))
1383 if (!ir_value_set_string(v, self->constval.vstring))
1387 compile_error(ast_ctx(self), "TODO: global constant array");
1390 compile_error(ast_ctx(self), "global of type function not properly generated");
1392 /* Cannot generate an IR value for a function,
1393 * need a pointer pointing to a function rather.
1396 if (!self->constval.vfield) {
1397 compile_error(ast_ctx(self), "field constant without vfield set");
1400 if (!self->constval.vfield->ir_v) {
1401 compile_error(ast_ctx(self), "field constant generated before its field");
1404 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1408 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1413 /* link us to the ir_value */
1416 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1417 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1420 error: /* clean up */
1425 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1429 if (self->expression.vtype == TYPE_NIL) {
1430 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1434 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1436 /* Do we allow local functions? I think not...
1437 * this is NOT a function pointer atm.
1442 if (self->expression.vtype == TYPE_ARRAY) {
1447 ast_expression *elemtype = self->expression.next;
1448 int vtype = elemtype->vtype;
1450 func->flags |= IR_FLAG_HAS_ARRAYS;
1452 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1453 compile_error(ast_ctx(self), "array-parameters are not supported");
1457 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1458 if (!self->expression.count || self->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1459 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1462 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1463 if (!self->ir_values) {
1464 compile_error(ast_ctx(self), "failed to allocate array values");
1468 v = ir_function_create_local(func, self->name, vtype, param);
1470 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1473 v->context = ast_ctx(self);
1474 v->unique_life = true;
1477 namelen = strlen(self->name);
1478 name = (char*)mem_a(namelen + 16);
1479 util_strncpy(name, self->name, namelen);
1481 self->ir_values[0] = v;
1482 for (ai = 1; ai < self->expression.count; ++ai) {
1483 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1484 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1485 if (!self->ir_values[ai]) {
1486 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1489 self->ir_values[ai]->context = ast_ctx(self);
1490 self->ir_values[ai]->unique_life = true;
1491 self->ir_values[ai]->locked = true;
1497 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1500 codegen_output_type(self, v);
1501 v->context = ast_ctx(self);
1504 /* A constant local... hmmm...
1505 * I suppose the IR will have to deal with this
1507 if (self->hasvalue) {
1508 switch (self->expression.vtype)
1511 if (!ir_value_set_float(v, self->constval.vfloat))
1515 if (!ir_value_set_vector(v, self->constval.vvec))
1519 if (!ir_value_set_string(v, self->constval.vstring))
1523 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1528 /* link us to the ir_value */
1532 if (!ast_generate_accessors(self, func->owner))
1536 error: /* clean up */
1541 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1544 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1545 if (!self->setter || !self->getter)
1547 for (i = 0; i < self->expression.count; ++i) {
1548 if (!self->ir_values) {
1549 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1552 if (!self->ir_values[i]) {
1553 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1556 if (self->ir_values[i]->life) {
1557 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1562 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1564 if (!ast_global_codegen (self->setter, ir, false) ||
1565 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1566 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1568 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1569 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1574 if (!ast_global_codegen (self->getter, ir, false) ||
1575 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1576 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1578 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1579 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1583 for (i = 0; i < self->expression.count; ++i) {
1584 vec_free(self->ir_values[i]->life);
1586 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1590 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1595 ast_expression_codegen *cgen;
1600 irf = self->ir_func;
1602 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1606 /* fill the parameter list */
1607 ec = &self->vtype->expression;
1608 for (i = 0; i < vec_size(ec->params); ++i)
1610 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1611 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1613 vec_push(irf->params, ec->params[i]->expression.vtype);
1614 if (!self->builtin) {
1615 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1620 if (self->varargs) {
1621 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1623 irf->max_varargs = self->varargs->expression.count;
1626 if (self->builtin) {
1627 irf->builtin = self->builtin;
1631 /* have a local return value variable? */
1632 if (self->return_value) {
1633 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1637 if (!vec_size(self->blocks)) {
1638 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1642 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1643 if (!self->curblock) {
1644 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1652 if (!ast_local_codegen(self->argc, self->ir_func, true))
1654 cgen = self->argc->expression.codegen;
1655 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1657 cgen = self->fixedparams->expression.codegen;
1658 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1660 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1661 ast_function_label(self, "va_count"), INSTR_SUB_F,
1662 ir_builder_get_va_count(ir), fixed);
1665 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1672 for (i = 0; i < vec_size(self->blocks); ++i) {
1673 cgen = self->blocks[i]->expression.codegen;
1674 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1678 /* TODO: check return types */
1679 if (!self->curblock->final)
1681 if (!self->vtype->expression.next ||
1682 self->vtype->expression.next->vtype == TYPE_VOID)
1684 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1686 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1688 if (self->return_value) {
1689 cgen = self->return_value->expression.codegen;
1690 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1692 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1694 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1695 "control reaches end of non-void function (`%s`) via %s",
1696 self->name, self->curblock->label))
1700 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1706 /* Note, you will not see ast_block_codegen generate ir_blocks.
1707 * To the AST and the IR, blocks are 2 different things.
1708 * In the AST it represents a block of code, usually enclosed in
1709 * curly braces {...}.
1710 * While in the IR it represents a block in terms of control-flow.
1712 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1716 /* We don't use this
1717 * Note: an ast-representation using the comma-operator
1718 * of the form: (a, b, c) = x should not assign to c...
1721 compile_error(ast_ctx(self), "not an l-value (code-block)");
1725 if (self->expression.outr) {
1726 *out = self->expression.outr;
1730 /* output is NULL at first, we'll have each expression
1731 * assign to out output, thus, a comma-operator represention
1732 * using an ast_block will return the last generated value,
1733 * so: (b, c) + a executed both b and c, and returns c,
1734 * which is then added to a.
1738 /* generate locals */
1739 for (i = 0; i < vec_size(self->locals); ++i)
1741 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1742 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1743 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1748 for (i = 0; i < vec_size(self->exprs); ++i)
1750 ast_expression_codegen *gen;
1751 if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1752 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1756 gen = self->exprs[i]->codegen;
1757 if (!(*gen)(self->exprs[i], func, false, out))
1761 self->expression.outr = *out;
1766 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1768 ast_expression_codegen *cgen;
1769 ir_value *left = NULL;
1770 ir_value *right = NULL;
1774 ast_array_index *ai = NULL;
1776 if (lvalue && self->expression.outl) {
1777 *out = self->expression.outl;
1781 if (!lvalue && self->expression.outr) {
1782 *out = self->expression.outr;
1786 if (ast_istype(self->dest, ast_array_index))
1789 ai = (ast_array_index*)self->dest;
1790 idx = (ast_value*)ai->index;
1792 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1797 /* we need to call the setter */
1798 ir_value *iridx, *funval;
1802 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1806 arr = (ast_value*)ai->array;
1807 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1808 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1812 cgen = idx->expression.codegen;
1813 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1816 cgen = arr->setter->expression.codegen;
1817 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1820 cgen = self->source->codegen;
1821 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1824 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1827 ir_call_param(call, iridx);
1828 ir_call_param(call, right);
1829 self->expression.outr = right;
1835 cgen = self->dest->codegen;
1837 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1839 self->expression.outl = left;
1841 cgen = self->source->codegen;
1843 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1846 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
1848 self->expression.outr = right;
1851 /* Theoretically, an assinment returns its left side as an
1852 * lvalue, if we don't need an lvalue though, we return
1853 * the right side as an rvalue, otherwise we have to
1854 * somehow know whether or not we need to dereference the pointer
1855 * on the left side - that is: OP_LOAD if it was an address.
1856 * Also: in original QC we cannot OP_LOADP *anyway*.
1858 *out = (lvalue ? left : right);
1863 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1865 ast_expression_codegen *cgen;
1866 ir_value *left, *right;
1868 /* A binary operation cannot yield an l-value */
1870 compile_error(ast_ctx(self), "not an l-value (binop)");
1874 if (self->expression.outr) {
1875 *out = self->expression.outr;
1879 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
1880 (self->op == INSTR_AND || self->op == INSTR_OR))
1882 /* short circuit evaluation */
1883 ir_block *other, *merge;
1884 ir_block *from_left, *from_right;
1888 /* prepare end-block */
1889 merge_id = vec_size(func->ir_func->blocks);
1890 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
1892 /* generate the left expression */
1893 cgen = self->left->codegen;
1894 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1896 /* remember the block */
1897 from_left = func->curblock;
1899 /* create a new block for the right expression */
1900 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
1901 if (self->op == INSTR_AND) {
1902 /* on AND: left==true -> other */
1903 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
1906 /* on OR: left==false -> other */
1907 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
1910 /* use the likely flag */
1911 vec_last(func->curblock->instr)->likely = true;
1913 /* enter the right-expression's block */
1914 func->curblock = other;
1916 cgen = self->right->codegen;
1917 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1919 /* remember block */
1920 from_right = func->curblock;
1922 /* jump to the merge block */
1923 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
1926 vec_remove(func->ir_func->blocks, merge_id, 1);
1927 vec_push(func->ir_func->blocks, merge);
1929 func->curblock = merge;
1930 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
1931 ast_function_label(func, "sce_value"),
1932 self->expression.vtype);
1933 ir_phi_add(phi, from_left, left);
1934 ir_phi_add(phi, from_right, right);
1935 *out = ir_phi_value(phi);
1939 if (!OPTS_FLAG(PERL_LOGIC)) {
1941 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
1942 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1943 ast_function_label(func, "sce_bool_v"),
1947 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1948 ast_function_label(func, "sce_bool"),
1953 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
1954 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1955 ast_function_label(func, "sce_bool_s"),
1959 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1960 ast_function_label(func, "sce_bool"),
1966 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
1967 ast_function_label(func, "sce_bool"),
1968 INSTR_AND, *out, *out);
1974 self->expression.outr = *out;
1975 codegen_output_type(self, *out);
1979 cgen = self->left->codegen;
1980 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1983 cgen = self->right->codegen;
1984 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1987 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
1988 self->op, left, right);
1991 self->expression.outr = *out;
1992 codegen_output_type(self, *out);
1997 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1999 ast_expression_codegen *cgen;
2000 ir_value *leftl = NULL, *leftr, *right, *bin;
2004 ast_array_index *ai = NULL;
2005 ir_value *iridx = NULL;
2007 if (lvalue && self->expression.outl) {
2008 *out = self->expression.outl;
2012 if (!lvalue && self->expression.outr) {
2013 *out = self->expression.outr;
2017 if (ast_istype(self->dest, ast_array_index))
2020 ai = (ast_array_index*)self->dest;
2021 idx = (ast_value*)ai->index;
2023 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2027 /* for a binstore we need both an lvalue and an rvalue for the left side */
2028 /* rvalue of destination! */
2030 cgen = idx->expression.codegen;
2031 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2034 cgen = self->dest->codegen;
2035 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2038 /* source as rvalue only */
2039 cgen = self->source->codegen;
2040 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2043 /* now the binary */
2044 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2045 self->opbin, leftr, right);
2046 self->expression.outr = bin;
2050 /* we need to call the setter */
2055 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2059 arr = (ast_value*)ai->array;
2060 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2061 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2065 cgen = arr->setter->expression.codegen;
2066 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2069 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2072 ir_call_param(call, iridx);
2073 ir_call_param(call, bin);
2074 self->expression.outr = bin;
2076 /* now store them */
2077 cgen = self->dest->codegen;
2078 /* lvalue of destination */
2079 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2081 self->expression.outl = leftl;
2083 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2085 self->expression.outr = bin;
2088 /* Theoretically, an assinment returns its left side as an
2089 * lvalue, if we don't need an lvalue though, we return
2090 * the right side as an rvalue, otherwise we have to
2091 * somehow know whether or not we need to dereference the pointer
2092 * on the left side - that is: OP_LOAD if it was an address.
2093 * Also: in original QC we cannot OP_LOADP *anyway*.
2095 *out = (lvalue ? leftl : bin);
2100 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2102 ast_expression_codegen *cgen;
2105 /* An unary operation cannot yield an l-value */
2107 compile_error(ast_ctx(self), "not an l-value (binop)");
2111 if (self->expression.outr) {
2112 *out = self->expression.outr;
2116 cgen = self->operand->codegen;
2118 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2121 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2125 self->expression.outr = *out;
2130 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2132 ast_expression_codegen *cgen;
2137 /* In the context of a return operation, we don't actually return
2141 compile_error(ast_ctx(self), "return-expression is not an l-value");
2145 if (self->expression.outr) {
2146 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2149 self->expression.outr = (ir_value*)1;
2151 if (self->operand) {
2152 cgen = self->operand->codegen;
2154 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2157 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2160 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2167 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2169 ast_expression_codegen *cgen;
2170 ir_value *ent, *field;
2172 /* This function needs to take the 'lvalue' flag into account!
2173 * As lvalue we provide a field-pointer, as rvalue we provide the
2177 if (lvalue && self->expression.outl) {
2178 *out = self->expression.outl;
2182 if (!lvalue && self->expression.outr) {
2183 *out = self->expression.outr;
2187 cgen = self->entity->codegen;
2188 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2191 cgen = self->field->codegen;
2192 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2197 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2200 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2201 ent, field, self->expression.vtype);
2202 /* Done AFTER error checking:
2203 codegen_output_type(self, *out);
2207 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2208 (lvalue ? "ADDRESS" : "FIELD"),
2209 type_name[self->expression.vtype]);
2213 codegen_output_type(self, *out);
2216 self->expression.outl = *out;
2218 self->expression.outr = *out;
2220 /* Hm that should be it... */
2224 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2226 ast_expression_codegen *cgen;
2229 /* in QC this is always an lvalue */
2230 if (lvalue && self->rvalue) {
2231 compile_error(ast_ctx(self), "not an l-value (member access)");
2234 if (self->expression.outl) {
2235 *out = self->expression.outl;
2239 cgen = self->owner->codegen;
2240 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2243 if (vec->vtype != TYPE_VECTOR &&
2244 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2249 *out = ir_value_vector_member(vec, self->field);
2250 self->expression.outl = *out;
2252 return (*out != NULL);
2255 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2260 if (!lvalue && self->expression.outr) {
2261 *out = self->expression.outr;
2264 if (lvalue && self->expression.outl) {
2265 *out = self->expression.outl;
2269 if (!ast_istype(self->array, ast_value)) {
2270 compile_error(ast_ctx(self), "array indexing this way is not supported");
2271 /* note this would actually be pointer indexing because the left side is
2272 * not an actual array but (hopefully) an indexable expression.
2273 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2274 * support this path will be filled.
2279 arr = (ast_value*)self->array;
2280 idx = (ast_value*)self->index;
2282 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2283 /* Time to use accessor functions */
2284 ast_expression_codegen *cgen;
2285 ir_value *iridx, *funval;
2289 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2294 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2298 cgen = self->index->codegen;
2299 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2302 cgen = arr->getter->expression.codegen;
2303 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2306 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2309 ir_call_param(call, iridx);
2311 *out = ir_call_value(call);
2312 self->expression.outr = *out;
2313 (*out)->vtype = self->expression.vtype;
2314 codegen_output_type(self, *out);
2318 if (idx->expression.vtype == TYPE_FLOAT) {
2319 unsigned int arridx = idx->constval.vfloat;
2320 if (arridx >= self->array->count)
2322 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2325 *out = arr->ir_values[arridx];
2327 else if (idx->expression.vtype == TYPE_INTEGER) {
2328 unsigned int arridx = idx->constval.vint;
2329 if (arridx >= self->array->count)
2331 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2334 *out = arr->ir_values[arridx];
2337 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2340 (*out)->vtype = self->expression.vtype;
2341 codegen_output_type(self, *out);
2345 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2347 ast_expression_codegen *cgen;
2355 ir_block *ontrue_endblock = NULL;
2356 ir_block *onfalse_endblock = NULL;
2357 ir_block *merge = NULL;
2359 /* We don't output any value, thus also don't care about r/lvalue */
2363 if (self->expression.outr) {
2364 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2367 self->expression.outr = (ir_value*)1;
2369 /* generate the condition */
2370 cgen = self->cond->codegen;
2371 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2373 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2374 cond = func->curblock;
2378 if (self->on_true) {
2379 /* create on-true block */
2380 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2384 /* enter the block */
2385 func->curblock = ontrue;
2388 cgen = self->on_true->codegen;
2389 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2392 /* we now need to work from the current endpoint */
2393 ontrue_endblock = func->curblock;
2398 if (self->on_false) {
2399 /* create on-false block */
2400 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2404 /* enter the block */
2405 func->curblock = onfalse;
2408 cgen = self->on_false->codegen;
2409 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2412 /* we now need to work from the current endpoint */
2413 onfalse_endblock = func->curblock;
2417 /* Merge block were they all merge in to */
2418 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2420 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2423 /* add jumps ot the merge block */
2424 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2426 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2429 /* Now enter the merge block */
2430 func->curblock = merge;
2433 /* we create the if here, that way all blocks are ordered :)
2435 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2436 (ontrue ? ontrue : merge),
2437 (onfalse ? onfalse : merge)))
2445 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2447 ast_expression_codegen *cgen;
2450 ir_value *trueval, *falseval;
2453 ir_block *cond = func->curblock;
2454 ir_block *cond_out = NULL;
2455 ir_block *ontrue, *ontrue_out = NULL;
2456 ir_block *onfalse, *onfalse_out = NULL;
2459 /* Ternary can never create an lvalue... */
2463 /* In theory it shouldn't be possible to pass through a node twice, but
2464 * in case we add any kind of optimization pass for the AST itself, it
2465 * may still happen, thus we remember a created ir_value and simply return one
2466 * if it already exists.
2468 if (self->expression.outr) {
2469 *out = self->expression.outr;
2473 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2475 /* generate the condition */
2476 func->curblock = cond;
2477 cgen = self->cond->codegen;
2478 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2480 cond_out = func->curblock;
2482 /* create on-true block */
2483 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2488 /* enter the block */
2489 func->curblock = ontrue;
2492 cgen = self->on_true->codegen;
2493 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2496 ontrue_out = func->curblock;
2499 /* create on-false block */
2500 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2505 /* enter the block */
2506 func->curblock = onfalse;
2509 cgen = self->on_false->codegen;
2510 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2513 onfalse_out = func->curblock;
2516 /* create merge block */
2517 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2520 /* jump to merge block */
2521 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2523 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2526 /* create if instruction */
2527 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2530 /* Now enter the merge block */
2531 func->curblock = merge;
2533 /* Here, now, we need a PHI node
2534 * but first some sanity checking...
2536 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2537 /* error("ternary with different types on the two sides"); */
2538 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2543 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2545 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2548 ir_phi_add(phi, ontrue_out, trueval);
2549 ir_phi_add(phi, onfalse_out, falseval);
2551 self->expression.outr = ir_phi_value(phi);
2552 *out = self->expression.outr;
2554 codegen_output_type(self, *out);
2559 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2561 ast_expression_codegen *cgen;
2563 ir_value *dummy = NULL;
2564 ir_value *precond = NULL;
2565 ir_value *postcond = NULL;
2567 /* Since we insert some jumps "late" so we have blocks
2568 * ordered "nicely", we need to keep track of the actual end-blocks
2569 * of expressions to add the jumps to.
2571 ir_block *bbody = NULL, *end_bbody = NULL;
2572 ir_block *bprecond = NULL, *end_bprecond = NULL;
2573 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2574 ir_block *bincrement = NULL, *end_bincrement = NULL;
2575 ir_block *bout = NULL, *bin = NULL;
2577 /* let's at least move the outgoing block to the end */
2580 /* 'break' and 'continue' need to be able to find the right blocks */
2581 ir_block *bcontinue = NULL;
2582 ir_block *bbreak = NULL;
2584 ir_block *tmpblock = NULL;
2589 if (self->expression.outr) {
2590 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2593 self->expression.outr = (ir_value*)1;
2596 * Should we ever need some kind of block ordering, better make this function
2597 * move blocks around than write a block ordering algorithm later... after all
2598 * the ast and ir should work together, not against each other.
2601 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2602 * anyway if for example it contains a ternary.
2606 cgen = self->initexpr->codegen;
2607 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2611 /* Store the block from which we enter this chaos */
2612 bin = func->curblock;
2614 /* The pre-loop condition needs its own block since we
2615 * need to be able to jump to the start of that expression.
2619 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2623 /* the pre-loop-condition the least important place to 'continue' at */
2624 bcontinue = bprecond;
2627 func->curblock = bprecond;
2630 cgen = self->precond->codegen;
2631 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2634 end_bprecond = func->curblock;
2636 bprecond = end_bprecond = NULL;
2639 /* Now the next blocks won't be ordered nicely, but we need to
2640 * generate them this early for 'break' and 'continue'.
2642 if (self->increment) {
2643 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2646 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2648 bincrement = end_bincrement = NULL;
2651 if (self->postcond) {
2652 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2655 bcontinue = bpostcond; /* postcond comes before the increment */
2657 bpostcond = end_bpostcond = NULL;
2660 bout_id = vec_size(func->ir_func->blocks);
2661 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2666 /* The loop body... */
2667 /* if (self->body) */
2669 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2674 func->curblock = bbody;
2676 vec_push(func->breakblocks, bbreak);
2678 vec_push(func->continueblocks, bcontinue);
2680 vec_push(func->continueblocks, bbody);
2684 cgen = self->body->codegen;
2685 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2689 end_bbody = func->curblock;
2690 vec_pop(func->breakblocks);
2691 vec_pop(func->continueblocks);
2694 /* post-loop-condition */
2698 func->curblock = bpostcond;
2701 cgen = self->postcond->codegen;
2702 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2705 end_bpostcond = func->curblock;
2708 /* The incrementor */
2709 if (self->increment)
2712 func->curblock = bincrement;
2715 cgen = self->increment->codegen;
2716 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2719 end_bincrement = func->curblock;
2722 /* In any case now, we continue from the outgoing block */
2723 func->curblock = bout;
2725 /* Now all blocks are in place */
2726 /* From 'bin' we jump to whatever comes first */
2727 if (bprecond) tmpblock = bprecond;
2728 else if (bbody) tmpblock = bbody;
2729 else if (bpostcond) tmpblock = bpostcond;
2730 else tmpblock = bout;
2731 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2737 ir_block *ontrue, *onfalse;
2738 if (bbody) ontrue = bbody;
2739 else if (bincrement) ontrue = bincrement;
2740 else if (bpostcond) ontrue = bpostcond;
2741 else ontrue = bprecond;
2743 if (self->pre_not) {
2748 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2755 if (bincrement) tmpblock = bincrement;
2756 else if (bpostcond) tmpblock = bpostcond;
2757 else if (bprecond) tmpblock = bprecond;
2758 else tmpblock = bbody;
2759 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2763 /* from increment */
2766 if (bpostcond) tmpblock = bpostcond;
2767 else if (bprecond) tmpblock = bprecond;
2768 else if (bbody) tmpblock = bbody;
2769 else tmpblock = bout;
2770 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2777 ir_block *ontrue, *onfalse;
2778 if (bprecond) ontrue = bprecond;
2779 else if (bbody) ontrue = bbody;
2780 else if (bincrement) ontrue = bincrement;
2781 else ontrue = bpostcond;
2783 if (self->post_not) {
2788 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2792 /* Move 'bout' to the end */
2793 vec_remove(func->ir_func->blocks, bout_id, 1);
2794 vec_push(func->ir_func->blocks, bout);
2799 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2806 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
2810 if (self->expression.outr) {
2811 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2814 self->expression.outr = (ir_value*)1;
2816 if (self->is_continue)
2817 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
2819 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
2822 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
2826 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
2831 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
2833 ast_expression_codegen *cgen;
2835 ast_switch_case *def_case = NULL;
2836 ir_block *def_bfall = NULL;
2837 ir_block *def_bfall_to = NULL;
2838 bool set_def_bfall_to = false;
2840 ir_value *dummy = NULL;
2841 ir_value *irop = NULL;
2842 ir_block *bout = NULL;
2843 ir_block *bfall = NULL;
2851 compile_error(ast_ctx(self), "switch expression is not an l-value");
2855 if (self->expression.outr) {
2856 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
2859 self->expression.outr = (ir_value*)1;
2864 cgen = self->operand->codegen;
2865 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
2868 if (!vec_size(self->cases))
2871 cmpinstr = type_eq_instr[irop->vtype];
2872 if (cmpinstr >= VINSTR_END) {
2873 ast_type_to_string(self->operand, typestr, sizeof(typestr));
2874 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
2878 bout_id = vec_size(func->ir_func->blocks);
2879 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
2883 /* setup the break block */
2884 vec_push(func->breakblocks, bout);
2886 /* Now create all cases */
2887 for (c = 0; c < vec_size(self->cases); ++c) {
2888 ir_value *cond, *val;
2889 ir_block *bcase, *bnot;
2892 ast_switch_case *swcase = &self->cases[c];
2894 if (swcase->value) {
2895 /* A regular case */
2896 /* generate the condition operand */
2897 cgen = swcase->value->codegen;
2898 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
2900 /* generate the condition */
2901 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
2905 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
2906 bnot_id = vec_size(func->ir_func->blocks);
2907 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
2908 if (!bcase || !bnot)
2910 if (set_def_bfall_to) {
2911 set_def_bfall_to = false;
2912 def_bfall_to = bcase;
2914 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
2917 /* Make the previous case-end fall through */
2918 if (bfall && !bfall->final) {
2919 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
2923 /* enter the case */
2924 func->curblock = bcase;
2925 cgen = swcase->code->codegen;
2926 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
2929 /* remember this block to fall through from */
2930 bfall = func->curblock;
2932 /* enter the else and move it down */
2933 func->curblock = bnot;
2934 vec_remove(func->ir_func->blocks, bnot_id, 1);
2935 vec_push(func->ir_func->blocks, bnot);
2937 /* The default case */
2938 /* Remember where to fall through from: */
2941 /* remember which case it was */
2943 /* And the next case will be remembered */
2944 set_def_bfall_to = true;
2948 /* Jump from the last bnot to bout */
2949 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
2951 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
2956 /* If there was a default case, put it down here */
2960 /* No need to create an extra block */
2961 bcase = func->curblock;
2963 /* Insert the fallthrough jump */
2964 if (def_bfall && !def_bfall->final) {
2965 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
2969 /* Now generate the default code */
2970 cgen = def_case->code->codegen;
2971 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
2974 /* see if we need to fall through */
2975 if (def_bfall_to && !func->curblock->final)
2977 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
2982 /* Jump from the last bnot to bout */
2983 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
2985 /* enter the outgoing block */
2986 func->curblock = bout;
2988 /* restore the break block */
2989 vec_pop(func->breakblocks);
2991 /* Move 'bout' to the end, it's nicer */
2992 vec_remove(func->ir_func->blocks, bout_id, 1);
2993 vec_push(func->ir_func->blocks, bout);
2998 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3003 if (self->undefined) {
3004 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3010 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3014 /* simply create a new block and jump to it */
3015 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3016 if (!self->irblock) {
3017 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3020 if (!func->curblock->final) {
3021 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3025 /* enter the new block */
3026 func->curblock = self->irblock;
3028 /* Generate all the leftover gotos */
3029 for (i = 0; i < vec_size(self->gotos); ++i) {
3030 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3037 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3041 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3045 if (self->target->irblock) {
3046 if (self->irblock_from) {
3047 /* we already tried once, this is the callback */
3048 self->irblock_from->final = false;
3049 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3050 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3056 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3057 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3064 /* the target has not yet been created...
3065 * close this block in a sneaky way:
3067 func->curblock->final = true;
3068 self->irblock_from = func->curblock;
3069 ast_label_register_goto(self->target, self);
3075 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3077 ast_expression_codegen *cgen;
3079 ir_instr *callinstr;
3082 ir_value *funval = NULL;
3084 /* return values are never lvalues */
3086 compile_error(ast_ctx(self), "not an l-value (function call)");
3090 if (self->expression.outr) {
3091 *out = self->expression.outr;
3095 cgen = self->func->codegen;
3096 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3104 for (i = 0; i < vec_size(self->params); ++i)
3107 ast_expression *expr = self->params[i];
3109 cgen = expr->codegen;
3110 if (!(*cgen)(expr, func, false, ¶m))
3114 vec_push(params, param);
3117 /* varargs counter */
3118 if (self->va_count) {
3120 ir_builder *builder = func->curblock->owner->owner;
3121 cgen = self->va_count->codegen;
3122 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3124 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3125 ir_builder_get_va_count(builder), va_count))
3131 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3132 ast_function_label(func, "call"),
3133 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3137 for (i = 0; i < vec_size(params); ++i) {
3138 ir_call_param(callinstr, params[i]);
3141 *out = ir_call_value(callinstr);
3142 self->expression.outr = *out;
3144 codegen_output_type(self, *out);