brw_cfg.cpp revision 9f464c52
1/*
2 * Copyright © 2012 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 DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 *    Eric Anholt <eric@anholt.net>
25 *
26 */
27
28#include "brw_cfg.h"
29
30/** @file brw_cfg.cpp
31 *
32 * Walks the shader instructions generated and creates a set of basic
33 * blocks with successor/predecessor edges connecting them.
34 */
35
36static bblock_t *
37pop_stack(exec_list *list)
38{
39   bblock_link *link = (bblock_link *)list->get_tail();
40   bblock_t *block = link->block;
41   link->link.remove();
42
43   return block;
44}
45
46static exec_node *
47link(void *mem_ctx, bblock_t *block)
48{
49   bblock_link *l = new(mem_ctx) bblock_link(block);
50   return &l->link;
51}
52
53bblock_t::bblock_t(cfg_t *cfg) :
54   cfg(cfg), idom(NULL), start_ip(0), end_ip(0), num(0), cycle_count(0)
55{
56   instructions.make_empty();
57   parents.make_empty();
58   children.make_empty();
59}
60
61void
62bblock_t::add_successor(void *mem_ctx, bblock_t *successor)
63{
64   successor->parents.push_tail(::link(mem_ctx, this));
65   children.push_tail(::link(mem_ctx, successor));
66}
67
68bool
69bblock_t::is_predecessor_of(const bblock_t *block) const
70{
71   foreach_list_typed_safe (bblock_link, parent, link, &block->parents) {
72      if (parent->block == this) {
73         return true;
74      }
75   }
76
77   return false;
78}
79
80bool
81bblock_t::is_successor_of(const bblock_t *block) const
82{
83   foreach_list_typed_safe (bblock_link, child, link, &block->children) {
84      if (child->block == this) {
85         return true;
86      }
87   }
88
89   return false;
90}
91
92static bool
93ends_block(const backend_instruction *inst)
94{
95   enum opcode op = inst->opcode;
96
97   return op == BRW_OPCODE_IF ||
98          op == BRW_OPCODE_ELSE ||
99          op == BRW_OPCODE_CONTINUE ||
100          op == BRW_OPCODE_BREAK ||
101          op == BRW_OPCODE_DO ||
102          op == BRW_OPCODE_WHILE;
103}
104
105static bool
106starts_block(const backend_instruction *inst)
107{
108   enum opcode op = inst->opcode;
109
110   return op == BRW_OPCODE_DO ||
111          op == BRW_OPCODE_ENDIF;
112}
113
114bool
115bblock_t::can_combine_with(const bblock_t *that) const
116{
117   if ((const bblock_t *)this->link.next != that)
118      return false;
119
120   if (ends_block(this->end()) ||
121       starts_block(that->start()))
122      return false;
123
124   return true;
125}
126
127void
128bblock_t::combine_with(bblock_t *that)
129{
130   assert(this->can_combine_with(that));
131   foreach_list_typed (bblock_link, link, link, &that->parents) {
132      assert(link->block == this);
133   }
134
135   this->end_ip = that->end_ip;
136   this->instructions.append_list(&that->instructions);
137
138   this->cfg->remove_block(that);
139}
140
141void
142bblock_t::dump(backend_shader *s) const
143{
144   int ip = this->start_ip;
145   foreach_inst_in_block(backend_instruction, inst, this) {
146      fprintf(stderr, "%5d: ", ip);
147      s->dump_instruction(inst);
148      ip++;
149   }
150}
151
152cfg_t::cfg_t(exec_list *instructions)
153{
154   mem_ctx = ralloc_context(NULL);
155   block_list.make_empty();
156   blocks = NULL;
157   num_blocks = 0;
158   idom_dirty = true;
159   cycle_count = 0;
160
161   bblock_t *cur = NULL;
162   int ip = 0;
163
164   bblock_t *entry = new_block();
165   bblock_t *cur_if = NULL;    /**< BB ending with IF. */
166   bblock_t *cur_else = NULL;  /**< BB ending with ELSE. */
167   bblock_t *cur_endif = NULL; /**< BB starting with ENDIF. */
168   bblock_t *cur_do = NULL;    /**< BB starting with DO. */
169   bblock_t *cur_while = NULL; /**< BB immediately following WHILE. */
170   exec_list if_stack, else_stack, do_stack, while_stack;
171   bblock_t *next;
172
173   set_next_block(&cur, entry, ip);
174
175   foreach_in_list_safe(backend_instruction, inst, instructions) {
176      /* set_next_block wants the post-incremented ip */
177      ip++;
178
179      inst->exec_node::remove();
180
181      switch (inst->opcode) {
182      case BRW_OPCODE_IF:
183         cur->instructions.push_tail(inst);
184
185	 /* Push our information onto a stack so we can recover from
186	  * nested ifs.
187	  */
188	 if_stack.push_tail(link(mem_ctx, cur_if));
189	 else_stack.push_tail(link(mem_ctx, cur_else));
190
191	 cur_if = cur;
192	 cur_else = NULL;
193         cur_endif = NULL;
194
195	 /* Set up our immediately following block, full of "then"
196	  * instructions.
197	  */
198	 next = new_block();
199	 cur_if->add_successor(mem_ctx, next);
200
201	 set_next_block(&cur, next, ip);
202	 break;
203
204      case BRW_OPCODE_ELSE:
205         cur->instructions.push_tail(inst);
206
207         cur_else = cur;
208
209	 next = new_block();
210         assert(cur_if != NULL);
211	 cur_if->add_successor(mem_ctx, next);
212
213	 set_next_block(&cur, next, ip);
214	 break;
215
216      case BRW_OPCODE_ENDIF: {
217         if (cur->instructions.is_empty()) {
218            /* New block was just created; use it. */
219            cur_endif = cur;
220         } else {
221            cur_endif = new_block();
222
223            cur->add_successor(mem_ctx, cur_endif);
224
225            set_next_block(&cur, cur_endif, ip - 1);
226         }
227
228         cur->instructions.push_tail(inst);
229
230         if (cur_else) {
231            cur_else->add_successor(mem_ctx, cur_endif);
232         } else {
233            assert(cur_if != NULL);
234            cur_if->add_successor(mem_ctx, cur_endif);
235         }
236
237         assert(cur_if->end()->opcode == BRW_OPCODE_IF);
238         assert(!cur_else || cur_else->end()->opcode == BRW_OPCODE_ELSE);
239
240	 /* Pop the stack so we're in the previous if/else/endif */
241	 cur_if = pop_stack(&if_stack);
242	 cur_else = pop_stack(&else_stack);
243	 break;
244      }
245      case BRW_OPCODE_DO:
246	 /* Push our information onto a stack so we can recover from
247	  * nested loops.
248	  */
249	 do_stack.push_tail(link(mem_ctx, cur_do));
250	 while_stack.push_tail(link(mem_ctx, cur_while));
251
252	 /* Set up the block just after the while.  Don't know when exactly
253	  * it will start, yet.
254	  */
255	 cur_while = new_block();
256
257         if (cur->instructions.is_empty()) {
258            /* New block was just created; use it. */
259            cur_do = cur;
260         } else {
261            cur_do = new_block();
262
263            cur->add_successor(mem_ctx, cur_do);
264
265            set_next_block(&cur, cur_do, ip - 1);
266         }
267
268         cur->instructions.push_tail(inst);
269
270         /* Represent divergent execution of the loop as a pair of alternative
271          * edges coming out of the DO instruction: For any physical iteration
272          * of the loop a given logical thread can either start off enabled
273          * (which is represented as the "next" successor), or disabled (if it
274          * has reached a non-uniform exit of the loop during a previous
275          * iteration, which is represented as the "cur_while" successor).
276          *
277          * The disabled edge will be taken by the logical thread anytime we
278          * arrive at the DO instruction through a back-edge coming from a
279          * conditional exit of the loop where divergent control flow started.
280          *
281          * This guarantees that there is a control-flow path from any
282          * divergence point of the loop into the convergence point
283          * (immediately past the WHILE instruction) such that it overlaps the
284          * whole IP region of divergent control flow (potentially the whole
285          * loop) *and* doesn't imply the execution of any instructions part
286          * of the loop (since the corresponding execution mask bit will be
287          * disabled for a diverging thread).
288          *
289          * This way we make sure that any variables that are live throughout
290          * the region of divergence for an inactive logical thread are also
291          * considered to interfere with any other variables assigned by
292          * active logical threads within the same physical region of the
293          * program, since otherwise we would risk cross-channel data
294          * corruption.
295          */
296         next = new_block();
297         cur->add_successor(mem_ctx, next);
298         cur->add_successor(mem_ctx, cur_while);
299         set_next_block(&cur, next, ip);
300	 break;
301
302      case BRW_OPCODE_CONTINUE:
303         cur->instructions.push_tail(inst);
304
305         /* A conditional CONTINUE may start a region of divergent control
306          * flow until the start of the next loop iteration (*not* until the
307          * end of the loop which is why the successor is not the top-level
308          * divergence point at cur_do).  The live interval of any variable
309          * extending through a CONTINUE edge is guaranteed to overlap the
310          * whole region of divergent execution, because any variable live-out
311          * at the CONTINUE instruction will also be live-in at the top of the
312          * loop, and therefore also live-out at the bottom-most point of the
313          * loop which is reachable from the top (since a control flow path
314          * exists from a definition of the variable through this CONTINUE
315          * instruction, the top of the loop, the (reachable) bottom of the
316          * loop, the top of the loop again, into a use of the variable).
317          */
318         assert(cur_do != NULL);
319         cur->add_successor(mem_ctx, cur_do->next());
320
321	 next = new_block();
322	 if (inst->predicate)
323	    cur->add_successor(mem_ctx, next);
324
325	 set_next_block(&cur, next, ip);
326	 break;
327
328      case BRW_OPCODE_BREAK:
329         cur->instructions.push_tail(inst);
330
331         /* A conditional BREAK instruction may start a region of divergent
332          * control flow until the end of the loop if the condition is
333          * non-uniform, in which case the loop will execute additional
334          * iterations with the present channel disabled.  We model this as a
335          * control flow path from the divergence point to the convergence
336          * point that overlaps the whole IP range of the loop and skips over
337          * the execution of any other instructions part of the loop.
338          *
339          * See the DO case for additional explanation.
340          */
341         assert(cur_do != NULL);
342         cur->add_successor(mem_ctx, cur_do);
343
344	 next = new_block();
345	 if (inst->predicate)
346	    cur->add_successor(mem_ctx, next);
347
348	 set_next_block(&cur, next, ip);
349	 break;
350
351      case BRW_OPCODE_WHILE:
352         cur->instructions.push_tail(inst);
353
354         assert(cur_do != NULL && cur_while != NULL);
355
356         /* A conditional WHILE instruction may start a region of divergent
357          * control flow until the end of the loop, just like the BREAK
358          * instruction.  See the BREAK case for more details.  OTOH an
359          * unconditional WHILE instruction is non-divergent (just like an
360          * unconditional CONTINUE), and will necessarily lead to the
361          * execution of an additional iteration of the loop for all enabled
362          * channels, so we may skip over the divergence point at the top of
363          * the loop to keep the CFG as unambiguous as possible.
364          */
365         cur->add_successor(mem_ctx, inst->predicate ? cur_do :
366                                     cur_do->next());
367
368	 set_next_block(&cur, cur_while, ip);
369
370	 /* Pop the stack so we're in the previous loop */
371	 cur_do = pop_stack(&do_stack);
372	 cur_while = pop_stack(&while_stack);
373	 break;
374
375      default:
376         cur->instructions.push_tail(inst);
377	 break;
378      }
379   }
380
381   cur->end_ip = ip - 1;
382
383   make_block_array();
384}
385
386cfg_t::~cfg_t()
387{
388   ralloc_free(mem_ctx);
389}
390
391void
392cfg_t::remove_block(bblock_t *block)
393{
394   foreach_list_typed_safe (bblock_link, predecessor, link, &block->parents) {
395      /* Remove block from all of its predecessors' successor lists. */
396      foreach_list_typed_safe (bblock_link, successor, link,
397                               &predecessor->block->children) {
398         if (block == successor->block) {
399            successor->link.remove();
400            ralloc_free(successor);
401         }
402      }
403
404      /* Add removed-block's successors to its predecessors' successor lists. */
405      foreach_list_typed (bblock_link, successor, link, &block->children) {
406         if (!successor->block->is_successor_of(predecessor->block)) {
407            predecessor->block->children.push_tail(link(mem_ctx,
408                                                        successor->block));
409         }
410      }
411   }
412
413   foreach_list_typed_safe (bblock_link, successor, link, &block->children) {
414      /* Remove block from all of its childrens' parents lists. */
415      foreach_list_typed_safe (bblock_link, predecessor, link,
416                               &successor->block->parents) {
417         if (block == predecessor->block) {
418            predecessor->link.remove();
419            ralloc_free(predecessor);
420         }
421      }
422
423      /* Add removed-block's predecessors to its successors' predecessor lists. */
424      foreach_list_typed (bblock_link, predecessor, link, &block->parents) {
425         if (!predecessor->block->is_predecessor_of(successor->block)) {
426            successor->block->parents.push_tail(link(mem_ctx,
427                                                     predecessor->block));
428         }
429      }
430   }
431
432   block->link.remove();
433
434   for (int b = block->num; b < this->num_blocks - 1; b++) {
435      this->blocks[b] = this->blocks[b + 1];
436      this->blocks[b]->num = b;
437   }
438
439   this->blocks[this->num_blocks - 1]->num = this->num_blocks - 2;
440   this->num_blocks--;
441   idom_dirty = true;
442}
443
444bblock_t *
445cfg_t::new_block()
446{
447   bblock_t *block = new(mem_ctx) bblock_t(this);
448
449   return block;
450}
451
452void
453cfg_t::set_next_block(bblock_t **cur, bblock_t *block, int ip)
454{
455   if (*cur) {
456      (*cur)->end_ip = ip - 1;
457   }
458
459   block->start_ip = ip;
460   block->num = num_blocks++;
461   block_list.push_tail(&block->link);
462   *cur = block;
463}
464
465void
466cfg_t::make_block_array()
467{
468   blocks = ralloc_array(mem_ctx, bblock_t *, num_blocks);
469
470   int i = 0;
471   foreach_block (block, this) {
472      blocks[i++] = block;
473   }
474   assert(i == num_blocks);
475}
476
477void
478cfg_t::dump(backend_shader *s)
479{
480   if (idom_dirty)
481      calculate_idom();
482
483   foreach_block (block, this) {
484      if (block->idom)
485         fprintf(stderr, "START B%d IDOM(B%d)", block->num, block->idom->num);
486      else
487         fprintf(stderr, "START B%d IDOM(none)", block->num);
488
489      foreach_list_typed(bblock_link, link, link, &block->parents) {
490         fprintf(stderr, " <-B%d",
491                 link->block->num);
492      }
493      fprintf(stderr, "\n");
494      if (s != NULL)
495         block->dump(s);
496      fprintf(stderr, "END B%d", block->num);
497      foreach_list_typed(bblock_link, link, link, &block->children) {
498         fprintf(stderr, " ->B%d",
499                 link->block->num);
500      }
501      fprintf(stderr, "\n");
502   }
503}
504
505/* Calculates the immediate dominator of each block, according to "A Simple,
506 * Fast Dominance Algorithm" by Keith D. Cooper, Timothy J. Harvey, and Ken
507 * Kennedy.
508 *
509 * The authors claim that for control flow graphs of sizes normally encountered
510 * (less than 1000 nodes) that this algorithm is significantly faster than
511 * others like Lengauer-Tarjan.
512 */
513void
514cfg_t::calculate_idom()
515{
516   foreach_block(block, this) {
517      block->idom = NULL;
518   }
519   blocks[0]->idom = blocks[0];
520
521   bool changed;
522   do {
523      changed = false;
524
525      foreach_block(block, this) {
526         if (block->num == 0)
527            continue;
528
529         bblock_t *new_idom = NULL;
530         foreach_list_typed(bblock_link, parent, link, &block->parents) {
531            if (parent->block->idom) {
532               if (new_idom == NULL) {
533                  new_idom = parent->block;
534               } else if (parent->block->idom != NULL) {
535                  new_idom = intersect(parent->block, new_idom);
536               }
537            }
538         }
539
540         if (block->idom != new_idom) {
541            block->idom = new_idom;
542            changed = true;
543         }
544      }
545   } while (changed);
546
547   idom_dirty = false;
548}
549
550bblock_t *
551cfg_t::intersect(bblock_t *b1, bblock_t *b2)
552{
553   /* Note, the comparisons here are the opposite of what the paper says
554    * because we index blocks from beginning -> end (i.e. reverse post-order)
555    * instead of post-order like they assume.
556    */
557   while (b1->num != b2->num) {
558      while (b1->num > b2->num)
559         b1 = b1->idom;
560      while (b2->num > b1->num)
561         b2 = b2->idom;
562   }
563   assert(b1);
564   return b1;
565}
566
567void
568cfg_t::dump_cfg()
569{
570   printf("digraph CFG {\n");
571   for (int b = 0; b < num_blocks; b++) {
572      bblock_t *block = this->blocks[b];
573
574      foreach_list_typed_safe (bblock_link, child, link, &block->children) {
575         printf("\t%d -> %d\n", b, child->block->num);
576      }
577   }
578   printf("}\n");
579}
580
581void
582cfg_t::dump_domtree()
583{
584   printf("digraph DominanceTree {\n");
585   foreach_block(block, this) {
586      if (block->idom) {
587         printf("\t%d -> %d\n", block->idom->num, block->num);
588      }
589   }
590   printf("}\n");
591}
592