navid/haze / 0a7dd3733e7f112437824753b751754396783304029099ce5b5bff5c75f10616 / src/codegen.cpp

codegen.cpp

← src · 58905 bytes · raw · download

#include "haze.h"

#include <cassert>
#include <cctype>
#include <sstream>
#include <utility>

namespace haze {

namespace {

constexpr size_t kObjectHeader = 8;

size_t slot_size(const TypePtr& t) {
    return qbe_type(t) == "l" ? 8 : 4;
}

size_t align_up(size_t n, size_t a) {
    return (n + a - 1) / a * a;
}

struct FieldLayout {
    size_t size = 0;
    std::vector<size_t> offsets;
};

FieldLayout layout_fields(const std::vector<Field>& fields, size_t start) {
    FieldLayout out;
    size_t at = start;
    for (auto& f : fields) {
        size_t sz = slot_size(f.type);
        at = align_up(at, sz);
        out.offsets.push_back(at);
        at += sz;
    }
    out.size = at;
    return out;
}

size_t sum_payload_size(const TypePtr& t) {
    size_t size = 8;
    for (auto& v : t->variants) {
        FieldLayout lay = layout_fields(v.fields, 8);
        if (lay.size > size)
            size = lay.size;
    }
    return align_up(size, 8);
}

struct Value {
    TypePtr ty;
    std::string s;
    bool valid = false;
};

struct Local {
    TypePtr ty;
    std::string slot;
    int root_index = -1;
};

struct LoopCtx {
    std::string break_label;
    std::string continue_label;
};

struct BlockOut {
    std::string label;
    std::vector<std::string> lines;
    bool terminated = false;
};

class Gen {
public:
    Gen(Program& p, std::string source_name) : program_(p), source_name_(std::move(source_name)) {
        for (auto& t : program_.types) {
            types_[t->name] = t;
            if (t->kind == Type::Kind::Sum)
                for (auto& v : t->variants)
                    ctors_[v.name] = CtorInfo{t, &v};
        }
        for (auto& fn : program_.functions) {
            FuncSig sig;
            sig.ret = fn->ret;
            for (auto& p : fn->params)
                sig.params.push_back(p.type);
            sigs_[fn->name] = std::move(sig);
            functions_by_name_[fn->name] = fn.get();
        }
        for (auto& g : program_.globals)
            globals_[g.name] = &g;
    }

    std::string run() {
        for (auto& fn : program_.functions) {
            if (!fn->type_params.empty())
                continue;
            gen_function(*fn);
        }

        std::ostringstream out;
        out << "# generated by haze from " << source_name_ << "\n\n";
        out << data_.str();
        out << funcs_.str();
        return out.str();
    }

private:
    struct CtorInfo {
        TypePtr sum;
        const Variant* variant;
    };

    Program& program_;
    std::string source_name_;
    SigMap sigs_;
    std::unordered_map<std::string, TypePtr> types_;
    std::unordered_map<std::string, CtorInfo> ctors_;
    std::unordered_map<std::string, Global*> globals_;
    std::unordered_map<std::string, Function*> functions_by_name_;
    std::unordered_map<std::string, std::string> closure_syms_;
    std::ostringstream data_;
    std::ostringstream funcs_;
    std::unordered_map<std::string, std::string> string_syms_;
    int string_counter_ = 0;
    int rootmap_counter_ = 0;

    Function* fn_ = nullptr;
    std::vector<BlockOut> blocks_;
    int cur_ = -1;
    int next_temp_ = 0;
    int next_slot_ = 0;
    int next_block_ = 0;
    std::vector<std::string> allocs_;
    std::vector<std::string> entry_;
    std::vector<std::unordered_map<std::string, Local>> scopes_;
    std::vector<LoopCtx> loops_;
    bool has_root_frame_ = false;
    std::string root_frame_;
    std::string root_slots_;
    std::string rootmap_sym_;
    std::string rootoffs_sym_;
    int root_count_ = 0;
    bool word_return_ = false;
    bool has_post_ = false;
    bool checking_post_ = false;
    std::unordered_map<std::string, std::string> post_slots_;

    std::string new_temp() {
        return "%t" + std::to_string(next_temp_++);
    }

    std::string new_label(const std::string& hint) {
        (void)hint;
        return "@bb" + std::to_string(next_block_++);
    }

    static std::string mangle(const std::string& name) {
        std::string out;
        for (char c : name) {
            unsigned char u = static_cast<unsigned char>(c);
            if (std::isalnum(u) || c == '_' || c == '.' || c == '$')
                out.push_back(c);
            else
                out += '_';
        }
        return out;
    }

    static std::string func_sym(const std::string& name) {
        return name == "main" ? "main" : "haze_" + mangle(name);
    }

    Value global_value(const Global& g) {
        const Expr& e = *g.expr;
        TypePtr ty = g.type ? g.type : e.ty;
        if (e.kind == Expr::Kind::Int)
            return Value{ty, std::to_string(e.ival), true};
        if (e.kind == Expr::Kind::Bool)
            return Value{ty, e.bval ? "1" : "0", true};
        if (e.kind == Expr::Kind::String)
            return Value{ty, "$" + intern_string(e.text), true};
        if (e.kind == Expr::Kind::Unary && e.op == "-" && e.lhs &&
            e.lhs->kind == Expr::Kind::Int)
            return Value{ty, std::to_string(-e.lhs->ival), true};
        throw Error(g.pos, "unsupported global initializer for '" + g.name + "'");
    }

    void scan_free_expr(const Expr& e, std::unordered_set<std::string> locals,
                        std::vector<Param>& captures, std::unordered_set<std::string>& seen) {
        auto add_var = [&](const std::string& name, Pos pos) {
            if (locals.count(name) || seen.count(name))
                return;
            Local* outer = lookup_local(name);
            if (!outer)
                return;
            seen.insert(name);
            Param p;
            p.name = name;
            p.type = outer->ty;
            p.pos = pos;
            captures.push_back(std::move(p));
        };

        switch (e.kind) {
        case Expr::Kind::Var:
            add_var(e.text, e.pos);
            break;
        case Expr::Kind::Unary:
            if (e.lhs)
                scan_free_expr(*e.lhs, locals, captures, seen);
            break;
        case Expr::Kind::Binary:
            if (e.lhs)
                scan_free_expr(*e.lhs, locals, captures, seen);
            if (e.rhs)
                scan_free_expr(*e.rhs, locals, captures, seen);
            break;
        case Expr::Kind::Call:
            if (e.lhs)
                scan_free_expr(*e.lhs, locals, captures, seen);
            for (auto& a : e.args)
                scan_free_expr(*a, locals, captures, seen);
            break;
        case Expr::Kind::If:
            if (e.cond)
                scan_free_expr(*e.cond, locals, captures, seen);
            if (e.then_e)
                scan_free_expr(*e.then_e, locals, captures, seen);
            if (e.else_e)
                scan_free_expr(*e.else_e, locals, captures, seen);
            break;
        case Expr::Kind::Match:
            if (e.lhs)
                scan_free_expr(*e.lhs, locals, captures, seen);
            for (auto& arm : e.arms) {
                auto arm_locals = locals;
                for (auto& b : arm.pat.binders)
                    if (b != "_")
                        arm_locals.insert(b);
                if (arm.body)
                    scan_free_expr(*arm.body, arm_locals, captures, seen);
            }
            break;
        case Expr::Kind::Block:
            if (e.block)
                scan_free_block(*e.block, locals, captures, seen);
            break;
        case Expr::Kind::List:
            for (auto& a : e.args)
                scan_free_expr(*a, locals, captures, seen);
            break;
        case Expr::Kind::RecordLit:
            for (auto& a : e.args)
                scan_free_expr(*a, locals, captures, seen);
            break;
        case Expr::Kind::Field:
            if (e.lhs)
                scan_free_expr(*e.lhs, locals, captures, seen);
            break;
        case Expr::Kind::Index:
            if (e.lhs)
                scan_free_expr(*e.lhs, locals, captures, seen);
            if (e.rhs)
                scan_free_expr(*e.rhs, locals, captures, seen);
            break;
        case Expr::Kind::Lambda: {
            auto inner = locals;
            for (auto& p : e.params)
                inner.insert(p.name);
            if (e.arrow)
                scan_free_expr(*e.arrow, inner, captures, seen);
            if (e.block)
                scan_free_block(*e.block, inner, captures, seen);
            break;
        }
        case Expr::Kind::Int:
        case Expr::Kind::Bool:
        case Expr::Kind::String:
        case Expr::Kind::Assign:
            break;
        }
    }

