name: Prepare MLIR Cache
description: Restore or build the cached MLIR toolchain.

inputs:
  llvm-commit:
    description: LLVM commit to build.
    required: true
  mold-linker-flags:
    description: Linker flags used to force mold.
    required: true

runs:
  using: composite
  steps:
    - name: Restore MLIR Cache
      id: restore-mlir-cache
      uses: actions/cache/restore@v4
      with:
        path: onnx-mlir/llvm-project
        key: mlir-${{ runner.os }}-${{ inputs.llvm-commit }}

    - name: Clone LLVM
      if: steps.restore-mlir-cache.outputs.cache-hit != 'true'
      shell: bash
      run: |
        git clone --filter=blob:none --no-checkout https://github.com/llvm/llvm-project.git onnx-mlir/llvm-project
        cd onnx-mlir/llvm-project
        git fetch --depth 1 origin ${{ inputs.llvm-commit }}
        git checkout FETCH_HEAD

    - name: Build MLIR
      if: steps.restore-mlir-cache.outputs.cache-hit != 'true'
      shell: bash
      run: |
        cmake -S onnx-mlir/llvm-project/llvm -B onnx-mlir/llvm-project/build -G Ninja \
          -DLLVM_ENABLE_PROJECTS="mlir;clang" \
          -DLLVM_ENABLE_RUNTIMES="openmp" \
          -DLLVM_TARGETS_TO_BUILD="host" \
          -DCMAKE_BUILD_TYPE=Release \
          -DLLVM_ENABLE_ASSERTIONS=ON \
          -DLLVM_ENABLE_RTTI=ON \
          -DENABLE_LIBOMPTARGET=OFF \
          -DLLVM_ENABLE_LIBEDIT=OFF \
          -DCMAKE_EXE_LINKER_FLAGS="${{ inputs.mold-linker-flags }}" \
          -DCMAKE_SHARED_LINKER_FLAGS="${{ inputs.mold-linker-flags }}" \
          -DCMAKE_MODULE_LINKER_FLAGS="${{ inputs.mold-linker-flags }}"
        cmake --build onnx-mlir/llvm-project/build

    - name: Save MLIR Cache
      if: steps.restore-mlir-cache.outputs.cache-hit != 'true'
      uses: actions/cache/save@v4
      with:
        path: onnx-mlir/llvm-project
        key: mlir-${{ runner.os }}-${{ inputs.llvm-commit }}
