]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.cpp
destructor call order is important here
[xonotic/gmqcc.git] / ast.cpp
1 #include <new>
2
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include "gmqcc.h"
7 #include "ast.h"
8 #include "fold.h"
9 //#include "parser.h"
10
11 #include "algo.h"
12
13 /* Initialize main ast node aprts */
14 ast_node::ast_node(lex_ctx_t ctx, int node_type)
15     : m_context(ctx)
16     , m_node_type(node_type)
17     , m_keep_node(false)
18     , m_side_effects(false)
19 {
20 }
21
22 ast_node::~ast_node()
23 {
24 }
25
26 /* weight and side effects */
27 void ast_node::propagateSideEffects(ast_node *other) const
28 {
29     other->m_side_effects = m_side_effects;
30 }
31
32 /* General expression initialization */
33 ast_expression::ast_expression(lex_ctx_t ctx, int nodetype, qc_type type)
34     : ast_node(ctx, nodetype)
35     , m_vtype(type)
36 {
37     if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
38         m_flags |= AST_FLAG_BLOCK_COVERAGE;
39 }
40 ast_expression::ast_expression(lex_ctx_t ctx, int nodetype)
41     : ast_expression(ctx, nodetype, TYPE_VOID)
42 {}
43
44 ast_expression::~ast_expression()
45 {
46     if (m_next)
47         delete m_next;
48     if (m_varparam)
49         delete m_varparam;
50 }
51
52 ast_expression::ast_expression(ast_copy_type_t, const ast_expression &other)
53     : ast_expression(ast_copy_type, other.m_context, other)
54 {}
55
56 ast_expression::ast_expression(ast_copy_type_t, lex_ctx_t ctx, const ast_expression &other)
57     : ast_expression(ast_copy_type, TYPE_ast_expression, ctx, other)
58 {}
59
60 ast_expression::ast_expression(ast_copy_type_t, int nodetype, const ast_expression &other)
61     : ast_expression(ast_copy_type, nodetype, other.m_context, other)
62 {}
63
64 ast_expression::ast_expression(ast_copy_type_t, int nodetype, lex_ctx_t ctx, const ast_expression &other)
65     : ast_expression(ctx, nodetype)
66 {
67     m_vtype = other.m_vtype;
68     m_count = other.m_count;
69     m_flags = other.m_flags;
70     if (other.m_next)
71         m_next = new ast_expression(ast_copy_type, *other.m_next);
72     m_type_params.reserve(other.m_type_params.size());
73     for (auto &it : other.m_type_params)
74         m_type_params.emplace_back(new ast_value(ast_copy_type, *it));
75 }
76
77
78 ast_expression *ast_expression::shallowType(lex_ctx_t ctx, qc_type vtype) {
79     auto expr = new ast_expression(ctx, TYPE_ast_expression);
80     expr->m_vtype = vtype;
81     return expr;
82 }
83
84 void ast_expression::adoptType(const ast_expression &other)
85 {
86     m_vtype = other.m_vtype;
87     if (other.m_next)
88         m_next = new ast_expression(ast_copy_type, *other.m_next);
89     m_count = other.m_count;
90     m_flags = other.m_flags;
91     m_type_params.clear();
92     m_type_params.reserve(other.m_type_params.size());
93     for (auto &it : other.m_type_params)
94         m_type_params.emplace_back(new ast_value(ast_copy_type, *it));
95 }
96
97 bool ast_expression::compareType(const ast_expression &other) const
98 {
99     if (m_vtype == TYPE_NIL ||
100         other.m_vtype == TYPE_NIL)
101         return true;
102     if (m_vtype != other.m_vtype)
103         return false;
104     if (!m_next != !other.m_next)
105         return false;
106     if (m_type_params.size() != other.m_type_params.size())
107         return false;
108     if ((m_flags & AST_FLAG_TYPE_MASK) !=
109         (other.m_flags & AST_FLAG_TYPE_MASK) )
110     {
111         return false;
112     }
113     if (m_type_params.size()) {
114         size_t i;
115         for (i = 0; i < m_type_params.size(); ++i) {
116             if (!m_type_params[i]->compareType(*other.m_type_params[i]))
117                 return false;
118         }
119     }
120     if (m_next)
121         return m_next->compareType(*other.m_next);
122     return true;
123 }
124
125 bool ast_expression::codegen(ast_function*, bool, ir_value**) {
126     compile_error(m_context, "ast_expression::codegen called!");
127     abort();
128     return false;
129 }
130
131 ast_value::ast_value(ast_copy_type_t, const ast_value &other, const std::string &name)
132     : ast_value(ast_copy_type, static_cast<const ast_expression&>(other), name)
133 {
134     m_keep_node = true; // keep values, always
135     memset(&m_constval, 0, sizeof(m_constval));
136 }
137
138 ast_value::ast_value(ast_copy_type_t, const ast_value &other)
139     : ast_value(ast_copy_type, static_cast<const ast_expression&>(other), other.m_name)
140 {
141     m_keep_node = true; // keep values, always
142     memset(&m_constval, 0, sizeof(m_constval));
143 }
144
145 ast_value::ast_value(ast_copy_type_t, const ast_expression &other, const std::string &name)
146     : ast_expression(ast_copy_type, TYPE_ast_value, other)
147     , m_name(name)
148 {
149     m_keep_node = true; // keep values, always
150     memset(&m_constval, 0, sizeof(m_constval));
151 }
152
153 ast_value::ast_value(lex_ctx_t ctx, const std::string &name, qc_type t)
154     : ast_expression(ctx, TYPE_ast_value, t)
155     , m_name(name)
156 {
157     m_keep_node = true; // keep values, always
158     memset(&m_constval, 0, sizeof(m_constval));
159 }
160
161 ast_value::~ast_value()
162 {
163     if (m_argcounter)
164         mem_d((void*)m_argcounter);
165     if (m_hasvalue) {
166         switch (m_vtype)
167         {
168         case TYPE_STRING:
169             mem_d((void*)m_constval.vstring);
170             break;
171         case TYPE_FUNCTION:
172             // unlink us from the function node
173             m_constval.vfunc->m_function_type = nullptr;
174             break;
175         // NOTE: delete function? currently collected in
176         // the parser structure
177         default:
178             break;
179         }
180     }
181
182     // initlist imples an array which implies .next in the expression exists.
183     if (m_initlist.size() && m_next->m_vtype == TYPE_STRING) {
184         for (auto &it : m_initlist)
185             if (it.vstring)
186                 mem_d(it.vstring);
187     }
188 }
189
190 static size_t ast_type_to_string_impl(const ast_expression *e, char *buf, size_t bufsize, size_t pos)
191 {
192     const char *typestr;
193     size_t typelen;
194     size_t i;
195
196     if (!e) {
197         if (pos + 6 >= bufsize)
198             goto full;
199         util_strncpy(buf + pos, "(null)", 6);
200         return pos + 6;
201     }
202
203     if (pos + 1 >= bufsize)
204         goto full;
205
206     switch (e->m_vtype) {
207         case TYPE_VARIANT:
208             util_strncpy(buf + pos, "(variant)", 9);
209             return pos + 9;
210
211         case TYPE_FIELD:
212             buf[pos++] = '.';
213             return ast_type_to_string_impl(e->m_next, buf, bufsize, pos);
214
215         case TYPE_POINTER:
216             if (pos + 3 >= bufsize)
217                 goto full;
218             buf[pos++] = '*';
219             buf[pos++] = '(';
220             pos = ast_type_to_string_impl(e->m_next, buf, bufsize, pos);
221             if (pos + 1 >= bufsize)
222                 goto full;
223             buf[pos++] = ')';
224             return pos;
225
226         case TYPE_FUNCTION:
227             pos = ast_type_to_string_impl(e->m_next, buf, bufsize, pos);
228             if (pos + 2 >= bufsize)
229                 goto full;
230             if (e->m_type_params.empty()) {
231                 buf[pos++] = '(';
232                 buf[pos++] = ')';
233                 return pos;
234             }
235             buf[pos++] = '(';
236             pos = ast_type_to_string_impl(e->m_type_params[0].get(), buf, bufsize, pos);
237             for (i = 1; i < e->m_type_params.size(); ++i) {
238                 if (pos + 2 >= bufsize)
239                     goto full;
240                 buf[pos++] = ',';
241                 buf[pos++] = ' ';
242                 pos = ast_type_to_string_impl(e->m_type_params[i].get(), buf, bufsize, pos);
243             }
244             if (pos + 1 >= bufsize)
245                 goto full;
246             buf[pos++] = ')';
247             return pos;
248
249         case TYPE_ARRAY:
250             pos = ast_type_to_string_impl(e->m_next, buf, bufsize, pos);
251             if (pos + 1 >= bufsize)
252                 goto full;
253             buf[pos++] = '[';
254             pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->m_count);
255             if (pos + 1 >= bufsize)
256                 goto full;
257             buf[pos++] = ']';
258             return pos;
259
260         default:
261             typestr = type_name[e->m_vtype];
262             typelen = strlen(typestr);
263             if (pos + typelen >= bufsize)
264                 goto full;
265             util_strncpy(buf + pos, typestr, typelen);
266             return pos + typelen;
267     }
268
269 full:
270     buf[bufsize-3] = '.';
271     buf[bufsize-2] = '.';
272     buf[bufsize-1] = '.';
273     return bufsize;
274 }
275
276 void ast_type_to_string(const ast_expression *e, char *buf, size_t bufsize)
277 {
278     size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
279     buf[pos] = 0;
280 }
281
282 void ast_value::addParam(ast_value *p)
283 {
284     m_type_params.emplace_back(p);
285 }
286
287 ast_binary::ast_binary(lex_ctx_t ctx, int op,
288                        ast_expression* left, ast_expression* right)
289     : ast_expression(ctx, TYPE_ast_binary)
290     , m_op(op)
291     // m_left/m_right happen after the peephole step right below
292     , m_right_first(false)
293 {
294     if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
295         ast_unary      *unary  = ((ast_unary*)right);
296         ast_expression *normal = unary->m_operand;
297
298         /* make a-(-b) => a + b */
299         if (unary->m_op == VINSTR_NEG_F || unary->m_op == VINSTR_NEG_V) {
300             if (op == INSTR_SUB_F) {
301                 op = INSTR_ADD_F;
302                 right = normal;
303                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
304             } else if (op == INSTR_SUB_V) {
305                 op = INSTR_ADD_V;
306                 right = normal;
307                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
308             }
309         }
310     }
311
312     m_left = left;
313     m_right = right;
314
315     propagateSideEffects(left);
316     propagateSideEffects(right);
317
318     if (op >= INSTR_EQ_F && op <= INSTR_GT)
319         m_vtype = TYPE_FLOAT;
320     else if (op == INSTR_AND || op == INSTR_OR) {
321         if (OPTS_FLAG(PERL_LOGIC))
322             adoptType(*right);
323         else
324             m_vtype = TYPE_FLOAT;
325     }
326     else if (op == INSTR_BITAND || op == INSTR_BITOR)
327         m_vtype = TYPE_FLOAT;
328     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
329         m_vtype = TYPE_VECTOR;
330     else if (op == INSTR_MUL_V)
331         m_vtype = TYPE_FLOAT;
332     else
333         m_vtype = left->m_vtype;
334
335     // references all
336     m_refs = AST_REF_ALL;
337 }
338
339 ast_binary::~ast_binary()
340 {
341     if (m_refs & AST_REF_LEFT)  ast_unref(m_left);
342     if (m_refs & AST_REF_RIGHT) ast_unref(m_right);
343 }
344
345 ast_binstore::ast_binstore(lex_ctx_t ctx, int storop, int mathop,
346                            ast_expression* left, ast_expression* right)
347     : ast_expression(ctx, TYPE_ast_binstore)
348     , m_opstore(storop)
349     , m_opbin(mathop)
350     , m_dest(left)
351     , m_source(right)
352     , m_keep_dest(false)
353 {
354     m_side_effects = true;
355     adoptType(*left);
356 }
357
358 ast_binstore::~ast_binstore()
359 {
360     if (!m_keep_dest)
361         ast_unref(m_dest);
362     ast_unref(m_source);
363 }
364
365 ast_unary* ast_unary::make(lex_ctx_t ctx, int op, ast_expression *expr)
366 {
367     if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
368         ast_unary *prev = (ast_unary*)((ast_unary*)expr)->m_operand;
369
370         /* Handle for double negation */
371         if (((ast_unary*)expr)->m_op == op)
372             prev = (ast_unary*)((ast_unary*)expr)->m_operand;
373
374         if (ast_istype(prev, ast_unary)) {
375             ++opts_optimizationcount[OPTIM_PEEPHOLE];
376             return prev;
377         }
378     }
379
380     return new ast_unary(ctx, op, expr);
381 }
382
383 ast_unary::ast_unary(lex_ctx_t ctx, int op, ast_expression *expr)
384     : ast_expression(ctx, TYPE_ast_unary)
385     , m_op(op)
386     , m_operand(expr)
387 {
388     propagateSideEffects(expr);
389     if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
390         m_vtype = TYPE_FLOAT;
391     } else if (op == VINSTR_NEG_V) {
392         m_vtype = TYPE_VECTOR;
393     } else {
394         compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
395     }
396 }
397
398 ast_unary::~ast_unary()
399 {
400     if (m_operand)
401         ast_unref(m_operand);
402 }
403
404 ast_return::ast_return(lex_ctx_t ctx, ast_expression *expr)
405     : ast_expression(ctx, TYPE_ast_return)
406     , m_operand(expr)
407 {
408     if (expr)
409         propagateSideEffects(expr);
410 }
411
412 ast_return::~ast_return()
413 {
414     if (m_operand)
415         ast_unref(m_operand);
416 }
417
418 ast_entfield::ast_entfield(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
419     : ast_entfield(ctx, entity, field, field->m_next)
420 {
421     if (field->m_vtype != TYPE_FIELD)
422         compile_error(ctx, "ast_entfield with expression not of type field");
423 }
424
425 ast_entfield::ast_entfield(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
426     : ast_expression(ctx, TYPE_ast_entfield)
427     , m_entity(entity)
428     , m_field(field)
429 {
430     propagateSideEffects(m_entity);
431     propagateSideEffects(m_field);
432
433     if (!outtype) {
434         compile_error(ctx, "ast_entfield: field has no type");
435         m_vtype = TYPE_VOID;
436     }
437     else
438         adoptType(*outtype);
439 }
440
441 ast_entfield::~ast_entfield()
442 {
443     ast_unref(m_entity);
444     ast_unref(m_field);
445 }
446
447 ast_member *ast_member::make(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const std::string &name)
448 {
449     if (field >= 3) {
450         compile_error(ctx, "ast_member: invalid field (>=3): %u", field);
451         return nullptr;
452     }
453     if (owner->m_vtype != TYPE_VECTOR &&
454         owner->m_vtype != TYPE_FIELD)
455     {
456         compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->m_vtype]);
457         return nullptr;
458     }
459     return new ast_member(ctx, owner, field, name);
460 }
461
462 ast_member::ast_member(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const std::string &name)
463     : ast_expression(ctx, TYPE_ast_member)
464     , m_owner(owner)
465     , m_field(field)
466     , m_name(name)
467     , m_rvalue(false)
468 {
469     m_keep_node = true;
470
471     if (m_owner->m_vtype == TYPE_VECTOR) {
472         m_vtype = TYPE_FLOAT;
473         m_next  = nullptr;
474     } else {
475         m_vtype = TYPE_FIELD;
476         m_next = ast_expression::shallowType(ctx, TYPE_FLOAT);
477     }
478
479     propagateSideEffects(owner);
480 }
481
482 ast_member::~ast_member()
483 {
484     // The owner is always an ast_value, which has .keep_node=true,
485     // also: ast_members are usually deleted after the owner, thus
486     // this will cause invalid access
487         //ast_unref(self->m_owner);
488     // once we allow (expression).x to access a vector-member, we need
489     // to change this: preferably by creating an alternate ast node for this
490     // purpose that is not garbage-collected.
491 }
492
493 ast_array_index* ast_array_index::make(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
494 {
495     ast_expression *outtype = array->m_next;
496     if (!outtype) {
497         // field has no type
498         return nullptr;
499     }
500
501     return new ast_array_index(ctx, array, index);
502 }
503
504 ast_array_index::ast_array_index(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
505     : ast_expression(ctx, TYPE_ast_array_index)
506     , m_array(array)
507     , m_index(index)
508 {
509     propagateSideEffects(array);
510     propagateSideEffects(index);
511
512     ast_expression *outtype = m_array->m_next;
513     adoptType(*outtype);
514
515     if (array->m_vtype == TYPE_FIELD && outtype->m_vtype == TYPE_ARRAY) {
516         // FIXME: investigate - this is not possible after adoptType
517         //if (m_vtype != TYPE_ARRAY) {
518         //    compile_error(self->m_context, "array_index node on type");
519         //    ast_array_index_delete(self);
520         //    return nullptr;
521         //}
522
523         m_array = outtype;
524         m_vtype = TYPE_FIELD;
525     }
526 }
527
528 ast_array_index::~ast_array_index()
529 {
530     if (m_array)
531         ast_unref(m_array);
532     if (m_index)
533         ast_unref(m_index);
534 }
535
536 ast_argpipe::ast_argpipe(lex_ctx_t ctx, ast_expression *index)
537     : ast_expression(ctx, TYPE_ast_argpipe)
538     , m_index(index)
539 {
540     m_vtype = TYPE_NOEXPR;
541 }
542
543 ast_argpipe::~ast_argpipe()
544 {
545     if (m_index)
546         ast_unref(m_index);
547 }
548
549 ast_store::ast_store(lex_ctx_t ctx, int op, ast_expression *dest, ast_expression *source)
550     : ast_expression(ctx, TYPE_ast_store)
551     , m_op(op)
552     , m_dest(dest)
553     , m_source(source)
554 {
555     m_side_effects = true;
556     adoptType(*dest);
557 }
558
559 ast_store::~ast_store()
560 {
561     ast_unref(m_dest);
562     ast_unref(m_source);
563 }
564
565 ast_ifthen::ast_ifthen(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
566     : ast_expression(ctx, TYPE_ast_ifthen)
567     , m_cond(cond)
568     , m_on_true(ontrue)
569     , m_on_false(onfalse)
570 {
571     propagateSideEffects(cond);
572     if (ontrue)
573         propagateSideEffects(ontrue);
574     if (onfalse)
575         propagateSideEffects(onfalse);
576 }
577
578 ast_ifthen::~ast_ifthen()
579 {
580     ast_unref(m_cond);
581     if (m_on_true)
582         ast_unref(m_on_true);
583     if (m_on_false)
584         ast_unref(m_on_false);
585 }
586
587 ast_ternary::ast_ternary(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
588     : ast_expression(ctx, TYPE_ast_ternary)
589     , m_cond(cond)
590     , m_on_true(ontrue)
591     , m_on_false(onfalse)
592 {
593     propagateSideEffects(cond);
594     propagateSideEffects(ontrue);
595     propagateSideEffects(onfalse);
596
597     if (ontrue->m_vtype == TYPE_NIL)
598         adoptType(*onfalse);
599     else
600         adoptType(*ontrue);
601 }
602
603 ast_ternary::~ast_ternary()
604 {
605     /* the if()s are only there because computed-gotos can set them
606      * to nullptr
607      */
608     if (m_cond)     ast_unref(m_cond);
609     if (m_on_true)  ast_unref(m_on_true);
610     if (m_on_false) ast_unref(m_on_false);
611 }
612
613 ast_loop::ast_loop(lex_ctx_t ctx,
614                    ast_expression *initexpr,
615                    ast_expression *precond, bool pre_not,
616                    ast_expression *postcond, bool post_not,
617                    ast_expression *increment,
618                    ast_expression *body)
619     : ast_expression(ctx, TYPE_ast_loop)
620     , m_initexpr(initexpr)
621     , m_precond(precond)
622     , m_postcond(postcond)
623     , m_increment(increment)
624     , m_body(body)
625     , m_pre_not(pre_not)
626     , m_post_not(post_not)
627 {
628     if (initexpr)
629         propagateSideEffects(initexpr);
630     if (precond)
631         propagateSideEffects(precond);
632     if (postcond)
633         propagateSideEffects(postcond);
634     if (increment)
635         propagateSideEffects(increment);
636     if (body)
637         propagateSideEffects(body);
638 }
639
640 ast_loop::~ast_loop()
641 {
642     if (m_initexpr)
643         ast_unref(m_initexpr);
644     if (m_precond)
645         ast_unref(m_precond);
646     if (m_postcond)
647         ast_unref(m_postcond);
648     if (m_increment)
649         ast_unref(m_increment);
650     if (m_body)
651         ast_unref(m_body);
652 }
653
654 ast_breakcont::ast_breakcont(lex_ctx_t ctx, bool iscont, unsigned int levels)
655     : ast_expression(ctx, TYPE_ast_breakcont)
656     , m_is_continue(iscont)
657     , m_levels(levels)
658 {
659 }
660
661 ast_breakcont::~ast_breakcont()
662 {
663 }
664
665 ast_switch::ast_switch(lex_ctx_t ctx, ast_expression *op)
666     : ast_expression(ctx, TYPE_ast_switch)
667     , m_operand(op)
668 {
669     propagateSideEffects(op);
670 }
671
672 ast_switch::~ast_switch()
673 {
674     ast_unref(m_operand);
675
676     for (auto &it : m_cases) {
677         if (it.m_value)
678             ast_unref(it.m_value);
679         ast_unref(it.m_code);
680     }
681 }
682
683 ast_label::ast_label(lex_ctx_t ctx, const std::string &name, bool undefined)
684     : ast_expression(ctx, TYPE_ast_label)
685     , m_name(name)
686     , m_irblock(nullptr)
687     , m_undefined(undefined)
688 {
689     m_vtype = TYPE_NOEXPR;
690 }
691
692 ast_label::~ast_label()
693 {
694 }
695
696 void ast_label::registerGoto(ast_goto *g)
697 {
698    m_gotos.push_back(g);
699 }
700
701 ast_goto::ast_goto(lex_ctx_t ctx, const std::string &name)
702     : ast_expression(ctx, TYPE_ast_goto)
703     , m_name(name)
704     , m_target(nullptr)
705     , m_irblock_from(nullptr)
706 {
707 }
708
709 ast_goto::~ast_goto()
710 {
711 }
712
713 void ast_goto::setLabel(ast_label *label)
714 {
715     m_target = label;
716 }
717
718 ast_state::ast_state(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
719     : ast_expression(ctx, TYPE_ast_expression)
720     , m_framenum(frame)
721     , m_nextthink(think)
722 {
723 }
724
725 ast_state::~ast_state()
726 {
727     if (m_framenum)
728         ast_unref(m_framenum);
729     if (m_nextthink)
730         ast_unref(m_nextthink);
731 }
732
733 ast_call *ast_call::make(lex_ctx_t ctx, ast_expression *funcexpr)
734 {
735     if (!funcexpr->m_next) {
736         compile_error(ctx, "not a function");
737         return nullptr;
738     }
739     return new ast_call(ctx, funcexpr);
740 }
741
742 ast_call::ast_call(lex_ctx_t ctx, ast_expression *funcexpr)
743     : ast_expression(ctx, TYPE_ast_call)
744     , m_func(funcexpr)
745     , m_va_count(nullptr)
746 {
747     m_side_effects = true;
748     adoptType(*funcexpr->m_next);
749 }
750
751 ast_call::~ast_call()
752 {
753     for (auto &it : m_params)
754         ast_unref(it);
755
756     if (m_func)
757         ast_unref(m_func);
758
759     if (m_va_count)
760         ast_unref(m_va_count);
761 }
762
763 bool ast_call::checkVararg(ast_expression *va_type, ast_expression *exp_type) const
764 {
765     char texp[1024];
766     char tgot[1024];
767     if (!exp_type)
768         return true;
769     if (!va_type || !va_type->compareType(*exp_type))
770     {
771         if (va_type && exp_type)
772         {
773             ast_type_to_string(va_type,  tgot, sizeof(tgot));
774             ast_type_to_string(exp_type, texp, sizeof(texp));
775             if (OPTS_FLAG(UNSAFE_VARARGS)) {
776                 if (compile_warning(m_context, WARN_UNSAFE_TYPES,
777                                     "piped variadic argument differs in type: constrained to type %s, expected type %s",
778                                     tgot, texp))
779                     return false;
780             } else {
781                 compile_error(m_context,
782                               "piped variadic argument differs in type: constrained to type %s, expected type %s",
783                               tgot, texp);
784                 return false;
785             }
786         }
787         else
788         {
789             ast_type_to_string(exp_type, texp, sizeof(texp));
790             if (OPTS_FLAG(UNSAFE_VARARGS)) {
791                 if (compile_warning(m_context, WARN_UNSAFE_TYPES,
792                                     "piped variadic argument may differ in type: expected type %s",
793                                     texp))
794                     return false;
795             } else {
796                 compile_error(m_context,
797                               "piped variadic argument may differ in type: expected type %s",
798                               texp);
799                 return false;
800             }
801         }
802     }
803     return true;
804 }
805
806 bool ast_call::checkTypes(ast_expression *va_type) const
807 {
808     char texp[1024];
809     char tgot[1024];
810     size_t i;
811     bool retval = true;
812
813     size_t count = m_params.size();
814     if (count > m_func->m_type_params.size())
815         count = m_func->m_type_params.size();
816
817     for (i = 0; i < count; ++i) {
818         if (ast_istype(m_params[i], ast_argpipe)) {
819             /* warn about type safety instead */
820             if (i+1 != count) {
821                 compile_error(m_context, "argpipe must be the last parameter to a function call");
822                 return false;
823             }
824             if (!checkVararg(va_type, m_func->m_type_params[i].get()))
825                 retval = false;
826         }
827         else if (!m_params[i]->compareType(*m_func->m_type_params[i]))
828         {
829             ast_type_to_string(m_params[i], tgot, sizeof(tgot));
830             ast_type_to_string(m_func->m_type_params[i].get(), texp, sizeof(texp));
831             compile_error(m_context, "invalid type for parameter %u in function call: expected %s, got %s",
832                      (unsigned int)(i+1), texp, tgot);
833             /* we don't immediately return */
834             retval = false;
835         }
836     }
837     count = m_params.size();
838     if (count > m_func->m_type_params.size() && m_func->m_varparam) {
839         for (; i < count; ++i) {
840             if (ast_istype(m_params[i], ast_argpipe)) {
841                 /* warn about type safety instead */
842                 if (i+1 != count) {
843                     compile_error(m_context, "argpipe must be the last parameter to a function call");
844                     return false;
845                 }
846                 if (!checkVararg(va_type, m_func->m_varparam))
847                     retval = false;
848             }
849             else if (!m_params[i]->compareType(*m_func->m_varparam))
850             {
851                 ast_type_to_string(m_params[i], tgot, sizeof(tgot));
852                 ast_type_to_string(m_func->m_varparam, texp, sizeof(texp));
853                 compile_error(m_context, "invalid type for variadic parameter %u in function call: expected %s, got %s",
854                          (unsigned int)(i+1), texp, tgot);
855                 /* we don't immediately return */
856                 retval = false;
857             }
858         }
859     }
860     return retval;
861 }
862
863 ast_block::ast_block(lex_ctx_t ctx)
864     : ast_expression(ctx, TYPE_ast_block)
865 {
866 }
867
868 ast_block::~ast_block()
869 {
870     for (auto &it : m_exprs) ast_unref(it);
871     for (auto &it : m_locals) delete it;
872     for (auto &it : m_collect) delete it;
873 }
874
875 void ast_block::setType(const ast_expression &from)
876 {
877     if (m_next)
878         delete m_next;
879     adoptType(from);
880 }
881
882
883 bool ast_block::addExpr(ast_expression *e)
884 {
885     propagateSideEffects(e);
886     m_exprs.push_back(e);
887     if (m_next) {
888         delete m_next;
889         m_next = nullptr;
890     }
891     adoptType(*e);
892     return true;
893 }
894
895 void ast_block::collect(ast_expression *expr)
896 {
897     m_collect.push_back(expr);
898     expr->m_keep_node = true;
899 }
900
901 ast_function *ast_function::make(lex_ctx_t ctx, const std::string &name, ast_value *vtype)
902 {
903     if (!vtype) {
904         compile_error(ctx, "internal error: ast_function_new condition 0");
905         return nullptr;
906     } else if (vtype->m_hasvalue || vtype->m_vtype != TYPE_FUNCTION) {
907         compile_error(ctx, "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
908                  (int)!vtype,
909                  (int)vtype->m_hasvalue,
910                  vtype->m_vtype);
911         return nullptr;
912     }
913     return new ast_function(ctx, name, vtype);
914 }
915
916 ast_function::ast_function(lex_ctx_t ctx, const std::string &name, ast_value *vtype)
917     : ast_node(ctx, TYPE_ast_function)
918     , m_function_type(vtype)
919     , m_name(name)
920     , m_builtin(0)
921     , m_static_count(0)
922     , m_ir_func(nullptr)
923     , m_curblock(nullptr)
924     , m_labelcount(0)
925     , m_varargs(nullptr)
926     , m_argc(nullptr)
927     , m_fixedparams(nullptr)
928     , m_return_value(nullptr)
929 {
930     vtype->m_hasvalue = true;
931     vtype->m_constval.vfunc = this;
932 }
933
934 ast_function::~ast_function()
935 {
936     if (m_function_type) {
937         // ast_value_delete(m_function_type);
938         m_function_type->m_hasvalue = false;
939         m_function_type->m_constval.vfunc = nullptr;
940         // We use unref - if it was stored in a global table it is supposed
941         // to be deleted from *there*
942         ast_unref(m_function_type);
943     }
944
945     if (m_fixedparams)
946         ast_unref(m_fixedparams);
947     if (m_return_value)
948         ast_unref(m_return_value);
949
950     // force this to be cleared before m_varargs/m_argc as blocks might
951     // try to access them via ast_unref()
952     m_blocks.clear();
953 }
954
955 const char* ast_function::makeLabel(const char *prefix)
956 {
957     size_t id;
958     size_t len;
959     char  *from;
960
961     if (!OPTS_OPTION_BOOL(OPTION_DUMP)    &&
962         !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
963         !OPTS_OPTION_BOOL(OPTION_DEBUG))
964     {
965         return nullptr;
966     }
967
968     id  = (m_labelcount++);
969     len = strlen(prefix);
970
971     from = m_labelbuf + sizeof(m_labelbuf)-1;
972     *from-- = 0;
973     do {
974         *from-- = (id%10) + '0';
975         id /= 10;
976     } while (id);
977     ++from;
978     memcpy(from - len, prefix, len);
979     return from - len;
980 }
981
982 /*********************************************************************/
983 /* AST codegen part
984  * by convention you must never pass nullptr to the 'ir_value **out'
985  * parameter. If you really don't care about the output, pass a dummy.
986  * But I can't imagine a pituation where the output is truly unnecessary.
987  */
988
989 static void codegen_output_type(ast_expression *self, ir_value *out)
990 {
991     if (out->m_vtype == TYPE_FIELD)
992         out->m_fieldtype = self->m_next->m_vtype;
993     if (out->m_vtype == TYPE_FUNCTION)
994         out->m_outtype = self->m_next->m_vtype;
995 }
996
997 bool ast_value::codegen(ast_function *func, bool lvalue, ir_value **out)
998 {
999     (void)func;
1000     (void)lvalue;
1001     if (m_vtype == TYPE_NIL) {
1002         *out = func->m_ir_func->m_owner->m_nil;
1003         return true;
1004     }
1005     // NOTE: This is the codegen for a variable used in an expression.
1006     // It is not the codegen to generate the value storage. For this purpose,
1007     // generateLocal and generateGlobal are to be used before this
1008     // is executed. ast_function::generateFunction should take care of its
1009     // locals, and the ast-user should take care of generateGlobal to be used
1010     // on all the globals.
1011     if (!m_ir_v) {
1012         char tname[1024]; /* typename is reserved in C++ */
1013         ast_type_to_string(this, tname, sizeof(tname));
1014         compile_error(m_context, "ast_value used before generated %s %s", tname, m_name);
1015         return false;
1016     }
1017     *out = m_ir_v;
1018     return true;
1019 }
1020
1021 bool ast_value::setGlobalArray()
1022 {
1023     size_t count = m_initlist.size();
1024     size_t i;
1025
1026     if (count > m_count) {
1027         compile_error(m_context, "too many elements in initializer");
1028         count = m_count;
1029     }
1030     else if (count < m_count) {
1031         /* add this?
1032         compile_warning(m_context, "not all elements are initialized");
1033         */
1034     }
1035
1036     for (i = 0; i != count; ++i) {
1037         switch (m_next->m_vtype) {
1038             case TYPE_FLOAT:
1039                 if (!ir_value_set_float(m_ir_values[i], m_initlist[i].vfloat))
1040                     return false;
1041                 break;
1042             case TYPE_VECTOR:
1043                 if (!ir_value_set_vector(m_ir_values[i], m_initlist[i].vvec))
1044                     return false;
1045                 break;
1046             case TYPE_STRING:
1047                 if (!ir_value_set_string(m_ir_values[i], m_initlist[i].vstring))
1048                     return false;
1049                 break;
1050             case TYPE_ARRAY:
1051                 /* we don't support them in any other place yet either */
1052                 compile_error(m_context, "TODO: nested arrays");
1053                 return false;
1054             case TYPE_FUNCTION:
1055                 /* this requiers a bit more work - similar to the fields I suppose */
1056                 compile_error(m_context, "global of type function not properly generated");
1057                 return false;
1058             case TYPE_FIELD:
1059                 if (!m_initlist[i].vfield) {
1060                     compile_error(m_context, "field constant without vfield set");
1061                     return false;
1062                 }
1063                 if (!m_initlist[i].vfield->m_ir_v) {
1064                     compile_error(m_context, "field constant generated before its field");
1065                     return false;
1066                 }
1067                 if (!ir_value_set_field(m_ir_values[i], m_initlist[i].vfield->m_ir_v))
1068                     return false;
1069                 break;
1070             default:
1071                 compile_error(m_context, "TODO: global constant type %i", m_vtype);
1072                 break;
1073         }
1074     }
1075     return true;
1076 }
1077
1078 bool ast_value::checkArray(const ast_value &array) const
1079 {
1080     if (array.m_flags & AST_FLAG_ARRAY_INIT && array.m_initlist.empty()) {
1081         compile_error(m_context, "array without size: %s", m_name);
1082         return false;
1083     }
1084     // we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements
1085     if (!array.m_count || array.m_count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1086         compile_error(m_context, "Invalid array of size %lu", (unsigned long)array.m_count);
1087         return false;
1088     }
1089     return true;
1090 }
1091
1092 bool ast_value::generateGlobal(ir_builder *ir, bool isfield)
1093 {
1094     if (m_vtype == TYPE_NIL) {
1095         compile_error(m_context, "internal error: trying to generate a variable of TYPE_NIL");
1096         return false;
1097     }
1098
1099     if (m_hasvalue && m_vtype == TYPE_FUNCTION)
1100         return generateGlobalFunction(ir);
1101
1102     if (isfield && m_vtype == TYPE_FIELD)
1103         return generateGlobalField(ir);
1104
1105     ir_value *v = nullptr;
1106     if (m_vtype == TYPE_ARRAY) {
1107         v = prepareGlobalArray(ir);
1108         if (!v)
1109             return false;
1110     } else {
1111         // Arrays don't do this since there's no "array" value which spans across the
1112         // whole thing.
1113         v = ir_builder_create_global(ir, m_name, m_vtype);
1114         if (!v) {
1115             compile_error(m_context, "ir_builder_create_global failed on `%s`", m_name);
1116             return false;
1117         }
1118         codegen_output_type(this, v);
1119         v->m_context = m_context;
1120     }
1121
1122     /* link us to the ir_value */
1123     v->m_cvq = m_cvq;
1124     m_ir_v = v;
1125
1126     if (m_flags & AST_FLAG_INCLUDE_DEF)
1127         m_ir_v->m_flags |= IR_FLAG_INCLUDE_DEF;
1128     if (m_flags & AST_FLAG_ERASEABLE)
1129         m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1130
1131     /* initialize */
1132     if (m_hasvalue) {
1133         switch (m_vtype)
1134         {
1135             case TYPE_FLOAT:
1136                 if (!ir_value_set_float(v, m_constval.vfloat))
1137                     return false;
1138                 break;
1139             case TYPE_VECTOR:
1140                 if (!ir_value_set_vector(v, m_constval.vvec))
1141                     return false;
1142                 break;
1143             case TYPE_STRING:
1144                 if (!ir_value_set_string(v, m_constval.vstring))
1145                     return false;
1146                 break;
1147             case TYPE_ARRAY:
1148                 if (!setGlobalArray())
1149                     return false;
1150                 break;
1151             case TYPE_FUNCTION:
1152                 compile_error(m_context, "global of type function not properly generated");
1153                 return false;
1154                 /* Cannot generate an IR value for a function,
1155                  * need a pointer pointing to a function rather.
1156                  */
1157             case TYPE_FIELD:
1158                 if (!m_constval.vfield) {
1159                     compile_error(m_context, "field constant without vfield set");
1160                     return false;
1161                 }
1162                 if (!m_constval.vfield->m_ir_v) {
1163                     compile_error(m_context, "field constant generated before its field");
1164                     return false;
1165                 }
1166                 if (!ir_value_set_field(v, m_constval.vfield->m_ir_v))
1167                     return false;
1168                 break;
1169             default:
1170                 compile_error(m_context, "TODO: global constant type %i", m_vtype);
1171                 break;
1172         }
1173     }
1174
1175     return true;
1176 }
1177
1178 bool ast_value::generateGlobalFunction(ir_builder *ir)
1179 {
1180     ir_function *func = ir_builder_create_function(ir, m_name, m_next->m_vtype);
1181     if (!func)
1182         return false;
1183     func->m_context = m_context;
1184     func->m_value->m_context = m_context;
1185
1186     m_constval.vfunc->m_ir_func = func;
1187     m_ir_v = func->m_value;
1188     if (m_flags & AST_FLAG_INCLUDE_DEF)
1189         m_ir_v->m_flags |= IR_FLAG_INCLUDE_DEF;
1190     if (m_flags & AST_FLAG_ERASEABLE)
1191         m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1192     if (m_flags & AST_FLAG_BLOCK_COVERAGE)
1193         func->m_flags |= IR_FLAG_BLOCK_COVERAGE;
1194     // The function is filled later on ast_function::generateFunction...
1195     return true;
1196 }
1197
1198 bool ast_value::generateGlobalField(ir_builder *ir)
1199 {
1200     ast_expression *fieldtype = m_next;
1201
1202     if (m_hasvalue) {
1203         compile_error(m_context, "TODO: constant field pointers with value");
1204         return false;
1205     }
1206
1207     if (fieldtype->m_vtype == TYPE_ARRAY) {
1208         if (!ast_istype(fieldtype, ast_value)) {
1209             compile_error(m_context, "internal error: ast_value required");
1210             return false;
1211         }
1212         ast_value      *array = reinterpret_cast<ast_value*>(fieldtype);
1213
1214         if (!checkArray(*array))
1215             return false;
1216
1217         ast_expression *elemtype = array->m_next;
1218         qc_type vtype = elemtype->m_vtype;
1219
1220         ir_value *v = ir_builder_create_field(ir, m_name, vtype);
1221         if (!v) {
1222             compile_error(m_context, "ir_builder_create_global failed on `%s`", m_name);
1223             return false;
1224         }
1225         v->m_context = m_context;
1226         v->m_unique_life = true;
1227         v->m_locked      = true;
1228         array->m_ir_v = m_ir_v = v;
1229
1230         if (m_flags & AST_FLAG_INCLUDE_DEF)
1231             m_ir_v->m_flags |= IR_FLAG_INCLUDE_DEF;
1232         if (m_flags & AST_FLAG_ERASEABLE)
1233             m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1234
1235         const size_t namelen = m_name.length();
1236         std::unique_ptr<char[]> name(new char[namelen+16]);
1237         util_strncpy(name.get(), m_name.c_str(), namelen);
1238
1239         array->m_ir_values.resize(array->m_count);
1240         array->m_ir_values[0] = v;
1241         for (size_t ai = 1; ai < array->m_count; ++ai) {
1242             util_snprintf(name.get() + namelen, 16, "[%u]", (unsigned int)ai);
1243             array->m_ir_values[ai] = ir_builder_create_field(ir, name.get(), vtype);
1244             if (!array->m_ir_values[ai]) {
1245                 compile_error(m_context, "ir_builder_create_global failed on `%s`", name.get());
1246                 return false;
1247             }
1248             array->m_ir_values[ai]->m_context = m_context;
1249             array->m_ir_values[ai]->m_unique_life = true;
1250             array->m_ir_values[ai]->m_locked      = true;
1251             if (m_flags & AST_FLAG_INCLUDE_DEF)
1252                 m_ir_values[ai]->m_flags |= IR_FLAG_INCLUDE_DEF;
1253         }
1254     }
1255     else
1256     {
1257         ir_value *v = ir_builder_create_field(ir, m_name, m_next->m_vtype);
1258         if (!v)
1259             return false;
1260         v->m_context = m_context;
1261         m_ir_v = v;
1262         if (m_flags & AST_FLAG_INCLUDE_DEF)
1263             m_ir_v->m_flags |= IR_FLAG_INCLUDE_DEF;
1264
1265         if (m_flags & AST_FLAG_ERASEABLE)
1266             m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1267     }
1268     return true;
1269 }
1270
1271 ir_value *ast_value::prepareGlobalArray(ir_builder *ir)
1272 {
1273     ast_expression *elemtype = m_next;
1274     qc_type vtype = elemtype->m_vtype;
1275
1276     if (m_flags & AST_FLAG_ARRAY_INIT && !m_count) {
1277         compile_error(m_context, "array `%s' has no size", m_name);
1278         return nullptr;
1279     }
1280
1281     /* same as with field arrays */
1282     if (!checkArray(*this))
1283         return nullptr;
1284
1285     ir_value *v = ir_builder_create_global(ir, m_name, vtype);
1286     if (!v) {
1287         compile_error(m_context, "ir_builder_create_global failed `%s`", m_name);
1288         return nullptr;
1289     }
1290     v->m_context = m_context;
1291     v->m_unique_life = true;
1292     v->m_locked      = true;
1293
1294     if (m_flags & AST_FLAG_INCLUDE_DEF)
1295         v->m_flags |= IR_FLAG_INCLUDE_DEF;
1296     if (m_flags & AST_FLAG_ERASEABLE)
1297         m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1298
1299     const size_t namelen = m_name.length();
1300     std::unique_ptr<char[]> name(new char[namelen+16]);
1301     util_strncpy(name.get(), m_name.c_str(), namelen);
1302
1303     m_ir_values.resize(m_count);
1304     m_ir_values[0] = v;
1305     for (size_t ai = 1; ai < m_count; ++ai) {
1306         util_snprintf(name.get() + namelen, 16, "[%u]", (unsigned int)ai);
1307         m_ir_values[ai] = ir_builder_create_global(ir, name.get(), vtype);
1308         if (!m_ir_values[ai]) {
1309             compile_error(m_context, "ir_builder_create_global failed `%s`", name.get());
1310             return nullptr;
1311         }
1312         m_ir_values[ai]->m_context = m_context;
1313         m_ir_values[ai]->m_unique_life = true;
1314         m_ir_values[ai]->m_locked      = true;
1315         if (m_flags & AST_FLAG_INCLUDE_DEF)
1316             m_ir_values[ai]->m_flags |= IR_FLAG_INCLUDE_DEF;
1317     }
1318
1319     return v;
1320 }
1321
1322 bool ast_value::generateLocal(ir_function *func, bool param)
1323 {
1324     if (m_vtype == TYPE_NIL) {
1325         compile_error(m_context, "internal error: trying to generate a variable of TYPE_NIL");
1326         return false;
1327     }
1328
1329     if (m_hasvalue && m_vtype == TYPE_FUNCTION)
1330     {
1331         /* Do we allow local functions? I think not...
1332          * this is NOT a function pointer atm.
1333          */
1334         return false;
1335     }
1336
1337     ir_value *v = nullptr;
1338     if (m_vtype == TYPE_ARRAY) {
1339         ast_expression *elemtype = m_next;
1340         qc_type vtype = elemtype->m_vtype;
1341
1342         func->m_flags |= IR_FLAG_HAS_ARRAYS;
1343
1344         if (param && !(m_flags & AST_FLAG_IS_VARARG)) {
1345             compile_error(m_context, "array-parameters are not supported");
1346             return false;
1347         }
1348
1349         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1350         if (!checkArray(*this))
1351             return false;
1352
1353         m_ir_values.resize(m_count);
1354         v = ir_function_create_local(func, m_name, vtype, param);
1355         if (!v) {
1356             compile_error(m_context, "internal error: ir_function_create_local failed");
1357             return false;
1358         }
1359         v->m_context = m_context;
1360         v->m_unique_life = true;
1361         v->m_locked      = true;
1362
1363         const size_t namelen = m_name.length();
1364         std::unique_ptr<char[]> name(new char[namelen+16]);
1365         util_strncpy(name.get(), m_name.c_str(), namelen);
1366
1367         m_ir_values[0] = v;
1368         for (size_t ai = 1; ai < m_count; ++ai) {
1369             util_snprintf(name.get() + namelen, 16, "[%u]", (unsigned int)ai);
1370             m_ir_values[ai] = ir_function_create_local(func, name.get(), vtype, param);
1371             if (!m_ir_values[ai]) {
1372                 compile_error(m_context, "internal_error: ir_builder_create_global failed on `%s`", name.get());
1373                 return false;
1374             }
1375             m_ir_values[ai]->m_context = m_context;
1376             m_ir_values[ai]->m_unique_life = true;
1377             m_ir_values[ai]->m_locked      = true;
1378         }
1379     }
1380     else
1381     {
1382         v = ir_function_create_local(func, m_name, m_vtype, param);
1383         if (!v)
1384             return false;
1385         codegen_output_type(this, v);
1386         v->m_context = m_context;
1387     }
1388
1389     // A constant local... hmmm...
1390     // I suppose the IR will have to deal with this
1391     if (m_hasvalue) {
1392         switch (m_vtype)
1393         {
1394             case TYPE_FLOAT:
1395                 if (!ir_value_set_float(v, m_constval.vfloat))
1396                     goto error;
1397                 break;
1398             case TYPE_VECTOR:
1399                 if (!ir_value_set_vector(v, m_constval.vvec))
1400                     goto error;
1401                 break;
1402             case TYPE_STRING:
1403                 if (!ir_value_set_string(v, m_constval.vstring))
1404                     goto error;
1405                 break;
1406             default:
1407                 compile_error(m_context, "TODO: global constant type %i", m_vtype);
1408                 break;
1409         }
1410     }
1411
1412     // link us to the ir_value
1413     v->m_cvq = m_cvq;
1414     m_ir_v = v;
1415
1416     if (!generateAccessors(func->m_owner))
1417         return false;
1418     return true;
1419
1420 error: /* clean up */
1421     delete v;
1422     return false;
1423 }
1424
1425 bool ast_value::generateAccessors(ir_builder *ir)
1426 {
1427     size_t i;
1428     bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1429     if (!m_setter || !m_getter)
1430         return true;
1431     if (m_count && m_ir_values.empty()) {
1432         compile_error(m_context, "internal error: no array values generated for `%s`", m_name);
1433         return false;
1434     }
1435     for (i = 0; i < m_count; ++i) {
1436         if (!m_ir_values[i]) {
1437             compile_error(m_context, "internal error: not all array values have been generated for `%s`", m_name);
1438             return false;
1439         }
1440         if (!m_ir_values[i]->m_life.empty()) {
1441             compile_error(m_context, "internal error: function containing `%s` already generated", m_name);
1442             return false;
1443         }
1444     }
1445
1446     opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1447     if (m_setter) {
1448         if (!m_setter->generateGlobal(ir, false) ||
1449             !m_setter->m_constval.vfunc->generateFunction(ir) ||
1450             !ir_function_finalize(m_setter->m_constval.vfunc->m_ir_func))
1451         {
1452             compile_error(m_context, "internal error: failed to generate setter for `%s`", m_name);
1453             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1454             return false;
1455         }
1456     }
1457     if (m_getter) {
1458         if (!m_getter->generateGlobal(ir, false) ||
1459             !m_getter->m_constval.vfunc->generateFunction(ir) ||
1460             !ir_function_finalize(m_getter->m_constval.vfunc->m_ir_func))
1461         {
1462             compile_error(m_context, "internal error: failed to generate getter for `%s`", m_name);
1463             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1464             return false;
1465         }
1466     }
1467     for (i = 0; i < m_count; ++i)
1468         m_ir_values[i]->m_life.clear();
1469     opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1470     return true;
1471 }
1472
1473 bool ast_function::generateFunction(ir_builder *ir)
1474 {
1475     (void)ir;
1476
1477     ir_value *dummy;
1478
1479     ir_function *irf = m_ir_func;
1480     if (!irf) {
1481         compile_error(m_context, "internal error: ast_function's related ast_value was not generated yet");
1482         return false;
1483     }
1484
1485     /* fill the parameter list */
1486     for (auto &it : m_function_type->m_type_params) {
1487         if (it->m_vtype == TYPE_FIELD)
1488             vec_push(irf->m_params, it->m_next->m_vtype);
1489         else
1490             vec_push(irf->m_params, it->m_vtype);
1491         if (!m_builtin) {
1492             if (!it->generateLocal(m_ir_func, true))
1493                 return false;
1494         }
1495     }
1496
1497     if (m_varargs) {
1498         if (!m_varargs->generateLocal(m_ir_func, true))
1499             return false;
1500         irf->m_max_varargs = m_varargs->m_count;
1501     }
1502
1503     if (m_builtin) {
1504         irf->m_builtin = m_builtin;
1505         return true;
1506     }
1507
1508     /* have a local return value variable? */
1509     if (m_return_value) {
1510         if (!m_return_value->generateLocal(m_ir_func, false))
1511             return false;
1512     }
1513
1514     if (m_blocks.empty()) {
1515         compile_error(m_context, "function `%s` has no body", m_name);
1516         return false;
1517     }
1518
1519     irf->m_first = m_curblock = ir_function_create_block(m_context, irf, "entry");
1520     if (!m_curblock) {
1521         compile_error(m_context, "failed to allocate entry block for `%s`", m_name);
1522         return false;
1523     }
1524
1525     if (m_argc) {
1526         ir_value *va_count;
1527         ir_value *fixed;
1528         ir_value *sub;
1529         if (!m_argc->generateLocal(m_ir_func, true))
1530             return false;
1531         if (!m_argc->codegen(this, false, &va_count))
1532             return false;
1533         if (!m_fixedparams->codegen(this, false, &fixed))
1534             return false;
1535         sub = ir_block_create_binop(m_curblock, m_context,
1536                                     makeLabel("va_count"), INSTR_SUB_F,
1537                                     ir_builder_get_va_count(ir), fixed);
1538         if (!sub)
1539             return false;
1540         if (!ir_block_create_store_op(m_curblock, m_context, INSTR_STORE_F,
1541                                       va_count, sub))
1542         {
1543             return false;
1544         }
1545     }
1546
1547     for (auto &it : m_blocks) {
1548         if (!it->codegen(this, false, &dummy))
1549           return false;
1550     }
1551
1552     /* TODO: check return types */
1553     if (!m_curblock->m_final)
1554     {
1555         if (!m_function_type->m_next ||
1556             m_function_type->m_next->m_vtype == TYPE_VOID)
1557         {
1558             return ir_block_create_return(m_curblock, m_context, nullptr);
1559         }
1560         else if (vec_size(m_curblock->m_entries) || m_curblock == irf->m_first)
1561         {
1562             if (m_return_value) {
1563                 if (!m_return_value->codegen(this, false, &dummy))
1564                     return false;
1565                 return ir_block_create_return(m_curblock, m_context, dummy);
1566             }
1567             else if (compile_warning(m_context, WARN_MISSING_RETURN_VALUES,
1568                                 "control reaches end of non-void function (`%s`) via %s",
1569                                 m_name.c_str(), m_curblock->m_label.c_str()))
1570             {
1571                 return false;
1572             }
1573             return ir_block_create_return(m_curblock, m_context, nullptr);
1574         }
1575     }
1576     return true;
1577 }
1578
1579 static bool starts_a_label(const ast_expression *ex)
1580 {
1581     while (ex && ast_istype(ex, ast_block)) {
1582         auto b = reinterpret_cast<const ast_block*>(ex);
1583         ex = b->m_exprs[0];
1584     }
1585     if (!ex)
1586         return false;
1587     return ast_istype(ex, ast_label);
1588 }
1589
1590 /* Note, you will not see ast_block_codegen generate ir_blocks.
1591  * To the AST and the IR, blocks are 2 different things.
1592  * In the AST it represents a block of code, usually enclosed in
1593  * curly braces {...}.
1594  * While in the IR it represents a block in terms of control-flow.
1595  */
1596 bool ast_block::codegen(ast_function *func, bool lvalue, ir_value **out)
1597 {
1598     /* We don't use this
1599      * Note: an ast-representation using the comma-operator
1600      * of the form: (a, b, c) = x should not assign to c...
1601      */
1602     if (lvalue) {
1603         compile_error(m_context, "not an l-value (code-block)");
1604         return false;
1605     }
1606
1607     if (m_outr) {
1608         *out = m_outr;
1609         return true;
1610     }
1611
1612     /* output is nullptr at first, we'll have each expression
1613      * assign to out output, thus, a comma-operator represention
1614      * using an ast_block will return the last generated value,
1615      * so: (b, c) + a  executed both b and c, and returns c,
1616      * which is then added to a.
1617      */
1618     *out = nullptr;
1619
1620     /* generate locals */
1621     for (auto &it : m_locals) {
1622         if (!it->generateLocal(func->m_ir_func, false)) {
1623             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1624                 compile_error(m_context, "failed to generate local `%s`", it->m_name);
1625             return false;
1626         }
1627     }
1628
1629     for (auto &it : m_exprs) {
1630         if (func->m_curblock->m_final && !starts_a_label(it)) {
1631             if (compile_warning(it->m_context, WARN_UNREACHABLE_CODE, "unreachable statement"))
1632                 return false;
1633             continue;
1634         }
1635         if (!it->codegen(func, false, out))
1636             return false;
1637     }
1638
1639     m_outr = *out;
1640
1641     return true;
1642 }
1643
1644 bool ast_store::codegen(ast_function *func, bool lvalue, ir_value **out)
1645 {
1646     ir_value *left  = nullptr;
1647     ir_value *right = nullptr;
1648
1649     ast_value       *idx = 0;
1650     ast_array_index *ai = nullptr;
1651
1652     if (lvalue && m_outl) {
1653         *out = m_outl;
1654         return true;
1655     }
1656
1657     if (!lvalue && m_outr) {
1658         *out = m_outr;
1659         return true;
1660     }
1661
1662     if (ast_istype(m_dest, ast_array_index))
1663     {
1664
1665         ai = (ast_array_index*)m_dest;
1666         idx = (ast_value*)ai->m_index;
1667
1668         if (ast_istype(ai->m_index, ast_value) && idx->m_hasvalue && idx->m_cvq == CV_CONST)
1669             ai = nullptr;
1670     }
1671
1672     if (ai) {
1673         /* we need to call the setter */
1674         ir_value  *iridx, *funval;
1675         ir_instr  *call;
1676
1677         if (lvalue) {
1678             compile_error(m_context, "array-subscript assignment cannot produce lvalues");
1679             return false;
1680         }
1681
1682         auto arr = reinterpret_cast<ast_value*>(ai->m_array);
1683         if (!ast_istype(ai->m_array, ast_value) || !arr->m_setter) {
1684             compile_error(m_context, "value has no setter (%s)", arr->m_name);
1685             return false;
1686         }
1687
1688         if (!idx->codegen(func, false, &iridx))
1689             return false;
1690
1691         if (!arr->m_setter->codegen(func, true, &funval))
1692             return false;
1693
1694         if (!m_source->codegen(func, false, &right))
1695             return false;
1696
1697         call = ir_block_create_call(func->m_curblock, m_context, func->makeLabel("store"), funval, false);
1698         if (!call)
1699             return false;
1700         ir_call_param(call, iridx);
1701         ir_call_param(call, right);
1702         m_outr = right;
1703     }
1704     else
1705     {
1706         // regular code
1707
1708         // lvalue!
1709         if (!m_dest->codegen(func, true, &left))
1710             return false;
1711         m_outl = left;
1712
1713         /* rvalue! */
1714         if (!m_source->codegen(func, false, &right))
1715             return false;
1716
1717         if (!ir_block_create_store_op(func->m_curblock, m_context, m_op, left, right))
1718             return false;
1719         m_outr = right;
1720     }
1721
1722     /* Theoretically, an assinment returns its left side as an
1723      * lvalue, if we don't need an lvalue though, we return
1724      * the right side as an rvalue, otherwise we have to
1725      * somehow know whether or not we need to dereference the pointer
1726      * on the left side - that is: OP_LOAD if it was an address.
1727      * Also: in original QC we cannot OP_LOADP *anyway*.
1728      */
1729     *out = (lvalue ? left : right);
1730
1731     return true;
1732 }
1733
1734 bool ast_binary::codegen(ast_function *func, bool lvalue, ir_value **out)
1735 {
1736     ir_value *left, *right;
1737
1738     /* A binary operation cannot yield an l-value */
1739     if (lvalue) {
1740         compile_error(m_context, "not an l-value (binop)");
1741         return false;
1742     }
1743
1744     if (m_outr) {
1745         *out = m_outr;
1746         return true;
1747     }
1748
1749     if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
1750         (m_op == INSTR_AND || m_op == INSTR_OR))
1751     {
1752         /* NOTE: The short-logic path will ignore right_first */
1753
1754         /* short circuit evaluation */
1755         ir_block *other, *merge;
1756         ir_block *from_left, *from_right;
1757         ir_instr *phi;
1758         size_t    merge_id;
1759
1760         /* prepare end-block */
1761         merge_id = func->m_ir_func->m_blocks.size();
1762         merge    = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("sce_merge"));
1763
1764         /* generate the left expression */
1765         if (!m_left->codegen(func, false, &left))
1766             return false;
1767         /* remember the block */
1768         from_left = func->m_curblock;
1769
1770         /* create a new block for the right expression */
1771         other = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("sce_other"));
1772         if (m_op == INSTR_AND) {
1773             /* on AND: left==true -> other */
1774             if (!ir_block_create_if(func->m_curblock, m_context, left, other, merge))
1775                 return false;
1776         } else {
1777             /* on OR: left==false -> other */
1778             if (!ir_block_create_if(func->m_curblock, m_context, left, merge, other))
1779                 return false;
1780         }
1781         /* use the likely flag */
1782         vec_last(func->m_curblock->m_instr)->m_likely = true;
1783
1784         /* enter the right-expression's block */
1785         func->m_curblock = other;
1786         /* generate */
1787         if (!m_right->codegen(func, false, &right))
1788             return false;
1789         /* remember block */
1790         from_right = func->m_curblock;
1791
1792         /* jump to the merge block */
1793         if (!ir_block_create_jump(func->m_curblock, m_context, merge))
1794             return false;
1795
1796         algo::shiftback(func->m_ir_func->m_blocks.begin() + merge_id,
1797                         func->m_ir_func->m_blocks.end());
1798         // FIXME::DELME::
1799         //func->m_ir_func->m_blocks[merge_id].release();
1800         //func->m_ir_func->m_blocks.erase(func->m_ir_func->m_blocks.begin() + merge_id);
1801         //func->m_ir_func->m_blocks.emplace_back(merge);
1802
1803         func->m_curblock = merge;
1804         phi = ir_block_create_phi(func->m_curblock, m_context,
1805                                   func->makeLabel("sce_value"),
1806                                   m_vtype);
1807         ir_phi_add(phi, from_left, left);
1808         ir_phi_add(phi, from_right, right);
1809         *out = ir_phi_value(phi);
1810         if (!*out)
1811             return false;
1812
1813         if (!OPTS_FLAG(PERL_LOGIC)) {
1814             /* cast-to-bool */
1815             if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->m_vtype == TYPE_VECTOR) {
1816                 *out = ir_block_create_unary(func->m_curblock, m_context,
1817                                              func->makeLabel("sce_bool_v"),
1818                                              INSTR_NOT_V, *out);
1819                 if (!*out)
1820                     return false;
1821                 *out = ir_block_create_unary(func->m_curblock, m_context,
1822                                              func->makeLabel("sce_bool"),
1823                                              INSTR_NOT_F, *out);
1824                 if (!*out)
1825                     return false;
1826             }
1827             else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->m_vtype == TYPE_STRING) {
1828                 *out = ir_block_create_unary(func->m_curblock, m_context,
1829                                              func->makeLabel("sce_bool_s"),
1830                                              INSTR_NOT_S, *out);
1831                 if (!*out)
1832                     return false;
1833                 *out = ir_block_create_unary(func->m_curblock, m_context,
1834                                              func->makeLabel("sce_bool"),
1835                                              INSTR_NOT_F, *out);
1836                 if (!*out)
1837                     return false;
1838             }
1839             else {
1840                 *out = ir_block_create_binop(func->m_curblock, m_context,
1841                                              func->makeLabel("sce_bool"),
1842                                              INSTR_AND, *out, *out);
1843                 if (!*out)
1844                     return false;
1845             }
1846         }
1847
1848         m_outr = *out;
1849         codegen_output_type(this, *out);
1850         return true;
1851     }
1852
1853     if (m_right_first) {
1854         if (!m_right->codegen(func, false, &right))
1855             return false;
1856         if (!m_left->codegen(func, false, &left))
1857             return false;
1858     } else {
1859         if (!m_left->codegen(func, false, &left))
1860             return false;
1861         if (!m_right->codegen(func, false, &right))
1862             return false;
1863     }
1864
1865     *out = ir_block_create_binop(func->m_curblock, m_context, func->makeLabel("bin"),
1866                                  m_op, left, right);
1867     if (!*out)
1868         return false;
1869     m_outr = *out;
1870     codegen_output_type(this, *out);
1871
1872     return true;
1873 }
1874
1875 bool ast_binstore::codegen(ast_function *func, bool lvalue, ir_value **out)
1876 {
1877     ir_value *leftl = nullptr, *leftr, *right, *bin;
1878
1879     ast_value       *arr;
1880     ast_value       *idx = 0;
1881     ast_array_index *ai = nullptr;
1882     ir_value        *iridx = nullptr;
1883
1884     if (lvalue && m_outl) {
1885         *out = m_outl;
1886         return true;
1887     }
1888
1889     if (!lvalue && m_outr) {
1890         *out = m_outr;
1891         return true;
1892     }
1893
1894     if (ast_istype(m_dest, ast_array_index))
1895     {
1896
1897         ai = (ast_array_index*)m_dest;
1898         idx = (ast_value*)ai->m_index;
1899
1900         if (ast_istype(ai->m_index, ast_value) && idx->m_hasvalue && idx->m_cvq == CV_CONST)
1901             ai = nullptr;
1902     }
1903
1904     /* for a binstore we need both an lvalue and an rvalue for the left side */
1905     /* rvalue of destination! */
1906     if (ai) {
1907         if (!idx->codegen(func, false, &iridx))
1908             return false;
1909     }
1910     if (!m_dest->codegen(func, false, &leftr))
1911         return false;
1912
1913     /* source as rvalue only */
1914     if (!m_source->codegen(func, false, &right))
1915         return false;
1916
1917     /* now the binary */
1918     bin = ir_block_create_binop(func->m_curblock, m_context, func->makeLabel("binst"),
1919                                 m_opbin, leftr, right);
1920     m_outr = bin;
1921
1922     if (ai) {
1923         /* we need to call the setter */
1924         ir_value  *funval;
1925         ir_instr  *call;
1926
1927         if (lvalue) {
1928             compile_error(m_context, "array-subscript assignment cannot produce lvalues");
1929             return false;
1930         }
1931
1932         arr = (ast_value*)ai->m_array;
1933         if (!ast_istype(ai->m_array, ast_value) || !arr->m_setter) {
1934             compile_error(m_context, "value has no setter (%s)", arr->m_name);
1935             return false;
1936         }
1937
1938         if (!arr->m_setter->codegen(func, true, &funval))
1939             return false;
1940
1941         call = ir_block_create_call(func->m_curblock, m_context, func->makeLabel("store"), funval, false);
1942         if (!call)
1943             return false;
1944         ir_call_param(call, iridx);
1945         ir_call_param(call, bin);
1946         m_outr = bin;
1947     } else {
1948         // now store them
1949         // lvalue of destination
1950         if (!m_dest->codegen(func, true, &leftl))
1951             return false;
1952         m_outl = leftl;
1953
1954         if (!ir_block_create_store_op(func->m_curblock, m_context, m_opstore, leftl, bin))
1955             return false;
1956         m_outr = bin;
1957     }
1958
1959     /* Theoretically, an assinment returns its left side as an
1960      * lvalue, if we don't need an lvalue though, we return
1961      * the right side as an rvalue, otherwise we have to
1962      * somehow know whether or not we need to dereference the pointer
1963      * on the left side - that is: OP_LOAD if it was an address.
1964      * Also: in original QC we cannot OP_LOADP *anyway*.
1965      */
1966     *out = (lvalue ? leftl : bin);
1967
1968     return true;
1969 }
1970
1971 bool ast_unary::codegen(ast_function *func, bool lvalue, ir_value **out)
1972 {
1973     ir_value *operand;
1974
1975     /* An unary operation cannot yield an l-value */
1976     if (lvalue) {
1977         compile_error(m_context, "not an l-value (binop)");
1978         return false;
1979     }
1980
1981     if (m_outr) {
1982         *out = m_outr;
1983         return true;
1984     }
1985
1986     /* lvalue! */
1987     if (!m_operand->codegen(func, false, &operand))
1988         return false;
1989
1990     *out = ir_block_create_unary(func->m_curblock, m_context, func->makeLabel("unary"),
1991                                  m_op, operand);
1992     if (!*out)
1993         return false;
1994     m_outr = *out;
1995
1996     return true;
1997 }
1998
1999 bool ast_return::codegen(ast_function *func, bool lvalue, ir_value **out)
2000 {
2001     ir_value *operand;
2002
2003     *out = nullptr;
2004
2005     /* In the context of a return operation, we don't actually return
2006      * anything...
2007      */
2008     if (lvalue) {
2009         compile_error(m_context, "return-expression is not an l-value");
2010         return false;
2011     }
2012
2013     if (m_outr) {
2014         compile_error(m_context, "internal error: ast_return cannot be reused, it bears no result!");
2015         return false;
2016     }
2017     m_outr = (ir_value*)1;
2018
2019     if (m_operand) {
2020         /* lvalue! */
2021         if (!m_operand->codegen(func, false, &operand))
2022             return false;
2023
2024         if (!ir_block_create_return(func->m_curblock, m_context, operand))
2025             return false;
2026     } else {
2027         if (!ir_block_create_return(func->m_curblock, m_context, nullptr))
2028             return false;
2029     }
2030
2031     return true;
2032 }
2033
2034 bool ast_entfield::codegen(ast_function *func, bool lvalue, ir_value **out)
2035 {
2036     ir_value *ent, *field;
2037
2038     // This function needs to take the 'lvalue' flag into account!
2039     // As lvalue we provide a field-pointer, as rvalue we provide the
2040     // value in a temp.
2041
2042     if (lvalue && m_outl) {
2043         *out = m_outl;
2044         return true;
2045     }
2046
2047     if (!lvalue && m_outr) {
2048         *out = m_outr;
2049         return true;
2050     }
2051
2052     if (!m_entity->codegen(func, false, &ent))
2053         return false;
2054
2055     if (!m_field->codegen(func, false, &field))
2056         return false;
2057
2058     if (lvalue) {
2059         /* address! */
2060         *out = ir_block_create_fieldaddress(func->m_curblock, m_context, func->makeLabel("efa"),
2061                                             ent, field);
2062     } else {
2063         *out = ir_block_create_load_from_ent(func->m_curblock, m_context, func->makeLabel("efv"),
2064                                              ent, field, m_vtype);
2065         /* Done AFTER error checking:
2066         codegen_output_type(this, *out);
2067         */
2068     }
2069     if (!*out) {
2070         compile_error(m_context, "failed to create %s instruction (output type %s)",
2071                  (lvalue ? "ADDRESS" : "FIELD"),
2072                  type_name[m_vtype]);
2073         return false;
2074     }
2075     if (!lvalue)
2076         codegen_output_type(this, *out);
2077
2078     if (lvalue)
2079         m_outl = *out;
2080     else
2081         m_outr = *out;
2082
2083     // Hm that should be it...
2084     return true;
2085 }
2086
2087 bool ast_member::codegen(ast_function *func, bool lvalue, ir_value **out)
2088 {
2089     ir_value *vec;
2090
2091     /* in QC this is always an lvalue */
2092     if (lvalue && m_rvalue) {
2093         compile_error(m_context, "not an l-value (member access)");
2094         return false;
2095     }
2096     if (m_outl) {
2097         *out = m_outl;
2098         return true;
2099     }
2100
2101     if (!m_owner->codegen(func, false, &vec))
2102         return false;
2103
2104     if (vec->m_vtype != TYPE_VECTOR &&
2105         !(vec->m_vtype == TYPE_FIELD && m_owner->m_next->m_vtype == TYPE_VECTOR))
2106     {
2107         return false;
2108     }
2109
2110     *out = ir_value_vector_member(vec, m_field);
2111     m_outl = *out;
2112
2113     return (*out != nullptr);
2114 }
2115
2116 bool ast_array_index::codegen(ast_function *func, bool lvalue, ir_value **out)
2117 {
2118     ast_value *arr;
2119     ast_value *idx;
2120
2121     if (!lvalue && m_outr) {
2122         *out = m_outr;
2123         return true;
2124     }
2125     if (lvalue && m_outl) {
2126         *out = m_outl;
2127         return true;
2128     }
2129
2130     if (!ast_istype(m_array, ast_value)) {
2131         compile_error(m_context, "array indexing this way is not supported");
2132         /* note this would actually be pointer indexing because the left side is
2133          * not an actual array but (hopefully) an indexable expression.
2134          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2135          * support this path will be filled.
2136          */
2137         return false;
2138     }
2139
2140     arr = reinterpret_cast<ast_value*>(m_array);
2141     idx = reinterpret_cast<ast_value*>(m_index);
2142
2143     if (!ast_istype(m_index, ast_value) || !idx->m_hasvalue || idx->m_cvq != CV_CONST) {
2144         /* Time to use accessor functions */
2145         ir_value               *iridx, *funval;
2146         ir_instr               *call;
2147
2148         if (lvalue) {
2149             compile_error(m_context, "(.2) array indexing here needs a compile-time constant");
2150             return false;
2151         }
2152
2153         if (!arr->m_getter) {
2154             compile_error(m_context, "value has no getter, don't know how to index it");
2155             return false;
2156         }
2157
2158         if (!m_index->codegen(func, false, &iridx))
2159             return false;
2160
2161         if (!arr->m_getter->codegen(func, true, &funval))
2162             return false;
2163
2164         call = ir_block_create_call(func->m_curblock, m_context, func->makeLabel("fetch"), funval, false);
2165         if (!call)
2166             return false;
2167         ir_call_param(call, iridx);
2168
2169         *out = ir_call_value(call);
2170         m_outr = *out;
2171         (*out)->m_vtype = m_vtype;
2172         codegen_output_type(this, *out);
2173         return true;
2174     }
2175
2176     if (idx->m_vtype == TYPE_FLOAT) {
2177         unsigned int arridx = idx->m_constval.vfloat;
2178         if (arridx >= m_array->m_count)
2179         {
2180             compile_error(m_context, "array index out of bounds: %i", arridx);
2181             return false;
2182         }
2183         *out = arr->m_ir_values[arridx];
2184     }
2185     else if (idx->m_vtype == TYPE_INTEGER) {
2186         unsigned int arridx = idx->m_constval.vint;
2187         if (arridx >= m_array->m_count)
2188         {
2189             compile_error(m_context, "array index out of bounds: %i", arridx);
2190             return false;
2191         }
2192         *out = arr->m_ir_values[arridx];
2193     }
2194     else {
2195         compile_error(m_context, "array indexing here needs an integer constant");
2196         return false;
2197     }
2198     (*out)->m_vtype = m_vtype;
2199     codegen_output_type(this, *out);
2200     return true;
2201 }
2202
2203 bool ast_argpipe::codegen(ast_function *func, bool lvalue, ir_value **out)
2204 {
2205     *out = nullptr;
2206     if (lvalue) {
2207         compile_error(m_context, "argpipe node: not an lvalue");
2208         return false;
2209     }
2210     (void)func;
2211     (void)out;
2212     compile_error(m_context, "TODO: argpipe codegen not implemented");
2213     return false;
2214 }
2215
2216 bool ast_ifthen::codegen(ast_function *func, bool lvalue, ir_value **out)
2217 {
2218     ir_value *condval;
2219     ir_value *dummy;
2220
2221     ir_block *cond;
2222     ir_block *ontrue;
2223     ir_block *onfalse;
2224     ir_block *ontrue_endblock = nullptr;
2225     ir_block *onfalse_endblock = nullptr;
2226     ir_block *merge = nullptr;
2227     int folded = 0;
2228
2229     /* We don't output any value, thus also don't care about r/lvalue */
2230     (void)out;
2231     (void)lvalue;
2232
2233     if (m_outr) {
2234         compile_error(m_context, "internal error: ast_ifthen cannot be reused, it bears no result!");
2235         return false;
2236     }
2237     m_outr = (ir_value*)1;
2238
2239     /* generate the condition */
2240     if (!m_cond->codegen(func, false, &condval))
2241         return false;
2242     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2243     cond = func->m_curblock;
2244
2245     /* try constant folding away the condition */
2246     if ((folded = fold::cond_ifthen(condval, func, this)) != -1)
2247         return folded;
2248
2249     if (m_on_true) {
2250         /* create on-true block */
2251         ontrue = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("ontrue"));
2252         if (!ontrue)
2253             return false;
2254
2255         /* enter the block */
2256         func->m_curblock = ontrue;
2257
2258         /* generate */
2259         if (!m_on_true->codegen(func, false, &dummy))
2260             return false;
2261
2262         /* we now need to work from the current endpoint */
2263         ontrue_endblock = func->m_curblock;
2264     } else
2265         ontrue = nullptr;
2266
2267     /* on-false path */
2268     if (m_on_false) {
2269         /* create on-false block */
2270         onfalse = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("onfalse"));
2271         if (!onfalse)
2272             return false;
2273
2274         /* enter the block */
2275         func->m_curblock = onfalse;
2276
2277         /* generate */
2278         if (!m_on_false->codegen(func, false, &dummy))
2279             return false;
2280
2281         /* we now need to work from the current endpoint */
2282         onfalse_endblock = func->m_curblock;
2283     } else
2284         onfalse = nullptr;
2285
2286     /* Merge block were they all merge in to */
2287     if (!ontrue || !onfalse || !ontrue_endblock->m_final || !onfalse_endblock->m_final)
2288     {
2289         merge = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("endif"));
2290         if (!merge)
2291             return false;
2292         /* add jumps ot the merge block */
2293         if (ontrue && !ontrue_endblock->m_final && !ir_block_create_jump(ontrue_endblock, m_context, merge))
2294             return false;
2295         if (onfalse && !onfalse_endblock->m_final && !ir_block_create_jump(onfalse_endblock, m_context, merge))
2296             return false;
2297
2298         /* Now enter the merge block */
2299         func->m_curblock = merge;
2300     }
2301
2302     /* we create the if here, that way all blocks are ordered :)
2303      */
2304     if (!ir_block_create_if(cond, m_context, condval,
2305                             (ontrue  ? ontrue  : merge),
2306                             (onfalse ? onfalse : merge)))
2307     {
2308         return false;
2309     }
2310
2311     return true;
2312 }
2313
2314 bool ast_ternary::codegen(ast_function *func, bool lvalue, ir_value **out)
2315 {
2316     ir_value *condval;
2317     ir_value *trueval, *falseval;
2318     ir_instr *phi;
2319
2320     ir_block *cond = func->m_curblock;
2321     ir_block *cond_out = nullptr;
2322     ir_block *ontrue, *ontrue_out = nullptr;
2323     ir_block *onfalse, *onfalse_out = nullptr;
2324     ir_block *merge;
2325     int folded = 0;
2326
2327     /* Ternary can never create an lvalue... */
2328     if (lvalue)
2329         return false;
2330
2331     /* In theory it shouldn't be possible to pass through a node twice, but
2332      * in case we add any kind of optimization pass for the AST itself, it
2333      * may still happen, thus we remember a created ir_value and simply return one
2334      * if it already exists.
2335      */
2336     if (m_outr) {
2337         *out = m_outr;
2338         return true;
2339     }
2340
2341     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2342
2343     /* generate the condition */
2344     func->m_curblock = cond;
2345     if (!m_cond->codegen(func, false, &condval))
2346         return false;
2347     cond_out = func->m_curblock;
2348
2349     /* try constant folding away the condition */
2350     if ((folded = fold::cond_ternary(condval, func, this)) != -1)
2351         return folded;
2352
2353     /* create on-true block */
2354     ontrue = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("tern_T"));
2355     if (!ontrue)
2356         return false;
2357     else
2358     {
2359         /* enter the block */
2360         func->m_curblock = ontrue;
2361
2362         /* generate */
2363         if (!m_on_true->codegen(func, false, &trueval))
2364             return false;
2365
2366         ontrue_out = func->m_curblock;
2367     }
2368
2369     /* create on-false block */
2370     onfalse = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("tern_F"));
2371     if (!onfalse)
2372         return false;
2373     else
2374     {
2375         /* enter the block */
2376         func->m_curblock = onfalse;
2377
2378         /* generate */
2379         if (!m_on_false->codegen(func, false, &falseval))
2380             return false;
2381
2382         onfalse_out = func->m_curblock;
2383     }
2384
2385     /* create merge block */
2386     merge = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("tern_out"));
2387     if (!merge)
2388         return false;
2389     /* jump to merge block */
2390     if (!ir_block_create_jump(ontrue_out, m_context, merge))
2391         return false;
2392     if (!ir_block_create_jump(onfalse_out, m_context, merge))
2393         return false;
2394
2395     /* create if instruction */
2396     if (!ir_block_create_if(cond_out, m_context, condval, ontrue, onfalse))
2397         return false;
2398
2399     /* Now enter the merge block */
2400     func->m_curblock = merge;
2401
2402     /* Here, now, we need a PHI node
2403      * but first some sanity checking...
2404      */
2405     if (trueval->m_vtype != falseval->m_vtype && trueval->m_vtype != TYPE_NIL && falseval->m_vtype != TYPE_NIL) {
2406         /* error("ternary with different types on the two sides"); */
2407         compile_error(m_context, "internal error: ternary operand types invalid");
2408         return false;
2409     }
2410
2411     /* create PHI */
2412     phi = ir_block_create_phi(merge, m_context, func->makeLabel("phi"), m_vtype);
2413     if (!phi) {
2414         compile_error(m_context, "internal error: failed to generate phi node");
2415         return false;
2416     }
2417     ir_phi_add(phi, ontrue_out,  trueval);
2418     ir_phi_add(phi, onfalse_out, falseval);
2419
2420     m_outr = ir_phi_value(phi);
2421     *out = m_outr;
2422
2423     codegen_output_type(this, *out);
2424
2425     return true;
2426 }
2427
2428 bool ast_loop::codegen(ast_function *func, bool lvalue, ir_value **out)
2429 {
2430     ir_value *dummy      = nullptr;
2431     ir_value *precond    = nullptr;
2432     ir_value *postcond   = nullptr;
2433
2434     /* Since we insert some jumps "late" so we have blocks
2435      * ordered "nicely", we need to keep track of the actual end-blocks
2436      * of expressions to add the jumps to.
2437      */
2438     ir_block *bbody      = nullptr, *end_bbody      = nullptr;
2439     ir_block *bprecond   = nullptr, *end_bprecond   = nullptr;
2440     ir_block *bpostcond  = nullptr, *end_bpostcond  = nullptr;
2441     ir_block *bincrement = nullptr, *end_bincrement = nullptr;
2442     ir_block *bout       = nullptr, *bin            = nullptr;
2443
2444     /* let's at least move the outgoing block to the end */
2445     size_t    bout_id;
2446
2447     /* 'break' and 'continue' need to be able to find the right blocks */
2448     ir_block *bcontinue     = nullptr;
2449     ir_block *bbreak        = nullptr;
2450
2451     ir_block *tmpblock      = nullptr;
2452
2453     (void)lvalue;
2454     (void)out;
2455
2456     if (m_outr) {
2457         compile_error(m_context, "internal error: ast_loop cannot be reused, it bears no result!");
2458         return false;
2459     }
2460     m_outr = (ir_value*)1;
2461
2462     /* NOTE:
2463      * Should we ever need some kind of block ordering, better make this function
2464      * move blocks around than write a block ordering algorithm later... after all
2465      * the ast and ir should work together, not against each other.
2466      */
2467
2468     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2469      * anyway if for example it contains a ternary.
2470      */
2471     if (m_initexpr)
2472     {
2473         if (!m_initexpr->codegen(func, false, &dummy))
2474             return false;
2475     }
2476
2477     /* Store the block from which we enter this chaos */
2478     bin = func->m_curblock;
2479
2480     /* The pre-loop condition needs its own block since we
2481      * need to be able to jump to the start of that expression.
2482      */
2483     if (m_precond)
2484     {
2485         bprecond = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("pre_loop_cond"));
2486         if (!bprecond)
2487             return false;
2488
2489         /* the pre-loop-condition the least important place to 'continue' at */
2490         bcontinue = bprecond;
2491
2492         /* enter */
2493         func->m_curblock = bprecond;
2494
2495         /* generate */
2496         if (!m_precond->codegen(func, false, &precond))
2497             return false;
2498
2499         end_bprecond = func->m_curblock;
2500     } else {
2501         bprecond = end_bprecond = nullptr;
2502     }
2503
2504     /* Now the next blocks won't be ordered nicely, but we need to
2505      * generate them this early for 'break' and 'continue'.
2506      */
2507     if (m_increment) {
2508         bincrement = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("loop_increment"));
2509         if (!bincrement)
2510             return false;
2511         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2512     } else {
2513         bincrement = end_bincrement = nullptr;
2514     }
2515
2516     if (m_postcond) {
2517         bpostcond = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("post_loop_cond"));
2518         if (!bpostcond)
2519             return false;
2520         bcontinue = bpostcond; /* postcond comes before the increment */
2521     } else {
2522         bpostcond = end_bpostcond = nullptr;
2523     }
2524
2525     bout_id = func->m_ir_func->m_blocks.size();
2526     bout = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("after_loop"));
2527     if (!bout)
2528         return false;
2529     bbreak = bout;
2530
2531     /* The loop body... */
2532     /* if (m_body) */
2533     {
2534         bbody = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("loop_body"));
2535         if (!bbody)
2536             return false;
2537
2538         /* enter */
2539         func->m_curblock = bbody;
2540
2541         func->m_breakblocks.push_back(bbreak);
2542         if (bcontinue)
2543             func->m_continueblocks.push_back(bcontinue);
2544         else
2545             func->m_continueblocks.push_back(bbody);
2546
2547         /* generate */
2548         if (m_body) {
2549             if (!m_body->codegen(func, false, &dummy))
2550                 return false;
2551         }
2552
2553         end_bbody = func->m_curblock;
2554         func->m_breakblocks.pop_back();
2555         func->m_continueblocks.pop_back();
2556     }
2557
2558     /* post-loop-condition */
2559     if (m_postcond)
2560     {
2561         /* enter */
2562         func->m_curblock = bpostcond;
2563
2564         /* generate */
2565         if (!m_postcond->codegen(func, false, &postcond))
2566             return false;
2567
2568         end_bpostcond = func->m_curblock;
2569     }
2570
2571     /* The incrementor */
2572     if (m_increment)
2573     {
2574         /* enter */
2575         func->m_curblock = bincrement;
2576
2577         /* generate */
2578         if (!m_increment->codegen(func, false, &dummy))
2579             return false;
2580
2581         end_bincrement = func->m_curblock;
2582     }
2583
2584     /* In any case now, we continue from the outgoing block */
2585     func->m_curblock = bout;
2586
2587     /* Now all blocks are in place */
2588     /* From 'bin' we jump to whatever comes first */
2589     if      (bprecond)   tmpblock = bprecond;
2590     else                 tmpblock = bbody;    /* can never be null */
2591
2592     /* DEAD CODE
2593     else if (bpostcond)  tmpblock = bpostcond;
2594     else                 tmpblock = bout;
2595     */
2596
2597     if (!ir_block_create_jump(bin, m_context, tmpblock))
2598         return false;
2599
2600     /* From precond */
2601     if (bprecond)
2602     {
2603         ir_block *ontrue, *onfalse;
2604         ontrue = bbody; /* can never be null */
2605
2606         /* all of this is dead code
2607         else if (bincrement) ontrue = bincrement;
2608         else                 ontrue = bpostcond;
2609         */
2610
2611         onfalse = bout;
2612         if (m_pre_not) {
2613             tmpblock = ontrue;
2614             ontrue   = onfalse;
2615             onfalse  = tmpblock;
2616         }
2617         if (!ir_block_create_if(end_bprecond, m_context, precond, ontrue, onfalse))
2618             return false;
2619     }
2620
2621     /* from body */
2622     if (bbody)
2623     {
2624         if      (bincrement) tmpblock = bincrement;
2625         else if (bpostcond)  tmpblock = bpostcond;
2626         else if (bprecond)   tmpblock = bprecond;
2627         else                 tmpblock = bbody;
2628         if (!end_bbody->m_final && !ir_block_create_jump(end_bbody, m_context, tmpblock))
2629             return false;
2630     }
2631
2632     /* from increment */
2633     if (bincrement)
2634     {
2635         if      (bpostcond)  tmpblock = bpostcond;
2636         else if (bprecond)   tmpblock = bprecond;
2637         else if (bbody)      tmpblock = bbody;
2638         else                 tmpblock = bout;
2639         if (!ir_block_create_jump(end_bincrement, m_context, tmpblock))
2640             return false;
2641     }
2642
2643     /* from postcond */
2644     if (bpostcond)
2645     {
2646         ir_block *ontrue, *onfalse;
2647         if      (bprecond)   ontrue = bprecond;
2648         else                 ontrue = bbody; /* can never be null */
2649
2650         /* all of this is dead code
2651         else if (bincrement) ontrue = bincrement;
2652         else                 ontrue = bpostcond;
2653         */
2654
2655         onfalse = bout;
2656         if (m_post_not) {
2657             tmpblock = ontrue;
2658             ontrue   = onfalse;
2659             onfalse  = tmpblock;
2660         }
2661         if (!ir_block_create_if(end_bpostcond, m_context, postcond, ontrue, onfalse))
2662             return false;
2663     }
2664
2665     /* Move 'bout' to the end */
2666     algo::shiftback(func->m_ir_func->m_blocks.begin() + bout_id,
2667                     func->m_ir_func->m_blocks.end());
2668     // FIXME::DELME::
2669     //func->m_ir_func->m_blocks[bout_id].release(); // it's a vector<std::unique_ptr<>>
2670     //func->m_ir_func->m_blocks.erase(func->m_ir_func->m_blocks.begin() + bout_id);
2671     //func->m_ir_func->m_blocks.emplace_back(bout);
2672
2673     return true;
2674 }
2675
2676 bool ast_breakcont::codegen(ast_function *func, bool lvalue, ir_value **out)
2677 {
2678     ir_block *target;
2679
2680     *out = nullptr;
2681
2682     if (lvalue) {
2683         compile_error(m_context, "break/continue expression is not an l-value");
2684         return false;
2685     }
2686
2687     if (m_outr) {
2688         compile_error(m_context, "internal error: ast_breakcont cannot be reused!");
2689         return false;
2690     }
2691     m_outr = (ir_value*)1;
2692
2693     if (m_is_continue)
2694         target = func->m_continueblocks[func->m_continueblocks.size()-1-m_levels];
2695     else
2696         target = func->m_breakblocks[func->m_breakblocks.size()-1-m_levels];
2697
2698     if (!target) {
2699         compile_error(m_context, "%s is lacking a target block", (m_is_continue ? "continue" : "break"));
2700         return false;
2701     }
2702
2703     if (!ir_block_create_jump(func->m_curblock, m_context, target))
2704         return false;
2705     return true;
2706 }
2707
2708 bool ast_switch::codegen(ast_function *func, bool lvalue, ir_value **out)
2709 {
2710     ast_switch_case *def_case     = nullptr;
2711     ir_block        *def_bfall    = nullptr;
2712     ir_block        *def_bfall_to = nullptr;
2713     bool set_def_bfall_to = false;
2714
2715     ir_value *dummy     = nullptr;
2716     ir_value *irop      = nullptr;
2717     ir_block *bout      = nullptr;
2718     ir_block *bfall     = nullptr;
2719     size_t    bout_id;
2720
2721     char      typestr[1024];
2722     uint16_t  cmpinstr;
2723
2724     if (lvalue) {
2725         compile_error(m_context, "switch expression is not an l-value");
2726         return false;
2727     }
2728
2729     if (m_outr) {
2730         compile_error(m_context, "internal error: ast_switch cannot be reused!");
2731         return false;
2732     }
2733     m_outr = (ir_value*)1;
2734
2735     (void)lvalue;
2736     (void)out;
2737
2738     if (!m_operand->codegen(func, false, &irop))
2739         return false;
2740
2741     if (m_cases.empty())
2742         return true;
2743
2744     cmpinstr = type_eq_instr[irop->m_vtype];
2745     if (cmpinstr >= VINSTR_END) {
2746         ast_type_to_string(m_operand, typestr, sizeof(typestr));
2747         compile_error(m_context, "invalid type to perform a switch on: %s", typestr);
2748         return false;
2749     }
2750
2751     bout_id = func->m_ir_func->m_blocks.size();
2752     bout = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("after_switch"));
2753     if (!bout)
2754         return false;
2755
2756     /* setup the break block */
2757     func->m_breakblocks.push_back(bout);
2758
2759     /* Now create all cases */
2760     for (auto &it : m_cases) {
2761         ir_value *cond, *val;
2762         ir_block *bcase, *bnot;
2763         size_t bnot_id;
2764
2765         ast_switch_case *swcase = &it;
2766
2767         if (swcase->m_value) {
2768             /* A regular case */
2769             /* generate the condition operand */
2770             if (!swcase->m_value->codegen(func, false, &val))
2771                 return false;
2772             /* generate the condition */
2773             cond = ir_block_create_binop(func->m_curblock, m_context, func->makeLabel("switch_eq"), cmpinstr, irop, val);
2774             if (!cond)
2775                 return false;
2776
2777             bcase = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("case"));
2778             bnot_id = func->m_ir_func->m_blocks.size();
2779             bnot = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("not_case"));
2780             if (!bcase || !bnot)
2781                 return false;
2782             if (set_def_bfall_to) {
2783                 set_def_bfall_to = false;
2784                 def_bfall_to = bcase;
2785             }
2786             if (!ir_block_create_if(func->m_curblock, m_context, cond, bcase, bnot))
2787                 return false;
2788
2789             /* Make the previous case-end fall through */
2790             if (bfall && !bfall->m_final) {
2791                 if (!ir_block_create_jump(bfall, m_context, bcase))
2792                     return false;
2793             }
2794
2795             /* enter the case */
2796             func->m_curblock = bcase;
2797             if (!swcase->m_code->codegen(func, false, &dummy))
2798                 return false;
2799
2800             /* remember this block to fall through from */
2801             bfall = func->m_curblock;
2802
2803             /* enter the else and move it down */
2804             func->m_curblock = bnot;
2805             algo::shiftback(func->m_ir_func->m_blocks.begin() + bnot_id,
2806                             func->m_ir_func->m_blocks.end());
2807             // FIXME::DELME::
2808             //func->m_ir_func->m_blocks[bnot_id].release();
2809             //func->m_ir_func->m_blocks.erase(func->m_ir_func->m_blocks.begin() + bnot_id);
2810             //func->m_ir_func->m_blocks.emplace_back(bnot);
2811         } else {
2812             /* The default case */
2813             /* Remember where to fall through from: */
2814             def_bfall = bfall;
2815             bfall     = nullptr;
2816             /* remember which case it was */
2817             def_case  = swcase;
2818             /* And the next case will be remembered */
2819             set_def_bfall_to = true;
2820         }
2821     }
2822
2823     /* Jump from the last bnot to bout */
2824     if (bfall && !bfall->m_final && !ir_block_create_jump(bfall, m_context, bout)) {
2825         /*
2826         astwarning(bfall->m_context, WARN_???, "missing break after last case");
2827         */
2828         return false;
2829     }
2830
2831     /* If there was a default case, put it down here */
2832     if (def_case) {
2833         ir_block *bcase;
2834
2835         /* No need to create an extra block */
2836         bcase = func->m_curblock;
2837
2838         /* Insert the fallthrough jump */
2839         if (def_bfall && !def_bfall->m_final) {
2840             if (!ir_block_create_jump(def_bfall, m_context, bcase))
2841                 return false;
2842         }
2843
2844         /* Now generate the default code */
2845         if (!def_case->m_code->codegen(func, false, &dummy))
2846             return false;
2847
2848         /* see if we need to fall through */
2849         if (def_bfall_to && !func->m_curblock->m_final)
2850         {
2851             if (!ir_block_create_jump(func->m_curblock, m_context, def_bfall_to))
2852                 return false;
2853         }
2854     }
2855
2856     /* Jump from the last bnot to bout */
2857     if (!func->m_curblock->m_final && !ir_block_create_jump(func->m_curblock, m_context, bout))
2858         return false;
2859     /* enter the outgoing block */
2860     func->m_curblock = bout;
2861
2862     /* restore the break block */
2863     func->m_breakblocks.pop_back();
2864
2865     /* Move 'bout' to the end, it's nicer */
2866     algo::shiftback(func->m_ir_func->m_blocks.begin() + bout_id,
2867                     func->m_ir_func->m_blocks.end());
2868     // FIXME::DELME::
2869     //func->m_ir_func->m_blocks[bout_id].release();
2870     //func->m_ir_func->m_blocks.erase(func->m_ir_func->m_blocks.begin() + bout_id);
2871     //func->m_ir_func->m_blocks.emplace_back(bout);
2872
2873     return true;
2874 }
2875
2876 bool ast_label::codegen(ast_function *func, bool lvalue, ir_value **out)
2877 {
2878     ir_value *dummy;
2879
2880     if (m_undefined) {
2881         compile_error(m_context, "internal error: ast_label never defined");
2882         return false;
2883     }
2884
2885     *out = nullptr;
2886     if (lvalue) {
2887         compile_error(m_context, "internal error: ast_label cannot be an lvalue");
2888         return false;
2889     }
2890
2891     /* simply create a new block and jump to it */
2892     m_irblock = ir_function_create_block(m_context, func->m_ir_func, m_name.c_str());
2893     if (!m_irblock) {
2894         compile_error(m_context, "failed to allocate label block `%s`", m_name);
2895         return false;
2896     }
2897     if (!func->m_curblock->m_final) {
2898         if (!ir_block_create_jump(func->m_curblock, m_context, m_irblock))
2899             return false;
2900     }
2901
2902     /* enter the new block */
2903     func->m_curblock = m_irblock;
2904
2905     /* Generate all the leftover gotos */
2906     for (auto &it : m_gotos) {
2907         if (!it->codegen(func, false, &dummy))
2908             return false;
2909     }
2910
2911     return true;
2912 }
2913
2914 bool ast_goto::codegen(ast_function *func, bool lvalue, ir_value **out)
2915 {
2916     *out = nullptr;
2917     if (lvalue) {
2918         compile_error(m_context, "internal error: ast_goto cannot be an lvalue");
2919         return false;
2920     }
2921
2922     if (m_target->m_irblock) {
2923         if (m_irblock_from) {
2924             /* we already tried once, this is the callback */
2925             m_irblock_from->m_final = false;
2926             if (!ir_block_create_goto(m_irblock_from, m_context, m_target->m_irblock)) {
2927                 compile_error(m_context, "failed to generate goto to `%s`", m_name);
2928                 return false;
2929             }
2930         }
2931         else
2932         {
2933             if (!ir_block_create_goto(func->m_curblock, m_context, m_target->m_irblock)) {
2934                 compile_error(m_context, "failed to generate goto to `%s`", m_name);
2935                 return false;
2936             }
2937         }
2938     }
2939     else
2940     {
2941         /* the target has not yet been created...
2942          * close this block in a sneaky way:
2943          */
2944         func->m_curblock->m_final = true;
2945         m_irblock_from = func->m_curblock;
2946         m_target->registerGoto(this);
2947     }
2948
2949     return true;
2950 }
2951
2952 bool ast_state::codegen(ast_function *func, bool lvalue, ir_value **out)
2953 {
2954     ir_value *frameval, *thinkval;
2955
2956     if (lvalue) {
2957         compile_error(m_context, "not an l-value (state operation)");
2958         return false;
2959     }
2960     if (m_outr) {
2961         compile_error(m_context, "internal error: ast_state cannot be reused!");
2962         return false;
2963     }
2964     *out = nullptr;
2965
2966     if (!m_framenum->codegen(func, false, &frameval))
2967         return false;
2968     if (!frameval)
2969         return false;
2970
2971     if (!m_nextthink->codegen(func, false, &thinkval))
2972         return false;
2973     if (!frameval)
2974         return false;
2975
2976     if (!ir_block_create_state_op(func->m_curblock, m_context, frameval, thinkval)) {
2977         compile_error(m_context, "failed to create STATE instruction");
2978         return false;
2979     }
2980
2981     m_outr = (ir_value*)1;
2982     return true;
2983 }
2984
2985 bool ast_call::codegen(ast_function *func, bool lvalue, ir_value **out)
2986 {
2987     std::vector<ir_value*> params;
2988     ir_instr *callinstr;
2989
2990     ir_value *funval = nullptr;
2991
2992     /* return values are never lvalues */
2993     if (lvalue) {
2994         compile_error(m_context, "not an l-value (function call)");
2995         return false;
2996     }
2997
2998     if (m_outr) {
2999         *out = m_outr;
3000         return true;
3001     }
3002
3003     if (!m_func->codegen(func, false, &funval))
3004         return false;
3005     if (!funval)
3006         return false;
3007
3008     /* parameters */
3009     for (auto &it : m_params) {
3010         ir_value *param;
3011         if (!it->codegen(func, false, &param))
3012             return false;
3013         if (!param)
3014             return false;
3015         params.push_back(param);
3016     }
3017
3018     /* varargs counter */
3019     if (m_va_count) {
3020         ir_value   *va_count;
3021         ir_builder *builder = func->m_curblock->m_owner->m_owner;
3022         if (!m_va_count->codegen(func, false, &va_count))
3023             return false;
3024         if (!ir_block_create_store_op(func->m_curblock, m_context, INSTR_STORE_F,
3025                                       ir_builder_get_va_count(builder), va_count))
3026         {
3027             return false;
3028         }
3029     }
3030
3031     callinstr = ir_block_create_call(func->m_curblock, m_context,
3032                                      func->makeLabel("call"),
3033                                      funval, !!(m_func->m_flags & AST_FLAG_NORETURN));
3034     if (!callinstr)
3035         return false;
3036
3037     for (auto &it : params)
3038         ir_call_param(callinstr, it);
3039
3040     *out = ir_call_value(callinstr);
3041     m_outr = *out;
3042
3043     codegen_output_type(this, *out);
3044
3045     return true;
3046 }