#include "xyz.h"

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

namespace xyz {

namespace {

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 &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);
    }
  }

  std::string run() {
    for (auto &fn : program_.functions)
      gen_function(*fn);

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

private:
  Program &program_;
  std::string source_name_;
  SigMap sigs_;
  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_++);
  }

  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 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 = "xyz_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 $xyz_panic(l $" + sym + ")");
    emit("hlt");
    blocks_[cur_].terminated = true;
  }

  void gen_pre_checks() {
    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) {
    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 $xyz_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::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;
    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_ = "xyz_rootmap_" + std::to_string(rootmap_counter_++);
    rootoffs_sym_ = "xyz_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 $xyz_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();

    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;
    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 << " $xyz_" << fn.name << "(";
    }
    for (size_t i = 0; i < fn.params.size(); i++) {
      if (i)
        f << ", ";
      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)
        throw Error(e.pos, "undefined variable '" + e.text + "'");
      return load_slot(l->slot, l->ty);
    }
    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::Block:
      return gen_block_value(*e.block);
    default:
      throw Error(e.pos, "unsupported expression");
    }
  }

  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_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 == "+" || 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_call(Expr &e) {
    if (e.lhs->kind != Expr::Kind::Var)
      throw Error(e.pos, "only named functions can be called");
    const std::string &name = e.lhs->text;

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

    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("xyz_print_i32", {t_i32()}, t_void());
      if (t->kind == Type::Kind::I64)
        return call("xyz_print_i64", {t_i64()}, t_void());
      if (t->kind == Type::Kind::Bool)
        return call("xyz_print_bool", {t_bool()}, t_void());
      return call("xyz_print_str", {t_str()}, t_void());
    }

    if (name == "__gc_alloc") {
      args.push_back(Value{t_i32(), "0", true});
      return call("xyz_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("xyz_gc_object_alive", {t_ptr()}, t_bool());

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

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

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

    if (name == "__gc_unpin")
      return call("xyz_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 $" << (name == "main" ? "main" : ("xyz_" + 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);
        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::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_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);
    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_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);
    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 xyz
