clc_compiler.c 59 KB
Newer Older
1
/*
2
 * Copyright © Microsoft Corporation
3 4 5 6
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
7 8 9
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
10 11 12 13 14 15 16
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 18 19 20 21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
22 23
 */

24
#include "nir.h"
25
#include "nir_serialize.h"
26 27
#include "glsl_types.h"
#include "nir_types.h"
28
#include "nir_lower_libclc.h"
29
#include "clc_compiler.h"
30
#include "clc_helpers.h"
31
#include "clc_nir.h"
32
#include "../compiler/dxil_nir.h"
33
#include "../compiler/dxil_nir_lower_int_samplers.h"
34
#include "../compiler/nir_to_dxil.h"
35 36

#include "util/u_debug.h"
37
#include <util/u_math.h>
Daniel Stone's avatar
Daniel Stone committed
38
#include "spirv/nir_spirv.h"
39
#include "nir_builder.h"
40
#include "nir_builtin_builder.h"
41

42 43
#include "git_sha1.h"

44
#include "spirv64-mesa3d-.spv.h"
45

46 47
enum clc_debug_flags {
   CLC_DEBUG_DUMP_SPIRV = 1 << 0,
48
   CLC_DEBUG_VERBOSE = 1 << 1,
49 50 51 52
};

static const struct debug_named_value debug_options[] = {
   { "dump_spirv",  CLC_DEBUG_DUMP_SPIRV, "Dump spirv blobs" },
53
   { "verbose",  CLC_DEBUG_VERBOSE, NULL },
54 55 56 57 58
   DEBUG_NAMED_VALUE_END
};

DEBUG_GET_ONCE_FLAGS_OPTION(debug_clc, "CLC_DEBUG", debug_options, 0)

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
static void
clc_print_kernels_info(const struct clc_object *obj)
{
   fprintf(stdout, "Kernels:\n");
   for (unsigned i = 0; i < obj->num_kernels; i++) {
      const struct clc_kernel_arg *args = obj->kernels[i].args;
      bool first = true;

      fprintf(stdout, "\tvoid %s(", obj->kernels[i].name);
      for (unsigned j = 0; j < obj->kernels[i].num_args; j++) {
         if (!first)
            fprintf(stdout, ", ");
         else
            first = false;

         switch (args[j].address_qualifier) {
         case CLC_KERNEL_ARG_ADDRESS_GLOBAL:
            fprintf(stdout, "__global ");
            break;
         case CLC_KERNEL_ARG_ADDRESS_LOCAL:
            fprintf(stdout, "__local ");
            break;
81
         case CLC_KERNEL_ARG_ADDRESS_CONSTANT:
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
            fprintf(stdout, "__constant ");
            break;
         default:
            break;
         }

         if (args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_VOLATILE)
            fprintf(stdout, "volatile ");
         if (args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_CONST)
            fprintf(stdout, "const ");
         if (args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_RESTRICT)
            fprintf(stdout, "restrict ");

         fprintf(stdout, "%s %s", args[j].type_name, args[j].name);
      }
      fprintf(stdout, ");\n");
   }
}

101 102 103
static enum glsl_base_type
glsl_base_type_for_image_pipe_format(enum pipe_format format)
{
104
   switch (format) {
105 106 107 108
   case PIPE_FORMAT_R32G32B32A32_FLOAT: return GLSL_TYPE_FLOAT;
   case PIPE_FORMAT_R16G16B16A16_FLOAT: return GLSL_TYPE_FLOAT16;
   case PIPE_FORMAT_R32G32B32A32_SINT: return GLSL_TYPE_INT;
   case PIPE_FORMAT_R32G32B32A32_UINT: return GLSL_TYPE_UINT;
109
   default: unreachable("Unexpected image format");
110
   }
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
}

static enum pipe_format
pipe_format_for_nir_format(enum nir_alu_type format)
{
   switch (format) {
   case nir_type_float: return PIPE_FORMAT_R32G32B32A32_FLOAT;
   case nir_type_float16: return PIPE_FORMAT_R16G16B16A16_FLOAT;
   case nir_type_int: return PIPE_FORMAT_R32G32B32A32_SINT;
   case nir_type_uint: return PIPE_FORMAT_R32G32B32A32_UINT;
   default: unreachable("Unexpected nir format");
   }
}

struct clc_image_lower_context
{
   struct clc_dxil_metadata *metadata;
   unsigned *num_srvs;
   unsigned *num_uavs;
   nir_deref_instr *deref;
   unsigned num_buf_ids;
   int metadata_index;
};

static nir_ssa_def *
lower_image_deref_impl(nir_builder *b, struct clc_image_lower_context *context,
                       const struct glsl_type *new_var_type,
                       unsigned *num_bindings, enum pipe_format image_format)
{
   nir_variable *in_var = nir_deref_instr_get_variable(context->deref);
   nir_variable *uniform = nir_variable_create(b->shader, nir_var_uniform, new_var_type, NULL);
   uniform->data.access = in_var->data.access;
   uniform->data.image.format = image_format;
   uniform->data.binding = in_var->data.binding;
   if (context->num_buf_ids > 0) {
      // Need to assign a new binding
      context->metadata->args[context->metadata_index].
         image.buf_ids[context->num_buf_ids] = uniform->data.binding = (*num_bindings)++;
   }
   context->num_buf_ids++;

   b->cursor = nir_after_instr(&context->deref->instr);
   nir_deref_instr* deref_uniform = nir_build_deref_var(b, uniform);
   return &deref_uniform->dest.ssa;
}

static nir_ssa_def *
lower_read_only_image_deref(nir_builder *b, struct clc_image_lower_context *context,
                            enum pipe_format image_format)
{
   nir_variable *in_var = nir_deref_instr_get_variable(context->deref);

   // Non-writeable images should be converted to samplers,
   // since they may have texture operations done on them
   const struct glsl_type *new_var_type =
      glsl_sampler_type(glsl_get_sampler_dim(in_var->type),
167 168
            false, glsl_sampler_type_is_array(in_var->type),
            glsl_base_type_for_image_pipe_format(image_format));
169 170 171 172 173 174 175 176 177 178
   return lower_image_deref_impl(b, context, new_var_type, context->num_srvs, image_format);
}

