nir: Add floating point atomic add instrinsics
[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
30 /**
31 * Variable-based copy propagation
32 *
33 * Normally, NIR trusts in SSA form for most of its copy-propagation needs.
34 * However, there are cases, especially when dealing with indirects, where SSA
35 * won't help you. This pass is for those times. Specifically, it handles
36 * the following things that the rest of NIR can't:
37 *
38 * 1) Copy-propagation on variables that have indirect access. This includes
39 * propagating from indirect stores into indirect loads.
40 *
41 * 2) Dead code elimination of store_var and copy_var intrinsics based on
42 * killed destination values.
43 *
44 * 3) 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 * Unfortunately, properly handling all of those cases makes this path rather
49 * complex. In order to avoid additional complexity, this pass is entirely
50 * block-local. If we tried to make it global, the data-flow analysis would
51 * rapidly get out of hand. Fortunately, for anything that is only ever
52 * accessed directly, we get SSA based copy-propagation which is extremely
53 * powerful so this isn't that great a loss.
54 */
55
56 struct value {
57 bool is_ssa;
58 union {
59 nir_ssa_def *ssa[4];
60 nir_deref_instr *deref;
61 };
62 };
63
64 struct copy_entry {
65 struct list_head link;
66
67 nir_instr *store_instr[4];
68
69 unsigned comps_may_be_read;
70 struct value src;
71
72 nir_deref_instr *dst;
73 };
74
75 struct copy_prop_var_state {
76 nir_shader *shader;
77
78 void *mem_ctx;
79
80 struct list_head copies;
81
82 /* We're going to be allocating and deleting a lot of copy entries so we'll
83 * keep a free list to avoid thrashing malloc too badly.
84 */
85 struct list_head copy_free_list;
86
87 bool progress;
88 };
89
90 static struct copy_entry *
91 copy_entry_create(struct copy_prop_var_state *state,
92 nir_deref_instr *dst_deref)
93 {
94 struct copy_entry *entry;
95 if (!list_empty(&state->copy_free_list)) {
96 struct list_head *item = state->copy_free_list.next;
97 list_del(item);
98 entry = LIST_ENTRY(struct copy_entry, item, link);
99 memset(entry, 0, sizeof(*entry));
100 } else {
101 entry = rzalloc(state->mem_ctx, struct copy_entry);
102 }
103
104 entry->dst = dst_deref;
105 list_add(&entry->link, &state->copies);
106
107 return entry;
108 }
109
110 static void
111 copy_entry_remove(struct copy_prop_var_state *state, struct copy_entry *entry)
112 {
113 list_del(&entry->link);
114 list_add(&entry->link, &state->copy_free_list);
115 }
116
117 static void
118 remove_dead_writes(struct copy_prop_var_state *state,
119 struct copy_entry *entry, unsigned write_mask)
120 {
121 /* We're overwriting another entry. Some of it's components may not
122 * have been read yet and, if that's the case, we may be able to delete
123 * some instructions but we have to be careful.
124 */
125 unsigned dead_comps = write_mask & ~entry->comps_may_be_read;
126
127 for (unsigned mask = dead_comps; mask;) {
128 unsigned i = u_bit_scan(&mask);
129
130 nir_instr *instr = entry->store_instr[i];
131
132 /* We may have already deleted it on a previous iteration */
133 if (!instr)
134 continue;
135
136 /* See if this instr is used anywhere that it's not dead */
137 bool keep = false;
138 for (unsigned j = 0; j < 4; j++) {
139 if (entry->store_instr[j] == instr) {
140 if (dead_comps & (1 << j)) {
141 entry->store_instr[j] = NULL;
142 } else {
143 keep = true;
144 }
145 }
146 }
147
148 if (!keep) {
149 nir_instr_remove(instr);
150 state->progress = true;
151 }
152 }
153 }
154
155 static struct copy_entry *
156 lookup_entry_for_deref(struct copy_prop_var_state *state,
157 nir_deref_instr *deref,
158 nir_deref_compare_result allowed_comparisons)
159 {
160 list_for_each_entry(struct copy_entry, iter, &state->copies, link) {
161 if (nir_compare_derefs(iter->dst, deref) & allowed_comparisons)
162 return iter;
163 }
164
165 return NULL;
166 }
167
168 static void
169 mark_aliased_entries_as_read(struct copy_prop_var_state *state,
170 nir_deref_instr *deref, unsigned components)
171 {
172 list_for_each_entry(struct copy_entry, iter, &state->copies, link) {
173 if (nir_compare_derefs(iter->dst, deref) & nir_derefs_may_alias_bit)
174 iter->comps_may_be_read |= components;
175 }
176 }
177
178 static struct copy_entry *
179 get_entry_and_kill_aliases(struct copy_prop_var_state *state,
180 nir_deref_instr *deref,
181 unsigned write_mask)
182 {
183 struct copy_entry *entry = NULL;
184 list_for_each_entry_safe(struct copy_entry, iter, &state->copies, link) {
185 if (!iter->src.is_ssa) {
186 /* If this write aliases the source of some entry, get rid of it */
187 if (nir_compare_derefs(iter->src.deref, deref) & nir_derefs_may_alias_bit) {
188 copy_entry_remove(state, iter);
189 continue;
190 }
191 }
192
193 nir_deref_compare_result comp = nir_compare_derefs(iter->dst, deref);
194 /* This is a store operation. If we completely overwrite some value, we
195 * want to delete any dead writes that may be present.
196 */
197 if (comp & nir_derefs_b_contains_a_bit)
198 remove_dead_writes(state, iter, write_mask);
199
200 if (comp & nir_derefs_equal_bit) {
201 assert(entry == NULL);
202 entry = iter;
203 } else if (comp & nir_derefs_may_alias_bit) {
204 copy_entry_remove(state, iter);
205 }
206 }
207
208 if (entry == NULL)
209 entry = copy_entry_create(state, deref);
210
211 return entry;
212 }
213
214 static void
215 apply_barrier_for_modes(struct copy_prop_var_state *state,
216 nir_variable_mode modes)
217 {
218 list_for_each_entry_safe(struct copy_entry, iter, &state->copies, link) {
219 nir_variable *dst_var = nir_deref_instr_get_variable(iter->dst);
220 nir_variable *src_var = iter->src.is_ssa ? NULL :
221 nir_deref_instr_get_variable(iter->src.deref);
222
223 if ((dst_var->data.mode & modes) ||
224 (src_var && (src_var->data.mode & modes)))
225 copy_entry_remove(state, iter);
226 }
227 }
228
229 static void
230 store_to_entry(struct copy_prop_var_state *state, struct copy_entry *entry,
231 const struct value *value, unsigned write_mask,
232 nir_instr *store_instr)
233 {
234 entry->comps_may_be_read &= ~write_mask;
235 if (value->is_ssa) {
236 entry->src.is_ssa = true;
237 /* Only overwrite the written components */
238 for (unsigned i = 0; i < 4; i++) {
239 if (write_mask & (1 << i)) {
240 entry->store_instr[i] = store_instr;
241 entry->src.ssa[i] = value->ssa[i];
242 }
243 }
244 } else {
245 /* Non-ssa stores always write everything */
246 entry->src.is_ssa = false;
247 entry->src.deref = value->deref;
248 for (unsigned i = 0; i < 4; i++)
249 entry->store_instr[i] = store_instr;
250 }
251 }
252
253 /* Do a "load" from an SSA-based entry return it in "value" as a value with a
254 * single SSA def. Because an entry could reference up to 4 different SSA
255 * defs, a vecN operation may be inserted to combine them into a single SSA
256 * def before handing it back to the caller. If the load instruction is no
257 * longer needed, it is removed and nir_instr::block is set to NULL. (It is
258 * possible, in some cases, for the load to be used in the vecN operation in
259 * which case it isn't deleted.)
260 */
261 static bool
262 load_from_ssa_entry_value(struct copy_prop_var_state *state,
263 struct copy_entry *entry,
264 nir_builder *b, nir_intrinsic_instr *intrin,
265 struct value *value)
266 {
267 *value = entry->src;
268 assert(value->is_ssa);
269
270 const struct glsl_type *type = entry->dst->type;
271 unsigned num_components = glsl_get_vector_elements(type);
272
273 nir_component_mask_t available = 0;
274 bool all_same = true;
275 for (unsigned i = 0; i < num_components; i++) {
276 if (value->ssa[i])
277 available |= (1 << i);
278
279 if (value->ssa[i] != value->ssa[0])
280 all_same = false;
281 }
282
283 if (all_same) {
284 /* Our work here is done */
285 b->cursor = nir_instr_remove(&intrin->instr);
286 intrin->instr.block = NULL;
287 return true;
288 }
289
290 if (available != (1 << num_components) - 1 &&
291 intrin->intrinsic == nir_intrinsic_load_deref &&
292 (available & nir_ssa_def_components_read(&intrin->dest.ssa)) == 0) {
293 /* If none of the components read are available as SSA values, then we
294 * should just bail. Otherwise, we would end up replacing the uses of
295 * the load_deref a vecN() that just gathers up its components.
296 */
297 return false;
298 }
299
300 b->cursor = nir_after_instr(&intrin->instr);
301
302 nir_ssa_def *load_def =
303 intrin->intrinsic == nir_intrinsic_load_deref ? &intrin->dest.ssa : NULL;
304
305 bool keep_intrin = false;
306 nir_ssa_def *comps[NIR_MAX_VEC_COMPONENTS];
307 for (unsigned i = 0; i < num_components; i++) {
308 if (value->ssa[i]) {
309 comps[i] = nir_channel(b, value->ssa[i], i);
310 } else {
311 /* We don't have anything for this component in our
312 * list. Just re-use a channel from the load.
313 */
314 if (load_def == NULL)
315 load_def = nir_load_deref(b, entry->dst);
316
317 if (load_def->parent_instr == &intrin->instr)
318 keep_intrin = true;
319
320 comps[i] = nir_channel(b, load_def, i);
321 }
322 }
323
324 nir_ssa_def *vec = nir_vec(b, comps, num_components);
325 for (unsigned i = 0; i < num_components; i++)
326 value->ssa[i] = vec;
327
328 if (!keep_intrin) {
329 /* Removing this instruction should not touch the cursor because we
330 * created the cursor after the intrinsic and have added at least one
331 * instruction (the vec) since then.
332 */
333 assert(b->cursor.instr != &intrin->instr);
334 nir_instr_remove(&intrin->instr);
335 intrin->instr.block = NULL;
336 }
337
338 return true;
339 }
340
341 /**
342 * Specialize the wildcards in a deref chain
343 *
344 * This function returns a deref chain identical to \param deref except that
345 * some of its wildcards are replaced with indices from \param specific. The
346 * process is guided by \param guide which references the same type as \param
347 * specific but has the same wildcard array lengths as \param deref.
348 */
349 static nir_deref_instr *
350 specialize_wildcards(nir_builder *b,
351 nir_deref_path *deref,
352 nir_deref_path *guide,
353 nir_deref_path *specific)
354 {
355 nir_deref_instr **deref_p = &deref->path[1];
356 nir_deref_instr **guide_p = &guide->path[1];
357 nir_deref_instr **spec_p = &specific->path[1];
358 nir_deref_instr *ret_tail = deref->path[0];
359 for (; *deref_p; deref_p++) {
360 if ((*deref_p)->deref_type == nir_deref_type_array_wildcard) {
361 /* This is where things get tricky. We have to search through
362 * the entry deref to find its corresponding wildcard and fill
363 * this slot in with the value from the src.
364 */
365 while (*guide_p &&
366 (*guide_p)->deref_type != nir_deref_type_array_wildcard) {
367 guide_p++;
368 spec_p++;
369 }
370 assert(*guide_p && *spec_p);
371
372 ret_tail = nir_build_deref_follower(b, ret_tail, *spec_p);
373
374 guide_p++;
375 spec_p++;
376 } else {
377 ret_tail = nir_build_deref_follower(b, ret_tail, *deref_p);
378 }
379 }
380
381 return ret_tail;
382 }
383
384 /* Do a "load" from an deref-based entry return it in "value" as a value. The
385 * deref returned in "value" will always be a fresh copy so the caller can
386 * steal it and assign it to the instruction directly without copying it
387 * again.
388 */
389 static bool
390 load_from_deref_entry_value(struct copy_prop_var_state *state,
391 struct copy_entry *entry,
392 nir_builder *b, nir_intrinsic_instr *intrin,
393 nir_deref_instr *src, struct value *value)
394 {
395 *value = entry->src;
396
397 b->cursor = nir_instr_remove(&intrin->instr);
398
399 nir_deref_path entry_dst_path, src_path;
400 nir_deref_path_init(&entry_dst_path, entry->dst, state->mem_ctx);
401 nir_deref_path_init(&src_path, src, state->mem_ctx);
402
403 bool need_to_specialize_wildcards = false;
404 nir_deref_instr **entry_p = &entry_dst_path.path[1];
405 nir_deref_instr **src_p = &src_path.path[1];
406 while (*entry_p && *src_p) {
407 nir_deref_instr *entry_tail = *entry_p++;
408 nir_deref_instr *src_tail = *src_p++;
409
410 if (src_tail->deref_type == nir_deref_type_array &&
411 entry_tail->deref_type == nir_deref_type_array_wildcard)
412 need_to_specialize_wildcards = true;
413 }
414
415 /* If the entry deref is longer than the source deref then it refers to a
416 * smaller type and we can't source from it.
417 */
418 assert(*entry_p == NULL);
419
420 if (need_to_specialize_wildcards) {
421 /* The entry has some wildcards that are not in src. This means we need
422 * to construct a new deref based on the entry but using the wildcards
423 * from the source and guided by the entry dst. Oof.
424 */
425 nir_deref_path entry_src_path;
426 nir_deref_path_init(&entry_src_path, entry->src.deref, state->mem_ctx);
427 value->deref = specialize_wildcards(b, &entry_src_path,
428 &entry_dst_path, &src_path);
429 nir_deref_path_finish(&entry_src_path);
430 }
431
432 /* If our source deref is longer than the entry deref, that's ok because
433 * it just means the entry deref needs to be extended a bit.
434 */
435 while (*src_p) {
436 nir_deref_instr *src_tail = *src_p++;
437 value->deref = nir_build_deref_follower(b, value->deref, src_tail);
438 }
439
440 nir_deref_path_finish(&entry_dst_path);
441 nir_deref_path_finish(&src_path);
442
443 return true;
444 }
445
446 static bool
447 try_load_from_entry(struct copy_prop_var_state *state, struct copy_entry *entry,
448 nir_builder *b, nir_intrinsic_instr *intrin,
449 nir_deref_instr *src, struct value *value)
450 {
451 if (entry == NULL)
452 return false;
453
454 if (entry->src.is_ssa) {
455 return load_from_ssa_entry_value(state, entry, b, intrin, value);
456 } else {
457 return load_from_deref_entry_value(state, entry, b, intrin, src, value);
458 }
459 }
460
461 static void
462 copy_prop_vars_block(struct copy_prop_var_state *state,
463 nir_builder *b, nir_block *block)
464 {
465 /* Start each block with a blank slate */
466 list_for_each_entry_safe(struct copy_entry, iter, &state->copies, link)
467 copy_entry_remove(state, iter);
468
469 nir_foreach_instr_safe(instr, block) {
470 if (instr->type != nir_instr_type_intrinsic)
471 continue;
472
473 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
474 switch (intrin->intrinsic) {
475 case nir_intrinsic_barrier:
476 case nir_intrinsic_memory_barrier:
477 /* If we hit a barrier, we need to trash everything that may possibly
478 * be accessible to another thread. Locals, globals, and things of
479 * the like are safe, however.
480 */
481 apply_barrier_for_modes(state, ~(nir_var_local | nir_var_global |
482 nir_var_shader_in | nir_var_uniform));
483 break;
484
485 case nir_intrinsic_emit_vertex:
486 case nir_intrinsic_emit_vertex_with_counter:
487 apply_barrier_for_modes(state, nir_var_shader_out);
488 break;
489
490 case nir_intrinsic_load_deref: {
491 nir_deref_instr *src = nir_src_as_deref(intrin->src[0]);
492
493 uint8_t comps_read = nir_ssa_def_components_read(&intrin->dest.ssa);
494 mark_aliased_entries_as_read(state, src, comps_read);
495
496 struct copy_entry *src_entry =
497 lookup_entry_for_deref(state, src, nir_derefs_a_contains_b_bit);
498 struct value value;
499 if (try_load_from_entry(state, src_entry, b, intrin, src, &value)) {
500 if (value.is_ssa) {
501 /* lookup_load has already ensured that we get a single SSA
502 * value that has all of the channels. We just have to do the
503 * rewrite operation.
504 */
505 if (intrin->instr.block) {
506 /* The lookup left our instruction in-place. This means it
507 * must have used it to vec up a bunch of different sources.
508 * We need to be careful when rewriting uses so we don't
509 * rewrite the vecN itself.
510 */
511 nir_ssa_def_rewrite_uses_after(&intrin->dest.ssa,
512 nir_src_for_ssa(value.ssa[0]),
513 value.ssa[0]->parent_instr);
514 } else {
515 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
516 nir_src_for_ssa(value.ssa[0]));
517 }
518 } else {
519 /* We're turning it into a load of a different variable */
520 intrin->src[0] = nir_src_for_ssa(&value.deref->dest.ssa);
521
522 /* Put it back in again. */
523 nir_builder_instr_insert(b, instr);
524
525 value.is_ssa = true;
526 for (unsigned i = 0; i < intrin->num_components; i++)
527 value.ssa[i] = &intrin->dest.ssa;
528 }
529 state->progress = true;
530 } else {
531 value.is_ssa = true;
532 for (unsigned i = 0; i < intrin->num_components; i++)
533 value.ssa[i] = &intrin->dest.ssa;
534 }
535
536 /* Now that we have a value, we're going to store it back so that we
537 * have the right value next time we come looking for it. In order
538 * to do this, we need an exact match, not just something that
539 * contains what we're looking for.
540 */
541 struct copy_entry *store_entry =
542 lookup_entry_for_deref(state, src, nir_derefs_equal_bit);
543 if (!store_entry)
544 store_entry = copy_entry_create(state, src);
545
546 /* Set up a store to this entry with the value of the load. This way
547 * we can potentially remove subsequent loads. However, we use a
548 * NULL instruction so we don't try and delete the load on a
549 * subsequent store.
550 */
551 store_to_entry(state, store_entry, &value,
552 ((1 << intrin->num_components) - 1), NULL);
553 break;
554 }
555
556 case nir_intrinsic_store_deref: {
557 struct value value = {
558 .is_ssa = true
559 };
560
561 for (unsigned i = 0; i < intrin->num_components; i++)
562 value.ssa[i] = intrin->src[1].ssa;
563
564 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
565 unsigned wrmask = nir_intrinsic_write_mask(intrin);
566 struct copy_entry *entry =
567 get_entry_and_kill_aliases(state, dst, wrmask);
568 store_to_entry(state, entry, &value, wrmask, &intrin->instr);
569 break;
570 }
571
572 case nir_intrinsic_copy_deref: {
573 nir_deref_instr *dst = nir_src_as_deref(intrin->src[0]);
574 nir_deref_instr *src = nir_src_as_deref(intrin->src[1]);
575
576 if (nir_compare_derefs(src, dst) & nir_derefs_equal_bit) {
577 /* This is a no-op self-copy. Get rid of it */
578 nir_instr_remove(instr);
579 continue;
580 }
581
582 mark_aliased_entries_as_read(state, src, 0xf);
583
584 struct copy_entry *src_entry =
585 lookup_entry_for_deref(state, src, nir_derefs_a_contains_b_bit);
586 struct value value;
587 if (try_load_from_entry(state, src_entry, b, intrin, src, &value)) {
588 if (value.is_ssa) {
589 nir_store_deref(b, dst, value.ssa[0], 0xf);
590 intrin = nir_instr_as_intrinsic(nir_builder_last_instr(b));
591 } else {
592 /* If this would be a no-op self-copy, don't bother. */
593 if (nir_compare_derefs(value.deref, dst) & nir_derefs_equal_bit)
594 continue;
595
596 /* Just turn it into a copy of a different deref */
597 intrin->src[1] = nir_src_for_ssa(&value.deref->dest.ssa);
598
599 /* Put it back in again. */
600 nir_builder_instr_insert(b, instr);
601 }
602
603 state->progress = true;
604 } else {
605 value = (struct value) {
606 .is_ssa = false,
607 { .deref = src },
608 };
609 }
610
611 struct copy_entry *dst_entry =
612 get_entry_and_kill_aliases(state, dst, 0xf);
613 store_to_entry(state, dst_entry, &value, 0xf, &intrin->instr);
614 break;
615 }
616
617 default:
618 break;
619 }
620 }
621 }
622
623 bool
624 nir_opt_copy_prop_vars(nir_shader *shader)
625 {
626 struct copy_prop_var_state state;
627
628 state.shader = shader;
629 state.mem_ctx = ralloc_context(NULL);
630 list_inithead(&state.copies);
631 list_inithead(&state.copy_free_list);
632
633 bool global_progress = false;
634 nir_foreach_function(function, shader) {
635 if (!function->impl)
636 continue;
637
638 nir_builder b;
639 nir_builder_init(&b, function->impl);
640
641 state.progress = false;
642 nir_foreach_block(block, function->impl)
643 copy_prop_vars_block(&state, &b, block);
644
645 if (state.progress) {
646 nir_metadata_preserve(function->impl, nir_metadata_block_index |
647 nir_metadata_dominance);
648 global_progress = true;
649 }
650 }
651
652 ralloc_free(state.mem_ctx);
653
654 return global_progress;
655 }