    void collect_captures(Function& lambda) {
        std::unordered_set<std::string> locals;
        for (auto& p : lambda.params)
            locals.insert(p.name);
        std::vector<Param> captures;
        std::unordered_set<std::string> seen;
        if (lambda.arrow)
            scan_free_expr(*lambda.arrow, locals, captures, seen);
        if (lambda.body)
            scan_free_block(*lambda.body, locals, captures, seen);
        lambda.captures = std::move(captures);
    }

    void scan_free_block(const Block& b, std::unordered_set<std::string> locals,
                         std::vector<Param>& captures, std::unordered_set<std::string>& seen) {
        auto block_locals = locals;
        for (auto& s : b.stmts)
            if (s->kind == Stmt::Kind::Let || s->kind == Stmt::Kind::Var)
                block_locals.insert(s->name);
        for (auto& s : b.stmts) {
            if (s->expr)
                scan_free_expr(*s->expr, block_locals, captures, seen);
            if (s->rhs)
                scan_free_expr(*s->rhs, block_locals, captures, seen);
            if (s->cond)
                scan_free_expr(*s->cond, block_locals, captures, seen);
            if (s->lo)
                scan_free_expr(*s->lo, block_locals, captures, seen);
            if (s->hi)
                scan_free_expr(*s->hi, block_locals, captures, seen);
            if (s->block)
                scan_free_block(*s->block, block_locals, captures, seen);
        }
    }

    void gen_thunk(const std::string& name, const std::string& thunk) {
        auto it = sigs_.find(name);
        if (it == sigs_.end())
            throw Error(Pos{}, "unknown function '" + name + "'");
        const FuncSig& sig = it->second;
        std::ostringstream f;
        f << "function";
        if (sig.ret && sig.ret->kind != Type::Kind::Void)
            f << " " << qbe_type(sig.ret);
        f << " $" << thunk << "(l %env";
        for (size_t i = 0; i < sig.params.size(); i++)
            f << ", " << qbe_type(sig.params[i]) << " %p" << i;
        f << ") {\n@start\n\t";
        if (sig.ret && sig.ret->kind != Type::Kind::Void)
            f << "%r =" << qbe_type(sig.ret) << " ";
        f << "call $" << func_sym(name) << "(";
        for (size_t i = 0; i < sig.params.size(); i++) {
            if (i)
                f << ", ";
            f << qbe_type(sig.params[i]) << " %p" << i;
        }
        f << ")\n";
        if (sig.ret && sig.ret->kind != Type::Kind::Void)
            f << "\tret %r\n";
        else
            f << "\tret\n";
        f << "}\n\n";
        funcs_ << f.str();
    }

    std::string closure_for_function(const std::string& name) {
        auto existing = closure_syms_.find(name);
        if (existing != closure_syms_.end())
            return existing->second;
        std::string closure = "haze_closure_" + mangle(name);
        std::string thunk = "haze_thunk_" + mangle(name);
        data_ << "data $" << closure << " = { l $" << thunk << " }\n\n";
        gen_thunk(name, thunk);
        closure_syms_[name] = closure;
        return closure;
    }

    void emit(const std::string& line) {
        assert(cur_ >= 0);
        blocks_[cur_].lines.push_back(line);
    }

    void emit_entry(const std::string& line) {
        entry_.push_back(line);
    }

    bool terminated() const {
        return cur_ >= 0 && blocks_[cur_].terminated;
    }

    void start_block(const std::string& label) {
        if (cur_ >= 0 && !blocks_[cur_].terminated) {
            emit("jmp " + label);
            blocks_[cur_].terminated = true;
        }
        BlockOut b;
        b.label = label;
        blocks_.push_back(std::move(b));
        cur_ = static_cast<int>(blocks_.size()) - 1;
    }

    void jump(const std::string& label) {
        emit("jmp " + label);
        blocks_[cur_].terminated = true;
    }

    void branch(const Value& cond, const std::string& t, const std::string& f) {
        emit("jnz " + cond.s + ", " + t + ", " + f);
        blocks_[cur_].terminated = true;
    }

    std::string alloc_slot(TypePtr ty) {
        std::string s = "%s" + std::to_string(next_slot_++);
        bool wide = qbe_type(ty) == "l";
        allocs_.push_back(s + " =l alloc" + (wide ? "8" : "4") + " " + (wide ? "8" : "4"));
        return s;
    }

    Value load_slot(const std::string& slot, TypePtr ty) {
        std::string t = new_temp();
        emit(t + " =" + qbe_type(ty) + " load" + (qbe_type(ty) == "l" ? "l" : "w") + " " + slot);
        return Value{ty, t, true};
    }

    Value alloc_object(size_t payload) {
        std::string t = new_temp();
        emit(t + " =l call $haze_alloc_slow(w " + std::to_string(payload) + ", w 0)");
        return Value{t_ptr(), t, true};
    }

    void store_at(const Value& base, size_t offset, Value v, const TypePtr& ty) {
        v = coerce(std::move(v), ty);
        std::string addr = new_temp();
        emit(addr + " =l add " + base.s + ", " + std::to_string(offset));
        emit("store" + store_suffix(ty) + " " + v.s + ", " + addr);
    }

    Value load_at(const Value& base, size_t offset, const TypePtr& ty) {
        std::string addr = new_temp();
        emit(addr + " =l add " + base.s + ", " + std::to_string(offset));
        std::string t = new_temp();
        emit(t + " =" + qbe_type(ty) + " load" + (qbe_type(ty) == "l" ? "l" : "w") + " " + addr);
        return Value{ty, t, true};
    }

    Value coerce(Value v, TypePtr to) {
        if (!v.valid || !to || same_type(v.ty, to))
            return v;
        if (to->kind == Type::Kind::I64 && v.ty && v.ty->kind == Type::Kind::I32) {
            std::string t = new_temp();
            emit(t + " =l extsw " + v.s);
            return Value{to, t, true};
        }
        return v;
    }

