+static bool
+alu_instr_is_comparison(const nir_alu_instr *alu)
+{
+ switch (alu->op) {
+ case nir_op_flt32:
+ case nir_op_fge32:
+ case nir_op_feq32:
+ case nir_op_fneu32:
+ case nir_op_ilt32:
+ case nir_op_ult32:
+ case nir_op_ige32:
+ case nir_op_uge32:
+ case nir_op_ieq32:
+ case nir_op_ine32:
+ return true;
+ default:
+ return nir_alu_instr_is_comparison(alu);
+ }
+}
+
+static bool
+alu_instr_is_type_conversion(const nir_alu_instr *alu)
+{
+ return nir_op_infos[alu->op].num_inputs == 1 &&
+ nir_op_infos[alu->op].output_type != nir_op_infos[alu->op].input_types[0];
+}
+
+/**
+ * Splits ALU instructions that have a source that is a phi node
+ *
+ * ALU instructions in the header block of a loop that meet the following
+ * criteria can be split.
+ *
+ * - The loop has no continue instructions other than the "natural" continue
+ * at the bottom of the loop.
+ *
+ * - At least one source of the instruction is a phi node from the header block.
+ *
+ * - The phi node selects a constant or undef from the block before the loop.
+ *
+ * - Any non-phi sources of the ALU instruction come from a block that
+ * dominates the block before the loop. The most common failure mode for
+ * this check is sources that are generated in the loop header block.
+ *
+ * The split process splits the original ALU instruction into two, one at the
+ * bottom of the loop and one at the block before the loop. The instruction
+ * before the loop computes the value on the first iteration, and the
+ * instruction at the bottom computes the value on the second, third, and so
+ * on. A new phi node is added to the header block that selects either the
+ * instruction before the loop or the one at the end, and uses of the original
+ * instruction are replaced by this phi.
+ *
+ * The splitting transforms a loop like:
+ *
+ * vec1 32 ssa_8 = load_const (0x00000001)
+ * vec1 32 ssa_10 = load_const (0x00000000)
+ * // succs: block_1
+ * loop {
+ * block block_1:
+ * // preds: block_0 block_4
+ * vec1 32 ssa_11 = phi block_0: ssa_10, block_4: ssa_15
+ * vec1 32 ssa_12 = phi block_0: ssa_1, block_4: ssa_15
+ * vec1 32 ssa_13 = phi block_0: ssa_10, block_4: ssa_16
+ * vec1 32 ssa_14 = iadd ssa_11, ssa_8
+ * vec1 32 ssa_15 = b32csel ssa_13, ssa_14, ssa_12
+ * ...
+ * // succs: block_1
+ * }
+ *
+ * into:
+ *
+ * vec1 32 ssa_8 = load_const (0x00000001)
+ * vec1 32 ssa_10 = load_const (0x00000000)
+ * vec1 32 ssa_22 = iadd ssa_10, ssa_8
+ * // succs: block_1
+ * loop {
+ * block block_1:
+ * // preds: block_0 block_4
+ * vec1 32 ssa_11 = phi block_0: ssa_10, block_4: ssa_15
+ * vec1 32 ssa_12 = phi block_0: ssa_1, block_4: ssa_15
+ * vec1 32 ssa_13 = phi block_0: ssa_10, block_4: ssa_16
+ * vec1 32 ssa_21 = phi block_0: ssa_22, block_4: ssa_20
+ * vec1 32 ssa_15 = b32csel ssa_13, ssa_21, ssa_12
+ * ...
+ * vec1 32 ssa_20 = iadd ssa_15, ssa_8
+ * // succs: block_1
+ * }
+ */
+static bool
+opt_split_alu_of_phi(nir_builder *b, nir_loop *loop)
+{
+ bool progress = false;
+ nir_block *header_block = nir_loop_first_block(loop);
+ nir_block *const prev_block =
+ nir_cf_node_as_block(nir_cf_node_prev(&loop->cf_node));
+
+ /* It would be insane if this were not true */
+ assert(_mesa_set_search(header_block->predecessors, prev_block));
+
+ /* The loop must have exactly one continue block which could be a block
+ * ending in a continue instruction or the "natural" continue from the
+ * last block in the loop back to the top.
+ */
+ if (header_block->predecessors->entries != 2)
+ return false;
+
+ nir_foreach_instr_safe(instr, header_block) {
+ if (instr->type != nir_instr_type_alu)
+ continue;
+
+ nir_alu_instr *const alu = nir_instr_as_alu(instr);
+
+ /* nir_op_vec{2,3,4} and nir_op_mov are excluded because they can easily
+ * lead to infinite optimization loops. Splitting comparisons can lead
+ * to loop unrolling not recognizing loop termintators, and type
+ * conversions also lead to regressions.
+ */
+ if (nir_op_is_vec(alu->op) ||
+ alu_instr_is_comparison(alu) ||
+ alu_instr_is_type_conversion(alu))
+ continue;
+
+ bool has_phi_src_from_prev_block = false;
+ bool all_non_phi_exist_in_prev_block = true;
+ bool is_prev_result_undef = true;
+ bool is_prev_result_const = true;
+ nir_ssa_def *prev_srcs[8]; // FINISHME: Array size?
+ nir_ssa_def *continue_srcs[8]; // FINISHME: Array size?
+
+ for (unsigned i = 0; i < nir_op_infos[alu->op].num_inputs; i++) {
+ nir_instr *const src_instr = alu->src[i].src.ssa->parent_instr;
+
+ /* If the source is a phi in the loop header block, then the
+ * prev_srcs and continue_srcs will come from the different sources
+ * of the phi.
+ */
+ if (src_instr->type == nir_instr_type_phi &&
+ src_instr->block == header_block) {
+ nir_phi_instr *const phi = nir_instr_as_phi(src_instr);
+
+ /* Only strictly need to NULL out the pointers when the assertions
+ * (below) are compiled in. Debugging a NULL pointer deref in the
+ * wild is easier than debugging a random pointer deref, so set
+ * NULL unconditionally just to be safe.
+ */
+ prev_srcs[i] = NULL;
+ continue_srcs[i] = NULL;
+
+ nir_foreach_phi_src(src_of_phi, phi) {
+ if (src_of_phi->pred == prev_block) {
+ if (src_of_phi->src.ssa->parent_instr->type !=
+ nir_instr_type_ssa_undef) {
+ is_prev_result_undef = false;
+ }
+
+ if (src_of_phi->src.ssa->parent_instr->type !=
+ nir_instr_type_load_const) {
+ is_prev_result_const = false;
+ }
+
+ prev_srcs[i] = src_of_phi->src.ssa;
+ has_phi_src_from_prev_block = true;
+ } else
+ continue_srcs[i] = src_of_phi->src.ssa;
+ }
+
+ assert(prev_srcs[i] != NULL);
+ assert(continue_srcs[i] != NULL);
+ } else {
+ /* If the source is not a phi (or a phi in a block other than the
+ * loop header), then the value must exist in prev_block.
+ */
+ if (!nir_block_dominates(src_instr->block, prev_block)) {
+ all_non_phi_exist_in_prev_block = false;
+ break;
+ }
+
+ prev_srcs[i] = alu->src[i].src.ssa;
+ continue_srcs[i] = alu->src[i].src.ssa;
+ }
+ }
+
+ if (has_phi_src_from_prev_block && all_non_phi_exist_in_prev_block &&
+ (is_prev_result_undef || is_prev_result_const)) {
+ nir_block *const continue_block = find_continue_block(loop);
+
+ b->cursor = nir_after_block(prev_block);
+ nir_ssa_def *prev_value = clone_alu_and_replace_src_defs(b, alu, prev_srcs);
+
+ /* Make a copy of the original ALU instruction. Replace the sources
+ * of the new instruction that read a phi with an undef source from
+ * prev_block with the non-undef source of that phi.
+ *
+ * Insert the new instruction at the end of the continue block.
+ */
+ b->cursor = nir_after_block_before_jump(continue_block);
+
+ nir_ssa_def *const alu_copy =
+ clone_alu_and_replace_src_defs(b, alu, continue_srcs);
+
+ /* Make a new phi node that selects a value from prev_block and the
+ * result of the new instruction from continue_block.
+ */
+ nir_phi_instr *const phi = nir_phi_instr_create(b->shader);
+ nir_phi_src *phi_src;
+
+ phi_src = ralloc(phi, nir_phi_src);
+ phi_src->pred = prev_block;
+ phi_src->src = nir_src_for_ssa(prev_value);
+ exec_list_push_tail(&phi->srcs, &phi_src->node);
+
+ phi_src = ralloc(phi, nir_phi_src);
+ phi_src->pred = continue_block;
+ phi_src->src = nir_src_for_ssa(alu_copy);
+ exec_list_push_tail(&phi->srcs, &phi_src->node);
+
+ nir_ssa_dest_init(&phi->instr, &phi->dest,
+ alu_copy->num_components, alu_copy->bit_size, NULL);
+
+ b->cursor = nir_after_phis(header_block);
+ nir_builder_instr_insert(b, &phi->instr);
+
+ /* Modify all readers of the original ALU instruction to read the
+ * result of the phi.
+ */
+ nir_foreach_use_safe(use_src, &alu->dest.dest.ssa) {
+ nir_instr_rewrite_src(use_src->parent_instr,
+ use_src,
+ nir_src_for_ssa(&phi->dest.ssa));
+ }
+
+ nir_foreach_if_use_safe(use_src, &alu->dest.dest.ssa) {
+ nir_if_rewrite_condition(use_src->parent_if,
+ nir_src_for_ssa(&phi->dest.ssa));
+ }
+
+ /* Since the original ALU instruction no longer has any readers, just
+ * remove it.
+ */
+ nir_instr_remove_v(&alu->instr);
+ ralloc_free(alu);
+
+ progress = true;
+ }
+ }
+
+ return progress;
+}
+
+/**
+ * Get the SSA value from a phi node that corresponds to a specific block
+ */
+static nir_ssa_def *
+ssa_for_phi_from_block(nir_phi_instr *phi, nir_block *block)
+{
+ nir_foreach_phi_src(src, phi) {
+ if (src->pred == block)
+ return src->src.ssa;
+ }
+
+ assert(!"Block is not a predecessor of phi.");
+ return NULL;
+}
+
+/**
+ * Simplify a bcsel whose sources are all phi nodes from the loop header block
+ *
+ * bcsel instructions in a loop that meet the following criteria can be
+ * converted to phi nodes:
+ *
+ * - The loop has no continue instructions other than the "natural" continue
+ * at the bottom of the loop.
+ *
+ * - All of the sources of the bcsel are phi nodes in the header block of the
+ * loop.
+ *
+ * - The phi node representing the condition of the bcsel instruction chooses
+ * only constant values.
+ *
+ * The contant value from the condition will select one of the other sources
+ * when entered from outside the loop and the remaining source when entered
+ * from the continue block. Since each of these sources is also a phi node in
+ * the header block, the value of the phi node can be "evaluated." These
+ * evaluated phi nodes provide the sources for a new phi node. All users of
+ * the bcsel result are updated to use the phi node result.
+ *
+ * The replacement transforms loops like:
+ *
+ * vec1 32 ssa_7 = undefined
+ * vec1 32 ssa_8 = load_const (0x00000001)
+ * vec1 32 ssa_9 = load_const (0x000000c8)
+ * vec1 32 ssa_10 = load_const (0x00000000)
+ * // succs: block_1
+ * loop {
+ * block block_1:
+ * // preds: block_0 block_4
+ * vec1 32 ssa_11 = phi block_0: ssa_1, block_4: ssa_14
+ * vec1 32 ssa_12 = phi block_0: ssa_10, block_4: ssa_15
+ * vec1 32 ssa_13 = phi block_0: ssa_7, block_4: ssa_25
+ * vec1 32 ssa_14 = b32csel ssa_12, ssa_13, ssa_11
+ * vec1 32 ssa_16 = ige32 ssa_14, ssa_9
+ * ...
+ * vec1 32 ssa_15 = load_const (0xffffffff)
+ * ...
+ * vec1 32 ssa_25 = iadd ssa_14, ssa_8
+ * // succs: block_1
+ * }
+ *
+ * into:
+ *
+ * vec1 32 ssa_7 = undefined
+ * vec1 32 ssa_8 = load_const (0x00000001)
+ * vec1 32 ssa_9 = load_const (0x000000c8)
+ * vec1 32 ssa_10 = load_const (0x00000000)
+ * // succs: block_1
+ * loop {
+ * block block_1:
+ * // preds: block_0 block_4
+ * vec1 32 ssa_11 = phi block_0: ssa_1, block_4: ssa_14
+ * vec1 32 ssa_12 = phi block_0: ssa_10, block_4: ssa_15
+ * vec1 32 ssa_13 = phi block_0: ssa_7, block_4: ssa_25
+ * vec1 32 sss_26 = phi block_0: ssa_1, block_4: ssa_25
+ * vec1 32 ssa_16 = ige32 ssa_26, ssa_9
+ * ...
+ * vec1 32 ssa_15 = load_const (0xffffffff)
+ * ...
+ * vec1 32 ssa_25 = iadd ssa_26, ssa_8
+ * // succs: block_1
+ * }
+ *
+ * \note
+ * It may be possible modify this function to not require a phi node as the
+ * source of the bcsel that is selected when entering from outside the loop.
+ * The only restriction is that the source must be geneated outside the loop
+ * (since it will become the source of a phi node in the header block of the
+ * loop).
+ */
+static bool
+opt_simplify_bcsel_of_phi(nir_builder *b, nir_loop *loop)
+{
+ bool progress = false;
+ nir_block *header_block = nir_loop_first_block(loop);
+ nir_block *const prev_block =
+ nir_cf_node_as_block(nir_cf_node_prev(&loop->cf_node));
+
+ /* It would be insane if this were not true */
+ assert(_mesa_set_search(header_block->predecessors, prev_block));
+
+ /* The loop must have exactly one continue block which could be a block
+ * ending in a continue instruction or the "natural" continue from the
+ * last block in the loop back to the top.
+ */
+ if (header_block->predecessors->entries != 2)
+ return false;
+
+ /* We can move any bcsel that can guaranteed to execut on every iteration
+ * of a loop. For now this is accomplished by only taking bcsels from the
+ * header_block. In the future, this could be expanced to include any
+ * bcsel that must come before any break.
+ *
+ * For more details, see
+ * https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/170#note_110305
+ */
+ nir_foreach_instr_safe(instr, header_block) {
+ if (instr->type != nir_instr_type_alu)
+ continue;
+
+ nir_alu_instr *const bcsel = nir_instr_as_alu(instr);
+ if (bcsel->op != nir_op_bcsel &&
+ bcsel->op != nir_op_b32csel &&
+ bcsel->op != nir_op_fcsel)
+ continue;
+
+ bool match = true;
+ for (unsigned i = 0; i < 3; i++) {
+ /* FINISHME: The abs and negate cases could be handled by adding
+ * move instructions at the bottom of the continue block and more
+ * phi nodes in the header_block.
+ */
+ if (!bcsel->src[i].src.is_ssa ||
+ bcsel->src[i].src.ssa->parent_instr->type != nir_instr_type_phi ||
+ bcsel->src[i].src.ssa->parent_instr->block != header_block ||
+ bcsel->src[i].negate || bcsel->src[i].abs) {
+ match = false;
+ break;
+ }
+ }
+
+ if (!match)
+ continue;
+
+ nir_phi_instr *const cond_phi =
+ nir_instr_as_phi(bcsel->src[0].src.ssa->parent_instr);
+
+ bool entry_val = false, continue_val = false;
+ if (!phi_has_constant_from_outside_and_one_from_inside_loop(cond_phi,
+ prev_block,
+ &entry_val,
+ &continue_val))
+ continue;
+
+ /* If they both execute or both don't execute, this is a job for
+ * nir_dead_cf, not this pass.
+ */
+ if ((entry_val && continue_val) || (!entry_val && !continue_val))
+ continue;
+
+ const unsigned entry_src = entry_val ? 1 : 2;
+ const unsigned continue_src = entry_val ? 2 : 1;
+
+ /* Create a new phi node that selects the value for prev_block from
+ * the bcsel source that is selected by entry_val and the value for
+ * continue_block from the other bcsel source. Both sources have
+ * already been verified to be phi nodes.
+ */
+ nir_block *const continue_block = find_continue_block(loop);
+ nir_phi_instr *const phi = nir_phi_instr_create(b->shader);
+ nir_phi_src *phi_src;
+
+ phi_src = ralloc(phi, nir_phi_src);
+ phi_src->pred = prev_block;
+ phi_src->src =
+ nir_src_for_ssa(ssa_for_phi_from_block(nir_instr_as_phi(bcsel->src[entry_src].src.ssa->parent_instr),
+ prev_block));
+ exec_list_push_tail(&phi->srcs, &phi_src->node);
+
+ phi_src = ralloc(phi, nir_phi_src);
+ phi_src->pred = continue_block;
+ phi_src->src =
+ nir_src_for_ssa(ssa_for_phi_from_block(nir_instr_as_phi(bcsel->src[continue_src].src.ssa->parent_instr),
+ continue_block));
+ exec_list_push_tail(&phi->srcs, &phi_src->node);
+
+ nir_ssa_dest_init(&phi->instr,
+ &phi->dest,
+ nir_dest_num_components(bcsel->dest.dest),
+ nir_dest_bit_size(bcsel->dest.dest),
+ NULL);
+
+ b->cursor = nir_after_phis(header_block);
+ nir_builder_instr_insert(b, &phi->instr);
+
+ /* Modify all readers of the bcsel instruction to read the result of
+ * the phi.
+ */
+ nir_foreach_use_safe(use_src, &bcsel->dest.dest.ssa) {
+ nir_instr_rewrite_src(use_src->parent_instr,
+ use_src,
+ nir_src_for_ssa(&phi->dest.ssa));
+ }
+
+ nir_foreach_if_use_safe(use_src, &bcsel->dest.dest.ssa) {
+ nir_if_rewrite_condition(use_src->parent_if,
+ nir_src_for_ssa(&phi->dest.ssa));
+ }
+
+ /* Since the original bcsel instruction no longer has any readers,
+ * just remove it.
+ */
+ nir_instr_remove_v(&bcsel->instr);
+ ralloc_free(bcsel);
+
+ progress = true;
+ }
+
+ return progress;
+}
+