/*
 * Copyright (C) 2022 Collabora Ltd.
 * SPDX-License-Identifier: MIT
 */

#include "compiler/nir/nir_builder.h"
#include "pan_nir.h"

static void
lower_xfb_output(nir_builder *b, nir_intrinsic_instr *intr,
                 unsigned start_component, unsigned num_components,
                 unsigned buffer, unsigned offset_words)
{
   assert(buffer < MAX_XFB_BUFFERS);
   assert(nir_intrinsic_component(intr) == 0); // TODO

   /* Transform feedback info in units of words, convert to bytes. */
   uint16_t stride = b->shader->info.xfb_stride[buffer] * 4;
   assert(stride != 0);

   uint16_t offset = offset_words * 4;

   nir_def *index = nir_iadd(
      b, nir_imul(b, nir_load_instance_id(b), nir_load_num_vertices(b)),
      nir_load_raw_vertex_id_pan(b));

   BITSET_SET(b->shader->info.system_values_read,
              SYSTEM_VALUE_VERTEX_ID_ZERO_BASE);
   BITSET_SET(b->shader->info.system_values_read, SYSTEM_VALUE_INSTANCE_ID);

   nir_def *buf = nir_load_xfb_address(b, 64, .base = buffer);
   nir_def *addr = nir_iadd(
      b, buf,
      nir_u2u64(b, nir_iadd_imm(b, nir_imul_imm(b, index, stride), offset)));

   nir_def *src = intr->src[0].ssa;
   nir_component_mask_t mask = nir_component_mask(num_components);
   nir_def *value = nir_channels(b, src, mask << start_component);
   nir_store_global(b, value, addr);
}

static bool
lower_xfb(nir_builder *b, nir_intrinsic_instr *intr, UNUSED void *data)
{
   /* In transform feedback programs, vertex ID becomes zero-based, so apply
    * that lowering even on Valhall.
    */
   if (intr->intrinsic == nir_intrinsic_load_vertex_id) {
      b->cursor = nir_instr_remove(&intr->instr);

      nir_def *repl = nir_iadd(b, nir_load_raw_vertex_id_pan(b),
                               nir_load_raw_vertex_offset_pan(b));

      nir_def_rewrite_uses(&intr->def, repl);
      return true;
   }

   if (intr->intrinsic != nir_intrinsic_store_output)
      return false;

   bool progress = false;

   b->cursor = nir_before_instr(&intr->instr);

   for (unsigned i = 0; i < 2; ++i) {
      nir_io_xfb xfb =
         i ? nir_intrinsic_io_xfb2(intr) : nir_intrinsic_io_xfb(intr);
      for (unsigned j = 0; j < 2; ++j) {
         if (!xfb.out[j].num_components)
            continue;

         lower_xfb_output(b, intr, i * 2 + j, xfb.out[j].num_components,
                          xfb.out[j].buffer, xfb.out[j].offset);
         progress = true;
      }
   }

   nir_instr_remove(&intr->instr);
   return progress;
}

bool
pan_nir_lower_xfb(nir_shader *nir)
{
   return nir_shader_intrinsics_pass(
      nir, lower_xfb, nir_metadata_control_flow, NULL);
}