static nir_ssa_def *
lower_read_write_image_deref(nir_builder *b, struct clc_image_lower_context *context,
                             enum pipe_format image_format)
{
   nir_variable *in_var = nir_deref_instr_get_variable(context->deref);
   const struct glsl_type *new_var_type =
      glsl_image_type(glsl_get_sampler_dim(in_var->type),
179 180
         glsl_sampler_type_is_array(in_var->type),
         glsl_base_type_for_image_pipe_format(image_format));
181
   return lower_image_deref_impl(b, context, new_var_type, context->num_uavs, image_format);
182 183 184
}

static void
185
clc_lower_input_image_deref(nir_builder *b, struct clc_image_lower_context *context)
186 187 188 189 190 191
{
   // The input variable here isn't actually an image, it's just the
   // image format data.
   //
   // For every use of an image in a different way, we'll add an
   // appropriate uniform to match it. That can result in up to
192 193
   // 3 uniforms (float4, int4, uint4) for each image. Only one of these
   // formats will actually produce correct data, but a single kernel
194 195 196 197
   // could use runtime conditionals to potentially access any of them.
   //
   // If the image is used in a query that doesn't have a corresponding
   // DXIL intrinsic (CL image channel order or channel format), then
198
   // we'll add a kernel input for that data that'll be lowered by the
199 200 201 202 203 204 205 206 207 208 209 210
   // explicit IO pass later on.
   //
   // After all that, we can remove the image input variable and deref.

   enum image_uniform_type {
      FLOAT4,
      INT4,
      UINT4,
      IMAGE_UNIFORM_TYPE_COUNT
   };

   nir_ssa_def *uniform_deref_dests[IMAGE_UNIFORM_TYPE_COUNT] = {0};
211
   nir_ssa_def *format_deref_dest = NULL, *order_deref_dest = NULL;
212

213
   nir_variable *in_var = nir_deref_instr_get_variable(context->deref);
214 215
   enum gl_access_qualifier access = in_var->data.access;

216 217 218
   context->metadata_index = 0;
   while (context->metadata->args[context->metadata_index].image.buf_ids[0] != in_var->data.binding)
      context->metadata_index++;
219

220
   context->num_buf_ids = 0;
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
   for (int pass = 0; pass < 2; ++pass) {
      nir_foreach_use_safe(src, &context->deref->dest.ssa) {
         enum image_uniform_type type;

         if (src->parent_instr->type == nir_instr_type_intrinsic) {
            nir_intrinsic_instr *intrinsic = nir_instr_as_intrinsic(src->parent_instr);
            enum nir_alu_type dest_type;

            switch (intrinsic->intrinsic) {
            case nir_intrinsic_image_deref_load:
            case nir_intrinsic_image_deref_store: {
               enum pipe_format intr_format = nir_intrinsic_format(intrinsic);

               switch (intr_format) {
               case PIPE_FORMAT_R32G32B32A32_FLOAT: type = FLOAT4; dest_type = nir_type_float; break;
               case PIPE_FORMAT_R32G32B32A32_SINT: type = INT4; dest_type = nir_type_int; break;
               case PIPE_FORMAT_R32G32B32A32_UINT: type = UINT4; dest_type = nir_type_uint; break;
               default: unreachable("Unsupported image format for load.");
               }

               nir_ssa_def *image_deref = uniform_deref_dests[type];
               if (!image_deref) {
                  const struct glsl_type *new_var_type;
                  if (in_var->data.access & ACCESS_NON_WRITEABLE) {
                     image_deref = lower_read_only_image_deref(b, context, intr_format);
                  } else {
                     image_deref = lower_read_write_image_deref(b, context, intr_format);
                  }

                  uniform_deref_dests[type] = image_deref;
               }
253

254
               if (in_var->data.access & ACCESS_NON_WRITEABLE) {
255 256 257
                  // Read of a read-only resource, convert to sampler fetch
                  assert(intrinsic->intrinsic == nir_intrinsic_image_deref_load);
                  b->cursor = nir_before_instr(&intrinsic->instr);
258 259

                  nir_deref_instr *deref = nir_src_as_deref(intrinsic->src[0]);
260
                  unsigned coord_comps = glsl_get_sampler_coordinate_components(deref->type);
261 262
                  nir_ssa_def *coord =
                     nir_channels(b, intrinsic->src[1].ssa, (1 << coord_comps) - 1);
263
                  nir_tex_instr *tex = nir_tex_instr_create(b->shader, 3);
264 265 266 267 268 269

                  tex->op = nir_texop_txf;
                  tex->is_array = glsl_sampler_type_is_array(in_var->type);
                  tex->sampler_dim = glsl_get_sampler_dim(in_var->type);
                  tex->src[0].src = nir_src_for_ssa(image_deref);
                  tex->src[0].src_type = nir_tex_src_texture_deref;
270
                  tex->src[1].src = nir_src_for_ssa(coord);
271
                  tex->src[1].src_type = nir_tex_src_coord;
272 273
                  tex->src[2].src = nir_src_for_ssa(nir_imm_int(b, 0));
                  tex->src[2].src_type = nir_tex_src_lod;
274 275 276 277 278 279 280
                  tex->coord_components = tex->src[1].src.ssa->num_components;
                  tex->dest_type = dest_type;
                  nir_ssa_dest_init(&tex->instr, &tex->dest, 4, 32, NULL);

                  nir_builder_instr_insert(b, &tex->instr);
                  nir_ssa_def_rewrite_uses(&intrinsic->dest.ssa, nir_src_for_ssa(&tex->dest.ssa));
                  nir_instr_remove(&intrinsic->instr);
281
               } else {
282 283 284
                  // Op on a writable image, leave as image intrinsic
                  nir_src uniform_src = nir_src_for_ssa(image_deref);
                  nir_instr_rewrite_src(&intrinsic->instr, src, uniform_src);
285
               }
286
               break;
287 288
            }

289
            case nir_intrinsic_image_deref_size: {
290 291 292 293 294 295
               nir_ssa_def *image_deref = NULL;
               for (unsigned i = 0; i < IMAGE_UNIFORM_TYPE_COUNT; ++i) {
                  if (uniform_deref_dests[i]) {
                     image_deref = uniform_deref_dests[i];
                     break;
                  }
296
               }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
               if (!image_deref) {
                  // Skip for now and come back to it
                  if (pass == 0)
                     break;

                  type = FLOAT4;
                  const struct glsl_type *new_var_type;
                  if (in_var->data.access & ACCESS_NON_WRITEABLE) {
                     image_deref = lower_read_only_image_deref(b, context, PIPE_FORMAT_R32G32B32A32_FLOAT);
                  } else {
                     image_deref = lower_read_write_image_deref(b, context, PIPE_FORMAT_R32G32B32A32_FLOAT);
                  }

                  uniform_deref_dests[type] = image_deref;
               }

313
               if (in_var->data.access & ACCESS_NON_WRITEABLE) {
314 315
                  // Size query on non-readable resource, convert to txs
                  b->cursor = nir_before_instr(&intrinsic->instr);
316
                  unsigned num_src = 2;
317 318 319 320 321 322 323
                  nir_tex_instr *tex = nir_tex_instr_create(b->shader, num_src);

                  tex->op = nir_texop_txs;
                  tex->is_array = glsl_sampler_type_is_array(in_var->type);
                  tex->sampler_dim = glsl_get_sampler_dim(in_var->type);
                  tex->src[0].src = nir_src_for_ssa(image_deref);
                  tex->src[0].src_type = nir_tex_src_texture_deref;
324 325
                  tex->src[1].src = nir_src_for_ssa(intrinsic->src[1].ssa);
                  tex->src[1].src_type = nir_tex_src_lod;
326 327 328 329 330 331
                  tex->dest_type = nir_type_uint;
                  nir_ssa_dest_init(&tex->instr, &tex->dest, nir_tex_instr_dest_size(tex), 32, NULL);

                  nir_builder_instr_insert(b, &tex->instr);
                  nir_ssa_def_rewrite_uses(&intrinsic->dest.ssa, nir_src_for_ssa(&tex->dest.ssa));
                  nir_instr_remove(&intrinsic->instr);
332
               } else {
333 334 335
                  // Op on a writable image, leave as image intrinsic
                  nir_src uniform_src = nir_src_for_ssa(image_deref);
                  nir_instr_rewrite_src(&intrinsic->instr, src, uniform_src);
336
               }
337
               break;
338 339
            }

340 341 342 343 344 345 346 347 348 349 350 351 352 353
            case nir_intrinsic_image_deref_format:
            case nir_intrinsic_image_deref_order: {
               nir_ssa_def **cached_deref = intrinsic->intrinsic == nir_intrinsic_image_deref_format ?
                  &format_deref_dest : &order_deref_dest;
               if (!*cached_deref) {
                  nir_variable *new_input = nir_variable_create(b->shader, nir_var_shader_in, glsl_uint_type(), NULL);
                  new_input->data.driver_location = in_var->data.driver_location;
                  if (intrinsic->intrinsic == nir_intrinsic_image_deref_format) {
                     /* Match cl_image_format { image_channel_order, image_channel_data_type }; */
                     new_input->data.driver_location += glsl_get_cl_size(new_input->type);
                  }

                  b->cursor = nir_after_instr(&context->deref->instr);
                  *cached_deref = nir_load_var(b, new_input);
354 355
               }

356 357
               /* No actual intrinsic needed here, just reference the loaded variable */
               nir_ssa_def_rewrite_uses(&intrinsic->dest.ssa, nir_src_for_ssa(*cached_deref));
358
               nir_instr_remove(&intrinsic->instr);
359
               break;
360 361
            }

362 363 364 365 366 367 368 369 370 371 372 373
            default:
               unreachable("Unsupported image intrinsic");
            }
         } else if (src->parent_instr->type == nir_instr_type_tex) {
            assert(in_var->data.access & ACCESS_NON_WRITEABLE);
            nir_tex_instr *tex = nir_instr_as_tex(src->parent_instr);

            switch (tex->dest_type) {
            case nir_type_float: type = FLOAT4; break;
            case nir_type_int: type = INT4; break;
            case nir_type_uint: type = UINT4; break;
            default: unreachable("Unsupported image format for sample.");
374 375
            }

376 377 378 379 380 381
            nir_ssa_def *image_deref = uniform_deref_dests[type];
            if (!image_deref) {
               enum pipe_format image_format = pipe_format_for_nir_format(tex->dest_type);
               image_deref = uniform_deref_dests[type] =
                  lower_read_only_image_deref(b, context, image_format);
            }
382

383 384
            nir_src uniform_src = nir_src_for_ssa(image_deref);
            nir_instr_rewrite_src(&tex->instr, src, uniform_src);
385
         }
386 387 388
      }
   }

389
   context->metadata->args[context->metadata_index].image.num_buf_ids = context->num_buf_ids;
390

391
   nir_instr_remove(&context->deref->instr);
392 393 394
   exec_node_remove(&in_var->node);
}

