Revert "nir: const `nir_call_instr::callee`"
[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 const struct glsl_type *type = entry->dst->type;
437 unsigned num_components = glsl_get_vector_elements(type);
438 assert(index < num_components);
439
440 /* We don't have the element available, so let the instruction do the work. */
441 if (!entry->src.ssa.def[index])
442 return false;
443
444 b->cursor = nir_instr_remove(&intrin->instr);
445 intrin->instr.block = NULL;
446
447 assert(entry->src.ssa.component[index] <
448 entry->src.ssa.def[index]->num_components);
449 nir_ssa_def *def = nir_channel(b, entry->src.ssa.def[index],
450 entry->src.ssa.component[index]);
451
452 *value = (struct value) {
453 .is_ssa = true,
454 .ssa = {
455 .def = { def },
456 .component = { 0 },
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 nir_deref_instr *src = nir_src_as_deref(intrin->src[0]);
816
817 /* Direct array_derefs of vectors operate on the vectors (the parent
818 * deref). Indirects will be handled like other derefs.
819 */
820 int vec_index = 0;
821 nir_deref_instr *vec_src = src;
822 if (is_array_deref_of_vector(src) && nir_src_is_const(src->arr.index)) {
823 vec_src = nir_deref_instr_parent(src);
824 unsigned vec_comps = glsl_get_vector_elements(vec_src->type);
825 vec_index = nir_src_as_uint(src->arr.index);
826
827 /* Loading from an invalid index yields an undef */
828 if (vec_index >= vec_comps) {
829 b->cursor = nir_instr_remove(instr);
830 nir_ssa_def *u = nir_ssa_undef(b, 1, intrin->dest.ssa.bit_size);
831 nir_ssa_def_rewrite_uses(&intrin->dest.ssa, nir_src_for_ssa(u));
832 break;
833 }
834 }
835
836 struct copy_entry *src_entry =
837 lookup_entry_for_deref(copies, src, nir_derefs_a_contains_b_bit);
838 struct value value = {0};
839 if (try_load_from_entry(state, src_entry, b, intrin, src, &value)) {
840 if (value.is_ssa) {
841 /* lookup_load has already ensured that we get a single SSA
842 * value that has all of the channels. We just have to do the
843 * rewrite operation. Note for array derefs of vectors, the
844 * channel 0 is used.
845 */
846 if (intrin->instr.block) {
847 /* The lookup left our instruction in-place. This means it
848 * must have used it to vec up a bunch of different sources.
849 * We need to be careful when rewriting uses so we don't
850 * rewrite the vecN itself.
851 */
852 nir_ssa_def_rewrite_uses_after(&intrin->dest.ssa,
853 nir_src_for_ssa(value.ssa.def[0]),
854 value.ssa.def[0]->parent_instr);
855 } else {
856 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
857 nir_src_for_ssa(value.ssa.def[0]));
858 }
859 } else {
860 /* We're turning it into a load of a different variable */
861 intrin->src[0] = nir_src_for_ssa(&value.deref->dest.ssa);
862
863 /* Put it back in again. */
864 nir_builder_instr_insert(b, instr);
865 value_set_ssa_components(&value, &intrin->dest.ssa,
866 intrin->num_components);
867 }
868 state->progress = true;
869 } else {
870 value_set_ssa_components(&value, &intrin->dest.ssa,
871 intrin->num_components);
872 }
873
874 /* Now that we have a value, we're going to store it back so that we
875 * have the right value next time we come looking for it. In order
876 * to do this, we need an exact match, not just something that
877 * contains what we're looking for.
878 */
879 struct copy_entry *entry =
880 lookup_entry_for_deref(copies, vec_src, nir_derefs_equal_bit);
881 if (!entry)
882 entry = copy_entry_create(copies, vec_src);
883
884 /* Update the entry with the value of the load. This way
885 * we can potentially remove subsequent loads.
886 */
887 value_set_from_value(&entry->src, &value, vec_index,
888 (1 << intrin->num_components) - 1);
889 break;
890 }
891
892 case nir_intrinsic_store_deref: {
893 if (debug) dump_instr(instr);
894
895 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
896 assert(glsl_type_is_vector_or_scalar(dst->type));
897
898 /* Direct array_derefs of vectors operate on the vectors (the parent
899 * deref). Indirects will be handled like other derefs.
900 */
901 int vec_index = 0;
902 nir_deref_instr *vec_dst = dst;
903 if (is_array_deref_of_vector(dst) && nir_src_is_const(dst->arr.index)) {
904 vec_dst = nir_deref_instr_parent(dst);
905 unsigned vec_comps = glsl_get_vector_elements(vec_dst->type);
906
907 vec_index = nir_src_as_uint(dst->arr.index);
908
909 /* Storing to an invalid index is a no-op. */
910 if (vec_index >= vec_comps) {
911 nir_instr_remove(instr);
912 break;
913 }
914 }
915
916 struct copy_entry *entry =
917 lookup_entry_for_deref(copies, dst, nir_derefs_equal_bit);
918 if (entry && value_equals_store_src(&entry->src, intrin)) {
919 /* If we are storing the value from a load of the same var the
920 * store is redundant so remove it.
921 */
922 nir_instr_remove(instr);
923 } else {
924 struct value value = {0};
925 value_set_ssa_components(&value, intrin->src[1].ssa,
926 intrin->num_components);
927 unsigned wrmask = nir_intrinsic_write_mask(intrin);
928 struct copy_entry *entry =
929 get_entry_and_kill_aliases(copies, vec_dst, wrmask);
930 value_set_from_value(&entry->src, &value, vec_index, wrmask);
931 }
932
933 break;
934 }
935
936 case nir_intrinsic_copy_deref: {
937 if (debug) dump_instr(instr);
938
939 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
940 nir_deref_instr *src = nir_src_as_deref(intrin->src[1]);
941
942 if (nir_compare_derefs(src, dst) & nir_derefs_equal_bit) {
943 /* This is a no-op self-copy. Get rid of it */
944 nir_instr_remove(instr);
945 continue;
946 }
947
948 /* The copy_deref intrinsic doesn't keep track of num_components, so
949 * get it ourselves.
950 */
951 unsigned num_components = glsl_get_vector_elements(dst->type);
952 unsigned full_mask = (1 << num_components) - 1;
953
954 /* Copy of direct array derefs of vectors are not handled. Just
955 * invalidate what's written and bail.
956 */
957 if ((is_array_deref_of_vector(src) && nir_src_is_const(src->arr.index)) ||
958 (is_array_deref_of_vector(dst) && nir_src_is_const(dst->arr.index))) {
959 kill_aliases(copies, dst, full_mask);
960 break;
961 }
962
963 struct copy_entry *src_entry =
964 lookup_entry_for_deref(copies, src, nir_derefs_a_contains_b_bit);
965 struct value value;
966 if (try_load_from_entry(state, src_entry, b, intrin, src, &value)) {
967 /* If load works, intrin (the copy_deref) is removed. */
968 if (value.is_ssa) {
969 nir_store_deref(b, dst, value.ssa.def[0], full_mask);
970 } else {
971 /* If this would be a no-op self-copy, don't bother. */
972 if (nir_compare_derefs(value.deref, dst) & nir_derefs_equal_bit)
973 continue;
974
975 /* Just turn it into a copy of a different deref */
976 intrin->src[1] = nir_src_for_ssa(&value.deref->dest.ssa);
977
978 /* Put it back in again. */
979 nir_builder_instr_insert(b, instr);
980 }
981
982 state->progress = true;
983 } else {
984 value = (struct value) {
985 .is_ssa = false,
986 { .deref = src },
987 };
988 }
989
990 struct copy_entry *dst_entry =
991 get_entry_and_kill_aliases(copies, dst, full_mask);
992 value_set_from_value(&dst_entry->src, &value, 0, full_mask);
993 break;
994 }
995
996 case nir_intrinsic_deref_atomic_add:
997 case nir_intrinsic_deref_atomic_imin:
998 case nir_intrinsic_deref_atomic_umin:
999 case nir_intrinsic_deref_atomic_imax:
1000 case nir_intrinsic_deref_atomic_umax:
1001 case nir_intrinsic_deref_atomic_and:
1002 case nir_intrinsic_deref_atomic_or:
1003 case nir_intrinsic_deref_atomic_xor:
1004 case nir_intrinsic_deref_atomic_exchange:
1005 case nir_intrinsic_deref_atomic_comp_swap:
1006 if (debug) dump_instr(instr);
1007
1008 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
1009 unsigned num_components = glsl_get_vector_elements(dst->type);
1010 unsigned full_mask = (1 << num_components) - 1;
1011 kill_aliases(copies, dst, full_mask);
1012 break;
1013
1014 default:
1015 continue; /* To skip the debug below. */
1016 }
1017
1018 if (debug) dump_copy_entries(copies);
1019 }
1020 }
1021
1022 static void
1023 copy_prop_vars_cf_node(struct copy_prop_var_state *state,
1024 struct util_dynarray *copies,
1025 nir_cf_node *cf_node)
1026 {
1027 switch (cf_node->type) {
1028 case nir_cf_node_function: {
1029 nir_function_impl *impl = nir_cf_node_as_function(cf_node);
1030
1031 struct util_dynarray impl_copies;
1032 util_dynarray_init(&impl_copies, state->mem_ctx);
1033
1034 foreach_list_typed_safe(nir_cf_node, cf_node, node, &impl->body)
1035 copy_prop_vars_cf_node(state, &impl_copies, cf_node);
1036
1037 break;
1038 }
1039
1040 case nir_cf_node_block: {
1041 nir_block *block = nir_cf_node_as_block(cf_node);
1042 nir_builder b;
1043 nir_builder_init(&b, state->impl);
1044 copy_prop_vars_block(state, &b, block, copies);
1045 break;
1046 }
1047
1048 case nir_cf_node_if: {
1049 nir_if *if_stmt = nir_cf_node_as_if(cf_node);
1050
1051 /* Clone the copies for each branch of the if statement. The idea is
1052 * that they both see the same state of available copies, but do not
1053 * interfere to each other.
1054 */
1055
1056 struct util_dynarray then_copies;
1057 util_dynarray_clone(&then_copies, state->mem_ctx, copies);
1058
1059 struct util_dynarray else_copies;
1060 util_dynarray_clone(&else_copies, state->mem_ctx, copies);
1061
1062 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->then_list)
1063 copy_prop_vars_cf_node(state, &then_copies, cf_node);
1064
1065 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->else_list)
1066 copy_prop_vars_cf_node(state, &else_copies, cf_node);
1067
1068 /* Both branches copies can be ignored, since the effect of running both
1069 * branches was captured in the first pass that collects vars_written.
1070 */
1071
1072 invalidate_copies_for_cf_node(state, copies, cf_node);
1073
1074 break;
1075 }
1076
1077 case nir_cf_node_loop: {
1078 nir_loop *loop = nir_cf_node_as_loop(cf_node);
1079
1080 /* Invalidate before cloning the copies for the loop, since the loop
1081 * body can be executed more than once.
1082 */
1083
1084 invalidate_copies_for_cf_node(state, copies, cf_node);
1085
1086 struct util_dynarray loop_copies;
1087 util_dynarray_clone(&loop_copies, state->mem_ctx, copies);
1088
1089 foreach_list_typed_safe(nir_cf_node, cf_node, node, &loop->body)
1090 copy_prop_vars_cf_node(state, &loop_copies, cf_node);
1091
1092 break;
1093 }
1094
1095 default:
1096 unreachable("Invalid CF node type");
1097 }
1098 }
1099
1100 static bool
1101 nir_copy_prop_vars_impl(nir_function_impl *impl)
1102 {
1103 void *mem_ctx = ralloc_context(NULL);
1104
1105 if (debug) {
1106 nir_metadata_require(impl, nir_metadata_block_index);
1107 printf("## nir_copy_prop_vars_impl for %s\n", impl->function->name);
1108 }
1109
1110 struct copy_prop_var_state state = {
1111 .impl = impl,
1112 .mem_ctx = mem_ctx,
1113 .lin_ctx = linear_zalloc_parent(mem_ctx, 0),
1114
1115 .vars_written_map = _mesa_pointer_hash_table_create(mem_ctx),
1116 };
1117
1118 gather_vars_written(&state, NULL, &impl->cf_node);
1119
1120 copy_prop_vars_cf_node(&state, NULL, &impl->cf_node);
1121
1122 if (state.progress) {
1123 nir_metadata_preserve(impl, nir_metadata_block_index |
1124 nir_metadata_dominance);
1125 } else {
1126 #ifndef NDEBUG
1127 impl->valid_metadata &= ~nir_metadata_not_properly_reset;
1128 #endif
1129 }
1130
1131 ralloc_free(mem_ctx);
1132 return state.progress;
1133 }
1134
1135 bool
1136 nir_opt_copy_prop_vars(nir_shader *shader)
1137 {
1138 bool progress = false;
1139
1140 nir_foreach_function(function, shader) {
1141 if (!function->impl)
1142 continue;
1143 progress |= nir_copy_prop_vars_impl(function->impl);
1144 }
1145
1146 return progress;
1147 }