• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2014 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_instr_set.h"
26 
27 /*
28  * Implements Global Code Motion.  A description of GCM can be found in
29  * "Global Code Motion; Global Value Numbering" by Cliff Click.
30  * Unfortunately, the algorithm presented in the paper is broken in a
31  * number of ways.  The algorithm used here differs substantially from the
32  * one in the paper but it is, in my opinion, much easier to read and
33  * verify correcness.
34  */
35 
36 /* This is used to stop GCM moving instruction out of a loop if the loop
37  * contains too many instructions and moving them would create excess spilling.
38  *
39  * TODO: Figure out a better way to decide if we should remove instructions from
40  * a loop.
41  */
42 #define MAX_LOOP_INSTRUCTIONS 100
43 
44 struct gcm_block_info {
45    /* Number of loops this block is inside */
46    unsigned loop_depth;
47 
48    /* Number of ifs this block is inside */
49    unsigned if_depth;
50 
51    unsigned loop_instr_count;
52 
53    /* The loop the block is nested inside or NULL */
54    nir_loop *loop;
55 
56    /* The last instruction inserted into this block.  This is used as we
57     * traverse the instructions and insert them back into the program to
58     * put them in the right order.
59     */
60    nir_instr *last_instr;
61 };
62 
63 struct gcm_instr_info {
64    nir_block *early_block;
65 };
66 
67 /* Flags used in the instr->pass_flags field for various instruction states */
68 enum {
69    GCM_INSTR_PINNED = (1 << 0),
70    GCM_INSTR_SCHEDULE_EARLIER_ONLY = (1 << 1),
71    GCM_INSTR_SCHEDULED_EARLY = (1 << 2),
72    GCM_INSTR_SCHEDULED_LATE = (1 << 3),
73    GCM_INSTR_PLACED = (1 << 4),
74 };
75 
76 struct gcm_state {
77    nir_function_impl *impl;
78    nir_instr *instr;
79 
80    bool progress;
81 
82    /* The list of non-pinned instructions.  As we do the late scheduling,
83     * we pull non-pinned instructions out of their blocks and place them in
84     * this list.  This saves us from having linked-list problems when we go
85     * to put instructions back in their blocks.
86     */
87    struct exec_list instrs;
88 
89    struct gcm_block_info *blocks;
90 
91    unsigned num_instrs;
92    struct gcm_instr_info *instr_infos;
93 };
94 
95 static unsigned
get_loop_instr_count(struct exec_list * cf_list)96 get_loop_instr_count(struct exec_list *cf_list)
97 {
98    unsigned loop_instr_count = 0;
99    foreach_list_typed(nir_cf_node, node, node, cf_list) {
100       switch (node->type) {
101       case nir_cf_node_block: {
102          nir_block *block = nir_cf_node_as_block(node);
103          nir_foreach_instr(instr, block) {
104             loop_instr_count++;
105          }
106          break;
107       }
108       case nir_cf_node_if: {
109          nir_if *if_stmt = nir_cf_node_as_if(node);
110          loop_instr_count += get_loop_instr_count(&if_stmt->then_list);
111          loop_instr_count += get_loop_instr_count(&if_stmt->else_list);
112          break;
113       }
114       case nir_cf_node_loop: {
115          nir_loop *loop = nir_cf_node_as_loop(node);
116          assert(!nir_loop_has_continue_construct(loop));
117          loop_instr_count += get_loop_instr_count(&loop->body);
118          break;
119       }
120       default:
121          unreachable("Invalid CF node type");
122       }
123    }
124 
125    return loop_instr_count;
126 }
127 
128 /* Recursively walks the CFG and builds the block_info structure */
129 static void
gcm_build_block_info(struct exec_list * cf_list,struct gcm_state * state,nir_loop * loop,unsigned loop_depth,unsigned if_depth,unsigned loop_instr_count)130 gcm_build_block_info(struct exec_list *cf_list, struct gcm_state *state,
131                      nir_loop *loop, unsigned loop_depth, unsigned if_depth,
132                      unsigned loop_instr_count)
133 {
134    foreach_list_typed(nir_cf_node, node, node, cf_list) {
135       switch (node->type) {
136       case nir_cf_node_block: {
137          nir_block *block = nir_cf_node_as_block(node);
138          state->blocks[block->index].if_depth = if_depth;
139          state->blocks[block->index].loop_depth = loop_depth;
140          state->blocks[block->index].loop_instr_count = loop_instr_count;
141          state->blocks[block->index].loop = loop;
142          break;
143       }
144       case nir_cf_node_if: {
145          nir_if *if_stmt = nir_cf_node_as_if(node);
146          gcm_build_block_info(&if_stmt->then_list, state, loop, loop_depth,
147                               if_depth + 1, ~0u);
148          gcm_build_block_info(&if_stmt->else_list, state, loop, loop_depth,
149                               if_depth + 1, ~0u);
150          break;
151       }
152       case nir_cf_node_loop: {
153          nir_loop *loop = nir_cf_node_as_loop(node);
154          assert(!nir_loop_has_continue_construct(loop));
155          gcm_build_block_info(&loop->body, state, loop, loop_depth + 1, if_depth,
156                               get_loop_instr_count(&loop->body));
157          break;
158       }
159       default:
160          unreachable("Invalid CF node type");
161       }
162    }
163 }
164 
165 static bool
is_src_scalarizable(nir_src * src)166 is_src_scalarizable(nir_src *src)
167 {
168 
169    nir_instr *src_instr = src->ssa->parent_instr;
170    switch (src_instr->type) {
171    case nir_instr_type_alu: {
172       nir_alu_instr *src_alu = nir_instr_as_alu(src_instr);
173 
174       /* ALU operations with output_size == 0 should be scalarized.  We
175        * will also see a bunch of vecN operations from scalarizing ALU
176        * operations and, since they can easily be copy-propagated, they
177        * are ok too.
178        */
179       return nir_op_infos[src_alu->op].output_size == 0 ||
180              src_alu->op == nir_op_vec2 ||
181              src_alu->op == nir_op_vec3 ||
182              src_alu->op == nir_op_vec4;
183    }
184 
185    case nir_instr_type_load_const:
186       /* These are trivially scalarizable */
187       return true;
188 
189    case nir_instr_type_undef:
190       return true;
191 
192    case nir_instr_type_intrinsic: {
193       nir_intrinsic_instr *src_intrin = nir_instr_as_intrinsic(src_instr);
194 
195       switch (src_intrin->intrinsic) {
196       case nir_intrinsic_load_deref: {
197          /* Don't scalarize if we see a load of a local variable because it
198           * might turn into one of the things we can't scalarize.
199           */
200          nir_deref_instr *deref = nir_src_as_deref(src_intrin->src[0]);
201          return !nir_deref_mode_may_be(deref, (nir_var_function_temp |
202                                                nir_var_shader_temp));
203       }
204 
205       case nir_intrinsic_interp_deref_at_centroid:
206       case nir_intrinsic_interp_deref_at_sample:
207       case nir_intrinsic_interp_deref_at_offset:
208       case nir_intrinsic_load_uniform:
209       case nir_intrinsic_load_ubo:
210       case nir_intrinsic_load_ssbo:
211       case nir_intrinsic_load_global:
212       case nir_intrinsic_load_global_constant:
213       case nir_intrinsic_load_input:
214          return true;
215       default:
216          break;
217       }
218 
219       return false;
220    }
221 
222    default:
223       /* We can't scalarize this type of instruction */
224       return false;
225    }
226 }
227 
228 static bool
is_binding_uniform(nir_src src)229 is_binding_uniform(nir_src src)
230 {
231    nir_binding binding = nir_chase_binding(src);
232    if (!binding.success)
233       return false;
234 
235    for (unsigned i = 0; i < binding.num_indices; i++) {
236       if (!nir_src_is_always_uniform(binding.indices[i]))
237          return false;
238    }
239 
240    return true;
241 }
242 
243 static void
pin_intrinsic(nir_intrinsic_instr * intrin)244 pin_intrinsic(nir_intrinsic_instr *intrin)
245 {
246    nir_instr *instr = &intrin->instr;
247 
248    if (!nir_intrinsic_can_reorder(intrin)) {
249       instr->pass_flags = GCM_INSTR_PINNED;
250       return;
251    }
252 
253    instr->pass_flags = 0;
254 
255    /* If the intrinsic requires a uniform source, we can't safely move it across non-uniform
256     * control flow if it's not uniform at the point it's defined.
257     * Stores and atomics can never be re-ordered, so we don't have to consider them here.
258     */
259    bool non_uniform = nir_intrinsic_has_access(intrin) &&
260                       (nir_intrinsic_access(intrin) & ACCESS_NON_UNIFORM);
261    if (!non_uniform &&
262        (intrin->intrinsic == nir_intrinsic_load_ubo ||
263         intrin->intrinsic == nir_intrinsic_load_ssbo ||
264         intrin->intrinsic == nir_intrinsic_get_ubo_size ||
265         intrin->intrinsic == nir_intrinsic_get_ssbo_size ||
266         nir_intrinsic_has_image_dim(intrin) ||
267         ((intrin->intrinsic == nir_intrinsic_load_deref ||
268           intrin->intrinsic == nir_intrinsic_deref_buffer_array_length) &&
269          nir_deref_mode_may_be(nir_src_as_deref(intrin->src[0]),
270                                nir_var_mem_ubo | nir_var_mem_ssbo)))) {
271       if (!is_binding_uniform(intrin->src[0]))
272          instr->pass_flags = GCM_INSTR_PINNED;
273    } else if (intrin->intrinsic == nir_intrinsic_load_push_constant) {
274       if (!nir_src_is_always_uniform(intrin->src[0]))
275          instr->pass_flags = GCM_INSTR_PINNED;
276    } else if (intrin->intrinsic == nir_intrinsic_load_deref &&
277               nir_deref_mode_is(nir_src_as_deref(intrin->src[0]),
278                                 nir_var_mem_push_const)) {
279       nir_deref_instr *deref = nir_src_as_deref(intrin->src[0]);
280       while (deref->deref_type != nir_deref_type_var) {
281          if ((deref->deref_type == nir_deref_type_array ||
282               deref->deref_type == nir_deref_type_ptr_as_array) &&
283              !nir_src_is_always_uniform(deref->arr.index)) {
284             instr->pass_flags = GCM_INSTR_PINNED;
285             return;
286          }
287          deref = nir_deref_instr_parent(deref);
288          if (!deref) {
289             instr->pass_flags = GCM_INSTR_PINNED;
290             return;
291          }
292       }
293    }
294 }
295 
296 /* Walks the instruction list and marks immovable instructions as pinned or
297  * placed.
298  *
299  * This function also serves to initialize the instr->pass_flags field.
300  * After this is completed, all instructions' pass_flags fields will be set
301  * to either GCM_INSTR_PINNED, GCM_INSTR_PLACED or 0.
302  */
303 static void
gcm_pin_instructions(nir_function_impl * impl,struct gcm_state * state)304 gcm_pin_instructions(nir_function_impl *impl, struct gcm_state *state)
305 {
306    state->num_instrs = 0;
307 
308    nir_foreach_block(block, impl) {
309       nir_foreach_instr_safe(instr, block) {
310          /* Index the instructions for use in gcm_state::instrs */
311          instr->index = state->num_instrs++;
312 
313          switch (instr->type) {
314          case nir_instr_type_alu: {
315             nir_alu_instr *alu = nir_instr_as_alu(instr);
316 
317             if (nir_op_is_derivative(alu->op)) {
318                /* These can only go in uniform control flow */
319                instr->pass_flags = GCM_INSTR_SCHEDULE_EARLIER_ONLY;
320             } else if (alu->op == nir_op_mov &&
321                        !is_src_scalarizable(&alu->src[0].src)) {
322                instr->pass_flags = GCM_INSTR_PINNED;
323             } else {
324                instr->pass_flags = 0;
325             }
326             break;
327          }
328 
329          case nir_instr_type_tex: {
330             nir_tex_instr *tex = nir_instr_as_tex(instr);
331             if (nir_tex_instr_has_implicit_derivative(tex))
332                instr->pass_flags = GCM_INSTR_SCHEDULE_EARLIER_ONLY;
333 
334             for (unsigned i = 0; i < tex->num_srcs; i++) {
335                nir_tex_src *src = &tex->src[i];
336                switch (src->src_type) {
337                case nir_tex_src_texture_deref:
338                   if (!tex->texture_non_uniform && !is_binding_uniform(src->src))
339                      instr->pass_flags = GCM_INSTR_PINNED;
340                   break;
341                case nir_tex_src_sampler_deref:
342                   if (!tex->sampler_non_uniform && !is_binding_uniform(src->src))
343                      instr->pass_flags = GCM_INSTR_PINNED;
344                   break;
345                case nir_tex_src_texture_offset:
346                case nir_tex_src_texture_handle:
347                   if (!tex->texture_non_uniform && !nir_src_is_always_uniform(src->src))
348                      instr->pass_flags = GCM_INSTR_PINNED;
349                   break;
350                case nir_tex_src_sampler_offset:
351                case nir_tex_src_sampler_handle:
352                   if (!tex->sampler_non_uniform && !nir_src_is_always_uniform(src->src))
353                      instr->pass_flags = GCM_INSTR_PINNED;
354                   break;
355                default:
356                   break;
357                }
358             }
359             break;
360          }
361 
362          case nir_instr_type_deref:
363          case nir_instr_type_load_const:
364             instr->pass_flags = 0;
365             break;
366 
367          case nir_instr_type_intrinsic:
368             pin_intrinsic(nir_instr_as_intrinsic(instr));
369             break;
370 
371          case nir_instr_type_call:
372             instr->pass_flags = GCM_INSTR_PINNED;
373             break;
374 
375          case nir_instr_type_jump:
376          case nir_instr_type_undef:
377          case nir_instr_type_phi:
378             instr->pass_flags = GCM_INSTR_PLACED;
379             break;
380 
381          default:
382             unreachable("Invalid instruction type in GCM");
383          }
384 
385          if (!(instr->pass_flags & GCM_INSTR_PLACED)) {
386             /* If this is an unplaced instruction, go ahead and pull it out of
387              * the program and put it on the instrs list.  This has a couple
388              * of benifits.  First, it makes the scheduling algorithm more
389              * efficient because we can avoid walking over basic blocks.
390              * Second, it keeps us from causing linked list confusion when
391              * we're trying to put everything in its proper place at the end
392              * of the pass.
393              *
394              * Note that we don't use nir_instr_remove here because that also
395              * cleans up uses and defs and we want to keep that information.
396              */
397             exec_node_remove(&instr->node);
398             exec_list_push_tail(&state->instrs, &instr->node);
399          }
400       }
401    }
402 }
403 
404 static void
405 gcm_schedule_early_instr(nir_instr *instr, struct gcm_state *state);
406 
407 /** Update an instructions schedule for the given source
408  *
409  * This function is called iteratively as we walk the sources of an
410  * instruction.  It ensures that the given source instruction has been
411  * scheduled and then update this instruction's block if the source
412  * instruction is lower down the tree.
413  */
414 static bool
gcm_schedule_early_src(nir_src * src,void * void_state)415 gcm_schedule_early_src(nir_src *src, void *void_state)
416 {
417    struct gcm_state *state = void_state;
418    nir_instr *instr = state->instr;
419 
420    gcm_schedule_early_instr(src->ssa->parent_instr, void_state);
421 
422    /* While the index isn't a proper dominance depth, it does have the
423     * property that if A dominates B then A->index <= B->index.  Since we
424     * know that this instruction must have been dominated by all of its
425     * sources at some point (even if it's gone through value-numbering),
426     * all of the sources must lie on the same branch of the dominance tree.
427     * Therefore, we can just go ahead and just compare indices.
428     */
429    struct gcm_instr_info *src_info =
430       &state->instr_infos[src->ssa->parent_instr->index];
431    struct gcm_instr_info *info = &state->instr_infos[instr->index];
432    if (info->early_block->index < src_info->early_block->index)
433       info->early_block = src_info->early_block;
434 
435    /* We need to restore the state instruction because it may have been
436     * changed through the gcm_schedule_early_instr call above.  Since we
437     * may still be iterating through sources and future calls to
438     * gcm_schedule_early_src for the same instruction will still need it.
439     */
440    state->instr = instr;
441 
442    return true;
443 }
444 
445 /** Schedules an instruction early
446  *
447  * This function performs a recursive depth-first search starting at the
448  * given instruction and proceeding through the sources to schedule
449  * instructions as early as they can possibly go in the dominance tree.
450  * The instructions are "scheduled" by updating the early_block field of
451  * the corresponding gcm_instr_state entry.
452  */
453 static void
gcm_schedule_early_instr(nir_instr * instr,struct gcm_state * state)454 gcm_schedule_early_instr(nir_instr *instr, struct gcm_state *state)
455 {
456    if (instr->pass_flags & GCM_INSTR_SCHEDULED_EARLY)
457       return;
458 
459    instr->pass_flags |= GCM_INSTR_SCHEDULED_EARLY;
460 
461    /* Pinned/placed instructions always get scheduled in their original block so
462     * we don't need to do anything.  Also, bailing here keeps us from ever
463     * following the sources of phi nodes which can be back-edges.
464     */
465    if (instr->pass_flags & GCM_INSTR_PINNED ||
466        instr->pass_flags & GCM_INSTR_PLACED) {
467       state->instr_infos[instr->index].early_block = instr->block;
468       return;
469    }
470 
471    /* Start with the instruction at the top.  As we iterate over the
472     * sources, it will get moved down as needed.
473     */
474    state->instr_infos[instr->index].early_block = nir_start_block(state->impl);
475    state->instr = instr;
476 
477    nir_foreach_src(instr, gcm_schedule_early_src, state);
478 }
479 
480 static bool
set_block_for_loop_instr(struct gcm_state * state,nir_instr * instr,nir_block * block)481 set_block_for_loop_instr(struct gcm_state *state, nir_instr *instr,
482                          nir_block *block)
483 {
484    /* If the instruction wasn't in a loop to begin with we don't want to push
485     * it down into one.
486     */
487    nir_loop *loop = state->blocks[instr->block->index].loop;
488    if (loop == NULL)
489       return true;
490 
491    assert(!nir_loop_has_continue_construct(loop));
492    if (nir_block_dominates(instr->block, block))
493       return true;
494 
495    /* If the loop only executes a single time i.e its wrapped in a:
496     *    do{ ... break; } while(true)
497     * Don't move the instruction as it will not help anything.
498     */
499    if (loop->info->limiting_terminator == NULL && !loop->info->complex_loop &&
500        nir_block_ends_in_break(nir_loop_last_block(loop)))
501       return false;
502 
503    /* Being too aggressive with how we pull instructions out of loops can
504     * result in extra register pressure and spilling. For example its fairly
505     * common for loops in compute shaders to calculate SSBO offsets using
506     * the workgroup id, subgroup id and subgroup invocation, pulling all
507     * these calculations outside the loop causes register pressure.
508     *
509     * To work around these issues for now we only allow constant and texture
510     * instructions to be moved outside their original loops, or instructions
511     * where the total loop instruction count is less than
512     * MAX_LOOP_INSTRUCTIONS.
513     *
514     * TODO: figure out some more heuristics to allow more to be moved out of
515     * loops.
516     */
517    if (state->blocks[instr->block->index].loop_instr_count < MAX_LOOP_INSTRUCTIONS)
518       return true;
519 
520    if (instr->type == nir_instr_type_load_const ||
521        instr->type == nir_instr_type_tex ||
522        (instr->type == nir_instr_type_intrinsic &&
523         nir_instr_as_intrinsic(instr)->intrinsic == nir_intrinsic_resource_intel))
524       return true;
525 
526    return false;
527 }
528 
529 static bool
set_block_to_if_block(struct gcm_state * state,nir_instr * instr,nir_block * block)530 set_block_to_if_block(struct gcm_state *state, nir_instr *instr,
531                       nir_block *block)
532 {
533    if (instr->type == nir_instr_type_load_const)
534       return true;
535 
536    if (instr->type == nir_instr_type_intrinsic &&
537        nir_instr_as_intrinsic(instr)->intrinsic == nir_intrinsic_resource_intel)
538       return true;
539 
540    /* TODO: Figure out some more heuristics to allow more to be moved into
541     * if-statements.
542     */
543 
544    return false;
545 }
546 
547 static nir_block *
gcm_choose_block_for_instr(nir_instr * instr,nir_block * early_block,nir_block * late_block,struct gcm_state * state)548 gcm_choose_block_for_instr(nir_instr *instr, nir_block *early_block,
549                            nir_block *late_block, struct gcm_state *state)
550 {
551    assert(nir_block_dominates(early_block, late_block));
552 
553    bool block_set = false;
554 
555    /* First see if we can push the instruction down into an if-statements block */
556    nir_block *best = late_block;
557    for (nir_block *block = late_block; block != NULL; block = block->imm_dom) {
558       if (state->blocks[block->index].loop_depth >
559           state->blocks[instr->block->index].loop_depth)
560          continue;
561 
562       if (state->blocks[block->index].if_depth >=
563              state->blocks[best->index].if_depth &&
564           set_block_to_if_block(state, instr, block)) {
565          /* If we are pushing the instruction into an if we want it to be
566           * in the earliest block not the latest to avoid creating register
567           * pressure issues. So we don't break unless we come across the
568           * block the instruction was originally in.
569           */
570          best = block;
571          block_set = true;
572          if (block == instr->block)
573             break;
574       } else if (block == instr->block) {
575          /* If we couldn't push the instruction later just put is back where it
576           * was previously.
577           */
578          if (!block_set)
579             best = block;
580          break;
581       }
582 
583       if (block == early_block)
584          break;
585    }
586 
587    /* Now see if we can evict the instruction from a loop */
588    for (nir_block *block = late_block; block != NULL; block = block->imm_dom) {
589       if (state->blocks[block->index].loop_depth <
590           state->blocks[best->index].loop_depth) {
591          if (set_block_for_loop_instr(state, instr, block)) {
592             best = block;
593          } else if (block == instr->block) {
594             if (!block_set)
595                best = block;
596             break;
597          }
598       }
599 
600       if (block == early_block)
601          break;
602    }
603 
604    return best;
605 }
606 
607 static void
608 gcm_schedule_late_instr(nir_instr *instr, struct gcm_state *state);
609 
610 /** Schedules the instruction associated with the given SSA def late
611  *
612  * This function works by first walking all of the uses of the given SSA
613  * definition, ensuring that they are scheduled, and then computing the LCA
614  * (least common ancestor) of its uses.  It then schedules this instruction
615  * as close to the LCA as possible while trying to stay out of loops.
616  */
617 static bool
gcm_schedule_late_def(nir_def * def,void * void_state)618 gcm_schedule_late_def(nir_def *def, void *void_state)
619 {
620    struct gcm_state *state = void_state;
621 
622    nir_block *lca = NULL;
623 
624    nir_foreach_use(use_src, def) {
625       nir_instr *use_instr = nir_src_parent_instr(use_src);
626 
627       gcm_schedule_late_instr(use_instr, state);
628 
629       /* Phi instructions are a bit special.  SSA definitions don't have to
630        * dominate the sources of the phi nodes that use them; instead, they
631        * have to dominate the predecessor block corresponding to the phi
632        * source.  We handle this by looking through the sources, finding
633        * any that are usingg this SSA def, and using those blocks instead
634        * of the one the phi lives in.
635        */
636       if (use_instr->type == nir_instr_type_phi) {
637          nir_phi_instr *phi = nir_instr_as_phi(use_instr);
638 
639          nir_foreach_phi_src(phi_src, phi) {
640             if (phi_src->src.ssa == def)
641                lca = nir_dominance_lca(lca, phi_src->pred);
642          }
643       } else {
644          lca = nir_dominance_lca(lca, use_instr->block);
645       }
646    }
647 
648    nir_foreach_if_use(use_src, def) {
649       nir_if *if_stmt = nir_src_parent_if(use_src);
650 
651       /* For if statements, we consider the block to be the one immediately
652        * preceding the if CF node.
653        */
654       nir_block *pred_block =
655          nir_cf_node_as_block(nir_cf_node_prev(&if_stmt->cf_node));
656 
657       lca = nir_dominance_lca(lca, pred_block);
658    }
659 
660    nir_block *early_block =
661       state->instr_infos[def->parent_instr->index].early_block;
662 
663    /* Some instructions may never be used.  Flag them and the instruction
664     * placement code will get rid of them for us.
665     */
666    if (lca == NULL) {
667       def->parent_instr->block = NULL;
668       return true;
669    }
670 
671    if (def->parent_instr->pass_flags & GCM_INSTR_SCHEDULE_EARLIER_ONLY &&
672        lca != def->parent_instr->block &&
673        nir_block_dominates(def->parent_instr->block, lca)) {
674       lca = def->parent_instr->block;
675    }
676 
677    /* We now have the LCA of all of the uses.  If our invariants hold,
678     * this is dominated by the block that we chose when scheduling early.
679     * We now walk up the dominance tree and pick the lowest block that is
680     * as far outside loops as we can get.
681     */
682    nir_block *best_block =
683       gcm_choose_block_for_instr(def->parent_instr, early_block, lca, state);
684 
685    if (def->parent_instr->block != best_block)
686       state->progress = true;
687 
688    def->parent_instr->block = best_block;
689 
690    return true;
691 }
692 
693 /** Schedules an instruction late
694  *
695  * This function performs a depth-first search starting at the given
696  * instruction and proceeding through its uses to schedule instructions as
697  * late as they can reasonably go in the dominance tree.  The instructions
698  * are "scheduled" by updating their instr->block field.
699  *
700  * The name of this function is actually a bit of a misnomer as it doesn't
701  * schedule them "as late as possible" as the paper implies.  Instead, it
702  * first finds the lates possible place it can schedule the instruction and
703  * then possibly schedules it earlier than that.  The actual location is as
704  * far down the tree as we can go while trying to stay out of loops.
705  */
706 static void
gcm_schedule_late_instr(nir_instr * instr,struct gcm_state * state)707 gcm_schedule_late_instr(nir_instr *instr, struct gcm_state *state)
708 {
709    if (instr->pass_flags & GCM_INSTR_SCHEDULED_LATE)
710       return;
711 
712    instr->pass_flags |= GCM_INSTR_SCHEDULED_LATE;
713 
714    /* Pinned/placed instructions are already scheduled so we don't need to do
715     * anything.  Also, bailing here keeps us from ever following phi nodes
716     * which can be back-edges.
717     */
718    if (instr->pass_flags & GCM_INSTR_PLACED ||
719        instr->pass_flags & GCM_INSTR_PINNED)
720       return;
721 
722    nir_foreach_def(instr, gcm_schedule_late_def, state);
723 }
724 
725 static bool
gcm_replace_def_with_undef(nir_def * def,void * void_state)726 gcm_replace_def_with_undef(nir_def *def, void *void_state)
727 {
728    struct gcm_state *state = void_state;
729 
730    if (nir_def_is_unused(def))
731       return true;
732 
733    nir_undef_instr *undef =
734       nir_undef_instr_create(state->impl->function->shader,
735                              def->num_components, def->bit_size);
736    nir_instr_insert(nir_before_impl(state->impl), &undef->instr);
737    nir_def_rewrite_uses(def, &undef->def);
738 
739    return true;
740 }
741 
742 /** Places an instrution back into the program
743  *
744  * The earlier passes of GCM simply choose blocks for each instruction and
745  * otherwise leave them alone.  This pass actually places the instructions
746  * into their chosen blocks.
747  *
748  * To do so, we simply insert instructions in the reverse order they were
749  * extracted. This will simply place instructions that were scheduled earlier
750  * onto the end of their new block and instructions that were scheduled later to
751  * the start of their new block.
752  */
753 static void
gcm_place_instr(nir_instr * instr,struct gcm_state * state)754 gcm_place_instr(nir_instr *instr, struct gcm_state *state)
755 {
756    if (instr->pass_flags & GCM_INSTR_PLACED)
757       return;
758 
759    instr->pass_flags |= GCM_INSTR_PLACED;
760 
761    if (instr->block == NULL) {
762       nir_foreach_def(instr, gcm_replace_def_with_undef, state);
763       nir_instr_remove(instr);
764       return;
765    }
766 
767    struct gcm_block_info *block_info = &state->blocks[instr->block->index];
768    exec_node_remove(&instr->node);
769 
770    if (block_info->last_instr) {
771       exec_node_insert_node_before(&block_info->last_instr->node,
772                                    &instr->node);
773    } else {
774       /* Schedule it at the end of the block */
775       nir_instr *jump_instr = nir_block_last_instr(instr->block);
776       if (jump_instr && jump_instr->type == nir_instr_type_jump) {
777          exec_node_insert_node_before(&jump_instr->node, &instr->node);
778       } else {
779          exec_list_push_tail(&instr->block->instr_list, &instr->node);
780       }
781    }
782 
783    block_info->last_instr = instr;
784 }
785 
786 /**
787  * Are instructions a and b both contained in the same if/else block?
788  */
789 static bool
weak_gvn(const nir_instr * a,const nir_instr * b)790 weak_gvn(const nir_instr *a, const nir_instr *b)
791 {
792    const struct nir_cf_node *ap = a->block->cf_node.parent;
793    const struct nir_cf_node *bp = b->block->cf_node.parent;
794    return ap && ap == bp && ap->type == nir_cf_node_if;
795 }
796 
797 static bool
opt_gcm_impl(nir_shader * shader,nir_function_impl * impl,bool value_number)798 opt_gcm_impl(nir_shader *shader, nir_function_impl *impl, bool value_number)
799 {
800    nir_metadata_require(impl, nir_metadata_block_index |
801                                  nir_metadata_dominance);
802    nir_metadata_require(impl, nir_metadata_loop_analysis,
803                         shader->options->force_indirect_unrolling,
804                         shader->options->force_indirect_unrolling_sampler);
805 
806    /* A previous pass may have left pass_flags dirty, so clear it all out. */
807    nir_foreach_block(block, impl)
808       nir_foreach_instr(instr, block)
809          instr->pass_flags = 0;
810 
811    struct gcm_state state;
812 
813    state.impl = impl;
814    state.instr = NULL;
815    state.progress = false;
816    exec_list_make_empty(&state.instrs);
817    state.blocks = rzalloc_array(NULL, struct gcm_block_info, impl->num_blocks);
818 
819    gcm_build_block_info(&impl->body, &state, NULL, 0, 0, ~0u);
820 
821    gcm_pin_instructions(impl, &state);
822 
823    state.instr_infos =
824       rzalloc_array(NULL, struct gcm_instr_info, state.num_instrs);
825 
826    /* Perform (at least some) Global Value Numbering (GVN).
827     *
828     * We perform full GVN when `value_number' is true.  This can be too
829     * aggressive, moving values far away and extending their live ranges,
830     * so we don't always want to do it.
831     *
832     * Otherwise, we perform 'weaker' GVN: if identical ALU instructions appear
833     * on both sides of the same if/else block, we allow them to be moved.
834     * This cleans up a lot of mess without being -too- aggressive.
835     */
836    struct set *gvn_set = nir_instr_set_create(NULL);
837    foreach_list_typed_safe(nir_instr, instr, node, &state.instrs) {
838       if (instr->pass_flags & GCM_INSTR_PINNED)
839          continue;
840 
841       if (nir_instr_set_add_or_rewrite(gvn_set, instr,
842                                        value_number ? NULL : weak_gvn))
843          state.progress = true;
844    }
845    nir_instr_set_destroy(gvn_set);
846 
847    foreach_list_typed(nir_instr, instr, node, &state.instrs)
848       gcm_schedule_early_instr(instr, &state);
849 
850    foreach_list_typed(nir_instr, instr, node, &state.instrs)
851       gcm_schedule_late_instr(instr, &state);
852 
853    while (!exec_list_is_empty(&state.instrs)) {
854       nir_instr *instr = exec_node_data(nir_instr,
855                                         state.instrs.tail_sentinel.prev, node);
856       gcm_place_instr(instr, &state);
857    }
858 
859    ralloc_free(state.blocks);
860    ralloc_free(state.instr_infos);
861 
862    nir_metadata_preserve(impl, nir_metadata_block_index |
863                                   nir_metadata_dominance |
864                                   nir_metadata_loop_analysis);
865 
866    return state.progress;
867 }
868 
869 bool
nir_opt_gcm(nir_shader * shader,bool value_number)870 nir_opt_gcm(nir_shader *shader, bool value_number)
871 {
872    bool progress = false;
873 
874    nir_foreach_function_impl(impl, shader) {
875       progress |= opt_gcm_impl(shader, impl, value_number);
876    }
877 
878    return progress;
879 }
880