2 * Copyright © 2010 Intel Corporation
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:
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
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.
24 #include "compiler/glsl_types.h"
25 #include "loop_analysis.h"
26 #include "ir_hierarchical_visitor.h"
28 static bool is_loop_terminator(ir_if
*ir
);
30 static bool all_expression_operands_are_loop_constant(ir_rvalue
*,
33 static ir_rvalue
*get_basic_induction_increment(ir_assignment
*, hash_table
*);
36 * Find an initializer of a variable outside a loop
38 * Works backwards from the loop to find the pre-loop value of the variable.
39 * This is used, for example, to find the initial value of loop induction
42 * \param loop Loop where \c var is an induction variable
43 * \param var Variable whose initializer is to be found
46 * The \c ir_rvalue assigned to the variable outside the loop. May return
47 * \c NULL if no initializer can be found.
50 find_initial_value(ir_loop
*loop
, ir_variable
*var
)
52 for (exec_node
*node
= loop
->prev
; !node
->is_head_sentinel();
54 ir_instruction
*ir
= (ir_instruction
*) node
;
56 switch (ir
->ir_type
) {
59 case ir_type_loop_jump
:
64 case ir_type_function
:
65 case ir_type_function_signature
:
66 assert(!"Should not get here.");
69 case ir_type_assignment
: {
70 ir_assignment
*assign
= ir
->as_assignment();
71 ir_variable
*assignee
= assign
->lhs
->whole_variable_referenced();
74 return (assign
->condition
!= NULL
) ? NULL
: assign
->rhs
;
89 calculate_iterations(ir_rvalue
*from
, ir_rvalue
*to
, ir_rvalue
*increment
,
90 enum ir_expression_operation op
)
92 if (from
== NULL
|| to
== NULL
|| increment
== NULL
)
95 void *mem_ctx
= ralloc_context(NULL
);
97 ir_expression
*const sub
=
98 new(mem_ctx
) ir_expression(ir_binop_sub
, from
->type
, to
, from
);
100 ir_expression
*const div
=
101 new(mem_ctx
) ir_expression(ir_binop_div
, sub
->type
, sub
, increment
);
103 ir_constant
*iter
= div
->constant_expression_value(mem_ctx
);
105 ralloc_free(mem_ctx
);
109 if (!iter
->type
->is_integer()) {
110 const ir_expression_operation op
= iter
->type
->is_double()
111 ? ir_unop_d2i
: ir_unop_f2i
;
113 new(mem_ctx
) ir_expression(op
, glsl_type::int_type
, iter
, NULL
);
115 iter
= cast
->constant_expression_value(mem_ctx
);
118 int iter_value
= iter
->get_int_component(0);
120 /* Make sure that the calculated number of iterations satisfies the exit
121 * condition. This is needed to catch off-by-one errors and some types of
122 * ill-formed loops. For example, we need to detect that the following
123 * loop does not have a maximum iteration count.
125 * for (float x = 0.0; x != 0.9; x += 0.2)
128 const int bias
[] = { -1, 0, 1 };
129 bool valid_loop
= false;
131 for (unsigned i
= 0; i
< ARRAY_SIZE(bias
); i
++) {
132 /* Increment may be of type int, uint or float. */
133 switch (increment
->type
->base_type
) {
135 iter
= new(mem_ctx
) ir_constant(iter_value
+ bias
[i
]);
138 iter
= new(mem_ctx
) ir_constant(unsigned(iter_value
+ bias
[i
]));
140 case GLSL_TYPE_FLOAT
:
141 iter
= new(mem_ctx
) ir_constant(float(iter_value
+ bias
[i
]));
143 case GLSL_TYPE_DOUBLE
:
144 iter
= new(mem_ctx
) ir_constant(double(iter_value
+ bias
[i
]));
147 unreachable("Unsupported type for loop iterator.");
150 ir_expression
*const mul
=
151 new(mem_ctx
) ir_expression(ir_binop_mul
, increment
->type
, iter
,
154 ir_expression
*const add
=
155 new(mem_ctx
) ir_expression(ir_binop_add
, mul
->type
, mul
, from
);
157 ir_expression
*const cmp
=
158 new(mem_ctx
) ir_expression(op
, glsl_type::bool_type
, add
, to
);
160 ir_constant
*const cmp_result
= cmp
->constant_expression_value(mem_ctx
);
162 assert(cmp_result
!= NULL
);
163 if (cmp_result
->get_bool_component(0)) {
164 iter_value
+= bias
[i
];
170 ralloc_free(mem_ctx
);
171 return (valid_loop
) ? iter_value
: -1;
176 * Record the fact that the given loop variable was referenced inside the loop.
178 * \arg in_assignee is true if the reference was on the LHS of an assignment.
180 * \arg in_conditional_code_or_nested_loop is true if the reference occurred
181 * inside an if statement or a nested loop.
183 * \arg current_assignment is the ir_assignment node that the loop variable is
184 * on the LHS of, if any (ignored if \c in_assignee is false).
187 loop_variable::record_reference(bool in_assignee
,
188 bool in_conditional_code_or_nested_loop
,
189 ir_assignment
*current_assignment
)
192 assert(current_assignment
!= NULL
);
194 if (in_conditional_code_or_nested_loop
||
195 current_assignment
->condition
!= NULL
) {
196 this->conditional_or_nested_assignment
= true;
199 if (this->first_assignment
== NULL
) {
200 assert(this->num_assignments
== 0);
202 this->first_assignment
= current_assignment
;
205 this->num_assignments
++;
206 } else if (this->first_assignment
== current_assignment
) {
207 /* This catches the case where the variable is used in the RHS of an
208 * assignment where it is also in the LHS.
210 this->read_before_write
= true;
215 loop_state::loop_state()
217 this->ht
= _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
218 _mesa_key_pointer_equal
);
219 this->mem_ctx
= ralloc_context(NULL
);
220 this->loop_found
= false;
224 loop_state::~loop_state()
226 _mesa_hash_table_destroy(this->ht
, NULL
);
227 ralloc_free(this->mem_ctx
);
231 loop_variable_state
*
232 loop_state::insert(ir_loop
*ir
)
234 loop_variable_state
*ls
= new(this->mem_ctx
) loop_variable_state
;
236 _mesa_hash_table_insert(this->ht
, ir
, ls
);
237 this->loop_found
= true;
243 loop_variable_state
*
244 loop_state::get(const ir_loop
*ir
)
246 hash_entry
*entry
= _mesa_hash_table_search(this->ht
, ir
);
247 return entry
? (loop_variable_state
*) entry
->data
: NULL
;
252 loop_variable_state::get(const ir_variable
*ir
)
254 hash_entry
*entry
= _mesa_hash_table_search(this->var_hash
, ir
);
255 return entry
? (loop_variable
*) entry
->data
: NULL
;
260 loop_variable_state::insert(ir_variable
*var
)
262 void *mem_ctx
= ralloc_parent(this);
263 loop_variable
*lv
= rzalloc(mem_ctx
, loop_variable
);
267 _mesa_hash_table_insert(this->var_hash
, lv
->var
, lv
);
268 this->variables
.push_tail(lv
);
275 loop_variable_state::insert(ir_if
*if_stmt
)
277 void *mem_ctx
= ralloc_parent(this);
278 loop_terminator
*t
= new(mem_ctx
) loop_terminator();
281 this->terminators
.push_tail(t
);
288 * If the given variable already is recorded in the state for this loop,
289 * return the corresponding loop_variable object that records information
292 * Otherwise, create a new loop_variable object to record information about
293 * the variable, and set its \c read_before_write field appropriately based on
296 * \arg in_assignee is true if this variable was encountered on the LHS of an
300 loop_variable_state::get_or_insert(ir_variable
*var
, bool in_assignee
)
302 loop_variable
*lv
= this->get(var
);
305 lv
= this->insert(var
);
306 lv
->read_before_write
= !in_assignee
;
315 class loop_analysis
: public ir_hierarchical_visitor
{
317 loop_analysis(loop_state
*loops
);
319 virtual ir_visitor_status
visit(ir_loop_jump
*);
320 virtual ir_visitor_status
visit(ir_dereference_variable
*);
322 virtual ir_visitor_status
visit_enter(ir_call
*);
324 virtual ir_visitor_status
visit_enter(ir_loop
*);
325 virtual ir_visitor_status
visit_leave(ir_loop
*);
326 virtual ir_visitor_status
visit_enter(ir_assignment
*);
327 virtual ir_visitor_status
visit_leave(ir_assignment
*);
328 virtual ir_visitor_status
visit_enter(ir_if
*);
329 virtual ir_visitor_status
visit_leave(ir_if
*);
333 int if_statement_depth
;
335 ir_assignment
*current_assignment
;
340 } /* anonymous namespace */
342 loop_analysis::loop_analysis(loop_state
*loops
)
343 : loops(loops
), if_statement_depth(0), current_assignment(NULL
)
350 loop_analysis::visit(ir_loop_jump
*ir
)
354 assert(!this->state
.is_empty());
356 loop_variable_state
*const ls
=
357 (loop_variable_state
*) this->state
.get_head();
359 ls
->num_loop_jumps
++;
361 return visit_continue
;
366 loop_analysis::visit_enter(ir_call
*)
368 /* Mark every loop that we're currently analyzing as containing an ir_call
369 * (even those at outer nesting levels).
371 foreach_in_list(loop_variable_state
, ls
, &this->state
) {
372 ls
->contains_calls
= true;
375 return visit_continue_with_parent
;
380 loop_analysis::visit(ir_dereference_variable
*ir
)
382 /* If we're not somewhere inside a loop, there's nothing to do.
384 if (this->state
.is_empty())
385 return visit_continue
;
389 foreach_in_list(loop_variable_state
, ls
, &this->state
) {
390 ir_variable
*var
= ir
->variable_referenced();
391 loop_variable
*lv
= ls
->get_or_insert(var
, this->in_assignee
);
393 lv
->record_reference(this->in_assignee
,
394 nested
|| this->if_statement_depth
> 0,
395 this->current_assignment
);
399 return visit_continue
;
403 loop_analysis::visit_enter(ir_loop
*ir
)
405 loop_variable_state
*ls
= this->loops
->insert(ir
);
406 this->state
.push_head(ls
);
408 return visit_continue
;
412 loop_analysis::visit_leave(ir_loop
*ir
)
414 loop_variable_state
*const ls
=
415 (loop_variable_state
*) this->state
.pop_head();
417 /* Function calls may contain side effects. These could alter any of our
418 * variables in ways that cannot be known, and may even terminate shader
419 * execution (say, calling discard in the fragment shader). So we can't
420 * rely on any of our analysis about assignments to variables.
422 * We could perform some conservative analysis (prove there's no statically
423 * possible assignment, etc.) but it isn't worth it for now; function
424 * inlining will allow us to unroll loops anyway.
426 if (ls
->contains_calls
)
427 return visit_continue
;
429 foreach_in_list(ir_instruction
, node
, &ir
->body_instructions
) {
430 /* Skip over declarations at the start of a loop.
432 if (node
->as_variable())
435 ir_if
*if_stmt
= ((ir_instruction
*) node
)->as_if();
437 if ((if_stmt
!= NULL
) && is_loop_terminator(if_stmt
))
444 foreach_in_list_safe(loop_variable
, lv
, &ls
->variables
) {
445 /* Move variables that are already marked as being loop constant to
446 * a separate list. These trivially don't need to be tested.
448 if (lv
->is_loop_constant()) {
450 ls
->constants
.push_tail(lv
);
454 /* Each variable assigned in the loop that isn't already marked as being loop
455 * constant might still be loop constant. The requirements at this point
458 * - Variable is written before it is read.
460 * - Only one assignment to the variable.
462 * - All operands on the RHS of the assignment are also loop constants.
464 * The last requirement is the reason for the progress loop. A variable
465 * marked as a loop constant on one pass may allow other variables to be
466 * marked as loop constant on following passes.
472 foreach_in_list_safe(loop_variable
, lv
, &ls
->variables
) {
473 if (lv
->conditional_or_nested_assignment
|| (lv
->num_assignments
> 1))
476 /* Process the RHS of the assignment. If all of the variables
477 * accessed there are loop constants, then add this
479 ir_rvalue
*const rhs
= lv
->first_assignment
->rhs
;
480 if (all_expression_operands_are_loop_constant(rhs
, ls
->var_hash
)) {
481 lv
->rhs_clean
= true;
483 if (lv
->is_loop_constant()) {
487 ls
->constants
.push_tail(lv
);
493 /* The remaining variables that are not loop invariant might be loop
494 * induction variables.
496 foreach_in_list_safe(loop_variable
, lv
, &ls
->variables
) {
497 /* If there is more than one assignment to a variable, it cannot be a
498 * loop induction variable. This isn't strictly true, but this is a
499 * very simple induction variable detector, and it can't handle more
502 if (lv
->num_assignments
> 1)
505 /* All of the variables with zero assignments in the loop are loop
506 * invariant, and they should have already been filtered out.
508 assert(lv
->num_assignments
== 1);
509 assert(lv
->first_assignment
!= NULL
);
511 /* The assignment to the variable in the loop must be unconditional and
512 * not inside a nested loop.
514 if (lv
->conditional_or_nested_assignment
)
517 /* Basic loop induction variables have a single assignment in the loop
518 * that has the form 'VAR = VAR + i' or 'VAR = VAR - i' where i is a
521 ir_rvalue
*const inc
=
522 get_basic_induction_increment(lv
->first_assignment
, ls
->var_hash
);
527 ls
->induction_variables
.push_tail(lv
);
531 /* Search the loop terminating conditions for those of the form 'i < c'
532 * where i is a loop induction variable, c is a constant, and < is any
533 * relative operator. From each of these we can infer an iteration count.
534 * Also figure out which terminator (if any) produces the smallest
535 * iteration count--this is the limiting terminator.
537 foreach_in_list(loop_terminator
, t
, &ls
->terminators
) {
538 ir_if
*if_stmt
= t
->ir
;
540 /* If-statements can be either 'if (expr)' or 'if (deref)'. We only care
541 * about the former here.
543 ir_expression
*cond
= if_stmt
->condition
->as_expression();
547 switch (cond
->operation
) {
549 case ir_binop_greater
:
550 case ir_binop_lequal
:
551 case ir_binop_gequal
: {
552 /* The expressions that we care about will either be of the form
553 * 'counter < limit' or 'limit < counter'. Figure out which is
556 ir_rvalue
*counter
= cond
->operands
[0]->as_dereference_variable();
557 ir_constant
*limit
= cond
->operands
[1]->as_constant();
558 enum ir_expression_operation cmp
= cond
->operation
;
561 counter
= cond
->operands
[1]->as_dereference_variable();
562 limit
= cond
->operands
[0]->as_constant();
565 case ir_binop_less
: cmp
= ir_binop_greater
; break;
566 case ir_binop_greater
: cmp
= ir_binop_less
; break;
567 case ir_binop_lequal
: cmp
= ir_binop_gequal
; break;
568 case ir_binop_gequal
: cmp
= ir_binop_lequal
; break;
569 default: assert(!"Should not get here.");
573 if ((counter
== NULL
) || (limit
== NULL
))
576 ir_variable
*var
= counter
->variable_referenced();
578 ir_rvalue
*init
= find_initial_value(ir
, var
);
580 loop_variable
*lv
= ls
->get(var
);
581 if (lv
!= NULL
&& lv
->is_induction_var()) {
582 t
->iterations
= calculate_iterations(init
, limit
, lv
->increment
,
585 if (t
->iterations
>= 0 &&
586 (ls
->limiting_terminator
== NULL
||
587 t
->iterations
< ls
->limiting_terminator
->iterations
)) {
588 ls
->limiting_terminator
= t
;
599 return visit_continue
;
603 loop_analysis::visit_enter(ir_if
*ir
)
607 if (!this->state
.is_empty())
608 this->if_statement_depth
++;
610 return visit_continue
;
614 loop_analysis::visit_leave(ir_if
*ir
)
618 if (!this->state
.is_empty())
619 this->if_statement_depth
--;
621 return visit_continue
;
625 loop_analysis::visit_enter(ir_assignment
*ir
)
627 /* If we're not somewhere inside a loop, there's nothing to do.
629 if (this->state
.is_empty())
630 return visit_continue_with_parent
;
632 this->current_assignment
= ir
;
634 return visit_continue
;
638 loop_analysis::visit_leave(ir_assignment
*ir
)
640 /* Since the visit_enter exits with visit_continue_with_parent for this
641 * case, the loop state stack should never be empty here.
643 assert(!this->state
.is_empty());
645 assert(this->current_assignment
== ir
);
646 this->current_assignment
= NULL
;
648 return visit_continue
;
652 class examine_rhs
: public ir_hierarchical_visitor
{
654 examine_rhs(hash_table
*loop_variables
)
656 this->only_uses_loop_constants
= true;
657 this->loop_variables
= loop_variables
;
660 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
662 hash_entry
*entry
= _mesa_hash_table_search(this->loop_variables
,
664 loop_variable
*lv
= entry
? (loop_variable
*) entry
->data
: NULL
;
668 if (lv
->is_loop_constant()) {
669 return visit_continue
;
671 this->only_uses_loop_constants
= false;
676 hash_table
*loop_variables
;
677 bool only_uses_loop_constants
;
682 all_expression_operands_are_loop_constant(ir_rvalue
*ir
, hash_table
*variables
)
684 examine_rhs
v(variables
);
688 return v
.only_uses_loop_constants
;
693 get_basic_induction_increment(ir_assignment
*ir
, hash_table
*var_hash
)
695 /* The RHS must be a binary expression.
697 ir_expression
*const rhs
= ir
->rhs
->as_expression();
699 || ((rhs
->operation
!= ir_binop_add
)
700 && (rhs
->operation
!= ir_binop_sub
)))
703 /* One of the of operands of the expression must be the variable assigned.
704 * If the operation is subtraction, the variable in question must be the
707 ir_variable
*const var
= ir
->lhs
->variable_referenced();
709 ir_variable
*const op0
= rhs
->operands
[0]->variable_referenced();
710 ir_variable
*const op1
= rhs
->operands
[1]->variable_referenced();
712 if (((op0
!= var
) && (op1
!= var
))
713 || ((op1
== var
) && (rhs
->operation
== ir_binop_sub
)))
716 ir_rvalue
*inc
= (op0
== var
) ? rhs
->operands
[1] : rhs
->operands
[0];
718 if (inc
->as_constant() == NULL
) {
719 ir_variable
*const inc_var
= inc
->variable_referenced();
720 if (inc_var
!= NULL
) {
721 hash_entry
*entry
= _mesa_hash_table_search(var_hash
, inc_var
);
722 loop_variable
*lv
= entry
? (loop_variable
*) entry
->data
: NULL
;
724 if (lv
== NULL
|| !lv
->is_loop_constant()) {
732 if ((inc
!= NULL
) && (rhs
->operation
== ir_binop_sub
)) {
733 void *mem_ctx
= ralloc_parent(ir
);
735 inc
= new(mem_ctx
) ir_expression(ir_unop_neg
,
737 inc
->clone(mem_ctx
, NULL
),
746 * Detect whether an if-statement is a loop terminating condition
748 * Detects if-statements of the form
750 * (if (expression bool ...) (break))
753 is_loop_terminator(ir_if
*ir
)
755 if (!ir
->else_instructions
.is_empty())
758 ir_instruction
*const inst
=
759 (ir_instruction
*) ir
->then_instructions
.get_head();
763 if (inst
->ir_type
!= ir_type_loop_jump
)
766 ir_loop_jump
*const jump
= (ir_loop_jump
*) inst
;
767 if (jump
->mode
!= ir_loop_jump::jump_break
)
775 analyze_loop_variables(exec_list
*instructions
)
777 loop_state
*loops
= new loop_state
;
778 loop_analysis
v(loops
);