nir/loop_analyze: Bail if we encounter swizzles
[mesa.git] / src / compiler / nir / nir_loop_analyze.c
1 /*
2 * Copyright © 2015 Thomas Helland
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_constant_expressions.h"
26 #include "nir_loop_analyze.h"
27
28 typedef enum {
29 undefined,
30 invariant,
31 not_invariant,
32 basic_induction
33 } nir_loop_variable_type;
34
35 struct nir_basic_induction_var;
36
37 typedef struct {
38 /* A link for the work list */
39 struct list_head process_link;
40
41 bool in_loop;
42
43 /* The ssa_def associated with this info */
44 nir_ssa_def *def;
45
46 /* The type of this ssa_def */
47 nir_loop_variable_type type;
48
49 /* If this is of type basic_induction */
50 struct nir_basic_induction_var *ind;
51
52 /* True if variable is in an if branch */
53 bool in_if_branch;
54
55 /* True if variable is in a nested loop */
56 bool in_nested_loop;
57
58 } nir_loop_variable;
59
60 typedef struct nir_basic_induction_var {
61 nir_op alu_op; /* The type of alu-operation */
62 nir_loop_variable *alu_def; /* The def of the alu-operation */
63 nir_loop_variable *invariant; /* The invariant alu-operand */
64 nir_loop_variable *def_outside_loop; /* The phi-src outside the loop */
65 } nir_basic_induction_var;
66
67 typedef struct {
68 /* The loop we store information for */
69 nir_loop *loop;
70
71 /* Loop_variable for all ssa_defs in function */
72 nir_loop_variable *loop_vars;
73
74 /* A list of the loop_vars to analyze */
75 struct list_head process_list;
76
77 nir_variable_mode indirect_mask;
78
79 } loop_info_state;
80
81 static nir_loop_variable *
82 get_loop_var(nir_ssa_def *value, loop_info_state *state)
83 {
84 return &(state->loop_vars[value->index]);
85 }
86
87 typedef struct {
88 loop_info_state *state;
89 bool in_if_branch;
90 bool in_nested_loop;
91 } init_loop_state;
92
93 static bool
94 init_loop_def(nir_ssa_def *def, void *void_init_loop_state)
95 {
96 init_loop_state *loop_init_state = void_init_loop_state;
97 nir_loop_variable *var = get_loop_var(def, loop_init_state->state);
98
99 if (loop_init_state->in_nested_loop) {
100 var->in_nested_loop = true;
101 } else if (loop_init_state->in_if_branch) {
102 var->in_if_branch = true;
103 } else {
104 /* Add to the tail of the list. That way we start at the beginning of
105 * the defs in the loop instead of the end when walking the list. This
106 * means less recursive calls. Only add defs that are not in nested
107 * loops or conditional blocks.
108 */
109 list_addtail(&var->process_link, &loop_init_state->state->process_list);
110 }
111
112 var->in_loop = true;
113
114 return true;
115 }
116
117 /** Calculate an estimated cost in number of instructions
118 *
119 * We do this so that we don't unroll loops which will later get massively
120 * inflated due to int64 or fp64 lowering. The estimates provided here don't
121 * have to be massively accurate; they just have to be good enough that loop
122 * unrolling doesn't cause things to blow up too much.
123 */
124 static unsigned
125 instr_cost(nir_instr *instr, const nir_shader_compiler_options *options)
126 {
127 if (instr->type == nir_instr_type_intrinsic ||
128 instr->type == nir_instr_type_tex)
129 return 1;
130
131 if (instr->type != nir_instr_type_alu)
132 return 0;
133
134 nir_alu_instr *alu = nir_instr_as_alu(instr);
135 const nir_op_info *info = &nir_op_infos[alu->op];
136
137 /* Assume everything 16 or 32-bit is cheap.
138 *
139 * There are no 64-bit ops that don't have a 64-bit thing as their
140 * destination or first source.
141 */
142 if (nir_dest_bit_size(alu->dest.dest) < 64 &&
143 nir_src_bit_size(alu->src[0].src) < 64)
144 return 1;
145
146 bool is_fp64 = nir_dest_bit_size(alu->dest.dest) == 64 &&
147 nir_alu_type_get_base_type(info->output_type) == nir_type_float;
148 for (unsigned i = 0; i < info->num_inputs; i++) {
149 if (nir_src_bit_size(alu->src[i].src) == 64 &&
150 nir_alu_type_get_base_type(info->input_types[i]) == nir_type_float)
151 is_fp64 = true;
152 }
153
154 if (is_fp64) {
155 /* If it's something lowered normally, it's expensive. */
156 unsigned cost = 1;
157 if (options->lower_doubles_options &
158 nir_lower_doubles_op_to_options_mask(alu->op))
159 cost *= 20;
160
161 /* If it's full software, it's even more expensive */
162 if (options->lower_doubles_options & nir_lower_fp64_full_software)
163 cost *= 100;
164
165 return cost;
166 } else {
167 if (options->lower_int64_options &
168 nir_lower_int64_op_to_options_mask(alu->op)) {
169 /* These require a doing the division algorithm. */
170 if (alu->op == nir_op_idiv || alu->op == nir_op_udiv ||
171 alu->op == nir_op_imod || alu->op == nir_op_umod ||
172 alu->op == nir_op_irem)
173 return 100;
174
175 /* Other int64 lowering isn't usually all that expensive */
176 return 5;
177 }
178
179 return 1;
180 }
181 }
182
183 static bool
184 init_loop_block(nir_block *block, loop_info_state *state,
185 bool in_if_branch, bool in_nested_loop,
186 const nir_shader_compiler_options *options)
187 {
188 init_loop_state init_state = {.in_if_branch = in_if_branch,
189 .in_nested_loop = in_nested_loop,
190 .state = state };
191
192 nir_foreach_instr(instr, block) {
193 state->loop->info->instr_cost += instr_cost(instr, options);
194 nir_foreach_ssa_def(instr, init_loop_def, &init_state);
195 }
196
197 return true;
198 }
199
200 static inline bool
201 is_var_alu(nir_loop_variable *var)
202 {
203 return var->def->parent_instr->type == nir_instr_type_alu;
204 }
205
206 static inline bool
207 is_var_constant(nir_loop_variable *var)
208 {
209 return var->def->parent_instr->type == nir_instr_type_load_const;
210 }
211
212 static inline bool
213 is_var_phi(nir_loop_variable *var)
214 {
215 return var->def->parent_instr->type == nir_instr_type_phi;
216 }
217
218 static inline bool
219 mark_invariant(nir_ssa_def *def, loop_info_state *state)
220 {
221 nir_loop_variable *var = get_loop_var(def, state);
222
223 if (var->type == invariant)
224 return true;
225
226 if (!var->in_loop) {
227 var->type = invariant;
228 return true;
229 }
230
231 if (var->type == not_invariant)
232 return false;
233
234 if (is_var_alu(var)) {
235 nir_alu_instr *alu = nir_instr_as_alu(def->parent_instr);
236
237 for (unsigned i = 0; i < nir_op_infos[alu->op].num_inputs; i++) {
238 if (!mark_invariant(alu->src[i].src.ssa, state)) {
239 var->type = not_invariant;
240 return false;
241 }
242 }
243 var->type = invariant;
244 return true;
245 }
246
247 /* Phis shouldn't be invariant except if one operand is invariant, and the
248 * other is the phi itself. These should be removed by opt_remove_phis.
249 * load_consts are already set to invariant and constant during init,
250 * and so should return earlier. Remaining op_codes are set undefined.
251 */
252 var->type = not_invariant;
253 return false;
254 }
255
256 static void
257 compute_invariance_information(loop_info_state *state)
258 {
259 /* An expression is invariant in a loop L if:
260 * (base cases)
261 * – it’s a constant
262 * – it’s a variable use, all of whose single defs are outside of L
263 * (inductive cases)
264 * – it’s a pure computation all of whose args are loop invariant
265 * – it’s a variable use whose single reaching def, and the
266 * rhs of that def is loop-invariant
267 */
268 list_for_each_entry_safe(nir_loop_variable, var, &state->process_list,
269 process_link) {
270 assert(!var->in_if_branch && !var->in_nested_loop);
271
272 if (mark_invariant(var->def, state))
273 list_del(&var->process_link);
274 }
275 }
276
277 /* If all of the instruction sources point to identical ALU instructions (as
278 * per nir_instrs_equal), return one of the ALU instructions. Otherwise,
279 * return NULL.
280 */
281 static nir_alu_instr *
282 phi_instr_as_alu(nir_phi_instr *phi)
283 {
284 nir_alu_instr *first = NULL;
285 nir_foreach_phi_src(src, phi) {
286 assert(src->src.is_ssa);
287 if (src->src.ssa->parent_instr->type != nir_instr_type_alu)
288 return NULL;
289
290 nir_alu_instr *alu = nir_instr_as_alu(src->src.ssa->parent_instr);
291 if (first == NULL) {
292 first = alu;
293 } else {
294 if (!nir_instrs_equal(&first->instr, &alu->instr))
295 return NULL;
296 }
297 }
298
299 return first;
300 }
301
302 static bool
303 compute_induction_information(loop_info_state *state)
304 {
305 bool found_induction_var = false;
306 list_for_each_entry_safe(nir_loop_variable, var, &state->process_list,
307 process_link) {
308
309 /* It can't be an induction variable if it is invariant. Invariants and
310 * things in nested loops or conditionals should have been removed from
311 * the list by compute_invariance_information().
312 */
313 assert(!var->in_if_branch && !var->in_nested_loop &&
314 var->type != invariant);
315
316 /* We are only interested in checking phis for the basic induction
317 * variable case as its simple to detect. All basic induction variables
318 * have a phi node
319 */
320 if (!is_var_phi(var))
321 continue;
322
323 /* We only handle scalars because none of the rest of the loop analysis
324 * code can properly handle swizzles.
325 */
326 if (var->def->num_components > 1)
327 continue;
328
329 nir_phi_instr *phi = nir_instr_as_phi(var->def->parent_instr);
330 nir_basic_induction_var *biv = rzalloc(state, nir_basic_induction_var);
331
332 nir_foreach_phi_src(src, phi) {
333 nir_loop_variable *src_var = get_loop_var(src->src.ssa, state);
334
335 /* If one of the sources is in an if branch or nested loop then don't
336 * attempt to go any further.
337 */
338 if (src_var->in_if_branch || src_var->in_nested_loop)
339 break;
340
341 /* Detect inductions variables that are incremented in both branches
342 * of an unnested if rather than in a loop block.
343 */
344 if (is_var_phi(src_var)) {
345 nir_phi_instr *src_phi =
346 nir_instr_as_phi(src_var->def->parent_instr);
347 nir_alu_instr *src_phi_alu = phi_instr_as_alu(src_phi);
348 if (src_phi_alu) {
349 src_var = get_loop_var(&src_phi_alu->dest.dest.ssa, state);
350 if (!src_var->in_if_branch)
351 break;
352 }
353 }
354
355 if (!src_var->in_loop) {
356 biv->def_outside_loop = src_var;
357 } else if (is_var_alu(src_var)) {
358 nir_alu_instr *alu = nir_instr_as_alu(src_var->def->parent_instr);
359
360 if (nir_op_infos[alu->op].num_inputs == 2) {
361 biv->alu_def = src_var;
362 biv->alu_op = alu->op;
363
364 for (unsigned i = 0; i < 2; i++) {
365 /* Is one of the operands const, and the other the phi */
366 if (alu->src[i].src.ssa->parent_instr->type == nir_instr_type_load_const &&
367 alu->src[i].swizzle[0] == 0 &&
368 alu->src[1-i].src.ssa == &phi->dest.ssa)
369 assert(alu->src[1-i].swizzle[0] == 0);
370 biv->invariant = get_loop_var(alu->src[i].src.ssa, state);
371 }
372 }
373 }
374 }
375
376 if (biv->alu_def && biv->def_outside_loop && biv->invariant &&
377 is_var_constant(biv->def_outside_loop)) {
378 assert(is_var_constant(biv->invariant));
379 biv->alu_def->type = basic_induction;
380 biv->alu_def->ind = biv;
381 var->type = basic_induction;
382 var->ind = biv;
383
384 found_induction_var = true;
385 } else {
386 ralloc_free(biv);
387 }
388 }
389 return found_induction_var;
390 }
391
392 static bool
393 initialize_ssa_def(nir_ssa_def *def, void *void_state)
394 {
395 loop_info_state *state = void_state;
396 nir_loop_variable *var = get_loop_var(def, state);
397
398 var->in_loop = false;
399 var->def = def;
400
401 if (def->parent_instr->type == nir_instr_type_load_const) {
402 var->type = invariant;
403 } else {
404 var->type = undefined;
405 }
406
407 return true;
408 }
409
410 static bool
411 find_loop_terminators(loop_info_state *state)
412 {
413 bool success = false;
414 foreach_list_typed_safe(nir_cf_node, node, node, &state->loop->body) {
415 if (node->type == nir_cf_node_if) {
416 nir_if *nif = nir_cf_node_as_if(node);
417
418 nir_block *break_blk = NULL;
419 nir_block *continue_from_blk = NULL;
420 bool continue_from_then = true;
421
422 nir_block *last_then = nir_if_last_then_block(nif);
423 nir_block *last_else = nir_if_last_else_block(nif);
424 if (nir_block_ends_in_break(last_then)) {
425 break_blk = last_then;
426 continue_from_blk = last_else;
427 continue_from_then = false;
428 } else if (nir_block_ends_in_break(last_else)) {
429 break_blk = last_else;
430 continue_from_blk = last_then;
431 }
432
433 /* If there is a break then we should find a terminator. If we can
434 * not find a loop terminator, but there is a break-statement then
435 * we should return false so that we do not try to find trip-count
436 */
437 if (!nir_is_trivial_loop_if(nif, break_blk)) {
438 state->loop->info->complex_loop = true;
439 return false;
440 }
441
442 /* Continue if the if contained no jumps at all */
443 if (!break_blk)
444 continue;
445
446 if (nif->condition.ssa->parent_instr->type == nir_instr_type_phi) {
447 state->loop->info->complex_loop = true;
448 return false;
449 }
450
451 nir_loop_terminator *terminator =
452 rzalloc(state->loop->info, nir_loop_terminator);
453
454 list_addtail(&terminator->loop_terminator_link,
455 &state->loop->info->loop_terminator_list);
456
457 terminator->nif = nif;
458 terminator->break_block = break_blk;
459 terminator->continue_from_block = continue_from_blk;
460 terminator->continue_from_then = continue_from_then;
461 terminator->conditional_instr = nif->condition.ssa->parent_instr;
462
463 success = true;
464 }
465 }
466
467 return success;
468 }
469
470 /* This function looks for an array access within a loop that uses an
471 * induction variable for the array index. If found it returns the size of the
472 * array, otherwise 0 is returned. If we find an induction var we pass it back
473 * to the caller via array_index_out.
474 */
475 static unsigned
476 find_array_access_via_induction(loop_info_state *state,
477 nir_deref_instr *deref,
478 nir_loop_variable **array_index_out)
479 {
480 for (nir_deref_instr *d = deref; d; d = nir_deref_instr_parent(d)) {
481 if (d->deref_type != nir_deref_type_array)
482 continue;
483
484 assert(d->arr.index.is_ssa);
485 nir_loop_variable *array_index = get_loop_var(d->arr.index.ssa, state);
486
487 if (array_index->type != basic_induction)
488 continue;
489
490 if (array_index_out)
491 *array_index_out = array_index;
492
493 nir_deref_instr *parent = nir_deref_instr_parent(d);
494 if (glsl_type_is_array_or_matrix(parent->type)) {
495 return glsl_get_length(parent->type);
496 } else {
497 assert(glsl_type_is_vector(parent->type));
498 return glsl_get_vector_elements(parent->type);
499 }
500 }
501
502 return 0;
503 }
504
505 static bool
506 guess_loop_limit(loop_info_state *state, nir_const_value *limit_val,
507 nir_loop_variable *basic_ind)
508 {
509 unsigned min_array_size = 0;
510
511 nir_foreach_block_in_cf_node(block, &state->loop->cf_node) {
512 nir_foreach_instr(instr, block) {
513 if (instr->type != nir_instr_type_intrinsic)
514 continue;
515
516 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
517
518 /* Check for arrays variably-indexed by a loop induction variable. */
519 if (intrin->intrinsic == nir_intrinsic_load_deref ||
520 intrin->intrinsic == nir_intrinsic_store_deref ||
521 intrin->intrinsic == nir_intrinsic_copy_deref) {
522
523 nir_loop_variable *array_idx = NULL;
524 unsigned array_size =
525 find_array_access_via_induction(state,
526 nir_src_as_deref(intrin->src[0]),
527 &array_idx);
528 if (basic_ind == array_idx &&
529 (min_array_size == 0 || min_array_size > array_size)) {
530 min_array_size = array_size;
531 }
532
533 if (intrin->intrinsic != nir_intrinsic_copy_deref)
534 continue;
535
536 array_size =
537 find_array_access_via_induction(state,
538 nir_src_as_deref(intrin->src[1]),
539 &array_idx);
540 if (basic_ind == array_idx &&
541 (min_array_size == 0 || min_array_size > array_size)) {
542 min_array_size = array_size;
543 }
544 }
545 }
546 }
547
548 if (min_array_size) {
549 *limit_val = nir_const_value_for_uint(min_array_size,
550 basic_ind->def->bit_size);
551 return true;
552 }
553
554 return false;
555 }
556
557 static bool
558 try_find_limit_of_alu(nir_loop_variable *limit, nir_const_value *limit_val,
559 nir_loop_terminator *terminator, loop_info_state *state)
560 {
561 if(!is_var_alu(limit))
562 return false;
563
564 nir_alu_instr *limit_alu = nir_instr_as_alu(limit->def->parent_instr);
565
566 if (limit_alu->op == nir_op_imin ||
567 limit_alu->op == nir_op_fmin) {
568 /* We don't handle swizzles here */
569 if (limit_alu->src[0].swizzle[0] > 0 || limit_alu->src[1].swizzle[0] > 0)
570 return false;
571
572 limit = get_loop_var(limit_alu->src[0].src.ssa, state);
573
574 if (!is_var_constant(limit))
575 limit = get_loop_var(limit_alu->src[1].src.ssa, state);
576
577 if (!is_var_constant(limit))
578 return false;
579
580 *limit_val = nir_instr_as_load_const(limit->def->parent_instr)->value[0];
581
582 terminator->exact_trip_count_unknown = true;
583
584 return true;
585 }
586
587 return false;
588 }
589
590 static nir_const_value
591 eval_const_unop(nir_op op, unsigned bit_size, nir_const_value src0)
592 {
593 assert(nir_op_infos[op].num_inputs == 1);
594 nir_const_value dest;
595 nir_const_value *src[1] = { &src0 };
596 nir_eval_const_opcode(op, &dest, 1, bit_size, src);
597 return dest;
598 }
599
600 static nir_const_value
601 eval_const_binop(nir_op op, unsigned bit_size,
602 nir_const_value src0, nir_const_value src1)
603 {
604 assert(nir_op_infos[op].num_inputs == 2);
605 nir_const_value dest;
606 nir_const_value *src[2] = { &src0, &src1 };
607 nir_eval_const_opcode(op, &dest, 1, bit_size, src);
608 return dest;
609 }
610
611 static int32_t
612 get_iteration(nir_op cond_op, nir_const_value initial, nir_const_value step,
613 nir_const_value limit, unsigned bit_size)
614 {
615 nir_const_value span, iter;
616
617 switch (cond_op) {
618 case nir_op_ige:
619 case nir_op_ilt:
620 case nir_op_ieq:
621 case nir_op_ine:
622 span = eval_const_binop(nir_op_isub, bit_size, limit, initial);
623 iter = eval_const_binop(nir_op_idiv, bit_size, span, step);
624 break;
625
626 case nir_op_uge:
627 case nir_op_ult:
628 span = eval_const_binop(nir_op_isub, bit_size, limit, initial);
629 iter = eval_const_binop(nir_op_udiv, bit_size, span, step);
630 break;
631
632 case nir_op_fge:
633 case nir_op_flt:
634 case nir_op_feq:
635 case nir_op_fne:
636 span = eval_const_binop(nir_op_fsub, bit_size, limit, initial);
637 iter = eval_const_binop(nir_op_fdiv, bit_size, span, step);
638 iter = eval_const_unop(nir_op_f2i64, bit_size, iter);
639 break;
640
641 default:
642 return -1;
643 }
644
645 uint64_t iter_u64 = nir_const_value_as_uint(iter, bit_size);
646 return iter_u64 > INT_MAX ? -1 : (int)iter_u64;
647 }
648
649 static bool
650 test_iterations(int32_t iter_int, nir_const_value *step,
651 nir_const_value *limit, nir_op cond_op, unsigned bit_size,
652 nir_alu_type induction_base_type,
653 nir_const_value *initial, bool limit_rhs, bool invert_cond)
654 {
655 assert(nir_op_infos[cond_op].num_inputs == 2);
656
657 nir_const_value iter_src;
658 nir_op mul_op;
659 nir_op add_op;
660 switch (induction_base_type) {
661 case nir_type_float:
662 iter_src = nir_const_value_for_float(iter_int, bit_size);
663 mul_op = nir_op_fmul;
664 add_op = nir_op_fadd;
665 break;
666 case nir_type_int:
667 case nir_type_uint:
668 iter_src = nir_const_value_for_int(iter_int, bit_size);
669 mul_op = nir_op_imul;
670 add_op = nir_op_iadd;
671 break;
672 default:
673 unreachable("Unhandled induction variable base type!");
674 }
675
676 /* Multiple the iteration count we are testing by the number of times we
677 * step the induction variable each iteration.
678 */
679 nir_const_value mul_result =
680 eval_const_binop(mul_op, bit_size, iter_src, *step);
681
682 /* Add the initial value to the accumulated induction variable total */
683 nir_const_value add_result =
684 eval_const_binop(add_op, bit_size, mul_result, *initial);
685
686 nir_const_value *src[2];
687 src[limit_rhs ? 0 : 1] = &add_result;
688 src[limit_rhs ? 1 : 0] = limit;
689
690 /* Evaluate the loop exit condition */
691 nir_const_value result;
692 nir_eval_const_opcode(cond_op, &result, 1, bit_size, src);
693
694 return invert_cond ? !result.b : result.b;
695 }
696
697 static int
698 calculate_iterations(nir_const_value *initial, nir_const_value *step,
699 nir_const_value *limit, nir_loop_variable *alu_def,
700 nir_alu_instr *cond_alu, nir_op alu_op, bool limit_rhs,
701 bool invert_cond)
702 {
703 assert(initial != NULL && step != NULL && limit != NULL);
704
705 nir_alu_instr *alu = nir_instr_as_alu(alu_def->def->parent_instr);
706
707 /* nir_op_isub should have been lowered away by this point */
708 assert(alu->op != nir_op_isub);
709
710 /* Make sure the alu type for our induction variable is compatible with the
711 * conditional alus input type. If its not something has gone really wrong.
712 */
713 nir_alu_type induction_base_type =
714 nir_alu_type_get_base_type(nir_op_infos[alu->op].output_type);
715 if (induction_base_type == nir_type_int || induction_base_type == nir_type_uint) {
716 assert(nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[1]) == nir_type_int ||
717 nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[1]) == nir_type_uint);
718 } else {
719 assert(nir_alu_type_get_base_type(nir_op_infos[alu_op].input_types[0]) ==
720 induction_base_type);
721 }
722
723 /* Check for nsupported alu operations */
724 if (alu->op != nir_op_iadd && alu->op != nir_op_fadd)
725 return -1;
726
727 /* do-while loops can increment the starting value before the condition is
728 * checked. e.g.
729 *
730 * do {
731 * ndx++;
732 * } while (ndx < 3);
733 *
734 * Here we check if the induction variable is used directly by the loop
735 * condition and if so we assume we need to step the initial value.
736 */
737 unsigned trip_offset = 0;
738 if (cond_alu->src[0].src.ssa == alu_def->def ||
739 cond_alu->src[1].src.ssa == alu_def->def) {
740 trip_offset = 1;
741 }
742
743 assert(nir_src_bit_size(alu->src[0].src) ==
744 nir_src_bit_size(alu->src[1].src));
745 unsigned bit_size = nir_src_bit_size(alu->src[0].src);
746 int iter_int = get_iteration(alu_op, *initial, *step, *limit, bit_size);
747
748 /* If iter_int is negative the loop is ill-formed or is the conditional is
749 * unsigned with a huge iteration count so don't bother going any further.
750 */
751 if (iter_int < 0)
752 return -1;
753
754 /* An explanation from the GLSL unrolling pass:
755 *
756 * Make sure that the calculated number of iterations satisfies the exit
757 * condition. This is needed to catch off-by-one errors and some types of
758 * ill-formed loops. For example, we need to detect that the following
759 * loop does not have a maximum iteration count.
760 *
761 * for (float x = 0.0; x != 0.9; x += 0.2);
762 */
763 for (int bias = -1; bias <= 1; bias++) {
764 const int iter_bias = iter_int + bias;
765
766 if (test_iterations(iter_bias, step, limit, alu_op, bit_size,
767 induction_base_type, initial,
768 limit_rhs, invert_cond)) {
769 return iter_bias > 0 ? iter_bias - trip_offset : iter_bias;
770 }
771 }
772
773 return -1;
774 }
775
776 static nir_op
777 inverse_comparison(nir_alu_instr *alu)
778 {
779 switch (alu->op) {
780 case nir_op_fge:
781 return nir_op_flt;
782 case nir_op_ige:
783 return nir_op_ilt;
784 case nir_op_uge:
785 return nir_op_ult;
786 case nir_op_flt:
787 return nir_op_fge;
788 case nir_op_ilt:
789 return nir_op_ige;
790 case nir_op_ult:
791 return nir_op_uge;
792 case nir_op_feq:
793 return nir_op_fne;
794 case nir_op_ieq:
795 return nir_op_ine;
796 case nir_op_fne:
797 return nir_op_feq;
798 case nir_op_ine:
799 return nir_op_ieq;
800 default:
801 unreachable("Unsuported comparison!");
802 }
803 }
804
805 static bool
806 is_supported_terminator_condition(nir_alu_instr *alu)
807 {
808 return nir_alu_instr_is_comparison(alu) &&
809 nir_op_infos[alu->op].num_inputs == 2;
810 }
811
812 static bool
813 get_induction_and_limit_vars(nir_alu_instr *alu, nir_loop_variable **ind,
814 nir_loop_variable **limit,
815 loop_info_state *state)
816 {
817 bool limit_rhs = true;
818
819 /* We assume that the limit is the "right" operand */
820 *ind = get_loop_var(alu->src[0].src.ssa, state);
821 *limit = get_loop_var(alu->src[1].src.ssa, state);
822
823 if ((*ind)->type != basic_induction) {
824 /* We had it the wrong way, flip things around */
825 *ind = get_loop_var(alu->src[1].src.ssa, state);
826 *limit = get_loop_var(alu->src[0].src.ssa, state);
827 limit_rhs = false;
828 }
829
830 return limit_rhs;
831 }
832
833 static void
834 try_find_trip_count_vars_in_iand(nir_alu_instr **alu,
835 nir_loop_variable **ind,
836 nir_loop_variable **limit,
837 bool *limit_rhs,
838 loop_info_state *state)
839 {
840 assert((*alu)->op == nir_op_ieq || (*alu)->op == nir_op_inot);
841
842 nir_ssa_def *iand_def = (*alu)->src[0].src.ssa;
843 /* This is used directly in an if condition so it must be a scalar */
844 assert(iand_def->num_components == 1);
845
846 if ((*alu)->op == nir_op_ieq) {
847 nir_ssa_def *zero_def = (*alu)->src[1].src.ssa;
848
849 /* We don't handle swizzles here */
850 if ((*alu)->src[0].swizzle[0] > 0 || (*alu)->src[1].swizzle[0] > 0)
851 return;
852
853 if (iand_def->parent_instr->type != nir_instr_type_alu ||
854 zero_def->parent_instr->type != nir_instr_type_load_const) {
855
856 /* Maybe we had it the wrong way, flip things around */
857 iand_def = (*alu)->src[1].src.ssa;
858 zero_def = (*alu)->src[0].src.ssa;
859
860 /* If we still didn't find what we need then return */
861 if (zero_def->parent_instr->type != nir_instr_type_load_const)
862 return;
863 }
864
865 /* If the loop is not breaking on (x && y) == 0 then return */
866 nir_const_value *zero =
867 nir_instr_as_load_const(zero_def->parent_instr)->value;
868 if (zero[0].i32 != 0)
869 return;
870 }
871
872 if (iand_def->parent_instr->type != nir_instr_type_alu)
873 return;
874
875 nir_alu_instr *iand = nir_instr_as_alu(iand_def->parent_instr);
876 if (iand->op != nir_op_iand)
877 return;
878
879 /* We don't handle swizzles here */
880 if ((*alu)->src[0].swizzle[0] > 0 || (*alu)->src[1].swizzle[0] > 0)
881 return;
882
883 /* Check if iand src is a terminator condition and try get induction var
884 * and trip limit var.
885 */
886 nir_ssa_def *src = iand->src[0].src.ssa;
887 if (src->parent_instr->type == nir_instr_type_alu) {
888 *alu = nir_instr_as_alu(src->parent_instr);
889 if (is_supported_terminator_condition(*alu))
890 *limit_rhs = get_induction_and_limit_vars(*alu, ind, limit, state);
891 }
892
893 /* Try the other iand src if needed */
894 if (*ind == NULL || (*ind && (*ind)->type != basic_induction) ||
895 !is_var_constant(*limit)) {
896 src = iand->src[1].src.ssa;
897 if (src->parent_instr->type == nir_instr_type_alu) {
898 nir_alu_instr *tmp_alu = nir_instr_as_alu(src->parent_instr);
899 if (is_supported_terminator_condition(tmp_alu)) {
900 *alu = tmp_alu;
901 *limit_rhs = get_induction_and_limit_vars(*alu, ind, limit, state);
902 }
903 }
904 }
905 }
906
907 /* Run through each of the terminators of the loop and try to infer a possible
908 * trip-count. We need to check them all, and set the lowest trip-count as the
909 * trip-count of our loop. If one of the terminators has an undecidable
910 * trip-count we can not safely assume anything about the duration of the
911 * loop.
912 */
913 static void
914 find_trip_count(loop_info_state *state)
915 {
916 bool trip_count_known = true;
917 bool guessed_trip_count = false;
918 nir_loop_terminator *limiting_terminator = NULL;
919 int max_trip_count = -1;
920
921 list_for_each_entry(nir_loop_terminator, terminator,
922 &state->loop->info->loop_terminator_list,
923 loop_terminator_link) {
924
925 if (terminator->conditional_instr->type != nir_instr_type_alu) {
926 /* If we get here the loop is dead and will get cleaned up by the
927 * nir_opt_dead_cf pass.
928 */
929 trip_count_known = false;
930 continue;
931 }
932
933 nir_alu_instr *alu = nir_instr_as_alu(terminator->conditional_instr);
934 nir_op alu_op = alu->op;
935
936 bool limit_rhs;
937 nir_loop_variable *basic_ind = NULL;
938 nir_loop_variable *limit;
939 if (alu->op == nir_op_inot || alu->op == nir_op_ieq) {
940 nir_alu_instr *new_alu = alu;
941 try_find_trip_count_vars_in_iand(&new_alu, &basic_ind, &limit,
942 &limit_rhs, state);
943
944 /* The loop is exiting on (x && y) == 0 so we need to get the
945 * inverse of x or y (i.e. which ever contained the induction var) in
946 * order to compute the trip count.
947 */
948 if (basic_ind && basic_ind->type == basic_induction) {
949 alu = new_alu;
950 alu_op = inverse_comparison(alu);
951 trip_count_known = false;
952 terminator->exact_trip_count_unknown = true;
953 }
954 }
955
956 if (!basic_ind) {
957 if (!is_supported_terminator_condition(alu)) {
958 trip_count_known = false;
959 continue;
960 }
961
962 limit_rhs = get_induction_and_limit_vars(alu, &basic_ind, &limit,
963 state);
964 }
965
966 /* The comparison has to have a basic induction variable for us to be
967 * able to find trip counts.
968 */
969 if (basic_ind->type != basic_induction) {
970 trip_count_known = false;
971 continue;
972 }
973
974 terminator->induction_rhs = !limit_rhs;
975
976 /* Attempt to find a constant limit for the loop */
977 nir_const_value limit_val;
978 if (is_var_constant(limit)) {
979 limit_val =
980 nir_instr_as_load_const(limit->def->parent_instr)->value[0];
981 } else {
982 trip_count_known = false;
983
984 if (!try_find_limit_of_alu(limit, &limit_val, terminator, state)) {
985 /* Guess loop limit based on array access */
986 if (!guess_loop_limit(state, &limit_val, basic_ind)) {
987 continue;
988 }
989
990 guessed_trip_count = true;
991 }
992 }
993
994 /* We have determined that we have the following constants:
995 * (With the typical int i = 0; i < x; i++; as an example)
996 * - Upper limit.
997 * - Starting value
998 * - Step / iteration size
999 * Thats all thats needed to calculate the trip-count
1000 */
1001
1002 nir_const_value *initial_val =
1003 nir_instr_as_load_const(basic_ind->ind->def_outside_loop->
1004 def->parent_instr)->value;
1005
1006 nir_const_value *step_val =
1007 nir_instr_as_load_const(basic_ind->ind->invariant->def->
1008 parent_instr)->value;
1009
1010 int iterations = calculate_iterations(initial_val, step_val,
1011 &limit_val,
1012 basic_ind->ind->alu_def, alu,
1013 alu_op, limit_rhs,
1014 terminator->continue_from_then);
1015
1016 /* Where we not able to calculate the iteration count */
1017 if (iterations == -1) {
1018 trip_count_known = false;
1019 guessed_trip_count = false;
1020 continue;
1021 }
1022
1023 if (guessed_trip_count) {
1024 guessed_trip_count = false;
1025 if (state->loop->info->guessed_trip_count == 0 ||
1026 state->loop->info->guessed_trip_count > iterations)
1027 state->loop->info->guessed_trip_count = iterations;
1028
1029 continue;
1030 }
1031
1032 /* If this is the first run or we have found a smaller amount of
1033 * iterations than previously (we have identified a more limiting
1034 * terminator) set the trip count and limiting terminator.
1035 */
1036 if (max_trip_count == -1 || iterations < max_trip_count) {
1037 max_trip_count = iterations;
1038 limiting_terminator = terminator;
1039 }
1040 }
1041
1042 state->loop->info->exact_trip_count_known = trip_count_known;
1043 if (max_trip_count > -1)
1044 state->loop->info->max_trip_count = max_trip_count;
1045 state->loop->info->limiting_terminator = limiting_terminator;
1046 }
1047
1048 static bool
1049 force_unroll_array_access(loop_info_state *state, nir_deref_instr *deref)
1050 {
1051 unsigned array_size = find_array_access_via_induction(state, deref, NULL);
1052 if (array_size) {
1053 if (array_size == state->loop->info->max_trip_count)
1054 return true;
1055
1056 if (deref->mode & state->indirect_mask)
1057 return true;
1058 }
1059
1060 return false;
1061 }
1062
1063 static bool
1064 force_unroll_heuristics(loop_info_state *state, nir_block *block)
1065 {
1066 nir_foreach_instr(instr, block) {
1067 if (instr->type != nir_instr_type_intrinsic)
1068 continue;
1069
1070 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
1071
1072 /* Check for arrays variably-indexed by a loop induction variable.
1073 * Unrolling the loop may convert that access into constant-indexing.
1074 */
1075 if (intrin->intrinsic == nir_intrinsic_load_deref ||
1076 intrin->intrinsic == nir_intrinsic_store_deref ||
1077 intrin->intrinsic == nir_intrinsic_copy_deref) {
1078 if (force_unroll_array_access(state,
1079 nir_src_as_deref(intrin->src[0])))
1080 return true;
1081
1082 if (intrin->intrinsic == nir_intrinsic_copy_deref &&
1083 force_unroll_array_access(state,
1084 nir_src_as_deref(intrin->src[1])))
1085 return true;
1086 }
1087 }
1088
1089 return false;
1090 }
1091
1092 static void
1093 get_loop_info(loop_info_state *state, nir_function_impl *impl)
1094 {
1095 nir_shader *shader = impl->function->shader;
1096 const nir_shader_compiler_options *options = shader->options;
1097
1098 /* Initialize all variables to "outside_loop". This also marks defs
1099 * invariant and constant if they are nir_instr_type_load_consts
1100 */
1101 nir_foreach_block(block, impl) {
1102 nir_foreach_instr(instr, block)
1103 nir_foreach_ssa_def(instr, initialize_ssa_def, state);
1104 }
1105
1106 /* Add all entries in the outermost part of the loop to the processing list
1107 * Mark the entries in conditionals or in nested loops accordingly
1108 */
1109 foreach_list_typed_safe(nir_cf_node, node, node, &state->loop->body) {
1110 switch (node->type) {
1111
1112 case nir_cf_node_block:
1113 init_loop_block(nir_cf_node_as_block(node), state,
1114 false, false, options);
1115 break;
1116
1117 case nir_cf_node_if:
1118 nir_foreach_block_in_cf_node(block, node)
1119 init_loop_block(block, state, true, false, options);
1120 break;
1121
1122 case nir_cf_node_loop:
1123 nir_foreach_block_in_cf_node(block, node) {
1124 init_loop_block(block, state, false, true, options);
1125 }
1126 break;
1127
1128 case nir_cf_node_function:
1129 break;
1130 }
1131 }
1132
1133 /* Try to find all simple terminators of the loop. If we can't find any,
1134 * or we find possible terminators that have side effects then bail.
1135 */
1136 if (!find_loop_terminators(state)) {
1137 list_for_each_entry_safe(nir_loop_terminator, terminator,
1138 &state->loop->info->loop_terminator_list,
1139 loop_terminator_link) {
1140 list_del(&terminator->loop_terminator_link);
1141 ralloc_free(terminator);
1142 }
1143 return;
1144 }
1145
1146 /* Induction analysis needs invariance information so get that first */
1147 compute_invariance_information(state);
1148
1149 /* We have invariance information so try to find induction variables */
1150 if (!compute_induction_information(state))
1151 return;
1152
1153 /* Run through each of the terminators and try to compute a trip-count */
1154 find_trip_count(state);
1155
1156 nir_foreach_block_in_cf_node(block, &state->loop->cf_node) {
1157 if (force_unroll_heuristics(state, block)) {
1158 state->loop->info->force_unroll = true;
1159 break;
1160 }
1161 }
1162 }
1163
1164 static loop_info_state *
1165 initialize_loop_info_state(nir_loop *loop, void *mem_ctx,
1166 nir_function_impl *impl)
1167 {
1168 loop_info_state *state = rzalloc(mem_ctx, loop_info_state);
1169 state->loop_vars = rzalloc_array(mem_ctx, nir_loop_variable,
1170 impl->ssa_alloc);
1171 state->loop = loop;
1172
1173 list_inithead(&state->process_list);
1174
1175 if (loop->info)
1176 ralloc_free(loop->info);
1177
1178 loop->info = rzalloc(loop, nir_loop_info);
1179
1180 list_inithead(&loop->info->loop_terminator_list);
1181
1182 return state;
1183 }
1184
1185 static void
1186 process_loops(nir_cf_node *cf_node, nir_variable_mode indirect_mask)
1187 {
1188 switch (cf_node->type) {
1189 case nir_cf_node_block:
1190 return;
1191 case nir_cf_node_if: {
1192 nir_if *if_stmt = nir_cf_node_as_if(cf_node);
1193 foreach_list_typed(nir_cf_node, nested_node, node, &if_stmt->then_list)
1194 process_loops(nested_node, indirect_mask);
1195 foreach_list_typed(nir_cf_node, nested_node, node, &if_stmt->else_list)
1196 process_loops(nested_node, indirect_mask);
1197 return;
1198 }
1199 case nir_cf_node_loop: {
1200 nir_loop *loop = nir_cf_node_as_loop(cf_node);
1201 foreach_list_typed(nir_cf_node, nested_node, node, &loop->body)
1202 process_loops(nested_node, indirect_mask);
1203 break;
1204 }
1205 default:
1206 unreachable("unknown cf node type");
1207 }
1208
1209 nir_loop *loop = nir_cf_node_as_loop(cf_node);
1210 nir_function_impl *impl = nir_cf_node_get_function(cf_node);
1211 void *mem_ctx = ralloc_context(NULL);
1212
1213 loop_info_state *state = initialize_loop_info_state(loop, mem_ctx, impl);
1214 state->indirect_mask = indirect_mask;
1215
1216 get_loop_info(state, impl);
1217
1218 ralloc_free(mem_ctx);
1219 }
1220
1221 void
1222 nir_loop_analyze_impl(nir_function_impl *impl,
1223 nir_variable_mode indirect_mask)
1224 {
1225 nir_index_ssa_defs(impl);
1226 foreach_list_typed(nir_cf_node, node, node, &impl->body)
1227 process_loops(node, indirect_mask);
1228 }