Path: blob/21.2-virgl/src/compiler/nir/nir_loop_analyze.c
4547 views
/*1* Copyright © 2015 Thomas Helland2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice (including the next11* paragraph) shall be included in all copies or substantial portions of the12* Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL17* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING19* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS20* IN THE SOFTWARE.21*/2223#include "nir.h"24#include "nir_constant_expressions.h"25#include "nir_loop_analyze.h"26#include "util/bitset.h"2728typedef enum {29undefined,30invariant,31not_invariant,32basic_induction33} nir_loop_variable_type;3435typedef struct nir_basic_induction_var {36nir_alu_instr *alu; /* The def of the alu-operation */37nir_ssa_def *def_outside_loop; /* The phi-src outside the loop */38} nir_basic_induction_var;3940typedef struct {41/* A link for the work list */42struct list_head process_link;4344bool in_loop;4546/* The ssa_def associated with this info */47nir_ssa_def *def;4849/* The type of this ssa_def */50nir_loop_variable_type type;5152/* If this is of type basic_induction */53struct nir_basic_induction_var *ind;5455/* True if variable is in an if branch */56bool in_if_branch;5758/* True if variable is in a nested loop */59bool in_nested_loop;6061} nir_loop_variable;6263typedef struct {64/* The loop we store information for */65nir_loop *loop;6667/* Loop_variable for all ssa_defs in function */68nir_loop_variable *loop_vars;69BITSET_WORD *loop_vars_init;7071/* A list of the loop_vars to analyze */72struct list_head process_list;7374nir_variable_mode indirect_mask;7576} loop_info_state;7778static nir_loop_variable *79get_loop_var(nir_ssa_def *value, loop_info_state *state)80{81nir_loop_variable *var = &(state->loop_vars[value->index]);8283if (!BITSET_TEST(state->loop_vars_init, value->index)) {84var->in_loop = false;85var->def = value;86var->in_if_branch = false;87var->in_nested_loop = false;88if (value->parent_instr->type == nir_instr_type_load_const)89var->type = invariant;90else91var->type = undefined;9293BITSET_SET(state->loop_vars_init, value->index);94}9596return var;97}9899typedef struct {100loop_info_state *state;101bool in_if_branch;102bool in_nested_loop;103} init_loop_state;104105static bool106init_loop_def(nir_ssa_def *def, void *void_init_loop_state)107{108init_loop_state *loop_init_state = void_init_loop_state;109nir_loop_variable *var = get_loop_var(def, loop_init_state->state);110111if (loop_init_state->in_nested_loop) {112var->in_nested_loop = true;113} else if (loop_init_state->in_if_branch) {114var->in_if_branch = true;115} else {116/* Add to the tail of the list. That way we start at the beginning of117* the defs in the loop instead of the end when walking the list. This118* means less recursive calls. Only add defs that are not in nested119* loops or conditional blocks.120*/121list_addtail(&var->process_link, &loop_init_state->state->process_list);122}123124var->in_loop = true;125126return true;127}128129/** Calculate an estimated cost in number of instructions130*131* We do this so that we don't unroll loops which will later get massively132* inflated due to int64 or fp64 lowering. The estimates provided here don't133* have to be massively accurate; they just have to be good enough that loop134* unrolling doesn't cause things to blow up too much.135*/136static unsigned137instr_cost(nir_instr *instr, const nir_shader_compiler_options *options)138{139if (instr->type == nir_instr_type_intrinsic ||140instr->type == nir_instr_type_tex)141return 1;142143if (instr->type != nir_instr_type_alu)144return 0;145146nir_alu_instr *alu = nir_instr_as_alu(instr);147const nir_op_info *info = &nir_op_infos[alu->op];148149/* Assume everything 16 or 32-bit is cheap.150*151* There are no 64-bit ops that don't have a 64-bit thing as their152* destination or first source.153*/154if (nir_dest_bit_size(alu->dest.dest) < 64 &&155nir_src_bit_size(alu->src[0].src) < 64)156return 1;157158bool is_fp64 = nir_dest_bit_size(alu->dest.dest) == 64 &&159nir_alu_type_get_base_type(info->output_type) == nir_type_float;160for (unsigned i = 0; i < info->num_inputs; i++) {161if (nir_src_bit_size(alu->src[i].src) == 64 &&162nir_alu_type_get_base_type(info->input_types[i]) == nir_type_float)163is_fp64 = true;164}165166if (is_fp64) {167/* If it's something lowered normally, it's expensive. */168unsigned cost = 1;169if (options->lower_doubles_options &170nir_lower_doubles_op_to_options_mask(alu->op))171cost *= 20;172173/* If it's full software, it's even more expensive */174if (options->lower_doubles_options & nir_lower_fp64_full_software)175cost *= 100;176177return cost;178} else {179if (options->lower_int64_options &180nir_lower_int64_op_to_options_mask(alu->op)) {181/* These require a doing the division algorithm. */182if (alu->op == nir_op_idiv || alu->op == nir_op_udiv ||183alu->op == nir_op_imod || alu->op == nir_op_umod ||184alu->op == nir_op_irem)185return 100;186187/* Other int64 lowering isn't usually all that expensive */188return 5;189}190191return 1;192}193}194195static bool196init_loop_block(nir_block *block, loop_info_state *state,197bool in_if_branch, bool in_nested_loop,198const nir_shader_compiler_options *options)199{200init_loop_state init_state = {.in_if_branch = in_if_branch,201.in_nested_loop = in_nested_loop,202.state = state };203204nir_foreach_instr(instr, block) {205state->loop->info->instr_cost += instr_cost(instr, options);206nir_foreach_ssa_def(instr, init_loop_def, &init_state);207}208209return true;210}211212static inline bool213is_var_alu(nir_loop_variable *var)214{215return var->def->parent_instr->type == nir_instr_type_alu;216}217218static inline bool219is_var_phi(nir_loop_variable *var)220{221return var->def->parent_instr->type == nir_instr_type_phi;222}223224static inline bool225mark_invariant(nir_ssa_def *def, loop_info_state *state)226{227nir_loop_variable *var = get_loop_var(def, state);228229if (var->type == invariant)230return true;231232if (!var->in_loop) {233var->type = invariant;234return true;235}236237if (var->type == not_invariant)238return false;239240if (is_var_alu(var)) {241nir_alu_instr *alu = nir_instr_as_alu(def->parent_instr);242243for (unsigned i = 0; i < nir_op_infos[alu->op].num_inputs; i++) {244if (!mark_invariant(alu->src[i].src.ssa, state)) {245var->type = not_invariant;246return false;247}248}249var->type = invariant;250return true;251}252253/* Phis shouldn't be invariant except if one operand is invariant, and the254* other is the phi itself. These should be removed by opt_remove_phis.255* load_consts are already set to invariant and constant during init,256* and so should return earlier. Remaining op_codes are set undefined.257*/258var->type = not_invariant;259return false;260}261262static void263compute_invariance_information(loop_info_state *state)264{265/* An expression is invariant in a loop L if:266* (base cases)267* – it’s a constant268* – it’s a variable use, all of whose single defs are outside of L269* (inductive cases)270* – it’s a pure computation all of whose args are loop invariant271* – it’s a variable use whose single reaching def, and the272* rhs of that def is loop-invariant273*/274list_for_each_entry_safe(nir_loop_variable, var, &state->process_list,275process_link) {276assert(!var->in_if_branch && !var->in_nested_loop);277278if (mark_invariant(var->def, state))279list_del(&var->process_link);280}281}282283/* If all of the instruction sources point to identical ALU instructions (as284* per nir_instrs_equal), return one of the ALU instructions. Otherwise,285* return NULL.286*/287static nir_alu_instr *288phi_instr_as_alu(nir_phi_instr *phi)289{290nir_alu_instr *first = NULL;291nir_foreach_phi_src(src, phi) {292assert(src->src.is_ssa);293if (src->src.ssa->parent_instr->type != nir_instr_type_alu)294return NULL;295296nir_alu_instr *alu = nir_instr_as_alu(src->src.ssa->parent_instr);297if (first == NULL) {298first = alu;299} else {300if (!nir_instrs_equal(&first->instr, &alu->instr))301return NULL;302}303}304305return first;306}307308static bool309alu_src_has_identity_swizzle(nir_alu_instr *alu, unsigned src_idx)310{311assert(nir_op_infos[alu->op].input_sizes[src_idx] == 0);312assert(alu->dest.dest.is_ssa);313for (unsigned i = 0; i < alu->dest.dest.ssa.num_components; i++) {314if (alu->src[src_idx].swizzle[i] != i)315return false;316}317318return true;319}320321static bool322compute_induction_information(loop_info_state *state)323{324bool found_induction_var = false;325list_for_each_entry_safe(nir_loop_variable, var, &state->process_list,326process_link) {327328/* It can't be an induction variable if it is invariant. Invariants and329* things in nested loops or conditionals should have been removed from330* the list by compute_invariance_information().331*/332assert(!var->in_if_branch && !var->in_nested_loop &&333var->type != invariant);334335/* We are only interested in checking phis for the basic induction336* variable case as its simple to detect. All basic induction variables337* have a phi node338*/339if (!is_var_phi(var))340continue;341342nir_phi_instr *phi = nir_instr_as_phi(var->def->parent_instr);343nir_basic_induction_var *biv = rzalloc(state, nir_basic_induction_var);344345nir_loop_variable *alu_src_var = NULL;346nir_foreach_phi_src(src, phi) {347nir_loop_variable *src_var = get_loop_var(src->src.ssa, state);348349/* If one of the sources is in an if branch or nested loop then don't350* attempt to go any further.351*/352if (src_var->in_if_branch || src_var->in_nested_loop)353break;354355/* Detect inductions variables that are incremented in both branches356* of an unnested if rather than in a loop block.357*/358if (is_var_phi(src_var)) {359nir_phi_instr *src_phi =360nir_instr_as_phi(src_var->def->parent_instr);361nir_alu_instr *src_phi_alu = phi_instr_as_alu(src_phi);362if (src_phi_alu) {363src_var = get_loop_var(&src_phi_alu->dest.dest.ssa, state);364if (!src_var->in_if_branch)365break;366}367}368369if (!src_var->in_loop && !biv->def_outside_loop) {370biv->def_outside_loop = src_var->def;371} else if (is_var_alu(src_var) && !biv->alu) {372alu_src_var = src_var;373nir_alu_instr *alu = nir_instr_as_alu(src_var->def->parent_instr);374375if (nir_op_infos[alu->op].num_inputs == 2) {376for (unsigned i = 0; i < 2; i++) {377/* Is one of the operands const, and the other the phi. The378* phi source can't be swizzled in any way.379*/380if (nir_src_is_const(alu->src[i].src) &&381alu->src[1-i].src.ssa == &phi->dest.ssa &&382alu_src_has_identity_swizzle(alu, 1 - i))383biv->alu = alu;384}385}386387if (!biv->alu)388break;389} else {390biv->alu = NULL;391break;392}393}394395if (biv->alu && biv->def_outside_loop &&396biv->def_outside_loop->parent_instr->type == nir_instr_type_load_const) {397alu_src_var->type = basic_induction;398alu_src_var->ind = biv;399var->type = basic_induction;400var->ind = biv;401402found_induction_var = true;403} else {404ralloc_free(biv);405}406}407return found_induction_var;408}409410static bool411find_loop_terminators(loop_info_state *state)412{413bool success = false;414foreach_list_typed_safe(nir_cf_node, node, node, &state->loop->body) {415if (node->type == nir_cf_node_if) {416nir_if *nif = nir_cf_node_as_if(node);417418nir_block *break_blk = NULL;419nir_block *continue_from_blk = NULL;420bool continue_from_then = true;421422nir_block *last_then = nir_if_last_then_block(nif);423nir_block *last_else = nir_if_last_else_block(nif);424if (nir_block_ends_in_break(last_then)) {425break_blk = last_then;426continue_from_blk = last_else;427continue_from_then = false;428} else if (nir_block_ends_in_break(last_else)) {429break_blk = last_else;430continue_from_blk = last_then;431}432433/* If there is a break then we should find a terminator. If we can434* not find a loop terminator, but there is a break-statement then435* we should return false so that we do not try to find trip-count436*/437if (!nir_is_trivial_loop_if(nif, break_blk)) {438state->loop->info->complex_loop = true;439return false;440}441442/* Continue if the if contained no jumps at all */443if (!break_blk)444continue;445446if (nif->condition.ssa->parent_instr->type == nir_instr_type_phi) {447state->loop->info->complex_loop = true;448return false;449}450451nir_loop_terminator *terminator =452rzalloc(state->loop->info, nir_loop_terminator);453454list_addtail(&terminator->loop_terminator_link,455&state->loop->info->loop_terminator_list);456457terminator->nif = nif;458terminator->break_block = break_blk;459terminator->continue_from_block = continue_from_blk;460terminator->continue_from_then = continue_from_then;461terminator->conditional_instr = nif->condition.ssa->parent_instr;462463success = true;464}465}466467return success;468}469470/* This function looks for an array access within a loop that uses an471* induction variable for the array index. If found it returns the size of the472* array, otherwise 0 is returned. If we find an induction var we pass it back473* to the caller via array_index_out.474*/475static unsigned476find_array_access_via_induction(loop_info_state *state,477nir_deref_instr *deref,478nir_loop_variable **array_index_out)479{480for (nir_deref_instr *d = deref; d; d = nir_deref_instr_parent(d)) {481if (d->deref_type != nir_deref_type_array)482continue;483484assert(d->arr.index.is_ssa);485nir_loop_variable *array_index = get_loop_var(d->arr.index.ssa, state);486487if (array_index->type != basic_induction)488continue;489490if (array_index_out)491*array_index_out = array_index;492493nir_deref_instr *parent = nir_deref_instr_parent(d);494if (glsl_type_is_array_or_matrix(parent->type)) {495return glsl_get_length(parent->type);496} else {497assert(glsl_type_is_vector(parent->type));498return glsl_get_vector_elements(parent->type);499}500}501502return 0;503}504505static bool506guess_loop_limit(loop_info_state *state, nir_const_value *limit_val,507nir_ssa_scalar basic_ind)508{509unsigned min_array_size = 0;510511nir_foreach_block_in_cf_node(block, &state->loop->cf_node) {512nir_foreach_instr(instr, block) {513if (instr->type != nir_instr_type_intrinsic)514continue;515516nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);517518/* Check for arrays variably-indexed by a loop induction variable. */519if (intrin->intrinsic == nir_intrinsic_load_deref ||520intrin->intrinsic == nir_intrinsic_store_deref ||521intrin->intrinsic == nir_intrinsic_copy_deref) {522523nir_loop_variable *array_idx = NULL;524unsigned array_size =525find_array_access_via_induction(state,526nir_src_as_deref(intrin->src[0]),527&array_idx);528if (array_idx && basic_ind.def == array_idx->def &&529(min_array_size == 0 || min_array_size > array_size)) {530/* Array indices are scalars */531assert(basic_ind.def->num_components == 1);532min_array_size = array_size;533}534535if (intrin->intrinsic != nir_intrinsic_copy_deref)536continue;537538array_size =539find_array_access_via_induction(state,540nir_src_as_deref(intrin->src[1]),541&array_idx);542if (array_idx && basic_ind.def == array_idx->def &&543(min_array_size == 0 || min_array_size > array_size)) {544/* Array indices are scalars */545assert(basic_ind.def->num_components == 1);546min_array_size = array_size;547}548}549}550}551552if (min_array_size) {553*limit_val = nir_const_value_for_uint(min_array_size,554basic_ind.def->bit_size);555return true;556}557558return false;559}560561static bool562try_find_limit_of_alu(nir_ssa_scalar limit, nir_const_value *limit_val,563nir_loop_terminator *terminator, loop_info_state *state)564{565if (!nir_ssa_scalar_is_alu(limit))566return false;567568nir_op limit_op = nir_ssa_scalar_alu_op(limit);569if (limit_op == nir_op_imin || limit_op == nir_op_fmin) {570for (unsigned i = 0; i < 2; i++) {571nir_ssa_scalar src = nir_ssa_scalar_chase_alu_src(limit, i);572if (nir_ssa_scalar_is_const(src)) {573*limit_val = nir_ssa_scalar_as_const_value(src);574terminator->exact_trip_count_unknown = true;575return true;576}577}578}579580return false;581}582583static nir_const_value584eval_const_unop(nir_op op, unsigned bit_size, nir_const_value src0,585unsigned execution_mode)586{587assert(nir_op_infos[op].num_inputs == 1);588nir_const_value dest;589nir_const_value *src[1] = { &src0 };590nir_eval_const_opcode(op, &dest, 1, bit_size, src, execution_mode);591return dest;592}593594static nir_const_value595eval_const_binop(nir_op op, unsigned bit_size,596nir_const_value src0, nir_const_value src1,597unsigned execution_mode)598{599assert(nir_op_infos[op].num_inputs == 2);600nir_const_value dest;601nir_const_value *src[2] = { &src0, &src1 };602nir_eval_const_opcode(op, &dest, 1, bit_size, src, execution_mode);603return dest;604}605606static int32_t607get_iteration(nir_op cond_op, nir_const_value initial, nir_const_value step,608nir_const_value limit, unsigned bit_size,609unsigned execution_mode)610{611nir_const_value span, iter;612613switch (cond_op) {614case nir_op_ige:615case nir_op_ilt:616case nir_op_ieq:617case nir_op_ine:618span = eval_const_binop(nir_op_isub, bit_size, limit, initial,619execution_mode);620iter = eval_const_binop(nir_op_idiv, bit_size, span, step,621execution_mode);622break;623624case nir_op_uge:625case nir_op_ult:626span = eval_const_binop(nir_op_isub, bit_size, limit, initial,627execution_mode);628iter = eval_const_binop(nir_op_udiv, bit_size, span, step,629execution_mode);630break;631632case nir_op_fge:633case nir_op_flt:634case nir_op_feq:635case nir_op_fneu:636span = eval_const_binop(nir_op_fsub, bit_size, limit, initial,637execution_mode);638iter = eval_const_binop(nir_op_fdiv, bit_size, span,639step, execution_mode);640iter = eval_const_unop(nir_op_f2i64, bit_size, iter, execution_mode);641break;642643default:644return -1;645}646647uint64_t iter_u64 = nir_const_value_as_uint(iter, bit_size);648return iter_u64 > INT_MAX ? -1 : (int)iter_u64;649}650651static bool652will_break_on_first_iteration(nir_const_value step,653nir_alu_type induction_base_type,654unsigned trip_offset,655nir_op cond_op, unsigned bit_size,656nir_const_value initial,657nir_const_value limit,658bool limit_rhs, bool invert_cond,659unsigned execution_mode)660{661if (trip_offset == 1) {662nir_op add_op;663switch (induction_base_type) {664case nir_type_float:665add_op = nir_op_fadd;666break;667case nir_type_int:668case nir_type_uint:669add_op = nir_op_iadd;670break;671default:672unreachable("Unhandled induction variable base type!");673}674675initial = eval_const_binop(add_op, bit_size, initial, step,676execution_mode);677}678679nir_const_value *src[2];680src[limit_rhs ? 0 : 1] = &initial;681src[limit_rhs ? 1 : 0] = &limit;682683/* Evaluate the loop exit condition */684nir_const_value result;685nir_eval_const_opcode(cond_op, &result, 1, bit_size, src, execution_mode);686687return invert_cond ? !result.b : result.b;688}689690static bool691test_iterations(int32_t iter_int, nir_const_value step,692nir_const_value limit, nir_op cond_op, unsigned bit_size,693nir_alu_type induction_base_type,694nir_const_value initial, bool limit_rhs, bool invert_cond,695unsigned execution_mode)696{697assert(nir_op_infos[cond_op].num_inputs == 2);698699nir_const_value iter_src;700nir_op mul_op;701nir_op add_op;702switch (induction_base_type) {703case nir_type_float:704iter_src = nir_const_value_for_float(iter_int, bit_size);705mul_op = nir_op_fmul;706add_op = nir_op_fadd;707break;708case nir_type_int:709case nir_type_uint:710iter_src = nir_const_value_for_int(iter_int, bit_size);711mul_op = nir_op_imul;712add_op = nir_op_iadd;713break;714default:715unreachable("Unhandled induction variable base type!");716}717718/* Multiple the iteration count we are testing by the number of times we719* step the induction variable each iteration.720*/721nir_const_value mul_result =722eval_const_binop(mul_op, bit_size, iter_src, step, execution_mode);723724/* Add the initial value to the accumulated induction variable total */725nir_const_value add_result =726eval_const_binop(add_op, bit_size, mul_result, initial, execution_mode);727728nir_const_value *src[2];729src[limit_rhs ? 0 : 1] = &add_result;730src[limit_rhs ? 1 : 0] = &limit;731732/* Evaluate the loop exit condition */733nir_const_value result;734nir_eval_const_opcode(cond_op, &result, 1, bit_size, src, execution_mode);735736return invert_cond ? !result.b : result.b;737}738739static int740calculate_iterations(nir_const_value initial, nir_const_value step,741nir_const_value limit, nir_alu_instr *alu,742nir_ssa_scalar cond, nir_op alu_op, bool limit_rhs,743bool invert_cond, unsigned execution_mode)744{745/* nir_op_isub should have been lowered away by this point */746assert(alu->op != nir_op_isub);747748/* Make sure the alu type for our induction variable is compatible with the749* conditional alus input type. If its not something has gone really wrong.750*/751nir_alu_type induction_base_type =752nir_alu_type_get_base_type(nir_op_infos[alu->op].output_type);753if (induction_base_type == nir_type_int || induction_base_type == nir_type_uint) {754assert(nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[1]) == nir_type_int ||755nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[1]) == nir_type_uint);756} else {757assert(nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[0]) ==758induction_base_type);759}760761/* Check for nsupported alu operations */762if (alu->op != nir_op_iadd && alu->op != nir_op_fadd)763return -1;764765/* do-while loops can increment the starting value before the condition is766* checked. e.g.767*768* do {769* ndx++;770* } while (ndx < 3);771*772* Here we check if the induction variable is used directly by the loop773* condition and if so we assume we need to step the initial value.774*/775unsigned trip_offset = 0;776nir_alu_instr *cond_alu = nir_instr_as_alu(cond.def->parent_instr);777if (cond_alu->src[0].src.ssa == &alu->dest.dest.ssa ||778cond_alu->src[1].src.ssa == &alu->dest.dest.ssa) {779trip_offset = 1;780}781782assert(nir_src_bit_size(alu->src[0].src) ==783nir_src_bit_size(alu->src[1].src));784unsigned bit_size = nir_src_bit_size(alu->src[0].src);785786/* get_iteration works under assumption that iterator will be787* incremented or decremented until it hits the limit,788* however if the loop condition is false on the first iteration789* get_iteration's assumption is broken. Handle such loops first.790*/791if (will_break_on_first_iteration(step, induction_base_type, trip_offset,792alu_op, bit_size, initial,793limit, limit_rhs, invert_cond,794execution_mode)) {795return 0;796}797798int iter_int = get_iteration(alu_op, initial, step, limit, bit_size,799execution_mode);800801/* If iter_int is negative the loop is ill-formed or is the conditional is802* unsigned with a huge iteration count so don't bother going any further.803*/804if (iter_int < 0)805return -1;806807/* An explanation from the GLSL unrolling pass:808*809* Make sure that the calculated number of iterations satisfies the exit810* condition. This is needed to catch off-by-one errors and some types of811* ill-formed loops. For example, we need to detect that the following812* loop does not have a maximum iteration count.813*814* for (float x = 0.0; x != 0.9; x += 0.2);815*/816for (int bias = -1; bias <= 1; bias++) {817const int iter_bias = iter_int + bias;818819if (test_iterations(iter_bias, step, limit, alu_op, bit_size,820induction_base_type, initial,821limit_rhs, invert_cond, execution_mode)) {822return iter_bias > 0 ? iter_bias - trip_offset : iter_bias;823}824}825826return -1;827}828829static nir_op830inverse_comparison(nir_op alu_op)831{832switch (alu_op) {833case nir_op_fge:834return nir_op_flt;835case nir_op_ige:836return nir_op_ilt;837case nir_op_uge:838return nir_op_ult;839case nir_op_flt:840return nir_op_fge;841case nir_op_ilt:842return nir_op_ige;843case nir_op_ult:844return nir_op_uge;845case nir_op_feq:846return nir_op_fneu;847case nir_op_ieq:848return nir_op_ine;849case nir_op_fneu:850return nir_op_feq;851case nir_op_ine:852return nir_op_ieq;853default:854unreachable("Unsuported comparison!");855}856}857858static bool859is_supported_terminator_condition(nir_ssa_scalar cond)860{861if (!nir_ssa_scalar_is_alu(cond))862return false;863864nir_alu_instr *alu = nir_instr_as_alu(cond.def->parent_instr);865return nir_alu_instr_is_comparison(alu) &&866nir_op_infos[alu->op].num_inputs == 2;867}868869static bool870get_induction_and_limit_vars(nir_ssa_scalar cond,871nir_ssa_scalar *ind,872nir_ssa_scalar *limit,873bool *limit_rhs,874loop_info_state *state)875{876nir_ssa_scalar rhs, lhs;877lhs = nir_ssa_scalar_chase_alu_src(cond, 0);878rhs = nir_ssa_scalar_chase_alu_src(cond, 1);879880if (get_loop_var(lhs.def, state)->type == basic_induction) {881*ind = lhs;882*limit = rhs;883*limit_rhs = true;884return true;885} else if (get_loop_var(rhs.def, state)->type == basic_induction) {886*ind = rhs;887*limit = lhs;888*limit_rhs = false;889return true;890} else {891return false;892}893}894895static bool896try_find_trip_count_vars_in_iand(nir_ssa_scalar *cond,897nir_ssa_scalar *ind,898nir_ssa_scalar *limit,899bool *limit_rhs,900loop_info_state *state)901{902const nir_op alu_op = nir_ssa_scalar_alu_op(*cond);903assert(alu_op == nir_op_ieq || alu_op == nir_op_inot);904905nir_ssa_scalar iand = nir_ssa_scalar_chase_alu_src(*cond, 0);906907if (alu_op == nir_op_ieq) {908nir_ssa_scalar zero = nir_ssa_scalar_chase_alu_src(*cond, 1);909910if (!nir_ssa_scalar_is_alu(iand) || !nir_ssa_scalar_is_const(zero)) {911/* Maybe we had it the wrong way, flip things around */912nir_ssa_scalar tmp = zero;913zero = iand;914iand = tmp;915916/* If we still didn't find what we need then return */917if (!nir_ssa_scalar_is_const(zero))918return false;919}920921/* If the loop is not breaking on (x && y) == 0 then return */922if (nir_ssa_scalar_as_uint(zero) != 0)923return false;924}925926if (!nir_ssa_scalar_is_alu(iand))927return false;928929if (nir_ssa_scalar_alu_op(iand) != nir_op_iand)930return false;931932/* Check if iand src is a terminator condition and try get induction var933* and trip limit var.934*/935bool found_induction_var = false;936for (unsigned i = 0; i < 2; i++) {937nir_ssa_scalar src = nir_ssa_scalar_chase_alu_src(iand, i);938if (is_supported_terminator_condition(src) &&939get_induction_and_limit_vars(src, ind, limit, limit_rhs, state)) {940*cond = src;941found_induction_var = true;942943/* If we've found one with a constant limit, stop. */944if (nir_ssa_scalar_is_const(*limit))945return true;946}947}948949return found_induction_var;950}951952/* Run through each of the terminators of the loop and try to infer a possible953* trip-count. We need to check them all, and set the lowest trip-count as the954* trip-count of our loop. If one of the terminators has an undecidable955* trip-count we can not safely assume anything about the duration of the956* loop.957*/958static void959find_trip_count(loop_info_state *state, unsigned execution_mode)960{961bool trip_count_known = true;962bool guessed_trip_count = false;963nir_loop_terminator *limiting_terminator = NULL;964int max_trip_count = -1;965966list_for_each_entry(nir_loop_terminator, terminator,967&state->loop->info->loop_terminator_list,968loop_terminator_link) {969assert(terminator->nif->condition.is_ssa);970nir_ssa_scalar cond = { terminator->nif->condition.ssa, 0 };971972if (!nir_ssa_scalar_is_alu(cond)) {973/* If we get here the loop is dead and will get cleaned up by the974* nir_opt_dead_cf pass.975*/976trip_count_known = false;977continue;978}979980nir_op alu_op = nir_ssa_scalar_alu_op(cond);981982bool limit_rhs;983nir_ssa_scalar basic_ind = { NULL, 0 };984nir_ssa_scalar limit;985if ((alu_op == nir_op_inot || alu_op == nir_op_ieq) &&986try_find_trip_count_vars_in_iand(&cond, &basic_ind, &limit,987&limit_rhs, state)) {988989/* The loop is exiting on (x && y) == 0 so we need to get the990* inverse of x or y (i.e. which ever contained the induction var) in991* order to compute the trip count.992*/993alu_op = inverse_comparison(nir_ssa_scalar_alu_op(cond));994trip_count_known = false;995terminator->exact_trip_count_unknown = true;996}997998if (!basic_ind.def) {999if (is_supported_terminator_condition(cond)) {1000get_induction_and_limit_vars(cond, &basic_ind,1001&limit, &limit_rhs, state);1002}1003}10041005/* The comparison has to have a basic induction variable for us to be1006* able to find trip counts.1007*/1008if (!basic_ind.def) {1009trip_count_known = false;1010continue;1011}10121013terminator->induction_rhs = !limit_rhs;10141015/* Attempt to find a constant limit for the loop */1016nir_const_value limit_val;1017if (nir_ssa_scalar_is_const(limit)) {1018limit_val = nir_ssa_scalar_as_const_value(limit);1019} else {1020trip_count_known = false;10211022if (!try_find_limit_of_alu(limit, &limit_val, terminator, state)) {1023/* Guess loop limit based on array access */1024if (!guess_loop_limit(state, &limit_val, basic_ind)) {1025continue;1026}10271028guessed_trip_count = true;1029}1030}10311032/* We have determined that we have the following constants:1033* (With the typical int i = 0; i < x; i++; as an example)1034* - Upper limit.1035* - Starting value1036* - Step / iteration size1037* Thats all thats needed to calculate the trip-count1038*/10391040nir_basic_induction_var *ind_var =1041get_loop_var(basic_ind.def, state)->ind;10421043/* The basic induction var might be a vector but, because we guarantee1044* earlier that the phi source has a scalar swizzle, we can take the1045* component from basic_ind.1046*/1047nir_ssa_scalar initial_s = { ind_var->def_outside_loop, basic_ind.comp };1048nir_ssa_scalar alu_s = { &ind_var->alu->dest.dest.ssa, basic_ind.comp };10491050nir_const_value initial_val = nir_ssa_scalar_as_const_value(initial_s);10511052/* We are guaranteed by earlier code that at least one of these sources1053* is a constant but we don't know which.1054*/1055nir_const_value step_val;1056memset(&step_val, 0, sizeof(step_val));1057UNUSED bool found_step_value = false;1058assert(nir_op_infos[ind_var->alu->op].num_inputs == 2);1059for (unsigned i = 0; i < 2; i++) {1060nir_ssa_scalar alu_src = nir_ssa_scalar_chase_alu_src(alu_s, i);1061if (nir_ssa_scalar_is_const(alu_src)) {1062found_step_value = true;1063step_val = nir_ssa_scalar_as_const_value(alu_src);1064break;1065}1066}1067assert(found_step_value);10681069int iterations = calculate_iterations(initial_val, step_val, limit_val,1070ind_var->alu, cond,1071alu_op, limit_rhs,1072terminator->continue_from_then,1073execution_mode);10741075/* Where we not able to calculate the iteration count */1076if (iterations == -1) {1077trip_count_known = false;1078guessed_trip_count = false;1079continue;1080}10811082if (guessed_trip_count) {1083guessed_trip_count = false;1084if (state->loop->info->guessed_trip_count == 0 ||1085state->loop->info->guessed_trip_count > iterations)1086state->loop->info->guessed_trip_count = iterations;10871088continue;1089}10901091/* If this is the first run or we have found a smaller amount of1092* iterations than previously (we have identified a more limiting1093* terminator) set the trip count and limiting terminator.1094*/1095if (max_trip_count == -1 || iterations < max_trip_count) {1096max_trip_count = iterations;1097limiting_terminator = terminator;1098}1099}11001101state->loop->info->exact_trip_count_known = trip_count_known;1102if (max_trip_count > -1)1103state->loop->info->max_trip_count = max_trip_count;1104state->loop->info->limiting_terminator = limiting_terminator;1105}11061107static bool1108force_unroll_array_access(loop_info_state *state, nir_deref_instr *deref)1109{1110unsigned array_size = find_array_access_via_induction(state, deref, NULL);1111if (array_size) {1112if ((array_size == state->loop->info->max_trip_count) &&1113nir_deref_mode_must_be(deref, nir_var_shader_in |1114nir_var_shader_out |1115nir_var_shader_temp |1116nir_var_function_temp))1117return true;11181119if (nir_deref_mode_must_be(deref, state->indirect_mask))1120return true;1121}11221123return false;1124}11251126static bool1127force_unroll_heuristics(loop_info_state *state, nir_block *block)1128{1129nir_foreach_instr(instr, block) {1130if (instr->type != nir_instr_type_intrinsic)1131continue;11321133nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);11341135/* Check for arrays variably-indexed by a loop induction variable.1136* Unrolling the loop may convert that access into constant-indexing.1137*/1138if (intrin->intrinsic == nir_intrinsic_load_deref ||1139intrin->intrinsic == nir_intrinsic_store_deref ||1140intrin->intrinsic == nir_intrinsic_copy_deref) {1141if (force_unroll_array_access(state,1142nir_src_as_deref(intrin->src[0])))1143return true;11441145if (intrin->intrinsic == nir_intrinsic_copy_deref &&1146force_unroll_array_access(state,1147nir_src_as_deref(intrin->src[1])))1148return true;1149}1150}11511152return false;1153}11541155static void1156get_loop_info(loop_info_state *state, nir_function_impl *impl)1157{1158nir_shader *shader = impl->function->shader;1159const nir_shader_compiler_options *options = shader->options;11601161/* Add all entries in the outermost part of the loop to the processing list1162* Mark the entries in conditionals or in nested loops accordingly1163*/1164foreach_list_typed_safe(nir_cf_node, node, node, &state->loop->body) {1165switch (node->type) {11661167case nir_cf_node_block:1168init_loop_block(nir_cf_node_as_block(node), state,1169false, false, options);1170break;11711172case nir_cf_node_if:1173nir_foreach_block_in_cf_node(block, node)1174init_loop_block(block, state, true, false, options);1175break;11761177case nir_cf_node_loop:1178nir_foreach_block_in_cf_node(block, node) {1179init_loop_block(block, state, false, true, options);1180}1181break;11821183case nir_cf_node_function:1184break;1185}1186}11871188/* Try to find all simple terminators of the loop. If we can't find any,1189* or we find possible terminators that have side effects then bail.1190*/1191if (!find_loop_terminators(state)) {1192list_for_each_entry_safe(nir_loop_terminator, terminator,1193&state->loop->info->loop_terminator_list,1194loop_terminator_link) {1195list_del(&terminator->loop_terminator_link);1196ralloc_free(terminator);1197}1198return;1199}12001201/* Induction analysis needs invariance information so get that first */1202compute_invariance_information(state);12031204/* We have invariance information so try to find induction variables */1205if (!compute_induction_information(state))1206return;12071208/* Run through each of the terminators and try to compute a trip-count */1209find_trip_count(state, impl->function->shader->info.float_controls_execution_mode);12101211nir_foreach_block_in_cf_node(block, &state->loop->cf_node) {1212if (force_unroll_heuristics(state, block)) {1213state->loop->info->force_unroll = true;1214break;1215}1216}1217}12181219static loop_info_state *1220initialize_loop_info_state(nir_loop *loop, void *mem_ctx,1221nir_function_impl *impl)1222{1223loop_info_state *state = rzalloc(mem_ctx, loop_info_state);1224state->loop_vars = ralloc_array(mem_ctx, nir_loop_variable,1225impl->ssa_alloc);1226state->loop_vars_init = rzalloc_array(mem_ctx, BITSET_WORD,1227BITSET_WORDS(impl->ssa_alloc));1228state->loop = loop;12291230list_inithead(&state->process_list);12311232if (loop->info)1233ralloc_free(loop->info);12341235loop->info = rzalloc(loop, nir_loop_info);12361237list_inithead(&loop->info->loop_terminator_list);12381239return state;1240}12411242static void1243process_loops(nir_cf_node *cf_node, nir_variable_mode indirect_mask)1244{1245switch (cf_node->type) {1246case nir_cf_node_block:1247return;1248case nir_cf_node_if: {1249nir_if *if_stmt = nir_cf_node_as_if(cf_node);1250foreach_list_typed(nir_cf_node, nested_node, node, &if_stmt->then_list)1251process_loops(nested_node, indirect_mask);1252foreach_list_typed(nir_cf_node, nested_node, node, &if_stmt->else_list)1253process_loops(nested_node, indirect_mask);1254return;1255}1256case nir_cf_node_loop: {1257nir_loop *loop = nir_cf_node_as_loop(cf_node);1258foreach_list_typed(nir_cf_node, nested_node, node, &loop->body)1259process_loops(nested_node, indirect_mask);1260break;1261}1262default:1263unreachable("unknown cf node type");1264}12651266nir_loop *loop = nir_cf_node_as_loop(cf_node);1267nir_function_impl *impl = nir_cf_node_get_function(cf_node);1268void *mem_ctx = ralloc_context(NULL);12691270loop_info_state *state = initialize_loop_info_state(loop, mem_ctx, impl);1271state->indirect_mask = indirect_mask;12721273get_loop_info(state, impl);12741275ralloc_free(mem_ctx);1276}12771278void1279nir_loop_analyze_impl(nir_function_impl *impl,1280nir_variable_mode indirect_mask)1281{1282nir_index_ssa_defs(impl);1283foreach_list_typed(nir_cf_node, node, node, &impl->body)1284process_loops(node, indirect_mask);1285}128612871288