3dc0ad805738381506b7c3117bfc4a2a59ec188f
[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 /**
32 * Variable-based copy propagation
33 *
34 * Normally, NIR trusts in SSA form for most of its copy-propagation needs.
35 * However, there are cases, especially when dealing with indirects, where SSA
36 * won't help you. This pass is for those times. Specifically, it handles
37 * the following things that the rest of NIR can't:
38 *
39 * 1) Copy-propagation on variables that have indirect access. This includes
40 * propagating from indirect stores into indirect loads.
41 *
42 * 2) Removal of redundant load_deref intrinsics. We can't trust regular CSE
43 * to do this because it isn't aware of variable writes that may alias the
44 * value and make the former load invalid.
45 *
46 * This pass uses an intermediate solution between being local / "per-block"
47 * and a complete data-flow analysis. It follows the control flow graph, and
48 * propagate the available copy information forward, invalidating data at each
49 * cf_node.
50 *
51 * Removal of dead writes to variables is handled by another pass.
52 */
53
54 struct vars_written {
55 nir_variable_mode modes;
56
57 /* Key is deref and value is the uintptr_t with the write mask. */
58 struct hash_table *derefs;
59 };
60
61 struct value {
62 bool is_ssa;
63 union {
64 nir_ssa_def *ssa[4];
65 nir_deref_instr *deref;
66 };
67 };
68
69 struct copy_entry {
70 struct value src;
71
72 nir_deref_instr *dst;
73 };
74
75 struct copy_prop_var_state {
76 nir_function_impl *impl;
77
78 void *mem_ctx;
79 void *lin_ctx;
80
81 /* Maps nodes to vars_written. Used to invalidate copy entries when
82 * visiting each node.
83 */
84 struct hash_table *vars_written_map;
85
86 bool progress;
87 };
88
89 static bool
90 value_equals_store_src(struct value *value, nir_intrinsic_instr *intrin)
91 {
92 assert(intrin->intrinsic == nir_intrinsic_store_deref);
93 uintptr_t write_mask = nir_intrinsic_write_mask(intrin);
94
95 for (unsigned i = 0; i < intrin->num_components; i++) {
96 if ((write_mask & (1 << i)) &&
97 value->ssa[i] != intrin->src[1].ssa)
98 return false;
99 }
100
101 return true;
102 }
103
104 static struct vars_written *
105 create_vars_written(struct copy_prop_var_state *state)
106 {
107 struct vars_written *written =
108 linear_zalloc_child(state->lin_ctx, sizeof(struct vars_written));
109 written->derefs = _mesa_pointer_hash_table_create(state->mem_ctx);
110 return written;
111 }
112
113 static void
114 gather_vars_written(struct copy_prop_var_state *state,
115 struct vars_written *written,
116 nir_cf_node *cf_node)
117 {
118 struct vars_written *new_written = NULL;
119
120 switch (cf_node->type) {
121 case nir_cf_node_function: {
122 nir_function_impl *impl = nir_cf_node_as_function(cf_node);
123 foreach_list_typed_safe(nir_cf_node, cf_node, node, &impl->body)
124 gather_vars_written(state, NULL, cf_node);
125 break;
126 }
127
128 case nir_cf_node_block: {
129 if (!written)
130 break;
131
132 nir_block *block = nir_cf_node_as_block(cf_node);
133 nir_foreach_instr(instr, block) {
134 if (instr->type == nir_instr_type_call) {
135 written->modes |= nir_var_shader_out |
136 nir_var_private |
137 nir_var_function |
138 nir_var_ssbo |
139 nir_var_shared;
140 continue;
141 }
142
143 if (instr->type != nir_instr_type_intrinsic)
144 continue;
145
146 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
147 switch (intrin->intrinsic) {
148 case nir_intrinsic_barrier:
149 case nir_intrinsic_memory_barrier:
150 written->modes |= nir_var_shader_out |
151 nir_var_ssbo |
152 nir_var_shared;
153 break;
154
155 case nir_intrinsic_emit_vertex:
156 case nir_intrinsic_emit_vertex_with_counter:
157 written->modes = nir_var_shader_out;
158 break;
159
160 case nir_intrinsic_store_deref:
161 case nir_intrinsic_copy_deref: {
162 /* Destination in _both_ store_deref and copy_deref is src[0]. */
163 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
164
165 uintptr_t mask = intrin->intrinsic == nir_intrinsic_store_deref ?
166 nir_intrinsic_write_mask(intrin) : (1 << glsl_get_vector_elements(dst->type)) - 1;
167
168 struct hash_entry *ht_entry = _mesa_hash_table_search(written->derefs, dst);
169 if (ht_entry)
170 ht_entry->data = (void *)(mask | (uintptr_t)ht_entry->data);
171 else
172 _mesa_hash_table_insert(written->derefs, dst, (void *)mask);
173
174 break;
175 }
176
177 default:
178 break;
179 }
180 }
181
182 break;
183 }
184
185 case nir_cf_node_if: {
186 nir_if *if_stmt = nir_cf_node_as_if(cf_node);
187
188 new_written = create_vars_written(state);
189
190 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->then_list)
191 gather_vars_written(state, new_written, cf_node);
192
193 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->else_list)
194 gather_vars_written(state, new_written, cf_node);
195
196 break;
197 }
198
199 case nir_cf_node_loop: {
200 nir_loop *loop = nir_cf_node_as_loop(cf_node);
201
202 new_written = create_vars_written(state);
203
204 foreach_list_typed_safe(nir_cf_node, cf_node, node, &loop->body)
205 gather_vars_written(state, new_written, cf_node);
206
207 break;
208 }
209
210 default:
211 unreachable("Invalid CF node type");
212 }
213
214 if (new_written) {
215 /* Merge new information to the parent control flow node. */
216 if (written) {
217 written->modes |= new_written->modes;
218 hash_table_foreach(new_written->derefs, new_entry) {
219 struct hash_entry *old_entry =
220 _mesa_hash_table_search_pre_hashed(written->derefs, new_entry->hash,
221 new_entry->key);
222 if (old_entry) {
223 nir_component_mask_t merged = (uintptr_t) new_entry->data |
224 (uintptr_t) old_entry->data;
225 old_entry->data = (void *) ((uintptr_t) merged);
226 } else {
227 _mesa_hash_table_insert_pre_hashed(written->derefs, new_entry->hash,
228 new_entry->key, new_entry->data);
229 }
230 }
231 }
232 _mesa_hash_table_insert(state->vars_written_map, cf_node, new_written);
233 }
234 }
235
236 static struct copy_entry *
237 copy_entry_create(struct util_dynarray *copies,
238 nir_deref_instr *dst_deref)
239 {
240 struct copy_entry new_entry = {
241 .dst = dst_deref,
242 };
243 util_dynarray_append(copies, struct copy_entry, new_entry);
244 return util_dynarray_top_ptr(copies, struct copy_entry);
245 }
246
247 /* Remove copy entry by swapping it with the last element and reducing the
248 * size. If used inside an iteration on copies, it must be a reverse
249 * (backwards) iteration. It is safe to use in those cases because the swap
250 * will not affect the rest of the iteration.
251 */
252 static void
253 copy_entry_remove(struct util_dynarray *copies,
254 struct copy_entry *entry)
255 {
256 /* This also works when removing the last element since pop don't shrink
257 * the memory used by the array, so the swap is useless but not invalid.
258 */
259 *entry = util_dynarray_pop(copies, struct copy_entry);
260 }
261
262 static struct copy_entry *
263 lookup_entry_for_deref(struct util_dynarray *copies,
264 nir_deref_instr *deref,
265 nir_deref_compare_result allowed_comparisons)
266 {
267 util_dynarray_foreach(copies, struct copy_entry, iter) {
268 if (nir_compare_derefs(iter->dst, deref) & allowed_comparisons)
269 return iter;
270 }
271
272 return NULL;
273 }
274
275 static struct copy_entry *
276 lookup_entry_and_kill_aliases(struct util_dynarray *copies,
277 nir_deref_instr *deref,
278 unsigned write_mask)
279 {
280 /* TODO: Take into account the write_mask. */
281
282 nir_deref_instr *dst_match = NULL;
283 util_dynarray_foreach_reverse(copies, struct copy_entry, iter) {
284 if (!iter->src.is_ssa) {
285 /* If this write aliases the source of some entry, get rid of it */
286 if (nir_compare_derefs(iter->src.deref, deref) & nir_derefs_may_alias_bit) {
287 copy_entry_remove(copies, iter);
288 continue;
289 }
290 }
291
292 nir_deref_compare_result comp = nir_compare_derefs(iter->dst, deref);
293
294 if (comp & nir_derefs_equal_bit) {
295 /* Removing entries invalidate previous iter pointers, so we'll
296 * collect the matching entry later. Just make sure it is unique.
297 */
298 assert(!dst_match);
299 dst_match = iter->dst;
300 } else if (comp & nir_derefs_may_alias_bit) {
301 copy_entry_remove(copies, iter);
302 }
303 }
304
305 struct copy_entry *entry = NULL;
306 if (dst_match) {
307 util_dynarray_foreach(copies, struct copy_entry, iter) {
308 if (iter->dst == dst_match) {
309 entry = iter;
310 break;
311 }
312 }
313 assert(entry);
314 }
315 return entry;
316 }
317
318 static void
319 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 struct copy_entry *entry =
326 lookup_entry_and_kill_aliases(copies, deref, write_mask);
327 if (entry)
328 copy_entry_remove(copies, entry);
329 }
330
331 static struct copy_entry *
332 get_entry_and_kill_aliases(struct util_dynarray *copies,
333 nir_deref_instr *deref,
334 unsigned write_mask)
335 {
336 /* TODO: Take into account the write_mask. */
337
338 struct copy_entry *entry =
339 lookup_entry_and_kill_aliases(copies, deref, write_mask);
340
341 if (entry == NULL)
342 entry = copy_entry_create(copies, deref);
343
344 return entry;
345 }
346
347 static void
348 apply_barrier_for_modes(struct util_dynarray *copies,
349 nir_variable_mode modes)
350 {
351 util_dynarray_foreach_reverse(copies, struct copy_entry, iter) {
352 if ((iter->dst->mode & modes) ||
353 (!iter->src.is_ssa && (iter->src.deref->mode & modes)))
354 copy_entry_remove(copies, iter);
355 }
356 }
357
358 static void
359 store_to_entry(struct copy_prop_var_state *state, struct copy_entry *entry,
360 const struct value *value, unsigned write_mask)
361 {
362 if (value->is_ssa) {
363 /* Clear src if it was being used as non-SSA. */
364 if (!entry->src.is_ssa)
365 memset(entry->src.ssa, 0, sizeof(entry->src.ssa));
366 entry->src.is_ssa = true;
367 /* Only overwrite the written components */
368 for (unsigned i = 0; i < 4; i++) {
369 if (write_mask & (1 << i))
370 entry->src.ssa[i] = value->ssa[i];
371 }
372 } else {
373 /* Non-ssa stores always write everything */
374 entry->src.is_ssa = false;
375 entry->src.deref = value->deref;
376 }
377 }
378
379 /* Do a "load" from an SSA-based entry return it in "value" as a value with a
380 * single SSA def. Because an entry could reference up to 4 different SSA
381 * defs, a vecN operation may be inserted to combine them into a single SSA
382 * def before handing it back to the caller. If the load instruction is no
383 * longer needed, it is removed and nir_instr::block is set to NULL. (It is
384 * possible, in some cases, for the load to be used in the vecN operation in
385 * which case it isn't deleted.)
386 */
387 static bool
388 load_from_ssa_entry_value(struct copy_prop_var_state *state,
389 struct copy_entry *entry,
390 nir_builder *b, nir_intrinsic_instr *intrin,
391 struct value *value)
392 {
393 *value = entry->src;
394 assert(value->is_ssa);
395
396 const struct glsl_type *type = entry->dst->type;
397 unsigned num_components = glsl_get_vector_elements(type);
398
399 nir_component_mask_t available = 0;
400 bool all_same = true;
401 for (unsigned i = 0; i < num_components; i++) {
402 if (value->ssa[i])
403 available |= (1 << i);
404
405 if (value->ssa[i] != value->ssa[0])
406 all_same = false;
407 }
408
409 if (all_same) {
410 /* Our work here is done */
411 b->cursor = nir_instr_remove(&intrin->instr);
412 intrin->instr.block = NULL;
413 return true;
414 }
415
416 if (available != (1 << num_components) - 1 &&
417 intrin->intrinsic == nir_intrinsic_load_deref &&
418 (available & nir_ssa_def_components_read(&intrin->dest.ssa)) == 0) {
419 /* If none of the components read are available as SSA values, then we
420 * should just bail. Otherwise, we would end up replacing the uses of
421 * the load_deref a vecN() that just gathers up its components.
422 */
423 return false;
424 }
425
426 b->cursor = nir_after_instr(&intrin->instr);
427
428 nir_ssa_def *load_def =
429 intrin->intrinsic == nir_intrinsic_load_deref ? &intrin->dest.ssa : NULL;
430
431 bool keep_intrin = false;
432 nir_ssa_def *comps[NIR_MAX_VEC_COMPONENTS];
433 for (unsigned i = 0; i < num_components; i++) {
434 if (value->ssa[i]) {
435 comps[i] = nir_channel(b, value->ssa[i], i);
436 } else {
437 /* We don't have anything for this component in our
438 * list. Just re-use a channel from the load.
439 */
440 if (load_def == NULL)
441 load_def = nir_load_deref(b, entry->dst);
442
443 if (load_def->parent_instr == &intrin->instr)
444 keep_intrin = true;
445
446 comps[i] = nir_channel(b, load_def, i);
447 }
448 }
449
450 nir_ssa_def *vec = nir_vec(b, comps, num_components);
451 for (unsigned i = 0; i < num_components; i++)
452 value->ssa[i] = vec;
453
454 if (!keep_intrin) {
455 /* Removing this instruction should not touch the cursor because we
456 * created the cursor after the intrinsic and have added at least one
457 * instruction (the vec) since then.
458 */
459 assert(b->cursor.instr != &intrin->instr);
460 nir_instr_remove(&intrin->instr);
461 intrin->instr.block = NULL;
462 }
463
464 return true;
465 }
466
467 /**
468 * Specialize the wildcards in a deref chain
469 *
470 * This function returns a deref chain identical to \param deref except that
471 * some of its wildcards are replaced with indices from \param specific. The
472 * process is guided by \param guide which references the same type as \param
473 * specific but has the same wildcard array lengths as \param deref.
474 */
475 static nir_deref_instr *
476 specialize_wildcards(nir_builder *b,
477 nir_deref_path *deref,
478 nir_deref_path *guide,
479 nir_deref_path *specific)
480 {
481 nir_deref_instr **deref_p = &deref->path[1];
482 nir_deref_instr **guide_p = &guide->path[1];
483 nir_deref_instr **spec_p = &specific->path[1];
484 nir_deref_instr *ret_tail = deref->path[0];
485 for (; *deref_p; deref_p++) {
486 if ((*deref_p)->deref_type == nir_deref_type_array_wildcard) {
487 /* This is where things get tricky. We have to search through
488 * the entry deref to find its corresponding wildcard and fill
489 * this slot in with the value from the src.
490 */
491 while (*guide_p &&
492 (*guide_p)->deref_type != nir_deref_type_array_wildcard) {
493 guide_p++;
494 spec_p++;
495 }
496 assert(*guide_p && *spec_p);
497
498 ret_tail = nir_build_deref_follower(b, ret_tail, *spec_p);
499
500 guide_p++;
501 spec_p++;
502 } else {
503 ret_tail = nir_build_deref_follower(b, ret_tail, *deref_p);
504 }
505 }
506
507 return ret_tail;
508 }
509
510 /* Do a "load" from an deref-based entry return it in "value" as a value. The
511 * deref returned in "value" will always be a fresh copy so the caller can
512 * steal it and assign it to the instruction directly without copying it
513 * again.
514 */
515 static bool
516 load_from_deref_entry_value(struct copy_prop_var_state *state,
517 struct copy_entry *entry,
518 nir_builder *b, nir_intrinsic_instr *intrin,
519 nir_deref_instr *src, struct value *value)
520 {
521 *value = entry->src;
522
523 b->cursor = nir_instr_remove(&intrin->instr);
524
525 nir_deref_path entry_dst_path, src_path;
526 nir_deref_path_init(&entry_dst_path, entry->dst, state->mem_ctx);
527 nir_deref_path_init(&src_path, src, state->mem_ctx);
528
529 bool need_to_specialize_wildcards = false;
530 nir_deref_instr **entry_p = &entry_dst_path.path[1];
531 nir_deref_instr **src_p = &src_path.path[1];
532 while (*entry_p && *src_p) {
533 nir_deref_instr *entry_tail = *entry_p++;
534 nir_deref_instr *src_tail = *src_p++;
535
536 if (src_tail->deref_type == nir_deref_type_array &&
537 entry_tail->deref_type == nir_deref_type_array_wildcard)
538 need_to_specialize_wildcards = true;
539 }
540
541 /* If the entry deref is longer than the source deref then it refers to a
542 * smaller type and we can't source from it.
543 */
544 assert(*entry_p == NULL);
545
546 if (need_to_specialize_wildcards) {
547 /* The entry has some wildcards that are not in src. This means we need
548 * to construct a new deref based on the entry but using the wildcards
549 * from the source and guided by the entry dst. Oof.
550 */
551 nir_deref_path entry_src_path;
552 nir_deref_path_init(&entry_src_path, entry->src.deref, state->mem_ctx);
553 value->deref = specialize_wildcards(b, &entry_src_path,
554 &entry_dst_path, &src_path);
555 nir_deref_path_finish(&entry_src_path);
556 }
557
558 /* If our source deref is longer than the entry deref, that's ok because
559 * it just means the entry deref needs to be extended a bit.
560 */
561 while (*src_p) {
562 nir_deref_instr *src_tail = *src_p++;
563 value->deref = nir_build_deref_follower(b, value->deref, src_tail);
564 }
565
566 nir_deref_path_finish(&entry_dst_path);
567 nir_deref_path_finish(&src_path);
568
569 return true;
570 }
571
572 static bool
573 try_load_from_entry(struct copy_prop_var_state *state, struct copy_entry *entry,
574 nir_builder *b, nir_intrinsic_instr *intrin,
575 nir_deref_instr *src, struct value *value)
576 {
577 if (entry == NULL)
578 return false;
579
580 if (entry->src.is_ssa) {
581 return load_from_ssa_entry_value(state, entry, b, intrin, value);
582 } else {
583 return load_from_deref_entry_value(state, entry, b, intrin, src, value);
584 }
585 }
586
587 static void
588 invalidate_copies_for_cf_node(struct copy_prop_var_state *state,
589 struct util_dynarray *copies,
590 nir_cf_node *cf_node)
591 {
592 struct hash_entry *ht_entry = _mesa_hash_table_search(state->vars_written_map, cf_node);
593 assert(ht_entry);
594
595 struct vars_written *written = ht_entry->data;
596 if (written->modes) {
597 util_dynarray_foreach_reverse(copies, struct copy_entry, entry) {
598 if (entry->dst->mode & written->modes)
599 copy_entry_remove(copies, entry);
600 }
601 }
602
603 hash_table_foreach (written->derefs, entry) {
604 nir_deref_instr *deref_written = (nir_deref_instr *)entry->key;
605 kill_aliases(copies, deref_written, (uintptr_t)entry->data);
606 }
607 }
608
609 static void
610 copy_prop_vars_block(struct copy_prop_var_state *state,
611 nir_builder *b, nir_block *block,
612 struct util_dynarray *copies)
613 {
614 nir_foreach_instr_safe(instr, block) {
615 if (instr->type == nir_instr_type_call) {
616 apply_barrier_for_modes(copies, nir_var_shader_out |
617 nir_var_private |
618 nir_var_function |
619 nir_var_ssbo |
620 nir_var_shared);
621 continue;
622 }
623
624 if (instr->type != nir_instr_type_intrinsic)
625 continue;
626
627 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
628 switch (intrin->intrinsic) {
629 case nir_intrinsic_barrier:
630 case nir_intrinsic_memory_barrier:
631 apply_barrier_for_modes(copies, nir_var_shader_out |
632 nir_var_ssbo |
633 nir_var_shared);
634 break;
635
636 case nir_intrinsic_emit_vertex:
637 case nir_intrinsic_emit_vertex_with_counter:
638 apply_barrier_for_modes(copies, nir_var_shader_out);
639 break;
640
641 case nir_intrinsic_load_deref: {
642 nir_deref_instr *src = nir_src_as_deref(intrin->src[0]);
643
644 struct copy_entry *src_entry =
645 lookup_entry_for_deref(copies, src, nir_derefs_a_contains_b_bit);
646 struct value value;
647 if (try_load_from_entry(state, src_entry, b, intrin, src, &value)) {
648 if (value.is_ssa) {
649 /* lookup_load has already ensured that we get a single SSA
650 * value that has all of the channels. We just have to do the
651 * rewrite operation.
652 */
653 if (intrin->instr.block) {
654 /* The lookup left our instruction in-place. This means it
655 * must have used it to vec up a bunch of different sources.
656 * We need to be careful when rewriting uses so we don't
657 * rewrite the vecN itself.
658 */
659 nir_ssa_def_rewrite_uses_after(&intrin->dest.ssa,
660 nir_src_for_ssa(value.ssa[0]),
661 value.ssa[0]->parent_instr);
662 } else {
663 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
664 nir_src_for_ssa(value.ssa[0]));
665 }
666 } else {
667 /* We're turning it into a load of a different variable */
668 intrin->src[0] = nir_src_for_ssa(&value.deref->dest.ssa);
669
670 /* Put it back in again. */
671 nir_builder_instr_insert(b, instr);
672
673 value.is_ssa = true;
674 for (unsigned i = 0; i < intrin->num_components; i++)
675 value.ssa[i] = &intrin->dest.ssa;
676 }
677 state->progress = true;
678 } else {
679 value.is_ssa = true;
680 for (unsigned i = 0; i < intrin->num_components; i++)
681 value.ssa[i] = &intrin->dest.ssa;
682 }
683
684 /* Now that we have a value, we're going to store it back so that we
685 * have the right value next time we come looking for it. In order
686 * to do this, we need an exact match, not just something that
687 * contains what we're looking for.
688 */
689 struct copy_entry *store_entry =
690 lookup_entry_for_deref(copies, src, nir_derefs_equal_bit);
691 if (!store_entry)
692 store_entry = copy_entry_create(copies, src);
693
694 /* Set up a store to this entry with the value of the load. This way
695 * we can potentially remove subsequent loads. However, we use a
696 * NULL instruction so we don't try and delete the load on a
697 * subsequent store.
698 */
699 store_to_entry(state, store_entry, &value,
700 ((1 << intrin->num_components) - 1));
701 break;
702 }
703
704 case nir_intrinsic_store_deref: {
705 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
706 struct copy_entry *entry =
707 lookup_entry_for_deref(copies, dst, nir_derefs_equal_bit);
708 if (entry && value_equals_store_src(&entry->src, intrin)) {
709 /* If we are storing the value from a load of the same var the
710 * store is redundant so remove it.
711 */
712 nir_instr_remove(instr);
713 } else {
714 struct value value = {
715 .is_ssa = true
716 };
717
718 for (unsigned i = 0; i < intrin->num_components; i++)
719 value.ssa[i] = intrin->src[1].ssa;
720
721 unsigned wrmask = nir_intrinsic_write_mask(intrin);
722 struct copy_entry *entry =
723 get_entry_and_kill_aliases(copies, dst, wrmask);
724 store_to_entry(state, entry, &value, wrmask);
725 }
726
727 break;
728 }
729
730 case nir_intrinsic_copy_deref: {
731 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
732 nir_deref_instr *src = nir_src_as_deref(intrin->src[1]);
733
734 if (nir_compare_derefs(src, dst) & nir_derefs_equal_bit) {
735 /* This is a no-op self-copy. Get rid of it */
736 nir_instr_remove(instr);
737 continue;
738 }
739
740 struct copy_entry *src_entry =
741 lookup_entry_for_deref(copies, src, nir_derefs_a_contains_b_bit);
742 struct value value;
743 if (try_load_from_entry(state, src_entry, b, intrin, src, &value)) {
744 /* If load works, intrin (the copy_deref) is removed. */
745 if (value.is_ssa) {
746 nir_store_deref(b, dst, value.ssa[0], 0xf);
747 } else {
748 /* If this would be a no-op self-copy, don't bother. */
749 if (nir_compare_derefs(value.deref, dst) & nir_derefs_equal_bit)
750 continue;
751
752 /* Just turn it into a copy of a different deref */
753 intrin->src[1] = nir_src_for_ssa(&value.deref->dest.ssa);
754
755 /* Put it back in again. */
756 nir_builder_instr_insert(b, instr);
757 }
758
759 state->progress = true;
760 } else {
761 value = (struct value) {
762 .is_ssa = false,
763 { .deref = src },
764 };
765 }
766
767 struct copy_entry *dst_entry =
768 get_entry_and_kill_aliases(copies, dst, 0xf);
769 store_to_entry(state, dst_entry, &value, 0xf);
770 break;
771 }
772
773 default:
774 break;
775 }
776 }
777 }
778
779 static void
780 copy_prop_vars_cf_node(struct copy_prop_var_state *state,
781 struct util_dynarray *copies,
782 nir_cf_node *cf_node)
783 {
784 switch (cf_node->type) {
785 case nir_cf_node_function: {
786 nir_function_impl *impl = nir_cf_node_as_function(cf_node);
787
788 struct util_dynarray impl_copies;
789 util_dynarray_init(&impl_copies, state->mem_ctx);
790
791 foreach_list_typed_safe(nir_cf_node, cf_node, node, &impl->body)
792 copy_prop_vars_cf_node(state, &impl_copies, cf_node);
793
794 break;
795 }
796
797 case nir_cf_node_block: {
798 nir_block *block = nir_cf_node_as_block(cf_node);
799 nir_builder b;
800 nir_builder_init(&b, state->impl);
801 copy_prop_vars_block(state, &b, block, copies);
802 break;
803 }
804
805 case nir_cf_node_if: {
806 nir_if *if_stmt = nir_cf_node_as_if(cf_node);
807
808 /* Clone the copies for each branch of the if statement. The idea is
809 * that they both see the same state of available copies, but do not
810 * interfere to each other.
811 */
812
813 struct util_dynarray then_copies;
814 util_dynarray_clone(&then_copies, state->mem_ctx, copies);
815
816 struct util_dynarray else_copies;
817 util_dynarray_clone(&else_copies, state->mem_ctx, copies);
818
819 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->then_list)
820 copy_prop_vars_cf_node(state, &then_copies, cf_node);
821
822 foreach_list_typed_safe(nir_cf_node, cf_node, node, &if_stmt->else_list)
823 copy_prop_vars_cf_node(state, &else_copies, cf_node);
824
825 /* Both branches copies can be ignored, since the effect of running both
826 * branches was captured in the first pass that collects vars_written.
827 */
828
829 invalidate_copies_for_cf_node(state, copies, cf_node);
830
831 break;
832 }
833
834 case nir_cf_node_loop: {
835 nir_loop *loop = nir_cf_node_as_loop(cf_node);
836
837 /* Invalidate before cloning the copies for the loop, since the loop
838 * body can be executed more than once.
839 */
840
841 invalidate_copies_for_cf_node(state, copies, cf_node);
842
843 struct util_dynarray loop_copies;
844 util_dynarray_clone(&loop_copies, state->mem_ctx, copies);
845
846 foreach_list_typed_safe(nir_cf_node, cf_node, node, &loop->body)
847 copy_prop_vars_cf_node(state, &loop_copies, cf_node);
848
849 break;
850 }
851
852 default:
853 unreachable("Invalid CF node type");
854 }
855 }
856
857 static bool
858 nir_copy_prop_vars_impl(nir_function_impl *impl)
859 {
860 void *mem_ctx = ralloc_context(NULL);
861
862 struct copy_prop_var_state state = {
863 .impl = impl,
864 .mem_ctx = mem_ctx,
865 .lin_ctx = linear_zalloc_parent(mem_ctx, 0),
866
867 .vars_written_map = _mesa_pointer_hash_table_create(mem_ctx),
868 };
869
870 gather_vars_written(&state, NULL, &impl->cf_node);
871
872 copy_prop_vars_cf_node(&state, NULL, &impl->cf_node);
873
874 if (state.progress) {
875 nir_metadata_preserve(impl, nir_metadata_block_index |
876 nir_metadata_dominance);
877 } else {
878 #ifndef NDEBUG
879 impl->valid_metadata &= ~nir_metadata_not_properly_reset;
880 #endif
881 }
882
883 ralloc_free(mem_ctx);
884 return state.progress;
885 }
886
887 bool
888 nir_opt_copy_prop_vars(nir_shader *shader)
889 {
890 bool progress = false;
891
892 nir_foreach_function(function, shader) {
893 if (!function->impl)
894 continue;
895 progress |= nir_copy_prop_vars_impl(function->impl);
896 }
897
898 return progress;
899 }