glsl: Assert that interfaces, like structures, are not seen as leaf types
[mesa.git] / src / glsl / link_uniforms.cpp
1 /*
2 * Copyright © 2011 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
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24 #include "main/core.h"
25 #include "ir.h"
26 #include "linker.h"
27 #include "ir_uniform.h"
28 #include "glsl_symbol_table.h"
29 #include "program/hash_table.h"
30 #include "program.h"
31
32 static inline unsigned int
33 align(unsigned int a, unsigned int align)
34 {
35 return (a + align - 1) / align * align;
36 }
37
38 /**
39 * \file link_uniforms.cpp
40 * Assign locations for GLSL uniforms.
41 *
42 * \author Ian Romanick <ian.d.romanick@intel.com>
43 */
44
45 /**
46 * Count the backing storage requirements for a type
47 */
48 static unsigned
49 values_for_type(const glsl_type *type)
50 {
51 if (type->is_sampler()) {
52 return 1;
53 } else if (type->is_array() && type->fields.array->is_sampler()) {
54 return type->array_size();
55 } else {
56 return type->component_slots();
57 }
58 }
59
60 void
61 uniform_field_visitor::process(const glsl_type *type, const char *name)
62 {
63 assert(type->is_record()
64 || (type->is_array() && type->fields.array->is_record())
65 || type->is_interface()
66 || (type->is_array() && type->fields.array->is_interface()));
67
68 char *name_copy = ralloc_strdup(NULL, name);
69 recursion(type, &name_copy, strlen(name), false);
70 ralloc_free(name_copy);
71 }
72
73 void
74 uniform_field_visitor::process(ir_variable *var)
75 {
76 const glsl_type *t = var->type;
77
78 /* false is always passed for the row_major parameter to the other
79 * processing functions because no information is available to do
80 * otherwise. See the warning in linker.h.
81 */
82
83 /* Only strdup the name if we actually will need to modify it. */
84 if (t->is_record() || (t->is_array() && t->fields.array->is_record())) {
85 char *name = ralloc_strdup(NULL, var->name);
86 recursion(var->type, &name, strlen(name), false);
87 ralloc_free(name);
88 } else if (t->is_interface()) {
89 char *name = ralloc_strdup(NULL, var->type->name);
90 recursion(var->type, &name, strlen(name), false);
91 ralloc_free(name);
92 } else if (t->is_array() && t->fields.array->is_interface()) {
93 char *name = ralloc_strdup(NULL, var->type->fields.array->name);
94 recursion(var->type, &name, strlen(name), false);
95 ralloc_free(name);
96 } else {
97 this->visit_field(t, var->name, false);
98 }
99 }
100
101 void
102 uniform_field_visitor::recursion(const glsl_type *t, char **name,
103 size_t name_length, bool row_major)
104 {
105 /* Records need to have each field processed individually.
106 *
107 * Arrays of records need to have each array element processed
108 * individually, then each field of the resulting array elements processed
109 * individually.
110 */
111 if (t->is_record() || t->is_interface()) {
112 for (unsigned i = 0; i < t->length; i++) {
113 const char *field = t->fields.structure[i].name;
114 size_t new_length = name_length;
115
116 if (t->fields.structure[i].type->is_record())
117 this->visit_field(&t->fields.structure[i]);
118
119 /* Append '.field' to the current uniform name. */
120 if (name_length == 0) {
121 ralloc_asprintf_rewrite_tail(name, &new_length, "%s", field);
122 } else {
123 ralloc_asprintf_rewrite_tail(name, &new_length, ".%s", field);
124 }
125
126 recursion(t->fields.structure[i].type, name, new_length,
127 t->fields.structure[i].row_major);
128 }
129 } else if (t->is_array() && (t->fields.array->is_record()
130 || t->fields.array->is_interface())) {
131 for (unsigned i = 0; i < t->length; i++) {
132 size_t new_length = name_length;
133
134 /* Append the subscript to the current uniform name */
135 ralloc_asprintf_rewrite_tail(name, &new_length, "[%u]", i);
136
137 recursion(t->fields.array, name, new_length,
138 t->fields.structure[i].row_major);
139 }
140 } else {
141 this->visit_field(t, *name, row_major);
142 }
143 }
144
145 void
146 uniform_field_visitor::visit_field(const glsl_struct_field *field)
147 {
148 (void) field;
149 /* empty */
150 }
151
152 /**
153 * Class to help calculate the storage requirements for a set of uniforms
154 *
155 * As uniforms are added to the active set the number of active uniforms and
156 * the storage requirements for those uniforms are accumulated. The active
157 * uniforms are added the the hash table supplied to the constructor.
158 *
159 * If the same uniform is added multiple times (i.e., once for each shader
160 * target), it will only be accounted once.
161 */
162 class count_uniform_size : public uniform_field_visitor {
163 public:
164 count_uniform_size(struct string_to_uint_map *map)
165 : num_active_uniforms(0), num_values(0), num_shader_samplers(0),
166 num_shader_uniform_components(0), map(map)
167 {
168 /* empty */
169 }
170
171 void start_shader()
172 {
173 this->num_shader_samplers = 0;
174 this->num_shader_uniform_components = 0;
175 }
176
177 void process(ir_variable *var)
178 {
179 if (var->is_interface_instance())
180 uniform_field_visitor::process(var->interface_type,
181 var->interface_type->name);
182 else
183 uniform_field_visitor::process(var);
184 }
185
186 /**
187 * Total number of active uniforms counted
188 */
189 unsigned num_active_uniforms;
190
191 /**
192 * Number of data values required to back the storage for the active uniforms
193 */
194 unsigned num_values;
195
196 /**
197 * Number of samplers used
198 */
199 unsigned num_shader_samplers;
200
201 /**
202 * Number of uniforms used in the current shader
203 */
204 unsigned num_shader_uniform_components;
205
206 private:
207 virtual void visit_field(const glsl_type *type, const char *name,
208 bool row_major)
209 {
210 assert(!type->is_record());
211 assert(!(type->is_array() && type->fields.array->is_record()));
212 assert(!type->is_interface());
213 assert(!(type->is_array() && type->fields.array->is_interface()));
214
215 (void) row_major;
216
217 /* Count the number of samplers regardless of whether the uniform is
218 * already in the hash table. The hash table prevents adding the same
219 * uniform for multiple shader targets, but in this case we want to
220 * count it for each shader target.
221 */
222 const unsigned values = values_for_type(type);
223 if (type->contains_sampler()) {
224 this->num_shader_samplers +=
225 type->is_array() ? type->array_size() : 1;
226 } else {
227 /* Accumulate the total number of uniform slots used by this shader.
228 * Note that samplers do not count against this limit because they
229 * don't use any storage on current hardware.
230 */
231 this->num_shader_uniform_components += values;
232 }
233
234 /* If the uniform is already in the map, there's nothing more to do.
235 */
236 unsigned id;
237 if (this->map->get(id, name))
238 return;
239
240 this->map->put(this->num_active_uniforms, name);
241
242 /* Each leaf uniform occupies one entry in the list of active
243 * uniforms.
244 */
245 this->num_active_uniforms++;
246 this->num_values += values;
247 }
248
249 struct string_to_uint_map *map;
250 };
251
252 /**
253 * Class to help parcel out pieces of backing storage to uniforms
254 *
255 * Each uniform processed has some range of the \c gl_constant_value
256 * structures associated with it. The association is done by finding
257 * the uniform in the \c string_to_uint_map and using the value from
258 * the map to connect that slot in the \c gl_uniform_storage table
259 * with the next available slot in the \c gl_constant_value array.
260 *
261 * \warning
262 * This class assumes that every uniform that will be processed is
263 * already in the \c string_to_uint_map. In addition, it assumes that
264 * the \c gl_uniform_storage and \c gl_constant_value arrays are "big
265 * enough."
266 */
267 class parcel_out_uniform_storage : public uniform_field_visitor {
268 public:
269 parcel_out_uniform_storage(struct string_to_uint_map *map,
270 struct gl_uniform_storage *uniforms,
271 union gl_constant_value *values)
272 : map(map), uniforms(uniforms), next_sampler(0), values(values)
273 {
274 memset(this->targets, 0, sizeof(this->targets));
275 }
276
277 void start_shader()
278 {
279 this->shader_samplers_used = 0;
280 this->shader_shadow_samplers = 0;
281 }
282
283 void set_and_process(struct gl_shader_program *prog,
284 struct gl_shader *shader,
285 ir_variable *var)
286 {
287 ubo_var = NULL;
288 if (var->is_in_uniform_block()) {
289 struct gl_uniform_block *block =
290 &shader->UniformBlocks[var->uniform_block];
291
292 ubo_block_index = -1;
293 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
294 if (!strcmp(prog->UniformBlocks[i].Name,
295 shader->UniformBlocks[var->uniform_block].Name)) {
296 ubo_block_index = i;
297 break;
298 }
299 }
300 assert(ubo_block_index != -1);
301
302 ubo_var_index = var->location;
303 ubo_var = &block->Uniforms[var->location];
304 ubo_byte_offset = ubo_var->Offset;
305 }
306
307 process(var);
308 }
309
310 struct gl_uniform_buffer_variable *ubo_var;
311 int ubo_block_index;
312 int ubo_var_index;
313 int ubo_byte_offset;
314
315 private:
316 virtual void visit_field(const glsl_type *type, const char *name,
317 bool row_major)
318 {
319 assert(!type->is_record());
320 assert(!(type->is_array() && type->fields.array->is_record()));
321 assert(!type->is_interface());
322 assert(!(type->is_array() && type->fields.array->is_interface()));
323
324 (void) row_major;
325
326 unsigned id;
327 bool found = this->map->get(id, name);
328 assert(found);
329
330 if (!found)
331 return;
332
333 /* If there is already storage associated with this uniform, it means
334 * that it was set while processing an earlier shader stage. For
335 * example, we may be processing the uniform in the fragment shader, but
336 * the uniform was already processed in the vertex shader.
337 */
338 if (this->uniforms[id].storage != NULL) {
339 /* If the uniform already has storage set from another shader stage,
340 * mark the samplers used for this shader stage.
341 */
342 if (type->contains_sampler()) {
343 const unsigned count = MAX2(1, this->uniforms[id].array_elements);
344 const unsigned shadow = (type->is_array())
345 ? type->fields.array->sampler_shadow : type->sampler_shadow;
346
347 for (unsigned i = 0; i < count; i++) {
348 const unsigned s = this->uniforms[id].sampler + i;
349
350 this->shader_samplers_used |= 1U << s;
351 this->shader_shadow_samplers |= shadow << s;
352 }
353 }
354
355 return;
356 }
357
358 const glsl_type *base_type;
359 if (type->is_array()) {
360 this->uniforms[id].array_elements = type->length;
361 base_type = type->fields.array;
362 } else {
363 this->uniforms[id].array_elements = 0;
364 base_type = type;
365 }
366
367 if (base_type->is_sampler()) {
368 this->uniforms[id].sampler = this->next_sampler;
369
370 /* Increment the sampler by 1 for non-arrays and by the number of
371 * array elements for arrays.
372 */
373 this->next_sampler += MAX2(1, this->uniforms[id].array_elements);
374
375 const gl_texture_index target = base_type->sampler_index();
376 const unsigned shadow = base_type->sampler_shadow;
377 for (unsigned i = this->uniforms[id].sampler
378 ; i < MIN2(this->next_sampler, MAX_SAMPLERS)
379 ; i++) {
380 this->targets[i] = target;
381 this->shader_samplers_used |= 1U << i;
382 this->shader_shadow_samplers |= shadow << i;
383 }
384
385 } else {
386 this->uniforms[id].sampler = ~0;
387 }
388
389 this->uniforms[id].name = ralloc_strdup(this->uniforms, name);
390 this->uniforms[id].type = base_type;
391 this->uniforms[id].initialized = 0;
392 this->uniforms[id].num_driver_storage = 0;
393 this->uniforms[id].driver_storage = NULL;
394 this->uniforms[id].storage = this->values;
395 if (this->ubo_var) {
396 this->uniforms[id].block_index = this->ubo_block_index;
397
398 unsigned alignment = type->std140_base_alignment(ubo_var->RowMajor);
399 this->ubo_byte_offset = align(this->ubo_byte_offset, alignment);
400 this->uniforms[id].offset = this->ubo_byte_offset;
401 this->ubo_byte_offset += type->std140_size(ubo_var->RowMajor);
402
403 if (type->is_array()) {
404 this->uniforms[id].array_stride =
405 align(type->fields.array->std140_size(ubo_var->RowMajor), 16);
406 } else {
407 this->uniforms[id].array_stride = 0;
408 }
409
410 if (type->is_matrix() ||
411 (type->is_array() && type->fields.array->is_matrix())) {
412 this->uniforms[id].matrix_stride = 16;
413 this->uniforms[id].row_major = ubo_var->RowMajor;
414 } else {
415 this->uniforms[id].matrix_stride = 0;
416 this->uniforms[id].row_major = false;
417 }
418 } else {
419 this->uniforms[id].block_index = -1;
420 this->uniforms[id].offset = -1;
421 this->uniforms[id].array_stride = -1;
422 this->uniforms[id].matrix_stride = -1;
423 this->uniforms[id].row_major = false;
424 }
425
426 this->values += values_for_type(type);
427 }
428
429 struct string_to_uint_map *map;
430
431 struct gl_uniform_storage *uniforms;
432 unsigned next_sampler;
433
434 public:
435 union gl_constant_value *values;
436
437 gl_texture_index targets[MAX_SAMPLERS];
438
439 /**
440 * Mask of samplers used by the current shader stage.
441 */
442 unsigned shader_samplers_used;
443
444 /**
445 * Mask of samplers used by the current shader stage for shadows.
446 */
447 unsigned shader_shadow_samplers;
448 };
449
450 /**
451 * Merges a uniform block into an array of uniform blocks that may or
452 * may not already contain a copy of it.
453 *
454 * Returns the index of the new block in the array.
455 */
456 int
457 link_cross_validate_uniform_block(void *mem_ctx,
458 struct gl_uniform_block **linked_blocks,
459 unsigned int *num_linked_blocks,
460 struct gl_uniform_block *new_block)
461 {
462 for (unsigned int i = 0; i < *num_linked_blocks; i++) {
463 struct gl_uniform_block *old_block = &(*linked_blocks)[i];
464
465 if (strcmp(old_block->Name, new_block->Name) == 0)
466 return link_uniform_blocks_are_compatible(old_block, new_block)
467 ? i : -1;
468 }
469
470 *linked_blocks = reralloc(mem_ctx, *linked_blocks,
471 struct gl_uniform_block,
472 *num_linked_blocks + 1);
473 int linked_block_index = (*num_linked_blocks)++;
474 struct gl_uniform_block *linked_block = &(*linked_blocks)[linked_block_index];
475
476 memcpy(linked_block, new_block, sizeof(*new_block));
477 linked_block->Uniforms = ralloc_array(*linked_blocks,
478 struct gl_uniform_buffer_variable,
479 linked_block->NumUniforms);
480
481 memcpy(linked_block->Uniforms,
482 new_block->Uniforms,
483 sizeof(*linked_block->Uniforms) * linked_block->NumUniforms);
484
485 for (unsigned int i = 0; i < linked_block->NumUniforms; i++) {
486 struct gl_uniform_buffer_variable *ubo_var =
487 &linked_block->Uniforms[i];
488
489 ubo_var->Name = ralloc_strdup(*linked_blocks, ubo_var->Name);
490 }
491
492 return linked_block_index;
493 }
494
495 /**
496 * Walks the IR and update the references to uniform blocks in the
497 * ir_variables to point at linked shader's list (previously, they
498 * would point at the uniform block list in one of the pre-linked
499 * shaders).
500 */
501 static void
502 link_update_uniform_buffer_variables(struct gl_shader *shader)
503 {
504 foreach_list(node, shader->ir) {
505 ir_variable *const var = ((ir_instruction *) node)->as_variable();
506
507 if ((var == NULL) || !var->is_in_uniform_block())
508 continue;
509
510 assert(var->mode == ir_var_uniform);
511
512 bool found = false;
513 for (unsigned i = 0; i < shader->NumUniformBlocks; i++) {
514 for (unsigned j = 0; j < shader->UniformBlocks[i].NumUniforms; j++) {
515 if (!strcmp(var->name, shader->UniformBlocks[i].Uniforms[j].Name)) {
516 found = true;
517 var->uniform_block = i;
518 var->location = j;
519 break;
520 }
521 }
522 if (found)
523 break;
524 }
525 assert(found);
526 }
527 }
528
529 void
530 link_assign_uniform_block_offsets(struct gl_shader *shader)
531 {
532 for (unsigned b = 0; b < shader->NumUniformBlocks; b++) {
533 struct gl_uniform_block *block = &shader->UniformBlocks[b];
534
535 unsigned offset = 0;
536 for (unsigned int i = 0; i < block->NumUniforms; i++) {
537 struct gl_uniform_buffer_variable *ubo_var = &block->Uniforms[i];
538 const struct glsl_type *type = ubo_var->Type;
539
540 unsigned alignment = type->std140_base_alignment(ubo_var->RowMajor);
541 unsigned size = type->std140_size(ubo_var->RowMajor);
542
543 offset = align(offset, alignment);
544 ubo_var->Offset = offset;
545 offset += size;
546 }
547
548 /* From the GL_ARB_uniform_buffer_object spec:
549 *
550 * "For uniform blocks laid out according to [std140] rules,
551 * the minimum buffer object size returned by the
552 * UNIFORM_BLOCK_DATA_SIZE query is derived by taking the
553 * offset of the last basic machine unit consumed by the
554 * last uniform of the uniform block (including any
555 * end-of-array or end-of-structure padding), adding one,
556 * and rounding up to the next multiple of the base
557 * alignment required for a vec4."
558 */
559 block->UniformBufferSize = align(offset, 16);
560 }
561 }
562
563 void
564 link_assign_uniform_locations(struct gl_shader_program *prog)
565 {
566 ralloc_free(prog->UniformStorage);
567 prog->UniformStorage = NULL;
568 prog->NumUserUniformStorage = 0;
569
570 if (prog->UniformHash != NULL) {
571 prog->UniformHash->clear();
572 } else {
573 prog->UniformHash = new string_to_uint_map;
574 }
575
576 /* Uniforms that lack an initializer in the shader code have an initial
577 * value of zero. This includes sampler uniforms.
578 *
579 * Page 24 (page 30 of the PDF) of the GLSL 1.20 spec says:
580 *
581 * "The link time initial value is either the value of the variable's
582 * initializer, if present, or 0 if no initializer is present. Sampler
583 * types cannot have initializers."
584 */
585 memset(prog->SamplerUnits, 0, sizeof(prog->SamplerUnits));
586
587 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
588 if (prog->_LinkedShaders[i] == NULL)
589 continue;
590
591 link_update_uniform_buffer_variables(prog->_LinkedShaders[i]);
592 }
593
594 /* First pass: Count the uniform resources used by the user-defined
595 * uniforms. While this happens, each active uniform will have an index
596 * assigned to it.
597 *
598 * Note: this is *NOT* the index that is returned to the application by
599 * glGetUniformLocation.
600 */
601 count_uniform_size uniform_size(prog->UniformHash);
602 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
603 if (prog->_LinkedShaders[i] == NULL)
604 continue;
605
606 /* Reset various per-shader target counts.
607 */
608 uniform_size.start_shader();
609
610 foreach_list(node, prog->_LinkedShaders[i]->ir) {
611 ir_variable *const var = ((ir_instruction *) node)->as_variable();
612
613 if ((var == NULL) || (var->mode != ir_var_uniform))
614 continue;
615
616 /* FINISHME: Update code to process built-in uniforms!
617 */
618 if (strncmp("gl_", var->name, 3) == 0) {
619 uniform_size.num_shader_uniform_components +=
620 var->type->component_slots();
621 continue;
622 }
623
624 uniform_size.process(var);
625 }
626
627 prog->_LinkedShaders[i]->num_samplers = uniform_size.num_shader_samplers;
628 prog->_LinkedShaders[i]->num_uniform_components =
629 uniform_size.num_shader_uniform_components;
630 }
631
632 const unsigned num_user_uniforms = uniform_size.num_active_uniforms;
633 const unsigned num_data_slots = uniform_size.num_values;
634
635 /* On the outside chance that there were no uniforms, bail out.
636 */
637 if (num_user_uniforms == 0)
638 return;
639
640 struct gl_uniform_storage *uniforms =
641 rzalloc_array(prog, struct gl_uniform_storage, num_user_uniforms);
642 union gl_constant_value *data =
643 rzalloc_array(uniforms, union gl_constant_value, num_data_slots);
644 #ifndef NDEBUG
645 union gl_constant_value *data_end = &data[num_data_slots];
646 #endif
647
648 parcel_out_uniform_storage parcel(prog->UniformHash, uniforms, data);
649
650 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
651 if (prog->_LinkedShaders[i] == NULL)
652 continue;
653
654 /* Reset various per-shader target counts.
655 */
656 parcel.start_shader();
657
658 foreach_list(node, prog->_LinkedShaders[i]->ir) {
659 ir_variable *const var = ((ir_instruction *) node)->as_variable();
660
661 if ((var == NULL) || (var->mode != ir_var_uniform))
662 continue;
663
664 /* FINISHME: Update code to process built-in uniforms!
665 */
666 if (strncmp("gl_", var->name, 3) == 0)
667 continue;
668
669 parcel.set_and_process(prog, prog->_LinkedShaders[i], var);
670 }
671
672 prog->_LinkedShaders[i]->active_samplers = parcel.shader_samplers_used;
673 prog->_LinkedShaders[i]->shadow_samplers = parcel.shader_shadow_samplers;
674 }
675
676 assert(sizeof(prog->SamplerTargets) == sizeof(parcel.targets));
677 memcpy(prog->SamplerTargets, parcel.targets, sizeof(prog->SamplerTargets));
678
679 #ifndef NDEBUG
680 for (unsigned i = 0; i < num_user_uniforms; i++) {
681 assert(uniforms[i].storage != NULL);
682 }
683
684 assert(parcel.values == data_end);
685 #endif
686
687 prog->NumUserUniformStorage = num_user_uniforms;
688 prog->UniformStorage = uniforms;
689
690 link_set_uniform_initializers(prog);
691
692 return;
693 }