    std::string store_suffix(TypePtr ty) {
        return qbe_type(ty) == "l" ? "l" : "w";
    }

    void store_local(const Local& l, Value v) {
        v = coerce(v, l.ty);
        emit("store" + store_suffix(l.ty) + " " + v.s + ", " + l.slot);
        if (l.root_index >= 0)
            store_root(l.root_index, v);
    }

    void store_root(int index, const Value& v) {
        std::string addr = new_temp();
        emit(addr + " =l add " + root_slots_ + ", " + std::to_string(index * 8));
        emit("storel " + v.s + ", " + addr);
    }

    Local* lookup_local(const std::string& name) {
        for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {
            auto f = it->find(name);
            if (f != it->end())
                return &f->second;
        }
        return nullptr;
    }

    void push_scope() {
        scopes_.emplace_back();
    }
    void pop_scope() {
        scopes_.pop_back();
    }

    Local& declare_local(const std::string& name, TypePtr ty, Value init) {
        Local l;
        l.ty = ty;
        l.slot = alloc_slot(ty);
        if (is_managed(ty)) {
            if (root_count_ >= 64)
                throw Error(fn_->pos, "too many managed locals in function '" + fn_->name + "'");
            l.root_index = root_count_++;
        }
        scopes_.back()[name] = l;
        store_local(scopes_.back()[name], std::move(init));
        return scopes_.back()[name];
    }

    std::string intern_string(const std::string& s) {
        auto it = string_syms_.find(s);
        if (it != string_syms_.end())
            return it->second;
        std::string sym = "haze_str_" + std::to_string(string_counter_++);
        data_ << "data $" << sym << " = { b";
        if (s.empty()) {
            data_ << " 0";
        } else {
            for (unsigned char c : s)
                data_ << " " << static_cast<unsigned>(c);
            data_ << " 0";
        }
        data_ << " }\n\n";
        string_syms_[s] = sym;
        return sym;
    }

    void panic_block(const std::string& message) {
        std::string sym = intern_string(message);
        emit("call $haze_panic(l $" + sym + ")");
        emit("hlt");
        blocks_[cur_].terminated = true;
    }

    void gen_pre_checks() {
        if (program_.release)
            return;
        for (auto& c : fn_->contracts) {
            if (c.kind != Contract::Kind::Pre)
                continue;
            Value v = gen_expr(*c.expr);
            std::string ok = new_label("pre.ok");
            std::string fail = new_label("pre.fail");
            branch(v, ok, fail);
            start_block(fail);
            panic_block("precondition failed");
            start_block(ok);
        }
    }

    void gen_post_checks(Value v) {
        if (program_.release)
            return;
        for (auto& entry : post_slots_)
            store_local(Local{fn_->ret, entry.second, -1}, v);
        for (auto& c : fn_->contracts) {
            if (c.kind != Contract::Kind::Post)
                continue;
            Value okv = gen_expr(*c.expr);
            std::string ok = new_label("post.ok");
            std::string fail = new_label("post.fail");
            branch(okv, ok, fail);
            start_block(fail);
            panic_block("postcondition failed");
            start_block(ok);
        }
    }

    void emit_ret(Value v, bool has_value) {
        if (has_value && has_post_ && !checking_post_) {
            checking_post_ = true;
            gen_post_checks(v);
            checking_post_ = false;
        }
        if (has_root_frame_)
            emit("call $haze_root_leave(l " + root_frame_ + ")");
        if (has_value)
            emit("ret " + v.s);
        else
            emit("ret");
        blocks_[cur_].terminated = true;
    }

    void emit_ret_void() {
        if (word_return_)
            emit_ret(Value{t_i32(), "0", true}, true);
        else
            emit_ret(Value{}, false);
    }

    bool expr_has_managed(const Expr& e) {
        if (e.kind == Expr::Kind::If) {
            if (e.then_e && e.then_e->kind == Expr::Kind::Block && e.then_e->block &&
                block_has_managed(*e.then_e->block))
                return true;
            if (e.else_e && e.else_e->kind == Expr::Kind::Block && e.else_e->block &&
                block_has_managed(*e.else_e->block))
                return true;
            if (e.else_e && e.else_e->kind == Expr::Kind::If && expr_has_managed(*e.else_e))
                return true;
        }
        if (e.kind == Expr::Kind::Block && e.block && block_has_managed(*e.block))
            return true;
        return false;
    }

    bool block_has_managed(const Block& b) {
        for (auto& s : b.stmts) {
            if (s->kind == Stmt::Kind::Let || s->kind == Stmt::Kind::Var) {
                TypePtr t = s->decl_type ? s->decl_type : s->expr->ty;
                if (is_managed(t))
                    return true;
            }
            if (s->kind == Stmt::Kind::ForIn)
                return true;
            if ((s->kind == Stmt::Kind::ForRange || s->kind == Stmt::Kind::ForCond ||
                 s->kind == Stmt::Kind::Block) &&
                s->block && block_has_managed(*s->block))
                return true;
            if (s->kind == Stmt::Kind::Expr && s->expr && expr_has_managed(*s->expr))
                return true;
            if (s->kind == Stmt::Kind::Assign && s->expr && expr_has_managed(*s->expr))
                return true;
        }
        return false;
    }

    bool function_has_managed(const Function& fn) {
        for (auto& p : fn.params)
            if (is_managed(p.type))
                return true;
        for (auto& c : fn.captures)
            if (is_managed(c.type))
                return true;
        if (is_managed(fn.ret))
            return true;
        if (fn.arrow && expr_has_managed(*fn.arrow))
            return true;
        if (fn.body && block_has_managed(*fn.body))
            return true;
        return false;
    }

    void emit_root_frame_init() {
        root_frame_ = new_temp();
        root_slots_ = new_temp();
        rootmap_sym_ = "haze_rootmap_" + std::to_string(rootmap_counter_++);
        rootoffs_sym_ = "haze_rootoffs_" + std::to_string(rootmap_counter_ - 1);

        allocs_.push_back(root_frame_ + " =l alloc16 24");
        allocs_.push_back(root_slots_ + " =l alloc16 512");

        for (int i = 0; i < 64; i++) {
            std::string a = new_temp();
            emit_entry(a + " =l add " + root_slots_ + ", " + std::to_string(i * 8));
            emit_entry("storel 0, " + a);
        }

        std::string a = new_temp();
        emit_entry(a + " =l add " + root_frame_ + ", 0");
        emit_entry("storel 0, " + a);

        a = new_temp();
        emit_entry(a + " =l add " + root_frame_ + ", 8");
        emit_entry("storel $" + rootmap_sym_ + ", " + a);

        a = new_temp();
        emit_entry(a + " =l add " + root_frame_ + ", 16");
        emit_entry("storel " + root_slots_ + ", " + a);

        emit_entry("call $haze_root_enter(l " + root_frame_ + ")");
    }

    void emit_root_map() {
        data_ << "data $" << rootmap_sym_ << " = { w " << root_count_ << ", w 24, l $"
              << rootoffs_sym_ << " }\n";
        data_ << "data $" << rootoffs_sym_ << " = { w";
        if (root_count_ == 0)
            data_ << " 0";
        else
            for (int i = 0; i < root_count_; i++)
                data_ << " " << (i * 8);
        data_ << " }\n\n";
    }

