#include "BasicBlock.h"
#include "Constant.h"
#include "Function.h"
#include "IRStmtBuilder.h"
#include "Module.h"
#include "Type.h"

#include <iostream>
#include <memory>

#define CONST_INT(num) \
    ConstantInt::create(num, module)

#define CONST_FP(num) \
    ConstantFloat::create(num, module) // 得到常数值的表示,方便后面多次用到

using namespace SysYF::IR;

int main()
{
    // 创建module和builder
    auto module = Module::create("SysYF code");
    auto builder = IRStmtBuilder::create(nullptr, module);
    SysYF::Ptr<Type> Int32Type = Type::get_int32_type(module);
    SysYF::Ptr<Type> FloatType = Type::get_float_type(module);
    // 全局变量
    auto zero_initializer = ConstantZero::create(Int32Type, module);
    auto a = GlobalVariable::create("a", module, Int32Type, false, zero_initializer);
    auto b = GlobalVariable::create("b", module, Int32Type, false, zero_initializer);
    // main 函数
    auto mainFunTy = Function::create(FunctionType::create(Int32Type, {}), "main", module);
    auto bb = BasicBlock::create(module, "entry", mainFunTy);
    builder->set_insert_point(bb);
    // 赋初值
    builder->create_store(CONST_INT(3), a); // a = 3
    builder->create_store(CONST_INT(0), b); // b = 0
    // 建立while循环
    auto condBB = BasicBlock::create(module, "condBB_while", mainFunTy);
    auto trueBB = BasicBlock::create(module, "trueBB_while", mainFunTy);
    auto falseBB = BasicBlock::create(module, "falseBB_while", mainFunTy);
    builder->create_br(condBB);
    builder->set_insert_point(condBB);
    // while循环条件
    auto a_Load = builder->create_load(a); // load a
    auto icmp = builder->create_icmp_gt(a_Load, CONST_INT(0));
    builder->create_cond_br(icmp, trueBB, falseBB);
    // while循环体
    builder->set_insert_point(trueBB);
    a_Load = builder->create_load(a);      // load a
    auto b_Load = builder->create_load(b); // load b
    auto add = builder->create_iadd(b_Load, a_Load);
    auto sub = builder->create_isub(a_Load, CONST_INT(1));
    builder->create_store(add, b); // b = b + a
    builder->create_store(sub, a); // a = a - 1
    builder->create_br(condBB);    // 跳转到循环条件
    // while循环结束
    builder->set_insert_point(falseBB);
    // return
    auto ret_Load = builder->create_load(b);
    builder->create_ret(ret_Load);
    // 输出IR
    std::cout << module->print();
}