summaryrefslogtreecommitdiffstats
path: root/src/freedreno/vulkan/tu_shader.c
blob: 2b68aeafffb399e968c0bcabdd4132c3e91a25dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*
 * Copyright © 2019 Google LLC
 *
 * 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
 * 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:
 *
 * 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,
 * 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.
 */

#include "tu_private.h"

#include "spirv/nir_spirv.h"
#include "util/mesa-sha1.h"

#include "ir3/ir3_nir.h"

static nir_shader *
tu_spirv_to_nir(struct ir3_compiler *compiler,
                const uint32_t *words,
                size_t word_count,
                gl_shader_stage stage,
                const char *entry_point_name,
                const VkSpecializationInfo *spec_info)
{
   /* TODO these are made-up */
   const struct spirv_to_nir_options spirv_options = {
      .lower_ubo_ssbo_access_to_offsets = true,
      .caps = { false },
   };
   const nir_shader_compiler_options *nir_options =
      ir3_get_compiler_options(compiler);

   /* convert VkSpecializationInfo */
   struct nir_spirv_specialization *spec = NULL;
   uint32_t num_spec = 0;
   if (spec_info && spec_info->mapEntryCount) {
      spec = malloc(sizeof(*spec) * spec_info->mapEntryCount);
      if (!spec)
         return NULL;

      for (uint32_t i = 0; i < spec_info->mapEntryCount; i++) {
         const VkSpecializationMapEntry *entry = &spec_info->pMapEntries[i];
         const void *data = spec_info->pData + entry->offset;
         assert(data + entry->size <= spec_info->pData + spec_info->dataSize);
         spec[i].id = entry->constantID;
         if (entry->size == 8)
            spec[i].data64 = *(const uint64_t *) data;
         else
            spec[i].data32 = *(const uint32_t *) data;
         spec[i].defined_on_module = false;
      }

      num_spec = spec_info->mapEntryCount;
   }

   nir_shader *nir =
      spirv_to_nir(words, word_count, spec, num_spec, stage, entry_point_name,
                   &spirv_options, nir_options);

   free(spec);

   assert(nir->info.stage == stage);
   nir_validate_shader(nir, "after spirv_to_nir");

   return nir;
}

static void
tu_sort_variables_by_location(struct exec_list *variables)
{
   struct exec_list sorted;
   exec_list_make_empty(&sorted);

   nir_foreach_variable_safe(var, variables)
   {
      exec_node_remove(&var->node);

      /* insert the variable into the sorted list */
      nir_variable *next = NULL;
      nir_foreach_variable(tmp, &sorted)
      {
         if (var->data.location < tmp->data.location) {
            next = tmp;
            break;
         }
      }
      if (next)
         exec_node_insert_node_before(&next->node, &var->node);
      else
         exec_list_push_tail(&sorted, &var->node);
   }

   exec_list_move_nodes_to(&sorted, variables);
}

static unsigned
map_add(struct tu_descriptor_map *map, int set, int binding)
{
   unsigned index;
   for (index = 0; index < map->num; index++) {
      if (set == map->set[index] && binding == map->binding[index])
         break;
   }

   assert(index < ARRAY_SIZE(map->set));

   map->set[index] = set;
   map->binding[index] = binding;
   map->num = MAX2(map->num, index + 1);
   return index;
}

static void
lower_tex_src_to_offset(nir_tex_instr *instr, unsigned src_idx,
                        struct tu_shader *shader, bool is_sampler)
{
   nir_deref_instr *deref =
      nir_instr_as_deref(instr->src[src_idx].src.ssa->parent_instr);

   if (deref->deref_type != nir_deref_type_var) {
      tu_finishme("sampler array");
      return;
   }

   if (is_sampler) {
      instr->sampler_index = map_add(&shader->sampler_map,
                                     deref->var->data.descriptor_set,
                                     deref->var->data.binding);
   } else {
      instr->texture_index = map_add(&shader->texture_map,
                                     deref->var->data.descriptor_set,
                                     deref->var->data.binding);
      instr->texture_array_size = 1;
   }

   nir_tex_instr_remove_src(instr, src_idx);
}

static bool
lower_sampler(nir_tex_instr *instr, struct tu_shader *shader)
{
   int texture_idx =
      nir_tex_instr_src_index(instr, nir_tex_src_texture_deref);

   if (texture_idx >= 0)
      lower_tex_src_to_offset(instr, texture_idx, shader, false);

   int sampler_idx =
      nir_tex_instr_src_index(instr, nir_tex_src_sampler_deref);

   if (sampler_idx >= 0)
      lower_tex_src_to_offset(instr, sampler_idx, shader, true);

   if (texture_idx < 0 && sampler_idx < 0)
      return false;

   return true;
}

static bool
lower_intrinsic(nir_builder *b, nir_intrinsic_instr *instr,
                struct tu_shader *shader)
{
   if (instr->intrinsic != nir_intrinsic_vulkan_resource_index)
      return false;