395 396
static void
clc_lower_images(nir_shader *nir, struct clc_image_lower_context *context)
397
{
398 399 400 401 402 403 404
   /* We'll do this in three steps:
    * 1. Change the deref mode for derefs of images/samplers to uniform.
    * 2. Run nir_opt_deref to remove casts, now that the deref modes match
    * 3. We should have unbroken deref chains from variables to their loads/stores,
    *    so follow those chains and adjust the variables to something saner.
    */

405 406 407 408 409 410 411 412 413 414 415
   nir_foreach_function(func, nir) {
      if (!func->is_entrypoint)
         continue;
      assert(func->impl);

      nir_builder b;
      nir_builder_init(&b, func->impl);

      nir_foreach_block(block, func->impl) {
         nir_foreach_instr_safe(instr, block) {
            if (instr->type == nir_instr_type_deref) {
416 417 418
               context->deref = nir_instr_as_deref(instr);

               if (context->deref->mode == nir_var_shader_in &&
419 420
                   (glsl_type_is_image(context->deref->type) ||
                    glsl_type_is_sampler(context->deref->type))) {
421
                  assert(context->deref->deref_type == nir_deref_type_var);
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
                  context->deref->mode = nir_var_uniform;

                  nir_variable *var = nir_deref_instr_get_variable(context->deref);
                  var->data.mode = nir_var_uniform;
                  exec_node_remove(&var->node);
                  nir_shader_add_variable(nir, var);
               }
            }
         }
      }
   }

   nir_opt_deref(nir);

   nir_foreach_function(func, nir) {
      if (!func->is_entrypoint)
         continue;
      assert(func->impl);

      nir_builder b;
      nir_builder_init(&b, func->impl);

      nir_foreach_block(block, func->impl) {
         nir_foreach_instr_safe(instr, block) {
            if (instr->type == nir_instr_type_deref) {
               context->deref = nir_instr_as_deref(instr);

               if (glsl_type_is_image(context->deref->type)) {
450
                  assert(context->deref->deref_type == nir_deref_type_var);
451
                  clc_lower_input_image_deref(&b, context);
452 453 454 455 456 457 458
               }
            }
         }
      }
   }
}

