// IR 构建工具：
// - 管理插入点（当前基本块/位置）
// - 提供创建各类指令的便捷接口，降低 IRGen 复杂度

#include "ir/IR.h"

#include <stdexcept>

#include "utils/Log.h"

namespace ir {
IRBuilder::IRBuilder(Context& ctx, BasicBlock* bb)
    : ctx_(ctx), insert_block_(bb) {}

void IRBuilder::SetInsertPoint(BasicBlock* bb) { insert_block_ = bb; }

BasicBlock* IRBuilder::GetInsertBlock() const { return insert_block_; }

ConstantInt* IRBuilder::CreateConstInt(int v) {
  // 常量不需要挂在基本块里，由 Context 负责去重与生命周期。
  return ctx_.GetConstInt(v);
}

BinaryInst* IRBuilder::CreateBinary(Opcode op, Value* lhs, Value* rhs,
                                    const std::string& name) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!lhs) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateBinary 缺少 lhs"));
  }
  if (!rhs) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateBinary 缺少 rhs"));
  }
  return insert_block_->Append<BinaryInst>(op, lhs->GetType(), lhs, rhs, name);
}

BinaryInst* IRBuilder::CreateAdd(Value* lhs, Value* rhs,
                                 const std::string& name) {
  return CreateBinary(Opcode::Add, lhs, rhs, name);
}

BinaryInst* IRBuilder::CreateSub(Value* lhs, Value* rhs,
                                 const std::string& name) {
  return CreateBinary(Opcode::Sub, lhs, rhs, name);
}

BinaryInst* IRBuilder::CreateMul(Value* lhs, Value* rhs,
                                 const std::string& name) {
  return CreateBinary(Opcode::Mul, lhs, rhs, name);
}

BinaryInst* IRBuilder::CreateDiv(Value* lhs, Value* rhs,
                                 const std::string& name) {
  return CreateBinary(Opcode::Div, lhs, rhs, name);
}

BinaryInst* IRBuilder::CreateMod(Value* lhs, Value* rhs,
                                 const std::string& name) {
  return CreateBinary(Opcode::Mod, lhs, rhs, name);
}

CmpInst* IRBuilder::CreateCmp(CmpOp op, Value* lhs, Value* rhs,
                              const std::string& name) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!lhs || !rhs) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateCmp 缺少操作数"));
  }
  return insert_block_->Append<CmpInst>(op, Type::GetInt32Type(), lhs, rhs,
                                        name);
}

AllocaInst* IRBuilder::CreateAllocaI32(const std::string& name) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  return insert_block_->Append<AllocaInst>(Type::GetPtrInt32Type(), name);
}

AllocaInst* IRBuilder::CreateAllocaArray(int count, const std::string& name) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (count <= 0) {
    throw std::runtime_error(FormatError("ir", "IRBuilder::CreateAllocaArray 数组大小必须为正数"));
  }
  return insert_block_->Append<AllocaInst>(Type::GetPtrInt32Type(), name, count);
}

GepInst* IRBuilder::CreateGep(Value* base, Value* index, const std::string& name) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!base || !index) {
    throw std::runtime_error(FormatError("ir", "IRBuilder::CreateGep 缺少操作数"));
  }
  return insert_block_->Append<GepInst>(Type::GetPtrInt32Type(), base, index, name);
}

LoadInst* IRBuilder::CreateLoad(Value* ptr, const std::string& name) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!ptr) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateLoad 缺少 ptr"));
  }
  return insert_block_->Append<LoadInst>(Type::GetInt32Type(), ptr, name);
}

StoreInst* IRBuilder::CreateStore(Value* val, Value* ptr) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!val) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateStore 缺少 val"));
  }
  if (!ptr) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateStore 缺少 ptr"));
  }
  return insert_block_->Append<StoreInst>(Type::GetVoidType(), val, ptr);
}

BranchInst* IRBuilder::CreateBr(BasicBlock* target) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!target) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateBr 缺少目标块"));
  }
  return insert_block_->Append<BranchInst>(Type::GetVoidType(), target);
}

CondBranchInst* IRBuilder::CreateCondBr(Value* cond, BasicBlock* true_bb,
                                        BasicBlock* false_bb) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!cond || !true_bb || !false_bb) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateCondBr 参数不完整"));
  }
  return insert_block_->Append<CondBranchInst>(Type::GetVoidType(), cond,
                                               true_bb, false_bb);
}

CallInst* IRBuilder::CreateCall(Function* callee,
                                const std::vector<Value*>& args,
                                const std::string& name) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!callee) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateCall 缺少被调函数"));
  }
  return insert_block_->Append<CallInst>(callee->GetType(), callee, args, name);
}

ReturnInst* IRBuilder::CreateRet(Value* v) {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  if (!v) {
    throw std::runtime_error(
        FormatError("ir", "IRBuilder::CreateRet 缺少返回值"));
  }
  return insert_block_->Append<ReturnInst>(Type::GetVoidType(), v);
}

ReturnInst* IRBuilder::CreateRetVoid() {
  if (!insert_block_) {
    throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点"));
  }
  return insert_block_->Append<ReturnInst>(Type::GetVoidType(), nullptr);
}

}  // namespace ir
