c65beb227562137be5a868cd883ecd07af00ecf3
[mesa.git] / src / compiler / nir / nir_opt_copy_prop_vars.c
1 /*
2 * Copyright © 2016 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_builder.h"
26 #include "nir_deref.h"
27
28 #include "util/bitscan.h"
29 #include "util/u_dynarray.h"
30
31 static const bool debug = false;
32
33 /**
34 * Variable-based copy propagation
35 *
36 * Normally, NIR trusts in SSA form for most of its copy-propagation needs.
37 * However, there are cases, especially when dealing with indirects, where SSA
38 * won't help you. This pass is for those times. Specifically, it handles
39 * the following things that the rest of NIR can't:
40 *
41 * 1) Copy-propagation on variables that have indirect access. This includes
42 * propagating from indirect stores into indirect loads.
43 *
44 * 2) Removal of redundant load_deref intrinsics. We can't trust regular CSE
45 * to do this because it isn't aware of variable writes that may alias the
46 * value and make the former load invalid.
47 *
48 * This pass uses an intermediate solution between being local / "per-block"
49 * and a complete data-flow analysis. It follows the control flow graph, and
50 * propagate the available copy information forward, invalidating data at each
51 * cf_node.
52 *
53 * Removal of dead writes to variables is handled by another pass.
54 */
55
56 struct vars_written {
57 nir_variable_mode modes;
58
59 /* Key is deref and value is the uintptr_t with the write mask. */
60 struct hash_table *derefs;
61 };
62
63 struct value {
64 bool is_ssa;
65 union {
66 struct {
67 nir_ssa_def *def[NIR_MAX_VEC_COMPONENTS];
68 uint8_t component[NIR_MAX_VEC_COMPONENTS];
69 } ssa;
70 nir_deref_instr *deref;
71 };
72 };
73
74 static void
75 value_set_ssa_components(struct value *value, nir_ssa_def *def,
76 unsigned num_components)
77 {
78 if (!value->is_ssa)
79 memset(&value->ssa, 0, sizeof(value->ssa));
80 value->is_ssa = true;
81 for (unsigned i = 0; i < num_components; i++) {
82 value->ssa.def[i] = def;
83 value->ssa.component[i] = i;
84 }
85 }
86
87 struct copy_entry {
88 struct value src;
89
90 nir_deref_instr *dst;
91 };
92
93 struct copy_prop_var_state {
94 nir_function_impl *impl;
95
96 void *mem_ctx;
97 void *lin_ctx;
98
99 /* Maps nodes to vars_written. Used to invalidate copy entries when
100 * visiting each node.
101 */
102 struct hash_table *vars_written_map;
103
104 bool progress;
105 };
106
107 static bool
108 value_equals_store_src(struct value *value, nir_intrinsic_instr *intrin)
109 {
110 assert(intrin->intrinsic == nir_intrinsic_store_deref);
111 uintptr_t write_mask = nir_intrinsic_write_mask(intrin);
112
113 for (unsigned i = 0; i < intrin->num_components; i++) {
114 if ((write_mask & (1 << i)) &&
115 (value->ssa.def[i] != intrin->src[1].ssa ||
116 value->ssa.component[i] != i))
117 return false;
118 }
119
120 return true;
121 }
122
123 static struct vars_written *
124 create_vars_written(struct copy_prop_var_state *state)
125 {
126 struct vars_written *written =
127 linear_zalloc_child(state->lin_ctx, sizeof(struct vars_written));
128 written->derefs = _mesa_pointer_hash_table_create(state->mem_ctx);
129 return written;
130 }
131
132 static void
133 gather_vars_written(struct copy_prop_var_state *state,
134 struct vars_written *written,
135 nir_cf_node *cf_node)
136 {
137 struct vars_written *new_written = NULL;
138
139 switch (cf_node->type) {
140 case nir_cf_node_function: {
141 nir_function_impl *impl = nir_cf_node_as_function(cf_node);
142 foreach_list_typed_safe(nir_cf_node, cf_node, node, &impl->body)
143 gather_vars_written(state, NULL, cf_node);
144 break;
145 }
146
147 case nir_cf_node_block: {
148 if (!written)
149 break;
150
151 nir_block *block = nir_cf_node_as_block(cf_node);
152 nir_foreach_instr(instr, block) {
153 if (instr->type == nir_instr_type_call) {
154 written->modes |= nir_var_shader_out |
155 nir_var_shader_temp |
156 nir_var_function_temp |
157 nir_var_mem_ssbo |
158 nir_var_mem_shared;
159 continue;
160 }
161
162 if (instr->type != nir_instr_type_intrinsic)
163 continue;
164
165 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
166 switch (intrin->intrinsic) {
167 case nir_intrinsic_barrier:
168 case nir_intrinsic_memory_barrier:
169 written->modes |= nir_var_shader_out |
170 nir_var_mem_ssbo |
171 nir_var_mem_shared;
172 break;
173
174 case nir_intrinsic_emit_vertex:
175 case nir_intrinsic_emit_vertex_with_counter:
176 written->modes = nir_var_shader_out;
177 break;
178
179 case nir_intrinsic_deref_atomic_add:
180 case nir_intrinsic_deref_atomic_imin:
181 case nir_intrinsic_deref_atomic_umin:
182 case nir_intrinsic_deref_atomic_imax:
183 case nir_intrinsic_deref_atomic_umax:
184 case nir_intrinsic_deref_atomic_and:
185 case nir_intrinsic_deref_atomic_or:
186 case nir_intrinsic_deref_atomic_xor:
187 case nir_intrinsic_deref_atomic_exchange:
188 case nir_intrinsic_deref_atomic_comp_swap:
189 case nir_intrinsic_store_deref:
190 case nir_intrinsic_copy_deref: {
191 /* Destination in all of store_deref, copy_deref and the atomics is src[0]. */
192 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
193
194 uintptr_t mask = intrin->intrinsic == nir_intrinsic_store_deref ?
195 nir_intrinsic_write_mask(intrin) : (1 << glsl_get_vector_elements(dst->type)) - 1;
196
197 struct hash_entry *ht_entry = _mesa_hash_table_search(written->derefs, dst);
198 if (ht_entry)
199 ht_entry->data = (void *)(mask | (uintptr_t)ht_entry->data);
200 else
201 _mesa_hash_table_insert(written->derefs, dst, (void *)mask);
202
203 break;
204 }
205
206 default:
207 break;
208 }
209 }
210
211 break;
212 }
213
214 case nir_cf_node_if: {
215 nir_if *if_stmt = nir_cf_node_as_if(cf_node);
216
217 new_written = create_vars_written(state);
218
219 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->then_list)
220 gather_vars_written(state, new_written, cf_node);
221
222 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->else_list)
223 gather_vars_written(state, new_written, cf_node);
224
225 break;
226 }
227
228 case nir_cf_node_loop: {
229 nir_loop *loop = nir_cf_node_as_loop(cf_node);
230
231 new_written = create_vars_written(state);
232
233 foreach_list_typed_safe(nir_cf_node, cf_node, node, &loop->body)
234 gather_vars_written(state, new_written, cf_node);
235
236 break;
237 }
238
239 default:
240 unreachable("Invalid CF node type");
241 }
242
243 if (new_written) {
244 /* Merge new information to the parent control flow node. */
245 if (written) {
246 written->modes |= new_written->modes;
247 hash_table_foreach(new_written->derefs, new_entry) {
248 struct hash_entry *old_entry =
249 _mesa_hash_table_search_pre_hashed(written->derefs, new_entry->hash,
250 new_entry->key);
251 if (old_entry) {
252 nir_component_mask_t merged = (uintptr_t) new_entry->data |
253 (uintptr_t) old_entry->data;
254 old_entry->data = (void *) ((uintptr_t) merged);
255 } else {
256 _mesa_hash_table_insert_pre_hashed(written->derefs, new_entry->hash,
257 new_entry->key, new_entry->data);
258 }
259 }
260 }
261 _mesa_hash_table_insert(state->vars_written_map, cf_node, new_written);
262 }
263 }
264
265 static struct copy_entry *
266 copy_entry_create(struct util_dynarray *copies,
267 nir_deref_instr *dst_deref)
268 {
269 struct copy_entry new_entry = {
270 .dst = dst_deref,
271 };
272 util_dynarray_append(copies, struct copy_entry, new_entry);
273 return util_dynarray_top_ptr(copies, struct copy_entry);
274 }
275
276 /* Remove copy entry by swapping it with the last element and reducing the
277 * size. If used inside an iteration on copies, it must be a reverse
278 * (backwards) iteration. It is safe to use in those cases because the swap
279 * will not affect the rest of the iteration.
280 */
281 static void
282 copy_entry_remove(struct util_dynarray *copies,
283 struct copy_entry *entry)
284 {
285 /* This also works when removing the last element since pop don't shrink
286 * the memory used by the array, so the swap is useless but not invalid.
287 */
288 *entry = util_dynarray_pop(copies, struct copy_entry);
289 }
290
291 static bool
292 is_array_deref_of_vector(nir_deref_instr *deref)
293 {
294 if (deref->deref_type != nir_deref_type_array)
295 return false;
296 nir_deref_instr *parent = nir_deref_instr_parent(deref);
297 return glsl_type_is_vector(parent->type);
298 }
299
300 static struct copy_entry *
301 lookup_entry_for_deref(struct util_dynarray *copies,
302 nir_deref_instr *deref,
303 nir_deref_compare_result allowed_comparisons)
304 {
305 struct copy_entry *entry = NULL;
306 util_dynarray_foreach(copies, struct copy_entry, iter) {
307 nir_deref_compare_result result = nir_compare_derefs(iter->dst, deref);
308 if (result & allowed_comparisons) {
309 entry = iter;
310 if (result & nir_derefs_equal_bit)
311 break;
312 /* Keep looking in case we have an equal match later in the array. */
313 }
314 }
315 return entry;
316 }
317
318 static struct copy_entry *
319 lookup_entry_and_kill_aliases(struct util_dynarray *copies,
320 nir_deref_instr *deref,
321 unsigned write_mask)
322 {
323 /* TODO: Take into account the write_mask. */
324
325 nir_deref_instr *dst_match = NULL;
326 util_dynarray_foreach_reverse(copies, struct copy_entry, iter) {
327 if (!iter->src.is_ssa) {
328 /* If this write aliases the source of some entry, get rid of it */
329 if (nir_compare_derefs(iter->src.deref, deref) & nir_derefs_may_alias_bit) {
330 copy_entry_remove(copies, iter);
331 continue;
332 }
333 }
334
335 nir_deref_compare_result comp = nir_compare_derefs(iter->dst, deref);
336
337 if (comp & nir_derefs_equal_bit) {
338 /* Removing entries invalidate previous iter pointers, so we'll
339 * collect the matching entry later. Just make sure it is unique.
340 */
341 assert(!dst_match);
342 dst_match = iter->dst;
343 } else if (comp & nir_derefs_may_alias_bit) {
344 copy_entry_remove(copies, iter);
345 }
346 }
347
348 struct copy_entry *entry = NULL;
349 if (dst_match) {
350 util_dynarray_foreach(copies, struct copy_entry, iter) {
351 if (iter->dst == dst_match) {
352 entry = iter;
353 break;
354 }
355 }
356 assert(entry);
357 }
358 return entry;
359 }
360
361 static void
362 kill_aliases(struct util_dynarray *copies,
363 nir_deref_instr *deref,
364 unsigned write_mask)
365 {
366 /* TODO: Take into account the write_mask. */
367
368 struct copy_entry *entry =
369 lookup_entry_and_kill_aliases(copies, deref, write_mask);
370 if (entry)
371 copy_entry_remove(copies, entry);
372 }
373
374 static struct copy_entry *
375 get_entry_and_kill_aliases(struct util_dynarray *copies,
376 nir_deref_instr *deref,
377 unsigned write_mask)
378 {
379 /* TODO: Take into account the write_mask. */
380
381 struct copy_entry *entry =
382 lookup_entry_and_kill_aliases(copies, deref, write_mask);
383
384 if (entry == NULL)
385 entry = copy_entry_create(copies, deref);
386
387 return entry;
388 }
389
390 static void
391 apply_barrier_for_modes(struct util_dynarray *copies,
392 nir_variable_mode modes)
393 {
394 util_dynarray_foreach_reverse(copies, struct copy_entry, iter) {
395 if ((iter->dst->mode & modes) ||
396 (!iter->src.is_ssa && (iter->src.deref->mode & modes)))
397 copy_entry_remove(copies, iter);
398 }
399 }
400
401 static void
402 value_set_from_value(struct value *value, const struct value *from,
403 unsigned base_index, unsigned write_mask)
404 {
405 /* We can't have non-zero indexes with non-trivial write masks */
406 assert(base_index == 0 || write_mask == 1);
407
408 if (from->is_ssa) {
409 /* Clear value if it was being used as non-SSA. */
410 if (!value->is_ssa)
411 memset(&value->ssa, 0, sizeof(value->ssa));
412 value->is_ssa = true;
413 /* Only overwrite the written components */
414 for (unsigned i = 0; i < NIR_MAX_VEC_COMPONENTS; i++) {
415 if (write_mask & (1 << i)) {
416 value->ssa.def[base_index + i] = from->ssa.def[i];
417 value->ssa.component[base_index + i] = from->ssa.component[i];
418 }
419 }
420 } else {
421 /* Non-ssa stores always write everything */
422 value->is_ssa = false;
423 value->deref = from->deref;
424 }
425 }
426
427 /* Try to load a single element of a vector from the copy_entry. If the data
428 * isn't available, just let the original intrinsic do the work.
429 */
430 static bool
431 load_element_from_ssa_entry_value(struct copy_prop_var_state *state,
432 struct copy_entry *entry,
433 nir_builder *b, nir_intrinsic_instr *intrin,
434 struct value *value, unsigned index)
435 {
436 assert(index < glsl_get_vector_elements(entry->dst->type));
437
438 /* We don't have the element available, so let the instruction do the work. */
439 if (!entry->src.ssa.def[index])
440 return false;
441
442 b->cursor = nir_instr_remove(&intrin->instr);
443 intrin->instr.block = NULL;
444
445 assert(entry->src.ssa.component[index] <
446 entry->src.ssa.def[index]->num_components);
447 nir_ssa_def *def = nir_channel(b, entry->src.ssa.def[index],
448 entry->src.ssa.component[index]);
449
450 *value = (struct value) {
451 .is_ssa = true,
452 {
453 .ssa = {
454 .def = { def },
455 .component = { 0 },
456 },
457 }
458 };
459
460 return true;
461 }
462
463 /* Do a "load" from an SSA-based entry return it in "value" as a value with a
464 * single SSA def. Because an entry could reference multiple different SSA
465 * defs, a vecN operation may be inserted to combine them into a single SSA
466 * def before handing it back to the caller. If the load instruction is no
467 * longer needed, it is removed and nir_instr::block is set to NULL. (It is
468 * possible, in some cases, for the load to be used in the vecN operation in
469 * which case it isn't deleted.)
470 */
471 static bool
472 load_from_ssa_entry_value(struct copy_prop_var_state *state,
473 struct copy_entry *entry,
474 nir_builder *b, nir_intrinsic_instr *intrin,
475 nir_deref_instr *src, struct value *value)
476 {
477 if (is_array_deref_of_vector(src)) {
478 if (nir_src_is_const(src->arr.index)) {
479 return load_element_from_ssa_entry_value(state, entry, b, intrin, value,
480 nir_src_as_uint(src->arr.index));
481 }
482
483 /* An SSA copy_entry for the vector won't help indirect load. */
484 if (glsl_type_is_vector(entry->dst->type)) {
485 assert(entry->dst->type == nir_deref_instr_parent(src)->type);
486 /* TODO: If all SSA entries are there, try an if-ladder. */
487 return false;
488 }
489 }
490
491 *value = entry->src;
492 assert(value->is_ssa);
493
494 const struct glsl_type *type = entry->dst->type;
495 unsigned num_components = glsl_get_vector_elements(type);
496
497 nir_component_mask_t available = 0;
498 bool all_same = true;
499 for (unsigned i = 0; i < num_components; i++) {
500 if (value->ssa.def[i])
501 available |= (1 << i);
502
503 if (value->ssa.def[i] != value->ssa.def[0])
504 all_same = false;
505
506 if (value->ssa.component[i] != i)
507 all_same = false;
508 }
509
510 if (all_same) {
511 /* Our work here is done */
512 b->cursor = nir_instr_remove(&intrin->instr);
513 intrin->instr.block = NULL;
514 return true;
515 }
516
517 if (available != (1 << num_components) - 1 &&
518 intrin->intrinsic == nir_intrinsic_load_deref &&
519 (available & nir_ssa_def_components_read(&intrin->dest.ssa)) == 0) {
520 /* If none of the components read are available as SSA values, then we
521 * should just bail. Otherwise, we would end up replacing the uses of
522 * the load_deref a vecN() that just gathers up its components.
523 */
524 return false;
525 }
526
527 b->cursor = nir_after_instr(&intrin->instr);
528
529 nir_ssa_def *load_def =
530 intrin->intrinsic == nir_intrinsic_load_deref ? &intrin->dest.ssa : NULL;
531
532 bool keep_intrin = false;
533 nir_ssa_def *comps[NIR_MAX_VEC_COMPONENTS];
534 for (unsigned i = 0; i < num_components; i++) {
535 if (value->ssa.def[i]) {
536 comps[i] = nir_channel(b, value->ssa.def[i], value->ssa.component[i]);
537 } else {
538 /* We don't have anything for this component in our
539 * list. Just re-use a channel from the load.
540 */
541 if (load_def == NULL)
542 load_def = nir_load_deref(b, entry->dst);
543
544 if (load_def->parent_instr == &intrin->instr)
545 keep_intrin = true;
546
547 comps[i] = nir_channel(b, load_def, i);
548 }
549 }
550
551 nir_ssa_def *vec = nir_vec(b, comps, num_components);
552 value_set_ssa_components(value, vec, num_components);
553
554 if (!keep_intrin) {
555 /* Removing this instruction should not touch the cursor because we
556 * created the cursor after the intrinsic and have added at least one
557 * instruction (the vec) since then.
558 */
559 assert(b->cursor.instr != &intrin->instr);
560 nir_instr_remove(&intrin->instr);
561 intrin->instr.block = NULL;
562 }
563
564 return true;
565 }
566
567 /**
568 * Specialize the wildcards in a deref chain
569 *
570 * This function returns a deref chain identical to \param deref except that
571 * some of its wildcards are replaced with indices from \param specific. The
572 * process is guided by \param guide which references the same type as \param
573 * specific but has the same wildcard array lengths as \param deref.
574 */
575 static nir_deref_instr *
576 specialize_wildcards(nir_builder *b,
577 nir_deref_path *deref,
578 nir_deref_path *guide,
579 nir_deref_path *specific)
580 {
581 nir_deref_instr **deref_p = &deref->path[1];
582 nir_deref_instr **guide_p = &guide->path[1];
583 nir_deref_instr **spec_p = &specific->path[1];
584 nir_deref_instr *ret_tail = deref->path[0];
585 for (; *deref_p; deref_p++) {
586 if ((*deref_p)->deref_type == nir_deref_type_array_wildcard) {
587 /* This is where things get tricky. We have to search through
588 * the entry deref to find its corresponding wildcard and fill
589 * this slot in with the value from the src.
590 */
591 while (*guide_p &&
592 (*guide_p)->deref_type != nir_deref_type_array_wildcard) {
593 guide_p++;
594 spec_p++;
595 }
596 assert(*guide_p && *spec_p);
597
598 ret_tail = nir_build_deref_follower(b, ret_tail, *spec_p);
599
600 guide_p++;
601 spec_p++;
602 } else {
603 ret_tail = nir_build_deref_follower(b, ret_tail, *deref_p);
604 }
605 }
606
607 return ret_tail;
608 }
609
610 /* Do a "load" from an deref-based entry return it in "value" as a value. The
611 * deref returned in "value" will always be a fresh copy so the caller can
612 * steal it and assign it to the instruction directly without copying it
613 * again.
614 */
615 static bool
616 load_from_deref_entry_value(struct copy_prop_var_state *state,
617 struct copy_entry *entry,
618 nir_builder *b, nir_intrinsic_instr *intrin,
619 nir_deref_instr *src, struct value *value)
620 {
621 *value = entry->src;
622
623 b->cursor = nir_instr_remove(&intrin->instr);
624
625 nir_deref_path entry_dst_path, src_path;
626 nir_deref_path_init(&entry_dst_path, entry->dst, state->mem_ctx);
627 nir_deref_path_init(&src_path, src, state->mem_ctx);
628
629 bool need_to_specialize_wildcards = false;
630 nir_deref_instr **entry_p = &entry_dst_path.path[1];
631 nir_deref_instr **src_p = &src_path.path[1];
632 while (*entry_p && *src_p) {
633 nir_deref_instr *entry_tail = *entry_p++;
634 nir_deref_instr *src_tail = *src_p++;
635
636 if (src_tail->deref_type == nir_deref_type_array &&
637 entry_tail->deref_type == nir_deref_type_array_wildcard)
638 need_to_specialize_wildcards = true;
639 }
640
641 /* If the entry deref is longer than the source deref then it refers to a
642 * smaller type and we can't source from it.
643 */
644 assert(*entry_p == NULL);
645
646 if (need_to_specialize_wildcards) {
647 /* The entry has some wildcards that are not in src. This means we need
648 * to construct a new deref based on the entry but using the wildcards
649 * from the source and guided by the entry dst. Oof.
650 */
651 nir_deref_path entry_src_path;
652 nir_deref_path_init(&entry_src_path, entry->src.deref, state->mem_ctx);
653 value->deref = specialize_wildcards(b, &entry_src_path,
654 &entry_dst_path, &src_path);
655 nir_deref_path_finish(&entry_src_path);
656 }
657
658 /* If our source deref is longer than the entry deref, that's ok because
659 * it just means the entry deref needs to be extended a bit.
660 */
661 while (*src_p) {
662 nir_deref_instr *src_tail = *src_p++;
663 value->deref = nir_build_deref_follower(b, value->deref, src_tail);
664 }
665
666 nir_deref_path_finish(&entry_dst_path);
667 nir_deref_path_finish(&src_path);
668
669 return true;
670 }
671
672 static bool
673 try_load_from_entry(struct copy_prop_var_state *state, struct copy_entry *entry,
674 nir_builder *b, nir_intrinsic_instr *intrin,
675 nir_deref_instr *src, struct value *value)
676 {
677 if (entry == NULL)
678 return false;
679
680 if (entry->src.is_ssa) {
681 return load_from_ssa_entry_value(state, entry, b, intrin, src, value);
682 } else {
683 return load_from_deref_entry_value(state, entry, b, intrin, src, value);
684 }
685 }
686
687 static void
688 invalidate_copies_for_cf_node(struct copy_prop_var_state *state,
689 struct util_dynarray *copies,
690 nir_cf_node *cf_node)
691 {
692 struct hash_entry *ht_entry = _mesa_hash_table_search(state->vars_written_map, cf_node);
693 assert(ht_entry);
694
695 struct vars_written *written = ht_entry->data;
696 if (written->modes) {
697 util_dynarray_foreach_reverse(copies, struct copy_entry, entry) {
698 if (entry->dst->mode & written->modes)
699 copy_entry_remove(copies, entry);
700 }
701 }
702
703 hash_table_foreach (written->derefs, entry) {
704 nir_deref_instr *deref_written = (nir_deref_instr *)entry->key;
705 kill_aliases(copies, deref_written, (uintptr_t)entry->data);
706 }
707 }
708
709 static void
710 print_value(struct value *value, unsigned num_components)
711 {
712 if (!value->is_ssa) {
713 printf(" %s ", glsl_get_type_name(value->deref->type));
714 nir_print_deref(value->deref, stdout);
715 return;
716 }
717
718 bool same_ssa = true;
719 for (unsigned i = 0; i < num_components; i++) {
720 if (value->ssa.component[i] != i ||
721 (i > 0 && value->ssa.def[i - 1] != value->ssa.def[i])) {
722 same_ssa = false;
723 break;
724 }
725 }
726 if (same_ssa) {
727 printf(" ssa_%d", value->ssa.def[0]->index);
728 } else {
729 for (int i = 0; i < num_components; i++) {
730 if (value->ssa.def[i])
731 printf(" ssa_%d[%u]", value->ssa.def[i]->index, value->ssa.component[i]);
732 else
733 printf(" _");
734 }
735 }
736 }
737
738 static void
739 print_copy_entry(struct copy_entry *entry)
740 {
741 printf(" %s ", glsl_get_type_name(entry->dst->type));
742 nir_print_deref(entry->dst, stdout);
743 printf(":\t");
744
745 unsigned num_components = glsl_get_vector_elements(entry->dst->type);
746 print_value(&entry->src, num_components);
747 printf("\n");
748 }
749
750 static void
751 dump_instr(nir_instr *instr)
752 {
753 printf(" ");
754 nir_print_instr(instr, stdout);
755 printf("\n");
756 }
757
758 static void
759 dump_copy_entries(struct util_dynarray *copies)
760 {
761 util_dynarray_foreach(copies, struct copy_entry, iter)
762 print_copy_entry(iter);
763 printf("\n");
764 }
765
766 static void
767 copy_prop_vars_block(struct copy_prop_var_state *state,
768 nir_builder *b, nir_block *block,
769 struct util_dynarray *copies)
770 {
771 if (debug) {
772 printf("# block%d\n", block->index);
773 dump_copy_entries(copies);
774 }
775
776 nir_foreach_instr_safe(instr, block) {
777 if (debug && instr->type == nir_instr_type_deref)
778 dump_instr(instr);
779
780 if (instr->type == nir_instr_type_call) {
781 if (debug) dump_instr(instr);
782 apply_barrier_for_modes(copies, nir_var_shader_out |
783 nir_var_shader_temp |
784 nir_var_function_temp |
785 nir_var_mem_ssbo |
786 nir_var_mem_shared);
787 if (debug) dump_copy_entries(copies);
788 continue;
789 }
790
791 if (instr->type != nir_instr_type_intrinsic)
792 continue;
793
794 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
795 switch (intrin->intrinsic) {
796 case nir_intrinsic_barrier:
797 case nir_intrinsic_memory_barrier:
798 if (debug) dump_instr(instr);
799
800 apply_barrier_for_modes(copies, nir_var_shader_out |
801 nir_var_mem_ssbo |
802 nir_var_mem_shared);
803 break;
804
805 case nir_intrinsic_emit_vertex:
806 case nir_intrinsic_emit_vertex_with_counter:
807 if (debug) dump_instr(instr);
808
809 apply_barrier_for_modes(copies, nir_var_shader_out);
810 break;
811
812 case nir_intrinsic_load_deref: {
813 if (debug) dump_instr(instr);
814
815 if (nir_intrinsic_access(intrin) & ACCESS_VOLATILE)
816 break;
817
818 nir_deref_instr *src = nir_src_as_deref(intrin->src[0]);
819
820 /* Direct array_derefs of vectors operate on the vectors (the parent
821 * deref). Indirects will be handled like other derefs.
822 */
823 int vec_index = 0;
824 nir_deref_instr *vec_src = src;
825 if (is_array_deref_of_vector(src) && nir_src_is_const(src->arr.index)) {
826 vec_src = nir_deref_instr_parent(src);
827 unsigned vec_comps = glsl_get_vector_elements(vec_src->type);
828 vec_index = nir_src_as_uint(src->arr.index);
829
830 /* Loading from an invalid index yields an undef */
831 if (vec_index >= vec_comps) {
832 b->cursor = nir_instr_remove(instr);
833 nir_ssa_def *u = nir_ssa_undef(b, 1, intrin->dest.ssa.bit_size);
834 nir_ssa_def_rewrite_uses(&intrin->dest.ssa, nir_src_for_ssa(u));
835 break;
836 }
837 }
838
839 struct copy_entry *src_entry =
840 lookup_entry_for_deref(copies, src, nir_derefs_a_contains_b_bit);
841 struct value value = {0};
842 if (try_load_from_entry(state, src_entry, b, intrin, src, &value)) {
843 if (value.is_ssa) {
844 /* lookup_load has already ensured that we get a single SSA
845 * value that has all of the channels. We just have to do the
846 * rewrite operation. Note for array derefs of vectors, the
847 * channel 0 is used.
848 */
849 if (intrin->instr.block) {
850 /* The lookup left our instruction in-place. This means it
851 * must have used it to vec up a bunch of different sources.
852 * We need to be careful when rewriting uses so we don't
853 * rewrite the vecN itself.
854 */
855 nir_ssa_def_rewrite_uses_after(&intrin->dest.ssa,
856 nir_src_for_ssa(value.ssa.def[0]),
857 value.ssa.def[0]->parent_instr);
858 } else {
859 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
860 nir_src_for_ssa(value.ssa.def[0]));
861 }
862 } else {
863 /* We're turning it into a load of a different variable */
864 intrin->src[0] = nir_src_for_ssa(&value.deref->dest.ssa);
865
866 /* Put it back in again. */
867 nir_builder_instr_insert(b, instr);
868 value_set_ssa_components(&value, &intrin->dest.ssa,
869 intrin->num_components);
870 }
871 state->progress = true;
872 } else {
873 value_set_ssa_components(&value, &intrin->dest.ssa,
874 intrin->num_components);
875 }
876
877 /* Now that we have a value, we're going to store it back so that we
878 * have the right value next time we come looking for it. In order
879 * to do this, we need an exact match, not just something that
880 * contains what we're looking for.
881 */
882 struct copy_entry *entry =
883 lookup_entry_for_deref(copies, vec_src, nir_derefs_equal_bit);
884 if (!entry)
885 entry = copy_entry_create(copies, vec_src);
886
887 /* Update the entry with the value of the load. This way
888 * we can potentially remove subsequent loads.
889 */
890 value_set_from_value(&entry->src, &value, vec_index,
891 (1 << intrin->num_components) - 1);
892 break;
893 }
894
895 case nir_intrinsic_store_deref: {
896 if (debug) dump_instr(instr);
897
898 if (nir_intrinsic_access(intrin) & ACCESS_VOLATILE)
899 break;
900
901 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
902 assert(glsl_type_is_vector_or_scalar(dst->type));
903
904 /* Direct array_derefs of vectors operate on the vectors (the parent
905 * deref). Indirects will be handled like other derefs.
906 */
907 int vec_index = 0;
908 nir_deref_instr *vec_dst = dst;
909 if (is_array_deref_of_vector(dst) && nir_src_is_const(dst->arr.index)) {
910 vec_dst = nir_deref_instr_parent(dst);
911 unsigned vec_comps = glsl_get_vector_elements(vec_dst->type);
912
913 vec_index = nir_src_as_uint(dst->arr.index);
914
915 /* Storing to an invalid index is a no-op. */
916 if (vec_index >= vec_comps) {
917 nir_instr_remove(instr);
918 break;
919 }
920 }
921
922 struct copy_entry *entry =
923 lookup_entry_for_deref(copies, dst, nir_derefs_equal_bit);
924 if (entry && value_equals_store_src(&entry->src, intrin)) {
925 /* If we are storing the value from a load of the same var the
926 * store is redundant so remove it.
927 */
928 nir_instr_remove(instr);
929 } else {
930 struct value value = {0};
931 value_set_ssa_components(&value, intrin->src[1].ssa,
932 intrin->num_components);
933 unsigned wrmask = nir_intrinsic_write_mask(intrin);
934 struct copy_entry *entry =
935 get_entry_and_kill_aliases(copies, vec_dst, wrmask);
936 value_set_from_value(&entry->src, &value, vec_index, wrmask);
937 }
938
939 break;
940 }
941
942 case nir_intrinsic_copy_deref: {
943 if (debug) dump_instr(instr);
944
945 if ((nir_intrinsic_src_access(intrin) & ACCESS_VOLATILE) ||
946 (nir_intrinsic_dst_access(intrin) & ACCESS_VOLATILE))
947 break;
948
949 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
950 nir_deref_instr *src = nir_src_as_deref(intrin->src[1]);
951
952 if (nir_compare_derefs(src, dst) & nir_derefs_equal_bit) {
953 /* This is a no-op self-copy. Get rid of it */
954 nir_instr_remove(instr);
955 continue;
956 }
957
958 /* The copy_deref intrinsic doesn't keep track of num_components, so
959 * get it ourselves.
960 */
961 unsigned num_components = glsl_get_vector_elements(dst->type);
962 unsigned full_mask = (1 << num_components) - 1;
963
964 /* Copy of direct array derefs of vectors are not handled. Just
965 * invalidate what's written and bail.
966 */
967 if ((is_array_deref_of_vector(src) && nir_src_is_const(src->arr.index)) ||
968 (is_array_deref_of_vector(dst) && nir_src_is_const(dst->arr.index))) {
969 kill_aliases(copies, dst, full_mask);
970 break;
971 }
972
973 struct copy_entry *src_entry =
974 lookup_entry_for_deref(copies, src, nir_derefs_a_contains_b_bit);
975 struct value value;
976 if (try_load_from_entry(state, src_entry, b, intrin, src, &value)) {
977 /* If load works, intrin (the copy_deref) is removed. */
978 if (value.is_ssa) {
979 nir_store_deref(b, dst, value.ssa.def[0], full_mask);
980 } else {
981 /* If this would be a no-op self-copy, don't bother. */
982 if (nir_compare_derefs(value.deref, dst) & nir_derefs_equal_bit)
983 continue;
984
985 /* Just turn it into a copy of a different deref */
986 intrin->src[1] = nir_src_for_ssa(&value.deref->dest.ssa);
987
988 /* Put it back in again. */
989 nir_builder_instr_insert(b, instr);
990 }
991
992 state->progress = true;
993 } else {
994 value = (struct value) {
995 .is_ssa = false,
996 { .deref = src },
997 };
998 }
999
1000 nir_variable *src_var = nir_deref_instr_get_variable(src);
1001 if (src_var && src_var->data.cannot_coalesce) {
1002 /* The source cannot be coaleseced, which means we can't propagate
1003 * this copy.
1004 */
1005 break;
1006 }
1007
1008 struct copy_entry *dst_entry =
1009 get_entry_and_kill_aliases(copies, dst, full_mask);
1010 value_set_from_value(&dst_entry->src, &value, 0, full_mask);
1011 break;
1012 }
1013
1014 case nir_intrinsic_deref_atomic_add:
1015 case nir_intrinsic_deref_atomic_imin:
1016 case nir_intrinsic_deref_atomic_umin:
1017 case nir_intrinsic_deref_atomic_imax:
1018 case nir_intrinsic_deref_atomic_umax:
1019 case nir_intrinsic_deref_atomic_and:
1020 case nir_intrinsic_deref_atomic_or:
1021 case nir_intrinsic_deref_atomic_xor:
1022 case nir_intrinsic_deref_atomic_exchange:
1023 case nir_intrinsic_deref_atomic_comp_swap:
1024 if (debug) dump_instr(instr);
1025
1026 if (nir_intrinsic_access(intrin) & ACCESS_VOLATILE)
1027 break;
1028
1029 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
1030 unsigned num_components = glsl_get_vector_elements(dst->type);
1031 unsigned full_mask = (1 << num_components) - 1;
1032 kill_aliases(copies, dst, full_mask);
1033 break;
1034
1035 default:
1036 continue; /* To skip the debug below. */
1037 }
1038
1039 if (debug) dump_copy_entries(copies);
1040 }
1041 }
1042
1043 static void
1044 copy_prop_vars_cf_node(struct copy_prop_var_state *state,
1045 struct util_dynarray *copies,
1046 nir_cf_node *cf_node)
1047 {
1048 switch (cf_node->type) {
1049 case nir_cf_node_function: {
1050 nir_function_impl *impl = nir_cf_node_as_function(cf_node);
1051
1052 struct util_dynarray impl_copies;
1053 util_dynarray_init(&impl_copies, state->mem_ctx);
1054
1055 foreach_list_typed_safe(nir_cf_node, cf_node, node, &impl->body)
1056 copy_prop_vars_cf_node(state, &impl_copies, cf_node);
1057
1058 break;
1059 }
1060
1061 case nir_cf_node_block: {
1062 nir_block *block = nir_cf_node_as_block(cf_node);
1063 nir_builder b;
1064 nir_builder_init(&b, state->impl);
1065 copy_prop_vars_block(state, &b, block, copies);
1066 break;
1067 }
1068
1069 case nir_cf_node_if: {
1070 nir_if *if_stmt = nir_cf_node_as_if(cf_node);
1071
1072 /* Clone the copies for each branch of the if statement. The idea is
1073 * that they both see the same state of available copies, but do not
1074 * interfere to each other.
1075 */
1076
1077 struct util_dynarray then_copies;
1078 util_dynarray_clone(&then_copies, state->mem_ctx, copies);
1079
1080 struct util_dynarray else_copies;
1081 util_dynarray_clone(&else_copies, state->mem_ctx, copies);
1082
1083 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->then_list)
1084 copy_prop_vars_cf_node(state, &then_copies, cf_node);
1085
1086 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->else_list)
1087 copy_prop_vars_cf_node(state, &else_copies, cf_node);
1088
1089 /* Both branches copies can be ignored, since the effect of running both
1090 * branches was captured in the first pass that collects vars_written.
1091 */
1092
1093 invalidate_copies_for_cf_node(state, copies, cf_node);
1094
1095 break;
1096 }
1097
1098 case nir_cf_node_loop: {
1099 nir_loop *loop = nir_cf_node_as_loop(cf_node);
1100
1101 /* Invalidate before cloning the copies for the loop, since the loop
1102 * body can be executed more than once.
1103 */
1104
1105 invalidate_copies_for_cf_node(state, copies, cf_node);
1106
1107 struct util_dynarray loop_copies;
1108 util_dynarray_clone(&loop_copies, state->mem_ctx, copies);
1109
1110 foreach_list_typed_safe(nir_cf_node, cf_node, node, &loop->body)
1111 copy_prop_vars_cf_node(state, &loop_copies, cf_node);
1112
1113 break;
1114 }
1115
1116 default:
1117 unreachable("Invalid CF node type");
1118 }
1119 }
1120
1121 static bool
1122 nir_copy_prop_vars_impl(nir_function_impl *impl)
1123 {
1124 void *mem_ctx = ralloc_context(NULL);
1125
1126 if (debug) {
1127 nir_metadata_require(impl, nir_metadata_block_index);
1128 printf("## nir_copy_prop_vars_impl for %s\n", impl->function->name);
1129 }
1130
1131 struct copy_prop_var_state state = {
1132 .impl = impl,
1133 .mem_ctx = mem_ctx,
1134 .lin_ctx = linear_zalloc_parent(mem_ctx, 0),
1135
1136 .vars_written_map = _mesa_pointer_hash_table_create(mem_ctx),
1137 };
1138
1139 gather_vars_written(&state, NULL, &impl->cf_node);
1140
1141 copy_prop_vars_cf_node(&state, NULL, &impl->cf_node);
1142
1143 if (state.progress) {
1144 nir_metadata_preserve(impl, nir_metadata_block_index |
1145 nir_metadata_dominance);
1146 } else {
1147 #ifndef NDEBUG
1148 impl->valid_metadata &= ~nir_metadata_not_properly_reset;
1149 #endif
1150 }
1151
1152 ralloc_free(mem_ctx);
1153 return state.progress;
1154 }
1155
1156 bool
1157 nir_opt_copy_prop_vars(nir_shader *shader)
1158 {
1159 bool progress = false;
1160
1161 nir_foreach_function(function, shader) {
1162 if (!function->impl)
1163 continue;
1164 progress |= nir_copy_prop_vars_impl(function->impl);
1165 }
1166
1167 return progress;
1168 }