459 460 461 462 463 464 465 466 467 468 469 470 471
static void
clc_lower_64bit_semantics(nir_shader *nir)
{
   nir_foreach_function(func, nir) {
      nir_builder b;
      nir_builder_init(&b, func->impl);

      nir_foreach_block(block, func->impl) {
         nir_foreach_instr_safe(instr, block) {
            if (instr->type == nir_instr_type_intrinsic) {
               nir_intrinsic_instr *intrinsic = nir_instr_as_intrinsic(instr);
               switch (intrinsic->intrinsic) {
               case nir_intrinsic_load_global_invocation_id:
472 473
               case nir_intrinsic_load_global_invocation_id_zero_base:
               case nir_intrinsic_load_base_global_invocation_id:
474 475
               case nir_intrinsic_load_local_invocation_id:
               case nir_intrinsic_load_work_group_id:
476 477
               case nir_intrinsic_load_work_group_id_zero_base:
               case nir_intrinsic_load_base_work_group_id:
478
               case nir_intrinsic_load_num_work_groups:
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
                  break;
               default:
                  continue;
               }

               if (nir_instr_ssa_def(instr)->bit_size != 64)
                  continue;

               intrinsic->dest.ssa.bit_size = 32;
               b.cursor = nir_after_instr(instr);

               nir_ssa_def *i64 = nir_u2u64(&b, &intrinsic->dest.ssa);
               nir_ssa_def_rewrite_uses_after(
                  &intrinsic->dest.ssa,
                  nir_src_for_ssa(i64),
                  i64->parent_instr);
            }
         }
      }
   }
}

501
static void
502
clc_lower_nonnormalized_samplers(nir_shader *nir,
503
                                 const dxil_wrap_sampler_state *states)
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
{
   nir_foreach_function(func, nir) {
      if (!func->is_entrypoint)
         continue;
      assert(func->impl);

      nir_builder b;
      nir_builder_init(&b, func->impl);

      nir_foreach_block(block, func->impl) {
         nir_foreach_instr_safe(instr, block) {
            if (instr->type != nir_instr_type_tex)
               continue;
            nir_tex_instr *tex = nir_instr_as_tex(instr);

            int sampler_src_idx = nir_tex_instr_src_index(tex, nir_tex_src_sampler_deref);
            if (sampler_src_idx == -1)
               continue;

            nir_src *sampler_src = &tex->src[sampler_src_idx].src;
            assert(sampler_src->is_ssa && sampler_src->ssa->parent_instr->type == nir_instr_type_deref);
            nir_variable *sampler = nir_deref_instr_get_variable(
               nir_instr_as_deref(sampler_src->ssa->parent_instr));

528 529 530 531
            // If the sampler returns ints, we'll handle this in the int lowering pass
            if (nir_alu_type_get_base_type(tex->dest_type) != nir_type_float)
               continue;

532
            // If sampler uses normalized coords, nothing to do
533
            if (!states[sampler->data.binding].is_nonnormalized_coords)
534 535
               continue;

536 537
            b.cursor = nir_before_instr(&tex->instr);

538 539 540 541 542 543
            int coords_idx = nir_tex_instr_src_index(tex, nir_tex_src_coord);
            assert(coords_idx != -1);
            nir_ssa_def *coords =
               nir_ssa_for_src(&b, tex->src[coords_idx].src, tex->coord_components);

            nir_ssa_def *txs = nir_i2f32(&b, nir_get_texture_size(&b, tex));
544 545

            // Normalize coords for tex
546
            nir_ssa_def *scale = nir_frcp(&b, txs);
547 548 549
            nir_ssa_def *comps[4];
            for (unsigned i = 0; i < coords->num_components; ++i) {
               comps[i] = nir_channel(&b, coords, i);
550 551 552 553 554
               if (tex->is_array && i == coords->num_components - 1) {
                  // Don't scale the array index, but do clamp it
                  comps[i] = nir_fround_even(&b, comps[i]);
                  comps[i] = nir_fmax(&b, comps[i], nir_imm_float(&b, 0.0f));
                  comps[i] = nir_fmin(&b, comps[i], nir_fsub(&b, nir_channel(&b, txs, i), nir_imm_float(&b, 1.0f)));
555
                  break;
556
               }
557

558 559
               // The CTS is pretty clear that this value has to be floored for nearest sampling
               // but must not be for linear sampling.
560
               if (!states[sampler->data.binding].is_linear_filtering)
561
                  comps[i] = nir_fadd_imm(&b, nir_ffloor(&b, comps[i]), 0.5f);
562 563 564
               comps[i] = nir_fmul(&b, comps[i], nir_channel(&b, scale, i));
            }
            nir_ssa_def *normalized_coords = nir_vec(&b, comps, coords->num_components);
565 566
            nir_instr_rewrite_src(&tex->instr,
                                  &tex->src[coords_idx].src,
567
                                  nir_src_for_ssa(normalized_coords));
568 569 570 571 572 573
         }
      }
   }
}


