• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2010 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
21  * DEALINGS IN THE SOFTWARE.
22  */
23 
24 #include "compiler/glsl_types.h"
25 #include "loop_analysis.h"
26 #include "ir_hierarchical_visitor.h"
27 
28 #include "main/mtypes.h"
29 
30 namespace {
31 
32 class loop_unroll_visitor : public ir_hierarchical_visitor {
33 public:
loop_unroll_visitor(loop_state * state,const struct gl_shader_compiler_options * options)34    loop_unroll_visitor(loop_state *state,
35                        const struct gl_shader_compiler_options *options)
36    {
37       this->state = state;
38       this->progress = false;
39       this->options = options;
40    }
41 
42    virtual ir_visitor_status visit_leave(ir_loop *ir);
43    void simple_unroll(ir_loop *ir, int iterations);
44    void complex_unroll(ir_loop *ir, int iterations,
45                        bool continue_from_then_branch,
46                        bool limiting_term_first,
47                        bool lt_continue_from_then_branch);
48    void splice_post_if_instructions(ir_if *ir_if, exec_list *splice_dest);
49 
50    loop_state *state;
51 
52    bool progress;
53    const struct gl_shader_compiler_options *options;
54 };
55 
56 } /* anonymous namespace */
57 
58 class loop_unroll_count : public ir_hierarchical_visitor {
59 public:
60    int nodes;
61    bool unsupported_variable_indexing;
62    bool array_indexed_by_induction_var_with_exact_iterations;
63    /* If there are nested loops, the node count will be inaccurate. */
64    bool nested_loop;
65 
loop_unroll_count(exec_list * list,loop_variable_state * ls,const struct gl_shader_compiler_options * options)66    loop_unroll_count(exec_list *list, loop_variable_state *ls,
67                      const struct gl_shader_compiler_options *options)
68       : ls(ls), options(options)
69    {
70       nodes = 0;
71       nested_loop = false;
72       unsupported_variable_indexing = false;
73       array_indexed_by_induction_var_with_exact_iterations = false;
74 
75       run(list);
76    }
77 
visit_enter(ir_assignment *)78    virtual ir_visitor_status visit_enter(ir_assignment *)
79    {
80       nodes++;
81       return visit_continue;
82    }
83 
visit_enter(ir_expression *)84    virtual ir_visitor_status visit_enter(ir_expression *)
85    {
86       nodes++;
87       return visit_continue;
88    }
89 
visit_enter(ir_loop *)90    virtual ir_visitor_status visit_enter(ir_loop *)
91    {
92       nested_loop = true;
93       return visit_continue;
94    }
95 
visit_enter(ir_dereference_array * ir)96    virtual ir_visitor_status visit_enter(ir_dereference_array *ir)
97    {
98       /* Force unroll in case of dynamic indexing with sampler arrays
99        * when EmitNoIndirectSampler is set.
100        */
101       if (options->EmitNoIndirectSampler) {
102          if ((ir->array->type->is_array() &&
103               ir->array->type->contains_sampler()) &&
104              !ir->array_index->constant_expression_value(ralloc_parent(ir))) {
105             unsupported_variable_indexing = true;
106             return visit_continue;
107          }
108       }
109 
110       /* Check for arrays variably-indexed by a loop induction variable.
111        * Unrolling the loop may convert that access into constant-indexing.
112        *
113        * Many drivers don't support particular kinds of variable indexing,
114        * and have to resort to using lower_variable_index_to_cond_assign to
115        * handle it.  This results in huge amounts of horrible code, so we'd
116        * like to avoid that if possible.  Here, we just note that it will
117        * happen.
118        */
119       if ((ir->array->type->is_array() || ir->array->type->is_matrix()) &&
120           !ir->array_index->as_constant()) {
121          ir_variable *array = ir->array->variable_referenced();
122          loop_variable *lv = ls->get(ir->array_index->variable_referenced());
123          if (array && lv && lv->is_induction_var()) {
124             /* If an array is indexed by a loop induction variable, and the
125              * array size is exactly the number of loop iterations, this is
126              * probably a simple for-loop trying to access each element in
127              * turn; the application may expect it to be unrolled.
128              */
129             if (int(array->type->length) == ls->limiting_terminator->iterations)
130                array_indexed_by_induction_var_with_exact_iterations = true;
131 
132             switch (array->data.mode) {
133             case ir_var_auto:
134             case ir_var_temporary:
135             case ir_var_const_in:
136             case ir_var_function_in:
137             case ir_var_function_out:
138             case ir_var_function_inout:
139                if (options->EmitNoIndirectTemp)
140                   unsupported_variable_indexing = true;
141                break;
142             case ir_var_uniform:
143             case ir_var_shader_storage:
144                if (options->EmitNoIndirectUniform)
145                   unsupported_variable_indexing = true;
146                break;
147             case ir_var_shader_in:
148                if (options->EmitNoIndirectInput)
149                   unsupported_variable_indexing = true;
150                break;
151             case ir_var_shader_out:
152                if (options->EmitNoIndirectOutput)
153                   unsupported_variable_indexing = true;
154                break;
155             }
156          }
157       }
158       return visit_continue;
159    }
160 
161 private:
162    loop_variable_state *ls;
163    const struct gl_shader_compiler_options *options;
164 };
165 
166 
167 /**
168  * Unroll a loop which does not contain any jumps.  For example, if the input
169  * is:
170  *
171  *     (loop (...) ...instrs...)
172  *
173  * And the iteration count is 3, the output will be:
174  *
175  *     ...instrs... ...instrs... ...instrs...
176  */
177 void
simple_unroll(ir_loop * ir,int iterations)178 loop_unroll_visitor::simple_unroll(ir_loop *ir, int iterations)
179 {
180    void *const mem_ctx = ralloc_parent(ir);
181    loop_variable_state *const ls = this->state->get(ir);
182 
183    ir_instruction *first_ir =
184       (ir_instruction *) ir->body_instructions.get_head();
185 
186    if (!first_ir) {
187       /* The loop is empty remove it and return */
188       ir->remove();
189       return;
190    }
191 
192    ir_if *limit_if = NULL;
193    bool exit_branch_has_instructions = false;
194    if (ls->limiting_terminator) {
195       limit_if = ls->limiting_terminator->ir;
196       ir_instruction *ir_if_last = (ir_instruction *)
197          limit_if->then_instructions.get_tail();
198 
199       if (is_break(ir_if_last)) {
200          if (ir_if_last != limit_if->then_instructions.get_head())
201             exit_branch_has_instructions = true;
202 
203          splice_post_if_instructions(limit_if, &limit_if->else_instructions);
204          ir_if_last->remove();
205       } else {
206          ir_if_last = (ir_instruction *)
207             limit_if->else_instructions.get_tail();
208          assert(is_break(ir_if_last));
209 
210          if (ir_if_last != limit_if->else_instructions.get_head())
211             exit_branch_has_instructions = true;
212 
213          splice_post_if_instructions(limit_if, &limit_if->then_instructions);
214          ir_if_last->remove();
215       }
216    }
217 
218    /* Because 'iterations' is the number of times we pass over the *entire*
219     * loop body before hitting the first break, we need to bump the number of
220     * iterations if the limiting terminator is not the first instruction in
221     * the loop, or it the exit branch contains instructions. This ensures we
222     * execute any instructions before the terminator or in its exit branch.
223     */
224    if (limit_if != first_ir->as_if() || exit_branch_has_instructions)
225       iterations++;
226 
227    for (int i = 0; i < iterations; i++) {
228       exec_list copy_list;
229 
230       copy_list.make_empty();
231       clone_ir_list(mem_ctx, &copy_list, &ir->body_instructions);
232 
233       ir->insert_before(&copy_list);
234    }
235 
236    /* The loop has been replaced by the unrolled copies.  Remove the original
237     * loop from the IR sequence.
238     */
239    ir->remove();
240 
241    this->progress = true;
242 }
243 
244 
245 /**
246  * Unroll a loop whose last statement is an ir_if.  If \c
247  * continue_from_then_branch is true, the loop is repeated only when the
248  * "then" branch of the if is taken; otherwise it is repeated only when the
249  * "else" branch of the if is taken.
250  *
251  * For example, if the input is:
252  *
253  *     (loop (...)
254  *      ...body...
255  *      (if (cond)
256  *          (...then_instrs...)
257  *        (...else_instrs...)))
258  *
259  * And the iteration count is 3, and \c continue_from_then_branch is true,
260  * then the output will be:
261  *
262  *     ...body...
263  *     (if (cond)
264  *         (...then_instrs...
265  *          ...body...
266  *          (if (cond)
267  *              (...then_instrs...
268  *               ...body...
269  *               (if (cond)
270  *                   (...then_instrs...)
271  *                 (...else_instrs...)))
272  *            (...else_instrs...)))
273  *       (...else_instrs))
274  */
275 void
complex_unroll(ir_loop * ir,int iterations,bool second_term_then_continue,bool extra_iteration_required,bool first_term_then_continue)276 loop_unroll_visitor::complex_unroll(ir_loop *ir, int iterations,
277                                     bool second_term_then_continue,
278                                     bool extra_iteration_required,
279                                     bool first_term_then_continue)
280 {
281    void *const mem_ctx = ralloc_parent(ir);
282    ir_instruction *ir_to_replace = ir;
283 
284    /* Because 'iterations' is the number of times we pass over the *entire*
285     * loop body before hitting the first break, we need to bump the number of
286     * iterations if the limiting terminator is not the first instruction in
287     * the loop, or it the exit branch contains instructions. This ensures we
288     * execute any instructions before the terminator or in its exit branch.
289     */
290    if (extra_iteration_required)
291       iterations++;
292 
293    for (int i = 0; i < iterations; i++) {
294       exec_list copy_list;
295 
296       copy_list.make_empty();
297       clone_ir_list(mem_ctx, &copy_list, &ir->body_instructions);
298 
299       ir_if *ir_if = ((ir_instruction *) copy_list.get_tail())->as_if();
300       assert(ir_if != NULL);
301 
302       exec_list *const first_list = first_term_then_continue
303          ? &ir_if->then_instructions : &ir_if->else_instructions;
304       ir_if = ((ir_instruction *) first_list->get_tail())->as_if();
305 
306       ir_to_replace->insert_before(&copy_list);
307       ir_to_replace->remove();
308 
309       /* placeholder that will be removed in the next iteration */
310       ir_to_replace =
311          new(mem_ctx) ir_loop_jump(ir_loop_jump::jump_continue);
312 
313       exec_list *const second_term_continue_list = second_term_then_continue
314          ? &ir_if->then_instructions : &ir_if->else_instructions;
315 
316       second_term_continue_list->push_tail(ir_to_replace);
317    }
318 
319    ir_to_replace->remove();
320 
321    this->progress = true;
322 }
323 
324 
325 /**
326  * Move all of the instructions which follow \c ir_if to the end of
327  * \c splice_dest.
328  *
329  * For example, in the code snippet:
330  *
331  *     (if (cond)
332  *         (...then_instructions...
333  *          break)
334  *       (...else_instructions...))
335  *     ...post_if_instructions...
336  *
337  * If \c ir_if points to the "if" instruction, and \c splice_dest points to
338  * (...else_instructions...), the code snippet is transformed into:
339  *
340  *     (if (cond)
341  *         (...then_instructions...
342  *          break)
343  *       (...else_instructions...
344  *        ...post_if_instructions...))
345  */
346 void
splice_post_if_instructions(ir_if * ir_if,exec_list * splice_dest)347 loop_unroll_visitor::splice_post_if_instructions(ir_if *ir_if,
348                                                  exec_list *splice_dest)
349 {
350    while (!ir_if->get_next()->is_tail_sentinel()) {
351       ir_instruction *move_ir = (ir_instruction *) ir_if->get_next();
352 
353       move_ir->remove();
354       splice_dest->push_tail(move_ir);
355    }
356 }
357 
358 static bool
exit_branch_has_instructions(ir_if * term_if,bool lt_then_continue)359 exit_branch_has_instructions(ir_if *term_if, bool lt_then_continue)
360 {
361    if (lt_then_continue) {
362       if (term_if->else_instructions.get_head() ==
363           term_if->else_instructions.get_tail())
364          return false;
365    } else {
366       if (term_if->then_instructions.get_head() ==
367           term_if->then_instructions.get_tail())
368          return false;
369    }
370 
371    return true;
372 }
373 
374 ir_visitor_status
visit_leave(ir_loop * ir)375 loop_unroll_visitor::visit_leave(ir_loop *ir)
376 {
377    loop_variable_state *const ls = this->state->get(ir);
378 
379    /* If we've entered a loop that hasn't been analyzed, something really,
380     * really bad has happened.
381     */
382    if (ls == NULL) {
383       assert(ls != NULL);
384       return visit_continue;
385    }
386 
387    if (ls->limiting_terminator != NULL) {
388       /* If the limiting terminator has an iteration count of zero, then we've
389        * proven that the loop cannot run, so delete it.
390        */
391       int iterations = ls->limiting_terminator->iterations;
392       if (iterations == 0) {
393          ir->remove();
394          this->progress = true;
395          return visit_continue;
396       }
397    }
398 
399    /* Remove the conditional break statements associated with all terminators
400     * that are associated with a fixed iteration count, except for the one
401     * associated with the limiting terminator--that one needs to stay, since
402     * it terminates the loop.  Exception: if the loop still has a normative
403     * bound, then that terminates the loop, so we don't even need the limiting
404     * terminator.
405     */
406    foreach_in_list_safe(loop_terminator, t, &ls->terminators) {
407       if (t->iterations < 0)
408          continue;
409 
410       exec_list *branch_instructions;
411       if (t != ls->limiting_terminator) {
412          ir_instruction *ir_if_last = (ir_instruction *)
413             t->ir->then_instructions.get_tail();
414          if (is_break(ir_if_last)) {
415             branch_instructions = &t->ir->else_instructions;
416          } else {
417             branch_instructions = &t->ir->then_instructions;
418             assert(is_break((ir_instruction *)
419                             t->ir->else_instructions.get_tail()));
420          }
421 
422          exec_list copy_list;
423          copy_list.make_empty();
424          clone_ir_list(ir, &copy_list, branch_instructions);
425 
426          t->ir->insert_before(&copy_list);
427          t->ir->remove();
428 
429          assert(ls->num_loop_jumps > 0);
430          ls->num_loop_jumps--;
431 
432          /* Also remove it from the terminator list */
433          t->remove();
434 
435          this->progress = true;
436       }
437    }
438 
439    if (ls->limiting_terminator == NULL) {
440       ir_instruction *last_ir =
441          (ir_instruction *) ir->body_instructions.get_tail();
442 
443       /* If a loop has no induction variable and the last instruction is
444        * a break, unroll the loop with a count of 1.  This is the classic
445        *
446        *    do {
447        *        // ...
448        *    } while (false)
449        *
450        * that is used to wrap multi-line macros.
451        *
452        * If num_loop_jumps is not zero, last_ir cannot be NULL... there has to
453        * be at least num_loop_jumps instructions in the loop.
454        */
455       if (ls->num_loop_jumps == 1 && is_break(last_ir)) {
456          last_ir->remove();
457 
458          simple_unroll(ir, 1);
459       }
460 
461       /* Don't try to unroll loops where the number of iterations is not known
462        * at compile-time.
463        */
464       return visit_continue;
465    }
466 
467    int iterations = ls->limiting_terminator->iterations;
468 
469    const int max_iterations = options->MaxUnrollIterations;
470 
471    /* Don't try to unroll loops that have zillions of iterations either.
472     */
473    if (iterations > max_iterations)
474       return visit_continue;
475 
476    /* Don't try to unroll nested loops and loops with a huge body.
477     */
478    loop_unroll_count count(&ir->body_instructions, ls, options);
479 
480    bool loop_too_large =
481       count.nested_loop || count.nodes * iterations > max_iterations * 5;
482 
483    if (loop_too_large && !count.unsupported_variable_indexing &&
484        !count.array_indexed_by_induction_var_with_exact_iterations)
485       return visit_continue;
486 
487    /* Note: the limiting terminator contributes 1 to ls->num_loop_jumps.
488     * We'll be removing the limiting terminator before we unroll.
489     */
490    assert(ls->num_loop_jumps > 0);
491    unsigned predicted_num_loop_jumps = ls->num_loop_jumps - 1;
492 
493    if (predicted_num_loop_jumps > 1)
494       return visit_continue;
495 
496    if (predicted_num_loop_jumps == 0) {
497       simple_unroll(ir, iterations);
498       return visit_continue;
499    }
500 
501    ir_instruction *last_ir = (ir_instruction *) ir->body_instructions.get_tail();
502    assert(last_ir != NULL);
503 
504    if (is_break(last_ir)) {
505       /* If the only loop-jump is a break at the end of the loop, the loop
506        * will execute exactly once.  Remove the break and use the simple
507        * unroller with an iteration count of 1.
508        */
509       last_ir->remove();
510 
511       simple_unroll(ir, 1);
512       return visit_continue;
513    }
514 
515    /* Complex unrolling can only handle two terminators. One with an unknown
516     * iteration count and one with a known iteration count. We have already
517     * made sure we have a known iteration count above and removed any
518     * unreachable terminators with a known count. Here we make sure there
519     * isn't any additional unknown terminators, or any other jumps nested
520     * inside futher ifs.
521     */
522    if (ls->num_loop_jumps != 2 || ls->terminators.length() != 2)
523       return visit_continue;
524 
525    ir_instruction *first_ir =
526       (ir_instruction *) ir->body_instructions.get_head();
527 
528    unsigned term_count = 0;
529    bool first_term_then_continue = false;
530    foreach_in_list(loop_terminator, t, &ls->terminators) {
531       ir_if *ir_if = t->ir->as_if();
532       assert(ir_if != NULL);
533 
534       ir_instruction *ir_if_last =
535          (ir_instruction *) ir_if->then_instructions.get_tail();
536 
537       if (is_break(ir_if_last)) {
538          splice_post_if_instructions(ir_if, &ir_if->else_instructions);
539          ir_if_last->remove();
540          if (term_count == 1) {
541             bool ebi =
542                exit_branch_has_instructions(ls->limiting_terminator->ir,
543                                             first_term_then_continue);
544             complex_unroll(ir, iterations, false,
545                            first_ir->as_if() != ls->limiting_terminator->ir ||
546                            ebi,
547                            first_term_then_continue);
548             return visit_continue;
549          }
550       } else {
551          ir_if_last =
552             (ir_instruction *) ir_if->else_instructions.get_tail();
553 
554          assert(is_break(ir_if_last));
555          if (is_break(ir_if_last)) {
556             splice_post_if_instructions(ir_if, &ir_if->then_instructions);
557             ir_if_last->remove();
558             if (term_count == 1) {
559                bool ebi =
560                   exit_branch_has_instructions(ls->limiting_terminator->ir,
561                                                first_term_then_continue);
562                complex_unroll(ir, iterations, true,
563                               first_ir->as_if() != ls->limiting_terminator->ir ||
564                               ebi,
565                               first_term_then_continue);
566                return visit_continue;
567             } else {
568                first_term_then_continue = true;
569             }
570          }
571       }
572 
573       term_count++;
574    }
575 
576    /* Did not find the break statement.  It must be in a complex if-nesting,
577     * so don't try to unroll.
578     */
579    return visit_continue;
580 }
581 
582 
583 bool
unroll_loops(exec_list * instructions,loop_state * ls,const struct gl_shader_compiler_options * options)584 unroll_loops(exec_list *instructions, loop_state *ls,
585              const struct gl_shader_compiler_options *options)
586 {
587    loop_unroll_visitor v(ls, options);
588 
589    v.run(instructions);
590 
591    return v.progress;
592 }
593