    void gen_function(Function& fn) {
        fn_ = &fn;
        blocks_.clear();
        cur_ = -1;
        next_temp_ = 0;
        next_slot_ = 0;
        next_block_ = 1;
        allocs_.clear();
        entry_.clear();
        scopes_.clear();
        loops_.clear();
        root_count_ = 0;
        has_post_ = false;
        checking_post_ = false;
        post_slots_.clear();
        has_root_frame_ = function_has_managed(fn);
        word_return_ = (fn.name == "main") || (fn.ret && fn.ret->kind != Type::Kind::Void);

        if (fn.name == "main" && !fn.params.empty())
            throw Error(fn.pos, "main cannot take arguments in this milestone");
        if (fn.body == nullptr && fn.arrow == nullptr)
            throw Error(fn.pos, "function has no body");

        push_scope();
        start_block("@start");

        if (has_root_frame_)
            emit_root_frame_init();

        if (fn.is_lambda) {
            for (size_t i = 0; i < fn.captures.size(); i++) {
                const Param& c = fn.captures[i];
                std::string addr = new_temp();
                emit(addr + " =l add %env, " + std::to_string(8 + i * 8));
                std::string v = new_temp();
                emit(v + " =" + qbe_type(c.type) + " load" +
                     (qbe_type(c.type) == "l" ? "l" : "w") + " " + addr);
                declare_local(c.name, c.type, Value{c.type, v, true});
            }
        }

        for (size_t i = 0; i < fn.params.size(); i++) {
            const Param& p = fn.params[i];
            Local l;
            l.ty = p.type;
            l.slot = alloc_slot(p.type);
            if (is_managed(p.type)) {
                if (root_count_ >= 64)
                    throw Error(fn.pos, "too many managed parameters");
                l.root_index = root_count_++;
            }
            scopes_.back()[p.name] = l;
            std::string pv = "%p" + std::to_string(i);
            entry_.push_back("store" + store_suffix(p.type) + " " + pv + ", " + l.slot);
            if (l.root_index >= 0) {
                std::string a = new_temp();
                entry_.push_back(a + " =l add " + root_slots_ + ", " +
                                 std::to_string(l.root_index * 8));
                entry_.push_back("storel " + pv + ", " + a);
            }
        }

        for (auto& c : fn.contracts) {
            if (c.kind != Contract::Kind::Post)
                continue;
            has_post_ = true;
            if (!c.result_name.empty() && !post_slots_.count(c.result_name)) {
                std::string slot = alloc_slot(fn.ret);
                Local l;
                l.ty = fn.ret;
                l.slot = slot;
                if (is_managed(fn.ret)) {
                    if (!has_root_frame_)
                        throw Error(fn.pos, "managed contract result needs a root frame");
                    if (root_count_ >= 64)
                        throw Error(fn.pos, "too many managed locals");
                    l.root_index = root_count_++;
                }
                scopes_.back()[c.result_name] = l;
                post_slots_[c.result_name] = slot;
            }
        }

        gen_pre_checks();

        if (fn.arrow) {
            Value v = gen_expr(*fn.arrow);
            v = coerce(v, fn.ret);
            emit_ret(v, true);
        } else {
            if (fn.ret->kind == Type::Kind::Void) {
                gen_block_stmt(*fn.body);
                if (!terminated())
                    emit_ret_void();
            } else {
                Value v = gen_block_value(*fn.body);
                if (!terminated()) {
                    if (v.valid) {
                        v = coerce(v, fn.ret);
                        emit_ret(v, true);
                    } else {
                        emit_ret(Value{fn.ret, "0", true}, true);
                    }
                }
            }
        }

        pop_scope();

        if (has_root_frame_)
            emit_root_map();

        std::ostringstream f;
        bool first_param = true;
        if (fn.name == "main")
            f << "export function w $main(";
        else {
            f << "function";
            if (fn.ret && fn.ret->kind != Type::Kind::Void)
                f << " " << qbe_type(fn.ret);
            f << " $" << func_sym(fn.name) << "(";
            if (fn.is_lambda) {
                f << "l %env";
                first_param = false;
            }
        }
        for (size_t i = 0; i < fn.params.size(); i++) {
            if (!first_param)
                f << ", ";
            first_param = false;
            f << qbe_type(fn.params[i].type) << " %p" << i;
        }
        f << ") {\n";

        auto write_block = [&](const BlockOut& b, bool first) {
            f << b.label << "\n";
            if (first) {
                for (auto& a : allocs_)
                    f << "\t" << a << "\n";
                for (auto& a : entry_)
                    f << "\t" << a << "\n";
            }
            for (auto& line : b.lines)
                f << "\t" << line << "\n";
        };

        if (blocks_.empty()) {
            /* Unreachable: every function has @start. */
            f << "@start\n\tret\n";
        } else {
            write_block(blocks_[0], true);
            for (size_t i = 1; i < blocks_.size(); i++)
                write_block(blocks_[i], false);
        }
        f << "}\n\n";
        funcs_ << f.str();
    }

    Value gen_block_value(Block& b) {
        push_scope();
        Value result;
        for (size_t i = 0; i < b.stmts.size(); i++) {
            if (terminated())
                break;
            if (i + 1 == b.stmts.size() && b.stmts[i]->kind == Stmt::Kind::Expr) {
                result = gen_expr(*b.stmts[i]->expr);
            } else {
                gen_stmt(*b.stmts[i]);
            }
        }
        pop_scope();
        return result;
    }

    void gen_block_stmt(Block& b) {
        push_scope();
        for (auto& s : b.stmts) {
            if (terminated())
                break;
            gen_stmt(*s);
        }
        pop_scope();
    }

    Value gen_expr(Expr& e) {
        switch (e.kind) {
        case Expr::Kind::Int:
            return Value{e.ty, std::to_string(e.ival), true};
        case Expr::Kind::Bool:
            return Value{e.ty, e.bval ? "1" : "0", true};
        case Expr::Kind::String: {
            std::string sym = intern_string(e.text);
            return Value{e.ty, "$" + sym, true};
        }
        case Expr::Kind::Var: {
            Local* l = lookup_local(e.text);
            if (l)
                return load_slot(l->slot, l->ty);
            auto c = ctors_.find(e.text);
            if (c != ctors_.end())
                return gen_construct(e.text, {});
            auto g = globals_.find(e.text);
            if (g != globals_.end())
                return global_value(*g->second);
            auto f = sigs_.find(e.text);
            if (f != sigs_.end())
                return Value{e.ty, "$" + closure_for_function(e.text), true};
            throw Error(e.pos, "undefined variable '" + e.text + "'");
        }
        case Expr::Kind::Lambda: {
            auto it = functions_by_name_.find(e.text);
            if (it == functions_by_name_.end())
                throw Error(e.pos, "unknown lambda");
            Function& lambda = *it->second;
            collect_captures(lambda);
            size_t payload = align_up(8 + lambda.captures.size() * 8, 8);
            Value obj = alloc_object(payload);
            store_at(obj, 0, Value{t_ptr(), "$" + func_sym(lambda.name), true}, t_ptr());
            for (size_t i = 0; i < lambda.captures.size(); i++) {
                Local* captured = lookup_local(lambda.captures[i].name);
                if (!captured)
                    throw Error(lambda.captures[i].pos,
                                "cannot capture '" + lambda.captures[i].name + "'");
                Value v = load_slot(captured->slot, captured->ty);
                Value wide = coerce(v, t_i64());
                store_at(obj, 8 + i * 8, wide, t_i64());
            }
            return Value{e.ty, obj.s, true};
        }
        case Expr::Kind::Unary:
            return gen_unary(e);
        case Expr::Kind::Binary:
            return gen_binary(e);
        case Expr::Kind::Call:
            return gen_call(e);
        case Expr::Kind::If:
            return gen_if(e);
        case Expr::Kind::Match:
            return gen_match(e);
        case Expr::Kind::Block:
            return gen_block_value(*e.block);
        case Expr::Kind::List:
            return gen_list_lit(e);
        case Expr::Kind::RecordLit:
            return gen_record_lit(e);
        case Expr::Kind::Field:
            return gen_field(e);
        case Expr::Kind::Index:
            return gen_index(e);
        default:
            throw Error(e.pos, "unsupported expression");
        }
    }