574
struct clc_context *
575
clc_context_new(const struct clc_logger *logger)
576 577 578
{
   struct clc_context *ctx = calloc(1, sizeof(*ctx));
   if (!ctx) {
579
      clc_error(logger, "D3D12: failed to allocate a clc_context");
580 581 582
      return NULL;
   }

583 584 585
   const struct spirv_to_nir_options libclc_spirv_options = {
      .environment = NIR_SPIRV_OPENCL,
      .create_library = true,
586
      .constant_addr_format = nir_address_format_32bit_index_offset_pack64,
587 588 589
      .global_addr_format = nir_address_format_32bit_index_offset_pack64,
      .shared_addr_format = nir_address_format_32bit_offset_as_64bit,
      .temp_addr_format = nir_address_format_32bit_offset_as_64bit,
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
      .caps = {
         .address = true,
         .float64 = true,
         .int8 = true,
         .int16 = true,
         .int64 = true,
         .kernel = true,
      },
   };
   const struct nir_shader_compiler_options *libclc_nir_options =
      dxil_get_nir_compiler_options();

   glsl_type_singleton_init_or_ref();

   ctx->libclc_nir =
      spirv_to_nir((uint32_t *) libclc_spirv_bytecode,
                   sizeof(libclc_spirv_bytecode) / 4,
                   NULL, 0, MESA_SHADER_KERNEL, "libclc_spirv",
Jesse Natalie's avatar
Jesse Natalie committed
608
                   &libclc_spirv_options, libclc_nir_options);
609
   if (!ctx->libclc_nir) {
610
      clc_error(logger, "D3D12: spirv_to_nir failed on libclc blob");
611 612
      goto err_free_ctx;
   }
613
   ((nir_shader*)ctx->libclc_nir)->info.internal = true;
614 615 616 617
   NIR_PASS_V(ctx->libclc_nir, nir_lower_goto_ifs);
   NIR_PASS_V(ctx->libclc_nir, nir_lower_variable_initializers, nir_var_function_temp);
   NIR_PASS_V(ctx->libclc_nir, nir_lower_returns);

618
   return ctx;
619 620 621 622

err_free_ctx:
   free(ctx);
   return NULL;
623 624 625 626 627
}

void
clc_free_context(struct clc_context *ctx)
{
628
   ralloc_free(ctx->libclc_nir);
629
   free(ctx);
630
   glsl_type_singleton_decref();
631 632
};

633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
void clc_context_serialize(struct clc_context *context,
                           void **serialized,
                           size_t *serialized_size)
{
   struct blob tmp;
   blob_init(&tmp);
   nir_serialize(&tmp, context->libclc_nir, true);

   blob_finish_get_buffer(&tmp, serialized, serialized_size);
}

void clc_context_free_serialized(void *serialized)
{
   free(serialized);
}

struct clc_context *
   clc_context_deserialize(const void *serialized, size_t serialized_size)
{
   struct clc_context *ctx = calloc(1, sizeof(*ctx));
   if (!ctx) {
      return NULL;
   }
   const struct nir_shader_compiler_options *libclc_nir_options =
      dxil_get_nir_compiler_options();

   glsl_type_singleton_init_or_ref();

   struct blob_reader tmp;
   blob_reader_init(&tmp, serialized, serialized_size);

   ctx->libclc_nir = nir_deserialize(NULL, libclc_nir_options, &tmp);
   if (!ctx->libclc_nir) {
      free(ctx);
      return NULL;
   }

   return ctx;
}

void clc_context_optimize(struct clc_context *context)
{
   nir_shader *s = context->libclc_nir;

   bool progress;
   do {
      progress = false;
      NIR_PASS(progress, s, nir_split_var_copies);
      NIR_PASS(progress, s, nir_opt_copy_prop_vars);
      NIR_PASS(progress, s, nir_lower_var_copies);
      NIR_PASS(progress, s, nir_lower_vars_to_ssa);
      NIR_PASS(progress, s, nir_copy_prop);
      NIR_PASS(progress, s, nir_opt_remove_phis);
      NIR_PASS(progress, s, nir_opt_dce);
      NIR_PASS(progress, s, nir_opt_if, true);
      NIR_PASS(progress, s, nir_opt_dead_cf);
      NIR_PASS(progress, s, nir_opt_cse);
      NIR_PASS(progress, s, nir_opt_peephole_select, 8, true, true);
      NIR_PASS(progress, s, nir_opt_algebraic);
      NIR_PASS(progress, s, nir_opt_constant_folding);
      NIR_PASS(progress, s, nir_opt_undef);
      NIR_PASS(progress, s, nir_lower_undef_to_zero);
      NIR_PASS(progress, s, nir_opt_deref);
   } while (progress);
}

699
struct clc_object *
700 701
clc_compile(struct clc_context *ctx,
            const struct clc_compile_args *args,
702 703 704 705 706
            const struct clc_logger *logger)
{
   struct clc_object *obj;
   int ret;

707
   obj = calloc(1, sizeof(*obj));
708
   if (!obj) {
709
      clc_error(logger, "D3D12: failed to allocate a clc_object");
710 711 712
      return NULL;
   }

713
   ret = clc_to_spirv(args, &obj->spvbin, logger);
714 715 716 717 718
   if (ret < 0) {
      free(obj);
      return NULL;
   }

719 720 721
   if (debug_get_option_debug_clc() & CLC_DEBUG_DUMP_SPIRV)
      clc_dump_spirv(&obj->spvbin, stdout);

722
   return obj;
723 724 725
}

struct clc_object *
726
clc_link(struct clc_context *ctx,
727
         const struct clc_linker_args *args,
728 729 730 731 732 733 734
         const struct clc_logger *logger)
{
   struct clc_object *out_obj;
   int ret;

   out_obj = malloc(sizeof(*out_obj));
   if (!out_obj) {
735
      clc_error(logger, "failed to allocate a clc_object");
736 737 738
      return NULL;
   }

739
   ret = clc_link_spirv_binaries(args, &out_obj->spvbin, logger);
740 741 742 743 744
   if (ret < 0) {
      free(out_obj);
      return NULL;
   }

745 746 747
   if (debug_get_option_debug_clc() & CLC_DEBUG_DUMP_SPIRV)
      clc_dump_spirv(&out_obj->spvbin, stdout);

748 749 750
   out_obj->kernels = clc_spirv_get_kernels_info(&out_obj->spvbin,
                                                 &out_obj->num_kernels);

751 752 753
   if (debug_get_option_debug_clc() & CLC_DEBUG_VERBOSE)
      clc_print_kernels_info(out_obj);

754
   return out_obj;
755 756 757 758
}

