• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2012 Advanced Micro Devices, Inc.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * on the rights to use, copy, modify, merge, publish, distribute, sub
9  * license, and/or sell copies of the Software, and to permit persons to whom
10  * the Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22  * USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24 
25 #include "ac_nir.h"
26 #include "ac_shader_util.h"
27 #include "compiler/nir/nir_serialize.h"
28 #include "nir/tgsi_to_nir.h"
29 #include "si_build_pm4.h"
30 #include "sid.h"
31 #include "util/crc32.h"
32 #include "util/disk_cache.h"
33 #include "util/hash_table.h"
34 #include "util/mesa-sha1.h"
35 #include "util/u_async_debug.h"
36 #include "util/u_memory.h"
37 #include "util/u_prim.h"
38 #include "tgsi/tgsi_from_mesa.h"
39 
si_determine_wave_size(struct si_screen * sscreen,struct si_shader * shader)40 unsigned si_determine_wave_size(struct si_screen *sscreen, struct si_shader *shader)
41 {
42    /* There are a few uses that pass shader=NULL here, expecting the default compute wave size. */
43    struct si_shader_info *info = shader ? &shader->selector->info : NULL;
44    gl_shader_stage stage = shader ? shader->selector->stage : MESA_SHADER_COMPUTE;
45 
46    if (sscreen->info.gfx_level < GFX10)
47       return 64;
48 
49    /* Legacy GS only supports Wave64. */
50    if ((stage == MESA_SHADER_VERTEX && shader->key.ge.as_es && !shader->key.ge.as_ngg) ||
51        (stage == MESA_SHADER_TESS_EVAL && shader->key.ge.as_es && !shader->key.ge.as_ngg) ||
52        (stage == MESA_SHADER_GEOMETRY && !shader->key.ge.as_ngg))
53       return 64;
54 
55    /* Small workgroups use Wave32 unconditionally. */
56    if (stage == MESA_SHADER_COMPUTE && info &&
57        !info->base.workgroup_size_variable &&
58        info->base.workgroup_size[0] *
59        info->base.workgroup_size[1] *
60        info->base.workgroup_size[2] <= 32)
61       return 32;
62 
63    /* Debug flags. */
64    unsigned dbg_wave_size = 0;
65    if (sscreen->debug_flags &
66        (stage == MESA_SHADER_COMPUTE ? DBG(W32_CS) :
67         stage == MESA_SHADER_FRAGMENT ? DBG(W32_PS) | DBG(W32_PS_DISCARD) : DBG(W32_GE)))
68       dbg_wave_size = 32;
69 
70    if (sscreen->debug_flags &
71        (stage == MESA_SHADER_COMPUTE ? DBG(W64_CS) :
72         stage == MESA_SHADER_FRAGMENT ? DBG(W64_PS) : DBG(W64_GE))) {
73       assert(!dbg_wave_size);
74       dbg_wave_size = 64;
75    }
76 
77    /* Shader profiles. */
78    unsigned profile_wave_size = 0;
79    if (info && info->options & SI_PROFILE_WAVE32)
80       profile_wave_size = 32;
81 
82    if (info && info->options & SI_PROFILE_WAVE64) {
83       assert(!profile_wave_size);
84       profile_wave_size = 64;
85    }
86 
87    if (profile_wave_size) {
88       /* Only debug flags override shader profiles. */
89       if (dbg_wave_size)
90          return dbg_wave_size;
91 
92       return profile_wave_size;
93    }
94 
95    /* LLVM 13 has a bug that causes compile failures with discard in Wave32
96     * in some cases. Alpha test in Wave32 is luckily unaffected.
97     */
98    if (stage == MESA_SHADER_FRAGMENT && info->base.fs.uses_discard &&
99        !(info && info->options & SI_PROFILE_IGNORE_LLVM13_DISCARD_BUG) &&
100        LLVM_VERSION_MAJOR == 13 && !(sscreen->debug_flags & DBG(W32_PS_DISCARD)))
101       return 64;
102 
103    /* Debug flags except w32psdiscard don't override the discard bug workaround,
104     * but they override everything else.
105     */
106    if (dbg_wave_size)
107       return dbg_wave_size;
108 
109    /* Pixel shaders without interp instructions don't suffer from reduced interpolation
110     * performance in Wave32, so use Wave32. This helps Piano and Voloplosion.
111     */
112    if (stage == MESA_SHADER_FRAGMENT && !info->num_inputs)
113       return 32;
114 
115    /* There are a few very rare cases where VS is better with Wave32, and there are no known
116     * cases where Wave64 is better.
117     * Wave32 is disabled for GFX10 when culling is active as a workaround for #6457. I don't
118     * know why this helps.
119     */
120    if (stage <= MESA_SHADER_GEOMETRY &&
121        !(sscreen->info.gfx_level == GFX10 && shader && shader->key.ge.opt.ngg_culling))
122       return 32;
123 
124    /* TODO: Merged shaders must use the same wave size because the driver doesn't recompile
125     * individual shaders of merged shaders to match the wave size between them.
126     */
127    bool merged_shader = stage <= MESA_SHADER_GEOMETRY && shader && !shader->is_gs_copy_shader &&
128                         (shader->key.ge.as_ls || shader->key.ge.as_es ||
129                          stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_GEOMETRY);
130 
131    /* Divergent loops in Wave64 can end up having too many iterations in one half of the wave
132     * while the other half is idling but occupying VGPRs, preventing other waves from launching.
133     * Wave32 eliminates the idling half to allow the next wave to start.
134     */
135    if (!merged_shader && info && info->has_divergent_loop)
136       return 32;
137 
138    return 64;
139 }
140 
141 /* SHADER_CACHE */
142 
143 /**
144  * Return the IR key for the shader cache.
145  */
si_get_ir_cache_key(struct si_shader_selector * sel,bool ngg,bool es,unsigned wave_size,unsigned char ir_sha1_cache_key[20])146 void si_get_ir_cache_key(struct si_shader_selector *sel, bool ngg, bool es,
147                          unsigned wave_size, unsigned char ir_sha1_cache_key[20])
148 {
149    struct blob blob = {};
150    unsigned ir_size;
151    void *ir_binary;
152 
153    if (sel->nir_binary) {
154       ir_binary = sel->nir_binary;
155       ir_size = sel->nir_size;
156    } else {
157       assert(sel->nir);
158 
159       blob_init(&blob);
160       /* Keep debug info if NIR debug prints are in use. */
161       nir_serialize(&blob, sel->nir, NIR_DEBUG(PRINT) == 0);
162       ir_binary = blob.data;
163       ir_size = blob.size;
164    }
165 
166    /* These settings affect the compilation, but they are not derived
167     * from the input shader IR.
168     */
169    unsigned shader_variant_flags = 0;
170 
171    if (ngg)
172       shader_variant_flags |= 1 << 0;
173    if (sel->nir)
174       shader_variant_flags |= 1 << 1;
175    if (wave_size == 32)
176       shader_variant_flags |= 1 << 2;
177    if (sel->stage == MESA_SHADER_FRAGMENT &&
178        /* Derivatives imply helper invocations so check for needs_quad_helper_invocations. */
179        sel->info.base.fs.needs_quad_helper_invocations &&
180        sel->info.base.fs.uses_discard &&
181        sel->screen->debug_flags & DBG(FS_CORRECT_DERIVS_AFTER_KILL))
182       shader_variant_flags |= 1 << 3;
183    /* use_ngg_culling disables NGG passthrough for non-culling shaders to reduce context
184     * rolls, which can be changed with AMD_DEBUG=nonggc or AMD_DEBUG=nggc.
185     */
186    if (sel->screen->use_ngg_culling)
187       shader_variant_flags |= 1 << 4;
188    if (sel->screen->record_llvm_ir)
189       shader_variant_flags |= 1 << 5;
190 
191    /* bit gap */
192 
193    if (sel->screen->options.no_infinite_interp)
194       shader_variant_flags |= 1 << 7;
195    if (sel->screen->options.clamp_div_by_zero)
196       shader_variant_flags |= 1 << 8;
197    if ((sel->stage == MESA_SHADER_VERTEX ||
198         sel->stage == MESA_SHADER_TESS_EVAL ||
199         sel->stage == MESA_SHADER_GEOMETRY) &&
200        !es &&
201        sel->screen->options.vrs2x2)
202       shader_variant_flags |= 1 << 10;
203    if (sel->screen->options.inline_uniforms)
204       shader_variant_flags |= 1 << 11;
205 
206    struct mesa_sha1 ctx;
207    _mesa_sha1_init(&ctx);
208    _mesa_sha1_update(&ctx, &shader_variant_flags, 4);
209    _mesa_sha1_update(&ctx, ir_binary, ir_size);
210    _mesa_sha1_final(&ctx, ir_sha1_cache_key);
211 
212    if (ir_binary == blob.data)
213       blob_finish(&blob);
214 }
215 
216 /** Copy "data" to "ptr" and return the next dword following copied data. */
write_data(uint32_t * ptr,const void * data,unsigned size)217 static uint32_t *write_data(uint32_t *ptr, const void *data, unsigned size)
218 {
219    /* data may be NULL if size == 0 */
220    if (size)
221       memcpy(ptr, data, size);
222    ptr += DIV_ROUND_UP(size, 4);
223    return ptr;
224 }
225 
226 /** Read data from "ptr". Return the next dword following the data. */
read_data(uint32_t * ptr,void * data,unsigned size)227 static uint32_t *read_data(uint32_t *ptr, void *data, unsigned size)
228 {
229    memcpy(data, ptr, size);
230    ptr += DIV_ROUND_UP(size, 4);
231    return ptr;
232 }
233 
234 /**
235  * Write the size as uint followed by the data. Return the next dword
236  * following the copied data.
237  */
write_chunk(uint32_t * ptr,const void * data,unsigned size)238 static uint32_t *write_chunk(uint32_t *ptr, const void *data, unsigned size)
239 {
240    *ptr++ = size;
241    return write_data(ptr, data, size);
242 }
243 
244 /**
245  * Read the size as uint followed by the data. Return both via parameters.
246  * Return the next dword following the data.
247  */
read_chunk(uint32_t * ptr,void ** data,unsigned * size)248 static uint32_t *read_chunk(uint32_t *ptr, void **data, unsigned *size)
249 {
250    *size = *ptr++;
251    assert(*data == NULL);
252    if (!*size)
253       return ptr;
254    *data = malloc(*size);
255    return read_data(ptr, *data, *size);
256 }
257 
258 /**
259  * Return the shader binary in a buffer. The first 4 bytes contain its size
260  * as integer.
261  */
si_get_shader_binary(struct si_shader * shader)262 static uint32_t *si_get_shader_binary(struct si_shader *shader)
263 {
264    /* There is always a size of data followed by the data itself. */
265    unsigned llvm_ir_size =
266       shader->binary.llvm_ir_string ? strlen(shader->binary.llvm_ir_string) + 1 : 0;
267 
268    /* Refuse to allocate overly large buffers and guard against integer
269     * overflow. */
270    if (shader->binary.elf_size > UINT_MAX / 4 || llvm_ir_size > UINT_MAX / 4)
271       return NULL;
272 
273    unsigned size = 4 + /* total size */
274                    4 + /* CRC32 of the data below */
275                    align(sizeof(shader->config), 4) + align(sizeof(shader->info), 4) + 4 +
276                    align(shader->binary.elf_size, 4) + 4 + align(llvm_ir_size, 4);
277    uint32_t *buffer = (uint32_t*)CALLOC(1, size);
278    uint32_t *ptr = buffer;
279 
280    if (!buffer)
281       return NULL;
282 
283    *ptr++ = size;
284    ptr++; /* CRC32 is calculated at the end. */
285 
286    ptr = write_data(ptr, &shader->config, sizeof(shader->config));
287    ptr = write_data(ptr, &shader->info, sizeof(shader->info));
288    ptr = write_chunk(ptr, shader->binary.elf_buffer, shader->binary.elf_size);
289    ptr = write_chunk(ptr, shader->binary.llvm_ir_string, llvm_ir_size);
290    assert((char *)ptr - (char *)buffer == (ptrdiff_t)size);
291 
292    /* Compute CRC32. */
293    ptr = buffer;
294    ptr++;
295    *ptr = util_hash_crc32(ptr + 1, size - 8);
296 
297    return buffer;
298 }
299 
si_load_shader_binary(struct si_shader * shader,void * binary)300 static bool si_load_shader_binary(struct si_shader *shader, void *binary)
301 {
302    uint32_t *ptr = (uint32_t *)binary;
303    uint32_t size = *ptr++;
304    uint32_t crc32 = *ptr++;
305    unsigned chunk_size;
306    unsigned elf_size;
307 
308    if (util_hash_crc32(ptr, size - 8) != crc32) {
309       fprintf(stderr, "radeonsi: binary shader has invalid CRC32\n");
310       return false;
311    }
312 
313    ptr = read_data(ptr, &shader->config, sizeof(shader->config));
314    ptr = read_data(ptr, &shader->info, sizeof(shader->info));
315    ptr = read_chunk(ptr, (void **)&shader->binary.elf_buffer, &elf_size);
316    shader->binary.elf_size = elf_size;
317    ptr = read_chunk(ptr, (void **)&shader->binary.llvm_ir_string, &chunk_size);
318 
319    if (!shader->is_gs_copy_shader &&
320        shader->selector->stage == MESA_SHADER_GEOMETRY && !shader->key.ge.as_ngg) {
321       shader->gs_copy_shader = CALLOC_STRUCT(si_shader);
322       if (!shader->gs_copy_shader)
323          return false;
324 
325       shader->gs_copy_shader->is_gs_copy_shader = true;
326 
327       if (!si_load_shader_binary(shader->gs_copy_shader, (uint8_t*)binary + size)) {
328          FREE(shader->gs_copy_shader);
329          shader->gs_copy_shader = NULL;
330          return false;
331       }
332 
333       util_queue_fence_init(&shader->gs_copy_shader->ready);
334       shader->gs_copy_shader->selector = shader->selector;
335       shader->gs_copy_shader->is_gs_copy_shader = true;
336       shader->gs_copy_shader->wave_size =
337          si_determine_wave_size(shader->selector->screen, shader->gs_copy_shader);
338 
339       si_shader_binary_upload(shader->selector->screen, shader->gs_copy_shader, 0);
340    }
341 
342    return true;
343 }
344 
345 /**
346  * Insert a shader into the cache. It's assumed the shader is not in the cache.
347  * Use si_shader_cache_load_shader before calling this.
348  */
si_shader_cache_insert_shader(struct si_screen * sscreen,unsigned char ir_sha1_cache_key[20],struct si_shader * shader,bool insert_into_disk_cache)349 void si_shader_cache_insert_shader(struct si_screen *sscreen, unsigned char ir_sha1_cache_key[20],
350                                    struct si_shader *shader, bool insert_into_disk_cache)
351 {
352    uint32_t *hw_binary;
353    struct hash_entry *entry;
354    uint8_t key[CACHE_KEY_SIZE];
355    bool memory_cache_full = sscreen->shader_cache_size >= sscreen->shader_cache_max_size;
356 
357    if (!insert_into_disk_cache && memory_cache_full)
358       return;
359 
360    entry = _mesa_hash_table_search(sscreen->shader_cache, ir_sha1_cache_key);
361    if (entry)
362       return; /* already added */
363 
364    hw_binary = si_get_shader_binary(shader);
365    if (!hw_binary)
366       return;
367 
368    unsigned size = *hw_binary;
369 
370    if (shader->selector->stage == MESA_SHADER_GEOMETRY && !shader->key.ge.as_ngg) {
371       uint32_t *gs_copy_binary = si_get_shader_binary(shader->gs_copy_shader);
372       if (!gs_copy_binary) {
373          FREE(hw_binary);
374          return;
375       }
376 
377       /* Combine both binaries. */
378       size += *gs_copy_binary;
379       uint32_t *combined_binary = (uint32_t*)MALLOC(size);
380       if (!combined_binary) {
381          FREE(hw_binary);
382          FREE(gs_copy_binary);
383          return;
384       }
385 
386       memcpy(combined_binary, hw_binary, *hw_binary);
387       memcpy(combined_binary + *hw_binary / 4, gs_copy_binary, *gs_copy_binary);
388       FREE(hw_binary);
389       FREE(gs_copy_binary);
390       hw_binary = combined_binary;
391    }
392 
393    if (!memory_cache_full) {
394       if (_mesa_hash_table_insert(sscreen->shader_cache,
395                                   mem_dup(ir_sha1_cache_key, 20),
396                                   hw_binary) == NULL) {
397           FREE(hw_binary);
398           return;
399       }
400 
401       sscreen->shader_cache_size += size;
402    }
403 
404    if (sscreen->disk_shader_cache && insert_into_disk_cache) {
405       disk_cache_compute_key(sscreen->disk_shader_cache, ir_sha1_cache_key, 20, key);
406       disk_cache_put(sscreen->disk_shader_cache, key, hw_binary, size, NULL);
407    }
408 
409    if (memory_cache_full)
410       FREE(hw_binary);
411 }
412 
si_shader_cache_load_shader(struct si_screen * sscreen,unsigned char ir_sha1_cache_key[20],struct si_shader * shader)413 bool si_shader_cache_load_shader(struct si_screen *sscreen, unsigned char ir_sha1_cache_key[20],
414                                  struct si_shader *shader)
415 {
416    struct hash_entry *entry = _mesa_hash_table_search(sscreen->shader_cache, ir_sha1_cache_key);
417 
418    if (entry) {
419       if (si_load_shader_binary(shader, entry->data)) {
420          p_atomic_inc(&sscreen->num_memory_shader_cache_hits);
421          return true;
422       }
423    }
424    p_atomic_inc(&sscreen->num_memory_shader_cache_misses);
425 
426    if (!sscreen->disk_shader_cache)
427       return false;
428 
429    unsigned char sha1[CACHE_KEY_SIZE];
430    disk_cache_compute_key(sscreen->disk_shader_cache, ir_sha1_cache_key, 20, sha1);
431 
432    size_t total_size;
433    uint32_t *buffer = (uint32_t*)disk_cache_get(sscreen->disk_shader_cache, sha1, &total_size);
434    if (buffer) {
435       unsigned size = *buffer;
436       unsigned gs_copy_binary_size = 0;
437 
438       /* The GS copy shader binary is after the GS binary. */
439       if (shader->selector->stage == MESA_SHADER_GEOMETRY && !shader->key.ge.as_ngg)
440          gs_copy_binary_size = buffer[size / 4];
441 
442       if (total_size >= sizeof(uint32_t) && size + gs_copy_binary_size == total_size) {
443          if (si_load_shader_binary(shader, buffer)) {
444             free(buffer);
445             si_shader_cache_insert_shader(sscreen, ir_sha1_cache_key, shader, false);
446             p_atomic_inc(&sscreen->num_disk_shader_cache_hits);
447             return true;
448          }
449       } else {
450          /* Something has gone wrong discard the item from the cache and
451           * rebuild/link from source.
452           */
453          assert(!"Invalid radeonsi shader disk cache item!");
454          disk_cache_remove(sscreen->disk_shader_cache, sha1);
455       }
456    }
457 
458    free(buffer);
459    p_atomic_inc(&sscreen->num_disk_shader_cache_misses);
460    return false;
461 }
462 
si_shader_cache_key_hash(const void * key)463 static uint32_t si_shader_cache_key_hash(const void *key)
464 {
465    /* Take the first dword of SHA1. */
466    return *(uint32_t *)key;
467 }
468 
si_shader_cache_key_equals(const void * a,const void * b)469 static bool si_shader_cache_key_equals(const void *a, const void *b)
470 {
471    /* Compare SHA1s. */
472    return memcmp(a, b, 20) == 0;
473 }
474 
si_destroy_shader_cache_entry(struct hash_entry * entry)475 static void si_destroy_shader_cache_entry(struct hash_entry *entry)
476 {
477    FREE((void *)entry->key);
478    FREE(entry->data);
479 }
480 
si_init_shader_cache(struct si_screen * sscreen)481 bool si_init_shader_cache(struct si_screen *sscreen)
482 {
483    (void)simple_mtx_init(&sscreen->shader_cache_mutex, mtx_plain);
484    sscreen->shader_cache =
485       _mesa_hash_table_create(NULL, si_shader_cache_key_hash, si_shader_cache_key_equals);
486    sscreen->shader_cache_size = 0;
487    /* Maximum size: 64MB on 32 bits, 1GB else */
488    sscreen->shader_cache_max_size = ((sizeof(void *) == 4) ? 64 : 1024) * 1024 * 1024;
489 
490    return sscreen->shader_cache != NULL;
491 }
492 
si_destroy_shader_cache(struct si_screen * sscreen)493 void si_destroy_shader_cache(struct si_screen *sscreen)
494 {
495    if (sscreen->shader_cache)
496       _mesa_hash_table_destroy(sscreen->shader_cache, si_destroy_shader_cache_entry);
497    simple_mtx_destroy(&sscreen->shader_cache_mutex);
498 }
499 
500 /* SHADER STATES */
501 
si_shader_mem_ordered(struct si_shader * shader)502 bool si_shader_mem_ordered(struct si_shader *shader)
503 {
504    if (shader->selector->screen->info.gfx_level < GFX10)
505       return false;
506 
507    /* Return true if both types of VMEM that return something are used. */
508    return shader->info.uses_vmem_sampler_or_bvh &&
509           (shader->info.uses_vmem_load_other ||
510            shader->config.scratch_bytes_per_wave);
511 }
512 
si_set_tesseval_regs(struct si_screen * sscreen,const struct si_shader_selector * tes,struct si_shader * shader)513 static void si_set_tesseval_regs(struct si_screen *sscreen, const struct si_shader_selector *tes,
514                                  struct si_shader *shader)
515 {
516    const struct si_shader_info *info = &tes->info;
517    enum tess_primitive_mode tes_prim_mode = info->base.tess._primitive_mode;
518    unsigned tes_spacing = info->base.tess.spacing;
519    bool tes_vertex_order_cw = !info->base.tess.ccw;
520    bool tes_point_mode = info->base.tess.point_mode;
521    unsigned type, partitioning, topology, distribution_mode;
522 
523    switch (tes_prim_mode) {
524    case TESS_PRIMITIVE_ISOLINES:
525       type = V_028B6C_TESS_ISOLINE;
526       break;
527    case TESS_PRIMITIVE_TRIANGLES:
528       type = V_028B6C_TESS_TRIANGLE;
529       break;
530    case TESS_PRIMITIVE_QUADS:
531       type = V_028B6C_TESS_QUAD;
532       break;
533    default:
534       assert(0);
535       return;
536    }
537 
538    switch (tes_spacing) {
539    case TESS_SPACING_FRACTIONAL_ODD:
540       partitioning = V_028B6C_PART_FRAC_ODD;
541       break;
542    case TESS_SPACING_FRACTIONAL_EVEN:
543       partitioning = V_028B6C_PART_FRAC_EVEN;
544       break;
545    case TESS_SPACING_EQUAL:
546       partitioning = V_028B6C_PART_INTEGER;
547       break;
548    default:
549       assert(0);
550       return;
551    }
552 
553    if (tes_point_mode)
554       topology = V_028B6C_OUTPUT_POINT;
555    else if (tes_prim_mode == TESS_PRIMITIVE_ISOLINES)
556       topology = V_028B6C_OUTPUT_LINE;
557    else if (tes_vertex_order_cw)
558       /* for some reason, this must be the other way around */
559       topology = V_028B6C_OUTPUT_TRIANGLE_CCW;
560    else
561       topology = V_028B6C_OUTPUT_TRIANGLE_CW;
562 
563    if (sscreen->info.has_distributed_tess) {
564       if (sscreen->info.family == CHIP_FIJI || sscreen->info.family >= CHIP_POLARIS10)
565          distribution_mode = V_028B6C_TRAPEZOIDS;
566       else
567          distribution_mode = V_028B6C_DONUTS;
568    } else
569       distribution_mode = V_028B6C_NO_DIST;
570 
571    shader->vgt_tf_param = S_028B6C_TYPE(type) | S_028B6C_PARTITIONING(partitioning) |
572                           S_028B6C_TOPOLOGY(topology) |
573                           S_028B6C_DISTRIBUTION_MODE(distribution_mode);
574 }
575 
576 /* Polaris needs different VTX_REUSE_DEPTH settings depending on
577  * whether the "fractional odd" tessellation spacing is used.
578  *
579  * Possible VGT configurations and which state should set the register:
580  *
581  *   Reg set in | VGT shader configuration   | Value
582  * ------------------------------------------------------
583  *     VS as VS | VS                         | 30
584  *     VS as ES | ES -> GS -> VS             | 30
585  *    TES as VS | LS -> HS -> VS             | 14 or 30
586  *    TES as ES | LS -> HS -> ES -> GS -> VS | 14 or 30
587  */
polaris_set_vgt_vertex_reuse(struct si_screen * sscreen,struct si_shader_selector * sel,struct si_shader * shader)588 static void polaris_set_vgt_vertex_reuse(struct si_screen *sscreen, struct si_shader_selector *sel,
589                                          struct si_shader *shader)
590 {
591    if (sscreen->info.family < CHIP_POLARIS10 || sscreen->info.gfx_level >= GFX10)
592       return;
593 
594    /* VS as VS, or VS as ES: */
595    if ((sel->stage == MESA_SHADER_VERTEX &&
596         (!shader->key.ge.as_ls && !shader->is_gs_copy_shader)) ||
597        /* TES as VS, or TES as ES: */
598        sel->stage == MESA_SHADER_TESS_EVAL) {
599       unsigned vtx_reuse_depth = 30;
600 
601       if (sel->stage == MESA_SHADER_TESS_EVAL &&
602           sel->info.base.tess.spacing == TESS_SPACING_FRACTIONAL_ODD)
603          vtx_reuse_depth = 14;
604 
605       shader->vgt_vertex_reuse_block_cntl = vtx_reuse_depth;
606    }
607 }
608 
si_get_shader_pm4_state(struct si_shader * shader)609 static struct si_pm4_state *si_get_shader_pm4_state(struct si_shader *shader)
610 {
611    si_pm4_clear_state(&shader->pm4);
612    shader->pm4.is_shader = true;
613    return &shader->pm4;
614 }
615 
si_get_num_vs_user_sgprs(struct si_shader * shader,unsigned num_always_on_user_sgprs)616 static unsigned si_get_num_vs_user_sgprs(struct si_shader *shader,
617                                          unsigned num_always_on_user_sgprs)
618 {
619    struct si_shader_selector *vs =
620       shader->previous_stage_sel ? shader->previous_stage_sel : shader->selector;
621    unsigned num_vbos_in_user_sgprs = vs->info.num_vbos_in_user_sgprs;
622 
623    /* 1 SGPR is reserved for the vertex buffer pointer. */
624    assert(num_always_on_user_sgprs <= SI_SGPR_VS_VB_DESCRIPTOR_FIRST - 1);
625 
626    if (num_vbos_in_user_sgprs)
627       return SI_SGPR_VS_VB_DESCRIPTOR_FIRST + num_vbos_in_user_sgprs * 4;
628 
629    /* Add the pointer to VBO descriptors. */
630    return num_always_on_user_sgprs + 1;
631 }
632 
633 /* Return VGPR_COMP_CNT for the API vertex shader. This can be hw LS, LSHS, ES, ESGS, VS. */
si_get_vs_vgpr_comp_cnt(struct si_screen * sscreen,struct si_shader * shader,bool legacy_vs_prim_id)634 static unsigned si_get_vs_vgpr_comp_cnt(struct si_screen *sscreen, struct si_shader *shader,
635                                         bool legacy_vs_prim_id)
636 {
637    assert(shader->selector->stage == MESA_SHADER_VERTEX ||
638           (shader->previous_stage_sel && shader->previous_stage_sel->stage == MESA_SHADER_VERTEX));
639 
640    /* GFX6-9   LS    (VertexID, RelAutoIndex,           InstanceID / StepRate0, InstanceID)
641     * GFX6-9   ES,VS (VertexID, InstanceID / StepRate0, VSPrimID,               InstanceID)
642     * GFX10-11 LS    (VertexID, RelAutoIndex,           UserVGPR1,              UserVGPR2 or InstanceID)
643     * GFX10-11 ES,VS (VertexID, UserVGPR1,              UserVGPR2 or VSPrimID,  UserVGPR3 or InstanceID)
644     */
645    bool is_ls = shader->selector->stage == MESA_SHADER_TESS_CTRL || shader->key.ge.as_ls;
646    unsigned max = 0;
647 
648    if (shader->info.uses_instanceid) {
649       if (sscreen->info.gfx_level >= GFX10)
650          max = MAX2(max, 3);
651       else if (is_ls)
652          max = MAX2(max, 2); /* use (InstanceID / StepRate0) because StepRate0 == 1 */
653       else
654          max = MAX2(max, 1); /* use (InstanceID / StepRate0) because StepRate0 == 1 */
655    }
656 
657    if (legacy_vs_prim_id)
658       max = MAX2(max, 2); /* VSPrimID */
659 
660    /* GFX11: We prefer to compute RelAutoIndex using (WaveID * WaveSize + ThreadID).
661     * Older chips didn't have WaveID in LS.
662     */
663    if (is_ls && sscreen->info.gfx_level <= GFX10_3)
664       max = MAX2(max, 1); /* RelAutoIndex */
665 
666    return max;
667 }
668 
si_get_shader_prefetch_size(struct si_shader * shader)669 unsigned si_get_shader_prefetch_size(struct si_shader *shader)
670 {
671    /* Return 0 for some A0 chips only. Other chips don't need it. */
672    if ((shader->selector->screen->info.family == CHIP_GFX1100 ||
673         shader->selector->screen->info.family == CHIP_GFX1102 ||
674         shader->selector->screen->info.family == CHIP_GFX1103) &&
675        shader->selector->screen->info.chip_rev == 0)
676       return 0;
677 
678    /* inst_pref_size is calculated in cache line size granularity */
679    assert(!(shader->bo->b.b.width0 & 0x7f));
680    return MIN2(shader->bo->b.b.width0, 8064) / 128;
681 }
682 
si_shader_ls(struct si_screen * sscreen,struct si_shader * shader)683 static void si_shader_ls(struct si_screen *sscreen, struct si_shader *shader)
684 {
685    struct si_pm4_state *pm4;
686    uint64_t va;
687 
688    assert(sscreen->info.gfx_level <= GFX8);
689 
690    pm4 = si_get_shader_pm4_state(shader);
691    if (!pm4)
692       return;
693 
694    va = shader->bo->gpu_address;
695    si_pm4_set_reg(pm4, R_00B520_SPI_SHADER_PGM_LO_LS, va >> 8);
696 
697    shader->config.rsrc1 = S_00B528_VGPRS((shader->config.num_vgprs - 1) / 4) |
698                           S_00B528_SGPRS((shader->config.num_sgprs - 1) / 8) |
699                           S_00B528_VGPR_COMP_CNT(si_get_vs_vgpr_comp_cnt(sscreen, shader, false)) |
700                           S_00B528_DX10_CLAMP(1) | S_00B528_FLOAT_MODE(shader->config.float_mode);
701    shader->config.rsrc2 =
702       S_00B52C_USER_SGPR(si_get_num_vs_user_sgprs(shader, SI_VS_NUM_USER_SGPR)) |
703       S_00B52C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
704 }
705 
si_shader_hs(struct si_screen * sscreen,struct si_shader * shader)706 static void si_shader_hs(struct si_screen *sscreen, struct si_shader *shader)
707 {
708    struct si_pm4_state *pm4;
709    uint64_t va;
710 
711    pm4 = si_get_shader_pm4_state(shader);
712    if (!pm4)
713       return;
714 
715    va = shader->bo->gpu_address;
716 
717    if (sscreen->info.gfx_level >= GFX9) {
718       if (sscreen->info.gfx_level >= GFX11) {
719          ac_set_reg_cu_en(pm4, R_00B404_SPI_SHADER_PGM_RSRC4_HS,
720                           S_00B404_INST_PREF_SIZE(si_get_shader_prefetch_size(shader)) |
721                           S_00B404_CU_EN(0xffff),
722                           C_00B404_CU_EN, 16, &sscreen->info,
723                           (void (*)(void*, unsigned, uint32_t))si_pm4_set_reg_idx3);
724       }
725       if (sscreen->info.gfx_level >= GFX10) {
726          si_pm4_set_reg(pm4, R_00B520_SPI_SHADER_PGM_LO_LS, va >> 8);
727       } else {
728          si_pm4_set_reg(pm4, R_00B410_SPI_SHADER_PGM_LO_LS, va >> 8);
729       }
730 
731       unsigned num_user_sgprs = si_get_num_vs_user_sgprs(shader, GFX9_TCS_NUM_USER_SGPR);
732 
733       shader->config.rsrc2 = S_00B42C_USER_SGPR(num_user_sgprs) |
734                              S_00B42C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
735 
736       if (sscreen->info.gfx_level >= GFX10)
737          shader->config.rsrc2 |= S_00B42C_USER_SGPR_MSB_GFX10(num_user_sgprs >> 5);
738       else
739          shader->config.rsrc2 |= S_00B42C_USER_SGPR_MSB_GFX9(num_user_sgprs >> 5);
740    } else {
741       si_pm4_set_reg(pm4, R_00B420_SPI_SHADER_PGM_LO_HS, va >> 8);
742       si_pm4_set_reg(pm4, R_00B424_SPI_SHADER_PGM_HI_HS,
743                      S_00B424_MEM_BASE(sscreen->info.address32_hi >> 8));
744 
745       shader->config.rsrc2 = S_00B42C_USER_SGPR(GFX6_TCS_NUM_USER_SGPR) | S_00B42C_OC_LDS_EN(1) |
746                              S_00B42C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
747    }
748 
749    si_pm4_set_reg(
750       pm4, R_00B428_SPI_SHADER_PGM_RSRC1_HS,
751       S_00B428_VGPRS((shader->config.num_vgprs - 1) / (shader->wave_size == 32 ? 8 : 4)) |
752          (sscreen->info.gfx_level <= GFX9 ? S_00B428_SGPRS((shader->config.num_sgprs - 1) / 8)
753                                            : 0) |
754          S_00B428_DX10_CLAMP(1) | S_00B428_MEM_ORDERED(si_shader_mem_ordered(shader)) |
755          S_00B428_WGP_MODE(sscreen->info.gfx_level >= GFX10) |
756          S_00B428_FLOAT_MODE(shader->config.float_mode) |
757          S_00B428_LS_VGPR_COMP_CNT(sscreen->info.gfx_level >= GFX9
758                                       ? si_get_vs_vgpr_comp_cnt(sscreen, shader, false)
759                                       : 0));
760 
761    if (sscreen->info.gfx_level <= GFX8) {
762       si_pm4_set_reg(pm4, R_00B42C_SPI_SHADER_PGM_RSRC2_HS, shader->config.rsrc2);
763    }
764 }
765 
si_emit_shader_es(struct si_context * sctx)766 static void si_emit_shader_es(struct si_context *sctx)
767 {
768    struct si_shader *shader = sctx->queued.named.es;
769    if (!shader)
770       return;
771 
772    radeon_begin(&sctx->gfx_cs);
773    radeon_opt_set_context_reg(sctx, R_028AAC_VGT_ESGS_RING_ITEMSIZE,
774                               SI_TRACKED_VGT_ESGS_RING_ITEMSIZE,
775                               shader->selector->info.esgs_itemsize / 4);
776 
777    if (shader->selector->stage == MESA_SHADER_TESS_EVAL)
778       radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
779                                  shader->vgt_tf_param);
780 
781    if (shader->vgt_vertex_reuse_block_cntl)
782       radeon_opt_set_context_reg(sctx, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL,
783                                  SI_TRACKED_VGT_VERTEX_REUSE_BLOCK_CNTL,
784                                  shader->vgt_vertex_reuse_block_cntl);
785    radeon_end_update_context_roll(sctx);
786 }
787 
si_shader_es(struct si_screen * sscreen,struct si_shader * shader)788 static void si_shader_es(struct si_screen *sscreen, struct si_shader *shader)
789 {
790    struct si_pm4_state *pm4;
791    unsigned num_user_sgprs;
792    unsigned vgpr_comp_cnt;
793    uint64_t va;
794    unsigned oc_lds_en;
795 
796    assert(sscreen->info.gfx_level <= GFX8);
797 
798    pm4 = si_get_shader_pm4_state(shader);
799    if (!pm4)
800       return;
801 
802    pm4->atom.emit = si_emit_shader_es;
803    va = shader->bo->gpu_address;
804 
805    if (shader->selector->stage == MESA_SHADER_VERTEX) {
806       vgpr_comp_cnt = si_get_vs_vgpr_comp_cnt(sscreen, shader, false);
807       num_user_sgprs = si_get_num_vs_user_sgprs(shader, SI_VS_NUM_USER_SGPR);
808    } else if (shader->selector->stage == MESA_SHADER_TESS_EVAL) {
809       vgpr_comp_cnt = shader->selector->info.uses_primid ? 3 : 2;
810       num_user_sgprs = SI_TES_NUM_USER_SGPR;
811    } else
812       unreachable("invalid shader selector type");
813 
814    oc_lds_en = shader->selector->stage == MESA_SHADER_TESS_EVAL ? 1 : 0;
815 
816    si_pm4_set_reg(pm4, R_00B320_SPI_SHADER_PGM_LO_ES, va >> 8);
817    si_pm4_set_reg(pm4, R_00B324_SPI_SHADER_PGM_HI_ES,
818                   S_00B324_MEM_BASE(sscreen->info.address32_hi >> 8));
819    si_pm4_set_reg(pm4, R_00B328_SPI_SHADER_PGM_RSRC1_ES,
820                   S_00B328_VGPRS((shader->config.num_vgprs - 1) / 4) |
821                      S_00B328_SGPRS((shader->config.num_sgprs - 1) / 8) |
822                      S_00B328_VGPR_COMP_CNT(vgpr_comp_cnt) | S_00B328_DX10_CLAMP(1) |
823                      S_00B328_FLOAT_MODE(shader->config.float_mode));
824    si_pm4_set_reg(pm4, R_00B32C_SPI_SHADER_PGM_RSRC2_ES,
825                   S_00B32C_USER_SGPR(num_user_sgprs) | S_00B32C_OC_LDS_EN(oc_lds_en) |
826                      S_00B32C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0));
827 
828    if (shader->selector->stage == MESA_SHADER_TESS_EVAL)
829       si_set_tesseval_regs(sscreen, shader->selector, shader);
830 
831    polaris_set_vgt_vertex_reuse(sscreen, shader->selector, shader);
832 }
833 
gfx9_get_gs_info(struct si_shader_selector * es,struct si_shader_selector * gs,struct gfx9_gs_info * out)834 void gfx9_get_gs_info(struct si_shader_selector *es, struct si_shader_selector *gs,
835                       struct gfx9_gs_info *out)
836 {
837    unsigned gs_num_invocations = MAX2(gs->info.base.gs.invocations, 1);
838    unsigned input_prim = gs->info.base.gs.input_primitive;
839    bool uses_adjacency =
840       input_prim >= PIPE_PRIM_LINES_ADJACENCY && input_prim <= PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY;
841 
842    /* All these are in dwords: */
843    /* We can't allow using the whole LDS, because GS waves compete with
844     * other shader stages for LDS space. */
845    const unsigned max_lds_size = 8 * 1024;
846    const unsigned esgs_itemsize = es->info.esgs_itemsize / 4;
847    unsigned esgs_lds_size;
848 
849    /* All these are per subgroup: */
850    const unsigned max_out_prims = 32 * 1024;
851    const unsigned max_es_verts = 255;
852    const unsigned ideal_gs_prims = 64;
853    unsigned max_gs_prims, gs_prims;
854    unsigned min_es_verts, es_verts, worst_case_es_verts;
855 
856    if (uses_adjacency || gs_num_invocations > 1)
857       max_gs_prims = 127 / gs_num_invocations;
858    else
859       max_gs_prims = 255;
860 
861    /* MAX_PRIMS_PER_SUBGROUP = gs_prims * max_vert_out * gs_invocations.
862     * Make sure we don't go over the maximum value.
863     */
864    if (gs->info.base.gs.vertices_out > 0) {
865       max_gs_prims =
866          MIN2(max_gs_prims, max_out_prims / (gs->info.base.gs.vertices_out * gs_num_invocations));
867    }
868    assert(max_gs_prims > 0);
869 
870    /* If the primitive has adjacency, halve the number of vertices
871     * that will be reused in multiple primitives.
872     */
873    min_es_verts = gs->info.gs_input_verts_per_prim / (uses_adjacency ? 2 : 1);
874 
875    gs_prims = MIN2(ideal_gs_prims, max_gs_prims);
876    worst_case_es_verts = MIN2(min_es_verts * gs_prims, max_es_verts);
877 
878    /* Compute ESGS LDS size based on the worst case number of ES vertices
879     * needed to create the target number of GS prims per subgroup.
880     */
881    esgs_lds_size = esgs_itemsize * worst_case_es_verts;
882 
883    /* If total LDS usage is too big, refactor partitions based on ratio
884     * of ESGS item sizes.
885     */
886    if (esgs_lds_size > max_lds_size) {
887       /* Our target GS Prims Per Subgroup was too large. Calculate
888        * the maximum number of GS Prims Per Subgroup that will fit
889        * into LDS, capped by the maximum that the hardware can support.
890        */
891       gs_prims = MIN2((max_lds_size / (esgs_itemsize * min_es_verts)), max_gs_prims);
892       assert(gs_prims > 0);
893       worst_case_es_verts = MIN2(min_es_verts * gs_prims, max_es_verts);
894 
895       esgs_lds_size = esgs_itemsize * worst_case_es_verts;
896       assert(esgs_lds_size <= max_lds_size);
897    }
898 
899    /* Now calculate remaining ESGS information. */
900    if (esgs_lds_size)
901       es_verts = MIN2(esgs_lds_size / esgs_itemsize, max_es_verts);
902    else
903       es_verts = max_es_verts;
904 
905    /* Vertices for adjacency primitives are not always reused, so restore
906     * it for ES_VERTS_PER_SUBGRP.
907     */
908    min_es_verts = gs->info.gs_input_verts_per_prim;
909 
910    /* For normal primitives, the VGT only checks if they are past the ES
911     * verts per subgroup after allocating a full GS primitive and if they
912     * are, kick off a new subgroup.  But if those additional ES verts are
913     * unique (e.g. not reused) we need to make sure there is enough LDS
914     * space to account for those ES verts beyond ES_VERTS_PER_SUBGRP.
915     */
916    es_verts -= min_es_verts - 1;
917 
918    out->es_verts_per_subgroup = es_verts;
919    out->gs_prims_per_subgroup = gs_prims;
920    out->gs_inst_prims_in_subgroup = gs_prims * gs_num_invocations;
921    out->max_prims_per_subgroup = out->gs_inst_prims_in_subgroup * gs->info.base.gs.vertices_out;
922    out->esgs_ring_size = esgs_lds_size;
923 
924    assert(out->max_prims_per_subgroup <= max_out_prims);
925 }
926 
si_emit_shader_gs(struct si_context * sctx)927 static void si_emit_shader_gs(struct si_context *sctx)
928 {
929    struct si_shader *shader = sctx->queued.named.gs;
930    if (!shader)
931       return;
932 
933    radeon_begin(&sctx->gfx_cs);
934 
935    /* R_028A60_VGT_GSVS_RING_OFFSET_1, R_028A64_VGT_GSVS_RING_OFFSET_2
936     * R_028A68_VGT_GSVS_RING_OFFSET_3 */
937    radeon_opt_set_context_reg3(
938       sctx, R_028A60_VGT_GSVS_RING_OFFSET_1, SI_TRACKED_VGT_GSVS_RING_OFFSET_1,
939       shader->ctx_reg.gs.vgt_gsvs_ring_offset_1, shader->ctx_reg.gs.vgt_gsvs_ring_offset_2,
940       shader->ctx_reg.gs.vgt_gsvs_ring_offset_3);
941 
942    /* R_028AB0_VGT_GSVS_RING_ITEMSIZE */
943    radeon_opt_set_context_reg(sctx, R_028AB0_VGT_GSVS_RING_ITEMSIZE,
944                               SI_TRACKED_VGT_GSVS_RING_ITEMSIZE,
945                               shader->ctx_reg.gs.vgt_gsvs_ring_itemsize);
946 
947    /* R_028B38_VGT_GS_MAX_VERT_OUT */
948    radeon_opt_set_context_reg(sctx, R_028B38_VGT_GS_MAX_VERT_OUT, SI_TRACKED_VGT_GS_MAX_VERT_OUT,
949                               shader->ctx_reg.gs.vgt_gs_max_vert_out);
950 
951    /* R_028B5C_VGT_GS_VERT_ITEMSIZE, R_028B60_VGT_GS_VERT_ITEMSIZE_1
952     * R_028B64_VGT_GS_VERT_ITEMSIZE_2, R_028B68_VGT_GS_VERT_ITEMSIZE_3 */
953    radeon_opt_set_context_reg4(
954       sctx, R_028B5C_VGT_GS_VERT_ITEMSIZE, SI_TRACKED_VGT_GS_VERT_ITEMSIZE,
955       shader->ctx_reg.gs.vgt_gs_vert_itemsize, shader->ctx_reg.gs.vgt_gs_vert_itemsize_1,
956       shader->ctx_reg.gs.vgt_gs_vert_itemsize_2, shader->ctx_reg.gs.vgt_gs_vert_itemsize_3);
957 
958    /* R_028B90_VGT_GS_INSTANCE_CNT */
959    radeon_opt_set_context_reg(sctx, R_028B90_VGT_GS_INSTANCE_CNT, SI_TRACKED_VGT_GS_INSTANCE_CNT,
960                               shader->ctx_reg.gs.vgt_gs_instance_cnt);
961 
962    if (sctx->gfx_level >= GFX9) {
963       /* R_028A44_VGT_GS_ONCHIP_CNTL */
964       radeon_opt_set_context_reg(sctx, R_028A44_VGT_GS_ONCHIP_CNTL, SI_TRACKED_VGT_GS_ONCHIP_CNTL,
965                                  shader->ctx_reg.gs.vgt_gs_onchip_cntl);
966       /* R_028A94_VGT_GS_MAX_PRIMS_PER_SUBGROUP */
967       radeon_opt_set_context_reg(sctx, R_028A94_VGT_GS_MAX_PRIMS_PER_SUBGROUP,
968                                  SI_TRACKED_VGT_GS_MAX_PRIMS_PER_SUBGROUP,
969                                  shader->ctx_reg.gs.vgt_gs_max_prims_per_subgroup);
970       /* R_028AAC_VGT_ESGS_RING_ITEMSIZE */
971       radeon_opt_set_context_reg(sctx, R_028AAC_VGT_ESGS_RING_ITEMSIZE,
972                                  SI_TRACKED_VGT_ESGS_RING_ITEMSIZE,
973                                  shader->ctx_reg.gs.vgt_esgs_ring_itemsize);
974 
975       if (shader->key.ge.part.gs.es->stage == MESA_SHADER_TESS_EVAL)
976          radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
977                                     shader->vgt_tf_param);
978       if (shader->vgt_vertex_reuse_block_cntl)
979          radeon_opt_set_context_reg(sctx, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL,
980                                     SI_TRACKED_VGT_VERTEX_REUSE_BLOCK_CNTL,
981                                     shader->vgt_vertex_reuse_block_cntl);
982    }
983    radeon_end_update_context_roll(sctx);
984 
985    /* These don't cause any context rolls. */
986    if (sctx->screen->info.spi_cu_en_has_effect) {
987       if (sctx->gfx_level >= GFX7) {
988          ac_set_reg_cu_en(&sctx->gfx_cs, R_00B21C_SPI_SHADER_PGM_RSRC3_GS,
989                           shader->ctx_reg.gs.spi_shader_pgm_rsrc3_gs,
990                           C_00B21C_CU_EN, 0, &sctx->screen->info,
991                           (void (*)(void*, unsigned, uint32_t))
992                           (sctx->gfx_level >= GFX10 ? radeon_set_sh_reg_idx3_func : radeon_set_sh_reg_func));
993          sctx->tracked_regs.reg_saved &= ~BITFIELD64_BIT(SI_TRACKED_SPI_SHADER_PGM_RSRC3_GS);
994       }
995       if (sctx->gfx_level >= GFX10) {
996          ac_set_reg_cu_en(&sctx->gfx_cs, R_00B204_SPI_SHADER_PGM_RSRC4_GS,
997                           shader->ctx_reg.gs.spi_shader_pgm_rsrc4_gs,
998                           C_00B204_CU_EN_GFX10, 16, &sctx->screen->info,
999                           (void (*)(void*, unsigned, uint32_t))
1000                           (sctx->gfx_level >= GFX10 ? radeon_set_sh_reg_idx3_func : radeon_set_sh_reg_func));
1001          sctx->tracked_regs.reg_saved &= ~BITFIELD64_BIT(SI_TRACKED_SPI_SHADER_PGM_RSRC4_GS);
1002       }
1003    } else {
1004       radeon_begin_again(&sctx->gfx_cs);
1005       if (sctx->gfx_level >= GFX7) {
1006          radeon_opt_set_sh_reg_idx3(sctx, R_00B21C_SPI_SHADER_PGM_RSRC3_GS,
1007                                     SI_TRACKED_SPI_SHADER_PGM_RSRC3_GS,
1008                                     shader->ctx_reg.gs.spi_shader_pgm_rsrc3_gs);
1009       }
1010       if (sctx->gfx_level >= GFX10) {
1011          radeon_opt_set_sh_reg_idx3(sctx, R_00B204_SPI_SHADER_PGM_RSRC4_GS,
1012                                     SI_TRACKED_SPI_SHADER_PGM_RSRC4_GS,
1013                                     shader->ctx_reg.gs.spi_shader_pgm_rsrc4_gs);
1014       }
1015       radeon_end();
1016    }
1017 }
1018 
si_shader_gs(struct si_screen * sscreen,struct si_shader * shader)1019 static void si_shader_gs(struct si_screen *sscreen, struct si_shader *shader)
1020 {
1021    struct si_shader_selector *sel = shader->selector;
1022    const ubyte *num_components = sel->info.num_stream_output_components;
1023    unsigned gs_num_invocations = sel->info.base.gs.invocations;
1024    struct si_pm4_state *pm4;
1025    uint64_t va;
1026    unsigned max_stream = util_last_bit(sel->info.base.gs.active_stream_mask);
1027    unsigned offset;
1028 
1029    assert(sscreen->info.gfx_level < GFX11); /* gfx11 doesn't have the legacy pipeline */
1030 
1031    pm4 = si_get_shader_pm4_state(shader);
1032    if (!pm4)
1033       return;
1034 
1035    pm4->atom.emit = si_emit_shader_gs;
1036 
1037    offset = num_components[0] * sel->info.base.gs.vertices_out;
1038    shader->ctx_reg.gs.vgt_gsvs_ring_offset_1 = offset;
1039 
1040    if (max_stream >= 2)
1041       offset += num_components[1] * sel->info.base.gs.vertices_out;
1042    shader->ctx_reg.gs.vgt_gsvs_ring_offset_2 = offset;
1043 
1044    if (max_stream >= 3)
1045       offset += num_components[2] * sel->info.base.gs.vertices_out;
1046    shader->ctx_reg.gs.vgt_gsvs_ring_offset_3 = offset;
1047 
1048    if (max_stream >= 4)
1049       offset += num_components[3] * sel->info.base.gs.vertices_out;
1050    shader->ctx_reg.gs.vgt_gsvs_ring_itemsize = offset;
1051 
1052    /* The GSVS_RING_ITEMSIZE register takes 15 bits */
1053    assert(offset < (1 << 15));
1054 
1055    shader->ctx_reg.gs.vgt_gs_max_vert_out = sel->info.base.gs.vertices_out;
1056 
1057    shader->ctx_reg.gs.vgt_gs_vert_itemsize = num_components[0];
1058    shader->ctx_reg.gs.vgt_gs_vert_itemsize_1 = (max_stream >= 2) ? num_components[1] : 0;
1059    shader->ctx_reg.gs.vgt_gs_vert_itemsize_2 = (max_stream >= 3) ? num_components[2] : 0;
1060    shader->ctx_reg.gs.vgt_gs_vert_itemsize_3 = (max_stream >= 4) ? num_components[3] : 0;
1061 
1062    shader->ctx_reg.gs.vgt_gs_instance_cnt =
1063       S_028B90_CNT(MIN2(gs_num_invocations, 127)) | S_028B90_ENABLE(gs_num_invocations > 0);
1064 
1065    /* Copy over fields from the GS copy shader to make them easily accessible from GS. */
1066    shader->pa_cl_vs_out_cntl = shader->gs_copy_shader->pa_cl_vs_out_cntl;
1067 
1068    va = shader->bo->gpu_address;
1069 
1070    if (sscreen->info.gfx_level >= GFX9) {
1071       unsigned input_prim = sel->info.base.gs.input_primitive;
1072       gl_shader_stage es_stage = shader->key.ge.part.gs.es->stage;
1073       unsigned es_vgpr_comp_cnt, gs_vgpr_comp_cnt;
1074 
1075       if (es_stage == MESA_SHADER_VERTEX) {
1076          es_vgpr_comp_cnt = si_get_vs_vgpr_comp_cnt(sscreen, shader, false);
1077       } else if (es_stage == MESA_SHADER_TESS_EVAL)
1078          es_vgpr_comp_cnt = shader->key.ge.part.gs.es->info.uses_primid ? 3 : 2;
1079       else
1080          unreachable("invalid shader selector type");
1081 
1082       /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
1083        * VGPR[0:4] are always loaded.
1084        */
1085       if (sel->info.uses_invocationid)
1086          gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
1087       else if (sel->info.uses_primid)
1088          gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
1089       else if (input_prim >= PIPE_PRIM_TRIANGLES)
1090          gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
1091       else
1092          gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
1093 
1094       unsigned num_user_sgprs;
1095       if (es_stage == MESA_SHADER_VERTEX)
1096          num_user_sgprs = si_get_num_vs_user_sgprs(shader, GFX9_GS_NUM_USER_SGPR);
1097       else
1098          num_user_sgprs = GFX9_GS_NUM_USER_SGPR;
1099 
1100       if (sscreen->info.gfx_level >= GFX10) {
1101          si_pm4_set_reg(pm4, R_00B320_SPI_SHADER_PGM_LO_ES, va >> 8);
1102       } else {
1103          si_pm4_set_reg(pm4, R_00B210_SPI_SHADER_PGM_LO_ES, va >> 8);
1104       }
1105 
1106       uint32_t rsrc1 = S_00B228_VGPRS((shader->config.num_vgprs - 1) / 4) | S_00B228_DX10_CLAMP(1) |
1107                        S_00B228_MEM_ORDERED(si_shader_mem_ordered(shader)) |
1108                        S_00B228_WGP_MODE(sscreen->info.gfx_level >= GFX10) |
1109                        S_00B228_FLOAT_MODE(shader->config.float_mode) |
1110                        S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt);
1111       uint32_t rsrc2 = S_00B22C_USER_SGPR(num_user_sgprs) |
1112                        S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
1113                        S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL) |
1114                        S_00B22C_LDS_SIZE(shader->config.lds_size) |
1115                        S_00B22C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
1116 
1117       if (sscreen->info.gfx_level >= GFX10) {
1118          rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX10(num_user_sgprs >> 5);
1119       } else {
1120          rsrc1 |= S_00B228_SGPRS((shader->config.num_sgprs - 1) / 8);
1121          rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX9(num_user_sgprs >> 5);
1122       }
1123 
1124       si_pm4_set_reg(pm4, R_00B228_SPI_SHADER_PGM_RSRC1_GS, rsrc1);
1125       si_pm4_set_reg(pm4, R_00B22C_SPI_SHADER_PGM_RSRC2_GS, rsrc2);
1126 
1127       shader->ctx_reg.gs.spi_shader_pgm_rsrc3_gs = S_00B21C_CU_EN(0xffff) |
1128                                                    S_00B21C_WAVE_LIMIT(0x3F);
1129       shader->ctx_reg.gs.spi_shader_pgm_rsrc4_gs =
1130          (sscreen->info.gfx_level >= GFX11 ? S_00B204_CU_EN_GFX11(1) : S_00B204_CU_EN_GFX10(0xffff)) |
1131          S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(0);
1132 
1133       shader->ctx_reg.gs.vgt_gs_onchip_cntl =
1134          S_028A44_ES_VERTS_PER_SUBGRP(shader->gs_info.es_verts_per_subgroup) |
1135          S_028A44_GS_PRIMS_PER_SUBGRP(shader->gs_info.gs_prims_per_subgroup) |
1136          S_028A44_GS_INST_PRIMS_IN_SUBGRP(shader->gs_info.gs_inst_prims_in_subgroup);
1137       shader->ctx_reg.gs.vgt_gs_max_prims_per_subgroup =
1138          S_028A94_MAX_PRIMS_PER_SUBGROUP(shader->gs_info.max_prims_per_subgroup);
1139       shader->ctx_reg.gs.vgt_esgs_ring_itemsize = shader->key.ge.part.gs.es->info.esgs_itemsize / 4;
1140 
1141       if (es_stage == MESA_SHADER_TESS_EVAL)
1142          si_set_tesseval_regs(sscreen, shader->key.ge.part.gs.es, shader);
1143 
1144       polaris_set_vgt_vertex_reuse(sscreen, shader->key.ge.part.gs.es, shader);
1145    } else {
1146       shader->ctx_reg.gs.spi_shader_pgm_rsrc3_gs = S_00B21C_CU_EN(0xffff) |
1147                                                    S_00B21C_WAVE_LIMIT(0x3F);
1148 
1149       si_pm4_set_reg(pm4, R_00B220_SPI_SHADER_PGM_LO_GS, va >> 8);
1150       si_pm4_set_reg(pm4, R_00B224_SPI_SHADER_PGM_HI_GS,
1151                      S_00B224_MEM_BASE(sscreen->info.address32_hi >> 8));
1152 
1153       si_pm4_set_reg(pm4, R_00B228_SPI_SHADER_PGM_RSRC1_GS,
1154                      S_00B228_VGPRS((shader->config.num_vgprs - 1) / 4) |
1155                         S_00B228_SGPRS((shader->config.num_sgprs - 1) / 8) |
1156                         S_00B228_DX10_CLAMP(1) | S_00B228_FLOAT_MODE(shader->config.float_mode));
1157       si_pm4_set_reg(pm4, R_00B22C_SPI_SHADER_PGM_RSRC2_GS,
1158                      S_00B22C_USER_SGPR(GFX6_GS_NUM_USER_SGPR) |
1159                         S_00B22C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0));
1160    }
1161 }
1162 
gfx10_is_ngg_passthrough(struct si_shader * shader)1163 bool gfx10_is_ngg_passthrough(struct si_shader *shader)
1164 {
1165    struct si_shader_selector *sel = shader->selector;
1166 
1167    /* Never use NGG passthrough if culling is possible even when it's not used by this shader,
1168     * so that we don't get context rolls when enabling and disabling NGG passthrough.
1169     */
1170    if (sel->screen->use_ngg_culling)
1171       return false;
1172 
1173    /* The definition of NGG passthrough is:
1174     * - user GS is turned off (no amplification, no GS instancing, and no culling)
1175     * - VGT_ESGS_RING_ITEMSIZE is ignored (behaving as if it was equal to 1)
1176     * - vertex indices are packed into 1 VGPR
1177     * - Navi23 and later chips can optionally skip the gs_alloc_req message
1178     *
1179     * NGG passthrough still allows the use of LDS.
1180     */
1181    return sel->stage != MESA_SHADER_GEOMETRY && !shader->key.ge.opt.ngg_culling;
1182 }
1183 
1184 /* Common tail code for NGG primitive shaders. */
gfx10_emit_shader_ngg_tail(struct si_context * sctx,struct si_shader * shader)1185 static void gfx10_emit_shader_ngg_tail(struct si_context *sctx, struct si_shader *shader)
1186 {
1187    radeon_begin(&sctx->gfx_cs);
1188    radeon_opt_set_context_reg(sctx, R_0287FC_GE_MAX_OUTPUT_PER_SUBGROUP,
1189                               SI_TRACKED_GE_MAX_OUTPUT_PER_SUBGROUP,
1190                               shader->ctx_reg.ngg.ge_max_output_per_subgroup);
1191    radeon_opt_set_context_reg(sctx, R_028B4C_GE_NGG_SUBGRP_CNTL, SI_TRACKED_GE_NGG_SUBGRP_CNTL,
1192                               shader->ctx_reg.ngg.ge_ngg_subgrp_cntl);
1193    radeon_opt_set_context_reg(sctx, R_028A84_VGT_PRIMITIVEID_EN, SI_TRACKED_VGT_PRIMITIVEID_EN,
1194                               shader->ctx_reg.ngg.vgt_primitiveid_en);
1195    if (sctx->gfx_level < GFX11) {
1196       radeon_opt_set_context_reg(sctx, R_028A44_VGT_GS_ONCHIP_CNTL, SI_TRACKED_VGT_GS_ONCHIP_CNTL,
1197                                  shader->ctx_reg.ngg.vgt_gs_onchip_cntl);
1198    }
1199    radeon_opt_set_context_reg(sctx, R_028B90_VGT_GS_INSTANCE_CNT, SI_TRACKED_VGT_GS_INSTANCE_CNT,
1200                               shader->ctx_reg.ngg.vgt_gs_instance_cnt);
1201    radeon_opt_set_context_reg(sctx, R_028AAC_VGT_ESGS_RING_ITEMSIZE,
1202                               SI_TRACKED_VGT_ESGS_RING_ITEMSIZE,
1203                               shader->ctx_reg.ngg.vgt_esgs_ring_itemsize);
1204    radeon_opt_set_context_reg(sctx, R_0286C4_SPI_VS_OUT_CONFIG, SI_TRACKED_SPI_VS_OUT_CONFIG,
1205                               shader->ctx_reg.ngg.spi_vs_out_config);
1206    radeon_opt_set_context_reg2(
1207       sctx, R_028708_SPI_SHADER_IDX_FORMAT, SI_TRACKED_SPI_SHADER_IDX_FORMAT,
1208       shader->ctx_reg.ngg.spi_shader_idx_format, shader->ctx_reg.ngg.spi_shader_pos_format);
1209    radeon_opt_set_context_reg(sctx, R_028818_PA_CL_VTE_CNTL, SI_TRACKED_PA_CL_VTE_CNTL,
1210                               shader->ctx_reg.ngg.pa_cl_vte_cntl);
1211    radeon_opt_set_context_reg(sctx, R_028838_PA_CL_NGG_CNTL, SI_TRACKED_PA_CL_NGG_CNTL,
1212                               shader->ctx_reg.ngg.pa_cl_ngg_cntl);
1213 
1214    radeon_end_update_context_roll(sctx);
1215 
1216    /* These don't cause a context roll. */
1217    radeon_begin_again(&sctx->gfx_cs);
1218    radeon_opt_set_uconfig_reg(sctx, R_030980_GE_PC_ALLOC, SI_TRACKED_GE_PC_ALLOC,
1219                               shader->ctx_reg.ngg.ge_pc_alloc);
1220    if (sctx->screen->info.spi_cu_en_has_effect) {
1221       radeon_end();
1222       ac_set_reg_cu_en(&sctx->gfx_cs, R_00B21C_SPI_SHADER_PGM_RSRC3_GS,
1223                        shader->ctx_reg.ngg.spi_shader_pgm_rsrc3_gs,
1224                        C_00B21C_CU_EN, 0, &sctx->screen->info,
1225                        (void (*)(void*, unsigned, uint32_t))
1226                        (sctx->gfx_level >= GFX10 ? radeon_set_sh_reg_idx3_func : radeon_set_sh_reg_func));
1227       ac_set_reg_cu_en(&sctx->gfx_cs, R_00B204_SPI_SHADER_PGM_RSRC4_GS,
1228                        shader->ctx_reg.ngg.spi_shader_pgm_rsrc4_gs,
1229                        C_00B204_CU_EN_GFX10, 16, &sctx->screen->info,
1230                        (void (*)(void*, unsigned, uint32_t))
1231                        (sctx->gfx_level >= GFX10 ? radeon_set_sh_reg_idx3_func : radeon_set_sh_reg_func));
1232       sctx->tracked_regs.reg_saved &= ~BITFIELD64_BIT(SI_TRACKED_SPI_SHADER_PGM_RSRC4_GS) &
1233                                       ~BITFIELD64_BIT(SI_TRACKED_SPI_SHADER_PGM_RSRC3_GS);
1234    } else {
1235       radeon_opt_set_sh_reg_idx3(sctx, R_00B21C_SPI_SHADER_PGM_RSRC3_GS,
1236                                  SI_TRACKED_SPI_SHADER_PGM_RSRC3_GS,
1237                                  shader->ctx_reg.ngg.spi_shader_pgm_rsrc3_gs);
1238       radeon_opt_set_sh_reg_idx3(sctx, R_00B204_SPI_SHADER_PGM_RSRC4_GS,
1239                                  SI_TRACKED_SPI_SHADER_PGM_RSRC4_GS,
1240                                  shader->ctx_reg.ngg.spi_shader_pgm_rsrc4_gs);
1241       radeon_end();
1242    }
1243 }
1244 
gfx10_emit_shader_ngg_notess_nogs(struct si_context * sctx)1245 static void gfx10_emit_shader_ngg_notess_nogs(struct si_context *sctx)
1246 {
1247    struct si_shader *shader = sctx->queued.named.gs;
1248    if (!shader)
1249       return;
1250 
1251    gfx10_emit_shader_ngg_tail(sctx, shader);
1252 }
1253 
gfx10_emit_shader_ngg_tess_nogs(struct si_context * sctx)1254 static void gfx10_emit_shader_ngg_tess_nogs(struct si_context *sctx)
1255 {
1256    struct si_shader *shader = sctx->queued.named.gs;
1257    if (!shader)
1258       return;
1259 
1260    radeon_begin(&sctx->gfx_cs);
1261    radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
1262                               shader->vgt_tf_param);
1263    radeon_end_update_context_roll(sctx);
1264 
1265    gfx10_emit_shader_ngg_tail(sctx, shader);
1266 }
1267 
gfx10_emit_shader_ngg_notess_gs(struct si_context * sctx)1268 static void gfx10_emit_shader_ngg_notess_gs(struct si_context *sctx)
1269 {
1270    struct si_shader *shader = sctx->queued.named.gs;
1271    if (!shader)
1272       return;
1273 
1274    radeon_begin(&sctx->gfx_cs);
1275    radeon_opt_set_context_reg(sctx, R_028B38_VGT_GS_MAX_VERT_OUT, SI_TRACKED_VGT_GS_MAX_VERT_OUT,
1276                               shader->ctx_reg.ngg.vgt_gs_max_vert_out);
1277    radeon_end_update_context_roll(sctx);
1278 
1279    gfx10_emit_shader_ngg_tail(sctx, shader);
1280 }
1281 
gfx10_emit_shader_ngg_tess_gs(struct si_context * sctx)1282 static void gfx10_emit_shader_ngg_tess_gs(struct si_context *sctx)
1283 {
1284    struct si_shader *shader = sctx->queued.named.gs;
1285 
1286    if (!shader)
1287       return;
1288 
1289    radeon_begin(&sctx->gfx_cs);
1290    radeon_opt_set_context_reg(sctx, R_028B38_VGT_GS_MAX_VERT_OUT, SI_TRACKED_VGT_GS_MAX_VERT_OUT,
1291                               shader->ctx_reg.ngg.vgt_gs_max_vert_out);
1292    radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
1293                               shader->vgt_tf_param);
1294    radeon_end_update_context_roll(sctx);
1295 
1296    gfx10_emit_shader_ngg_tail(sctx, shader);
1297 }
1298 
si_get_input_prim(const struct si_shader_selector * gs,const union si_shader_key * key)1299 unsigned si_get_input_prim(const struct si_shader_selector *gs, const union si_shader_key *key)
1300 {
1301    if (gs->stage == MESA_SHADER_GEOMETRY)
1302       return gs->info.base.gs.input_primitive;
1303 
1304    if (gs->stage == MESA_SHADER_TESS_EVAL) {
1305       if (gs->info.base.tess.point_mode)
1306          return PIPE_PRIM_POINTS;
1307       if (gs->info.base.tess._primitive_mode == TESS_PRIMITIVE_ISOLINES)
1308          return PIPE_PRIM_LINES;
1309       return PIPE_PRIM_TRIANGLES;
1310    }
1311 
1312    if (key->ge.opt.ngg_culling & SI_NGG_CULL_LINES)
1313       return PIPE_PRIM_LINES;
1314 
1315    return PIPE_PRIM_TRIANGLES; /* worst case for all callers */
1316 }
1317 
si_get_vs_out_cntl(const struct si_shader_selector * sel,const struct si_shader * shader,bool ngg)1318 static unsigned si_get_vs_out_cntl(const struct si_shader_selector *sel,
1319                                    const struct si_shader *shader, bool ngg)
1320 {
1321    /* Clip distances can be killed, but cull distances can't. */
1322    unsigned clipcull_mask = (sel->info.clipdist_mask & ~shader->key.ge.opt.kill_clip_distances) |
1323                             sel->info.culldist_mask;
1324    bool writes_psize = sel->info.writes_psize && !shader->key.ge.opt.kill_pointsize;
1325    bool misc_vec_ena = writes_psize || (sel->info.writes_edgeflag && !ngg) ||
1326                        sel->screen->options.vrs2x2 ||
1327                        sel->info.writes_layer || sel->info.writes_viewport_index;
1328 
1329    return S_02881C_VS_OUT_CCDIST0_VEC_ENA((clipcull_mask & 0x0F) != 0) |
1330           S_02881C_VS_OUT_CCDIST1_VEC_ENA((clipcull_mask & 0xF0) != 0) |
1331           S_02881C_USE_VTX_POINT_SIZE(writes_psize) |
1332           S_02881C_USE_VTX_EDGE_FLAG(sel->info.writes_edgeflag && !ngg) |
1333           S_02881C_USE_VTX_VRS_RATE(sel->screen->options.vrs2x2) |
1334           S_02881C_USE_VTX_RENDER_TARGET_INDX(sel->info.writes_layer) |
1335           S_02881C_USE_VTX_VIEWPORT_INDX(sel->info.writes_viewport_index) |
1336           S_02881C_VS_OUT_MISC_VEC_ENA(misc_vec_ena) |
1337           S_02881C_VS_OUT_MISC_SIDE_BUS_ENA(misc_vec_ena);
1338 }
1339 
1340 /**
1341  * Prepare the PM4 image for \p shader, which will run as a merged ESGS shader
1342  * in NGG mode.
1343  */
gfx10_shader_ngg(struct si_screen * sscreen,struct si_shader * shader)1344 static void gfx10_shader_ngg(struct si_screen *sscreen, struct si_shader *shader)
1345 {
1346    const struct si_shader_selector *gs_sel = shader->selector;
1347    const struct si_shader_info *gs_info = &gs_sel->info;
1348    const gl_shader_stage gs_stage = shader->selector->stage;
1349    const struct si_shader_selector *es_sel =
1350       shader->previous_stage_sel ? shader->previous_stage_sel : shader->selector;
1351    const struct si_shader_info *es_info = &es_sel->info;
1352    const gl_shader_stage es_stage = es_sel->stage;
1353    unsigned num_user_sgprs;
1354    unsigned nparams, es_vgpr_comp_cnt, gs_vgpr_comp_cnt;
1355    uint64_t va;
1356    bool window_space = gs_sel->stage == MESA_SHADER_VERTEX ?
1357                           gs_info->base.vs.window_space_position : 0;
1358    bool es_enable_prim_id = shader->key.ge.mono.u.vs_export_prim_id || es_info->uses_primid;
1359    unsigned gs_num_invocations = gs_sel->stage == MESA_SHADER_GEOMETRY ?
1360                                     MAX2(gs_info->base.gs.invocations, 1) : 0;
1361    unsigned input_prim = si_get_input_prim(gs_sel, &shader->key);
1362    bool break_wave_at_eoi = false;
1363    struct si_pm4_state *pm4 = si_get_shader_pm4_state(shader);
1364    if (!pm4)
1365       return;
1366 
1367    if (es_stage == MESA_SHADER_TESS_EVAL) {
1368       pm4->atom.emit = gs_stage == MESA_SHADER_GEOMETRY ? gfx10_emit_shader_ngg_tess_gs
1369                                                        : gfx10_emit_shader_ngg_tess_nogs;
1370    } else {
1371       pm4->atom.emit = gs_stage == MESA_SHADER_GEOMETRY ? gfx10_emit_shader_ngg_notess_gs
1372                                                        : gfx10_emit_shader_ngg_notess_nogs;
1373    }
1374 
1375    va = shader->bo->gpu_address;
1376 
1377    if (es_stage == MESA_SHADER_VERTEX) {
1378       es_vgpr_comp_cnt = si_get_vs_vgpr_comp_cnt(sscreen, shader, false);
1379 
1380       if (es_info->base.vs.blit_sgprs_amd) {
1381          num_user_sgprs =
1382             SI_SGPR_VS_BLIT_DATA + es_info->base.vs.blit_sgprs_amd;
1383       } else {
1384          num_user_sgprs = si_get_num_vs_user_sgprs(shader, GFX9_GS_NUM_USER_SGPR);
1385       }
1386    } else {
1387       assert(es_stage == MESA_SHADER_TESS_EVAL);
1388       es_vgpr_comp_cnt = es_enable_prim_id ? 3 : 2;
1389       num_user_sgprs = GFX9_GS_NUM_USER_SGPR;
1390 
1391       if (es_enable_prim_id || gs_info->uses_primid)
1392          break_wave_at_eoi = true;
1393    }
1394 
1395    /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
1396     * VGPR[0:4] are always loaded.
1397     *
1398     * Vertex shaders always need to load VGPR3, because they need to
1399     * pass edge flags for decomposed primitives (such as quads) to the PA
1400     * for the GL_LINE polygon mode to skip rendering lines on inner edges.
1401     */
1402    if (gs_info->uses_invocationid ||
1403        (gfx10_edgeflags_have_effect(shader) && !gfx10_is_ngg_passthrough(shader)))
1404       gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID, edge flags. */
1405    else if ((gs_stage == MESA_SHADER_GEOMETRY && gs_info->uses_primid) ||
1406             (gs_stage == MESA_SHADER_VERTEX && shader->key.ge.mono.u.vs_export_prim_id))
1407       gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
1408    else if (input_prim >= PIPE_PRIM_TRIANGLES && !gfx10_is_ngg_passthrough(shader))
1409       gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
1410    else
1411       gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
1412 
1413    unsigned late_alloc_wave64, cu_mask;
1414 
1415    ac_compute_late_alloc(&sscreen->info, true, shader->key.ge.opt.ngg_culling,
1416                          shader->config.scratch_bytes_per_wave > 0,
1417                          &late_alloc_wave64, &cu_mask);
1418 
1419    si_pm4_set_reg(pm4, R_00B320_SPI_SHADER_PGM_LO_ES, va >> 8);
1420    si_pm4_set_reg(
1421       pm4, R_00B228_SPI_SHADER_PGM_RSRC1_GS,
1422       S_00B228_VGPRS((shader->config.num_vgprs - 1) / (shader->wave_size == 32 ? 8 : 4)) |
1423          S_00B228_FLOAT_MODE(shader->config.float_mode) | S_00B228_DX10_CLAMP(1) |
1424          S_00B228_MEM_ORDERED(si_shader_mem_ordered(shader)) |
1425          /* Disable the WGP mode on gfx10.3 because it can hang. (it happened on VanGogh)
1426           * Let's disable it on all chips that disable exactly 1 CU per SA for GS. */
1427          S_00B228_WGP_MODE(sscreen->info.gfx_level == GFX10) |
1428          S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt));
1429    si_pm4_set_reg(pm4, R_00B22C_SPI_SHADER_PGM_RSRC2_GS,
1430                   S_00B22C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0) |
1431                      S_00B22C_USER_SGPR(num_user_sgprs) |
1432                      S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
1433                      S_00B22C_USER_SGPR_MSB_GFX10(num_user_sgprs >> 5) |
1434                      S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL) |
1435                      S_00B22C_LDS_SIZE(shader->config.lds_size));
1436 
1437    shader->ctx_reg.ngg.spi_shader_pgm_rsrc3_gs = S_00B21C_CU_EN(cu_mask) |
1438                                                  S_00B21C_WAVE_LIMIT(0x3F);
1439    if (sscreen->info.gfx_level >= GFX11) {
1440       shader->ctx_reg.ngg.spi_shader_pgm_rsrc4_gs =
1441          S_00B204_CU_EN_GFX11(0x1) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(late_alloc_wave64) |
1442          S_00B204_INST_PREF_SIZE(si_get_shader_prefetch_size(shader));
1443    } else {
1444       shader->ctx_reg.ngg.spi_shader_pgm_rsrc4_gs =
1445          S_00B204_CU_EN_GFX10(0xffff) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(late_alloc_wave64);
1446    }
1447 
1448    nparams = MAX2(shader->info.nr_param_exports, 1);
1449    shader->ctx_reg.ngg.spi_vs_out_config =
1450       S_0286C4_VS_EXPORT_COUNT(nparams - 1) |
1451       S_0286C4_NO_PC_EXPORT(shader->info.nr_param_exports == 0);
1452 
1453    shader->ctx_reg.ngg.spi_shader_idx_format =
1454       S_028708_IDX0_EXPORT_FORMAT(V_028708_SPI_SHADER_1COMP);
1455    shader->ctx_reg.ngg.spi_shader_pos_format =
1456       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
1457       S_02870C_POS1_EXPORT_FORMAT(shader->info.nr_pos_exports > 1 ? V_02870C_SPI_SHADER_4COMP
1458                                                                   : V_02870C_SPI_SHADER_NONE) |
1459       S_02870C_POS2_EXPORT_FORMAT(shader->info.nr_pos_exports > 2 ? V_02870C_SPI_SHADER_4COMP
1460                                                                   : V_02870C_SPI_SHADER_NONE) |
1461       S_02870C_POS3_EXPORT_FORMAT(shader->info.nr_pos_exports > 3 ? V_02870C_SPI_SHADER_4COMP
1462                                                                   : V_02870C_SPI_SHADER_NONE);
1463 
1464    shader->ctx_reg.ngg.vgt_primitiveid_en =
1465       S_028A84_PRIMITIVEID_EN(es_enable_prim_id) |
1466       S_028A84_NGG_DISABLE_PROVOK_REUSE(shader->key.ge.mono.u.vs_export_prim_id ||
1467                                         gs_sel->info.writes_primid);
1468 
1469    if (gs_stage == MESA_SHADER_GEOMETRY) {
1470       shader->ctx_reg.ngg.vgt_esgs_ring_itemsize = es_sel->info.esgs_itemsize / 4;
1471       shader->ctx_reg.ngg.vgt_gs_max_vert_out = gs_sel->info.base.gs.vertices_out;
1472    } else {
1473       shader->ctx_reg.ngg.vgt_esgs_ring_itemsize = 1;
1474    }
1475 
1476    if (es_stage == MESA_SHADER_TESS_EVAL)
1477       si_set_tesseval_regs(sscreen, es_sel, shader);
1478 
1479    shader->ctx_reg.ngg.ge_max_output_per_subgroup =
1480       S_0287FC_MAX_VERTS_PER_SUBGROUP(shader->ngg.max_out_verts);
1481    shader->ctx_reg.ngg.ge_ngg_subgrp_cntl = S_028B4C_PRIM_AMP_FACTOR(shader->ngg.prim_amp_factor) |
1482                                             S_028B4C_THDS_PER_SUBGRP(0); /* for fast launch */
1483    shader->ctx_reg.ngg.vgt_gs_instance_cnt =
1484       S_028B90_CNT(gs_num_invocations) | S_028B90_ENABLE(gs_num_invocations > 1) |
1485       S_028B90_EN_MAX_VERT_OUT_PER_GS_INSTANCE(shader->ngg.max_vert_out_per_gs_instance);
1486 
1487    /* Output hw-generated edge flags if needed and pass them via the prim
1488     * export to prevent drawing lines on internal edges of decomposed
1489     * primitives (such as quads) with polygon mode = lines.
1490     */
1491    shader->ctx_reg.ngg.pa_cl_ngg_cntl =
1492       S_028838_INDEX_BUF_EDGE_FLAG_ENA(gfx10_edgeflags_have_effect(shader)) |
1493       /* Reuse for NGG. */
1494       S_028838_VERTEX_REUSE_DEPTH(sscreen->info.gfx_level >= GFX10_3 ? 30 : 0);
1495    shader->pa_cl_vs_out_cntl = si_get_vs_out_cntl(shader->selector, shader, true);
1496 
1497    /* Oversubscribe PC. This improves performance when there are too many varyings. */
1498    unsigned oversub_pc_factor = 1;
1499 
1500    if (shader->key.ge.opt.ngg_culling) {
1501       /* Be more aggressive with NGG culling. */
1502       if (shader->info.nr_param_exports > 4)
1503          oversub_pc_factor = 4;
1504       else if (shader->info.nr_param_exports > 2)
1505          oversub_pc_factor = 3;
1506       else
1507          oversub_pc_factor = 2;
1508    }
1509 
1510    unsigned oversub_pc_lines =
1511       late_alloc_wave64 ? (sscreen->info.pc_lines / 4) * oversub_pc_factor : 0;
1512    shader->ctx_reg.ngg.ge_pc_alloc = S_030980_OVERSUB_EN(oversub_pc_lines > 0) |
1513                                      S_030980_NUM_PC_LINES(oversub_pc_lines - 1);
1514 
1515    if (sscreen->info.gfx_level >= GFX11) {
1516       shader->ge_cntl = S_03096C_PRIMS_PER_SUBGRP(shader->ngg.max_gsprims) |
1517                         S_03096C_VERTS_PER_SUBGRP(shader->ngg.hw_max_esverts) |
1518                         S_03096C_BREAK_PRIMGRP_AT_EOI(break_wave_at_eoi) |
1519                         S_03096C_PRIM_GRP_SIZE_GFX11(252 / MAX2(shader->ngg.prim_amp_factor, 1));
1520    } else {
1521       shader->ge_cntl = S_03096C_PRIM_GRP_SIZE_GFX10(shader->ngg.max_gsprims) |
1522                         S_03096C_VERT_GRP_SIZE(shader->ngg.hw_max_esverts) |
1523                         S_03096C_BREAK_WAVE_AT_EOI(break_wave_at_eoi);
1524 
1525       shader->ctx_reg.ngg.vgt_gs_onchip_cntl =
1526          S_028A44_ES_VERTS_PER_SUBGRP(shader->ngg.hw_max_esverts) |
1527          S_028A44_GS_PRIMS_PER_SUBGRP(shader->ngg.max_gsprims) |
1528          S_028A44_GS_INST_PRIMS_IN_SUBGRP(shader->ngg.max_gsprims * gs_num_invocations);
1529    }
1530 
1531    /* On gfx10, the GE only checks against the maximum number of ES verts after
1532     * allocating a full GS primitive. So we need to ensure that whenever
1533     * this check passes, there is enough space for a full primitive without
1534     * vertex reuse. VERT_GRP_SIZE=256 doesn't need this. We should always get 256
1535     * if we have enough LDS.
1536     *
1537     * Tessellation is unaffected because it always sets GE_CNTL.VERT_GRP_SIZE = 0.
1538     */
1539    if ((sscreen->info.gfx_level == GFX10) &&
1540        (es_stage == MESA_SHADER_VERTEX || gs_stage == MESA_SHADER_VERTEX) && /* = no tess */
1541        shader->ngg.hw_max_esverts != 256 &&
1542        shader->ngg.hw_max_esverts > 5) {
1543       /* This could be based on the input primitive type. 5 is the worst case
1544        * for primitive types with adjacency.
1545        */
1546       shader->ge_cntl &= C_03096C_VERT_GRP_SIZE;
1547       shader->ge_cntl |= S_03096C_VERT_GRP_SIZE(shader->ngg.hw_max_esverts - 5);
1548    }
1549 
1550    if (window_space) {
1551       shader->ctx_reg.ngg.pa_cl_vte_cntl = S_028818_VTX_XY_FMT(1) | S_028818_VTX_Z_FMT(1);
1552    } else {
1553       shader->ctx_reg.ngg.pa_cl_vte_cntl =
1554          S_028818_VTX_W0_FMT(1) | S_028818_VPORT_X_SCALE_ENA(1) | S_028818_VPORT_X_OFFSET_ENA(1) |
1555          S_028818_VPORT_Y_SCALE_ENA(1) | S_028818_VPORT_Y_OFFSET_ENA(1) |
1556          S_028818_VPORT_Z_SCALE_ENA(1) | S_028818_VPORT_Z_OFFSET_ENA(1);
1557    }
1558 
1559    shader->ctx_reg.ngg.vgt_stages.u.ngg = 1;
1560    shader->ctx_reg.ngg.vgt_stages.u.streamout = si_shader_uses_streamout(shader);
1561    shader->ctx_reg.ngg.vgt_stages.u.ngg_passthrough = gfx10_is_ngg_passthrough(shader);
1562    shader->ctx_reg.ngg.vgt_stages.u.gs_wave32 = shader->wave_size == 32;
1563 }
1564 
si_emit_shader_vs(struct si_context * sctx)1565 static void si_emit_shader_vs(struct si_context *sctx)
1566 {
1567    struct si_shader *shader = sctx->queued.named.vs;
1568    if (!shader)
1569       return;
1570 
1571    radeon_begin(&sctx->gfx_cs);
1572    radeon_opt_set_context_reg(sctx, R_028A40_VGT_GS_MODE, SI_TRACKED_VGT_GS_MODE,
1573                               shader->ctx_reg.vs.vgt_gs_mode);
1574    radeon_opt_set_context_reg(sctx, R_028A84_VGT_PRIMITIVEID_EN, SI_TRACKED_VGT_PRIMITIVEID_EN,
1575                               shader->ctx_reg.vs.vgt_primitiveid_en);
1576 
1577    if (sctx->gfx_level <= GFX8) {
1578       radeon_opt_set_context_reg(sctx, R_028AB4_VGT_REUSE_OFF, SI_TRACKED_VGT_REUSE_OFF,
1579                                  shader->ctx_reg.vs.vgt_reuse_off);
1580    }
1581 
1582    radeon_opt_set_context_reg(sctx, R_0286C4_SPI_VS_OUT_CONFIG, SI_TRACKED_SPI_VS_OUT_CONFIG,
1583                               shader->ctx_reg.vs.spi_vs_out_config);
1584 
1585    radeon_opt_set_context_reg(sctx, R_02870C_SPI_SHADER_POS_FORMAT,
1586                               SI_TRACKED_SPI_SHADER_POS_FORMAT,
1587                               shader->ctx_reg.vs.spi_shader_pos_format);
1588 
1589    radeon_opt_set_context_reg(sctx, R_028818_PA_CL_VTE_CNTL, SI_TRACKED_PA_CL_VTE_CNTL,
1590                               shader->ctx_reg.vs.pa_cl_vte_cntl);
1591 
1592    if (shader->selector->stage == MESA_SHADER_TESS_EVAL)
1593       radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
1594                                  shader->vgt_tf_param);
1595 
1596    if (shader->vgt_vertex_reuse_block_cntl)
1597       radeon_opt_set_context_reg(sctx, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL,
1598                                  SI_TRACKED_VGT_VERTEX_REUSE_BLOCK_CNTL,
1599                                  shader->vgt_vertex_reuse_block_cntl);
1600 
1601    /* Required programming for tessellation. (legacy pipeline only) */
1602    if (sctx->gfx_level >= GFX10 && shader->selector->stage == MESA_SHADER_TESS_EVAL) {
1603       radeon_opt_set_context_reg(sctx, R_028A44_VGT_GS_ONCHIP_CNTL,
1604                                  SI_TRACKED_VGT_GS_ONCHIP_CNTL,
1605                                  S_028A44_ES_VERTS_PER_SUBGRP(250) |
1606                                  S_028A44_GS_PRIMS_PER_SUBGRP(126) |
1607                                  S_028A44_GS_INST_PRIMS_IN_SUBGRP(126));
1608    }
1609 
1610    radeon_end_update_context_roll(sctx);
1611 
1612    /* GE_PC_ALLOC is not a context register, so it doesn't cause a context roll. */
1613    if (sctx->gfx_level >= GFX10) {
1614       radeon_begin_again(&sctx->gfx_cs);
1615       radeon_opt_set_uconfig_reg(sctx, R_030980_GE_PC_ALLOC, SI_TRACKED_GE_PC_ALLOC,
1616                                  shader->ctx_reg.vs.ge_pc_alloc);
1617       radeon_end();
1618    }
1619 }
1620 
1621 /**
1622  * Compute the state for \p shader, which will run as a vertex shader on the
1623  * hardware.
1624  *
1625  * If \p gs is non-NULL, it points to the geometry shader for which this shader
1626  * is the copy shader.
1627  */
si_shader_vs(struct si_screen * sscreen,struct si_shader * shader,struct si_shader_selector * gs)1628 static void si_shader_vs(struct si_screen *sscreen, struct si_shader *shader,
1629                          struct si_shader_selector *gs)
1630 {
1631    const struct si_shader_info *info = &shader->selector->info;
1632    struct si_pm4_state *pm4;
1633    unsigned num_user_sgprs, vgpr_comp_cnt;
1634    uint64_t va;
1635    unsigned nparams, oc_lds_en;
1636    bool window_space = shader->selector->stage == MESA_SHADER_VERTEX ?
1637                           info->base.vs.window_space_position : 0;
1638    bool enable_prim_id = shader->key.ge.mono.u.vs_export_prim_id || info->uses_primid;
1639 
1640    assert(sscreen->info.gfx_level < GFX11);
1641 
1642    pm4 = si_get_shader_pm4_state(shader);
1643    if (!pm4)
1644       return;
1645 
1646    pm4->atom.emit = si_emit_shader_vs;
1647 
1648    /* We always write VGT_GS_MODE in the VS state, because every switch
1649     * between different shader pipelines involving a different GS or no
1650     * GS at all involves a switch of the VS (different GS use different
1651     * copy shaders). On the other hand, when the API switches from a GS to
1652     * no GS and then back to the same GS used originally, the GS state is
1653     * not sent again.
1654     */
1655    if (!gs) {
1656       unsigned mode = V_028A40_GS_OFF;
1657 
1658       /* PrimID needs GS scenario A. */
1659       if (enable_prim_id)
1660          mode = V_028A40_GS_SCENARIO_A;
1661 
1662       shader->ctx_reg.vs.vgt_gs_mode = S_028A40_MODE(mode);
1663       shader->ctx_reg.vs.vgt_primitiveid_en = enable_prim_id;
1664    } else {
1665       shader->ctx_reg.vs.vgt_gs_mode =
1666          ac_vgt_gs_mode(gs->info.base.gs.vertices_out, sscreen->info.gfx_level);
1667       shader->ctx_reg.vs.vgt_primitiveid_en = 0;
1668    }
1669 
1670    if (sscreen->info.gfx_level <= GFX8) {
1671       /* Reuse needs to be set off if we write oViewport. */
1672       shader->ctx_reg.vs.vgt_reuse_off = S_028AB4_REUSE_OFF(info->writes_viewport_index);
1673    }
1674 
1675    va = shader->bo->gpu_address;
1676 
1677    if (gs) {
1678       vgpr_comp_cnt = 0; /* only VertexID is needed for GS-COPY. */
1679       num_user_sgprs = SI_GSCOPY_NUM_USER_SGPR;
1680    } else if (shader->selector->stage == MESA_SHADER_VERTEX) {
1681       vgpr_comp_cnt = si_get_vs_vgpr_comp_cnt(sscreen, shader, enable_prim_id);
1682 
1683       if (info->base.vs.blit_sgprs_amd) {
1684          num_user_sgprs = SI_SGPR_VS_BLIT_DATA + info->base.vs.blit_sgprs_amd;
1685       } else {
1686          num_user_sgprs = si_get_num_vs_user_sgprs(shader, SI_VS_NUM_USER_SGPR);
1687       }
1688    } else if (shader->selector->stage == MESA_SHADER_TESS_EVAL) {
1689       vgpr_comp_cnt = enable_prim_id ? 3 : 2;
1690       num_user_sgprs = SI_TES_NUM_USER_SGPR;
1691    } else
1692       unreachable("invalid shader selector type");
1693 
1694    /* VS is required to export at least one param. */
1695    nparams = MAX2(shader->info.nr_param_exports, 1);
1696    shader->ctx_reg.vs.spi_vs_out_config = S_0286C4_VS_EXPORT_COUNT(nparams - 1);
1697 
1698    if (sscreen->info.gfx_level >= GFX10) {
1699       shader->ctx_reg.vs.spi_vs_out_config |=
1700          S_0286C4_NO_PC_EXPORT(shader->info.nr_param_exports == 0);
1701    }
1702 
1703    shader->ctx_reg.vs.spi_shader_pos_format =
1704       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
1705       S_02870C_POS1_EXPORT_FORMAT(shader->info.nr_pos_exports > 1 ? V_02870C_SPI_SHADER_4COMP
1706                                                                   : V_02870C_SPI_SHADER_NONE) |
1707       S_02870C_POS2_EXPORT_FORMAT(shader->info.nr_pos_exports > 2 ? V_02870C_SPI_SHADER_4COMP
1708                                                                   : V_02870C_SPI_SHADER_NONE) |
1709       S_02870C_POS3_EXPORT_FORMAT(shader->info.nr_pos_exports > 3 ? V_02870C_SPI_SHADER_4COMP
1710                                                                   : V_02870C_SPI_SHADER_NONE);
1711    unsigned late_alloc_wave64, cu_mask;
1712    ac_compute_late_alloc(&sscreen->info, false, false,
1713                          shader->config.scratch_bytes_per_wave > 0,
1714                          &late_alloc_wave64, &cu_mask);
1715 
1716    shader->ctx_reg.vs.ge_pc_alloc = S_030980_OVERSUB_EN(late_alloc_wave64 > 0) |
1717                                     S_030980_NUM_PC_LINES(sscreen->info.pc_lines / 4 - 1);
1718    shader->pa_cl_vs_out_cntl = si_get_vs_out_cntl(shader->selector, shader, false);
1719 
1720    oc_lds_en = shader->selector->stage == MESA_SHADER_TESS_EVAL ? 1 : 0;
1721 
1722    if (sscreen->info.gfx_level >= GFX7) {
1723       ac_set_reg_cu_en(pm4, R_00B118_SPI_SHADER_PGM_RSRC3_VS,
1724                        S_00B118_CU_EN(cu_mask) | S_00B118_WAVE_LIMIT(0x3F),
1725                        C_00B118_CU_EN, 0, &sscreen->info,
1726                        (void (*)(void*, unsigned, uint32_t))
1727                        (sscreen->info.gfx_level >= GFX10 ? si_pm4_set_reg_idx3 : si_pm4_set_reg));
1728       si_pm4_set_reg(pm4, R_00B11C_SPI_SHADER_LATE_ALLOC_VS, S_00B11C_LIMIT(late_alloc_wave64));
1729    }
1730 
1731    si_pm4_set_reg(pm4, R_00B120_SPI_SHADER_PGM_LO_VS, va >> 8);
1732    si_pm4_set_reg(pm4, R_00B124_SPI_SHADER_PGM_HI_VS,
1733                   S_00B124_MEM_BASE(sscreen->info.address32_hi >> 8));
1734 
1735    uint32_t rsrc1 =
1736       S_00B128_VGPRS((shader->config.num_vgprs - 1) / (shader->wave_size == 32 ? 8 : 4)) |
1737       S_00B128_VGPR_COMP_CNT(vgpr_comp_cnt) | S_00B128_DX10_CLAMP(1) |
1738       S_00B128_MEM_ORDERED(si_shader_mem_ordered(shader)) |
1739       S_00B128_FLOAT_MODE(shader->config.float_mode);
1740    uint32_t rsrc2 = S_00B12C_USER_SGPR(num_user_sgprs) | S_00B12C_OC_LDS_EN(oc_lds_en) |
1741                     S_00B12C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
1742 
1743    if (sscreen->info.gfx_level >= GFX10)
1744       rsrc2 |= S_00B12C_USER_SGPR_MSB_GFX10(num_user_sgprs >> 5);
1745    else if (sscreen->info.gfx_level == GFX9)
1746       rsrc2 |= S_00B12C_USER_SGPR_MSB_GFX9(num_user_sgprs >> 5);
1747 
1748    if (sscreen->info.gfx_level <= GFX9)
1749       rsrc1 |= S_00B128_SGPRS((shader->config.num_sgprs - 1) / 8);
1750 
1751    if (!sscreen->use_ngg_streamout && si_shader_uses_streamout(shader)) {
1752       rsrc2 |= S_00B12C_SO_BASE0_EN(!!shader->selector->info.base.xfb_stride[0]) |
1753                S_00B12C_SO_BASE1_EN(!!shader->selector->info.base.xfb_stride[1]) |
1754                S_00B12C_SO_BASE2_EN(!!shader->selector->info.base.xfb_stride[2]) |
1755                S_00B12C_SO_BASE3_EN(!!shader->selector->info.base.xfb_stride[3]) |
1756                S_00B12C_SO_EN(1);
1757    }
1758 
1759    si_pm4_set_reg(pm4, R_00B128_SPI_SHADER_PGM_RSRC1_VS, rsrc1);
1760    si_pm4_set_reg(pm4, R_00B12C_SPI_SHADER_PGM_RSRC2_VS, rsrc2);
1761 
1762    if (window_space)
1763       shader->ctx_reg.vs.pa_cl_vte_cntl = S_028818_VTX_XY_FMT(1) | S_028818_VTX_Z_FMT(1);
1764    else
1765       shader->ctx_reg.vs.pa_cl_vte_cntl =
1766          S_028818_VTX_W0_FMT(1) | S_028818_VPORT_X_SCALE_ENA(1) | S_028818_VPORT_X_OFFSET_ENA(1) |
1767          S_028818_VPORT_Y_SCALE_ENA(1) | S_028818_VPORT_Y_OFFSET_ENA(1) |
1768          S_028818_VPORT_Z_SCALE_ENA(1) | S_028818_VPORT_Z_OFFSET_ENA(1);
1769 
1770    if (shader->selector->stage == MESA_SHADER_TESS_EVAL)
1771       si_set_tesseval_regs(sscreen, shader->selector, shader);
1772 
1773    polaris_set_vgt_vertex_reuse(sscreen, shader->selector, shader);
1774 }
1775 
si_get_spi_shader_col_format(struct si_shader * shader)1776 static unsigned si_get_spi_shader_col_format(struct si_shader *shader)
1777 {
1778    unsigned spi_shader_col_format = shader->key.ps.part.epilog.spi_shader_col_format;
1779    unsigned value = 0, num_mrts = 0;
1780    unsigned i, num_targets = (util_last_bit(spi_shader_col_format) + 3) / 4;
1781 
1782    /* Remove holes in spi_shader_col_format. */
1783    for (i = 0; i < num_targets; i++) {
1784       unsigned spi_format = (spi_shader_col_format >> (i * 4)) & 0xf;
1785 
1786       if (spi_format) {
1787          value |= spi_format << (num_mrts * 4);
1788          num_mrts++;
1789       }
1790    }
1791 
1792    return value;
1793 }
1794 
si_emit_shader_ps(struct si_context * sctx)1795 static void si_emit_shader_ps(struct si_context *sctx)
1796 {
1797    struct si_shader *shader = sctx->queued.named.ps;
1798    if (!shader)
1799       return;
1800 
1801    radeon_begin(&sctx->gfx_cs);
1802    /* R_0286CC_SPI_PS_INPUT_ENA, R_0286D0_SPI_PS_INPUT_ADDR*/
1803    radeon_opt_set_context_reg2(sctx, R_0286CC_SPI_PS_INPUT_ENA, SI_TRACKED_SPI_PS_INPUT_ENA,
1804                                shader->ctx_reg.ps.spi_ps_input_ena,
1805                                shader->ctx_reg.ps.spi_ps_input_addr);
1806 
1807    radeon_opt_set_context_reg(sctx, R_0286E0_SPI_BARYC_CNTL, SI_TRACKED_SPI_BARYC_CNTL,
1808                               shader->ctx_reg.ps.spi_baryc_cntl);
1809    radeon_opt_set_context_reg(sctx, R_0286D8_SPI_PS_IN_CONTROL, SI_TRACKED_SPI_PS_IN_CONTROL,
1810                               shader->ctx_reg.ps.spi_ps_in_control);
1811 
1812    /* R_028710_SPI_SHADER_Z_FORMAT, R_028714_SPI_SHADER_COL_FORMAT */
1813    radeon_opt_set_context_reg2(sctx, R_028710_SPI_SHADER_Z_FORMAT, SI_TRACKED_SPI_SHADER_Z_FORMAT,
1814                                shader->ctx_reg.ps.spi_shader_z_format,
1815                                shader->ctx_reg.ps.spi_shader_col_format);
1816 
1817    radeon_opt_set_context_reg(sctx, R_02823C_CB_SHADER_MASK, SI_TRACKED_CB_SHADER_MASK,
1818                               shader->ctx_reg.ps.cb_shader_mask);
1819    radeon_end_update_context_roll(sctx);
1820 }
1821 
si_shader_ps(struct si_screen * sscreen,struct si_shader * shader)1822 static void si_shader_ps(struct si_screen *sscreen, struct si_shader *shader)
1823 {
1824    struct si_shader_info *info = &shader->selector->info;
1825    struct si_pm4_state *pm4;
1826    unsigned spi_ps_in_control, spi_shader_col_format, cb_shader_mask;
1827    unsigned spi_baryc_cntl = S_0286E0_FRONT_FACE_ALL_BITS(1);
1828    uint64_t va;
1829    unsigned input_ena = shader->config.spi_ps_input_ena;
1830 
1831    /* we need to enable at least one of them, otherwise we hang the GPU */
1832    assert(G_0286CC_PERSP_SAMPLE_ENA(input_ena) || G_0286CC_PERSP_CENTER_ENA(input_ena) ||
1833           G_0286CC_PERSP_CENTROID_ENA(input_ena) || G_0286CC_PERSP_PULL_MODEL_ENA(input_ena) ||
1834           G_0286CC_LINEAR_SAMPLE_ENA(input_ena) || G_0286CC_LINEAR_CENTER_ENA(input_ena) ||
1835           G_0286CC_LINEAR_CENTROID_ENA(input_ena) || G_0286CC_LINE_STIPPLE_TEX_ENA(input_ena));
1836    /* POS_W_FLOAT_ENA requires one of the perspective weights. */
1837    assert(!G_0286CC_POS_W_FLOAT_ENA(input_ena) || G_0286CC_PERSP_SAMPLE_ENA(input_ena) ||
1838           G_0286CC_PERSP_CENTER_ENA(input_ena) || G_0286CC_PERSP_CENTROID_ENA(input_ena) ||
1839           G_0286CC_PERSP_PULL_MODEL_ENA(input_ena));
1840 
1841    /* Validate interpolation optimization flags (read as implications). */
1842    assert(!shader->key.ps.part.prolog.bc_optimize_for_persp ||
1843           (G_0286CC_PERSP_CENTER_ENA(input_ena) && G_0286CC_PERSP_CENTROID_ENA(input_ena)));
1844    assert(!shader->key.ps.part.prolog.bc_optimize_for_linear ||
1845           (G_0286CC_LINEAR_CENTER_ENA(input_ena) && G_0286CC_LINEAR_CENTROID_ENA(input_ena)));
1846    assert(!shader->key.ps.part.prolog.force_persp_center_interp ||
1847           (!G_0286CC_PERSP_SAMPLE_ENA(input_ena) && !G_0286CC_PERSP_CENTROID_ENA(input_ena)));
1848    assert(!shader->key.ps.part.prolog.force_linear_center_interp ||
1849           (!G_0286CC_LINEAR_SAMPLE_ENA(input_ena) && !G_0286CC_LINEAR_CENTROID_ENA(input_ena)));
1850    assert(!shader->key.ps.part.prolog.force_persp_sample_interp ||
1851           (!G_0286CC_PERSP_CENTER_ENA(input_ena) && !G_0286CC_PERSP_CENTROID_ENA(input_ena)));
1852    assert(!shader->key.ps.part.prolog.force_linear_sample_interp ||
1853           (!G_0286CC_LINEAR_CENTER_ENA(input_ena) && !G_0286CC_LINEAR_CENTROID_ENA(input_ena)));
1854 
1855    /* Validate cases when the optimizations are off (read as implications). */
1856    assert(shader->key.ps.part.prolog.bc_optimize_for_persp ||
1857           !G_0286CC_PERSP_CENTER_ENA(input_ena) || !G_0286CC_PERSP_CENTROID_ENA(input_ena));
1858    assert(shader->key.ps.part.prolog.bc_optimize_for_linear ||
1859           !G_0286CC_LINEAR_CENTER_ENA(input_ena) || !G_0286CC_LINEAR_CENTROID_ENA(input_ena));
1860 
1861    /* DB_SHADER_CONTROL */
1862    unsigned db_shader_control =
1863       S_02880C_Z_EXPORT_ENABLE(info->writes_z) |
1864       S_02880C_STENCIL_TEST_VAL_EXPORT_ENABLE(info->writes_stencil) |
1865       S_02880C_MASK_EXPORT_ENABLE(info->writes_samplemask) |
1866       S_02880C_KILL_ENABLE(si_shader_uses_discard(shader));
1867 
1868    switch (info->base.fs.depth_layout) {
1869    case FRAG_DEPTH_LAYOUT_GREATER:
1870       db_shader_control |= S_02880C_CONSERVATIVE_Z_EXPORT(V_02880C_EXPORT_GREATER_THAN_Z);
1871       break;
1872    case FRAG_DEPTH_LAYOUT_LESS:
1873       db_shader_control |= S_02880C_CONSERVATIVE_Z_EXPORT(V_02880C_EXPORT_LESS_THAN_Z);
1874       break;
1875    default:;
1876    }
1877 
1878    /* Z_ORDER, EXEC_ON_HIER_FAIL and EXEC_ON_NOOP should be set as following:
1879     *
1880     *   | early Z/S | writes_mem | allow_ReZ? |      Z_ORDER       | EXEC_ON_HIER_FAIL | EXEC_ON_NOOP
1881     * --|-----------|------------|------------|--------------------|-------------------|-------------
1882     * 1a|   false   |   false    |   true     | EarlyZ_Then_ReZ    |         0         |     0
1883     * 1b|   false   |   false    |   false    | EarlyZ_Then_LateZ  |         0         |     0
1884     * 2 |   false   |   true     |   n/a      |       LateZ        |         1         |     0
1885     * 3 |   true    |   false    |   n/a      | EarlyZ_Then_LateZ  |         0         |     0
1886     * 4 |   true    |   true     |   n/a      | EarlyZ_Then_LateZ  |         0         |     1
1887     *
1888     * In cases 3 and 4, HW will force Z_ORDER to EarlyZ regardless of what's set in the register.
1889     * In case 2, NOOP_CULL is a don't care field. In case 2, 3 and 4, ReZ doesn't make sense.
1890     *
1891     * Don't use ReZ without profiling !!!
1892     *
1893     * ReZ decreases performance by 15% in DiRT: Showdown on Ultra settings, which has pretty complex
1894     * shaders.
1895     */
1896    if (info->base.fs.early_fragment_tests) {
1897       /* Cases 3, 4. */
1898       db_shader_control |= S_02880C_DEPTH_BEFORE_SHADER(1) |
1899                            S_02880C_Z_ORDER(V_02880C_EARLY_Z_THEN_LATE_Z) |
1900                            S_02880C_EXEC_ON_NOOP(info->base.writes_memory);
1901    } else if (info->base.writes_memory) {
1902       /* Case 2. */
1903       db_shader_control |= S_02880C_Z_ORDER(V_02880C_LATE_Z) | S_02880C_EXEC_ON_HIER_FAIL(1);
1904    } else {
1905       /* Case 1. */
1906       db_shader_control |= S_02880C_Z_ORDER(V_02880C_EARLY_Z_THEN_LATE_Z);
1907    }
1908 
1909    if (info->base.fs.post_depth_coverage)
1910       db_shader_control |= S_02880C_PRE_SHADER_DEPTH_COVERAGE_ENABLE(1);
1911 
1912    shader->ctx_reg.ps.db_shader_control = db_shader_control;
1913 
1914    pm4 = si_get_shader_pm4_state(shader);
1915    if (!pm4)
1916       return;
1917 
1918    /* If multiple state sets are allowed to be in a bin, break the batch on a new PS. */
1919    if (sscreen->dpbb_allowed &&
1920        (sscreen->pbb_context_states_per_bin > 1 ||
1921         sscreen->pbb_persistent_states_per_bin > 1)) {
1922       si_pm4_cmd_add(pm4, PKT3(PKT3_EVENT_WRITE, 0, 0));
1923       si_pm4_cmd_add(pm4, EVENT_TYPE(V_028A90_BREAK_BATCH) | EVENT_INDEX(0));
1924    }
1925 
1926    pm4->atom.emit = si_emit_shader_ps;
1927 
1928    /* SPI_BARYC_CNTL.POS_FLOAT_LOCATION
1929     * Possible vaules:
1930     * 0 -> Position = pixel center
1931     * 1 -> Position = pixel centroid
1932     * 2 -> Position = at sample position
1933     *
1934     * From GLSL 4.5 specification, section 7.1:
1935     *   "The variable gl_FragCoord is available as an input variable from
1936     *    within fragment shaders and it holds the window relative coordinates
1937     *    (x, y, z, 1/w) values for the fragment. If multi-sampling, this
1938     *    value can be for any location within the pixel, or one of the
1939     *    fragment samples. The use of centroid does not further restrict
1940     *    this value to be inside the current primitive."
1941     *
1942     * Meaning that centroid has no effect and we can return anything within
1943     * the pixel. Thus, return the value at sample position, because that's
1944     * the most accurate one shaders can get.
1945     */
1946    spi_baryc_cntl |= S_0286E0_POS_FLOAT_LOCATION(2);
1947 
1948    if (info->base.fs.pixel_center_integer)
1949       spi_baryc_cntl |= S_0286E0_POS_FLOAT_ULC(1);
1950 
1951    spi_shader_col_format = si_get_spi_shader_col_format(shader);
1952    cb_shader_mask = ac_get_cb_shader_mask(shader->key.ps.part.epilog.spi_shader_col_format);
1953 
1954    /* Ensure that some export memory is always allocated, for two reasons:
1955     *
1956     * 1) Correctness: The hardware ignores the EXEC mask if no export
1957     *    memory is allocated, so KILL and alpha test do not work correctly
1958     *    without this.
1959     * 2) Performance: Every shader needs at least a NULL export, even when
1960     *    it writes no color/depth output. The NULL export instruction
1961     *    stalls without this setting.
1962     *
1963     * Don't add this to CB_SHADER_MASK.
1964     *
1965     * GFX10 supports pixel shaders without exports by setting both
1966     * the color and Z formats to SPI_SHADER_ZERO. The hw will skip export
1967     * instructions if any are present.
1968     */
1969    bool has_mrtz = info->writes_z || info->writes_stencil || info->writes_samplemask;
1970 
1971    if (!spi_shader_col_format && !has_mrtz) {
1972       if (sscreen->info.gfx_level >= GFX10) {
1973          if (G_02880C_KILL_ENABLE(db_shader_control))
1974             spi_shader_col_format = V_028714_SPI_SHADER_32_R;
1975       } else {
1976          spi_shader_col_format = V_028714_SPI_SHADER_32_R;
1977       }
1978    }
1979 
1980    shader->ctx_reg.ps.spi_ps_input_ena = input_ena;
1981    shader->ctx_reg.ps.spi_ps_input_addr = shader->config.spi_ps_input_addr;
1982 
1983    unsigned num_interp = si_get_ps_num_interp(shader);
1984 
1985    /* Set interpolation controls. */
1986    spi_ps_in_control = S_0286D8_NUM_INTERP(num_interp) |
1987                        S_0286D8_PS_W32_EN(shader->wave_size == 32);
1988 
1989    /* Enable PARAM_GEN for point smoothing.
1990     * Gfx11 workaround when there are no PS inputs but LDS is used.
1991     */
1992    if ((sscreen->info.gfx_level == GFX11 && !num_interp && shader->config.lds_size) ||
1993        shader->key.ps.mono.point_smoothing)
1994       spi_ps_in_control |= S_0286D8_PARAM_GEN(1);
1995 
1996    shader->ctx_reg.ps.num_interp = num_interp;
1997    shader->ctx_reg.ps.spi_baryc_cntl = spi_baryc_cntl;
1998    shader->ctx_reg.ps.spi_ps_in_control = spi_ps_in_control;
1999    shader->ctx_reg.ps.spi_shader_z_format =
2000       ac_get_spi_shader_z_format(info->writes_z, info->writes_stencil, info->writes_samplemask,
2001                                  shader->key.ps.part.epilog.alpha_to_coverage_via_mrtz);
2002    shader->ctx_reg.ps.spi_shader_col_format = spi_shader_col_format;
2003    shader->ctx_reg.ps.cb_shader_mask = cb_shader_mask;
2004 
2005    va = shader->bo->gpu_address;
2006    si_pm4_set_reg(pm4, R_00B020_SPI_SHADER_PGM_LO_PS, va >> 8);
2007    si_pm4_set_reg(pm4, R_00B024_SPI_SHADER_PGM_HI_PS,
2008                   S_00B024_MEM_BASE(sscreen->info.address32_hi >> 8));
2009 
2010    uint32_t rsrc1 =
2011       S_00B028_VGPRS((shader->config.num_vgprs - 1) / (shader->wave_size == 32 ? 8 : 4)) |
2012       S_00B028_DX10_CLAMP(1) | S_00B028_MEM_ORDERED(si_shader_mem_ordered(shader)) |
2013       S_00B028_FLOAT_MODE(shader->config.float_mode);
2014 
2015    if (sscreen->info.gfx_level < GFX10) {
2016       rsrc1 |= S_00B028_SGPRS((shader->config.num_sgprs - 1) / 8);
2017    }
2018 
2019    si_pm4_set_reg(pm4, R_00B028_SPI_SHADER_PGM_RSRC1_PS, rsrc1);
2020    si_pm4_set_reg(pm4, R_00B02C_SPI_SHADER_PGM_RSRC2_PS,
2021                   S_00B02C_EXTRA_LDS_SIZE(shader->config.lds_size) |
2022                      S_00B02C_USER_SGPR(SI_PS_NUM_USER_SGPR) |
2023                      S_00B32C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0));
2024 
2025    if (sscreen->info.gfx_level >= GFX11) {
2026       unsigned cu_mask_ps = gfx103_get_cu_mask_ps(sscreen);
2027 
2028       ac_set_reg_cu_en(pm4, R_00B004_SPI_SHADER_PGM_RSRC4_PS,
2029                        S_00B004_INST_PREF_SIZE(si_get_shader_prefetch_size(shader)) |
2030                        S_00B004_CU_EN(cu_mask_ps >> 16),
2031                        C_00B004_CU_EN, 16, &sscreen->info,
2032                        (void (*)(void*, unsigned, uint32_t))si_pm4_set_reg_idx3);
2033    }
2034 }
2035 
si_shader_init_pm4_state(struct si_screen * sscreen,struct si_shader * shader)2036 static void si_shader_init_pm4_state(struct si_screen *sscreen, struct si_shader *shader)
2037 {
2038    assert(shader->wave_size);
2039 
2040    switch (shader->selector->stage) {
2041    case MESA_SHADER_VERTEX:
2042       if (shader->key.ge.as_ls)
2043          si_shader_ls(sscreen, shader);
2044       else if (shader->key.ge.as_es)
2045          si_shader_es(sscreen, shader);
2046       else if (shader->key.ge.as_ngg)
2047          gfx10_shader_ngg(sscreen, shader);
2048       else
2049          si_shader_vs(sscreen, shader, NULL);
2050       break;
2051    case MESA_SHADER_TESS_CTRL:
2052       si_shader_hs(sscreen, shader);
2053       break;
2054    case MESA_SHADER_TESS_EVAL:
2055       if (shader->key.ge.as_es)
2056          si_shader_es(sscreen, shader);
2057       else if (shader->key.ge.as_ngg)
2058          gfx10_shader_ngg(sscreen, shader);
2059       else
2060          si_shader_vs(sscreen, shader, NULL);
2061       break;
2062    case MESA_SHADER_GEOMETRY:
2063       if (shader->key.ge.as_ngg) {
2064          gfx10_shader_ngg(sscreen, shader);
2065       } else {
2066          /* VS must be initialized first because GS uses its fields. */
2067          si_shader_vs(sscreen, shader->gs_copy_shader, shader->selector);
2068          si_shader_gs(sscreen, shader);
2069       }
2070       break;
2071    case MESA_SHADER_FRAGMENT:
2072       si_shader_ps(sscreen, shader);
2073       break;
2074    default:
2075       assert(0);
2076    }
2077 }
2078 
si_clear_vs_key_inputs(struct si_context * sctx,union si_shader_key * key,struct si_vs_prolog_bits * prolog_key)2079 static void si_clear_vs_key_inputs(struct si_context *sctx, union si_shader_key *key,
2080                                    struct si_vs_prolog_bits *prolog_key)
2081 {
2082    prolog_key->instance_divisor_is_one = 0;
2083    prolog_key->instance_divisor_is_fetched = 0;
2084    key->ge.mono.vs_fetch_opencode = 0;
2085    memset(key->ge.mono.vs_fix_fetch, 0, sizeof(key->ge.mono.vs_fix_fetch));
2086 }
2087 
si_vs_key_update_inputs(struct si_context * sctx)2088 void si_vs_key_update_inputs(struct si_context *sctx)
2089 {
2090    struct si_shader_selector *vs = sctx->shader.vs.cso;
2091    struct si_vertex_elements *elts = sctx->vertex_elements;
2092    union si_shader_key *key = &sctx->shader.vs.key;
2093 
2094    if (!vs)
2095       return;
2096 
2097    if (vs->info.base.vs.blit_sgprs_amd) {
2098       si_clear_vs_key_inputs(sctx, key, &key->ge.part.vs.prolog);
2099       key->ge.opt.prefer_mono = 0;
2100       sctx->uses_nontrivial_vs_prolog = false;
2101       return;
2102    }
2103 
2104    bool uses_nontrivial_vs_prolog = false;
2105 
2106    if (elts->instance_divisor_is_one || elts->instance_divisor_is_fetched)
2107       uses_nontrivial_vs_prolog = true;
2108 
2109    key->ge.part.vs.prolog.instance_divisor_is_one = elts->instance_divisor_is_one;
2110    key->ge.part.vs.prolog.instance_divisor_is_fetched = elts->instance_divisor_is_fetched;
2111    key->ge.opt.prefer_mono = elts->instance_divisor_is_fetched;
2112 
2113    unsigned count_mask = (1 << vs->info.num_inputs) - 1;
2114    unsigned fix = elts->fix_fetch_always & count_mask;
2115    unsigned opencode = elts->fix_fetch_opencode & count_mask;
2116 
2117    if (sctx->vertex_buffer_unaligned & elts->vb_alignment_check_mask) {
2118       uint32_t mask = elts->fix_fetch_unaligned & count_mask;
2119       while (mask) {
2120          unsigned i = u_bit_scan(&mask);
2121          unsigned log_hw_load_size = 1 + ((elts->hw_load_is_dword >> i) & 1);
2122          unsigned vbidx = elts->vertex_buffer_index[i];
2123          struct pipe_vertex_buffer *vb = &sctx->vertex_buffer[vbidx];
2124          unsigned align_mask = (1 << log_hw_load_size) - 1;
2125          if (vb->buffer_offset & align_mask || vb->stride & align_mask) {
2126             fix |= 1 << i;
2127             opencode |= 1 << i;
2128          }
2129       }
2130    }
2131 
2132    memset(key->ge.mono.vs_fix_fetch, 0, sizeof(key->ge.mono.vs_fix_fetch));
2133 
2134    while (fix) {
2135       unsigned i = u_bit_scan(&fix);
2136       uint8_t fix_fetch = elts->fix_fetch[i];
2137 
2138       key->ge.mono.vs_fix_fetch[i].bits = fix_fetch;
2139       if (fix_fetch)
2140          uses_nontrivial_vs_prolog = true;
2141    }
2142    key->ge.mono.vs_fetch_opencode = opencode;
2143    if (opencode)
2144       uses_nontrivial_vs_prolog = true;
2145 
2146    sctx->uses_nontrivial_vs_prolog = uses_nontrivial_vs_prolog;
2147 
2148    /* draw_vertex_state (display lists) requires a trivial VS prolog that ignores
2149     * the current vertex buffers and vertex elements.
2150     *
2151     * We just computed the prolog key because we needed to set uses_nontrivial_vs_prolog,
2152     * so that we know whether the VS prolog should be updated when we switch from
2153     * draw_vertex_state to draw_vbo. Now clear the VS prolog for draw_vertex_state.
2154     * This should happen rarely because the VS prolog should be trivial in most
2155     * cases.
2156     */
2157    if (uses_nontrivial_vs_prolog && sctx->force_trivial_vs_prolog)
2158       si_clear_vs_key_inputs(sctx, key, &key->ge.part.vs.prolog);
2159 }
2160 
si_get_vs_key_inputs(struct si_context * sctx,union si_shader_key * key,struct si_vs_prolog_bits * prolog_key)2161 void si_get_vs_key_inputs(struct si_context *sctx, union si_shader_key *key,
2162                           struct si_vs_prolog_bits *prolog_key)
2163 {
2164    prolog_key->instance_divisor_is_one = sctx->shader.vs.key.ge.part.vs.prolog.instance_divisor_is_one;
2165    prolog_key->instance_divisor_is_fetched = sctx->shader.vs.key.ge.part.vs.prolog.instance_divisor_is_fetched;
2166 
2167    key->ge.mono.vs_fetch_opencode = sctx->shader.vs.key.ge.mono.vs_fetch_opencode;
2168    memcpy(key->ge.mono.vs_fix_fetch, sctx->shader.vs.key.ge.mono.vs_fix_fetch,
2169           sizeof(key->ge.mono.vs_fix_fetch));
2170 }
2171 
si_update_ps_inputs_read_or_disabled(struct si_context * sctx)2172 void si_update_ps_inputs_read_or_disabled(struct si_context *sctx)
2173 {
2174    struct si_shader_selector *ps = sctx->shader.ps.cso;
2175 
2176    /* Find out if PS is disabled. */
2177    bool ps_disabled = true;
2178    if (ps) {
2179       bool ps_modifies_zs = ps->info.base.fs.uses_discard ||
2180                             ps->info.writes_z ||
2181                             ps->info.writes_stencil ||
2182                             ps->info.writes_samplemask ||
2183                             sctx->queued.named.blend->alpha_to_coverage ||
2184                             sctx->queued.named.dsa->alpha_func != PIPE_FUNC_ALWAYS ||
2185                             sctx->queued.named.rasterizer->poly_stipple_enable ||
2186                             sctx->queued.named.rasterizer->point_smooth;
2187       unsigned ps_colormask = si_get_total_colormask(sctx);
2188 
2189       ps_disabled = sctx->queued.named.rasterizer->rasterizer_discard ||
2190                     (!ps_colormask && !ps_modifies_zs && !ps->info.base.writes_memory);
2191    }
2192 
2193    sctx->ps_inputs_read_or_disabled = ps_disabled ? 0 : ps->info.inputs_read;
2194 }
2195 
si_get_vs_key_outputs(struct si_context * sctx,struct si_shader_selector * vs,union si_shader_key * key)2196 static void si_get_vs_key_outputs(struct si_context *sctx, struct si_shader_selector *vs,
2197                                   union si_shader_key *key)
2198 {
2199    key->ge.opt.kill_clip_distances = vs->info.clipdist_mask & ~sctx->queued.named.rasterizer->clip_plane_enable;
2200 
2201    /* Find out which VS outputs aren't used by the PS. */
2202    uint64_t outputs_written = vs->info.outputs_written_before_ps;
2203    uint64_t linked = outputs_written & sctx->ps_inputs_read_or_disabled;
2204 
2205    key->ge.opt.kill_outputs = ~linked & outputs_written;
2206    key->ge.opt.ngg_culling = sctx->ngg_culling;
2207    key->ge.mono.u.vs_export_prim_id = vs->stage != MESA_SHADER_GEOMETRY &&
2208                                       sctx->shader.ps.cso && sctx->shader.ps.cso->info.uses_primid;
2209    key->ge.opt.kill_pointsize = vs->info.writes_psize &&
2210                                 sctx->current_rast_prim != PIPE_PRIM_POINTS &&
2211                                 !sctx->queued.named.rasterizer->polygon_mode_is_points;
2212    key->ge.opt.remove_streamout = vs->info.enabled_streamout_buffer_mask &&
2213                                   !sctx->streamout.enabled_mask;
2214 }
2215 
si_clear_vs_key_outputs(struct si_context * sctx,struct si_shader_selector * vs,union si_shader_key * key)2216 static void si_clear_vs_key_outputs(struct si_context *sctx, struct si_shader_selector *vs,
2217                                     union si_shader_key *key)
2218 {
2219    key->ge.opt.kill_clip_distances = 0;
2220    key->ge.opt.kill_outputs = 0;
2221    key->ge.opt.remove_streamout = 0;
2222    key->ge.opt.ngg_culling = 0;
2223    key->ge.mono.u.vs_export_prim_id = 0;
2224    key->ge.opt.kill_pointsize = 0;
2225 }
2226 
si_ps_key_update_framebuffer(struct si_context * sctx)2227 void si_ps_key_update_framebuffer(struct si_context *sctx)
2228 {
2229    struct si_shader_selector *sel = sctx->shader.ps.cso;
2230    union si_shader_key *key = &sctx->shader.ps.key;
2231 
2232    if (!sel)
2233       return;
2234 
2235    if (sel->info.color0_writes_all_cbufs &&
2236        sel->info.colors_written == 0x1)
2237       key->ps.part.epilog.last_cbuf = MAX2(sctx->framebuffer.state.nr_cbufs, 1) - 1;
2238    else
2239       key->ps.part.epilog.last_cbuf = 0;
2240 
2241    /* ps_uses_fbfetch is true only if the color buffer is bound. */
2242    if (sctx->ps_uses_fbfetch) {
2243       struct pipe_surface *cb0 = sctx->framebuffer.state.cbufs[0];
2244       struct pipe_resource *tex = cb0->texture;
2245 
2246       /* 1D textures are allocated and used as 2D on GFX9. */
2247       key->ps.mono.fbfetch_msaa = sctx->framebuffer.nr_samples > 1;
2248       key->ps.mono.fbfetch_is_1D =
2249          sctx->gfx_level != GFX9 &&
2250          (tex->target == PIPE_TEXTURE_1D || tex->target == PIPE_TEXTURE_1D_ARRAY);
2251       key->ps.mono.fbfetch_layered =
2252          tex->target == PIPE_TEXTURE_1D_ARRAY || tex->target == PIPE_TEXTURE_2D_ARRAY ||
2253          tex->target == PIPE_TEXTURE_CUBE || tex->target == PIPE_TEXTURE_CUBE_ARRAY ||
2254          tex->target == PIPE_TEXTURE_3D;
2255    } else {
2256       key->ps.mono.fbfetch_msaa = 0;
2257       key->ps.mono.fbfetch_is_1D = 0;
2258       key->ps.mono.fbfetch_layered = 0;
2259    }
2260 }
2261 
si_ps_key_update_framebuffer_blend(struct si_context * sctx)2262 void si_ps_key_update_framebuffer_blend(struct si_context *sctx)
2263 {
2264    struct si_shader_selector *sel = sctx->shader.ps.cso;
2265    union si_shader_key *key = &sctx->shader.ps.key;
2266    struct si_state_blend *blend = sctx->queued.named.blend;
2267 
2268    if (!sel)
2269       return;
2270 
2271    /* Select the shader color format based on whether
2272     * blending or alpha are needed.
2273     */
2274    key->ps.part.epilog.spi_shader_col_format =
2275       (blend->blend_enable_4bit & blend->need_src_alpha_4bit &
2276        sctx->framebuffer.spi_shader_col_format_blend_alpha) |
2277       (blend->blend_enable_4bit & ~blend->need_src_alpha_4bit &
2278        sctx->framebuffer.spi_shader_col_format_blend) |
2279       (~blend->blend_enable_4bit & blend->need_src_alpha_4bit &
2280        sctx->framebuffer.spi_shader_col_format_alpha) |
2281       (~blend->blend_enable_4bit & ~blend->need_src_alpha_4bit &
2282        sctx->framebuffer.spi_shader_col_format);
2283    key->ps.part.epilog.spi_shader_col_format &= blend->cb_target_enabled_4bit;
2284 
2285    key->ps.part.epilog.dual_src_blend_swizzle = sctx->gfx_level >= GFX11 &&
2286                                                 blend->dual_src_blend &&
2287                                                 (sel->info.colors_written_4bit & 0xff) == 0xff;
2288 
2289    /* The output for dual source blending should have
2290     * the same format as the first output.
2291     */
2292    if (blend->dual_src_blend) {
2293       key->ps.part.epilog.spi_shader_col_format |=
2294          (key->ps.part.epilog.spi_shader_col_format & 0xf) << 4;
2295    }
2296 
2297    /* If alpha-to-coverage is enabled, we have to export alpha
2298     * even if there is no color buffer.
2299     */
2300    if (!(key->ps.part.epilog.spi_shader_col_format & 0xf) && blend->alpha_to_coverage)
2301       key->ps.part.epilog.spi_shader_col_format |= V_028710_SPI_SHADER_32_AR;
2302 
2303    /* On GFX6 and GFX7 except Hawaii, the CB doesn't clamp outputs
2304     * to the range supported by the type if a channel has less
2305     * than 16 bits and the export format is 16_ABGR.
2306     */
2307    if (sctx->gfx_level <= GFX7 && sctx->family != CHIP_HAWAII) {
2308       key->ps.part.epilog.color_is_int8 = sctx->framebuffer.color_is_int8;
2309       key->ps.part.epilog.color_is_int10 = sctx->framebuffer.color_is_int10;
2310    }
2311 
2312    /* Disable unwritten outputs (if WRITE_ALL_CBUFS isn't enabled). */
2313    if (!key->ps.part.epilog.last_cbuf) {
2314       key->ps.part.epilog.spi_shader_col_format &= sel->info.colors_written_4bit;
2315       key->ps.part.epilog.color_is_int8 &= sel->info.colors_written;
2316       key->ps.part.epilog.color_is_int10 &= sel->info.colors_written;
2317    }
2318 
2319    /* Eliminate shader code computing output values that are unused.
2320     * This enables dead code elimination between shader parts.
2321     * Check if any output is eliminated.
2322     *
2323     * Dual source blending never has color buffer 1 enabled, so ignore it.
2324     *
2325     * On gfx11, pixel shaders that write memory should be compiled with an inlined epilog,
2326     * so that the compiler can see s_endpgm and deallocates VGPRs before memory stores return.
2327     */
2328    if (sel->info.colors_written_4bit &
2329        (blend->dual_src_blend ? 0xffffff0f : 0xffffffff) &
2330        ~(sctx->framebuffer.colorbuf_enabled_4bit & blend->cb_target_enabled_4bit))
2331       key->ps.opt.prefer_mono = 1;
2332    else if (sctx->gfx_level >= GFX11 && sel->info.base.writes_memory)
2333       key->ps.opt.prefer_mono = 1;
2334    else
2335       key->ps.opt.prefer_mono = 0;
2336 }
2337 
si_ps_key_update_blend_rasterizer(struct si_context * sctx)2338 void si_ps_key_update_blend_rasterizer(struct si_context *sctx)
2339 {
2340    union si_shader_key *key = &sctx->shader.ps.key;
2341    struct si_state_blend *blend = sctx->queued.named.blend;
2342    struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
2343    struct si_shader_selector *ps = sctx->shader.ps.cso;
2344 
2345    if (!ps)
2346       return;
2347 
2348    key->ps.part.epilog.alpha_to_one = blend->alpha_to_one && rs->multisample_enable;
2349    key->ps.part.epilog.alpha_to_coverage_via_mrtz =
2350       sctx->gfx_level >= GFX11 && blend->alpha_to_coverage && rs->multisample_enable &&
2351       (ps->info.writes_z || ps->info.writes_stencil || ps->info.writes_samplemask);
2352 }
2353 
si_ps_key_update_rasterizer(struct si_context * sctx)2354 void si_ps_key_update_rasterizer(struct si_context *sctx)
2355 {
2356    struct si_shader_selector *sel = sctx->shader.ps.cso;
2357    union si_shader_key *key = &sctx->shader.ps.key;
2358    struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
2359 
2360    if (!sel)
2361       return;
2362 
2363    key->ps.part.prolog.color_two_side = rs->two_side && sel->info.colors_read;
2364    key->ps.part.prolog.flatshade_colors = rs->flatshade && sel->info.uses_interp_color;
2365    key->ps.part.epilog.clamp_color = rs->clamp_fragment_color;
2366 }
2367 
si_ps_key_update_dsa(struct si_context * sctx)2368 void si_ps_key_update_dsa(struct si_context *sctx)
2369 {
2370    union si_shader_key *key = &sctx->shader.ps.key;
2371 
2372    key->ps.part.epilog.alpha_func = sctx->queued.named.dsa->alpha_func;
2373 }
2374 
si_ps_key_update_primtype_shader_rasterizer_framebuffer(struct si_context * sctx)2375 static void si_ps_key_update_primtype_shader_rasterizer_framebuffer(struct si_context *sctx)
2376 {
2377    union si_shader_key *key = &sctx->shader.ps.key;
2378    struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
2379 
2380    bool is_poly = !util_prim_is_points_or_lines(sctx->current_rast_prim);
2381    bool is_line = util_prim_is_lines(sctx->current_rast_prim);
2382 
2383    key->ps.part.prolog.poly_stipple = rs->poly_stipple_enable && is_poly;
2384    key->ps.mono.poly_line_smoothing =
2385       ((is_poly && rs->poly_smooth) || (is_line && rs->line_smooth)) &&
2386       sctx->framebuffer.nr_samples <= 1;
2387 
2388    key->ps.mono.point_smoothing = rs->point_smooth &&
2389                                   sctx->current_rast_prim == PIPE_PRIM_POINTS;
2390 }
2391 
si_ps_key_update_sample_shading(struct si_context * sctx)2392 void si_ps_key_update_sample_shading(struct si_context *sctx)
2393 {
2394    struct si_shader_selector *sel = sctx->shader.ps.cso;
2395    union si_shader_key *key = &sctx->shader.ps.key;
2396 
2397    if (!sel)
2398       return;
2399 
2400    if (sctx->ps_iter_samples > 1 && sel->info.reads_samplemask)
2401       key->ps.part.prolog.samplemask_log_ps_iter = util_logbase2(sctx->ps_iter_samples);
2402    else
2403       key->ps.part.prolog.samplemask_log_ps_iter = 0;
2404 }
2405 
si_ps_key_update_framebuffer_rasterizer_sample_shading(struct si_context * sctx)2406 void si_ps_key_update_framebuffer_rasterizer_sample_shading(struct si_context *sctx)
2407 {
2408    struct si_shader_selector *sel = sctx->shader.ps.cso;
2409    union si_shader_key *key = &sctx->shader.ps.key;
2410    struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
2411 
2412    if (!sel)
2413       return;
2414 
2415    bool uses_persp_center = sel->info.uses_persp_center ||
2416                             (!rs->flatshade && sel->info.uses_persp_center_color);
2417    bool uses_persp_centroid = sel->info.uses_persp_centroid ||
2418                               (!rs->flatshade && sel->info.uses_persp_centroid_color);
2419    bool uses_persp_sample = sel->info.uses_persp_sample ||
2420                             (!rs->flatshade && sel->info.uses_persp_sample_color);
2421 
2422    if (rs->force_persample_interp && rs->multisample_enable &&
2423        sctx->framebuffer.nr_samples > 1 && sctx->ps_iter_samples > 1) {
2424       key->ps.part.prolog.force_persp_sample_interp =
2425          uses_persp_center || uses_persp_centroid;
2426 
2427       key->ps.part.prolog.force_linear_sample_interp =
2428          sel->info.uses_linear_center || sel->info.uses_linear_centroid;
2429 
2430       key->ps.part.prolog.force_persp_center_interp = 0;
2431       key->ps.part.prolog.force_linear_center_interp = 0;
2432       key->ps.part.prolog.bc_optimize_for_persp = 0;
2433       key->ps.part.prolog.bc_optimize_for_linear = 0;
2434       key->ps.mono.interpolate_at_sample_force_center = 0;
2435    } else if (rs->multisample_enable && sctx->framebuffer.nr_samples > 1) {
2436       key->ps.part.prolog.force_persp_sample_interp = 0;
2437       key->ps.part.prolog.force_linear_sample_interp = 0;
2438       key->ps.part.prolog.force_persp_center_interp = 0;
2439       key->ps.part.prolog.force_linear_center_interp = 0;
2440       key->ps.part.prolog.bc_optimize_for_persp =
2441          uses_persp_center && uses_persp_centroid;
2442       key->ps.part.prolog.bc_optimize_for_linear =
2443          sel->info.uses_linear_center && sel->info.uses_linear_centroid;
2444       key->ps.mono.interpolate_at_sample_force_center = 0;
2445    } else {
2446       key->ps.part.prolog.force_persp_sample_interp = 0;
2447       key->ps.part.prolog.force_linear_sample_interp = 0;
2448 
2449       /* Make sure SPI doesn't compute more than 1 pair
2450        * of (i,j), which is the optimization here. */
2451       key->ps.part.prolog.force_persp_center_interp = uses_persp_center +
2452                                                       uses_persp_centroid +
2453                                                       uses_persp_sample > 1;
2454 
2455       key->ps.part.prolog.force_linear_center_interp = sel->info.uses_linear_center +
2456                                                        sel->info.uses_linear_centroid +
2457                                                        sel->info.uses_linear_sample > 1;
2458       key->ps.part.prolog.bc_optimize_for_persp = 0;
2459       key->ps.part.prolog.bc_optimize_for_linear = 0;
2460       key->ps.mono.interpolate_at_sample_force_center = sel->info.uses_interp_at_sample;
2461    }
2462 }
2463 
2464 /* Compute the key for the hw shader variant */
si_shader_selector_key(struct pipe_context * ctx,struct si_shader_selector * sel,union si_shader_key * key)2465 static inline void si_shader_selector_key(struct pipe_context *ctx, struct si_shader_selector *sel,
2466                                           union si_shader_key *key)
2467 {
2468    struct si_context *sctx = (struct si_context *)ctx;
2469 
2470    switch (sel->stage) {
2471    case MESA_SHADER_VERTEX:
2472       if (!sctx->shader.tes.cso && !sctx->shader.gs.cso)
2473          si_get_vs_key_outputs(sctx, sel, key);
2474       else
2475          si_clear_vs_key_outputs(sctx, sel, key);
2476       break;
2477    case MESA_SHADER_TESS_CTRL:
2478       if (sctx->gfx_level >= GFX9) {
2479          si_get_vs_key_inputs(sctx, key, &key->ge.part.tcs.ls_prolog);
2480          key->ge.part.tcs.ls = sctx->shader.vs.cso;
2481       }
2482       break;
2483    case MESA_SHADER_TESS_EVAL:
2484       if (!sctx->shader.gs.cso)
2485          si_get_vs_key_outputs(sctx, sel, key);
2486       else
2487          si_clear_vs_key_outputs(sctx, sel, key);
2488       break;
2489    case MESA_SHADER_GEOMETRY:
2490       if (sctx->gfx_level >= GFX9) {
2491          if (sctx->shader.tes.cso) {
2492             si_clear_vs_key_inputs(sctx, key, &key->ge.part.gs.vs_prolog);
2493             key->ge.part.gs.es = sctx->shader.tes.cso;
2494          } else {
2495             si_get_vs_key_inputs(sctx, key, &key->ge.part.gs.vs_prolog);
2496             key->ge.part.gs.es = sctx->shader.vs.cso;
2497          }
2498 
2499          /* Only NGG can eliminate GS outputs, because the code is shared with VS. */
2500          if (sctx->ngg)
2501             si_get_vs_key_outputs(sctx, sel, key);
2502          else
2503             si_clear_vs_key_outputs(sctx, sel, key);
2504       }
2505       break;
2506    case MESA_SHADER_FRAGMENT:
2507       si_ps_key_update_primtype_shader_rasterizer_framebuffer(sctx);
2508       break;
2509    default:
2510       assert(0);
2511    }
2512 }
2513 
si_build_shader_variant(struct si_shader * shader,int thread_index,bool low_priority)2514 static void si_build_shader_variant(struct si_shader *shader, int thread_index, bool low_priority)
2515 {
2516    struct si_shader_selector *sel = shader->selector;
2517    struct si_screen *sscreen = sel->screen;
2518    struct ac_llvm_compiler *compiler;
2519    struct util_debug_callback *debug = &shader->compiler_ctx_state.debug;
2520 
2521    if (thread_index >= 0) {
2522       if (low_priority) {
2523          assert(thread_index < (int)ARRAY_SIZE(sscreen->compiler_lowp));
2524          compiler = &sscreen->compiler_lowp[thread_index];
2525       } else {
2526          assert(thread_index < (int)ARRAY_SIZE(sscreen->compiler));
2527          compiler = &sscreen->compiler[thread_index];
2528       }
2529       if (!debug->async)
2530          debug = NULL;
2531    } else {
2532       assert(!low_priority);
2533       compiler = shader->compiler_ctx_state.compiler;
2534    }
2535 
2536    if (!compiler->passes)
2537       si_init_compiler(sscreen, compiler);
2538 
2539    if (unlikely(!si_create_shader_variant(sscreen, compiler, shader, debug))) {
2540       PRINT_ERR("Failed to build shader variant (type=%u)\n", sel->stage);
2541       shader->compilation_failed = true;
2542       return;
2543    }
2544 
2545    if (shader->compiler_ctx_state.is_debug_context) {
2546       FILE *f = open_memstream(&shader->shader_log, &shader->shader_log_size);
2547       if (f) {
2548          si_shader_dump(sscreen, shader, NULL, f, false);
2549          fclose(f);
2550       }
2551    }
2552 
2553    si_shader_init_pm4_state(sscreen, shader);
2554 }
2555 
si_build_shader_variant_low_priority(void * job,void * gdata,int thread_index)2556 static void si_build_shader_variant_low_priority(void *job, void *gdata, int thread_index)
2557 {
2558    struct si_shader *shader = (struct si_shader *)job;
2559 
2560    assert(thread_index >= 0);
2561 
2562    si_build_shader_variant(shader, thread_index, true);
2563 }
2564 
2565 /* This should be const, but C++ doesn't allow implicit zero-initialization with const. */
2566 static union si_shader_key zeroed;
2567 
si_check_missing_main_part(struct si_screen * sscreen,struct si_shader_selector * sel,struct si_compiler_ctx_state * compiler_state,const union si_shader_key * key)2568 static bool si_check_missing_main_part(struct si_screen *sscreen, struct si_shader_selector *sel,
2569                                        struct si_compiler_ctx_state *compiler_state,
2570                                        const union si_shader_key *key)
2571 {
2572    struct si_shader **mainp = si_get_main_shader_part(sel, key);
2573 
2574    if (!*mainp) {
2575       struct si_shader *main_part = CALLOC_STRUCT(si_shader);
2576 
2577       if (!main_part)
2578          return false;
2579 
2580       /* We can leave the fence as permanently signaled because the
2581        * main part becomes visible globally only after it has been
2582        * compiled. */
2583       util_queue_fence_init(&main_part->ready);
2584 
2585       main_part->selector = sel;
2586       if (sel->stage <= MESA_SHADER_GEOMETRY) {
2587          main_part->key.ge.as_es = key->ge.as_es;
2588          main_part->key.ge.as_ls = key->ge.as_ls;
2589          main_part->key.ge.as_ngg = key->ge.as_ngg;
2590       }
2591       main_part->is_monolithic = false;
2592       main_part->wave_size = si_determine_wave_size(sscreen, main_part);
2593 
2594       if (!si_compile_shader(sscreen, compiler_state->compiler, main_part,
2595                              &compiler_state->debug)) {
2596          FREE(main_part);
2597          return false;
2598       }
2599       *mainp = main_part;
2600    }
2601    return true;
2602 }
2603 
2604 /* A helper to copy *key to *local_key and return local_key. */
2605 template<typename SHADER_KEY_TYPE>
2606 static ALWAYS_INLINE const SHADER_KEY_TYPE *
use_local_key_copy(const SHADER_KEY_TYPE * key,SHADER_KEY_TYPE * local_key,unsigned key_size)2607 use_local_key_copy(const SHADER_KEY_TYPE *key, SHADER_KEY_TYPE *local_key, unsigned key_size)
2608 {
2609    if (key != local_key)
2610       memcpy(local_key, key, key_size);
2611 
2612    return local_key;
2613 }
2614 
2615 #define NO_INLINE_UNIFORMS false
2616 
2617 /**
2618  * Select a shader variant according to the shader key.
2619  *
2620  * This uses a C++ template to compute the optimal memcmp size at compile time, which is important
2621  * for getting inlined memcmp. The memcmp size depends on the shader key type and whether inlined
2622  * uniforms are enabled.
2623  */
2624 template<bool INLINE_UNIFORMS = true, typename SHADER_KEY_TYPE>
si_shader_select_with_key(struct si_context * sctx,struct si_shader_ctx_state * state,const SHADER_KEY_TYPE * key)2625 static int si_shader_select_with_key(struct si_context *sctx, struct si_shader_ctx_state *state,
2626                                      const SHADER_KEY_TYPE *key)
2627 {
2628    struct si_screen *sscreen = sctx->screen;
2629    struct si_shader_selector *sel = state->cso;
2630    struct si_shader_selector *previous_stage_sel = NULL;
2631    struct si_shader *current = state->current;
2632    struct si_shader *shader = NULL;
2633    const SHADER_KEY_TYPE *zeroed_key = (SHADER_KEY_TYPE*)&zeroed;
2634 
2635    /* "opt" must be the last field and "inlined_uniform_values" must be the last field inside opt.
2636     * If there is padding, insert the padding manually before opt or inside opt.
2637     */
2638    STATIC_ASSERT(offsetof(SHADER_KEY_TYPE, opt) + sizeof(key->opt) == sizeof(*key));
2639    STATIC_ASSERT(offsetof(SHADER_KEY_TYPE, opt.inlined_uniform_values) +
2640                  sizeof(key->opt.inlined_uniform_values) == sizeof(*key));
2641 
2642    const unsigned key_size_no_uniforms = sizeof(*key) - sizeof(key->opt.inlined_uniform_values);
2643    /* Don't compare inlined_uniform_values if uniform inlining is disabled. */
2644    const unsigned key_size = INLINE_UNIFORMS ? sizeof(*key) : key_size_no_uniforms;
2645    const unsigned key_opt_size =
2646       INLINE_UNIFORMS ? sizeof(key->opt) :
2647                         sizeof(key->opt) - sizeof(key->opt.inlined_uniform_values);
2648 
2649    /* si_shader_select_with_key must not modify 'key' because it would affect future shaders.
2650     * If we need to modify it for this specific shader (eg: to disable optimizations), we
2651     * use a copy.
2652     */
2653    SHADER_KEY_TYPE local_key;
2654 
2655    if (unlikely(sscreen->debug_flags & DBG(NO_OPT_VARIANT))) {
2656       /* Disable shader variant optimizations. */
2657       key = use_local_key_copy<SHADER_KEY_TYPE>(key, &local_key, key_size);
2658       memset(&local_key.opt, 0, key_opt_size);
2659    }
2660 
2661 again:
2662    /* Check if we don't need to change anything.
2663     * This path is also used for most shaders that don't need multiple
2664     * variants, it will cost just a computation of the key and this
2665     * test. */
2666    if (likely(current && memcmp(&current->key, key, key_size) == 0)) {
2667       if (unlikely(!util_queue_fence_is_signalled(&current->ready))) {
2668          if (current->is_optimized) {
2669             key = use_local_key_copy(key, &local_key, key_size);
2670             memset(&local_key.opt, 0, key_opt_size);
2671             goto current_not_ready;
2672          }
2673 
2674          util_queue_fence_wait(&current->ready);
2675       }
2676 
2677       return current->compilation_failed ? -1 : 0;
2678    }
2679 current_not_ready:
2680 
2681    /* This must be done before the mutex is locked, because async GS
2682     * compilation calls this function too, and therefore must enter
2683     * the mutex first.
2684     */
2685    util_queue_fence_wait(&sel->ready);
2686 
2687    simple_mtx_lock(&sel->mutex);
2688 
2689    int variant_count = 0;
2690    const int max_inline_uniforms_variants = 5;
2691 
2692    /* Find the shader variant. */
2693    const unsigned cnt = sel->variants_count;
2694    for (unsigned i = 0; i < cnt; i++) {
2695       const SHADER_KEY_TYPE *iter_key = (const SHADER_KEY_TYPE *)&sel->keys[i];
2696 
2697       if (memcmp(iter_key, key, key_size_no_uniforms) == 0) {
2698          struct si_shader *iter = sel->variants[i];
2699 
2700          /* Check the inlined uniform values separately, and count
2701           * the number of variants based on them.
2702           */
2703          if (key->opt.inline_uniforms &&
2704              memcmp(iter_key->opt.inlined_uniform_values,
2705                     key->opt.inlined_uniform_values,
2706                     MAX_INLINABLE_UNIFORMS * 4) != 0) {
2707             if (variant_count++ > max_inline_uniforms_variants) {
2708                key = use_local_key_copy(key, &local_key, key_size);
2709                /* Too many variants. Disable inlining for this shader. */
2710                local_key.opt.inline_uniforms = 0;
2711                memset(local_key.opt.inlined_uniform_values, 0, MAX_INLINABLE_UNIFORMS * 4);
2712                simple_mtx_unlock(&sel->mutex);
2713                goto again;
2714             }
2715             continue;
2716          }
2717 
2718          simple_mtx_unlock(&sel->mutex);
2719 
2720          if (unlikely(!util_queue_fence_is_signalled(&iter->ready))) {
2721             /* If it's an optimized shader and its compilation has
2722              * been started but isn't done, use the unoptimized
2723              * shader so as not to cause a stall due to compilation.
2724              */
2725             if (iter->is_optimized) {
2726                key = use_local_key_copy(key, &local_key, key_size);
2727                memset(&local_key.opt, 0, key_opt_size);
2728                goto again;
2729             }
2730 
2731             util_queue_fence_wait(&iter->ready);
2732          }
2733 
2734          if (iter->compilation_failed) {
2735             return -1; /* skip the draw call */
2736          }
2737 
2738          state->current = sel->variants[i];
2739          return 0;
2740       }
2741    }
2742 
2743    /* Build a new shader. */
2744    shader = CALLOC_STRUCT(si_shader);
2745    if (!shader) {
2746       simple_mtx_unlock(&sel->mutex);
2747       return -ENOMEM;
2748    }
2749 
2750    util_queue_fence_init(&shader->ready);
2751 
2752    if (!sctx->compiler.passes)
2753       si_init_compiler(sctx->screen, &sctx->compiler);
2754 
2755    shader->selector = sel;
2756    *((SHADER_KEY_TYPE*)&shader->key) = *key;
2757    shader->wave_size = si_determine_wave_size(sscreen, shader);
2758    shader->compiler_ctx_state.compiler = &sctx->compiler;
2759    shader->compiler_ctx_state.debug = sctx->debug;
2760    shader->compiler_ctx_state.is_debug_context = sctx->is_debug;
2761 
2762    /* If this is a merged shader, get the first shader's selector. */
2763    if (sscreen->info.gfx_level >= GFX9) {
2764       if (sel->stage == MESA_SHADER_TESS_CTRL)
2765          previous_stage_sel = ((struct si_shader_key_ge*)key)->part.tcs.ls;
2766       else if (sel->stage == MESA_SHADER_GEOMETRY)
2767          previous_stage_sel = ((struct si_shader_key_ge*)key)->part.gs.es;
2768 
2769       /* We need to wait for the previous shader. */
2770       if (previous_stage_sel)
2771          util_queue_fence_wait(&previous_stage_sel->ready);
2772    }
2773 
2774    bool is_pure_monolithic =
2775       sscreen->use_monolithic_shaders || memcmp(&key->mono, &zeroed_key->mono, sizeof(key->mono)) != 0;
2776 
2777    /* Compile the main shader part if it doesn't exist. This can happen
2778     * if the initial guess was wrong.
2779     */
2780    if (!is_pure_monolithic) {
2781       bool ok = true;
2782 
2783       /* Make sure the main shader part is present. This is needed
2784        * for shaders that can be compiled as VS, LS, or ES, and only
2785        * one of them is compiled at creation.
2786        *
2787        * It is also needed for GS, which can be compiled as non-NGG
2788        * and NGG.
2789        *
2790        * For merged shaders, check that the starting shader's main
2791        * part is present.
2792        */
2793       if (previous_stage_sel) {
2794          union si_shader_key shader1_key = zeroed;
2795 
2796          if (sel->stage == MESA_SHADER_TESS_CTRL) {
2797             shader1_key.ge.as_ls = 1;
2798          } else if (sel->stage == MESA_SHADER_GEOMETRY) {
2799             shader1_key.ge.as_es = 1;
2800             shader1_key.ge.as_ngg = ((struct si_shader_key_ge*)key)->as_ngg; /* for Wave32 vs Wave64 */
2801          } else {
2802             assert(0);
2803          }
2804 
2805          simple_mtx_lock(&previous_stage_sel->mutex);
2806          ok = si_check_missing_main_part(sscreen, previous_stage_sel, &shader->compiler_ctx_state,
2807                                          &shader1_key);
2808          simple_mtx_unlock(&previous_stage_sel->mutex);
2809       }
2810 
2811       if (ok) {
2812          ok = si_check_missing_main_part(sscreen, sel, &shader->compiler_ctx_state,
2813                                          (union si_shader_key*)key);
2814       }
2815 
2816       if (!ok) {
2817          FREE(shader);
2818          simple_mtx_unlock(&sel->mutex);
2819          return -ENOMEM; /* skip the draw call */
2820       }
2821    }
2822 
2823    if (sel->variants_count == sel->variants_max_count) {
2824       sel->variants_max_count += 2;
2825       sel->variants = (struct si_shader**)
2826          realloc(sel->variants, sel->variants_max_count * sizeof(struct si_shader*));
2827       sel->keys = (union si_shader_key*)
2828          realloc(sel->keys, sel->variants_max_count * sizeof(union si_shader_key));
2829    }
2830 
2831    /* Keep the reference to the 1st shader of merged shaders, so that
2832     * Gallium can't destroy it before we destroy the 2nd shader.
2833     *
2834     * Set sctx = NULL, because it's unused if we're not releasing
2835     * the shader, and we don't have any sctx here.
2836     */
2837    si_shader_selector_reference(NULL, &shader->previous_stage_sel, previous_stage_sel);
2838 
2839    /* Monolithic-only shaders don't make a distinction between optimized
2840     * and unoptimized. */
2841    shader->is_monolithic =
2842       is_pure_monolithic || memcmp(&key->opt, &zeroed_key->opt, key_opt_size) != 0;
2843 
2844    shader->is_optimized = !is_pure_monolithic &&
2845                           memcmp(&key->opt, &zeroed_key->opt, key_opt_size) != 0;
2846 
2847    /* If it's an optimized shader, compile it asynchronously. */
2848    if (shader->is_optimized) {
2849       /* Compile it asynchronously. */
2850       util_queue_add_job(&sscreen->shader_compiler_queue_low_priority, shader, &shader->ready,
2851                          si_build_shader_variant_low_priority, NULL, 0);
2852 
2853       /* Add only after the ready fence was reset, to guard against a
2854        * race with si_bind_XX_shader. */
2855       sel->variants[sel->variants_count] = shader;
2856       sel->keys[sel->variants_count] = shader->key;
2857       sel->variants_count++;
2858 
2859       /* Use the default (unoptimized) shader for now. */
2860       key = use_local_key_copy(key, &local_key, key_size);
2861       memset(&local_key.opt, 0, key_opt_size);
2862       simple_mtx_unlock(&sel->mutex);
2863 
2864       if (sscreen->options.sync_compile)
2865          util_queue_fence_wait(&shader->ready);
2866 
2867       goto again;
2868    }
2869 
2870    /* Reset the fence before adding to the variant list. */
2871    util_queue_fence_reset(&shader->ready);
2872 
2873    sel->variants[sel->variants_count] = shader;
2874    sel->keys[sel->variants_count] = shader->key;
2875    sel->variants_count++;
2876 
2877    simple_mtx_unlock(&sel->mutex);
2878 
2879    assert(!shader->is_optimized);
2880    si_build_shader_variant(shader, -1, false);
2881 
2882    util_queue_fence_signal(&shader->ready);
2883 
2884    if (!shader->compilation_failed)
2885       state->current = shader;
2886 
2887    return shader->compilation_failed ? -1 : 0;
2888 }
2889 
si_shader_select(struct pipe_context * ctx,struct si_shader_ctx_state * state)2890 int si_shader_select(struct pipe_context *ctx, struct si_shader_ctx_state *state)
2891 {
2892    struct si_context *sctx = (struct si_context *)ctx;
2893 
2894    si_shader_selector_key(ctx, state->cso, &state->key);
2895 
2896    if (state->cso->stage == MESA_SHADER_FRAGMENT) {
2897       if (state->key.ps.opt.inline_uniforms)
2898          return si_shader_select_with_key(sctx, state, &state->key.ps);
2899       else
2900          return si_shader_select_with_key<NO_INLINE_UNIFORMS>(sctx, state, &state->key.ps);
2901    } else {
2902       if (state->key.ge.opt.inline_uniforms) {
2903          return si_shader_select_with_key(sctx, state, &state->key.ge);
2904       } else {
2905          return si_shader_select_with_key<NO_INLINE_UNIFORMS>(sctx, state, &state->key.ge);
2906       }
2907    }
2908 }
2909 
si_parse_next_shader_property(const struct si_shader_info * info,union si_shader_key * key)2910 static void si_parse_next_shader_property(const struct si_shader_info *info,
2911                                           union si_shader_key *key)
2912 {
2913    gl_shader_stage next_shader = info->base.next_stage;
2914 
2915    switch (info->base.stage) {
2916    case MESA_SHADER_VERTEX:
2917       switch (next_shader) {
2918       case MESA_SHADER_GEOMETRY:
2919          key->ge.as_es = 1;
2920          break;
2921       case MESA_SHADER_TESS_CTRL:
2922       case MESA_SHADER_TESS_EVAL:
2923          key->ge.as_ls = 1;
2924          break;
2925       default:
2926          /* If POSITION isn't written, it can only be a HW VS
2927           * if streamout is used. If streamout isn't used,
2928           * assume that it's a HW LS. (the next shader is TCS)
2929           * This heuristic is needed for separate shader objects.
2930           */
2931          if (!info->writes_position && !info->enabled_streamout_buffer_mask)
2932             key->ge.as_ls = 1;
2933       }
2934       break;
2935 
2936    case MESA_SHADER_TESS_EVAL:
2937       if (next_shader == MESA_SHADER_GEOMETRY || !info->writes_position)
2938          key->ge.as_es = 1;
2939       break;
2940 
2941    default:;
2942    }
2943 }
2944 
2945 /**
2946  * Compile the main shader part or the monolithic shader as part of
2947  * si_shader_selector initialization. Since it can be done asynchronously,
2948  * there is no way to report compile failures to applications.
2949  */
si_init_shader_selector_async(void * job,void * gdata,int thread_index)2950 static void si_init_shader_selector_async(void *job, void *gdata, int thread_index)
2951 {
2952    struct si_shader_selector *sel = (struct si_shader_selector *)job;
2953    struct si_screen *sscreen = sel->screen;
2954    struct ac_llvm_compiler *compiler;
2955    struct util_debug_callback *debug = &sel->compiler_ctx_state.debug;
2956 
2957    assert(!debug->debug_message || debug->async);
2958    assert(thread_index >= 0);
2959    assert(thread_index < (int)ARRAY_SIZE(sscreen->compiler));
2960    compiler = &sscreen->compiler[thread_index];
2961 
2962    if (!compiler->passes)
2963       si_init_compiler(sscreen, compiler);
2964 
2965    /* Serialize NIR to save memory. Monolithic shader variants
2966     * have to deserialize NIR before compilation.
2967     */
2968    if (sel->nir) {
2969       struct blob blob;
2970       size_t size;
2971 
2972       blob_init(&blob);
2973       /* true = remove optional debugging data to increase
2974        * the likehood of getting more shader cache hits.
2975        * It also drops variable names, so we'll save more memory.
2976        * If NIR debug prints are used we don't strip to get more
2977        * useful logs.
2978        */
2979       nir_serialize(&blob, sel->nir, NIR_DEBUG(PRINT) == 0);
2980       blob_finish_get_buffer(&blob, &sel->nir_binary, &size);
2981       sel->nir_size = size;
2982    }
2983 
2984    /* Compile the main shader part for use with a prolog and/or epilog.
2985     * If this fails, the driver will try to compile a monolithic shader
2986     * on demand.
2987     */
2988    if (!sscreen->use_monolithic_shaders) {
2989       struct si_shader *shader = CALLOC_STRUCT(si_shader);
2990       unsigned char ir_sha1_cache_key[20];
2991 
2992       if (!shader) {
2993          fprintf(stderr, "radeonsi: can't allocate a main shader part\n");
2994          return;
2995       }
2996 
2997       /* We can leave the fence signaled because use of the default
2998        * main part is guarded by the selector's ready fence. */
2999       util_queue_fence_init(&shader->ready);
3000 
3001       shader->selector = sel;
3002       shader->is_monolithic = false;
3003       si_parse_next_shader_property(&sel->info, &shader->key);
3004 
3005       if (sel->stage <= MESA_SHADER_GEOMETRY &&
3006           sscreen->use_ngg && (!sel->info.enabled_streamout_buffer_mask ||
3007                                sscreen->use_ngg_streamout) &&
3008           ((sel->stage == MESA_SHADER_VERTEX && !shader->key.ge.as_ls) ||
3009            sel->stage == MESA_SHADER_TESS_EVAL || sel->stage == MESA_SHADER_GEOMETRY))
3010          shader->key.ge.as_ngg = 1;
3011 
3012       shader->wave_size = si_determine_wave_size(sscreen, shader);
3013 
3014       if (sel->nir) {
3015          if (sel->stage <= MESA_SHADER_GEOMETRY) {
3016             si_get_ir_cache_key(sel, shader->key.ge.as_ngg, shader->key.ge.as_es,
3017                                 shader->wave_size, ir_sha1_cache_key);
3018          } else {
3019             si_get_ir_cache_key(sel, false, false, shader->wave_size, ir_sha1_cache_key);
3020          }
3021       }
3022 
3023       /* Try to load the shader from the shader cache. */
3024       simple_mtx_lock(&sscreen->shader_cache_mutex);
3025 
3026       if (si_shader_cache_load_shader(sscreen, ir_sha1_cache_key, shader)) {
3027          simple_mtx_unlock(&sscreen->shader_cache_mutex);
3028          si_shader_dump_stats_for_shader_db(sscreen, shader, debug);
3029       } else {
3030          simple_mtx_unlock(&sscreen->shader_cache_mutex);
3031 
3032          /* Compile the shader if it hasn't been loaded from the cache. */
3033          if (!si_compile_shader(sscreen, compiler, shader, debug)) {
3034             FREE(shader);
3035             fprintf(stderr, "radeonsi: can't compile a main shader part\n");
3036             return;
3037          }
3038 
3039          simple_mtx_lock(&sscreen->shader_cache_mutex);
3040          si_shader_cache_insert_shader(sscreen, ir_sha1_cache_key, shader, true);
3041          simple_mtx_unlock(&sscreen->shader_cache_mutex);
3042       }
3043 
3044       *si_get_main_shader_part(sel, &shader->key) = shader;
3045 
3046       /* Unset "outputs_written" flags for outputs converted to
3047        * DEFAULT_VAL, so that later inter-shader optimizations don't
3048        * try to eliminate outputs that don't exist in the final
3049        * shader.
3050        *
3051        * This is only done if non-monolithic shaders are enabled.
3052        */
3053       if ((sel->stage == MESA_SHADER_VERTEX ||
3054            sel->stage == MESA_SHADER_TESS_EVAL ||
3055            sel->stage == MESA_SHADER_GEOMETRY) &&
3056           !shader->key.ge.as_ls && !shader->key.ge.as_es) {
3057          unsigned i;
3058 
3059          for (i = 0; i < sel->info.num_outputs; i++) {
3060             unsigned semantic = sel->info.output_semantic[i];
3061             unsigned ps_input_cntl = shader->info.vs_output_ps_input_cntl[semantic];
3062 
3063             /* OFFSET=0x20 means DEFAULT_VAL, which means VS doesn't export it. */
3064             if (G_028644_OFFSET(ps_input_cntl) != 0x20)
3065                continue;
3066 
3067             unsigned id;
3068 
3069             /* Remove the output from the mask. */
3070             if ((semantic <= VARYING_SLOT_VAR31 || semantic >= VARYING_SLOT_VAR0_16BIT) &&
3071                 semantic != VARYING_SLOT_POS &&
3072                 semantic != VARYING_SLOT_PSIZ &&
3073                 semantic != VARYING_SLOT_CLIP_VERTEX &&
3074                 semantic != VARYING_SLOT_EDGE) {
3075                id = si_shader_io_get_unique_index(semantic, true);
3076                sel->info.outputs_written_before_ps &= ~(1ull << id);
3077             }
3078          }
3079       }
3080    }
3081 
3082    /* Free NIR. We only keep serialized NIR after this point. */
3083    if (sel->nir) {
3084       ralloc_free(sel->nir);
3085       sel->nir = NULL;
3086    }
3087 }
3088 
si_schedule_initial_compile(struct si_context * sctx,gl_shader_stage stage,struct util_queue_fence * ready_fence,struct si_compiler_ctx_state * compiler_ctx_state,void * job,util_queue_execute_func execute)3089 void si_schedule_initial_compile(struct si_context *sctx, gl_shader_stage stage,
3090                                  struct util_queue_fence *ready_fence,
3091                                  struct si_compiler_ctx_state *compiler_ctx_state, void *job,
3092                                  util_queue_execute_func execute)
3093 {
3094    util_queue_fence_init(ready_fence);
3095 
3096    struct util_async_debug_callback async_debug;
3097    bool debug = (sctx->debug.debug_message && !sctx->debug.async) || sctx->is_debug ||
3098                 si_can_dump_shader(sctx->screen, stage);
3099 
3100    if (debug) {
3101       u_async_debug_init(&async_debug);
3102       compiler_ctx_state->debug = async_debug.base;
3103    }
3104 
3105    util_queue_add_job(&sctx->screen->shader_compiler_queue, job, ready_fence, execute, NULL, 0);
3106 
3107    if (debug) {
3108       util_queue_fence_wait(ready_fence);
3109       u_async_debug_drain(&async_debug, &sctx->debug);
3110       u_async_debug_cleanup(&async_debug);
3111    }
3112 
3113    if (sctx->screen->options.sync_compile)
3114       util_queue_fence_wait(ready_fence);
3115 }
3116 
3117 /* Return descriptor slot usage masks from the given shader info. */
si_get_active_slot_masks(struct si_screen * sscreen,const struct si_shader_info * info,uint64_t * const_and_shader_buffers,uint64_t * samplers_and_images)3118 void si_get_active_slot_masks(struct si_screen *sscreen, const struct si_shader_info *info,
3119                               uint64_t *const_and_shader_buffers, uint64_t *samplers_and_images)
3120 {
3121    unsigned start, num_shaderbufs, num_constbufs, num_images, num_msaa_images, num_samplers;
3122 
3123    num_shaderbufs = info->base.num_ssbos;
3124    num_constbufs = info->base.num_ubos;
3125    /* two 8-byte images share one 16-byte slot */
3126    num_images = align(info->base.num_images, 2);
3127    num_msaa_images = align(BITSET_LAST_BIT(info->base.msaa_images), 2);
3128    num_samplers = BITSET_LAST_BIT(info->base.textures_used);
3129 
3130    /* The layout is: sb[last] ... sb[0], cb[0] ... cb[last] */
3131    start = si_get_shaderbuf_slot(num_shaderbufs - 1);
3132    *const_and_shader_buffers = u_bit_consecutive64(start, num_shaderbufs + num_constbufs);
3133 
3134    /* The layout is:
3135     *   - fmask[last] ... fmask[0]     go to [15-last .. 15]
3136     *   - image[last] ... image[0]     go to [31-last .. 31]
3137     *   - sampler[0] ... sampler[last] go to [32 .. 32+last*2]
3138     *
3139     * FMASKs for images are placed separately, because MSAA images are rare,
3140     * and so we can benefit from a better cache hit rate if we keep image
3141     * descriptors together.
3142     */
3143    if (sscreen->info.gfx_level < GFX11 && num_msaa_images)
3144       num_images = SI_NUM_IMAGES + num_msaa_images; /* add FMASK descriptors */
3145 
3146    start = si_get_image_slot(num_images - 1) / 2;
3147    *samplers_and_images = u_bit_consecutive64(start, num_images / 2 + num_samplers);
3148 }
3149 
si_create_shader_selector(struct pipe_context * ctx,const struct pipe_shader_state * state)3150 static void *si_create_shader_selector(struct pipe_context *ctx,
3151                                        const struct pipe_shader_state *state)
3152 {
3153    struct si_screen *sscreen = (struct si_screen *)ctx->screen;
3154    struct si_context *sctx = (struct si_context *)ctx;
3155    struct si_shader_selector *sel = CALLOC_STRUCT(si_shader_selector);
3156 
3157    if (!sel)
3158       return NULL;
3159 
3160    sel->screen = sscreen;
3161    sel->compiler_ctx_state.debug = sctx->debug;
3162    sel->compiler_ctx_state.is_debug_context = sctx->is_debug;
3163    sel->variants_max_count = 2;
3164    sel->keys = (union si_shader_key *)
3165       realloc(NULL, sel->variants_max_count * sizeof(union si_shader_key));
3166    sel->variants = (struct si_shader **)
3167       realloc(NULL, sel->variants_max_count * sizeof(struct si_shader *));
3168 
3169    if (state->type == PIPE_SHADER_IR_TGSI) {
3170       sel->nir = tgsi_to_nir(state->tokens, ctx->screen, true);
3171    } else {
3172       assert(state->type == PIPE_SHADER_IR_NIR);
3173       sel->nir = (nir_shader*)state->ir.nir;
3174    }
3175 
3176    si_nir_scan_shader(sscreen, sel->nir, &sel->info);
3177 
3178    sel->stage = sel->nir->info.stage;
3179    const enum pipe_shader_type type = pipe_shader_type_from_mesa(sel->stage);
3180    sel->pipe_shader_type = type;
3181    sel->const_and_shader_buf_descriptors_index =
3182       si_const_and_shader_buffer_descriptors_idx(type);
3183    sel->sampler_and_images_descriptors_index =
3184       si_sampler_and_image_descriptors_idx(type);
3185 
3186    p_atomic_inc(&sscreen->num_shaders_created);
3187    si_get_active_slot_masks(sscreen, &sel->info, &sel->active_const_and_shader_buffers,
3188                             &sel->active_samplers_and_images);
3189 
3190    switch (sel->stage) {
3191    case MESA_SHADER_GEOMETRY:
3192       /* Only possibilities: POINTS, LINE_STRIP, TRIANGLES */
3193       sel->rast_prim = (enum pipe_prim_type)sel->info.base.gs.output_primitive;
3194       if (util_rast_prim_is_triangles(sel->rast_prim))
3195          sel->rast_prim = PIPE_PRIM_TRIANGLES;
3196 
3197       /* EN_MAX_VERT_OUT_PER_GS_INSTANCE does not work with tesselation so
3198        * we can't split workgroups. Disable ngg if any of the following conditions is true:
3199        * - num_invocations * gs.vertices_out > 256
3200        * - LDS usage is too high
3201        */
3202       sel->tess_turns_off_ngg = sscreen->info.gfx_level >= GFX10 &&
3203                                 sscreen->info.gfx_level <= GFX10_3 &&
3204                                 (sel->info.base.gs.invocations * sel->info.base.gs.vertices_out > 256 ||
3205                                  sel->info.base.gs.invocations * sel->info.base.gs.vertices_out *
3206                                  (sel->info.num_outputs * 4 + 1) > 6500 /* max dw per GS primitive */);
3207       break;
3208 
3209    case MESA_SHADER_VERTEX:
3210    case MESA_SHADER_TESS_EVAL:
3211       if (sel->stage == MESA_SHADER_TESS_EVAL) {
3212          if (sel->info.base.tess.point_mode)
3213             sel->rast_prim = PIPE_PRIM_POINTS;
3214          else if (sel->info.base.tess._primitive_mode == TESS_PRIMITIVE_ISOLINES)
3215             sel->rast_prim = PIPE_PRIM_LINE_STRIP;
3216          else
3217             sel->rast_prim = PIPE_PRIM_TRIANGLES;
3218       } else {
3219          sel->rast_prim = PIPE_PRIM_TRIANGLES;
3220       }
3221       break;
3222    default:;
3223    }
3224 
3225    bool ngg_culling_allowed =
3226       sscreen->info.gfx_level >= GFX10 &&
3227       sscreen->use_ngg_culling &&
3228       sel->info.writes_position &&
3229       !sel->info.writes_viewport_index && /* cull only against viewport 0 */
3230       !sel->info.base.writes_memory &&
3231       /* NGG GS supports culling with streamout because it culls after streamout. */
3232       (sel->stage == MESA_SHADER_GEOMETRY || !sel->info.enabled_streamout_buffer_mask) &&
3233       (sel->stage != MESA_SHADER_GEOMETRY || sel->info.num_stream_output_components[0]) &&
3234       (sel->stage != MESA_SHADER_VERTEX ||
3235        (!sel->info.base.vs.blit_sgprs_amd &&
3236         !sel->info.base.vs.window_space_position));
3237 
3238    sel->ngg_cull_vert_threshold = UINT_MAX; /* disabled (changed below) */
3239 
3240    if (ngg_culling_allowed) {
3241       if (sel->stage == MESA_SHADER_VERTEX) {
3242          if (sscreen->debug_flags & DBG(ALWAYS_NGG_CULLING_ALL))
3243             sel->ngg_cull_vert_threshold = 0; /* always enabled */
3244          else
3245             sel->ngg_cull_vert_threshold = 128;
3246       } else if (sel->stage == MESA_SHADER_TESS_EVAL ||
3247                  sel->stage == MESA_SHADER_GEOMETRY) {
3248          if (sel->rast_prim != PIPE_PRIM_POINTS)
3249             sel->ngg_cull_vert_threshold = 0; /* always enabled */
3250       }
3251    }
3252 
3253    (void)simple_mtx_init(&sel->mutex, mtx_plain);
3254 
3255    si_schedule_initial_compile(sctx, sel->stage, &sel->ready, &sel->compiler_ctx_state,
3256                                sel, si_init_shader_selector_async);
3257    return sel;
3258 }
3259 
si_create_shader(struct pipe_context * ctx,const struct pipe_shader_state * state)3260 static void *si_create_shader(struct pipe_context *ctx, const struct pipe_shader_state *state)
3261 {
3262    struct si_context *sctx = (struct si_context *)ctx;
3263    struct si_screen *sscreen = (struct si_screen *)ctx->screen;
3264    bool cache_hit;
3265    struct si_shader_selector *sel = (struct si_shader_selector *)util_live_shader_cache_get(
3266       ctx, &sscreen->live_shader_cache, state, &cache_hit);
3267 
3268    if (sel && cache_hit && sctx->debug.debug_message) {
3269       if (sel->main_shader_part)
3270          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part, &sctx->debug);
3271       if (sel->main_shader_part_ls)
3272          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part_ls, &sctx->debug);
3273       if (sel->main_shader_part_es)
3274          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part_es, &sctx->debug);
3275       if (sel->main_shader_part_ngg)
3276          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part_ngg, &sctx->debug);
3277       if (sel->main_shader_part_ngg_es)
3278          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part_ngg_es, &sctx->debug);
3279    }
3280    return sel;
3281 }
3282 
si_update_streamout_state(struct si_context * sctx)3283 static void si_update_streamout_state(struct si_context *sctx)
3284 {
3285    struct si_shader_selector *shader_with_so = si_get_vs(sctx)->cso;
3286 
3287    if (!shader_with_so)
3288       return;
3289 
3290    sctx->streamout.enabled_stream_buffers_mask = shader_with_so->info.enabled_streamout_buffer_mask;
3291    sctx->streamout.stride_in_dw = shader_with_so->info.base.xfb_stride;
3292 
3293    /* GDS must be allocated when any GDS instructions are used, otherwise it hangs. */
3294    if (sctx->screen->use_ngg_streamout && shader_with_so->info.enabled_streamout_buffer_mask)
3295       si_allocate_gds(sctx);
3296 }
3297 
si_update_clip_regs(struct si_context * sctx,struct si_shader_selector * old_hw_vs,struct si_shader * old_hw_vs_variant,struct si_shader_selector * next_hw_vs,struct si_shader * next_hw_vs_variant)3298 static void si_update_clip_regs(struct si_context *sctx, struct si_shader_selector *old_hw_vs,
3299                                 struct si_shader *old_hw_vs_variant,
3300                                 struct si_shader_selector *next_hw_vs,
3301                                 struct si_shader *next_hw_vs_variant)
3302 {
3303    if (next_hw_vs &&
3304        (!old_hw_vs ||
3305         (old_hw_vs->stage == MESA_SHADER_VERTEX && old_hw_vs->info.base.vs.window_space_position) !=
3306         (next_hw_vs->stage == MESA_SHADER_VERTEX && next_hw_vs->info.base.vs.window_space_position) ||
3307         old_hw_vs->info.clipdist_mask != next_hw_vs->info.clipdist_mask ||
3308         old_hw_vs->info.culldist_mask != next_hw_vs->info.culldist_mask || !old_hw_vs_variant ||
3309         !next_hw_vs_variant ||
3310         old_hw_vs_variant->pa_cl_vs_out_cntl != next_hw_vs_variant->pa_cl_vs_out_cntl))
3311       si_mark_atom_dirty(sctx, &sctx->atoms.s.clip_regs);
3312 }
3313 
si_update_rasterized_prim(struct si_context * sctx)3314 static void si_update_rasterized_prim(struct si_context *sctx)
3315 {
3316    enum pipe_prim_type rast_prim;
3317 
3318    if (sctx->shader.gs.cso) {
3319       /* Only possibilities: POINTS, LINE_STRIP, TRIANGLES */
3320       rast_prim = sctx->shader.gs.cso->rast_prim;
3321    } else if (sctx->shader.tes.cso) {
3322       /* Only possibilities: POINTS, LINE_STRIP, TRIANGLES */
3323       rast_prim = sctx->shader.tes.cso->rast_prim;
3324    } else {
3325       /* Determined by draw calls. */
3326       return;
3327    }
3328 
3329    if (rast_prim != sctx->current_rast_prim) {
3330       if (util_prim_is_points_or_lines(sctx->current_rast_prim) !=
3331           util_prim_is_points_or_lines(rast_prim))
3332          si_mark_atom_dirty(sctx, &sctx->atoms.s.guardband);
3333 
3334       sctx->current_rast_prim = rast_prim;
3335    }
3336 }
3337 
si_update_common_shader_state(struct si_context * sctx,struct si_shader_selector * sel,enum pipe_shader_type type)3338 static void si_update_common_shader_state(struct si_context *sctx, struct si_shader_selector *sel,
3339                                           enum pipe_shader_type type)
3340 {
3341    si_set_active_descriptors_for_shader(sctx, sel);
3342 
3343    sctx->uses_bindless_samplers = si_shader_uses_bindless_samplers(sctx->shader.vs.cso) ||
3344                                   si_shader_uses_bindless_samplers(sctx->shader.gs.cso) ||
3345                                   si_shader_uses_bindless_samplers(sctx->shader.ps.cso) ||
3346                                   si_shader_uses_bindless_samplers(sctx->shader.tcs.cso) ||
3347                                   si_shader_uses_bindless_samplers(sctx->shader.tes.cso);
3348    sctx->uses_bindless_images = si_shader_uses_bindless_images(sctx->shader.vs.cso) ||
3349                                 si_shader_uses_bindless_images(sctx->shader.gs.cso) ||
3350                                 si_shader_uses_bindless_images(sctx->shader.ps.cso) ||
3351                                 si_shader_uses_bindless_images(sctx->shader.tcs.cso) ||
3352                                 si_shader_uses_bindless_images(sctx->shader.tes.cso);
3353 
3354    if (type == PIPE_SHADER_VERTEX || type == PIPE_SHADER_TESS_EVAL || type == PIPE_SHADER_GEOMETRY)
3355       sctx->ngg_culling = 0; /* this will be enabled on the first draw if needed */
3356 
3357    si_invalidate_inlinable_uniforms(sctx, type);
3358    sctx->do_update_shaders = true;
3359 }
3360 
si_bind_vs_shader(struct pipe_context * ctx,void * state)3361 static void si_bind_vs_shader(struct pipe_context *ctx, void *state)
3362 {
3363    struct si_context *sctx = (struct si_context *)ctx;
3364    struct si_shader_selector *old_hw_vs = si_get_vs(sctx)->cso;
3365    struct si_shader *old_hw_vs_variant = si_get_vs(sctx)->current;
3366    struct si_shader_selector *sel = (struct si_shader_selector*)state;
3367 
3368    if (sctx->shader.vs.cso == sel)
3369       return;
3370 
3371    sctx->shader.vs.cso = sel;
3372    sctx->shader.vs.current = (sel && sel->variants_count) ? sel->variants[0] : NULL;
3373    sctx->num_vs_blit_sgprs = sel ? sel->info.base.vs.blit_sgprs_amd : 0;
3374    sctx->vs_uses_draw_id = sel ? sel->info.uses_drawid : false;
3375 
3376    if (si_update_ngg(sctx))
3377       si_shader_change_notify(sctx);
3378 
3379    si_update_common_shader_state(sctx, sel, PIPE_SHADER_VERTEX);
3380    si_select_draw_vbo(sctx);
3381    si_update_vs_viewport_state(sctx);
3382    si_update_streamout_state(sctx);
3383    si_update_clip_regs(sctx, old_hw_vs, old_hw_vs_variant, si_get_vs(sctx)->cso,
3384                        si_get_vs(sctx)->current);
3385    si_update_rasterized_prim(sctx);
3386    si_vs_key_update_inputs(sctx);
3387 
3388    if (sctx->screen->dpbb_allowed) {
3389       bool force_off = sel && sel->info.options & SI_PROFILE_VS_NO_BINNING;
3390 
3391       if (force_off != sctx->dpbb_force_off_profile_vs) {
3392          sctx->dpbb_force_off_profile_vs = force_off;
3393          si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
3394       }
3395    }
3396 }
3397 
si_update_tess_uses_prim_id(struct si_context * sctx)3398 static void si_update_tess_uses_prim_id(struct si_context *sctx)
3399 {
3400    sctx->ia_multi_vgt_param_key.u.tess_uses_prim_id =
3401       (sctx->shader.tes.cso && sctx->shader.tes.cso->info.uses_primid) ||
3402       (sctx->shader.tcs.cso && sctx->shader.tcs.cso->info.uses_primid) ||
3403       (sctx->shader.gs.cso && sctx->shader.gs.cso->info.uses_primid) ||
3404       (sctx->shader.ps.cso && !sctx->shader.gs.cso && sctx->shader.ps.cso->info.uses_primid);
3405 }
3406 
si_update_ngg(struct si_context * sctx)3407 bool si_update_ngg(struct si_context *sctx)
3408 {
3409    if (!sctx->screen->use_ngg) {
3410       assert(!sctx->ngg);
3411       return false;
3412    }
3413 
3414    bool new_ngg = true;
3415 
3416    if (sctx->shader.gs.cso && sctx->shader.tes.cso && sctx->shader.gs.cso->tess_turns_off_ngg) {
3417       new_ngg = false;
3418    } else if (!sctx->screen->use_ngg_streamout) {
3419       struct si_shader_selector *last = si_get_vs(sctx)->cso;
3420 
3421       if ((last && last->info.enabled_streamout_buffer_mask) ||
3422           sctx->streamout.prims_gen_query_enabled)
3423          new_ngg = false;
3424    }
3425 
3426    if (new_ngg != sctx->ngg) {
3427       /* Transitioning from NGG to legacy GS requires VGT_FLUSH on Navi10-14.
3428        * VGT_FLUSH is also emitted at the beginning of IBs when legacy GS ring
3429        * pointers are set.
3430        */
3431       if (sctx->screen->info.has_vgt_flush_ngg_legacy_bug && !new_ngg) {
3432          sctx->flags |= SI_CONTEXT_VGT_FLUSH;
3433          if (sctx->gfx_level == GFX10) {
3434             /* Workaround for https://gitlab.freedesktop.org/mesa/mesa/-/issues/2941 */
3435             si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
3436          }
3437       }
3438 
3439       sctx->ngg = new_ngg;
3440       sctx->last_gs_out_prim = -1; /* reset this so that it gets updated */
3441       si_select_draw_vbo(sctx);
3442       return true;
3443    }
3444    return false;
3445 }
3446 
si_bind_gs_shader(struct pipe_context * ctx,void * state)3447 static void si_bind_gs_shader(struct pipe_context *ctx, void *state)
3448 {
3449    struct si_context *sctx = (struct si_context *)ctx;
3450    struct si_shader_selector *old_hw_vs = si_get_vs(sctx)->cso;
3451    struct si_shader *old_hw_vs_variant = si_get_vs(sctx)->current;
3452    struct si_shader_selector *sel = (struct si_shader_selector*)state;
3453    bool enable_changed = !!sctx->shader.gs.cso != !!sel;
3454    bool ngg_changed;
3455 
3456    if (sctx->shader.gs.cso == sel)
3457       return;
3458 
3459    sctx->shader.gs.cso = sel;
3460    sctx->shader.gs.current = (sel && sel->variants_count) ? sel->variants[0] : NULL;
3461    sctx->ia_multi_vgt_param_key.u.uses_gs = sel != NULL;
3462 
3463    si_update_common_shader_state(sctx, sel, PIPE_SHADER_GEOMETRY);
3464    si_select_draw_vbo(sctx);
3465    sctx->last_gs_out_prim = -1; /* reset this so that it gets updated */
3466 
3467    ngg_changed = si_update_ngg(sctx);
3468    if (ngg_changed || enable_changed)
3469       si_shader_change_notify(sctx);
3470    if (enable_changed) {
3471       if (sctx->ia_multi_vgt_param_key.u.uses_tess)
3472          si_update_tess_uses_prim_id(sctx);
3473    }
3474    si_update_vs_viewport_state(sctx);
3475    si_update_streamout_state(sctx);
3476    si_update_clip_regs(sctx, old_hw_vs, old_hw_vs_variant, si_get_vs(sctx)->cso,
3477                        si_get_vs(sctx)->current);
3478    si_update_rasterized_prim(sctx);
3479 }
3480 
si_bind_tcs_shader(struct pipe_context * ctx,void * state)3481 static void si_bind_tcs_shader(struct pipe_context *ctx, void *state)
3482 {
3483    struct si_context *sctx = (struct si_context *)ctx;
3484    struct si_shader_selector *sel = (struct si_shader_selector*)state;
3485    bool enable_changed = !!sctx->shader.tcs.cso != !!sel;
3486 
3487    /* Note it could happen that user shader sel is same as fixed function shader,
3488     * so we should update this field even sctx->shader.tcs.cso == sel.
3489     */
3490    sctx->is_user_tcs = !!sel;
3491 
3492    if (sctx->shader.tcs.cso == sel)
3493       return;
3494 
3495    sctx->shader.tcs.cso = sel;
3496    sctx->shader.tcs.current = (sel && sel->variants_count) ? sel->variants[0] : NULL;
3497    sctx->shader.tcs.key.ge.part.tcs.epilog.invoc0_tess_factors_are_def =
3498       sel ? sel->info.tessfactors_are_def_in_all_invocs : 0;
3499    si_update_tess_uses_prim_id(sctx);
3500 
3501    si_update_common_shader_state(sctx, sel, PIPE_SHADER_TESS_CTRL);
3502 
3503    if (enable_changed)
3504       sctx->last_tcs = NULL; /* invalidate derived tess state */
3505 }
3506 
si_bind_tes_shader(struct pipe_context * ctx,void * state)3507 static void si_bind_tes_shader(struct pipe_context *ctx, void *state)
3508 {
3509    struct si_context *sctx = (struct si_context *)ctx;
3510    struct si_shader_selector *old_hw_vs = si_get_vs(sctx)->cso;
3511    struct si_shader *old_hw_vs_variant = si_get_vs(sctx)->current;
3512    struct si_shader_selector *sel = (struct si_shader_selector*)state;
3513    bool enable_changed = !!sctx->shader.tes.cso != !!sel;
3514 
3515    if (sctx->shader.tes.cso == sel)
3516       return;
3517 
3518    sctx->shader.tes.cso = sel;
3519    sctx->shader.tes.current = (sel && sel->variants_count) ? sel->variants[0] : NULL;
3520    sctx->ia_multi_vgt_param_key.u.uses_tess = sel != NULL;
3521    si_update_tess_uses_prim_id(sctx);
3522 
3523    sctx->shader.tcs.key.ge.part.tcs.epilog.prim_mode =
3524       sel ? sel->info.base.tess._primitive_mode : 0;
3525 
3526    sctx->shader.tcs.key.ge.part.tcs.epilog.tes_reads_tess_factors =
3527       sel ? sel->info.reads_tess_factors : 0;
3528 
3529    si_update_common_shader_state(sctx, sel, PIPE_SHADER_TESS_EVAL);
3530    si_select_draw_vbo(sctx);
3531    sctx->last_gs_out_prim = -1; /* reset this so that it gets updated */
3532 
3533    bool ngg_changed = si_update_ngg(sctx);
3534    if (ngg_changed || enable_changed)
3535       si_shader_change_notify(sctx);
3536    if (enable_changed)
3537       sctx->last_tes_sh_base = -1; /* invalidate derived tess state */
3538    si_update_vs_viewport_state(sctx);
3539    si_update_streamout_state(sctx);
3540    si_update_clip_regs(sctx, old_hw_vs, old_hw_vs_variant, si_get_vs(sctx)->cso,
3541                        si_get_vs(sctx)->current);
3542    si_update_rasterized_prim(sctx);
3543 }
3544 
si_update_vrs_flat_shading(struct si_context * sctx)3545 void si_update_vrs_flat_shading(struct si_context *sctx)
3546 {
3547    if (sctx->gfx_level >= GFX10_3 && sctx->shader.ps.cso) {
3548       struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
3549       struct si_shader_info *info = &sctx->shader.ps.cso->info;
3550       bool allow_flat_shading = info->allow_flat_shading;
3551 
3552       if (allow_flat_shading &&
3553           (rs->line_smooth || rs->poly_smooth || rs->poly_stipple_enable ||
3554            rs->point_smooth || (!rs->flatshade && info->uses_interp_color)))
3555          allow_flat_shading = false;
3556 
3557       if (sctx->allow_flat_shading != allow_flat_shading) {
3558          sctx->allow_flat_shading = allow_flat_shading;
3559          si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
3560       }
3561    }
3562 }
3563 
si_bind_ps_shader(struct pipe_context * ctx,void * state)3564 static void si_bind_ps_shader(struct pipe_context *ctx, void *state)
3565 {
3566    struct si_context *sctx = (struct si_context *)ctx;
3567    struct si_shader_selector *old_sel = sctx->shader.ps.cso;
3568    struct si_shader_selector *sel = (struct si_shader_selector*)state;
3569 
3570    /* skip if supplied shader is one already in use */
3571    if (old_sel == sel)
3572       return;
3573 
3574    sctx->shader.ps.cso = sel;
3575    sctx->shader.ps.current = (sel && sel->variants_count) ? sel->variants[0] : NULL;
3576 
3577    si_update_common_shader_state(sctx, sel, PIPE_SHADER_FRAGMENT);
3578    if (sel) {
3579       if (sctx->ia_multi_vgt_param_key.u.uses_tess)
3580          si_update_tess_uses_prim_id(sctx);
3581 
3582       if (!old_sel || old_sel->info.colors_written != sel->info.colors_written)
3583          si_mark_atom_dirty(sctx, &sctx->atoms.s.cb_render_state);
3584 
3585       if (sctx->screen->has_out_of_order_rast &&
3586           (!old_sel || old_sel->info.base.writes_memory != sel->info.base.writes_memory ||
3587            old_sel->info.base.fs.early_fragment_tests !=
3588               sel->info.base.fs.early_fragment_tests))
3589          si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
3590    }
3591    si_update_ps_colorbuf0_slot(sctx);
3592 
3593    si_ps_key_update_framebuffer(sctx);
3594    si_ps_key_update_framebuffer_blend(sctx);
3595    si_ps_key_update_blend_rasterizer(sctx);
3596    si_ps_key_update_rasterizer(sctx);
3597    si_ps_key_update_dsa(sctx);
3598    si_ps_key_update_sample_shading(sctx);
3599    si_ps_key_update_framebuffer_rasterizer_sample_shading(sctx);
3600    si_update_ps_inputs_read_or_disabled(sctx);
3601    si_update_vrs_flat_shading(sctx);
3602 
3603    if (sctx->screen->dpbb_allowed) {
3604       bool force_off = sel && sel->info.options & SI_PROFILE_PS_NO_BINNING;
3605 
3606       if (force_off != sctx->dpbb_force_off_profile_ps) {
3607          sctx->dpbb_force_off_profile_ps = force_off;
3608          si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
3609       }
3610    }
3611 }
3612 
si_delete_shader(struct si_context * sctx,struct si_shader * shader)3613 static void si_delete_shader(struct si_context *sctx, struct si_shader *shader)
3614 {
3615    if (shader->is_optimized) {
3616       util_queue_drop_job(&sctx->screen->shader_compiler_queue_low_priority, &shader->ready);
3617    }
3618 
3619    util_queue_fence_destroy(&shader->ready);
3620 
3621    /* If destroyed shaders were not unbound, the next compiled
3622     * shader variant could get the same pointer address and so
3623     * binding it to the same shader stage would be considered
3624     * a no-op, causing random behavior.
3625     */
3626    int state_index = -1;
3627 
3628    switch (shader->selector->stage) {
3629    case MESA_SHADER_VERTEX:
3630       if (shader->key.ge.as_ls) {
3631          if (sctx->gfx_level <= GFX8)
3632             state_index = SI_STATE_IDX(ls);
3633       } else if (shader->key.ge.as_es) {
3634          if (sctx->gfx_level <= GFX8)
3635             state_index = SI_STATE_IDX(es);
3636       } else if (shader->key.ge.as_ngg) {
3637          state_index = SI_STATE_IDX(gs);
3638       } else {
3639          state_index = SI_STATE_IDX(vs);
3640       }
3641       break;
3642    case MESA_SHADER_TESS_CTRL:
3643       state_index = SI_STATE_IDX(hs);
3644       break;
3645    case MESA_SHADER_TESS_EVAL:
3646       if (shader->key.ge.as_es) {
3647          if (sctx->gfx_level <= GFX8)
3648             state_index = SI_STATE_IDX(es);
3649       } else if (shader->key.ge.as_ngg) {
3650          state_index = SI_STATE_IDX(gs);
3651       } else {
3652          state_index = SI_STATE_IDX(vs);
3653       }
3654       break;
3655    case MESA_SHADER_GEOMETRY:
3656       if (shader->is_gs_copy_shader)
3657          state_index = SI_STATE_IDX(vs);
3658       else
3659          state_index = SI_STATE_IDX(gs);
3660       break;
3661    case MESA_SHADER_FRAGMENT:
3662       state_index = SI_STATE_IDX(ps);
3663       break;
3664    default:;
3665    }
3666 
3667    if (shader->gs_copy_shader)
3668       si_delete_shader(sctx, shader->gs_copy_shader);
3669 
3670    si_shader_selector_reference(sctx, &shader->previous_stage_sel, NULL);
3671    si_shader_destroy(shader);
3672    si_pm4_free_state(sctx, &shader->pm4, state_index);
3673 }
3674 
si_destroy_shader_selector(struct pipe_context * ctx,void * cso)3675 static void si_destroy_shader_selector(struct pipe_context *ctx, void *cso)
3676 {
3677    struct si_context *sctx = (struct si_context *)ctx;
3678    struct si_shader_selector *sel = (struct si_shader_selector *)cso;
3679    enum pipe_shader_type type = pipe_shader_type_from_mesa(sel->stage);
3680 
3681    util_queue_drop_job(&sctx->screen->shader_compiler_queue, &sel->ready);
3682 
3683    if (sctx->shaders[type].cso == sel) {
3684       sctx->shaders[type].cso = NULL;
3685       sctx->shaders[type].current = NULL;
3686    }
3687 
3688    for (unsigned i = 0; i < sel->variants_count; i++) {
3689       si_delete_shader(sctx, sel->variants[i]);
3690    }
3691 
3692    if (sel->main_shader_part)
3693       si_delete_shader(sctx, sel->main_shader_part);
3694    if (sel->main_shader_part_ls)
3695       si_delete_shader(sctx, sel->main_shader_part_ls);
3696    if (sel->main_shader_part_es)
3697       si_delete_shader(sctx, sel->main_shader_part_es);
3698    if (sel->main_shader_part_ngg)
3699       si_delete_shader(sctx, sel->main_shader_part_ngg);
3700 
3701    free(sel->keys);
3702    free(sel->variants);
3703 
3704    util_queue_fence_destroy(&sel->ready);
3705    simple_mtx_destroy(&sel->mutex);
3706    ralloc_free(sel->nir);
3707    free(sel->nir_binary);
3708    free(sel);
3709 }
3710 
si_delete_shader_selector(struct pipe_context * ctx,void * state)3711 static void si_delete_shader_selector(struct pipe_context *ctx, void *state)
3712 {
3713    struct si_context *sctx = (struct si_context *)ctx;
3714    struct si_shader_selector *sel = (struct si_shader_selector *)state;
3715 
3716    si_shader_selector_reference(sctx, &sel, NULL);
3717 }
3718 
3719 /**
3720  * Writing CONFIG or UCONFIG VGT registers requires VGT_FLUSH before that.
3721  */
si_cs_preamble_add_vgt_flush(struct si_context * sctx,bool tmz)3722 static void si_cs_preamble_add_vgt_flush(struct si_context *sctx, bool tmz)
3723 {
3724    struct si_pm4_state *pm4 = tmz ? sctx->cs_preamble_state_tmz : sctx->cs_preamble_state;
3725    bool *has_vgt_flush = tmz ? &sctx->cs_preamble_has_vgt_flush_tmz :
3726                                &sctx->cs_preamble_has_vgt_flush;
3727 
3728    /* We shouldn't get here if registers are shadowed. */
3729    assert(!sctx->shadowed_regs);
3730 
3731    if (*has_vgt_flush)
3732       return;
3733 
3734    /* Done by Vulkan before VGT_FLUSH. */
3735    si_pm4_cmd_add(pm4, PKT3(PKT3_EVENT_WRITE, 0, 0));
3736    si_pm4_cmd_add(pm4, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
3737 
3738    /* VGT_FLUSH is required even if VGT is idle. It resets VGT pointers. */
3739    si_pm4_cmd_add(pm4, PKT3(PKT3_EVENT_WRITE, 0, 0));
3740    si_pm4_cmd_add(pm4, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
3741 
3742    *has_vgt_flush = true;
3743 }
3744 
3745 /**
3746  * Writing CONFIG or UCONFIG VGT registers requires VGT_FLUSH before that.
3747  */
si_emit_vgt_flush(struct radeon_cmdbuf * cs)3748 static void si_emit_vgt_flush(struct radeon_cmdbuf *cs)
3749 {
3750    radeon_begin(cs);
3751 
3752    /* This is required before VGT_FLUSH. */
3753    radeon_emit(PKT3(PKT3_EVENT_WRITE, 0, 0));
3754    radeon_emit(EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
3755 
3756    /* VGT_FLUSH is required even if VGT is idle. It resets VGT pointers. */
3757    radeon_emit(PKT3(PKT3_EVENT_WRITE, 0, 0));
3758    radeon_emit(EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
3759    radeon_end();
3760 }
3761 
3762 /* Initialize state related to ESGS / GSVS ring buffers */
si_update_gs_ring_buffers(struct si_context * sctx)3763 bool si_update_gs_ring_buffers(struct si_context *sctx)
3764 {
3765    assert(sctx->gfx_level < GFX11);
3766 
3767    struct si_shader_selector *es =
3768       sctx->shader.tes.cso ? sctx->shader.tes.cso : sctx->shader.vs.cso;
3769    struct si_shader_selector *gs = sctx->shader.gs.cso;
3770 
3771    /* Chip constants. */
3772    unsigned num_se = sctx->screen->info.max_se;
3773    unsigned wave_size = 64;
3774    unsigned max_gs_waves = 32 * num_se; /* max 32 per SE on GCN */
3775    /* On GFX6-GFX7, the value comes from VGT_GS_VERTEX_REUSE = 16.
3776     * On GFX8+, the value comes from VGT_VERTEX_REUSE_BLOCK_CNTL = 30 (+2).
3777     */
3778    unsigned gs_vertex_reuse = (sctx->gfx_level >= GFX8 ? 32 : 16) * num_se;
3779    unsigned alignment = 256 * num_se;
3780    /* The maximum size is 63.999 MB per SE. */
3781    unsigned max_size = ((unsigned)(63.999 * 1024 * 1024) & ~255) * num_se;
3782 
3783    /* Calculate the minimum size. */
3784    unsigned min_esgs_ring_size = align(es->info.esgs_itemsize * gs_vertex_reuse * wave_size, alignment);
3785 
3786    /* These are recommended sizes, not minimum sizes. */
3787    unsigned esgs_ring_size =
3788       max_gs_waves * 2 * wave_size * es->info.esgs_itemsize * gs->info.gs_input_verts_per_prim;
3789    unsigned gsvs_ring_size = max_gs_waves * 2 * wave_size * gs->info.max_gsvs_emit_size;
3790 
3791    min_esgs_ring_size = align(min_esgs_ring_size, alignment);
3792    esgs_ring_size = align(esgs_ring_size, alignment);
3793    gsvs_ring_size = align(gsvs_ring_size, alignment);
3794 
3795    esgs_ring_size = CLAMP(esgs_ring_size, min_esgs_ring_size, max_size);
3796    gsvs_ring_size = MIN2(gsvs_ring_size, max_size);
3797 
3798    /* Some rings don't have to be allocated if shaders don't use them.
3799     * (e.g. no varyings between ES and GS or GS and VS)
3800     *
3801     * GFX9 doesn't have the ESGS ring.
3802     */
3803    bool update_esgs = sctx->gfx_level <= GFX8 && esgs_ring_size &&
3804                       (!sctx->esgs_ring || sctx->esgs_ring->width0 < esgs_ring_size);
3805    bool update_gsvs =
3806       gsvs_ring_size && (!sctx->gsvs_ring || sctx->gsvs_ring->width0 < gsvs_ring_size);
3807 
3808    if (!update_esgs && !update_gsvs)
3809       return true;
3810 
3811    if (update_esgs) {
3812       pipe_resource_reference(&sctx->esgs_ring, NULL);
3813       sctx->esgs_ring =
3814          pipe_aligned_buffer_create(sctx->b.screen,
3815                                     PIPE_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_DRIVER_INTERNAL |
3816                                     SI_RESOURCE_FLAG_DISCARDABLE,
3817                                     PIPE_USAGE_DEFAULT,
3818                                     esgs_ring_size, sctx->screen->info.pte_fragment_size);
3819       if (!sctx->esgs_ring)
3820          return false;
3821    }
3822 
3823    if (update_gsvs) {
3824       pipe_resource_reference(&sctx->gsvs_ring, NULL);
3825       sctx->gsvs_ring =
3826          pipe_aligned_buffer_create(sctx->b.screen,
3827                                     PIPE_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_DRIVER_INTERNAL |
3828                                     SI_RESOURCE_FLAG_DISCARDABLE,
3829                                     PIPE_USAGE_DEFAULT,
3830                                     gsvs_ring_size, sctx->screen->info.pte_fragment_size);
3831       if (!sctx->gsvs_ring)
3832          return false;
3833    }
3834 
3835    /* Set ring bindings. */
3836    if (sctx->esgs_ring) {
3837       assert(sctx->gfx_level <= GFX8);
3838       si_set_ring_buffer(sctx, SI_RING_ESGS, sctx->esgs_ring, 0, sctx->esgs_ring->width0, false,
3839                          false, 0, 0, 0);
3840    }
3841    if (sctx->gsvs_ring) {
3842       si_set_ring_buffer(sctx, SI_RING_GSVS, sctx->gsvs_ring, 0, sctx->gsvs_ring->width0, false,
3843                          false, 0, 0, 0);
3844    }
3845 
3846    if (sctx->shadowed_regs) {
3847       /* These registers will be shadowed, so set them only once. */
3848       struct radeon_cmdbuf *cs = &sctx->gfx_cs;
3849 
3850       assert(sctx->gfx_level >= GFX7);
3851 
3852       si_emit_vgt_flush(cs);
3853 
3854       radeon_begin(cs);
3855 
3856       /* Set the GS registers. */
3857       if (sctx->esgs_ring) {
3858          assert(sctx->gfx_level <= GFX8);
3859          radeon_set_uconfig_reg(R_030900_VGT_ESGS_RING_SIZE,
3860                                 sctx->esgs_ring->width0 / 256);
3861       }
3862       if (sctx->gsvs_ring) {
3863          radeon_set_uconfig_reg(R_030904_VGT_GSVS_RING_SIZE,
3864                                 sctx->gsvs_ring->width0 / 256);
3865       }
3866       radeon_end();
3867       return true;
3868    }
3869 
3870    /* The codepath without register shadowing. */
3871    for (unsigned tmz = 0; tmz <= 1; tmz++) {
3872       struct si_pm4_state *pm4 = tmz ? sctx->cs_preamble_state_tmz : sctx->cs_preamble_state;
3873       uint16_t *gs_ring_state_dw_offset = tmz ? &sctx->gs_ring_state_dw_offset_tmz :
3874                                                 &sctx->gs_ring_state_dw_offset;
3875       unsigned old_ndw = 0;
3876 
3877       si_cs_preamble_add_vgt_flush(sctx, tmz);
3878 
3879       if (!*gs_ring_state_dw_offset) {
3880          /* We are here for the first time. The packets will be added. */
3881          *gs_ring_state_dw_offset = pm4->ndw;
3882       } else {
3883          /* We have been here before. Overwrite the previous packets. */
3884          old_ndw = pm4->ndw;
3885          pm4->ndw = *gs_ring_state_dw_offset;
3886       }
3887 
3888       /* Unallocated rings are written to reserve the space in the pm4
3889        * (to be able to overwrite them later). */
3890       if (sctx->gfx_level >= GFX7) {
3891          if (sctx->gfx_level <= GFX8)
3892             si_pm4_set_reg(pm4, R_030900_VGT_ESGS_RING_SIZE,
3893                            sctx->esgs_ring ? sctx->esgs_ring->width0 / 256 : 0);
3894          si_pm4_set_reg(pm4, R_030904_VGT_GSVS_RING_SIZE,
3895                         sctx->gsvs_ring ? sctx->gsvs_ring->width0 / 256 : 0);
3896       } else {
3897          si_pm4_set_reg(pm4, R_0088C8_VGT_ESGS_RING_SIZE,
3898                         sctx->esgs_ring ? sctx->esgs_ring->width0 / 256 : 0);
3899          si_pm4_set_reg(pm4, R_0088CC_VGT_GSVS_RING_SIZE,
3900                         sctx->gsvs_ring ? sctx->gsvs_ring->width0 / 256 : 0);
3901       }
3902 
3903       if (old_ndw) {
3904          pm4->ndw = old_ndw;
3905          pm4->last_opcode = 255; /* invalid opcode (we don't save the last opcode) */
3906       }
3907    }
3908 
3909    /* Flush the context to re-emit both cs_preamble states. */
3910    sctx->last_preamble = NULL; /* flag that the preamble has changed */
3911    sctx->initial_gfx_cs_size = 0; /* force flush */
3912    si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
3913 
3914    return true;
3915 }
3916 
si_shader_lock(struct si_shader * shader)3917 static void si_shader_lock(struct si_shader *shader)
3918 {
3919    simple_mtx_lock(&shader->selector->mutex);
3920    if (shader->previous_stage_sel) {
3921       assert(shader->previous_stage_sel != shader->selector);
3922       simple_mtx_lock(&shader->previous_stage_sel->mutex);
3923    }
3924 }
3925 
si_shader_unlock(struct si_shader * shader)3926 static void si_shader_unlock(struct si_shader *shader)
3927 {
3928    if (shader->previous_stage_sel)
3929       simple_mtx_unlock(&shader->previous_stage_sel->mutex);
3930    simple_mtx_unlock(&shader->selector->mutex);
3931 }
3932 
3933 /**
3934  * @returns 1 if \p sel has been updated to use a new scratch buffer
3935  *          0 if not
3936  *          < 0 if there was a failure
3937  */
si_update_scratch_buffer(struct si_context * sctx,struct si_shader * shader)3938 static int si_update_scratch_buffer(struct si_context *sctx, struct si_shader *shader)
3939 {
3940    uint64_t scratch_va = sctx->scratch_buffer->gpu_address;
3941 
3942    if (!shader)
3943       return 0;
3944 
3945    /* This shader doesn't need a scratch buffer */
3946    if (shader->config.scratch_bytes_per_wave == 0)
3947       return 0;
3948 
3949    /* Prevent race conditions when updating:
3950     * - si_shader::scratch_bo
3951     * - si_shader::binary::code
3952     * - si_shader::previous_stage::binary::code.
3953     */
3954    si_shader_lock(shader);
3955 
3956    /* This shader is already configured to use the current
3957     * scratch buffer. */
3958    if (shader->scratch_bo == sctx->scratch_buffer) {
3959       si_shader_unlock(shader);
3960       return 0;
3961    }
3962 
3963    assert(sctx->scratch_buffer);
3964 
3965    /* Replace the shader bo with a new bo that has the relocs applied. */
3966    if (!si_shader_binary_upload(sctx->screen, shader, scratch_va)) {
3967       si_shader_unlock(shader);
3968       return -1;
3969    }
3970 
3971    /* Update the shader state to use the new shader bo. */
3972    si_shader_init_pm4_state(sctx->screen, shader);
3973 
3974    si_resource_reference(&shader->scratch_bo, sctx->scratch_buffer);
3975 
3976    si_shader_unlock(shader);
3977    return 1;
3978 }
3979 
si_update_scratch_relocs(struct si_context * sctx)3980 static bool si_update_scratch_relocs(struct si_context *sctx)
3981 {
3982    int r;
3983 
3984    /* Update the shaders, so that they are using the latest scratch.
3985     * The scratch buffer may have been changed since these shaders were
3986     * last used, so we still need to try to update them, even if they
3987     * require scratch buffers smaller than the current size.
3988     */
3989    r = si_update_scratch_buffer(sctx, sctx->shader.ps.current);
3990    if (r < 0)
3991       return false;
3992    if (r == 1)
3993       si_pm4_bind_state(sctx, ps, sctx->shader.ps.current);
3994 
3995    r = si_update_scratch_buffer(sctx, sctx->shader.gs.current);
3996    if (r < 0)
3997       return false;
3998    if (r == 1)
3999       si_pm4_bind_state(sctx, gs, sctx->shader.gs.current);
4000 
4001    r = si_update_scratch_buffer(sctx, sctx->shader.tcs.current);
4002    if (r < 0)
4003       return false;
4004    if (r == 1)
4005       si_pm4_bind_state(sctx, hs, sctx->shader.tcs.current);
4006 
4007    /* VS can be bound as LS, ES, or VS. */
4008    r = si_update_scratch_buffer(sctx, sctx->shader.vs.current);
4009    if (r < 0)
4010       return false;
4011    if (r == 1) {
4012       if (sctx->shader.vs.current->key.ge.as_ls)
4013          si_pm4_bind_state(sctx, ls, sctx->shader.vs.current);
4014       else if (sctx->shader.vs.current->key.ge.as_es)
4015          si_pm4_bind_state(sctx, es, sctx->shader.vs.current);
4016       else if (sctx->shader.vs.current->key.ge.as_ngg)
4017          si_pm4_bind_state(sctx, gs, sctx->shader.vs.current);
4018       else
4019          si_pm4_bind_state(sctx, vs, sctx->shader.vs.current);
4020    }
4021 
4022    /* TES can be bound as ES or VS. */
4023    r = si_update_scratch_buffer(sctx, sctx->shader.tes.current);
4024    if (r < 0)
4025       return false;
4026    if (r == 1) {
4027       if (sctx->shader.tes.current->key.ge.as_es)
4028          si_pm4_bind_state(sctx, es, sctx->shader.tes.current);
4029       else if (sctx->shader.tes.current->key.ge.as_ngg)
4030          si_pm4_bind_state(sctx, gs, sctx->shader.tes.current);
4031       else
4032          si_pm4_bind_state(sctx, vs, sctx->shader.tes.current);
4033    }
4034 
4035    return true;
4036 }
4037 
si_update_spi_tmpring_size(struct si_context * sctx,unsigned bytes)4038 bool si_update_spi_tmpring_size(struct si_context *sctx, unsigned bytes)
4039 {
4040    unsigned spi_tmpring_size;
4041    ac_get_scratch_tmpring_size(&sctx->screen->info, bytes,
4042                                &sctx->max_seen_scratch_bytes_per_wave, &spi_tmpring_size);
4043 
4044    unsigned scratch_needed_size = sctx->max_seen_scratch_bytes_per_wave *
4045                                   sctx->screen->info.max_scratch_waves;
4046 
4047    if (scratch_needed_size > 0) {
4048       if (!sctx->scratch_buffer || scratch_needed_size > sctx->scratch_buffer->b.b.width0) {
4049          /* Create a bigger scratch buffer */
4050          si_resource_reference(&sctx->scratch_buffer, NULL);
4051 
4052          sctx->scratch_buffer = si_aligned_buffer_create(
4053             &sctx->screen->b,
4054             PIPE_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_DRIVER_INTERNAL |
4055             SI_RESOURCE_FLAG_DISCARDABLE,
4056             PIPE_USAGE_DEFAULT, scratch_needed_size,
4057             sctx->screen->info.pte_fragment_size);
4058          if (!sctx->scratch_buffer)
4059             return false;
4060 
4061          si_context_add_resource_size(sctx, &sctx->scratch_buffer->b.b);
4062       }
4063 
4064       if (sctx->gfx_level < GFX11 && !si_update_scratch_relocs(sctx))
4065          return false;
4066    }
4067 
4068    if (spi_tmpring_size != sctx->spi_tmpring_size) {
4069       sctx->spi_tmpring_size = spi_tmpring_size;
4070       si_mark_atom_dirty(sctx, &sctx->atoms.s.scratch_state);
4071    }
4072    return true;
4073 }
4074 
si_init_tess_factor_ring(struct si_context * sctx)4075 void si_init_tess_factor_ring(struct si_context *sctx)
4076 {
4077    assert(!sctx->tess_rings);
4078 
4079    /* The address must be aligned to 2^19, because the shader only
4080     * receives the high 13 bits. Align it to 2MB to match the GPU page size.
4081     */
4082    sctx->tess_rings = pipe_aligned_buffer_create(sctx->b.screen,
4083                                                  PIPE_RESOURCE_FLAG_UNMAPPABLE |
4084                                                  SI_RESOURCE_FLAG_32BIT |
4085                                                  SI_RESOURCE_FLAG_DRIVER_INTERNAL |
4086                                                  SI_RESOURCE_FLAG_DISCARDABLE,
4087                                                  PIPE_USAGE_DEFAULT,
4088                                                  sctx->screen->hs.tess_offchip_ring_size +
4089                                                  sctx->screen->hs.tess_factor_ring_size,
4090                                                  2 * 1024 * 1024);
4091    if (!sctx->tess_rings)
4092       return;
4093 
4094    if (sctx->screen->info.has_tmz_support) {
4095       sctx->tess_rings_tmz = pipe_aligned_buffer_create(sctx->b.screen,
4096                                                         PIPE_RESOURCE_FLAG_UNMAPPABLE |
4097                                                         PIPE_RESOURCE_FLAG_ENCRYPTED |
4098                                                         SI_RESOURCE_FLAG_32BIT |
4099                                                         SI_RESOURCE_FLAG_DRIVER_INTERNAL |
4100                                                         SI_RESOURCE_FLAG_DISCARDABLE,
4101                                                         PIPE_USAGE_DEFAULT,
4102                                                         sctx->screen->hs.tess_offchip_ring_size +
4103                                                         sctx->screen->hs.tess_factor_ring_size,
4104                                                         2 * 1024 * 1024);
4105    }
4106 
4107    uint64_t factor_va =
4108       si_resource(sctx->tess_rings)->gpu_address + sctx->screen->hs.tess_offchip_ring_size;
4109 
4110    unsigned tf_ring_size_field = sctx->screen->hs.tess_factor_ring_size / 4;
4111    if (sctx->gfx_level >= GFX11)
4112       tf_ring_size_field /= sctx->screen->info.max_se;
4113 
4114    assert((tf_ring_size_field & C_030938_SIZE) == 0);
4115 
4116    if (sctx->shadowed_regs) {
4117       /* These registers will be shadowed, so set them only once. */
4118       /* TODO: tmz + shadowed_regs support */
4119       struct radeon_cmdbuf *cs = &sctx->gfx_cs;
4120 
4121       assert(sctx->gfx_level >= GFX7);
4122 
4123       radeon_add_to_buffer_list(sctx, &sctx->gfx_cs, si_resource(sctx->tess_rings),
4124                                 RADEON_USAGE_READWRITE | RADEON_PRIO_SHADER_RINGS);
4125       si_emit_vgt_flush(cs);
4126 
4127       /* Set tessellation registers. */
4128       radeon_begin(cs);
4129       radeon_set_uconfig_reg(R_030938_VGT_TF_RING_SIZE,
4130                              S_030938_SIZE(tf_ring_size_field));
4131       radeon_set_uconfig_reg(R_030940_VGT_TF_MEMORY_BASE, factor_va >> 8);
4132       if (sctx->gfx_level >= GFX10) {
4133          radeon_set_uconfig_reg(R_030984_VGT_TF_MEMORY_BASE_HI,
4134                                 S_030984_BASE_HI(factor_va >> 40));
4135       } else if (sctx->gfx_level == GFX9) {
4136          radeon_set_uconfig_reg(R_030944_VGT_TF_MEMORY_BASE_HI,
4137                                 S_030944_BASE_HI(factor_va >> 40));
4138       }
4139       radeon_set_uconfig_reg(R_03093C_VGT_HS_OFFCHIP_PARAM,
4140                              sctx->screen->hs.hs_offchip_param);
4141       radeon_end();
4142       return;
4143    }
4144 
4145    /* The codepath without register shadowing is below. */
4146    /* Add these registers to cs_preamble_state. */
4147    for (unsigned tmz = 0; tmz <= 1; tmz++) {
4148       struct si_pm4_state *pm4 = tmz ? sctx->cs_preamble_state_tmz : sctx->cs_preamble_state;
4149       struct pipe_resource *tf_ring = tmz ? sctx->tess_rings_tmz : sctx->tess_rings;
4150 
4151       if (!tf_ring)
4152          continue; /* TMZ not supported */
4153 
4154       uint64_t va = si_resource(tf_ring)->gpu_address + sctx->screen->hs.tess_offchip_ring_size;
4155 
4156       si_cs_preamble_add_vgt_flush(sctx, tmz);
4157 
4158       if (sctx->gfx_level >= GFX7) {
4159          si_pm4_set_reg(pm4, R_030938_VGT_TF_RING_SIZE, S_030938_SIZE(tf_ring_size_field));
4160          si_pm4_set_reg(pm4, R_03093C_VGT_HS_OFFCHIP_PARAM, sctx->screen->hs.hs_offchip_param);
4161          si_pm4_set_reg(pm4, R_030940_VGT_TF_MEMORY_BASE, va >> 8);
4162          if (sctx->gfx_level >= GFX10)
4163             si_pm4_set_reg(pm4, R_030984_VGT_TF_MEMORY_BASE_HI, S_030984_BASE_HI(va >> 40));
4164          else if (sctx->gfx_level == GFX9)
4165             si_pm4_set_reg(pm4, R_030944_VGT_TF_MEMORY_BASE_HI, S_030944_BASE_HI(va >> 40));
4166       } else {
4167          si_pm4_set_reg(pm4, R_008988_VGT_TF_RING_SIZE, S_008988_SIZE(tf_ring_size_field));
4168          si_pm4_set_reg(pm4, R_0089B8_VGT_TF_MEMORY_BASE, factor_va >> 8);
4169          si_pm4_set_reg(pm4, R_0089B0_VGT_HS_OFFCHIP_PARAM, sctx->screen->hs.hs_offchip_param);
4170       }
4171    }
4172 
4173    /* Flush the context to re-emit the cs_preamble state.
4174     * This is done only once in a lifetime of a context.
4175     */
4176    sctx->last_preamble = NULL; /* flag that the preamble has changed */
4177    sctx->initial_gfx_cs_size = 0; /* force flush */
4178    si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
4179 }
4180 
si_build_vgt_shader_config(struct si_screen * screen,union si_vgt_stages_key key)4181 struct si_pm4_state *si_build_vgt_shader_config(struct si_screen *screen, union si_vgt_stages_key key)
4182 {
4183    struct si_pm4_state *pm4 = CALLOC_STRUCT(si_pm4_state);
4184    uint32_t stages = 0;
4185 
4186    if (key.u.tess) {
4187       stages |= S_028B54_LS_EN(V_028B54_LS_STAGE_ON) | S_028B54_HS_EN(1) | S_028B54_DYNAMIC_HS(1);
4188 
4189       if (key.u.gs)
4190          stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_DS) | S_028B54_GS_EN(1);
4191       else if (key.u.ngg)
4192          stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_DS);
4193       else
4194          stages |= S_028B54_VS_EN(V_028B54_VS_STAGE_DS);
4195    } else if (key.u.gs) {
4196       stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_REAL) | S_028B54_GS_EN(1);
4197    } else if (key.u.ngg) {
4198       stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_REAL);
4199    }
4200 
4201    if (key.u.ngg) {
4202       stages |= S_028B54_PRIMGEN_EN(1) |
4203                 S_028B54_NGG_WAVE_ID_EN(key.u.streamout) |
4204                 S_028B54_PRIMGEN_PASSTHRU_EN(key.u.ngg_passthrough) |
4205                 S_028B54_PRIMGEN_PASSTHRU_NO_MSG(key.u.ngg_passthrough &&
4206                                                  screen->info.family >= CHIP_NAVI23);
4207    } else if (key.u.gs)
4208       stages |= S_028B54_VS_EN(V_028B54_VS_STAGE_COPY_SHADER);
4209 
4210    if (screen->info.gfx_level >= GFX9)
4211       stages |= S_028B54_MAX_PRIMGRP_IN_WAVE(2);
4212 
4213    if (screen->info.gfx_level >= GFX10) {
4214       stages |= S_028B54_HS_W32_EN(key.u.hs_wave32) |
4215                 S_028B54_GS_W32_EN(key.u.gs_wave32) |
4216                 S_028B54_VS_W32_EN(key.u.vs_wave32);
4217       /* Legacy GS only supports Wave64. Read it as an implication. */
4218       assert(!(key.u.gs && !key.u.ngg) || !key.u.gs_wave32);
4219    }
4220 
4221    si_pm4_set_reg(pm4, R_028B54_VGT_SHADER_STAGES_EN, stages);
4222    return pm4;
4223 }
4224 
si_emit_scratch_state(struct si_context * sctx)4225 static void si_emit_scratch_state(struct si_context *sctx)
4226 {
4227    struct radeon_cmdbuf *cs = &sctx->gfx_cs;
4228 
4229    radeon_begin(cs);
4230    if (sctx->gfx_level >= GFX11) {
4231       radeon_set_context_reg_seq(R_0286E8_SPI_TMPRING_SIZE, 3);
4232       radeon_emit(sctx->spi_tmpring_size);                  /* SPI_TMPRING_SIZE */
4233       radeon_emit(sctx->scratch_buffer->gpu_address >> 8);  /* SPI_GFX_SCRATCH_BASE_LO */
4234       radeon_emit(sctx->scratch_buffer->gpu_address >> 40); /* SPI_GFX_SCRATCH_BASE_HI */
4235    } else {
4236       radeon_set_context_reg(R_0286E8_SPI_TMPRING_SIZE, sctx->spi_tmpring_size);
4237    }
4238    radeon_end();
4239 
4240    if (sctx->scratch_buffer) {
4241       radeon_add_to_buffer_list(sctx, &sctx->gfx_cs, sctx->scratch_buffer,
4242                                 RADEON_USAGE_READWRITE | RADEON_PRIO_SCRATCH_BUFFER);
4243    }
4244 }
4245 
4246 struct si_fixed_func_tcs_shader_key {
4247    uint64_t outputs_written;
4248    uint8_t vertices_out;
4249 };
4250 
si_fixed_func_tcs_shader_key_hash(const void * key)4251 static uint32_t si_fixed_func_tcs_shader_key_hash(const void *key)
4252 {
4253    return _mesa_hash_data(key, sizeof(struct si_fixed_func_tcs_shader_key));
4254 }
4255 
si_fixed_func_tcs_shader_key_equals(const void * a,const void * b)4256 static bool si_fixed_func_tcs_shader_key_equals(const void *a, const void *b)
4257 {
4258    return memcmp(a, b, sizeof(struct si_fixed_func_tcs_shader_key)) == 0;
4259 }
4260 
si_set_tcs_to_fixed_func_shader(struct si_context * sctx)4261 bool si_set_tcs_to_fixed_func_shader(struct si_context *sctx)
4262 {
4263    if (!sctx->fixed_func_tcs_shader_cache) {
4264       sctx->fixed_func_tcs_shader_cache = _mesa_hash_table_create(
4265          NULL, si_fixed_func_tcs_shader_key_hash,
4266          si_fixed_func_tcs_shader_key_equals);
4267    }
4268 
4269    struct si_fixed_func_tcs_shader_key key;
4270    key.outputs_written = sctx->shader.vs.cso->info.outputs_written;
4271    key.vertices_out = sctx->patch_vertices;
4272 
4273    struct hash_entry *entry = _mesa_hash_table_search(
4274       sctx->fixed_func_tcs_shader_cache, &key);
4275 
4276    struct si_shader_selector *tcs;
4277    if (entry)
4278       tcs = (struct si_shader_selector *)entry->data;
4279    else {
4280       tcs = (struct si_shader_selector *)si_create_passthrough_tcs(sctx);
4281       if (!tcs)
4282          return false;
4283       _mesa_hash_table_insert(sctx->fixed_func_tcs_shader_cache, &key, (void *)tcs);
4284    }
4285 
4286    sctx->shader.tcs.cso = tcs;
4287    sctx->shader.tcs.key.ge.part.tcs.epilog.invoc0_tess_factors_are_def =
4288       tcs->info.tessfactors_are_def_in_all_invocs;
4289 
4290    return true;
4291 }
4292 
si_init_screen_live_shader_cache(struct si_screen * sscreen)4293 void si_init_screen_live_shader_cache(struct si_screen *sscreen)
4294 {
4295    util_live_shader_cache_init(&sscreen->live_shader_cache, si_create_shader_selector,
4296                                si_destroy_shader_selector);
4297 }
4298 
si_init_shader_functions(struct si_context * sctx)4299 void si_init_shader_functions(struct si_context *sctx)
4300 {
4301    sctx->atoms.s.scratch_state.emit = si_emit_scratch_state;
4302 
4303    sctx->b.create_vs_state = si_create_shader;
4304    sctx->b.create_tcs_state = si_create_shader;
4305    sctx->b.create_tes_state = si_create_shader;
4306    sctx->b.create_gs_state = si_create_shader;
4307    sctx->b.create_fs_state = si_create_shader;
4308 
4309    sctx->b.bind_vs_state = si_bind_vs_shader;
4310    sctx->b.bind_tcs_state = si_bind_tcs_shader;
4311    sctx->b.bind_tes_state = si_bind_tes_shader;
4312    sctx->b.bind_gs_state = si_bind_gs_shader;
4313    sctx->b.bind_fs_state = si_bind_ps_shader;
4314 
4315    sctx->b.delete_vs_state = si_delete_shader_selector;
4316    sctx->b.delete_tcs_state = si_delete_shader_selector;
4317    sctx->b.delete_tes_state = si_delete_shader_selector;
4318    sctx->b.delete_gs_state = si_delete_shader_selector;
4319    sctx->b.delete_fs_state = si_delete_shader_selector;
4320 }
4321