    Value gen_construct(const std::string& name, std::vector<Value> args) {
        auto it = ctors_.find(name);
        if (it == ctors_.end())
            throw Error(Pos{}, "unknown constructor '" + name + "'");
        const TypePtr& sum = it->second.sum;
        const Variant& v = *it->second.variant;
        size_t index = 0;
        for (size_t i = 0; i < sum->variants.size(); i++)
            if (&sum->variants[i] == &v)
                index = i;
        FieldLayout lay = layout_fields(v.fields, 8);
        Value obj = alloc_object(sum_payload_size(sum));
        store_at(obj, kObjectHeader, Value{t_i32(), std::to_string(index), true}, t_i32());
        for (size_t i = 0; i < args.size(); i++)
            store_at(obj, kObjectHeader + lay.offsets[i], args[i], v.fields[i].type);
        return Value{sum, obj.s, true};
    }

    Value gen_record_lit(Expr& e) {
        auto it = types_.find(e.text);
        if (it == types_.end() || it->second->kind != Type::Kind::Record)
            throw Error(e.pos, "unknown record type '" + e.text + "'");
        TypePtr rt = it->second;
        std::vector<Value> args;
        for (auto& a : e.args)
            args.push_back(gen_expr(*a));
        FieldLayout lay = layout_fields(rt->fields, 0);
        Value obj = alloc_object(align_up(lay.size, 8));
        for (size_t i = 0; i < e.args.size(); i++) {
            for (size_t j = 0; j < rt->fields.size(); j++) {
                if (rt->fields[j].name == e.names[i]) {
                    store_at(obj, kObjectHeader + lay.offsets[j], args[i], rt->fields[j].type);
                    break;
                }
            }
        }
        return Value{rt, obj.s, true};
    }

    Value gen_list_lit(Expr& e) {
        TypePtr lt = e.ty;
        TypePtr elem = lt->elem;
        size_t stride = slot_size(elem);
        std::vector<Value> args;
        for (auto& a : e.args)
            args.push_back(gen_expr(*a));
        size_t payload = align_up(8 + args.size() * stride, 8);
        Value obj = alloc_object(payload);
        store_at(obj, kObjectHeader, Value{t_i32(), std::to_string(args.size()), true}, t_i32());
        for (size_t i = 0; i < args.size(); i++)
            store_at(obj, kObjectHeader + 8 + i * stride, args[i], elem);
        return Value{lt, obj.s, true};
    }

    Value gen_field(Expr& e) {
        Value base = gen_expr(*e.lhs);
        if (base.ty->kind == Type::Kind::List && e.text == "len")
            return load_at(base, kObjectHeader, t_i32());
        if (base.ty->kind != Type::Kind::Record)
            throw Error(e.pos, "field access requires a record");
        const TypePtr& rt = base.ty;
        FieldLayout lay = layout_fields(rt->fields, 0);
        for (size_t i = 0; i < rt->fields.size(); i++)
            if (rt->fields[i].name == e.text)
                return load_at(base, kObjectHeader + lay.offsets[i], rt->fields[i].type);
        throw Error(e.pos, "record '" + type_name(rt) + "' has no field '" + e.text + "'");
    }

    Value gen_index(Expr& e) {
        Value base = gen_expr(*e.lhs);
        Value idx = gen_expr(*e.rhs);
        TypePtr elem = base.ty->elem;
        size_t stride = slot_size(elem);
        Value off_idx = coerce(idx, t_i64());
        std::string off = new_temp();
        emit(off + " =l mul " + off_idx.s + ", " + std::to_string(stride));
        std::string addr = new_temp();
        emit(addr + " =l add " + base.s + ", " + std::to_string(kObjectHeader + 8));
        std::string final_addr = new_temp();
        emit(final_addr + " =l add " + addr + ", " + off);
        std::string t = new_temp();
        emit(t + " =" + qbe_type(elem) + " load" + (qbe_type(elem) == "l" ? "l" : "w") + " " +
             final_addr);
        return Value{elem, t, true};
    }

    Value gen_match(Expr& e) {
        Value scrutinee = gen_expr(*e.lhs);
        Value tag = load_at(scrutinee, kObjectHeader, t_i32());
        TypePtr rt = e.ty;
        bool want = rt && rt->kind != Type::Kind::Void;
        std::string slot;
        if (want)
            slot = alloc_slot(rt);
        std::string end = new_label("match.end");

        std::vector<std::string> labels(e.arms.size());
        std::string fallback;
        for (size_t i = 0; i < e.arms.size(); i++) {
            labels[i] = new_label("match.arm");
            if (e.arms[i].pat.wildcard && fallback.empty())
                fallback = labels[i];
        }
        bool has_wildcard = !fallback.empty();
        if (!has_wildcard)
            fallback = new_label("match.fail");

        for (size_t i = 0; i < e.arms.size(); i++) {
            if (e.arms[i].pat.wildcard)
                continue;
            auto c = ctors_.find(e.arms[i].pat.ctor);
            size_t index = 0;
            for (size_t k = 0; k < c->second.sum->variants.size(); k++)
                if (&c->second.sum->variants[k] == c->second.variant)
                    index = k;
            std::string cmp = new_temp();
            emit(cmp + " =w ceqw " + tag.s + ", " + std::to_string(index));
            std::string next = new_label("match.next");
            emit("jnz " + cmp + ", " + labels[i] + ", " + next);
            blocks_[cur_].terminated = true;
            start_block(next);
        }
        jump(fallback);

        for (size_t i = 0; i < e.arms.size(); i++) {
            start_block(labels[i]);
            push_scope();
            if (!e.arms[i].pat.wildcard) {
                auto c = ctors_.find(e.arms[i].pat.ctor);
                const Variant& v = *c->second.variant;
                FieldLayout lay = layout_fields(v.fields, 8);
                for (size_t j = 0; j < e.arms[i].pat.binders.size(); j++) {
                    if (e.arms[i].pat.binders[j] == "_")
                        continue;
                    Value fv = load_at(scrutinee, kObjectHeader + lay.offsets[j], v.fields[j].type);
                    declare_local(e.arms[i].pat.binders[j], v.fields[j].type, fv);
                }
            }
            Value bv = gen_branch_value(*e.arms[i].body);
            if (!terminated()) {
                if (want) {
                    bv = coerce(bv, rt);
                    store_local(Local{rt, slot, -1}, bv);
                }
                jump(end);
            }
            pop_scope();
        }
        if (!has_wildcard) {
            start_block(fallback);
            panic_block("match: no arm matched");
        }
        start_block(end);
        if (want)
            return load_slot(slot, rt);
        return Value{};
    }