void clc_free_object(struct clc_object *obj)
{
759
   clc_free_kernels_info(obj->kernels, obj->num_kernels);
760 761 762 763
   clc_free_spirv_binary(&obj->spvbin);
   free(obj);
}

764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
static nir_variable *
add_kernel_inputs_var(struct clc_dxil_object *dxil, nir_shader *nir,
                      unsigned *cbv_id)
{
   if (!dxil->kernel->num_args)
      return NULL;

   struct clc_dxil_metadata *metadata = &dxil->metadata;
   unsigned size = 0;

   nir_foreach_variable(var, &nir->inputs)
      size = MAX2(size,
                  var->data.driver_location +
                  glsl_get_cl_size(var->type));

   size = align(size, 4);

   nir_variable *var =
      nir_variable_create(nir, nir_var_mem_ubo,
                          glsl_array_type(glsl_uint_type(),
                                          size / 4, 0),
                          "kernel_inputs");
   var->data.binding = (*cbv_id)++;
   var->data.how_declared = nir_var_hidden;
   return var;
}

static nir_variable *
792
add_work_properties_var(struct clc_dxil_object *dxil,
793 794 795 796 797
                           struct nir_shader *nir, unsigned *cbv_id)
{
   struct clc_dxil_metadata *metadata = &dxil->metadata;
   nir_variable *var =
      nir_variable_create(nir, nir_var_mem_ubo,
798 799 800
                          glsl_array_type(glsl_uint_type(),
                                          sizeof(struct clc_work_properties_data) / sizeof(unsigned),
                                          0),
801
                          "kernel_work_properies");
802 803 804 805 806
   var->data.binding = (*cbv_id)++;
   var->data.how_declared = nir_var_hidden;
   return var;
}

807
static void
808
clc_lower_constant_to_ssbo(nir_shader *nir,
809 810 811 812 813 814 815 816 817 818 819 820
                      const struct clc_kernel_info *kerninfo, unsigned *uav_id)
{
   /* First mark constant inputs as global inputs. */
   for (unsigned i = 0; i < kerninfo->num_args; i++) {
      if (kerninfo->args[i].address_qualifier == CLC_KERNEL_ARG_ADDRESS_CONSTANT) {
         assert(!(nir->info.cs.global_inputs & BITFIELD_BIT(i)));
         nir->info.cs.global_inputs |= BITFIELD_BIT(i);
      }
   }

   /* Update UBO vars and assign them a binding. */
   nir_foreach_variable(var, &nir->uniforms) {
821
      if (var->data.mode == nir_var_mem_constant) {
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
         var->data.mode = nir_var_mem_ssbo;
         var->data.binding = (*uav_id)++;
      }
   }

   /* And finally patch all the derefs referincing the constant
    * variables/pointers.
    */
   nir_foreach_function(func, nir) {
      if (!func->is_entrypoint)
         continue;

      assert(func->impl);

      nir_builder b;
      nir_builder_init(&b, func->impl);

      nir_foreach_block(block, func->impl) {
840
         nir_foreach_instr(instr, block) {
841 842 843 844 845
            if (instr->type != nir_instr_type_deref)
               continue;

            nir_deref_instr *deref = nir_instr_as_deref(instr);

846
            if (deref->mode != nir_var_mem_constant)
847 848 849 850 851 852 853 854
               continue;

            deref->mode = nir_var_mem_ssbo;
         }
      }
   }
}

855 856 857 858 859 860 861 862 863 864
static void
clc_lower_global_to_ssbo(nir_shader *nir)
{
   nir_foreach_function(func, nir) {
      if (!func->is_entrypoint)
         continue;

      assert(func->impl);

      nir_foreach_block(block, func->impl) {
865
         nir_foreach_instr(instr, block) {
866 867 868 869 870 871 872 873 874 875 876 877 878 879
            if (instr->type != nir_instr_type_deref)
               continue;

            nir_deref_instr *deref = nir_instr_as_deref(instr);

            if (deref->mode != nir_var_mem_global)
               continue;

            deref->mode = nir_var_mem_ssbo;
         }
      }
   }
}

880 881 882 883 884 885 886 887
static void
copy_const_initializer(const nir_constant *constant, const struct glsl_type *type,
                       uint8_t *data)
{
   unsigned size = glsl_get_cl_size(type);

   if (glsl_type_is_array(type)) {
      const struct glsl_type *elm_type = glsl_get_array_element(type);
888
      unsigned step_size = glsl_get_explicit_stride(type);
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925

      for (unsigned i = 0; i < constant->num_elements; i++) {
         copy_const_initializer(constant->elements[i], elm_type,
                                data + (i * step_size));
      }
   } else if (glsl_type_is_struct(type)) {
      for (unsigned i = 0; i < constant->num_elements; i++) {
         const struct glsl_type *elm_type = glsl_get_struct_field(type, i);
         int offset = glsl_get_struct_field_offset(type, i);
         copy_const_initializer(constant->elements[i], elm_type, data + offset);
      }
   } else {
      assert(glsl_type_is_vector_or_scalar(type));

      for (unsigned i = 0; i < glsl_get_components(type); i++) {
         switch (glsl_get_bit_size(type)) {
         case 64:
            *((uint64_t *)data) = constant->values[i].u64;
            break;
         case 32:
            *((uint32_t *)data) = constant->values[i].u32;
            break;
         case 16:
            *((uint16_t *)data) = constant->values[i].u16;
            break;
         case 8:
            *((uint8_t *)data) = constant->values[i].u8;
            break;
         default:
            unreachable("Invalid base type");
         }

         data += glsl_get_bit_size(type) / 8;
      }
   }
}

