glsl: move loop analysis helpers to loop_analysis.cpp
[mesa.git] / src / compiler / glsl / loop_analysis.cpp
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 static bool is_loop_terminator(ir_if *ir);
29
30 static bool all_expression_operands_are_loop_constant(ir_rvalue *,
31 hash_table *);
32
33 static ir_rvalue *get_basic_induction_increment(ir_assignment *, hash_table *);
34
35 /**
36 * Find an initializer of a variable outside a loop
37 *
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
40 * variables.
41 *
42 * \param loop Loop where \c var is an induction variable
43 * \param var Variable whose initializer is to be found
44 *
45 * \return
46 * The \c ir_rvalue assigned to the variable outside the loop. May return
47 * \c NULL if no initializer can be found.
48 */
49 static ir_rvalue *
50 find_initial_value(ir_loop *loop, ir_variable *var)
51 {
52 for (exec_node *node = loop->prev; !node->is_head_sentinel();
53 node = node->prev) {
54 ir_instruction *ir = (ir_instruction *) node;
55
56 switch (ir->ir_type) {
57 case ir_type_call:
58 case ir_type_loop:
59 case ir_type_loop_jump:
60 case ir_type_return:
61 case ir_type_if:
62 return NULL;
63
64 case ir_type_function:
65 case ir_type_function_signature:
66 assert(!"Should not get here.");
67 return NULL;
68
69 case ir_type_assignment: {
70 ir_assignment *assign = ir->as_assignment();
71 ir_variable *assignee = assign->lhs->whole_variable_referenced();
72
73 if (assignee == var)
74 return (assign->condition != NULL) ? NULL : assign->rhs;
75
76 break;
77 }
78
79 default:
80 break;
81 }
82 }
83
84 return NULL;
85 }
86
87
88 static int
89 calculate_iterations(ir_rvalue *from, ir_rvalue *to, ir_rvalue *increment,
90 enum ir_expression_operation op)
91 {
92 if (from == NULL || to == NULL || increment == NULL)
93 return -1;
94
95 void *mem_ctx = ralloc_context(NULL);
96
97 ir_expression *const sub =
98 new(mem_ctx) ir_expression(ir_binop_sub, from->type, to, from);
99
100 ir_expression *const div =
101 new(mem_ctx) ir_expression(ir_binop_div, sub->type, sub, increment);
102
103 ir_constant *iter = div->constant_expression_value(mem_ctx);
104 if (iter == NULL) {
105 ralloc_free(mem_ctx);
106 return -1;
107 }
108
109 if (!iter->type->is_integer()) {
110 const ir_expression_operation op = iter->type->is_double()
111 ? ir_unop_d2i : ir_unop_f2i;
112 ir_rvalue *cast =
113 new(mem_ctx) ir_expression(op, glsl_type::int_type, iter, NULL);
114
115 iter = cast->constant_expression_value(mem_ctx);
116 }
117
118 int iter_value = iter->get_int_component(0);
119
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.
124 *
125 * for (float x = 0.0; x != 0.9; x += 0.2)
126 * ;
127 */
128 const int bias[] = { -1, 0, 1 };
129 bool valid_loop = false;
130
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) {
134 case GLSL_TYPE_INT:
135 iter = new(mem_ctx) ir_constant(iter_value + bias[i]);
136 break;
137 case GLSL_TYPE_UINT:
138 iter = new(mem_ctx) ir_constant(unsigned(iter_value + bias[i]));
139 break;
140 case GLSL_TYPE_FLOAT:
141 iter = new(mem_ctx) ir_constant(float(iter_value + bias[i]));
142 break;
143 case GLSL_TYPE_DOUBLE:
144 iter = new(mem_ctx) ir_constant(double(iter_value + bias[i]));
145 break;
146 default:
147 unreachable("Unsupported type for loop iterator.");
148 }
149
150 ir_expression *const mul =
151 new(mem_ctx) ir_expression(ir_binop_mul, increment->type, iter,
152 increment);
153
154 ir_expression *const add =
155 new(mem_ctx) ir_expression(ir_binop_add, mul->type, mul, from);
156
157 ir_expression *const cmp =
158 new(mem_ctx) ir_expression(op, glsl_type::bool_type, add, to);
159
160 ir_constant *const cmp_result = cmp->constant_expression_value(mem_ctx);
161
162 assert(cmp_result != NULL);
163 if (cmp_result->get_bool_component(0)) {
164 iter_value += bias[i];
165 valid_loop = true;
166 break;
167 }
168 }
169
170 ralloc_free(mem_ctx);
171 return (valid_loop) ? iter_value : -1;
172 }
173
174
175 /**
176 * Record the fact that the given loop variable was referenced inside the loop.
177 *
178 * \arg in_assignee is true if the reference was on the LHS of an assignment.
179 *
180 * \arg in_conditional_code_or_nested_loop is true if the reference occurred
181 * inside an if statement or a nested loop.
182 *
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).
185 */
186 void
187 loop_variable::record_reference(bool in_assignee,
188 bool in_conditional_code_or_nested_loop,
189 ir_assignment *current_assignment)
190 {
191 if (in_assignee) {
192 assert(current_assignment != NULL);
193
194 if (in_conditional_code_or_nested_loop ||
195 current_assignment->condition != NULL) {
196 this->conditional_or_nested_assignment = true;
197 }
198
199 if (this->first_assignment == NULL) {
200 assert(this->num_assignments == 0);
201
202 this->first_assignment = current_assignment;
203 }
204
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.
209 */
210 this->read_before_write = true;
211 }
212 }
213
214
215 loop_state::loop_state()
216 {
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;
221 }
222
223
224 loop_state::~loop_state()
225 {
226 _mesa_hash_table_destroy(this->ht, NULL);
227 ralloc_free(this->mem_ctx);
228 }
229
230
231 loop_variable_state *
232 loop_state::insert(ir_loop *ir)
233 {
234 loop_variable_state *ls = new(this->mem_ctx) loop_variable_state;
235
236 _mesa_hash_table_insert(this->ht, ir, ls);
237 this->loop_found = true;
238
239 return ls;
240 }
241
242
243 loop_variable_state *
244 loop_state::get(const ir_loop *ir)
245 {
246 hash_entry *entry = _mesa_hash_table_search(this->ht, ir);
247 return entry ? (loop_variable_state *) entry->data : NULL;
248 }
249
250
251 loop_variable *
252 loop_variable_state::get(const ir_variable *ir)
253 {
254 hash_entry *entry = _mesa_hash_table_search(this->var_hash, ir);
255 return entry ? (loop_variable *) entry->data : NULL;
256 }
257
258
259 loop_variable *
260 loop_variable_state::insert(ir_variable *var)
261 {
262 void *mem_ctx = ralloc_parent(this);
263 loop_variable *lv = rzalloc(mem_ctx, loop_variable);
264
265 lv->var = var;
266
267 _mesa_hash_table_insert(this->var_hash, lv->var, lv);
268 this->variables.push_tail(lv);
269
270 return lv;
271 }
272
273
274 loop_terminator *
275 loop_variable_state::insert(ir_if *if_stmt)
276 {
277 void *mem_ctx = ralloc_parent(this);
278 loop_terminator *t = new(mem_ctx) loop_terminator();
279
280 t->ir = if_stmt;
281 this->terminators.push_tail(t);
282
283 return t;
284 }
285
286
287 /**
288 * If the given variable already is recorded in the state for this loop,
289 * return the corresponding loop_variable object that records information
290 * about it.
291 *
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
294 * \c in_assignee.
295 *
296 * \arg in_assignee is true if this variable was encountered on the LHS of an
297 * assignment.
298 */
299 loop_variable *
300 loop_variable_state::get_or_insert(ir_variable *var, bool in_assignee)
301 {
302 loop_variable *lv = this->get(var);
303
304 if (lv == NULL) {
305 lv = this->insert(var);
306 lv->read_before_write = !in_assignee;
307 }
308
309 return lv;
310 }
311
312
313 namespace {
314
315 class loop_analysis : public ir_hierarchical_visitor {
316 public:
317 loop_analysis(loop_state *loops);
318
319 virtual ir_visitor_status visit(ir_loop_jump *);
320 virtual ir_visitor_status visit(ir_dereference_variable *);
321
322 virtual ir_visitor_status visit_enter(ir_call *);
323
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 *);
330
331 loop_state *loops;
332
333 int if_statement_depth;
334
335 ir_assignment *current_assignment;
336
337 exec_list state;
338 };
339
340 } /* anonymous namespace */
341
342 loop_analysis::loop_analysis(loop_state *loops)
343 : loops(loops), if_statement_depth(0), current_assignment(NULL)
344 {
345 /* empty */
346 }
347
348
349 ir_visitor_status
350 loop_analysis::visit(ir_loop_jump *ir)
351 {
352 (void) ir;
353
354 assert(!this->state.is_empty());
355
356 loop_variable_state *const ls =
357 (loop_variable_state *) this->state.get_head();
358
359 ls->num_loop_jumps++;
360
361 return visit_continue;
362 }
363
364
365 ir_visitor_status
366 loop_analysis::visit_enter(ir_call *)
367 {
368 /* Mark every loop that we're currently analyzing as containing an ir_call
369 * (even those at outer nesting levels).
370 */
371 foreach_in_list(loop_variable_state, ls, &this->state) {
372 ls->contains_calls = true;
373 }
374
375 return visit_continue_with_parent;
376 }
377
378
379 ir_visitor_status
380 loop_analysis::visit(ir_dereference_variable *ir)
381 {
382 /* If we're not somewhere inside a loop, there's nothing to do.
383 */
384 if (this->state.is_empty())
385 return visit_continue;
386
387 bool nested = false;
388
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);
392
393 lv->record_reference(this->in_assignee,
394 nested || this->if_statement_depth > 0,
395 this->current_assignment);
396 nested = true;
397 }
398
399 return visit_continue;
400 }
401
402 ir_visitor_status
403 loop_analysis::visit_enter(ir_loop *ir)
404 {
405 loop_variable_state *ls = this->loops->insert(ir);
406 this->state.push_head(ls);
407
408 return visit_continue;
409 }
410
411 ir_visitor_status
412 loop_analysis::visit_leave(ir_loop *ir)
413 {
414 loop_variable_state *const ls =
415 (loop_variable_state *) this->state.pop_head();
416
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.
421 *
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.
425 */
426 if (ls->contains_calls)
427 return visit_continue;
428
429 foreach_in_list(ir_instruction, node, &ir->body_instructions) {
430 /* Skip over declarations at the start of a loop.
431 */
432 if (node->as_variable())
433 continue;
434
435 ir_if *if_stmt = ((ir_instruction *) node)->as_if();
436
437 if ((if_stmt != NULL) && is_loop_terminator(if_stmt))
438 ls->insert(if_stmt);
439 else
440 break;
441 }
442
443
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.
447 */
448 if (lv->is_loop_constant()) {
449 lv->remove();
450 ls->constants.push_tail(lv);
451 }
452 }
453
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
456 * are:
457 *
458 * - Variable is written before it is read.
459 *
460 * - Only one assignment to the variable.
461 *
462 * - All operands on the RHS of the assignment are also loop constants.
463 *
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.
467 */
468 bool progress;
469 do {
470 progress = false;
471
472 foreach_in_list_safe(loop_variable, lv, &ls->variables) {
473 if (lv->conditional_or_nested_assignment || (lv->num_assignments > 1))
474 continue;
475
476 /* Process the RHS of the assignment. If all of the variables
477 * accessed there are loop constants, then add this
478 */
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;
482
483 if (lv->is_loop_constant()) {
484 progress = true;
485
486 lv->remove();
487 ls->constants.push_tail(lv);
488 }
489 }
490 }
491 } while (progress);
492
493 /* The remaining variables that are not loop invariant might be loop
494 * induction variables.
495 */
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
500 * complex cases.
501 */
502 if (lv->num_assignments > 1)
503 continue;
504
505 /* All of the variables with zero assignments in the loop are loop
506 * invariant, and they should have already been filtered out.
507 */
508 assert(lv->num_assignments == 1);
509 assert(lv->first_assignment != NULL);
510
511 /* The assignment to the variable in the loop must be unconditional and
512 * not inside a nested loop.
513 */
514 if (lv->conditional_or_nested_assignment)
515 continue;
516
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
519 * loop invariant.
520 */
521 ir_rvalue *const inc =
522 get_basic_induction_increment(lv->first_assignment, ls->var_hash);
523 if (inc != NULL) {
524 lv->increment = inc;
525
526 lv->remove();
527 ls->induction_variables.push_tail(lv);
528 }
529 }
530
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.
536 */
537 foreach_in_list(loop_terminator, t, &ls->terminators) {
538 ir_if *if_stmt = t->ir;
539
540 /* If-statements can be either 'if (expr)' or 'if (deref)'. We only care
541 * about the former here.
542 */
543 ir_expression *cond = if_stmt->condition->as_expression();
544 if (cond == NULL)
545 continue;
546
547 switch (cond->operation) {
548 case ir_binop_less:
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
554 * which.
555 */
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;
559
560 if (limit == NULL) {
561 counter = cond->operands[1]->as_dereference_variable();
562 limit = cond->operands[0]->as_constant();
563
564 switch (cmp) {
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.");
570 }
571 }
572
573 if ((counter == NULL) || (limit == NULL))
574 break;
575
576 ir_variable *var = counter->variable_referenced();
577
578 ir_rvalue *init = find_initial_value(ir, var);
579
580 loop_variable *lv = ls->get(var);
581 if (lv != NULL && lv->is_induction_var()) {
582 t->iterations = calculate_iterations(init, limit, lv->increment,
583 cmp);
584
585 if (t->iterations >= 0 &&
586 (ls->limiting_terminator == NULL ||
587 t->iterations < ls->limiting_terminator->iterations)) {
588 ls->limiting_terminator = t;
589 }
590 }
591 break;
592 }
593
594 default:
595 break;
596 }
597 }
598
599 return visit_continue;
600 }
601
602 ir_visitor_status
603 loop_analysis::visit_enter(ir_if *ir)
604 {
605 (void) ir;
606
607 if (!this->state.is_empty())
608 this->if_statement_depth++;
609
610 return visit_continue;
611 }
612
613 ir_visitor_status
614 loop_analysis::visit_leave(ir_if *ir)
615 {
616 (void) ir;
617
618 if (!this->state.is_empty())
619 this->if_statement_depth--;
620
621 return visit_continue;
622 }
623
624 ir_visitor_status
625 loop_analysis::visit_enter(ir_assignment *ir)
626 {
627 /* If we're not somewhere inside a loop, there's nothing to do.
628 */
629 if (this->state.is_empty())
630 return visit_continue_with_parent;
631
632 this->current_assignment = ir;
633
634 return visit_continue;
635 }
636
637 ir_visitor_status
638 loop_analysis::visit_leave(ir_assignment *ir)
639 {
640 /* Since the visit_enter exits with visit_continue_with_parent for this
641 * case, the loop state stack should never be empty here.
642 */
643 assert(!this->state.is_empty());
644
645 assert(this->current_assignment == ir);
646 this->current_assignment = NULL;
647
648 return visit_continue;
649 }
650
651
652 class examine_rhs : public ir_hierarchical_visitor {
653 public:
654 examine_rhs(hash_table *loop_variables)
655 {
656 this->only_uses_loop_constants = true;
657 this->loop_variables = loop_variables;
658 }
659
660 virtual ir_visitor_status visit(ir_dereference_variable *ir)
661 {
662 hash_entry *entry = _mesa_hash_table_search(this->loop_variables,
663 ir->var);
664 loop_variable *lv = entry ? (loop_variable *) entry->data : NULL;
665
666 assert(lv != NULL);
667
668 if (lv->is_loop_constant()) {
669 return visit_continue;
670 } else {
671 this->only_uses_loop_constants = false;
672 return visit_stop;
673 }
674 }
675
676 hash_table *loop_variables;
677 bool only_uses_loop_constants;
678 };
679
680
681 bool
682 all_expression_operands_are_loop_constant(ir_rvalue *ir, hash_table *variables)
683 {
684 examine_rhs v(variables);
685
686 ir->accept(&v);
687
688 return v.only_uses_loop_constants;
689 }
690
691
692 ir_rvalue *
693 get_basic_induction_increment(ir_assignment *ir, hash_table *var_hash)
694 {
695 /* The RHS must be a binary expression.
696 */
697 ir_expression *const rhs = ir->rhs->as_expression();
698 if ((rhs == NULL)
699 || ((rhs->operation != ir_binop_add)
700 && (rhs->operation != ir_binop_sub)))
701 return NULL;
702
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
705 * "left" operand.
706 */
707 ir_variable *const var = ir->lhs->variable_referenced();
708
709 ir_variable *const op0 = rhs->operands[0]->variable_referenced();
710 ir_variable *const op1 = rhs->operands[1]->variable_referenced();
711
712 if (((op0 != var) && (op1 != var))
713 || ((op1 == var) && (rhs->operation == ir_binop_sub)))
714 return NULL;
715
716 ir_rvalue *inc = (op0 == var) ? rhs->operands[1] : rhs->operands[0];
717
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;
723
724 if (lv == NULL || !lv->is_loop_constant()) {
725 assert(lv != NULL);
726 inc = NULL;
727 }
728 } else
729 inc = NULL;
730 }
731
732 if ((inc != NULL) && (rhs->operation == ir_binop_sub)) {
733 void *mem_ctx = ralloc_parent(ir);
734
735 inc = new(mem_ctx) ir_expression(ir_unop_neg,
736 inc->type,
737 inc->clone(mem_ctx, NULL),
738 NULL);
739 }
740
741 return inc;
742 }
743
744
745 /**
746 * Detect whether an if-statement is a loop terminating condition
747 *
748 * Detects if-statements of the form
749 *
750 * (if (expression bool ...) (break))
751 */
752 bool
753 is_loop_terminator(ir_if *ir)
754 {
755 if (!ir->else_instructions.is_empty())
756 return false;
757
758 ir_instruction *const inst =
759 (ir_instruction *) ir->then_instructions.get_head();
760 if (inst == NULL)
761 return false;
762
763 if (inst->ir_type != ir_type_loop_jump)
764 return false;
765
766 ir_loop_jump *const jump = (ir_loop_jump *) inst;
767 if (jump->mode != ir_loop_jump::jump_break)
768 return false;
769
770 return true;
771 }
772
773
774 loop_state *
775 analyze_loop_variables(exec_list *instructions)
776 {
777 loop_state *loops = new loop_state;
778 loop_analysis v(loops);
779
780 v.run(instructions);
781 return v.loops;
782 }