    Value gen_unary(Expr& e) {
        Value v = gen_expr(*e.lhs);
        if (e.op == "-") {
            v = coerce(v, e.ty);
            std::string t = new_temp();
            emit(t + " =" + qbe_type(e.ty) + " sub 0, " + v.s);
            return Value{e.ty, t, true};
        }
        std::string t = new_temp();
        emit(t + " =w ceqw " + v.s + ", 0");
        return Value{t_bool(), t, true};
    }

    Value gen_list_concat(Value a, Value b, TypePtr elem) {
        size_t stride = slot_size(elem);
        Value alen = load_at(a, kObjectHeader, t_i32());
        Value blen = load_at(b, kObjectHeader, t_i32());
        std::string total = new_temp();
        emit(total + " =w add " + alen.s + ", " + blen.s);
        std::string bytes = new_temp();
        emit(bytes + " =w mul " + total + ", " + std::to_string(stride));
        std::string payload = new_temp();
        emit(payload + " =w add " + bytes + ", 16");
        Value obj{t_list(elem), new_temp(), true};
        emit(obj.s + " =l call $haze_alloc_slow(w " + payload + ", w 0)");
        store_at(obj, kObjectHeader, Value{t_i32(), total, true}, t_i32());

        std::string index = alloc_slot(t_i32());

        auto copy_loop = [&](Value src, Value count, bool append) {
            emit("storew 0, " + index);
            std::string cond = new_label("concat.cond");
            std::string body = new_label("concat.body");
            std::string done = new_label("concat.done");
            start_block(cond);
            Value i = load_slot(index, t_i32());
            std::string cmp = new_temp();
            emit(cmp + " =w csltw " + i.s + ", " + count.s);
            branch(Value{t_bool(), cmp, true}, body, done);

            start_block(body);
            Value idx64 = coerce(i, t_i64());
            std::string off = new_temp();
            emit(off + " =l mul " + idx64.s + ", " + std::to_string(stride));
            std::string saddr = new_temp();
            emit(saddr + " =l add " + src.s + ", " + std::to_string(kObjectHeader + 8));
            std::string saddr2 = new_temp();
            emit(saddr2 + " =l add " + saddr + ", " + off);
            std::string ev = new_temp();
            emit(ev + " =" + qbe_type(elem) + " load" +
                 (qbe_type(elem) == "l" ? "l" : "w") + " " + saddr2);

            std::string dest_index = i.s;
            if (append) {
                dest_index = new_temp();
                emit(dest_index + " =w add " + alen.s + ", " + i.s);
            }
            Value didx64 = coerce(Value{t_i32(), dest_index, true}, t_i64());
            std::string doff = new_temp();
            emit(doff + " =l mul " + didx64.s + ", " + std::to_string(stride));
            std::string daddr = new_temp();
            emit(daddr + " =l add " + obj.s + ", " + std::to_string(kObjectHeader + 8));
            std::string daddr2 = new_temp();
            emit(daddr2 + " =l add " + daddr + ", " + doff);
            emit(std::string("store") + (qbe_type(elem) == "l" ? "l" : "w") + " " + ev +
                 ", " + daddr2);

            std::string next = new_temp();
            emit(next + " =w add " + i.s + ", 1");
            emit("storew " + next + ", " + index);
            jump(cond);

            start_block(done);
        };

        copy_loop(a, alen, false);
        copy_loop(b, blen, true);
        return obj;
    }

    Value gen_binary(Expr& e) {
        if (e.op == "&&" || e.op == "||")
            return gen_logic(e);

        Value a = gen_expr(*e.lhs);
        Value b = gen_expr(*e.rhs);

        if (e.op == "+" && a.ty && b.ty && a.ty->kind == Type::Kind::List &&
            b.ty->kind == Type::Kind::List)
            return gen_list_concat(a, b, e.ty->elem);

        if (e.op == "+" || e.op == "-" || e.op == "*" || e.op == "/" || e.op == "%") {
            TypePtr ty = e.ty;
            a = coerce(a, ty);
            b = coerce(b, ty);
            std::string ins = e.op == "+"   ? "add"
                              : e.op == "-" ? "sub"
                              : e.op == "*" ? "mul"
                              : e.op == "/" ? "div"
                                            : "rem";
            std::string t = new_temp();
            emit(t + " =" + qbe_type(ty) + " " + ins + " " + a.s + ", " + b.s);
            return Value{ty, t, true};
        }

        if (e.op == "==" || e.op == "!=") {
            TypePtr ty = a.ty;
            if (ty && ty->kind != Type::Kind::Str) {
                if (a.ty->kind == Type::Kind::I64 || b.ty->kind == Type::Kind::I64) {
                    a = coerce(a, t_i64());
                    b = coerce(b, t_i64());
                    ty = t_i64();
                }
            }
            if (ty && ty->kind == Type::Kind::Str) {
                std::string t = new_temp();
                emit(t + " =w call $strcmp(l " + a.s + ", l " + b.s + ")");
                std::string q = new_temp();
                emit(q + " =w " + (e.op == "==" ? "ceqw " : "cnew ") + t + ", 0");
                return Value{t_bool(), q, true};
            }
            std::string base = qbe_type(ty);
            std::string ins = e.op == "==" ? "ceq" : "cne";
            std::string t = new_temp();
            emit(t + " =w " + ins + base + " " + a.s + ", " + b.s);
            return Value{t_bool(), t, true};
        }

        std::string ins;
        if (e.op == "<")
            ins = "cslt";
        else if (e.op == "<=")
            ins = "csle";
        else if (e.op == ">")
            ins = "csgt";
        else
            ins = "csge";
        TypePtr ty = a.ty;
        if (a.ty->kind == Type::Kind::I64 || b.ty->kind == Type::Kind::I64) {
            a = coerce(a, t_i64());
            b = coerce(b, t_i64());
            ty = t_i64();
        }
        std::string t = new_temp();
        emit(t + " =w " + ins + qbe_type(ty) + " " + a.s + ", " + b.s);
        return Value{t_bool(), t, true};
    }

    Value gen_logic(Expr& e) {
        bool is_and = e.op == "&&";
        std::string slot = alloc_slot(t_bool());
        std::string rhs = new_label("rhs");
        std::string other = new_label("other");
        std::string end = new_label("end");

        Value a = gen_expr(*e.lhs);
        if (is_and)
            branch(a, rhs, other);
        else
            branch(a, other, rhs);

        if (is_and) {
            start_block(rhs);
            Value b = gen_expr(*e.rhs);
            store_local(Local{t_bool(), slot, -1}, b);
            jump(end);

            start_block(other);
            store_local(Local{t_bool(), slot, -1}, Value{t_bool(), "0", true});
            jump(end);
        } else {
            start_block(other);
            store_local(Local{t_bool(), slot, -1}, Value{t_bool(), "1", true});
            jump(end);

            start_block(rhs);
            Value b = gen_expr(*e.rhs);
            store_local(Local{t_bool(), slot, -1}, b);
            jump(end);
        }

        start_block(end);
        return load_slot(slot, t_bool());
    }

