#include "ir/PassManager.h"
#include <iostream>

namespace ir {

void RunFunctionOptimizationPasses(Function* func, Context& ctx) {
  RunMem2Reg(func, ctx);

  bool changed = true;
  int iterations = 0;
  const int max_iterations = 16;

  while (changed && iterations < max_iterations) {
    changed = false;
    iterations++;

    changed |= RunConstProp(func, ctx);
    changed |= RunConstFold(func, ctx);
    changed |= RunAlgebraicSimplify(func, ctx);
    changed |= RunCSE(func);
    changed |= RunLICM(func);
    changed |= RunDCE(func);
    changed |= RunCFGSimplify(func);
  }
}

void RunOptimizationPasses(Module& module) {
  for (const auto& funcPtr : module.GetFunctions()) {
    if (!funcPtr->GetBlocks().empty()) {
      RunFunctionOptimizationPasses(funcPtr.get(), module.GetContext());
    }
  }
}

} // namespace ir