   nir_const_value *const_val = nir_src_as_const_value(instr->src[0]);
   if (!const_val || const_val->u32 != 0) {
      tu_finishme("non-zero vulkan_resource_index array index");
      return false;
   }

   if (nir_intrinsic_desc_type(instr) != VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) {
      tu_finishme("non-ubo vulkan_resource_index");
      return false;
   }

   unsigned index = map_add(&shader->ubo_map,
                            nir_intrinsic_desc_set(instr),
                            nir_intrinsic_binding(instr));

   b->cursor = nir_before_instr(&instr->instr);
   /* skip index 0 because ir3 treats it differently */
   nir_ssa_def_rewrite_uses(&instr->dest.ssa,
                            nir_src_for_ssa(nir_imm_int(b, index + 1)));
   nir_instr_remove(&instr->instr);

   return true;
}

static bool
lower_impl(nir_function_impl *impl, struct tu_shader *shader)
{
   nir_builder b;
   nir_builder_init(&b, impl);
   bool progress = false;

   nir_foreach_block(block, impl) {
      nir_foreach_instr_safe(instr, block) {
         switch (instr->type) {
         case nir_instr_type_tex:
            progress |= lower_sampler(nir_instr_as_tex(instr), shader);
            break;
         case nir_instr_type_intrinsic:
            progress |= lower_intrinsic(&b, nir_instr_as_intrinsic(instr), shader);
            break;
         default:
            break;
         }
      }
   }

   return progress;
}

static bool
tu_lower_io(nir_shader *shader, struct tu_shader *tu_shader)
{
   bool progress = false;

   nir_foreach_function(function, shader) {
      if (function->impl)
         progress |= lower_impl(function->impl, tu_shader);
   }

   return progress;
}

struct tu_shader *
tu_shader_create(struct tu_device *dev,
                 gl_shader_stage stage,
                 const VkPipelineShaderStageCreateInfo *stage_info,
                 const VkAllocationCallbacks *alloc)
{
   const struct tu_shader_module *module =
      tu_shader_module_from_handle(stage_info->module);
   struct tu_shader *shader;

   const uint32_t max_variant_count = (stage == MESA_SHADER_VERTEX) ? 2 : 1;
   shader = vk_zalloc2(
      &dev->alloc, alloc,
      sizeof(*shader) + sizeof(struct ir3_shader_variant) * max_variant_count,
      8, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
   if (!shader)
      return NULL;

   /* translate SPIR-V to NIR */
   assert(module->code_size % 4 == 0);
   nir_shader *nir = tu_spirv_to_nir(
      dev->compiler, (const uint32_t *) module->code, module->code_size / 4,
      stage, stage_info->pName, stage_info->pSpecializationInfo);
   if (!nir) {
      vk_free2(&dev->alloc, alloc, shader);
      return NULL;
   }

   if (unlikely(dev->physical_device->instance->debug_flags & TU_DEBUG_NIR)) {
      fprintf(stderr, "translated nir:\n");
      nir_print_shader(nir, stderr);
   }

   /* TODO what needs to happen? */

   switch (stage) {
   case MESA_SHADER_VERTEX:
      tu_sort_variables_by_location(&nir->outputs);
      break;
   case MESA_SHADER_TESS_CTRL:
   case MESA_SHADER_TESS_EVAL:
   case MESA_SHADER_GEOMETRY:
      tu_sort_variables_by_location(&nir->inputs);
      tu_sort_variables_by_location(&nir->outputs);
      break;
   case MESA_SHADER_FRAGMENT:
      tu_sort_variables_by_location(&nir->inputs);
      break;
   case MESA_SHADER_COMPUTE:
      break;
   default:
      unreachable("invalid gl_shader_stage");
      break;
   }

   nir_assign_var_locations(&nir->inputs, &nir->num_inputs,
                            ir3_glsl_type_size);
   nir_assign_var_locations(&nir->outputs, &nir->num_outputs,
                            ir3_glsl_type_size);
   nir_assign_var_locations(&nir->uniforms, &nir->num_uniforms,
                            ir3_glsl_type_size);

   NIR_PASS_V(nir, nir_opt_copy_prop_vars);

   NIR_PASS_V(nir, nir_lower_system_values);
   NIR_PASS_V(nir, nir_lower_frexp);

   NIR_PASS_V(nir, tu_lower_io, shader);

   NIR_PASS_V(nir, nir_lower_io, nir_var_all, ir3_glsl_type_size, 0);

   nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));

   shader->ir3_shader.compiler = dev->compiler;
   shader->ir3_shader.type = stage;
   shader->ir3_shader.nir = nir;

   return shader;
}

