nir/scheduler: Move nir_scheduler to its own header
[mesa.git] / src / compiler / glsl / gl_nir_link_uniforms.c
1 /*
2 * Copyright © 2018 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include "nir.h"
25 #include "nir_deref.h"
26 #include "gl_nir_linker.h"
27 #include "compiler/glsl/ir_uniform.h" /* for gl_uniform_storage */
28 #include "linker_util.h"
29 #include "main/context.h"
30 #include "main/mtypes.h"
31
32 /**
33 * This file do the common link for GLSL uniforms, using NIR, instead of IR as
34 * the counter-part glsl/link_uniforms.cpp
35 */
36
37 #define UNMAPPED_UNIFORM_LOC ~0u
38
39 struct uniform_array_info {
40 /** List of dereferences of the uniform array. */
41 struct util_dynarray *deref_list;
42
43 /** Set of bit-flags to note which array elements have been accessed. */
44 BITSET_WORD *indices;
45 };
46
47 /**
48 * Built-in / reserved GL variables names start with "gl_"
49 */
50 static inline bool
51 is_gl_identifier(const char *s)
52 {
53 return s && s[0] == 'g' && s[1] == 'l' && s[2] == '_';
54 }
55
56 static unsigned
57 uniform_storage_size(const struct glsl_type *type)
58 {
59 switch (glsl_get_base_type(type)) {
60 case GLSL_TYPE_STRUCT:
61 case GLSL_TYPE_INTERFACE: {
62 unsigned size = 0;
63 for (unsigned i = 0; i < glsl_get_length(type); i++)
64 size += uniform_storage_size(glsl_get_struct_field(type, i));
65 return size;
66 }
67 case GLSL_TYPE_ARRAY: {
68 const struct glsl_type *e_type = glsl_get_array_element(type);
69 enum glsl_base_type e_base_type = glsl_get_base_type(e_type);
70 if (e_base_type == GLSL_TYPE_STRUCT ||
71 e_base_type == GLSL_TYPE_INTERFACE ||
72 e_base_type == GLSL_TYPE_ARRAY) {
73 unsigned length = !glsl_type_is_unsized_array(type) ?
74 glsl_get_length(type) : 1;
75 return length * uniform_storage_size(e_type);
76 } else
77 return 1;
78 }
79 default:
80 return 1;
81 }
82 }
83
84 /**
85 * Update the sizes of linked shader uniform arrays to the maximum
86 * array index used.
87 *
88 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
89 *
90 * If one or more elements of an array are active,
91 * GetActiveUniform will return the name of the array in name,
92 * subject to the restrictions listed above. The type of the array
93 * is returned in type. The size parameter contains the highest
94 * array element index used, plus one. The compiler or linker
95 * determines the highest index used. There will be only one
96 * active uniform reported by the GL per uniform array.
97 */
98 static void
99 update_array_sizes(struct gl_shader_program *prog, nir_variable *var,
100 struct hash_table **referenced_uniforms,
101 unsigned current_var_stage)
102 {
103 /* For now we only resize 1D arrays.
104 * TODO: add support for resizing more complex array types ??
105 */
106 if (!glsl_type_is_array(var->type) ||
107 glsl_type_is_array(glsl_get_array_element(var->type)))
108 return;
109
110 /* GL_ARB_uniform_buffer_object says that std140 uniforms
111 * will not be eliminated. Since we always do std140, just
112 * don't resize arrays in UBOs.
113 *
114 * Atomic counters are supposed to get deterministic
115 * locations assigned based on the declaration ordering and
116 * sizes, array compaction would mess that up.
117 *
118 * Subroutine uniforms are not removed.
119 */
120 if (nir_variable_is_in_block(var) || glsl_contains_atomic(var->type) ||
121 glsl_get_base_type(glsl_without_array(var->type)) == GLSL_TYPE_SUBROUTINE ||
122 var->constant_initializer)
123 return;
124
125 struct uniform_array_info *ainfo = NULL;
126 int words = BITSET_WORDS(glsl_array_size(var->type));
127 int max_array_size = 0;
128 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
129 struct gl_linked_shader *sh = prog->_LinkedShaders[stage];
130 if (!sh)
131 continue;
132
133 struct hash_entry *entry =
134 _mesa_hash_table_search(referenced_uniforms[stage], var->name);
135 if (entry) {
136 ainfo = (struct uniform_array_info *) entry->data;
137 max_array_size = MAX2(BITSET_LAST_BIT(ainfo->indices, words),
138 max_array_size);
139 }
140
141 if (max_array_size == glsl_array_size(var->type))
142 return;
143 }
144
145 if (max_array_size != glsl_array_size(var->type)) {
146 /* If this is a built-in uniform (i.e., it's backed by some
147 * fixed-function state), adjust the number of state slots to
148 * match the new array size. The number of slots per array entry
149 * is not known. It seems safe to assume that the total number of
150 * slots is an integer multiple of the number of array elements.
151 * Determine the number of slots per array element by dividing by
152 * the old (total) size.
153 */
154 const unsigned num_slots = var->num_state_slots;
155 if (num_slots > 0) {
156 var->num_state_slots =
157 (max_array_size * (num_slots / glsl_array_size(var->type)));
158 }
159
160 var->type = glsl_array_type(glsl_get_array_element(var->type),
161 max_array_size, 0);
162
163 /* Update the types of dereferences in case we changed any. */
164 struct hash_entry *entry =
165 _mesa_hash_table_search(referenced_uniforms[current_var_stage], var->name);
166 if (entry) {
167 struct uniform_array_info *ainfo =
168 (struct uniform_array_info *) entry->data;
169 util_dynarray_foreach(ainfo->deref_list, nir_deref_instr *, deref) {
170 (*deref)->type = var->type;
171 }
172 }
173 }
174 }
175
176 static void
177 nir_setup_uniform_remap_tables(struct gl_context *ctx,
178 struct gl_shader_program *prog)
179 {
180 unsigned total_entries = prog->NumExplicitUniformLocations;
181
182 /* For glsl this may have been allocated by reserve_explicit_locations() so
183 * that we can keep track of unused uniforms with explicit locations.
184 */
185 assert(!prog->data->spirv ||
186 (prog->data->spirv && !prog->UniformRemapTable));
187 if (!prog->UniformRemapTable) {
188 prog->UniformRemapTable = rzalloc_array(prog,
189 struct gl_uniform_storage *,
190 prog->NumUniformRemapTable);
191 }
192
193 union gl_constant_value *data =
194 rzalloc_array(prog->data,
195 union gl_constant_value, prog->data->NumUniformDataSlots);
196 if (!prog->UniformRemapTable || !data) {
197 linker_error(prog, "Out of memory during linking.\n");
198 return;
199 }
200 prog->data->UniformDataSlots = data;
201
202 prog->data->UniformDataDefaults =
203 rzalloc_array(prog->data->UniformDataSlots,
204 union gl_constant_value, prog->data->NumUniformDataSlots);
205
206 unsigned data_pos = 0;
207
208 /* Reserve all the explicit locations of the active uniforms. */
209 for (unsigned i = 0; i < prog->data->NumUniformStorage; i++) {
210 struct gl_uniform_storage *uniform = &prog->data->UniformStorage[i];
211
212 if (uniform->is_shader_storage ||
213 glsl_get_base_type(uniform->type) == GLSL_TYPE_SUBROUTINE)
214 continue;
215
216 if (prog->data->UniformStorage[i].remap_location == UNMAPPED_UNIFORM_LOC)
217 continue;
218
219 /* How many new entries for this uniform? */
220 const unsigned entries = MAX2(1, uniform->array_elements);
221 unsigned num_slots = glsl_get_component_slots(uniform->type);
222
223 uniform->storage = &data[data_pos];
224
225 /* Set remap table entries point to correct gl_uniform_storage. */
226 for (unsigned j = 0; j < entries; j++) {
227 unsigned element_loc = uniform->remap_location + j;
228 prog->UniformRemapTable[element_loc] = uniform;
229
230 data_pos += num_slots;
231 }
232 }
233
234 /* Reserve locations for rest of the uniforms. */
235 if (prog->data->spirv)
236 link_util_update_empty_uniform_locations(prog);
237
238 for (unsigned i = 0; i < prog->data->NumUniformStorage; i++) {
239 struct gl_uniform_storage *uniform = &prog->data->UniformStorage[i];
240
241 if (uniform->is_shader_storage ||
242 glsl_get_base_type(uniform->type) == GLSL_TYPE_SUBROUTINE)
243 continue;
244
245 /* Built-in uniforms should not get any location. */
246 if (uniform->builtin)
247 continue;
248
249 /* Explicit ones have been set already. */
250 if (uniform->remap_location != UNMAPPED_UNIFORM_LOC)
251 continue;
252
253 /* How many entries for this uniform? */
254 const unsigned entries = MAX2(1, uniform->array_elements);
255
256 /* Add new entries to the total amount for checking against MAX_UNIFORM-
257 * _LOCATIONS. This only applies to the default uniform block (-1),
258 * because locations of uniform block entries are not assignable.
259 */
260 if (prog->data->UniformStorage[i].block_index == -1)
261 total_entries += entries;
262
263 unsigned location =
264 link_util_find_empty_block(prog, &prog->data->UniformStorage[i]);
265
266 if (location == -1) {
267 location = prog->NumUniformRemapTable;
268
269 /* resize remap table to fit new entries */
270 prog->UniformRemapTable =
271 reralloc(prog,
272 prog->UniformRemapTable,
273 struct gl_uniform_storage *,
274 prog->NumUniformRemapTable + entries);
275 prog->NumUniformRemapTable += entries;
276 }
277
278 /* set the base location in remap table for the uniform */
279 uniform->remap_location = location;
280
281 unsigned num_slots = glsl_get_component_slots(uniform->type);
282
283 if (uniform->block_index == -1)
284 uniform->storage = &data[data_pos];
285
286 /* Set remap table entries point to correct gl_uniform_storage. */
287 for (unsigned j = 0; j < entries; j++) {
288 unsigned element_loc = uniform->remap_location + j;
289 prog->UniformRemapTable[element_loc] = uniform;
290
291 if (uniform->block_index == -1)
292 data_pos += num_slots;
293 }
294 }
295
296 /* Verify that total amount of entries for explicit and implicit locations
297 * is less than MAX_UNIFORM_LOCATIONS.
298 */
299 if (total_entries > ctx->Const.MaxUserAssignableUniformLocations) {
300 linker_error(prog, "count of uniform locations > MAX_UNIFORM_LOCATIONS"
301 "(%u > %u)", total_entries,
302 ctx->Const.MaxUserAssignableUniformLocations);
303 }
304
305 /* Reserve all the explicit locations of the active subroutine uniforms. */
306 for (unsigned i = 0; i < prog->data->NumUniformStorage; i++) {
307 struct gl_uniform_storage *uniform = &prog->data->UniformStorage[i];
308
309 if (glsl_get_base_type(uniform->type) != GLSL_TYPE_SUBROUTINE)
310 continue;
311
312 if (prog->data->UniformStorage[i].remap_location == UNMAPPED_UNIFORM_LOC)
313 continue;
314
315 /* How many new entries for this uniform? */
316 const unsigned entries =
317 MAX2(1, prog->data->UniformStorage[i].array_elements);
318
319 uniform->storage = &data[data_pos];
320
321 unsigned num_slots = glsl_get_component_slots(uniform->type);
322 unsigned mask = prog->data->linked_stages;
323 while (mask) {
324 const int j = u_bit_scan(&mask);
325 struct gl_program *p = prog->_LinkedShaders[j]->Program;
326
327 if (!prog->data->UniformStorage[i].opaque[j].active)
328 continue;
329
330 /* Set remap table entries point to correct gl_uniform_storage. */
331 for (unsigned k = 0; k < entries; k++) {
332 unsigned element_loc =
333 prog->data->UniformStorage[i].remap_location + k;
334 p->sh.SubroutineUniformRemapTable[element_loc] =
335 &prog->data->UniformStorage[i];
336
337 data_pos += num_slots;
338 }
339 }
340 }
341
342 /* reserve subroutine locations */
343 for (unsigned i = 0; i < prog->data->NumUniformStorage; i++) {
344 struct gl_uniform_storage *uniform = &prog->data->UniformStorage[i];
345
346 if (glsl_get_base_type(uniform->type) != GLSL_TYPE_SUBROUTINE)
347 continue;
348
349 if (prog->data->UniformStorage[i].remap_location !=
350 UNMAPPED_UNIFORM_LOC)
351 continue;
352
353 const unsigned entries =
354 MAX2(1, prog->data->UniformStorage[i].array_elements);
355
356 uniform->storage = &data[data_pos];
357
358 unsigned num_slots = glsl_get_component_slots(uniform->type);
359 unsigned mask = prog->data->linked_stages;
360 while (mask) {
361 const int j = u_bit_scan(&mask);
362 struct gl_program *p = prog->_LinkedShaders[j]->Program;
363
364 if (!prog->data->UniformStorage[i].opaque[j].active)
365 continue;
366
367 p->sh.SubroutineUniformRemapTable =
368 reralloc(p,
369 p->sh.SubroutineUniformRemapTable,
370 struct gl_uniform_storage *,
371 p->sh.NumSubroutineUniformRemapTable + entries);
372
373 for (unsigned k = 0; k < entries; k++) {
374 p->sh.SubroutineUniformRemapTable[p->sh.NumSubroutineUniformRemapTable + k] =
375 &prog->data->UniformStorage[i];
376
377 data_pos += num_slots;
378 }
379 prog->data->UniformStorage[i].remap_location =
380 p->sh.NumSubroutineUniformRemapTable;
381 p->sh.NumSubroutineUniformRemapTable += entries;
382 }
383 }
384 }
385
386 static void
387 add_var_use_deref(nir_deref_instr *deref, struct hash_table *live,
388 struct array_deref_range **derefs, unsigned *derefs_size)
389 {
390 nir_deref_path path;
391 nir_deref_path_init(&path, deref, NULL);
392
393 deref = path.path[0];
394 if (deref->deref_type != nir_deref_type_var ||
395 deref->mode & ~(nir_var_uniform | nir_var_mem_ubo | nir_var_mem_ssbo)) {
396 nir_deref_path_finish(&path);
397 return;
398 }
399
400 /* Number of derefs used in current processing. */
401 unsigned num_derefs = 0;
402
403 const struct glsl_type *deref_type = deref->var->type;
404 nir_deref_instr **p = &path.path[1];
405 for (; *p; p++) {
406 if ((*p)->deref_type == nir_deref_type_array) {
407
408 /* Skip matrix derefences */
409 if (!glsl_type_is_array(deref_type))
410 break;
411
412 if ((num_derefs + 1) * sizeof(struct array_deref_range) > *derefs_size) {
413 void *ptr = reralloc_size(NULL, *derefs, *derefs_size + 4096);
414
415 if (ptr == NULL) {
416 nir_deref_path_finish(&path);
417 return;
418 }
419
420 *derefs_size += 4096;
421 *derefs = (struct array_deref_range *)ptr;
422 }
423
424 struct array_deref_range *dr = &(*derefs)[num_derefs];
425 num_derefs++;
426
427 dr->size = glsl_get_length(deref_type);
428
429 if (nir_src_is_const((*p)->arr.index)) {
430 dr->index = nir_src_as_uint((*p)->arr.index);
431 } else {
432 /* An unsized array can occur at the end of an SSBO. We can't track
433 * accesses to such an array, so bail.
434 */
435 if (dr->size == 0) {
436 nir_deref_path_finish(&path);
437 return;
438 }
439
440 dr->index = dr->size;
441 }
442
443 deref_type = glsl_get_array_element(deref_type);
444 } else if ((*p)->deref_type == nir_deref_type_struct) {
445 /* We have reached the end of the array. */
446 break;
447 }
448 }
449
450 nir_deref_path_finish(&path);
451
452
453 struct uniform_array_info *ainfo = NULL;
454
455 struct hash_entry *entry =
456 _mesa_hash_table_search(live, deref->var->name);
457 if (!entry && glsl_type_is_array(deref->var->type)) {
458 ainfo = ralloc(live, struct uniform_array_info);
459
460 unsigned num_bits = MAX2(1, glsl_get_aoa_size(deref->var->type));
461 ainfo->indices = rzalloc_array(live, BITSET_WORD, BITSET_WORDS(num_bits));
462
463 ainfo->deref_list = ralloc(live, struct util_dynarray);
464 util_dynarray_init(ainfo->deref_list, live);
465 }
466
467 if (entry)
468 ainfo = (struct uniform_array_info *) entry->data;
469
470 if (glsl_type_is_array(deref->var->type)) {
471 /* Count the "depth" of the arrays-of-arrays. */
472 unsigned array_depth = 0;
473 for (const struct glsl_type *type = deref->var->type;
474 glsl_type_is_array(type);
475 type = glsl_get_array_element(type)) {
476 array_depth++;
477 }
478
479 link_util_mark_array_elements_referenced(*derefs, num_derefs, array_depth,
480 ainfo->indices);
481
482 util_dynarray_append(ainfo->deref_list, nir_deref_instr *, deref);
483 }
484
485 assert(deref->mode == deref->var->data.mode);
486 _mesa_hash_table_insert(live, deref->var->name, ainfo);
487 }
488
489 /* Iterate over the shader and collect infomation about uniform use */
490 static void
491 add_var_use_shader(nir_shader *shader, struct hash_table *live)
492 {
493 /* Currently allocated buffer block of derefs. */
494 struct array_deref_range *derefs = NULL;
495
496 /* Size of the derefs buffer in bytes. */
497 unsigned derefs_size = 0;
498
499 nir_foreach_function(function, shader) {
500 if (function->impl) {
501 nir_foreach_block(block, function->impl) {
502 nir_foreach_instr(instr, block) {
503 if (instr->type == nir_instr_type_intrinsic) {
504 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
505 switch (intr->intrinsic) {
506 case nir_intrinsic_atomic_counter_read_deref:
507 case nir_intrinsic_atomic_counter_inc_deref:
508 case nir_intrinsic_atomic_counter_pre_dec_deref:
509 case nir_intrinsic_atomic_counter_post_dec_deref:
510 case nir_intrinsic_atomic_counter_add_deref:
511 case nir_intrinsic_atomic_counter_min_deref:
512 case nir_intrinsic_atomic_counter_max_deref:
513 case nir_intrinsic_atomic_counter_and_deref:
514 case nir_intrinsic_atomic_counter_or_deref:
515 case nir_intrinsic_atomic_counter_xor_deref:
516 case nir_intrinsic_atomic_counter_exchange_deref:
517 case nir_intrinsic_atomic_counter_comp_swap_deref:
518 case nir_intrinsic_image_deref_load:
519 case nir_intrinsic_image_deref_store:
520 case nir_intrinsic_image_deref_atomic_add:
521 case nir_intrinsic_image_deref_atomic_umin:
522 case nir_intrinsic_image_deref_atomic_imin:
523 case nir_intrinsic_image_deref_atomic_umax:
524 case nir_intrinsic_image_deref_atomic_imax:
525 case nir_intrinsic_image_deref_atomic_and:
526 case nir_intrinsic_image_deref_atomic_or:
527 case nir_intrinsic_image_deref_atomic_xor:
528 case nir_intrinsic_image_deref_atomic_exchange:
529 case nir_intrinsic_image_deref_atomic_comp_swap:
530 case nir_intrinsic_image_deref_size:
531 case nir_intrinsic_image_deref_samples:
532 case nir_intrinsic_load_deref:
533 case nir_intrinsic_store_deref:
534 add_var_use_deref(nir_src_as_deref(intr->src[0]), live,
535 &derefs, &derefs_size);
536 break;
537
538 default:
539 /* Nothing to do */
540 break;
541 }
542 } else if (instr->type == nir_instr_type_tex) {
543 nir_tex_instr *tex_instr = nir_instr_as_tex(instr);
544 int sampler_idx =
545 nir_tex_instr_src_index(tex_instr,
546 nir_tex_src_sampler_deref);
547 int texture_idx =
548 nir_tex_instr_src_index(tex_instr,
549 nir_tex_src_texture_deref);
550
551 if (sampler_idx >= 0) {
552 nir_deref_instr *deref =
553 nir_src_as_deref(tex_instr->src[sampler_idx].src);
554 add_var_use_deref(deref, live, &derefs, &derefs_size);
555 }
556
557 if (texture_idx >= 0) {
558 nir_deref_instr *deref =
559 nir_src_as_deref(tex_instr->src[texture_idx].src);
560 add_var_use_deref(deref, live, &derefs, &derefs_size);
561 }
562 }
563 }
564 }
565 }
566 }
567
568 ralloc_free(derefs);
569 }
570
571 static void
572 mark_stage_as_active(struct gl_uniform_storage *uniform,
573 unsigned stage)
574 {
575 uniform->active_shader_mask |= 1 << stage;
576 }
577
578 /* Used to build a tree representing the glsl_type so that we can have a place
579 * to store the next index for opaque types. Array types are expanded so that
580 * they have a single child which is used for all elements of the array.
581 * Struct types have a child for each member. The tree is walked while
582 * processing a uniform so that we can recognise when an opaque type is
583 * encountered a second time in order to reuse the same range of indices that
584 * was reserved the first time. That way the sampler indices can be arranged
585 * so that members of an array are placed sequentially even if the array is an
586 * array of structs containing other opaque members.
587 */
588 struct type_tree_entry {
589 /* For opaque types, this will be the next index to use. If we haven’t
590 * encountered this member yet, it will be UINT_MAX.
591 */
592 unsigned next_index;
593 unsigned array_size;
594 struct type_tree_entry *parent;
595 struct type_tree_entry *next_sibling;
596 struct type_tree_entry *children;
597 };
598
599 struct nir_link_uniforms_state {
600 /* per-whole program */
601 unsigned num_hidden_uniforms;
602 unsigned num_values;
603 unsigned max_uniform_location;
604
605 /* per-shader stage */
606 unsigned next_bindless_image_index;
607 unsigned next_bindless_sampler_index;
608 unsigned next_image_index;
609 unsigned next_sampler_index;
610 unsigned next_subroutine;
611 unsigned num_shader_samplers;
612 unsigned num_shader_images;
613 unsigned num_shader_uniform_components;
614 unsigned shader_samplers_used;
615 unsigned shader_shadow_samplers;
616 unsigned shader_storage_blocks_write_access;
617 struct gl_program_parameter_list *params;
618
619 /* per-variable */
620 nir_variable *current_var;
621 const struct glsl_type *current_ifc_type;
622 int offset;
623 bool var_is_in_block;
624 bool set_top_level_array;
625 int top_level_array_size;
626 int top_level_array_stride;
627
628 struct type_tree_entry *current_type;
629 struct hash_table *referenced_uniforms[MESA_SHADER_STAGES];
630 struct hash_table *uniform_hash;
631 };
632
633 static void
634 add_parameter(struct gl_uniform_storage *uniform,
635 struct gl_context *ctx,
636 struct gl_shader_program *prog,
637 const struct glsl_type *type,
638 struct nir_link_uniforms_state *state)
639 {
640 if (!state->params || uniform->is_shader_storage ||
641 (glsl_contains_opaque(type) && !state->current_var->data.bindless))
642 return;
643
644 unsigned num_params = glsl_get_aoa_size(type);
645 num_params = MAX2(num_params, 1);
646 num_params *= glsl_get_matrix_columns(glsl_without_array(type));
647
648 bool is_dual_slot = glsl_type_is_dual_slot(glsl_without_array(type));
649 if (is_dual_slot)
650 num_params *= 2;
651
652 struct gl_program_parameter_list *params = state->params;
653 int base_index = params->NumParameters;
654 _mesa_reserve_parameter_storage(params, num_params);
655
656 if (ctx->Const.PackedDriverUniformStorage) {
657 for (unsigned i = 0; i < num_params; i++) {
658 unsigned dmul = glsl_type_is_64bit(glsl_without_array(type)) ? 2 : 1;
659 unsigned comps = glsl_get_vector_elements(glsl_without_array(type)) * dmul;
660 if (is_dual_slot) {
661 if (i & 0x1)
662 comps -= 4;
663 else
664 comps = 4;
665 }
666
667 _mesa_add_parameter(params, PROGRAM_UNIFORM, uniform->name, comps,
668 glsl_get_gl_type(type), NULL, NULL, false);
669 }
670 } else {
671 for (unsigned i = 0; i < num_params; i++) {
672 _mesa_add_parameter(params, PROGRAM_UNIFORM, uniform->name, 4,
673 glsl_get_gl_type(type), NULL, NULL, true);
674 }
675 }
676
677 /* Each Parameter will hold the index to the backing uniform storage.
678 * This avoids relying on names to match parameters and uniform
679 * storages.
680 */
681 for (unsigned i = 0; i < num_params; i++) {
682 struct gl_program_parameter *param = &params->Parameters[base_index + i];
683 param->UniformStorageIndex = uniform - prog->data->UniformStorage;
684 param->MainUniformStorageIndex = state->current_var->data.location;
685 }
686 }
687
688 static unsigned
689 get_next_index(struct nir_link_uniforms_state *state,
690 const struct gl_uniform_storage *uniform,
691 unsigned *next_index, bool *initialised)
692 {
693 /* If we’ve already calculated an index for this member then we can just
694 * offset from there.
695 */
696 if (state->current_type->next_index == UINT_MAX) {
697 /* Otherwise we need to reserve enough indices for all of the arrays
698 * enclosing this member.
699 */
700
701 unsigned array_size = 1;
702
703 for (const struct type_tree_entry *p = state->current_type;
704 p;
705 p = p->parent) {
706 array_size *= p->array_size;
707 }
708
709 state->current_type->next_index = *next_index;
710 *next_index += array_size;
711 *initialised = true;
712 } else
713 *initialised = false;
714
715 unsigned index = state->current_type->next_index;
716
717 state->current_type->next_index += MAX2(1, uniform->array_elements);
718
719 return index;
720 }
721
722 /* Update the uniforms info for the current shader stage */
723 static void
724 update_uniforms_shader_info(struct gl_shader_program *prog,
725 struct nir_link_uniforms_state *state,
726 struct gl_uniform_storage *uniform,
727 const struct glsl_type *type,
728 unsigned stage)
729 {
730 unsigned values = glsl_get_component_slots(type);
731 const struct glsl_type *type_no_array = glsl_without_array(type);
732
733 if (glsl_type_is_sampler(type_no_array)) {
734 bool init_idx;
735 unsigned *next_index = state->current_var->data.bindless ?
736 &state->next_bindless_sampler_index :
737 &state->next_sampler_index;
738 int sampler_index = get_next_index(state, uniform, next_index, &init_idx);
739 struct gl_linked_shader *sh = prog->_LinkedShaders[stage];
740
741 if (state->current_var->data.bindless) {
742 if (init_idx) {
743 sh->Program->sh.BindlessSamplers =
744 rerzalloc(sh->Program, sh->Program->sh.BindlessSamplers,
745 struct gl_bindless_sampler,
746 sh->Program->sh.NumBindlessSamplers,
747 state->next_bindless_sampler_index);
748
749 for (unsigned j = sh->Program->sh.NumBindlessSamplers;
750 j < state->next_bindless_sampler_index; j++) {
751 sh->Program->sh.BindlessSamplers[j].target =
752 glsl_get_sampler_target(type_no_array);
753 }
754
755 sh->Program->sh.NumBindlessSamplers =
756 state->next_bindless_sampler_index;
757 }
758
759 if (!state->var_is_in_block)
760 state->num_shader_uniform_components += values;
761 } else {
762 /* Samplers (bound or bindless) are counted as two components
763 * as specified by ARB_bindless_texture.
764 */
765 state->num_shader_samplers += values / 2;
766
767 if (init_idx) {
768 const unsigned shadow = glsl_sampler_type_is_shadow(type_no_array);
769 for (unsigned i = sampler_index;
770 i < MIN2(state->next_sampler_index, MAX_SAMPLERS); i++) {
771 sh->Program->sh.SamplerTargets[i] =
772 glsl_get_sampler_target(type_no_array);
773 state->shader_samplers_used |= 1U << i;
774 state->shader_shadow_samplers |= shadow << i;
775 }
776 }
777 }
778
779 uniform->opaque[stage].active = true;
780 uniform->opaque[stage].index = sampler_index;
781 } else if (glsl_type_is_image(type_no_array)) {
782 struct gl_linked_shader *sh = prog->_LinkedShaders[stage];
783
784 /* Set image access qualifiers */
785 enum gl_access_qualifier image_access =
786 state->current_var->data.access;
787 const GLenum access =
788 (image_access & ACCESS_NON_WRITEABLE) ?
789 ((image_access & ACCESS_NON_READABLE) ? GL_NONE :
790 GL_READ_ONLY) :
791 ((image_access & ACCESS_NON_READABLE) ? GL_WRITE_ONLY :
792 GL_READ_WRITE);
793
794 int image_index;
795 if (state->current_var->data.bindless) {
796 image_index = state->next_bindless_image_index;
797 state->next_bindless_image_index += MAX2(1, uniform->array_elements);
798
799 sh->Program->sh.BindlessImages =
800 rerzalloc(sh->Program, sh->Program->sh.BindlessImages,
801 struct gl_bindless_image,
802 sh->Program->sh.NumBindlessImages,
803 state->next_bindless_image_index);
804
805 for (unsigned j = sh->Program->sh.NumBindlessImages;
806 j < state->next_bindless_image_index; j++) {
807 sh->Program->sh.BindlessImages[j].access = access;
808 }
809
810 sh->Program->sh.NumBindlessImages = state->next_bindless_image_index;
811
812 } else {
813 image_index = state->next_image_index;
814 state->next_image_index += MAX2(1, uniform->array_elements);
815
816 /* Images (bound or bindless) are counted as two components as
817 * specified by ARB_bindless_texture.
818 */
819 state->num_shader_images += values / 2;
820
821 for (unsigned i = image_index;
822 i < MIN2(state->next_image_index, MAX_IMAGE_UNIFORMS); i++) {
823 sh->Program->sh.ImageAccess[i] = access;
824 }
825 }
826
827 uniform->opaque[stage].active = true;
828 uniform->opaque[stage].index = image_index;
829
830 if (!uniform->is_shader_storage)
831 state->num_shader_uniform_components += values;
832 } else {
833 if (glsl_get_base_type(type_no_array) == GLSL_TYPE_SUBROUTINE) {
834 struct gl_linked_shader *sh = prog->_LinkedShaders[stage];
835
836 uniform->opaque[stage].index = state->next_subroutine;
837 uniform->opaque[stage].active = true;
838
839 sh->Program->sh.NumSubroutineUniforms++;
840
841 /* Increment the subroutine index by 1 for non-arrays and by the
842 * number of array elements for arrays.
843 */
844 state->next_subroutine += MAX2(1, uniform->array_elements);
845 }
846
847 if (!state->var_is_in_block)
848 state->num_shader_uniform_components += values;
849 }
850 }
851
852 static bool
853 find_and_update_named_uniform_storage(struct gl_context *ctx,
854 struct gl_shader_program *prog,
855 struct nir_link_uniforms_state *state,
856 nir_variable *var, char **name,
857 size_t name_length,
858 const struct glsl_type *type,
859 unsigned stage, bool *first_element)
860 {
861 /* gl_uniform_storage can cope with one level of array, so if the type is a
862 * composite type or an array where each element occupies more than one
863 * location than we need to recursively process it.
864 */
865 if (glsl_type_is_struct_or_ifc(type) ||
866 (glsl_type_is_array(type) &&
867 (glsl_type_is_array(glsl_get_array_element(type)) ||
868 glsl_type_is_struct_or_ifc(glsl_get_array_element(type))))) {
869
870 struct type_tree_entry *old_type = state->current_type;
871 state->current_type = old_type->children;
872
873 /* Shader storage block unsized arrays: add subscript [0] to variable
874 * names.
875 */
876 unsigned length = glsl_get_length(type);
877 if (glsl_type_is_unsized_array(type))
878 length = 1;
879
880 bool result = false;
881 for (unsigned i = 0; i < length; i++) {
882 const struct glsl_type *field_type;
883 size_t new_length = name_length;
884
885 if (glsl_type_is_struct_or_ifc(type)) {
886 field_type = glsl_get_struct_field(type, i);
887
888 /* Append '.field' to the current variable name. */
889 if (name) {
890 ralloc_asprintf_rewrite_tail(name, &new_length, ".%s",
891 glsl_get_struct_elem_name(type, i));
892 }
893 } else {
894 field_type = glsl_get_array_element(type);
895
896 /* Append the subscript to the current variable name */
897 if (name)
898 ralloc_asprintf_rewrite_tail(name, &new_length, "[%u]", i);
899 }
900
901 result = find_and_update_named_uniform_storage(ctx, prog, state,
902 var, name, new_length,
903 field_type, stage,
904 first_element);
905
906 if (glsl_type_is_struct_or_ifc(type))
907 state->current_type = state->current_type->next_sibling;
908
909 if (!result) {
910 state->current_type = old_type;
911 return false;
912 }
913 }
914
915 state->current_type = old_type;
916
917 return result;
918 } else {
919 struct hash_entry *entry =
920 _mesa_hash_table_search(state->uniform_hash, *name);
921 if (entry) {
922 unsigned i = (unsigned) (intptr_t) entry->data;
923 struct gl_uniform_storage *uniform = &prog->data->UniformStorage[i];
924
925 if (*first_element && !state->var_is_in_block) {
926 *first_element = false;
927 var->data.location = uniform - prog->data->UniformStorage;
928 }
929
930 update_uniforms_shader_info(prog, state, uniform, type, stage);
931
932 const struct glsl_type *type_no_array = glsl_without_array(type);
933 struct hash_entry *entry = prog->data->spirv ? NULL :
934 _mesa_hash_table_search(state->referenced_uniforms[stage],
935 state->current_var->name);
936 if (entry != NULL ||
937 glsl_get_base_type(type_no_array) == GLSL_TYPE_SUBROUTINE ||
938 prog->data->spirv)
939 uniform->active_shader_mask |= 1 << stage;
940
941 if (!state->var_is_in_block)
942 add_parameter(uniform, ctx, prog, type, state);
943
944 return true;
945 }
946 }
947
948 return false;
949 }
950
951 /**
952 * Finds, returns, and updates the stage info for any uniform in UniformStorage
953 * defined by @var. For GLSL this is done using the name, for SPIR-V in general
954 * is this done using the explicit location, except:
955 *
956 * * UBOs/SSBOs: as they lack explicit location, binding is used to locate
957 * them. That means that more that one entry at the uniform storage can be
958 * found. In that case all of them are updated, and the first entry is
959 * returned, in order to update the location of the nir variable.
960 *
961 * * Special uniforms: like atomic counters. They lack a explicit location,
962 * so they are skipped. They will be handled and assigned a location later.
963 *
964 */
965 static bool
966 find_and_update_previous_uniform_storage(struct gl_context *ctx,
967 struct gl_shader_program *prog,
968 struct nir_link_uniforms_state *state,
969 nir_variable *var, char *name,
970 const struct glsl_type *type,
971 unsigned stage)
972 {
973 if (!prog->data->spirv) {
974 bool first_element = true;
975 char *name_tmp = ralloc_strdup(NULL, name);
976 bool r = find_and_update_named_uniform_storage(ctx, prog, state, var,
977 &name_tmp,
978 strlen(name_tmp), type,
979 stage, &first_element);
980 ralloc_free(name_tmp);
981
982 return r;
983 }
984
985 if (nir_variable_is_in_block(var)) {
986 struct gl_uniform_storage *uniform = NULL;
987
988 ASSERTED unsigned num_blks = nir_variable_is_in_ubo(var) ?
989 prog->data->NumUniformBlocks :
990 prog->data->NumShaderStorageBlocks;
991
992 struct gl_uniform_block *blks = nir_variable_is_in_ubo(var) ?
993 prog->data->UniformBlocks : prog->data->ShaderStorageBlocks;
994
995 bool result = false;
996 for (unsigned i = 0; i < prog->data->NumUniformStorage; i++) {
997 /* UniformStorage contains both variables from ubos and ssbos */
998 if ( prog->data->UniformStorage[i].is_shader_storage !=
999 nir_variable_is_in_ssbo(var))
1000 continue;
1001
1002 int block_index = prog->data->UniformStorage[i].block_index;
1003 if (block_index != -1) {
1004 assert(block_index < num_blks);
1005
1006 if (var->data.binding == blks[block_index].Binding) {
1007 if (!uniform)
1008 uniform = &prog->data->UniformStorage[i];
1009 mark_stage_as_active(&prog->data->UniformStorage[i],
1010 stage);
1011 result = true;
1012 }
1013 }
1014 }
1015
1016 if (result)
1017 var->data.location = uniform - prog->data->UniformStorage;
1018 return result;
1019 }
1020
1021 /* Beyond blocks, there are still some corner cases of uniforms without
1022 * location (ie: atomic counters) that would have a initial location equal
1023 * to -1. We just return on that case. Those uniforms will be handled
1024 * later.
1025 */
1026 if (var->data.location == -1)
1027 return false;
1028
1029 /* TODO: following search can be problematic with shaders with a lot of
1030 * uniforms. Would it be better to use some type of hash
1031 */
1032 for (unsigned i = 0; i < prog->data->NumUniformStorage; i++) {
1033 if (prog->data->UniformStorage[i].remap_location == var->data.location) {
1034 mark_stage_as_active(&prog->data->UniformStorage[i], stage);
1035
1036 struct gl_uniform_storage *uniform = &prog->data->UniformStorage[i];
1037 var->data.location = uniform - prog->data->UniformStorage;
1038 add_parameter(uniform, ctx, prog, var->type, state);
1039 return true;
1040 }
1041 }
1042
1043 return false;
1044 }
1045
1046 static struct type_tree_entry *
1047 build_type_tree_for_type(const struct glsl_type *type)
1048 {
1049 struct type_tree_entry *entry = malloc(sizeof *entry);
1050
1051 entry->array_size = 1;
1052 entry->next_index = UINT_MAX;
1053 entry->children = NULL;
1054 entry->next_sibling = NULL;
1055 entry->parent = NULL;
1056
1057 if (glsl_type_is_array(type)) {
1058 entry->array_size = glsl_get_length(type);
1059 entry->children = build_type_tree_for_type(glsl_get_array_element(type));
1060 entry->children->parent = entry;
1061 } else if (glsl_type_is_struct_or_ifc(type)) {
1062 struct type_tree_entry *last = NULL;
1063
1064 for (unsigned i = 0; i < glsl_get_length(type); i++) {
1065 const struct glsl_type *field_type = glsl_get_struct_field(type, i);
1066 struct type_tree_entry *field_entry =
1067 build_type_tree_for_type(field_type);
1068
1069 if (last == NULL)
1070 entry->children = field_entry;
1071 else
1072 last->next_sibling = field_entry;
1073
1074 field_entry->parent = entry;
1075
1076 last = field_entry;
1077 }
1078 }
1079
1080 return entry;
1081 }
1082
1083 static void
1084 free_type_tree(struct type_tree_entry *entry)
1085 {
1086 struct type_tree_entry *p, *next;
1087
1088 for (p = entry->children; p; p = next) {
1089 next = p->next_sibling;
1090 free_type_tree(p);
1091 }
1092
1093 free(entry);
1094 }
1095
1096 static void
1097 hash_free_uniform_name(struct hash_entry *entry)
1098 {
1099 free((void*)entry->key);
1100 }
1101
1102 static void
1103 enter_record(struct nir_link_uniforms_state *state,
1104 struct gl_context *ctx,
1105 const struct glsl_type *type,
1106 bool row_major)
1107 {
1108 assert(glsl_type_is_struct(type));
1109 if (!state->var_is_in_block)
1110 return;
1111
1112 bool use_std430 = ctx->Const.UseSTD430AsDefaultPacking;
1113 const enum glsl_interface_packing packing =
1114 glsl_get_internal_ifc_packing(state->current_var->interface_type,
1115 use_std430);
1116
1117 if (packing == GLSL_INTERFACE_PACKING_STD430)
1118 state->offset = glsl_align(
1119 state->offset, glsl_get_std430_base_alignment(type, row_major));
1120 else
1121 state->offset = glsl_align(
1122 state->offset, glsl_get_std140_base_alignment(type, row_major));
1123 }
1124
1125 static void
1126 leave_record(struct nir_link_uniforms_state *state,
1127 struct gl_context *ctx,
1128 const struct glsl_type *type,
1129 bool row_major)
1130 {
1131 assert(glsl_type_is_struct(type));
1132 if (!state->var_is_in_block)
1133 return;
1134
1135 bool use_std430 = ctx->Const.UseSTD430AsDefaultPacking;
1136 const enum glsl_interface_packing packing =
1137 glsl_get_internal_ifc_packing(state->current_var->interface_type,
1138 use_std430);
1139
1140 if (packing == GLSL_INTERFACE_PACKING_STD430)
1141 state->offset = glsl_align(
1142 state->offset, glsl_get_std430_base_alignment(type, row_major));
1143 else
1144 state->offset = glsl_align(
1145 state->offset, glsl_get_std140_base_alignment(type, row_major));
1146 }
1147
1148 /**
1149 * Creates the neccessary entries in UniformStorage for the uniform. Returns
1150 * the number of locations used or -1 on failure.
1151 */
1152 static int
1153 nir_link_uniform(struct gl_context *ctx,
1154 struct gl_shader_program *prog,
1155 struct gl_program *stage_program,
1156 gl_shader_stage stage,
1157 const struct glsl_type *type,
1158 unsigned index_in_parent,
1159 int location,
1160 struct nir_link_uniforms_state *state,
1161 char **name, size_t name_length, bool row_major)
1162 {
1163 struct gl_uniform_storage *uniform = NULL;
1164
1165 if (state->set_top_level_array &&
1166 nir_variable_is_in_ssbo(state->current_var)) {
1167 /* Type is the top level SSBO member */
1168 if (glsl_type_is_array(type) &&
1169 (glsl_type_is_array(glsl_get_array_element(type)) ||
1170 glsl_type_is_struct_or_ifc(glsl_get_array_element(type)))) {
1171 /* Type is a top-level array (array of aggregate types) */
1172 state->top_level_array_size = glsl_get_length(type);
1173 state->top_level_array_stride = glsl_get_explicit_stride(type);
1174 } else {
1175 state->top_level_array_size = 1;
1176 state->top_level_array_stride = 0;
1177 }
1178
1179 state->set_top_level_array = false;
1180 }
1181
1182 /* gl_uniform_storage can cope with one level of array, so if the type is a
1183 * composite type or an array where each element occupies more than one
1184 * location than we need to recursively process it.
1185 */
1186 if (glsl_type_is_struct_or_ifc(type) ||
1187 (glsl_type_is_array(type) &&
1188 (glsl_type_is_array(glsl_get_array_element(type)) ||
1189 glsl_type_is_struct_or_ifc(glsl_get_array_element(type))))) {
1190 int location_count = 0;
1191 struct type_tree_entry *old_type = state->current_type;
1192 unsigned int struct_base_offset = state->offset;
1193
1194 state->current_type = old_type->children;
1195
1196 /* Shader storage block unsized arrays: add subscript [0] to variable
1197 * names.
1198 */
1199 unsigned length = glsl_get_length(type);
1200 if (glsl_type_is_unsized_array(type))
1201 length = 1;
1202
1203 if (glsl_type_is_struct(type) && !prog->data->spirv)
1204 enter_record(state, ctx, type, row_major);
1205
1206 for (unsigned i = 0; i < length; i++) {
1207 const struct glsl_type *field_type;
1208 size_t new_length = name_length;
1209 bool field_row_major = row_major;
1210
1211 if (glsl_type_is_struct_or_ifc(type)) {
1212 field_type = glsl_get_struct_field(type, i);
1213 /* Use the offset inside the struct only for variables backed by
1214 * a buffer object. For variables not backed by a buffer object,
1215 * offset is -1.
1216 */
1217 if (state->var_is_in_block) {
1218 if (prog->data->spirv) {
1219 state->offset =
1220 struct_base_offset + glsl_get_struct_field_offset(type, i);
1221 } else if (glsl_get_struct_field_offset(type, i) != -1 &&
1222 type == state->current_ifc_type) {
1223 state->offset = glsl_get_struct_field_offset(type, i);
1224 }
1225
1226 if (glsl_type_is_interface(type))
1227 state->set_top_level_array = true;
1228 }
1229
1230 /* Append '.field' to the current variable name. */
1231 if (name) {
1232 ralloc_asprintf_rewrite_tail(name, &new_length, ".%s",
1233 glsl_get_struct_elem_name(type, i));
1234 }
1235
1236
1237 /* The layout of structures at the top level of the block is set
1238 * during parsing. For matrices contained in multiple levels of
1239 * structures in the block, the inner structures have no layout.
1240 * These cases must potentially inherit the layout from the outer
1241 * levels.
1242 */
1243 const enum glsl_matrix_layout matrix_layout =
1244 glsl_get_struct_field_data(type, i)->matrix_layout;
1245 if (matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR) {
1246 field_row_major = true;
1247 } else if (matrix_layout == GLSL_MATRIX_LAYOUT_COLUMN_MAJOR) {
1248 field_row_major = false;
1249 }
1250 } else {
1251 field_type = glsl_get_array_element(type);
1252
1253 /* Append the subscript to the current variable name */
1254 if (name)
1255 ralloc_asprintf_rewrite_tail(name, &new_length, "[%u]", i);
1256 }
1257
1258 int entries = nir_link_uniform(ctx, prog, stage_program, stage,
1259 field_type, i, location,
1260 state, name, new_length,
1261 field_row_major);
1262
1263 if (entries == -1)
1264 return -1;
1265
1266 if (location != -1)
1267 location += entries;
1268 location_count += entries;
1269
1270 if (glsl_type_is_struct_or_ifc(type))
1271 state->current_type = state->current_type->next_sibling;
1272 }
1273
1274 if (glsl_type_is_struct(type) && !prog->data->spirv)
1275 leave_record(state, ctx, type, row_major);
1276
1277 state->current_type = old_type;
1278
1279 return location_count;
1280 } else {
1281 /* TODO: reallocating storage is slow, we should figure out a way to
1282 * allocate storage up front for spirv like we do for GLSL.
1283 */
1284 if (prog->data->spirv) {
1285 /* Create a new uniform storage entry */
1286 prog->data->UniformStorage =
1287 reralloc(prog->data,
1288 prog->data->UniformStorage,
1289 struct gl_uniform_storage,
1290 prog->data->NumUniformStorage + 1);
1291 if (!prog->data->UniformStorage) {
1292 linker_error(prog, "Out of memory during linking.\n");
1293 return -1;
1294 }
1295 }
1296
1297 uniform = &prog->data->UniformStorage[prog->data->NumUniformStorage];
1298 prog->data->NumUniformStorage++;
1299
1300 /* Initialize its members */
1301 memset(uniform, 0x00, sizeof(struct gl_uniform_storage));
1302
1303 uniform->name =
1304 name ? ralloc_strdup(prog->data->UniformStorage, *name) : NULL;
1305
1306 const struct glsl_type *type_no_array = glsl_without_array(type);
1307 if (glsl_type_is_array(type)) {
1308 uniform->type = type_no_array;
1309 uniform->array_elements = glsl_get_length(type);
1310 } else {
1311 uniform->type = type;
1312 uniform->array_elements = 0;
1313 }
1314 uniform->top_level_array_size = state->top_level_array_size;
1315 uniform->top_level_array_stride = state->top_level_array_stride;
1316
1317 struct hash_entry *entry = prog->data->spirv ? NULL :
1318 _mesa_hash_table_search(state->referenced_uniforms[stage],
1319 state->current_var->name);
1320 if (entry != NULL ||
1321 glsl_get_base_type(type_no_array) == GLSL_TYPE_SUBROUTINE ||
1322 prog->data->spirv)
1323 uniform->active_shader_mask |= 1 << stage;
1324
1325 if (location >= 0) {
1326 /* Uniform has an explicit location */
1327 uniform->remap_location = location;
1328 } else {
1329 uniform->remap_location = UNMAPPED_UNIFORM_LOC;
1330 }
1331
1332 uniform->hidden = state->current_var->data.how_declared == nir_var_hidden;
1333 if (uniform->hidden)
1334 state->num_hidden_uniforms++;
1335
1336 uniform->is_shader_storage = nir_variable_is_in_ssbo(state->current_var);
1337 uniform->is_bindless = state->current_var->data.bindless;
1338
1339 /* Set fields whose default value depend on the variable being inside a
1340 * block.
1341 *
1342 * From the OpenGL 4.6 spec, 7.3 Program objects:
1343 *
1344 * "For the property ARRAY_STRIDE, ... For active variables not declared
1345 * as an array of basic types, zero is written to params. For active
1346 * variables not backed by a buffer object, -1 is written to params,
1347 * regardless of the variable type."
1348 *
1349 * "For the property MATRIX_STRIDE, ... For active variables not declared
1350 * as a matrix or array of matrices, zero is written to params. For active
1351 * variables not backed by a buffer object, -1 is written to params,
1352 * regardless of the variable type."
1353 *
1354 * For the property IS_ROW_MAJOR, ... For active variables backed by a
1355 * buffer object, declared as a single matrix or array of matrices, and
1356 * stored in row-major order, one is written to params. For all other
1357 * active variables, zero is written to params.
1358 */
1359 uniform->array_stride = -1;
1360 uniform->matrix_stride = -1;
1361 uniform->row_major = false;
1362
1363 if (state->var_is_in_block) {
1364 uniform->array_stride = glsl_type_is_array(type) ?
1365 glsl_get_explicit_stride(type) : 0;
1366
1367 if (glsl_type_is_matrix(uniform->type)) {
1368 uniform->matrix_stride = glsl_get_explicit_stride(uniform->type);
1369 uniform->row_major = glsl_matrix_type_is_row_major(uniform->type);
1370 } else {
1371 uniform->matrix_stride = 0;
1372 }
1373
1374 if (!prog->data->spirv) {
1375 bool use_std430 = ctx->Const.UseSTD430AsDefaultPacking;
1376 const enum glsl_interface_packing packing =
1377 glsl_get_internal_ifc_packing(state->current_var->interface_type,
1378 use_std430);
1379
1380 unsigned alignment =
1381 glsl_get_std140_base_alignment(type, uniform->row_major);
1382 if (packing == GLSL_INTERFACE_PACKING_STD430) {
1383 alignment =
1384 glsl_get_std430_base_alignment(type, uniform->row_major);
1385 }
1386 state->offset = glsl_align(state->offset, alignment);
1387 }
1388 }
1389
1390 uniform->offset = state->var_is_in_block ? state->offset : -1;
1391
1392 int buffer_block_index = -1;
1393 /* If the uniform is inside a uniform block determine its block index by
1394 * comparing the bindings, we can not use names.
1395 */
1396 if (state->var_is_in_block) {
1397 struct gl_uniform_block *blocks = nir_variable_is_in_ssbo(state->current_var) ?
1398 prog->data->ShaderStorageBlocks : prog->data->UniformBlocks;
1399
1400 int num_blocks = nir_variable_is_in_ssbo(state->current_var) ?
1401 prog->data->NumShaderStorageBlocks : prog->data->NumUniformBlocks;
1402
1403 if (!prog->data->spirv) {
1404 bool is_interface_array =
1405 glsl_without_array(state->current_var->type) == state->current_var->interface_type &&
1406 glsl_type_is_array(state->current_var->type);
1407
1408 const char *ifc_name =
1409 glsl_get_type_name(state->current_var->interface_type);
1410 if (is_interface_array) {
1411 unsigned l = strlen(ifc_name);
1412 for (unsigned i = 0; i < num_blocks; i++) {
1413 if (strncmp(ifc_name, blocks[i].Name, l) == 0 &&
1414 blocks[i].Name[l] == '[') {
1415 buffer_block_index = i;
1416 break;
1417 }
1418 }
1419 } else {
1420 for (unsigned i = 0; i < num_blocks; i++) {
1421 if (strcmp(ifc_name, blocks[i].Name) == 0) {
1422 buffer_block_index = i;
1423 break;
1424 }
1425 }
1426 }
1427
1428 /* Compute the next offset. */
1429 bool use_std430 = ctx->Const.UseSTD430AsDefaultPacking;
1430 const enum glsl_interface_packing packing =
1431 glsl_get_internal_ifc_packing(state->current_var->interface_type,
1432 use_std430);
1433 if (packing == GLSL_INTERFACE_PACKING_STD430)
1434 state->offset += glsl_get_std430_size(type, uniform->row_major);
1435 else
1436 state->offset += glsl_get_std140_size(type, uniform->row_major);
1437 } else {
1438 for (unsigned i = 0; i < num_blocks; i++) {
1439 if (state->current_var->data.binding == blocks[i].Binding) {
1440 buffer_block_index = i;
1441 break;
1442 }
1443 }
1444
1445 /* Compute the next offset. */
1446 state->offset += glsl_get_explicit_size(type, true);
1447 }
1448 assert(buffer_block_index >= 0);
1449 }
1450
1451 uniform->block_index = buffer_block_index;
1452 uniform->builtin = is_gl_identifier(uniform->name);
1453 uniform->atomic_buffer_index = -1;
1454
1455 /* The following are not for features not supported by ARB_gl_spirv */
1456 uniform->num_compatible_subroutines = 0;
1457
1458 unsigned entries = MAX2(1, uniform->array_elements);
1459 unsigned values = glsl_get_component_slots(type);
1460
1461 update_uniforms_shader_info(prog, state, uniform, type, stage);
1462
1463 if (uniform->remap_location != UNMAPPED_UNIFORM_LOC &&
1464 state->max_uniform_location < uniform->remap_location + entries)
1465 state->max_uniform_location = uniform->remap_location + entries;
1466
1467 if (!state->var_is_in_block)
1468 add_parameter(uniform, ctx, prog, type, state);
1469
1470 if (name) {
1471 _mesa_hash_table_insert(state->uniform_hash, strdup(*name),
1472 (void *) (intptr_t)
1473 (prog->data->NumUniformStorage - 1));
1474 }
1475
1476 if (!is_gl_identifier(uniform->name) && !uniform->is_shader_storage &&
1477 !state->var_is_in_block)
1478 state->num_values += values;
1479
1480 return MAX2(uniform->array_elements, 1);
1481 }
1482 }
1483
1484 bool
1485 gl_nir_link_uniforms(struct gl_context *ctx,
1486 struct gl_shader_program *prog,
1487 bool fill_parameters)
1488 {
1489 /* First free up any previous UniformStorage items */
1490 ralloc_free(prog->data->UniformStorage);
1491 prog->data->UniformStorage = NULL;
1492 prog->data->NumUniformStorage = 0;
1493
1494 /* Iterate through all linked shaders */
1495 struct nir_link_uniforms_state state = {0,};
1496
1497 if (!prog->data->spirv) {
1498 /* Gather information on uniform use */
1499 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1500 struct gl_linked_shader *sh = prog->_LinkedShaders[stage];
1501 if (!sh)
1502 continue;
1503
1504 state.referenced_uniforms[stage] =
1505 _mesa_hash_table_create(NULL, _mesa_hash_string,
1506 _mesa_key_string_equal);
1507
1508 nir_shader *nir = sh->Program->nir;
1509 add_var_use_shader(nir, state.referenced_uniforms[stage]);
1510 }
1511
1512 /* Resize uniform arrays based on the maximum array index */
1513 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1514 struct gl_linked_shader *sh = prog->_LinkedShaders[stage];
1515 if (!sh)
1516 continue;
1517
1518 nir_shader *nir = sh->Program->nir;
1519 nir_foreach_variable(var, &nir->uniforms)
1520 update_array_sizes(prog, var, state.referenced_uniforms, stage);
1521 }
1522 }
1523
1524 /* Count total number of uniforms and allocate storage */
1525 unsigned storage_size = 0;
1526 if (!prog->data->spirv) {
1527 struct set *storage_counted =
1528 _mesa_set_create(NULL, _mesa_hash_string, _mesa_key_string_equal);
1529 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1530 struct gl_linked_shader *sh = prog->_LinkedShaders[stage];
1531 if (!sh)
1532 continue;
1533
1534 nir_foreach_variable(var, &sh->Program->nir->uniforms) {
1535 const struct glsl_type *type = var->type;
1536 const char *name = var->name;
1537 if (nir_variable_is_in_block(var) &&
1538 glsl_without_array(type) == var->interface_type) {
1539 type = glsl_without_array(var->type);
1540 name = glsl_get_type_name(type);
1541 }
1542
1543 struct set_entry *entry = _mesa_set_search(storage_counted, name);
1544 if (!entry) {
1545 storage_size += uniform_storage_size(type);
1546 _mesa_set_add(storage_counted, name);
1547 }
1548 }
1549 }
1550 _mesa_set_destroy(storage_counted, NULL);
1551
1552 prog->data->UniformStorage = rzalloc_array(prog->data,
1553 struct gl_uniform_storage,
1554 storage_size);
1555 if (!prog->data->UniformStorage) {
1556 linker_error(prog, "Out of memory while linking uniforms.\n");
1557 return false;
1558 }
1559 }
1560
1561 /* Iterate through all linked shaders */
1562 state.uniform_hash = _mesa_hash_table_create(NULL, _mesa_hash_string,
1563 _mesa_key_string_equal);
1564
1565 for (unsigned shader_type = 0; shader_type < MESA_SHADER_STAGES; shader_type++) {
1566 struct gl_linked_shader *sh = prog->_LinkedShaders[shader_type];
1567 if (!sh)
1568 continue;
1569
1570 nir_shader *nir = sh->Program->nir;
1571 assert(nir);
1572
1573 state.next_bindless_image_index = 0;
1574 state.next_bindless_sampler_index = 0;
1575 state.next_image_index = 0;
1576 state.next_sampler_index = 0;
1577 state.num_shader_samplers = 0;
1578 state.num_shader_images = 0;
1579 state.num_shader_uniform_components = 0;
1580 state.shader_storage_blocks_write_access = 0;
1581 state.shader_samplers_used = 0;
1582 state.shader_shadow_samplers = 0;
1583 state.params = fill_parameters ? sh->Program->Parameters : NULL;
1584
1585 nir_foreach_variable(var, &nir->uniforms) {
1586 state.current_var = var;
1587 state.current_ifc_type = NULL;
1588 state.offset = 0;
1589 state.var_is_in_block = nir_variable_is_in_block(var);
1590 state.set_top_level_array = false;
1591 state.top_level_array_size = 0;
1592 state.top_level_array_stride = 0;
1593
1594 /*
1595 * From ARB_program_interface spec, issue (16):
1596 *
1597 * "RESOLVED: We will follow the default rule for enumerating block
1598 * members in the OpenGL API, which is:
1599 *
1600 * * If a variable is a member of an interface block without an
1601 * instance name, it is enumerated using just the variable name.
1602 *
1603 * * If a variable is a member of an interface block with an
1604 * instance name, it is enumerated as "BlockName.Member", where
1605 * "BlockName" is the name of the interface block (not the
1606 * instance name) and "Member" is the name of the variable.
1607 *
1608 * For example, in the following code:
1609 *
1610 * uniform Block1 {
1611 * int member1;
1612 * };
1613 * uniform Block2 {
1614 * int member2;
1615 * } instance2;
1616 * uniform Block3 {
1617 * int member3;
1618 * } instance3[2]; // uses two separate buffer bindings
1619 *
1620 * the three uniforms (if active) are enumerated as "member1",
1621 * "Block2.member2", and "Block3.member3"."
1622 *
1623 * Note that in the last example, with an array of ubo, only one
1624 * uniform is generated. For that reason, while unrolling the
1625 * uniforms of a ubo, or the variables of a ssbo, we need to treat
1626 * arrays of instance as a single block.
1627 */
1628 char *name;
1629 const struct glsl_type *type = var->type;
1630 if (state.var_is_in_block &&
1631 ((!prog->data->spirv && glsl_without_array(type) == var->interface_type) ||
1632 (prog->data->spirv && type == var->interface_type))) {
1633 type = glsl_without_array(var->type);
1634 state.current_ifc_type = type;
1635 name = ralloc_strdup(NULL, glsl_get_type_name(type));
1636 } else {
1637 state.set_top_level_array = true;
1638 name = ralloc_strdup(NULL, var->name);
1639 }
1640
1641 struct type_tree_entry *type_tree =
1642 build_type_tree_for_type(type);
1643 state.current_type = type_tree;
1644
1645 int location = var->data.location;
1646
1647 struct gl_uniform_block *blocks;
1648 int num_blocks;
1649 int buffer_block_index = -1;
1650 if (!prog->data->spirv && state.var_is_in_block) {
1651 /* If the uniform is inside a uniform block determine its block index by
1652 * comparing the bindings, we can not use names.
1653 */
1654 blocks = nir_variable_is_in_ssbo(state.current_var) ?
1655 prog->data->ShaderStorageBlocks : prog->data->UniformBlocks;
1656 num_blocks = nir_variable_is_in_ssbo(state.current_var) ?
1657 prog->data->NumShaderStorageBlocks : prog->data->NumUniformBlocks;
1658
1659 bool is_interface_array =
1660 glsl_without_array(state.current_var->type) == state.current_var->interface_type &&
1661 glsl_type_is_array(state.current_var->type);
1662
1663 const char *ifc_name =
1664 glsl_get_type_name(state.current_var->interface_type);
1665
1666 if (is_interface_array) {
1667 unsigned l = strlen(ifc_name);
1668
1669 /* Even when a match is found, do not "break" here. As this is
1670 * an array of instances, all elements of the array need to be
1671 * marked as referenced.
1672 */
1673 for (unsigned i = 0; i < num_blocks; i++) {
1674 if (strncmp(ifc_name, blocks[i].Name, l) == 0 &&
1675 blocks[i].Name[l] == '[') {
1676 if (buffer_block_index == -1)
1677 buffer_block_index = i;
1678
1679 struct hash_entry *entry =
1680 _mesa_hash_table_search(state.referenced_uniforms[shader_type],
1681 var->name);
1682 if (entry) {
1683 struct uniform_array_info *ainfo =
1684 (struct uniform_array_info *) entry->data;
1685 if (BITSET_TEST(ainfo->indices, blocks[i].linearized_array_index))
1686 blocks[i].stageref |= 1U << shader_type;
1687 }
1688 }
1689 }
1690 } else {
1691 for (unsigned i = 0; i < num_blocks; i++) {
1692 if (strcmp(ifc_name, blocks[i].Name) == 0) {
1693 buffer_block_index = i;
1694
1695 struct hash_entry *entry =
1696 _mesa_hash_table_search(state.referenced_uniforms[shader_type],
1697 var->name);
1698 if (entry)
1699 blocks[i].stageref |= 1U << shader_type;
1700
1701 break;
1702 }
1703 }
1704 }
1705
1706 if (nir_variable_is_in_ssbo(var) &&
1707 !(var->data.access & ACCESS_NON_WRITEABLE)) {
1708 unsigned array_size = is_interface_array ?
1709 glsl_get_length(var->type) : 1;
1710
1711 STATIC_ASSERT(MAX_SHADER_STORAGE_BUFFERS <= 32);
1712
1713 /* Shaders that use too many SSBOs will fail to compile, which
1714 * we don't care about.
1715 *
1716 * This is true for shaders that do not use too many SSBOs:
1717 */
1718 if (buffer_block_index + array_size <= 32) {
1719 state.shader_storage_blocks_write_access |=
1720 u_bit_consecutive(buffer_block_index, array_size);
1721 }
1722 }
1723 }
1724
1725 if (!prog->data->spirv && state.var_is_in_block &&
1726 glsl_without_array(state.current_var->type) != state.current_var->interface_type) {
1727
1728 bool found = false;
1729 char sentinel = '\0';
1730
1731 if (glsl_type_is_struct(state.current_var->type)) {
1732 sentinel = '.';
1733 } else if (glsl_type_is_array(state.current_var->type) &&
1734 (glsl_type_is_array(glsl_get_array_element(state.current_var->type))
1735 || glsl_type_is_struct(glsl_without_array(state.current_var->type)))) {
1736 sentinel = '[';
1737 }
1738
1739 const unsigned l = strlen(state.current_var->name);
1740 for (unsigned i = 0; i < num_blocks; i++) {
1741 for (unsigned j = 0; j < blocks[i].NumUniforms; j++) {
1742 if (sentinel) {
1743 const char *begin = blocks[i].Uniforms[j].Name;
1744 const char *end = strchr(begin, sentinel);
1745
1746 if (end == NULL)
1747 continue;
1748
1749 if ((ptrdiff_t) l != (end - begin))
1750 continue;
1751 found = strncmp(state.current_var->name, begin, l) == 0;
1752 } else {
1753 found = strcmp(state.current_var->name, blocks[i].Uniforms[j].Name) == 0;
1754 }
1755
1756 if (found) {
1757 location = j;
1758
1759 struct hash_entry *entry =
1760 _mesa_hash_table_search(state.referenced_uniforms[shader_type], var->name);
1761 if (entry)
1762 blocks[i].stageref |= 1U << shader_type;
1763
1764 break;
1765 }
1766 }
1767
1768 if (found)
1769 break;
1770 }
1771 assert(found);
1772
1773 const struct gl_uniform_block *const block =
1774 &blocks[buffer_block_index];
1775 assert(location != -1);
1776
1777 const struct gl_uniform_buffer_variable *const ubo_var =
1778 &block->Uniforms[location];
1779
1780 state.offset = ubo_var->Offset;
1781 var->data.location = location;
1782 }
1783
1784 /* Check if the uniform has been processed already for
1785 * other stage. If so, validate they are compatible and update
1786 * the active stage mask.
1787 */
1788 if (find_and_update_previous_uniform_storage(ctx, prog, &state, var,
1789 name, type, shader_type)) {
1790 ralloc_free(name);
1791 free_type_tree(type_tree);
1792 continue;
1793 }
1794
1795 /* From now on the variable’s location will be its uniform index */
1796 if (!state.var_is_in_block)
1797 var->data.location = prog->data->NumUniformStorage;
1798 else
1799 location = -1;
1800
1801 bool row_major =
1802 var->data.matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR;
1803 int res = nir_link_uniform(ctx, prog, sh->Program, shader_type, type,
1804 0, location,
1805 &state,
1806 !prog->data->spirv ? &name : NULL,
1807 !prog->data->spirv ? strlen(name) : 0,
1808 row_major);
1809
1810 free_type_tree(type_tree);
1811 ralloc_free(name);
1812
1813 if (res == -1)
1814 return false;
1815 }
1816
1817 if (!prog->data->spirv) {
1818 _mesa_hash_table_destroy(state.referenced_uniforms[shader_type],
1819 NULL);
1820 }
1821
1822 if (state.num_shader_samplers >
1823 ctx->Const.Program[shader_type].MaxTextureImageUnits) {
1824 linker_error(prog, "Too many %s shader texture samplers\n",
1825 _mesa_shader_stage_to_string(shader_type));
1826 continue;
1827 }
1828
1829 if (state.num_shader_images >
1830 ctx->Const.Program[shader_type].MaxImageUniforms) {
1831 linker_error(prog, "Too many %s shader image uniforms (%u > %u)\n",
1832 _mesa_shader_stage_to_string(shader_type),
1833 state.num_shader_images,
1834 ctx->Const.Program[shader_type].MaxImageUniforms);
1835 continue;
1836 }
1837
1838 sh->Program->SamplersUsed = state.shader_samplers_used;
1839 sh->Program->sh.ShaderStorageBlocksWriteAccess =
1840 state.shader_storage_blocks_write_access;
1841 sh->shadow_samplers = state.shader_shadow_samplers;
1842 sh->Program->info.num_textures = state.num_shader_samplers;
1843 sh->Program->info.num_images = state.num_shader_images;
1844 sh->num_uniform_components = state.num_shader_uniform_components;
1845 sh->num_combined_uniform_components = sh->num_uniform_components;
1846 }
1847
1848 prog->data->NumHiddenUniforms = state.num_hidden_uniforms;
1849 prog->data->NumUniformDataSlots = state.num_values;
1850
1851 assert(prog->data->spirv || prog->data->NumUniformStorage == storage_size);
1852
1853 if (prog->data->spirv)
1854 prog->NumUniformRemapTable = state.max_uniform_location;
1855
1856 nir_setup_uniform_remap_tables(ctx, prog);
1857 gl_nir_set_uniform_initializers(ctx, prog);
1858
1859 _mesa_hash_table_destroy(state.uniform_hash, hash_free_uniform_name);
1860
1861 return true;
1862 }