    Value gen_if(Expr& e) {
        Value cond = gen_expr(*e.cond);
        TypePtr rt = e.ty;
        bool want = rt && rt->kind != Type::Kind::Void;
        std::string slot;
        if (want)
            slot = alloc_slot(rt);

        std::string then_l = new_label("then");
        std::string else_l = new_label("else");
        std::string end_l = new_label("endif");

        branch(cond, then_l, else_l);

        start_block(then_l);
        Value a = gen_branch_value(*e.then_e);
        if (!terminated()) {
            if (want) {
                a = coerce(a, rt);
                store_local(Local{rt, slot, -1}, a);
            }
            jump(end_l);
        }

        start_block(else_l);
        if (e.else_e) {
            Value b = gen_branch_value(*e.else_e);
            if (!terminated()) {
                if (want) {
                    b = coerce(b, rt);
                    store_local(Local{rt, slot, -1}, b);
                }
                jump(end_l);
            }
        } else {
            jump(end_l);
        }

        start_block(end_l);
        if (want)
            return load_slot(slot, rt);
        return Value{};
    }

    Value gen_branch_value(Expr& e) {
        if (e.kind == Expr::Kind::Block)
            return gen_block_value(*e.block);
        return gen_expr(e);
    }

    Value gen_indirect_call(Expr& e, Value callee) {
        TypePtr ft = e.lhs->ty;
        if (!ft || ft->kind != Type::Kind::Function)
            throw Error(e.pos, "called expression is not a function");
        std::vector<Value> args;
        for (auto& a : e.args)
            args.push_back(gen_expr(*a));

        Value fnptr = load_at(callee, 0, t_ptr());
        std::ostringstream s;
        if (ft->ret && ft->ret->kind != Type::Kind::Void)
            s << new_temp() << " =" << qbe_type(ft->ret) << " ";
        s << "call " << fnptr.s << "(l " << callee.s;
        for (size_t i = 0; i < args.size(); i++) {
            Value v = coerce(args[i], ft->params[i]);
            s << ", " << qbe_type(ft->params[i]) << " " << v.s;
        }
        s << ")";
        emit(s.str());
        if (ft->ret && ft->ret->kind != Type::Kind::Void) {
            std::string full = s.str();
            auto pos = full.find(" =");
            return Value{ft->ret, full.substr(0, pos), true};
        }
        return Value{};
    }

    Value gen_call(Expr& e) {
        if (e.lhs->kind != Expr::Kind::Var) {
            Value callee = gen_expr(*e.lhs);
            return gen_indirect_call(e, callee);
        }

        Local* local = lookup_local(e.lhs->text);
        if (local && local->ty && local->ty->kind == Type::Kind::Function)
            return gen_indirect_call(e, load_slot(local->slot, local->ty));

        auto global = globals_.find(e.lhs->text);
        if (global != globals_.end() && global->second->type &&
            global->second->type->kind == Type::Kind::Function)
            return gen_indirect_call(e, global_value(*global->second));

        const std::string& name = e.lhs->text;

        std::vector<Value> args;
        for (auto& a : e.args)
            args.push_back(gen_expr(*a));

        if (ctors_.count(name))
            return gen_construct(name, std::move(args));

        auto call = [&](const std::string& sym, const std::vector<TypePtr>& types,
                        TypePtr ret) -> Value {
            std::ostringstream s;
            if (ret && ret->kind != Type::Kind::Void)
                s << new_temp() << " =" << qbe_type(ret) << " ";
            s << "call $" << sym << "(";
            for (size_t i = 0; i < args.size(); i++) {
                if (i)
                    s << ", ";
                Value v = coerce(args[i], types[i]);
                s << qbe_type(types[i]) << " " << v.s;
            }
            s << ")";
            emit(s.str());
            if (ret && ret->kind != Type::Kind::Void) {
                std::string t = s.str();
                auto pos = t.find(" =");
                return Value{ret, t.substr(0, pos), true};
            }
            return Value{};
        };

        if (name == "print") {
            TypePtr t = args[0].ty;
            if (t->kind == Type::Kind::I32)
                return call("haze_print_i32", {t_i32()}, t_void());
            if (t->kind == Type::Kind::I64)
                return call("haze_print_i64", {t_i64()}, t_void());
            if (t->kind == Type::Kind::Bool)
                return call("haze_print_bool", {t_bool()}, t_void());
            return call("haze_print_str", {t_str()}, t_void());
        }

        if (name == "__gc_alloc") {
            args.push_back(Value{t_i32(), "0", true});
            return call("haze_alloc_slow", {t_i32(), t_i32()}, t_ptr());
        }

        if (name == "__gc_store") {
            Value p = coerce(args[0], t_ptr());
            Value off = coerce(args[1], t_i64());
            Value val = coerce(args[2], t_ptr());
            std::string addr = new_temp();
            emit(addr + " =l add " + p.s + ", " + off.s);
            emit("storel " + val.s + ", " + addr);
            return Value{};
        }

        if (name == "__gc_load") {
            Value p = coerce(args[0], t_ptr());
            Value off = coerce(args[1], t_i64());
            std::string addr = new_temp();
            emit(addr + " =l add " + p.s + ", " + off.s);
            std::string v = new_temp();
            emit(v + " =l loadl " + addr);
            return Value{t_ptr(), v, true};
        }

        if (name == "__gc_alive")
            return call("haze_gc_object_alive", {t_ptr()}, t_bool());

        if (name == "__gc_collect")
            return call("haze_gc_collect", {}, t_void());

        if (name == "__gc_verify")
            return call("haze_gc_verify", {}, t_void());

        if (name == "__gc_pin")
            return call("haze_pin", {t_ptr()}, t_void());

        if (name == "__gc_unpin")
            return call("haze_unpin", {t_ptr()}, t_void());

        auto it = sigs_.find(name);
        if (it == sigs_.end())
            throw Error(e.pos, "unknown function '" + name + "'");
        const FuncSig& sig = it->second;
        std::ostringstream s;
        if (sig.ret->kind != Type::Kind::Void)
            s << new_temp() << " =" << qbe_type(sig.ret) << " ";
        s << "call $" << func_sym(name) << "(";
        for (size_t i = 0; i < args.size(); i++) {
            if (i)
                s << ", ";
            Value v = coerce(args[i], sig.params[i]);
            s << qbe_type(sig.params[i]) << " " << v.s;
        }
        s << ")";
        emit(s.str());
        if (sig.ret->kind != Type::Kind::Void) {
            std::string full = s.str();
            auto pos = full.find(" =");
            return Value{sig.ret, full.substr(0, pos), true};
        }
        return Value{};
    }