926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
static const struct glsl_type *
get_cast_type(unsigned bit_size)
{
   switch (bit_size) {
   case 64:
      return glsl_int64_t_type();
   case 32:
      return glsl_int_type();
   case 16:
      return glsl_int16_t_type();
   case 8:
      return glsl_int8_t_type();
   }
   unreachable("Invalid bit_size");
}

942
static void
943
split_unaligned_load(nir_builder *b, nir_intrinsic_instr *intrin, unsigned alignment)
944 945 946 947 948 949 950 951 952
{
   enum gl_access_qualifier access = nir_intrinsic_access(intrin);
   nir_ssa_def *srcs[NIR_MAX_VEC_COMPONENTS * NIR_MAX_VEC_COMPONENTS * sizeof(int64_t) / 8];
   unsigned comp_size = intrin->dest.ssa.bit_size / 8;
   unsigned num_comps = intrin->dest.ssa.num_components;

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

   nir_deref_instr *ptr = nir_src_as_deref(intrin->src[0]);
953

954
   const struct glsl_type *cast_type = get_cast_type(alignment * 8);
955 956 957 958 959
   nir_deref_instr *cast = nir_build_deref_cast(b, &ptr->dest.ssa, ptr->mode, cast_type, alignment);

   unsigned num_loads = DIV_ROUND_UP(comp_size * num_comps, alignment);
   for (unsigned i = 0; i < num_loads; ++i) {
      nir_deref_instr *elem = nir_build_deref_ptr_as_array(b, cast, nir_imm_intN_t(b, i, cast->dest.ssa.bit_size));
960
      srcs[i] = nir_load_deref_with_access(b, elem, access);
961 962 963 964 965 966 967 968
   }

   nir_ssa_def *new_dest = nir_extract_bits(b, srcs, num_loads, 0, num_comps, intrin->dest.ssa.bit_size);
   nir_ssa_def_rewrite_uses(&intrin->dest.ssa, nir_src_for_ssa(new_dest));
   nir_instr_remove(&intrin->instr);
}

static void
969
split_unaligned_store(nir_builder *b, nir_intrinsic_instr *intrin, unsigned alignment)
970 971 972 973 974 975 976
{
   enum gl_access_qualifier access = nir_intrinsic_access(intrin);

   assert(intrin->src[1].is_ssa);
   nir_ssa_def *value = intrin->src[1].ssa;
   unsigned comp_size = value->bit_size / 8;
   unsigned num_comps = value->num_components;
977

978 979 980
   b->cursor = nir_before_instr(&intrin->instr);

   nir_deref_instr *ptr = nir_src_as_deref(intrin->src[0]);
981

982
   const struct glsl_type *cast_type = get_cast_type(alignment * 8);
983 984 985 986 987 988
   nir_deref_instr *cast = nir_build_deref_cast(b, &ptr->dest.ssa, ptr->mode, cast_type, alignment);

   unsigned num_stores = DIV_ROUND_UP(comp_size * num_comps, alignment);
   for (unsigned i = 0; i < num_stores; ++i) {
      nir_ssa_def *substore_val = nir_extract_bits(b, &value, 1, i * alignment * 8, 1, alignment * 8);
      nir_deref_instr *elem = nir_build_deref_ptr_as_array(b, cast, nir_imm_intN_t(b, i, cast->dest.ssa.bit_size));
989
      nir_store_deref_with_access(b, elem, substore_val, ~0, access);
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
   }

   nir_instr_remove(&intrin->instr);
}

