xref: /aosp_15_r20/external/mesa3d/src/intel/compiler/brw_cfg.cpp (revision 6104692788411f58d303aa86923a9ff6ecaded22)
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 <[email protected]>
25  *
26  */
27 
28 #include "brw_cfg.h"
29 #include "util/u_dynarray.h"
30 #include "brw_fs.h"
31 
32 /** @file
33  *
34  * Walks the shader instructions generated and creates a set of basic
35  * blocks with successor/predecessor edges connecting them.
36  */
37 
38 using namespace brw;
39 
40 static bblock_t *
pop_stack(exec_list * list)41 pop_stack(exec_list *list)
42 {
43    bblock_link *link = (bblock_link *)list->get_tail();
44    bblock_t *block = link->block;
45    link->link.remove();
46 
47    return block;
48 }
49 
50 static exec_node *
link(void * mem_ctx,bblock_t * block,enum bblock_link_kind kind)51 link(void *mem_ctx, bblock_t *block, enum bblock_link_kind kind)
52 {
53    bblock_link *l = new(mem_ctx) bblock_link(block, kind);
54    return &l->link;
55 }
56 
57 void
push_stack(exec_list * list,void * mem_ctx,bblock_t * block)58 push_stack(exec_list *list, void *mem_ctx, bblock_t *block)
59 {
60    /* The kind of the link is immaterial, but we need to provide one since
61     * this is (ab)using the edge data structure in order to implement a stack.
62     */
63    list->push_tail(link(mem_ctx, block, bblock_link_logical));
64 }
65 
bblock_t(cfg_t * cfg)66 bblock_t::bblock_t(cfg_t *cfg) :
67    cfg(cfg), start_ip(0), end_ip(0), end_ip_delta(0), num(0)
68 {
69    instructions.make_empty();
70    parents.make_empty();
71    children.make_empty();
72 }
73 
74 void
add_successor(void * mem_ctx,bblock_t * successor,enum bblock_link_kind kind)75 bblock_t::add_successor(void *mem_ctx, bblock_t *successor,
76                         enum bblock_link_kind kind)
77 {
78    successor->parents.push_tail(::link(mem_ctx, this, kind));
79    children.push_tail(::link(mem_ctx, successor, kind));
80 }
81 
82 bool
is_predecessor_of(const bblock_t * block,enum bblock_link_kind kind) const83 bblock_t::is_predecessor_of(const bblock_t *block,
84                             enum bblock_link_kind kind) const
85 {
86    foreach_list_typed_safe (bblock_link, parent, link, &block->parents) {
87       if (parent->block == this && parent->kind <= kind) {
88          return true;
89       }
90    }
91 
92    return false;
93 }
94 
95 bool
is_successor_of(const bblock_t * block,enum bblock_link_kind kind) const96 bblock_t::is_successor_of(const bblock_t *block,
97                           enum bblock_link_kind kind) const
98 {
99    foreach_list_typed_safe (bblock_link, child, link, &block->children) {
100       if (child->block == this && child->kind <= kind) {
101          return true;
102       }
103    }
104 
105    return false;
106 }
107 
108 static bool
ends_block(const fs_inst * inst)109 ends_block(const fs_inst *inst)
110 {
111    enum opcode op = inst->opcode;
112 
113    return op == BRW_OPCODE_IF ||
114           op == BRW_OPCODE_ELSE ||
115           op == BRW_OPCODE_CONTINUE ||
116           op == BRW_OPCODE_BREAK ||
117           op == BRW_OPCODE_DO ||
118           op == BRW_OPCODE_WHILE;
119 }
120 
121 static bool
starts_block(const fs_inst * inst)122 starts_block(const fs_inst *inst)
123 {
124    enum opcode op = inst->opcode;
125 
126    return op == BRW_OPCODE_DO ||
127           op == BRW_OPCODE_ENDIF;
128 }
129 
130 bool
can_combine_with(const bblock_t * that) const131 bblock_t::can_combine_with(const bblock_t *that) const
132 {
133    if ((const bblock_t *)this->link.next != that)
134       return false;
135 
136    if (ends_block(this->end()) ||
137        starts_block(that->start()))
138       return false;
139 
140    return true;
141 }
142 
143 void
combine_with(bblock_t * that)144 bblock_t::combine_with(bblock_t *that)
145 {
146    assert(this->can_combine_with(that));
147    foreach_list_typed (bblock_link, link, link, &that->parents) {
148       assert(link->block == this);
149    }
150 
151    this->end_ip = that->end_ip;
152    this->instructions.append_list(&that->instructions);
153 
154    this->cfg->remove_block(that);
155 }
156 
157 void
dump(FILE * file) const158 bblock_t::dump(FILE *file) const
159 {
160    const fs_visitor *s = this->cfg->s;
161 
162    int ip = this->start_ip;
163    foreach_inst_in_block(fs_inst, inst, this) {
164       fprintf(file, "%5d: ", ip);
165       brw_print_instruction(*s, inst, file);
166       ip++;
167    }
168 }
169 
170 void
unlink_list(exec_list * list)171 bblock_t::unlink_list(exec_list *list)
172 {
173    assert(list == &parents || list == &children);
174    const bool remove_parent = list == &children;
175 
176    foreach_list_typed_safe(bblock_link, link, link, list) {
177       /* Also break the links from the other block back to this block. */
178       exec_list *sub_list = remove_parent ? &link->block->parents : &link->block->children;
179 
180       foreach_list_typed_safe(bblock_link, sub_link, link, sub_list) {
181          if (sub_link->block == this) {
182             sub_link->link.remove();
183             ralloc_free(sub_link);
184          }
185       }
186 
187       link->link.remove();
188       ralloc_free(link);
189    }
190 }
191 
cfg_t(const fs_visitor * s,exec_list * instructions)192 cfg_t::cfg_t(const fs_visitor *s, exec_list *instructions) :
193    s(s)
194 {
195    mem_ctx = ralloc_context(NULL);
196    block_list.make_empty();
197    blocks = NULL;
198    num_blocks = 0;
199 
200    bblock_t *cur = NULL;
201    int ip = 0;
202 
203    bblock_t *entry = new_block();
204    bblock_t *cur_if = NULL;    /**< BB ending with IF. */
205    bblock_t *cur_else = NULL;  /**< BB ending with ELSE. */
206    bblock_t *cur_do = NULL;    /**< BB starting with DO. */
207    bblock_t *cur_while = NULL; /**< BB immediately following WHILE. */
208    exec_list if_stack, else_stack, do_stack, while_stack;
209    bblock_t *next;
210 
211    set_next_block(&cur, entry, ip);
212 
213    foreach_in_list_safe(fs_inst, inst, instructions) {
214       /* set_next_block wants the post-incremented ip */
215       ip++;
216 
217       inst->exec_node::remove();
218 
219       switch (inst->opcode) {
220       case BRW_OPCODE_IF:
221          cur->instructions.push_tail(inst);
222 
223 	 /* Push our information onto a stack so we can recover from
224 	  * nested ifs.
225 	  */
226          push_stack(&if_stack, mem_ctx, cur_if);
227          push_stack(&else_stack, mem_ctx, cur_else);
228 
229 	 cur_if = cur;
230 	 cur_else = NULL;
231 
232 	 /* Set up our immediately following block, full of "then"
233 	  * instructions.
234 	  */
235 	 next = new_block();
236          cur_if->add_successor(mem_ctx, next, bblock_link_logical);
237 
238 	 set_next_block(&cur, next, ip);
239 	 break;
240 
241       case BRW_OPCODE_ELSE:
242          cur->instructions.push_tail(inst);
243 
244          cur_else = cur;
245 
246 	 next = new_block();
247          assert(cur_if != NULL);
248          cur_if->add_successor(mem_ctx, next, bblock_link_logical);
249          cur_else->add_successor(mem_ctx, next, bblock_link_physical);
250 
251 	 set_next_block(&cur, next, ip);
252 	 break;
253 
254       case BRW_OPCODE_ENDIF: {
255          bblock_t *cur_endif;
256 
257          if (cur->instructions.is_empty()) {
258             /* New block was just created; use it. */
259             cur_endif = cur;
260          } else {
261             cur_endif = new_block();
262 
263             cur->add_successor(mem_ctx, cur_endif, bblock_link_logical);
264 
265             set_next_block(&cur, cur_endif, ip - 1);
266          }
267 
268          cur->instructions.push_tail(inst);
269 
270          if (cur_else) {
271             cur_else->add_successor(mem_ctx, cur_endif, bblock_link_logical);
272          } else {
273             assert(cur_if != NULL);
274             cur_if->add_successor(mem_ctx, cur_endif, bblock_link_logical);
275          }
276 
277          assert(cur_if->end()->opcode == BRW_OPCODE_IF);
278          assert(!cur_else || cur_else->end()->opcode == BRW_OPCODE_ELSE);
279 
280 	 /* Pop the stack so we're in the previous if/else/endif */
281 	 cur_if = pop_stack(&if_stack);
282 	 cur_else = pop_stack(&else_stack);
283 	 break;
284       }
285       case BRW_OPCODE_DO:
286 	 /* Push our information onto a stack so we can recover from
287 	  * nested loops.
288 	  */
289          push_stack(&do_stack, mem_ctx, cur_do);
290          push_stack(&while_stack, mem_ctx, cur_while);
291 
292 	 /* Set up the block just after the while.  Don't know when exactly
293 	  * it will start, yet.
294 	  */
295 	 cur_while = new_block();
296 
297          if (cur->instructions.is_empty()) {
298             /* New block was just created; use it. */
299             cur_do = cur;
300          } else {
301             cur_do = new_block();
302 
303             cur->add_successor(mem_ctx, cur_do, bblock_link_logical);
304 
305             set_next_block(&cur, cur_do, ip - 1);
306          }
307 
308          cur->instructions.push_tail(inst);
309 
310          /* Represent divergent execution of the loop as a pair of alternative
311           * edges coming out of the DO instruction: For any physical iteration
312           * of the loop a given logical thread can either start off enabled
313           * (which is represented as the "next" successor), or disabled (if it
314           * has reached a non-uniform exit of the loop during a previous
315           * iteration, which is represented as the "cur_while" successor).
316           *
317           * The disabled edge will be taken by the logical thread anytime we
318           * arrive at the DO instruction through a back-edge coming from a
319           * conditional exit of the loop where divergent control flow started.
320           *
321           * This guarantees that there is a control-flow path from any
322           * divergence point of the loop into the convergence point
323           * (immediately past the WHILE instruction) such that it overlaps the
324           * whole IP region of divergent control flow (potentially the whole
325           * loop) *and* doesn't imply the execution of any instructions part
326           * of the loop (since the corresponding execution mask bit will be
327           * disabled for a diverging thread).
328           *
329           * This way we make sure that any variables that are live throughout
330           * the region of divergence for an inactive logical thread are also
331           * considered to interfere with any other variables assigned by
332           * active logical threads within the same physical region of the
333           * program, since otherwise we would risk cross-channel data
334           * corruption.
335           */
336          next = new_block();
337          cur->add_successor(mem_ctx, next, bblock_link_logical);
338          cur->add_successor(mem_ctx, cur_while, bblock_link_physical);
339          set_next_block(&cur, next, ip);
340 	 break;
341 
342       case BRW_OPCODE_CONTINUE:
343          cur->instructions.push_tail(inst);
344 
345          /* A conditional CONTINUE may start a region of divergent control
346           * flow until the start of the next loop iteration (*not* until the
347           * end of the loop which is why the successor is not the top-level
348           * divergence point at cur_do).  The live interval of any variable
349           * extending through a CONTINUE edge is guaranteed to overlap the
350           * whole region of divergent execution, because any variable live-out
351           * at the CONTINUE instruction will also be live-in at the top of the
352           * loop, and therefore also live-out at the bottom-most point of the
353           * loop which is reachable from the top (since a control flow path
354           * exists from a definition of the variable through this CONTINUE
355           * instruction, the top of the loop, the (reachable) bottom of the
356           * loop, the top of the loop again, into a use of the variable).
357           */
358          assert(cur_do != NULL);
359          cur->add_successor(mem_ctx, cur_do->next(), bblock_link_logical);
360 
361 	 next = new_block();
362 	 if (inst->predicate)
363             cur->add_successor(mem_ctx, next, bblock_link_logical);
364          else
365             cur->add_successor(mem_ctx, next, bblock_link_physical);
366 
367 	 set_next_block(&cur, next, ip);
368 	 break;
369 
370       case BRW_OPCODE_BREAK:
371          cur->instructions.push_tail(inst);
372 
373          /* A conditional BREAK instruction may start a region of divergent
374           * control flow until the end of the loop if the condition is
375           * non-uniform, in which case the loop will execute additional
376           * iterations with the present channel disabled.  We model this as a
377           * control flow path from the divergence point to the convergence
378           * point that overlaps the whole IP range of the loop and skips over
379           * the execution of any other instructions part of the loop.
380           *
381           * See the DO case for additional explanation.
382           */
383          assert(cur_do != NULL);
384          cur->add_successor(mem_ctx, cur_do, bblock_link_physical);
385          cur->add_successor(mem_ctx, cur_while, bblock_link_logical);
386 
387 	 next = new_block();
388 	 if (inst->predicate)
389             cur->add_successor(mem_ctx, next, bblock_link_logical);
390          else
391             cur->add_successor(mem_ctx, next, bblock_link_physical);
392 
393 	 set_next_block(&cur, next, ip);
394 	 break;
395 
396       case BRW_OPCODE_WHILE:
397          cur->instructions.push_tail(inst);
398 
399          assert(cur_do != NULL && cur_while != NULL);
400 
401          /* A conditional WHILE instruction may start a region of divergent
402           * control flow until the end of the loop, just like the BREAK
403           * instruction.  See the BREAK case for more details.  OTOH an
404           * unconditional WHILE instruction is non-divergent (just like an
405           * unconditional CONTINUE), and will necessarily lead to the
406           * execution of an additional iteration of the loop for all enabled
407           * channels, so we may skip over the divergence point at the top of
408           * the loop to keep the CFG as unambiguous as possible.
409           */
410          if (inst->predicate) {
411             cur->add_successor(mem_ctx, cur_do, bblock_link_logical);
412          } else {
413             cur->add_successor(mem_ctx, cur_do->next(), bblock_link_logical);
414          }
415 
416 	 set_next_block(&cur, cur_while, ip);
417 
418 	 /* Pop the stack so we're in the previous loop */
419 	 cur_do = pop_stack(&do_stack);
420 	 cur_while = pop_stack(&while_stack);
421 	 break;
422 
423       default:
424          cur->instructions.push_tail(inst);
425 	 break;
426       }
427    }
428 
429    cur->end_ip = ip - 1;
430 
431    make_block_array();
432 }
433 
~cfg_t()434 cfg_t::~cfg_t()
435 {
436    ralloc_free(mem_ctx);
437 }
438 
439 void
remove_block(bblock_t * block)440 cfg_t::remove_block(bblock_t *block)
441 {
442    foreach_list_typed_safe (bblock_link, predecessor, link, &block->parents) {
443       /* cfg_t::validate checks that predecessor and successor lists are well
444        * formed, so it is known that the loop here would find exactly one
445        * block. Set old_link_kind to silence "variable used but not set"
446        * warnings.
447        */
448       bblock_link_kind old_link_kind = bblock_link_logical;
449 
450       /* Remove block from all of its predecessors' successor lists. */
451       foreach_list_typed_safe (bblock_link, successor, link,
452                                &predecessor->block->children) {
453          if (block == successor->block) {
454             old_link_kind = successor->kind;
455             successor->link.remove();
456             ralloc_free(successor);
457             break;
458          }
459       }
460 
461       /* Add removed-block's successors to its predecessors' successor lists. */
462       foreach_list_typed (bblock_link, successor, link, &block->children) {
463          bool need_to_link = true;
464          bblock_link_kind new_link_kind = MAX2(old_link_kind, successor->kind);
465 
466          foreach_list_typed_safe (bblock_link, child, link, &predecessor->block->children) {
467             /* There is already a link between the two blocks. If the links
468              * are the same kind or the link is logical, do nothing. If the
469              * existing link is physical and the proposed new link is logical,
470              * promote the existing link to logical.
471              *
472              * This is accomplished by taking the minimum of the existing link
473              * kind and the proposed link kind.
474              */
475             if (child->block == successor->block) {
476                child->kind = MIN2(child->kind, new_link_kind);
477                need_to_link = false;
478                break;
479             }
480          }
481 
482          if (need_to_link) {
483             predecessor->block->children.push_tail(link(mem_ctx,
484                                                         successor->block,
485                                                         new_link_kind));
486          }
487       }
488    }
489 
490    foreach_list_typed_safe (bblock_link, successor, link, &block->children) {
491       /* cfg_t::validate checks that predecessor and successor lists are well
492        * formed, so it is known that the loop here would find exactly one
493        * block. Set old_link_kind to silence "variable used but not set"
494        * warnings.
495        */
496       bblock_link_kind old_link_kind = bblock_link_logical;
497 
498       /* Remove block from all of its childrens' parents lists. */
499       foreach_list_typed_safe (bblock_link, predecessor, link,
500                                &successor->block->parents) {
501          if (block == predecessor->block) {
502             old_link_kind = predecessor->kind;
503             predecessor->link.remove();
504             ralloc_free(predecessor);
505          }
506       }
507 
508       /* Add removed-block's predecessors to its successors' predecessor lists. */
509       foreach_list_typed (bblock_link, predecessor, link, &block->parents) {
510          bool need_to_link = true;
511          bblock_link_kind new_link_kind = MAX2(old_link_kind, predecessor->kind);
512 
513          foreach_list_typed_safe (bblock_link, parent, link, &successor->block->parents) {
514             /* There is already a link between the two blocks. If the links
515              * are the same kind or the link is logical, do nothing. If the
516              * existing link is physical and the proposed new link is logical,
517              * promote the existing link to logical.
518              *
519              * This is accomplished by taking the minimum of the existing link
520              * kind and the proposed link kind.
521              */
522             if (parent->block == predecessor->block) {
523                parent->kind = MIN2(parent->kind, new_link_kind);
524                need_to_link = false;
525                break;
526             }
527          }
528 
529          if (need_to_link) {
530             successor->block->parents.push_tail(link(mem_ctx,
531                                                      predecessor->block,
532                                                      new_link_kind));
533          }
534       }
535    }
536 
537    block->link.remove();
538 
539    for (int b = block->num; b < this->num_blocks - 1; b++) {
540       this->blocks[b] = this->blocks[b + 1];
541       this->blocks[b]->num = b;
542    }
543 
544    this->blocks[this->num_blocks - 1]->num = this->num_blocks - 2;
545    this->num_blocks--;
546 }
547 
548 bblock_t *
new_block()549 cfg_t::new_block()
550 {
551    bblock_t *block = new(mem_ctx) bblock_t(this);
552 
553    return block;
554 }
555 
556 void
set_next_block(bblock_t ** cur,bblock_t * block,int ip)557 cfg_t::set_next_block(bblock_t **cur, bblock_t *block, int ip)
558 {
559    if (*cur) {
560       (*cur)->end_ip = ip - 1;
561    }
562 
563    block->start_ip = ip;
564    block->num = num_blocks++;
565    block_list.push_tail(&block->link);
566    *cur = block;
567 }
568 
569 void
make_block_array()570 cfg_t::make_block_array()
571 {
572    blocks = ralloc_array(mem_ctx, bblock_t *, num_blocks);
573 
574    int i = 0;
575    foreach_block (block, this) {
576       blocks[i++] = block;
577    }
578    assert(i == num_blocks);
579 }
580 
581 namespace {
582 
583 struct link_desc {
584    char kind;
585    int num;
586 };
587 
588 int
compare_link_desc(const void * a,const void * b)589 compare_link_desc(const void *a, const void *b)
590 {
591    const link_desc *la = (const link_desc *)a;
592    const link_desc *lb = (const link_desc *)b;
593 
594    return la->num < lb->num ? -1 :
595           la->num > lb->num ? +1 :
596           la->kind < lb->kind ? -1 :
597           la->kind > lb->kind ? +1 :
598           0;
599 }
600 
601 void
sort_links(util_dynarray * scratch,exec_list * list)602 sort_links(util_dynarray *scratch, exec_list *list)
603 {
604    util_dynarray_clear(scratch);
605    foreach_list_typed(bblock_link, link, link, list) {
606       link_desc l;
607       l.kind = link->kind == bblock_link_logical ? '-' : '~';
608       l.num = link->block->num;
609       util_dynarray_append(scratch, link_desc, l);
610    }
611    qsort(scratch->data, util_dynarray_num_elements(scratch, link_desc),
612          sizeof(link_desc), compare_link_desc);
613 }
614 
615 } /* namespace */
616 
617 void
dump(FILE * file)618 cfg_t::dump(FILE *file)
619 {
620    const idom_tree *idom = (s ? &s->idom_analysis.require() : NULL);
621 
622    /* Temporary storage to sort the lists of blocks.  This normalizes the
623     * output, making it possible to use it for certain tests.
624     */
625    util_dynarray scratch;
626    util_dynarray_init(&scratch, NULL);
627 
628    foreach_block (block, this) {
629       if (idom && idom->parent(block))
630          fprintf(file, "START B%d IDOM(B%d)", block->num,
631                  idom->parent(block)->num);
632       else
633          fprintf(file, "START B%d IDOM(none)", block->num);
634 
635       sort_links(&scratch, &block->parents);
636       util_dynarray_foreach(&scratch, link_desc, l)
637          fprintf(file, " <%cB%d", l->kind, l->num);
638       fprintf(file, "\n");
639 
640       if (s != NULL)
641          block->dump(file);
642       fprintf(file, "END B%d", block->num);
643 
644       sort_links(&scratch, &block->children);
645       util_dynarray_foreach(&scratch, link_desc, l)
646          fprintf(file, " %c>B%d", l->kind, l->num);
647       fprintf(file, "\n");
648    }
649 
650    util_dynarray_fini(&scratch);
651 }
652 
653 /* Calculates the immediate dominator of each block, according to "A Simple,
654  * Fast Dominance Algorithm" by Keith D. Cooper, Timothy J. Harvey, and Ken
655  * Kennedy.
656  *
657  * The authors claim that for control flow graphs of sizes normally encountered
658  * (less than 1000 nodes) that this algorithm is significantly faster than
659  * others like Lengauer-Tarjan.
660  */
idom_tree(const fs_visitor * s)661 idom_tree::idom_tree(const fs_visitor *s) :
662    num_parents(s->cfg->num_blocks),
663    parents(new bblock_t *[num_parents]())
664 {
665    bool changed;
666 
667    parents[0] = s->cfg->blocks[0];
668 
669    do {
670       changed = false;
671 
672       foreach_block(block, s->cfg) {
673          if (block->num == 0)
674             continue;
675 
676          bblock_t *new_idom = NULL;
677          foreach_list_typed(bblock_link, parent_link, link, &block->parents) {
678             if (parent(parent_link->block)) {
679                new_idom = (new_idom ? intersect(new_idom, parent_link->block) :
680                            parent_link->block);
681             }
682          }
683 
684          if (parent(block) != new_idom) {
685             parents[block->num] = new_idom;
686             changed = true;
687          }
688       }
689    } while (changed);
690 }
691 
~idom_tree()692 idom_tree::~idom_tree()
693 {
694    delete[] parents;
695 }
696 
697 bblock_t *
intersect(bblock_t * b1,bblock_t * b2) const698 idom_tree::intersect(bblock_t *b1, bblock_t *b2) const
699 {
700    /* Note, the comparisons here are the opposite of what the paper says
701     * because we index blocks from beginning -> end (i.e. reverse post-order)
702     * instead of post-order like they assume.
703     */
704    while (b1->num != b2->num) {
705       while (b1->num > b2->num)
706          b1 = parent(b1);
707       while (b2->num > b1->num)
708          b2 = parent(b2);
709    }
710    assert(b1);
711    return b1;
712 }
713 
714 void
dump(FILE * file) const715 idom_tree::dump(FILE *file) const
716 {
717    fprintf(file, "digraph DominanceTree {\n");
718    for (unsigned i = 0; i < num_parents; i++)
719       fprintf(file, "\t%d -> %d\n", parents[i]->num, i);
720    fprintf(file, "}\n");
721 }
722 
723 void
dump_cfg()724 cfg_t::dump_cfg()
725 {
726    printf("digraph CFG {\n");
727    for (int b = 0; b < num_blocks; b++) {
728       bblock_t *block = this->blocks[b];
729 
730       foreach_list_typed_safe (bblock_link, child, link, &block->children) {
731          printf("\t%d -> %d\n", b, child->block->num);
732       }
733    }
734    printf("}\n");
735 }
736 
737 void
brw_calculate_cfg(fs_visitor & s)738 brw_calculate_cfg(fs_visitor &s)
739 {
740    if (s.cfg)
741       return;
742    s.cfg = new(s.mem_ctx) cfg_t(&s, &s.instructions);
743 }
744 
745 #define cfgv_assert(assertion)                                          \
746    {                                                                    \
747       if (!(assertion)) {                                               \
748          fprintf(stderr, "ASSERT: CFG validation in %s failed!\n", stage_abbrev); \
749          fprintf(stderr, "%s:%d: '%s' failed\n", __FILE__, __LINE__, #assertion);  \
750          abort();                                                       \
751       }                                                                 \
752    }
753 
754 #ifndef NDEBUG
755 void
validate(const char * stage_abbrev)756 cfg_t::validate(const char *stage_abbrev)
757 {
758    foreach_block(block, this) {
759       foreach_list_typed(bblock_link, successor, link, &block->children) {
760          /* Each successor of a block must have one predecessor link back to
761           * the block.
762           */
763          bool successor_links_back_to_predecessor = false;
764          bblock_t *succ_block = successor->block;
765 
766          foreach_list_typed(bblock_link, predecessor, link, &succ_block->parents) {
767             if (predecessor->block == block) {
768                cfgv_assert(!successor_links_back_to_predecessor);
769                cfgv_assert(successor->kind == predecessor->kind);
770                successor_links_back_to_predecessor = true;
771             }
772          }
773 
774          cfgv_assert(successor_links_back_to_predecessor);
775 
776          /* Each successor block must appear only once in the list of
777           * successors.
778           */
779          foreach_list_typed_from(bblock_link, later_successor, link,
780                                  &block->children, successor->link.next) {
781             cfgv_assert(successor->block != later_successor->block);
782          }
783       }
784 
785       foreach_list_typed(bblock_link, predecessor, link, &block->parents) {
786          /* Each predecessor of a block must have one successor link back to
787           * the block.
788           */
789          bool predecessor_links_back_to_successor = false;
790          bblock_t *pred_block = predecessor->block;
791 
792          foreach_list_typed(bblock_link, successor, link, &pred_block->children) {
793             if (successor->block == block) {
794                cfgv_assert(!predecessor_links_back_to_successor);
795                cfgv_assert(successor->kind == predecessor->kind);
796                predecessor_links_back_to_successor = true;
797             }
798          }
799 
800          cfgv_assert(predecessor_links_back_to_successor);
801 
802          /* Each precessor block must appear only once in the list of
803           * precessors.
804           */
805          foreach_list_typed_from(bblock_link, later_precessor, link,
806                                  &block->parents, predecessor->link.next) {
807             cfgv_assert(predecessor->block != later_precessor->block);
808          }
809       }
810 
811       fs_inst *first_inst = block->start();
812       if (first_inst->opcode == BRW_OPCODE_DO) {
813          /* DO instructions both begin and end a block, so the DO instruction
814           * must be the only instruction in the block.
815           */
816          cfgv_assert(exec_list_is_singular(&block->instructions));
817 
818          /* A block starting with DO should have exactly two successors. One
819           * is a physical link to the block starting after the WHILE
820           * instruction. The other is a logical link to the block starting the
821           * body of the loop.
822           */
823          bblock_t *physical_block = nullptr;
824          bblock_t *logical_block = nullptr;
825 
826          foreach_list_typed(bblock_link, child, link, &block->children) {
827             if (child->kind == bblock_link_physical) {
828                cfgv_assert(physical_block == nullptr);
829                physical_block = child->block;
830             } else {
831                cfgv_assert(logical_block == nullptr);
832                logical_block = child->block;
833             }
834          }
835 
836          cfgv_assert(logical_block != nullptr);
837          cfgv_assert(physical_block != nullptr);
838       }
839    }
840 }
841 #endif
842