    void gen_stmt(Stmt& s) {
        switch (s.kind) {
        case Stmt::Kind::Let:
        case Stmt::Kind::Var: {
            Value v = gen_expr(*s.expr);
            TypePtr ty = s.decl_type ? s.decl_type : s.expr->ty;
            v = coerce(v, ty);
            declare_local(s.name, ty, v);
            break;
        }
        case Stmt::Kind::Assign: {
            if (s.expr->kind != Expr::Kind::Var)
                throw Error(s.pos, "assignment target must be a variable");
            Local* l = lookup_local(s.expr->text);
            if (!l)
                throw Error(s.pos, "undefined variable '" + s.expr->text + "'");
            if (s.op == "=") {
                Value v = gen_expr(*s.rhs);
                store_local(*l, coerce(v, l->ty));
            } else {
                Value old = load_slot(l->slot, l->ty);
                Value rhs = gen_expr(*s.rhs);
                if (l->ty->kind == Type::Kind::List && s.op == "+=") {
                    store_local(*l, gen_list_concat(old, rhs, l->ty->elem));
                    break;
                }
                rhs = coerce(rhs, l->ty);
                std::string ins = s.op == "+="   ? "add"
                                  : s.op == "-=" ? "sub"
                                  : s.op == "*=" ? "mul"
                                  : s.op == "/=" ? "div"
                                                 : "rem";
                std::string t = new_temp();
                emit(t + " =" + qbe_type(l->ty) + " " + ins + " " + old.s + ", " + rhs.s);
                store_local(*l, Value{l->ty, t, true});
            }
            break;
        }
        case Stmt::Kind::Return: {
            if (s.expr) {
                Value v = gen_expr(*s.expr);
                v = coerce(v, fn_->ret);
                emit_ret(v, true);
            } else {
                emit_ret_void();
            }
            break;
        }
        case Stmt::Kind::ForRange:
            gen_for_range(s);
            break;
        case Stmt::Kind::ForIn:
            gen_for_in(s);
            break;
        case Stmt::Kind::ForCond:
            gen_for_cond(s);
            break;
        case Stmt::Kind::Break:
            jump(loops_.back().break_label);
            break;
        case Stmt::Kind::Continue:
            jump(loops_.back().continue_label);
            break;
        case Stmt::Kind::Expr:
            gen_expr(*s.expr);
            break;
        case Stmt::Kind::Block:
            gen_block_stmt(*s.block);
            break;
        }
    }

    void gen_invariants(Stmt& s) {
        if (program_.release)
            return;
        for (auto& inv : s.invariants) {
            Value v = gen_expr(*inv);
            std::string ok = new_label("invariant.ok");
            std::string fail = new_label("invariant.fail");
            branch(v, ok, fail);
            start_block(fail);
            panic_block("loop invariant failed");
            start_block(ok);
        }
    }

    void gen_for_range(Stmt& s) {
        Value lo = gen_expr(*s.lo);
        Value hi = gen_expr(*s.hi);
        TypePtr it = lo.ty->kind == Type::Kind::I64 || (hi.ty && hi.ty->kind == Type::Kind::I64)
                         ? t_i64()
                         : t_i32();
        lo = coerce(lo, it);
        hi = coerce(hi, it);

        std::string i_slot = alloc_slot(it);
        std::string hi_slot = alloc_slot(it);
        emit("store" + store_suffix(it) + " " + lo.s + ", " + i_slot);
        emit("store" + store_suffix(it) + " " + hi.s + ", " + hi_slot);

        std::string cond = new_label("for.cond");
        std::string body = new_label("for.body");
        std::string incr = new_label("for.incr");
        std::string end = new_label("for.end");

        push_scope();
        Local loopvar;
        loopvar.ty = it;
        loopvar.slot = i_slot;
        scopes_.back()[s.name] = loopvar;

        start_block(cond);
        gen_invariants(s);
        Value iv = load_slot(i_slot, it);
        Value hv = load_slot(hi_slot, it);
        std::string c = new_temp();
        emit(c + " =w " + (it->kind == Type::Kind::I64 ? "csltl " : "csltw ") + iv.s + ", " + hv.s);
        branch(Value{t_bool(), c, true}, body, end);

        start_block(body);
        loops_.push_back(LoopCtx{end, incr});
        gen_block_stmt(*s.block);
        loops_.pop_back();
        if (!terminated())
            jump(incr);

        start_block(incr);
        iv = load_slot(i_slot, it);
        std::string one = it->kind == Type::Kind::I64 ? "1" : "1";
        std::string n = new_temp();
        emit(n + " =" + qbe_type(it) + " add " + iv.s + ", " + one);
        emit("store" + store_suffix(it) + " " + n + ", " + i_slot);
        jump(cond);

        start_block(end);
        pop_scope();
    }

    void gen_for_in(Stmt& s) {
        Value listv = gen_expr(*s.expr);
        TypePtr lt = listv.ty;
        TypePtr elem = lt->elem;
        size_t stride = slot_size(elem);

        push_scope();
        std::string hidden = "$iter" + std::to_string(next_slot_);
        Local listl = declare_local(hidden, lt, listv);

        std::string i_slot = alloc_slot(t_i32());
        emit("storew 0, " + i_slot);
        Value len = load_at(listv, kObjectHeader, t_i32());
        std::string len_slot = alloc_slot(t_i32());
        emit("storew " + len.s + ", " + len_slot);

        Value zero{elem, "0", true};
        Local eleml = declare_local(s.name, elem, zero);

        std::string cond = new_label("forin.cond");
        std::string body = new_label("forin.body");
        std::string incr = new_label("forin.incr");
        std::string end = new_label("forin.end");

        start_block(cond);
        gen_invariants(s);
        Value iv = load_slot(i_slot, t_i32());
        Value lv = load_slot(len_slot, t_i32());
        std::string c = new_temp();
        emit(c + " =w csltw " + iv.s + ", " + lv.s);
        branch(Value{t_bool(), c, true}, body, end);

        start_block(body);
        Value base = load_slot(listl.slot, lt);
        Value idx = coerce(iv, t_i64());
        std::string off = new_temp();
        emit(off + " =l mul " + idx.s + ", " + std::to_string(stride));
        std::string addr = new_temp();
        emit(addr + " =l add " + base.s + ", " + std::to_string(kObjectHeader + 8));
        std::string final_addr = new_temp();
        emit(final_addr + " =l add " + addr + ", " + off);
        std::string ev = new_temp();
        emit(ev + " =" + qbe_type(elem) + " load" + (qbe_type(elem) == "l" ? "l" : "w") + " " +
             final_addr);
        store_local(eleml, Value{elem, ev, true});

        loops_.push_back(LoopCtx{end, incr});
        gen_block_stmt(*s.block);
        loops_.pop_back();
        if (!terminated())
            jump(incr);

        start_block(incr);
        iv = load_slot(i_slot, t_i32());
        std::string n = new_temp();
        emit(n + " =w add " + iv.s + ", 1");
        emit("storew " + n + ", " + i_slot);
        jump(cond);

        start_block(end);
        pop_scope();
    }

    void gen_for_cond(Stmt& s) {
        std::string cond = new_label("while.cond");
        std::string body = new_label("while.body");
        std::string end = new_label("while.end");

        start_block(cond);
        gen_invariants(s);
        Value c = gen_expr(*s.cond);
        branch(c, body, end);

        start_block(body);
        loops_.push_back(LoopCtx{end, cond});
        gen_block_stmt(*s.block);
        loops_.pop_back();
        if (!terminated())
            jump(cond);

        start_block(end);
    }
};

} // namespace

std::string generate_qbe(Program& program, const std::string& source_name) {
    Gen g(program, source_name);
    return g.run();
}

} // namespace haze