static bool
split_unaligned_loads_stores(nir_shader *shader)
{
   bool progress = false;

   nir_foreach_function(function, shader) {
      if (!function->impl)
         continue;

      nir_builder b;
      nir_builder_init(&b, function->impl);

      nir_foreach_block(block, function->impl) {
         nir_foreach_instr_safe(instr, block) {
            if (instr->type != nir_instr_type_intrinsic)
               continue;
            nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
            if (intrin->intrinsic != nir_intrinsic_load_deref &&
                intrin->intrinsic != nir_intrinsic_store_deref)
               continue;
1015 1016
            nir_deref_instr *deref = nir_src_as_deref(intrin->src[0]);

1017 1018 1019 1020 1021 1022 1023
            unsigned align_mul = 0, align_offset = 0;
            nir_get_explicit_deref_align(deref, true, &align_mul, &align_offset);

            unsigned alignment = align_offset ? 1 << (ffs(align_offset) - 1) : align_mul;

            /* We can load anything at 4-byte alignment, except for 
             * UBOs (AKA CBs where the granularity is 16 bytes).
1024
             */
1025
            if (alignment >= (deref->mode == nir_var_mem_ubo ? 16 : 4))
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
               continue;

            nir_ssa_def *val;
            if (intrin->intrinsic == nir_intrinsic_load_deref) {
               assert(intrin->dest.is_ssa);
               val = &intrin->dest.ssa;
            } else {
               assert(intrin->src[1].is_ssa);
               val = intrin->src[1].ssa;
            }

            unsigned natural_alignment =
               val->bit_size / 8 *
               (val->num_components == 3 ? 4 : val->num_components);

            if (alignment >= natural_alignment)
               continue;

            if (intrin->intrinsic == nir_intrinsic_load_deref)
1045
               split_unaligned_load(&b, intrin, alignment);
1046
            else
1047
               split_unaligned_store(&b, intrin, alignment);
1048 1049 1050 1051 1052 1053 1054 1055
            progress = true;
         }
      }
   }

   return progress;
}

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
static enum pipe_tex_wrap
wrap_from_cl_addressing(unsigned addressing_mode)
{
   switch (addressing_mode)
   {
   default:
   case ADDRESSING_MODE_NONE:
   case ADDRESSING_MODE_CLAMP:
      // Since OpenCL's only border color is 0's and D3D specs out-of-bounds loads to return 0, don't apply any wrap mode
      return (enum pipe_tex_wrap)-1;
   case ADDRESSING_MODE_CLAMP_TO_EDGE: return PIPE_TEX_WRAP_CLAMP_TO_EDGE;
   case ADDRESSING_MODE_REPEAT: return PIPE_TEX_WRAP_REPEAT;
   case ADDRESSING_MODE_REPEAT_MIRRORED: return PIPE_TEX_WRAP_MIRROR_REPEAT;
   }
}

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
static bool shader_has_double(nir_shader *nir)
{
   bool progress = false;

   foreach_list_typed(nir_function, func, node, &nir->functions) {
      if (!func->is_entrypoint)
         continue;

      assert(func->impl);

      nir_foreach_block(block, func->impl) {
         nir_foreach_instr_safe(instr, block) {
            if (instr->type != nir_instr_type_alu)
               continue;

             nir_alu_instr *alu = nir_instr_as_alu(instr);
             const nir_op_info *info = &nir_op_infos[alu->op];

             if (info->output_type & nir_type_float &&
                 nir_dest_bit_size(alu->dest.dest) == 64)
                 return true;
         }
      }
   }

   return false;
}

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
static bool
scale_fdiv(nir_shader *nir)
{
   bool progress = false;
   nir_foreach_function(func, nir) {
      if (!func->impl)
         continue;
      nir_builder b;
      nir_builder_init(&b, func->impl);
      nir_foreach_block(block, func->impl) {
         nir_foreach_instr(instr, block) {
            if (instr->type != nir_instr_type_alu)
               continue;
            nir_alu_instr *alu = nir_instr_as_alu(instr);
            if (alu->op != nir_op_fdiv)
               continue;

            b.cursor = nir_before_instr(instr);
            nir_ssa_def *fabs = nir_fabs(&b, alu->src[1].src.ssa);
            nir_ssa_def *big = nir_flt(&b, nir_imm_int(&b, 0x7e800000), fabs);
            nir_ssa_def *small = nir_flt(&b, fabs, nir_imm_int(&b, 0x00800000));

            nir_ssa_def *scaled_down_a = nir_fmul_imm(&b, alu->src[0].src.ssa, 0.25);
            nir_ssa_def *scaled_down_b = nir_fmul_imm(&b, alu->src[1].src.ssa, 0.25);
            nir_ssa_def *scaled_up_a = nir_fmul_imm(&b, alu->src[0].src.ssa, 16777216.0);
            nir_ssa_def *scaled_up_b = nir_fmul_imm(&b, alu->src[1].src.ssa, 16777216.0);

            nir_ssa_def *final_a =
               nir_bcsel(&b, big, scaled_down_a,
              (nir_bcsel(&b, small, scaled_up_a, alu->src[0].src.ssa)));
            nir_ssa_def *final_b =
               nir_bcsel(&b, big, scaled_down_b,
              (nir_bcsel(&b, small, scaled_up_b, alu->src[1].src.ssa)));

            nir_instr_rewrite_src(instr, &alu->src[0].src, nir_src_for_ssa(final_a));
            nir_instr_rewrite_src(instr, &alu->src[1].src, nir_src_for_ssa(final_b));
            progress = true;
         }
      }
   }
   return progress;
}

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
static bool
clc_opt_vec4_cast_of_vec3(nir_shader *nir)
{
   bool progress = false;
   nir_foreach_function(func, nir) {
      if (!func->impl)
         continue;
      nir_foreach_block(block, func->impl) {
         nir_foreach_instr_safe(instr, block) {
            if (instr->type != nir_instr_type_intrinsic)
               continue;

            nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
            if (intr->intrinsic != nir_intrinsic_store_deref &&
                 intr->intrinsic != nir_intrinsic_load_deref)
               continue;

            nir_ssa_def *value = intr->intrinsic == nir_intrinsic_store_deref ?
               intr->src[1].ssa : &intr->dest.ssa;
            if (value->num_components != 4)
               continue;

            if (intr->intrinsic == nir_intrinsic_store_deref) {
               if (value->parent_instr->type != nir_instr_type_alu ||
                   nir_instr_as_alu(value->parent_instr)->op != nir_op_vec4)
                  continue;

               nir_alu_instr *vec = nir_instr_as_alu(value->parent_instr);
               if (vec->src[3].src.ssa->parent_instr->type != nir_instr_type_ssa_undef)
                  continue;
            }

            nir_deref_instr *dest = nir_src_as_deref(intr->src[0]);
            if (dest->deref_type != nir_deref_type_cast)
               continue;

            nir_deref_instr *cast_src = nir_deref_instr_parent(dest);
            if (!cast_src || cast_src->deref_type != nir_deref_type_var)
               continue;

            nir_variable *var = cast_src->var;
            if (!glsl_type_is_vector(var->type) || glsl_get_vector_elements(var->type) != 3)
               continue;

            nir_builder b;
            nir_builder_init(&b, func->impl);
            b.cursor = nir_before_instr(instr);

            nir_instr_rewrite_src(instr, &intr->src[0], nir_src_for_ssa(&cast_src->dest.ssa));
            intr->num_components = 3;

            if (intr->intrinsic == nir_intrinsic_store_deref) {
               nir_instr_rewrite_src(instr, &intr->src[1], nir_src_for_ssa(nir_channels(&b, value, 0x7)));
               nir_intrinsic_set_write_mask(intr, 0x7);
            } else {
               b.cursor = nir_after_instr(instr);
               value->num_components = 3;
               nir_ssa_def *vec4 = nir_vec4(&b, nir_channel(&b, value, 0),
                                                nir_channel(&b, value, 1),
                                                nir_channel(&b, value, 2),
                                                nir_ssa_undef(&b, 1, value->bit_size));
               nir_ssa_def_rewrite_uses_after(value, nir_src_for_ssa(vec4), vec4->parent_instr);
            }
            progress = true;
         }

         nir_metadata_preserve(func->impl, nir_metadata_block_index | nir_metadata_dominance | nir_metadata_loop_analysis);
      }
   }

   return progress;
}

1216
struct clc_dxil_object *
1217 1218
clc_to_dxil(struct clc_context *ctx,
            const struct clc_object *obj,
1219
            const char *entrypoint,
1220
            const struct clc_runtime_kernel_conf *conf,