void
tu_shader_destroy(struct tu_device *dev,
                  struct tu_shader *shader,
                  const VkAllocationCallbacks *alloc)
{
   if (shader->ir3_shader.nir)
      ralloc_free(shader->ir3_shader.nir);

   for (uint32_t i = 0; i < 1 + shader->has_binning_pass; i++) {
      if (shader->variants[i].ir)
         ir3_destroy(shader->variants[i].ir);
   }

   if (shader->ir3_shader.const_state.immediates)
	   free(shader->ir3_shader.const_state.immediates);
   if (shader->binary)
      free(shader->binary);
   if (shader->binning_binary)
      free(shader->binning_binary);

   vk_free2(&dev->alloc, alloc, shader);
}

void
tu_shader_compile_options_init(
   struct tu_shader_compile_options *options,
   const VkGraphicsPipelineCreateInfo *pipeline_info)
{
   *options = (struct tu_shader_compile_options) {
      /* TODO ir3_key */

      .optimize = !(pipeline_info->flags &
                    VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT),
      .include_binning_pass = true,
   };
}

static uint32_t *
tu_compile_shader_variant(struct ir3_shader *shader,
                          const struct ir3_shader_key *key,
                          struct ir3_shader_variant *nonbinning,
                          struct ir3_shader_variant *variant)
{
   variant->shader = shader;
   variant->type = shader->type;
   variant->key = *key;
   variant->binning_pass = !!nonbinning;
   variant->nonbinning = nonbinning;

   int ret = ir3_compile_shader_nir(shader->compiler, variant);
   if (ret)
      return NULL;

   /* when assemble fails, we rely on tu_shader_destroy to clean up the
    * variant
    */
   return ir3_shader_assemble(variant, shader->compiler->gpu_id);
}

VkResult
tu_shader_compile(struct tu_device *dev,
                  struct tu_shader *shader,
                  const struct tu_shader *next_stage,
                  const struct tu_shader_compile_options *options,
                  const VkAllocationCallbacks *alloc)
{
   if (options->optimize) {
      /* ignore the key for the first pass of optimization */
      ir3_optimize_nir(&shader->ir3_shader, shader->ir3_shader.nir, NULL);

      if (unlikely(dev->physical_device->instance->debug_flags &
                   TU_DEBUG_NIR)) {
         fprintf(stderr, "optimized nir:\n");
         nir_print_shader(shader->ir3_shader.nir, stderr);
      }
   }

   shader->binary = tu_compile_shader_variant(
      &shader->ir3_shader, &options->key, NULL, &shader->variants[0]);
   if (!shader->binary)
      return VK_ERROR_OUT_OF_HOST_MEMORY;

   /* compile another variant for the binning pass */
   if (options->include_binning_pass &&
       shader->ir3_shader.type == MESA_SHADER_VERTEX) {
      shader->binning_binary = tu_compile_shader_variant(
         &shader->ir3_shader, &options->key, &shader->variants[0],
         &shader->variants[1]);
      if (!shader->binning_binary)
         return VK_ERROR_OUT_OF_HOST_MEMORY;

      shader->has_binning_pass = true;
   }

   if (unlikely(dev->physical_device->instance->debug_flags & TU_DEBUG_IR3)) {
      fprintf(stderr, "disassembled ir3:\n");
      fprintf(stderr, "shader: %s\n",
              gl_shader_stage_name(shader->ir3_shader.type));
      ir3_shader_disasm(&shader->variants[0], shader->binary, stderr);

      if (shader->has_binning_pass) {
         fprintf(stderr, "disassembled ir3:\n");
         fprintf(stderr, "shader: %s (binning)\n",
                 gl_shader_stage_name(shader->ir3_shader.type));
         ir3_shader_disasm(&shader->variants[1], shader->binning_binary,
                           stderr);
      }
   }

   return VK_SUCCESS;
}

VkResult
tu_CreateShaderModule(VkDevice _device,
                      const VkShaderModuleCreateInfo *pCreateInfo,
                      const VkAllocationCallbacks *pAllocator,
                      VkShaderModule *pShaderModule)
{
   TU_FROM_HANDLE(tu_device, device, _device);
   struct tu_shader_module *module;

   assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
   assert(pCreateInfo->flags == 0);
   assert(pCreateInfo->codeSize % 4 == 0);

   module = vk_alloc2(&device->alloc, pAllocator,
                      sizeof(*module) + pCreateInfo->codeSize, 8,
                      VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
   if (module == NULL)
      return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);

   module->code_size = pCreateInfo->codeSize;
   memcpy(module->code, pCreateInfo->pCode, pCreateInfo->codeSize);

   _mesa_sha1_compute(module->code, module->code_size, module->sha1);

   *pShaderModule = tu_shader_module_to_handle(module);

   return VK_SUCCESS;
}

void
tu_DestroyShaderModule(VkDevice _device,
                       VkShaderModule _module,
                       const VkAllocationCallbacks *pAllocator)
{
   TU_FROM_HANDLE(tu_device, device, _device);
   TU_FROM_HANDLE(tu_shader_module, module, _module);

   if (!module)
      return;

   vk_free2(&device->alloc, pAllocator, module);
}