1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // This file defines algorithms related to dominance.
9 // Dominator tree construction ----------------------------------------
11 // We use the algorithm described in Lengauer & Tarjan. 1979. A fast
12 // algorithm for finding dominators in a flowgraph.
13 // http://doi.acm.org/10.1145/357062.357071
15 // We also apply the optimizations to SLT described in Georgiadis et
16 // al, Finding Dominators in Practice, JGAA 2006,
17 // http://jgaa.info/accepted/2006/GeorgiadisTarjanWerneck2006.10.1.pdf
18 // to avoid the need for buckets of size > 1.
29 // Idom returns the block that immediately dominates b:
30 // its parent in the dominator tree, if any.
31 // The entry node (b.Index==0) does not have a parent.
33 func (b *BasicBlock) Idom() *BasicBlock { return b.dom.idom }
35 // Dominees returns the list of blocks that b immediately dominates:
36 // its children in the dominator tree.
38 func (b *BasicBlock) Dominees() []*BasicBlock { return b.dom.children }
40 // Dominates reports whether b dominates c.
41 func (b *BasicBlock) Dominates(c *BasicBlock) bool {
42 return b.dom.pre <= c.dom.pre && c.dom.post <= b.dom.post
45 type byDomPreorder []*BasicBlock
47 func (a byDomPreorder) Len() int { return len(a) }
48 func (a byDomPreorder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
49 func (a byDomPreorder) Less(i, j int) bool { return a[i].dom.pre < a[j].dom.pre }
51 // DomPreorder returns a new slice containing the blocks of f in
52 // dominator tree preorder.
54 func (f *Function) DomPreorder() []*BasicBlock {
56 order := make(byDomPreorder, n)
62 // domInfo contains a BasicBlock's dominance information.
64 idom *BasicBlock // immediate dominator (parent in domtree)
65 children []*BasicBlock // nodes immediately dominated by this one
66 pre, post int32 // pre- and post-order numbering within domtree
69 // buildDomTree computes the dominator tree of f using the LT algorithm.
70 // Precondition: all blocks are reachable (e.g. optimizeBlocks has been run).
72 func buildDomTree(fn *Function) {
73 // The step numbers refer to the original LT paper; the
74 // reordering is due to Georgiadis.
76 // Clear any previous domInfo.
77 for _, b := range fn.Blocks {
81 idoms := make([]*BasicBlock, len(fn.Blocks))
83 order := make([]*BasicBlock, 0, len(fn.Blocks))
84 seen := fn.blockset(0)
85 var dfs func(b *BasicBlock)
86 dfs = func(b *BasicBlock) {
90 for _, succ := range b.Succs {
93 if fn.fakeExits.Has(b) {
96 order = append(order, b)
97 b.post = len(order) - 1
101 for i := 0; i < len(order)/2; i++ {
102 o := len(order) - i - 1
103 order[i], order[o] = order[o], order[i]
106 idoms[fn.Blocks[0].Index] = fn.Blocks[0]
110 // iterate over all nodes in reverse postorder, except for the
112 for _, b := range order[1:] {
113 var newIdom *BasicBlock
114 do := func(p *BasicBlock) {
115 if idoms[p.Index] == nil {
123 for finger1 != finger2 {
124 for finger1.post < finger2.post {
125 finger1 = idoms[finger1.Index]
127 for finger2.post < finger1.post {
128 finger2 = idoms[finger2.Index]
134 for _, p := range b.Preds {
138 for _, p := range fn.Blocks {
139 if fn.fakeExits.Has(p) {
145 if idoms[b.Index] != newIdom {
146 idoms[b.Index] = newIdom
152 for i, b := range idoms {
153 fn.Blocks[i].dom.idom = b
161 b.dom.children = append(b.dom.children, fn.Blocks[i])
164 numberDomTree(fn.Blocks[0], 0, 0)
166 // printDomTreeDot(os.Stderr, fn) // debugging
167 // printDomTreeText(os.Stderr, root, 0) // debugging
169 if fn.Prog.mode&SanityCheckFunctions != 0 {
170 sanityCheckDomTree(fn)
174 // buildPostDomTree is like buildDomTree, but builds the post-dominator tree instead.
175 func buildPostDomTree(fn *Function) {
176 // The step numbers refer to the original LT paper; the
177 // reordering is due to Georgiadis.
179 // Clear any previous domInfo.
180 for _, b := range fn.Blocks {
184 idoms := make([]*BasicBlock, len(fn.Blocks))
186 order := make([]*BasicBlock, 0, len(fn.Blocks))
187 seen := fn.blockset(0)
188 var dfs func(b *BasicBlock)
189 dfs = func(b *BasicBlock) {
193 for _, pred := range b.Preds {
197 for _, p := range fn.Blocks {
198 if fn.fakeExits.Has(p) {
203 order = append(order, b)
204 b.post = len(order) - 1
208 for i := 0; i < len(order)/2; i++ {
209 o := len(order) - i - 1
210 order[i], order[o] = order[o], order[i]
213 idoms[fn.Exit.Index] = fn.Exit
217 // iterate over all nodes in reverse postorder, except for the
219 for _, b := range order[1:] {
220 var newIdom *BasicBlock
221 do := func(p *BasicBlock) {
222 if idoms[p.Index] == nil {
230 for finger1 != finger2 {
231 for finger1.post < finger2.post {
232 finger1 = idoms[finger1.Index]
234 for finger2.post < finger1.post {
235 finger2 = idoms[finger2.Index]
241 for _, p := range b.Succs {
244 if fn.fakeExits.Has(b) {
248 if idoms[b.Index] != newIdom {
249 idoms[b.Index] = newIdom
255 for i, b := range idoms {
256 fn.Blocks[i].pdom.idom = b
264 b.pdom.children = append(b.pdom.children, fn.Blocks[i])
267 numberPostDomTree(fn.Exit, 0, 0)
269 // printPostDomTreeDot(os.Stderr, fn) // debugging
270 // printPostDomTreeText(os.Stderr, fn.Exit, 0) // debugging
272 if fn.Prog.mode&SanityCheckFunctions != 0 { // XXX
273 sanityCheckDomTree(fn) // XXX
277 // numberDomTree sets the pre- and post-order numbers of a depth-first
278 // traversal of the dominator tree rooted at v. These are used to
279 // answer dominance queries in constant time.
281 func numberDomTree(v *BasicBlock, pre, post int32) (int32, int32) {
284 for _, child := range v.dom.children {
285 pre, post = numberDomTree(child, pre, post)
292 // numberPostDomTree sets the pre- and post-order numbers of a depth-first
293 // traversal of the post-dominator tree rooted at v. These are used to
294 // answer post-dominance queries in constant time.
296 func numberPostDomTree(v *BasicBlock, pre, post int32) (int32, int32) {
299 for _, child := range v.pdom.children {
300 pre, post = numberPostDomTree(child, pre, post)
307 // Testing utilities ----------------------------------------
309 // sanityCheckDomTree checks the correctness of the dominator tree
310 // computed by the LT algorithm by comparing against the dominance
311 // relation computed by a naive Kildall-style forward dataflow
312 // analysis (Algorithm 10.16 from the "Dragon" book).
314 func sanityCheckDomTree(f *Function) {
317 // D[i] is the set of blocks that dominate f.Blocks[i],
318 // represented as a bit-set of block indices.
319 D := make([]big.Int, n)
323 // all is the set of all blocks; constant.
325 all.Set(one).Lsh(&all, uint(n)).Sub(&all, one)
328 for i := range f.Blocks {
330 // A root is dominated only by itself.
331 D[i].SetBit(&D[0], 0, 1)
333 // All other blocks are (initially) dominated
339 // Iteration until fixed point.
340 for changed := true; changed; {
342 for i, b := range f.Blocks {
346 // Compute intersection across predecessors.
349 for _, pred := range b.Preds {
350 x.And(&x, &D[pred.Index])
353 for _, p := range f.Blocks {
354 if f.fakeExits.Has(p) {
355 x.And(&x, &D[p.Index])
359 x.SetBit(&x, i, 1) // a block always dominates itself.
360 if D[i].Cmp(&x) != 0 {
367 // Check the entire relation. O(n^2).
369 for i := 0; i < n; i++ {
370 for j := 0; j < n; j++ {
371 b, c := f.Blocks[i], f.Blocks[j]
372 actual := b.Dominates(c)
373 expected := D[j].Bit(i) == 1
374 if actual != expected {
375 fmt.Fprintf(os.Stderr, "dominates(%s, %s)==%t, want %t\n", b, c, actual, expected)
381 preorder := f.DomPreorder()
382 for _, b := range f.Blocks {
383 if got := preorder[b.dom.pre]; got != b {
384 fmt.Fprintf(os.Stderr, "preorder[%d]==%s, want %s\n", b.dom.pre, got, b)
390 panic("sanityCheckDomTree failed for " + f.String())
395 // Printing functions ----------------------------------------
397 // printDomTree prints the dominator tree as text, using indentation.
398 //lint:ignore U1000 used during debugging
399 func printDomTreeText(buf *bytes.Buffer, v *BasicBlock, indent int) {
400 fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v)
401 for _, child := range v.dom.children {
402 printDomTreeText(buf, child, indent+1)
406 // printDomTreeDot prints the dominator tree of f in AT&T GraphViz
408 //lint:ignore U1000 used during debugging
409 func printDomTreeDot(buf io.Writer, f *Function) {
410 fmt.Fprintln(buf, "//", f)
411 fmt.Fprintln(buf, "digraph domtree {")
412 for i, b := range f.Blocks {
414 fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post)
415 // TODO(adonovan): improve appearance of edges
416 // belonging to both dominator tree and CFG.
418 // Dominator tree edge.
420 fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.dom.pre, v.pre)
423 for _, pred := range b.Preds {
424 fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.dom.pre, v.pre)
427 fmt.Fprintln(buf, "}")
430 // printDomTree prints the dominator tree as text, using indentation.
431 //lint:ignore U1000 used during debugging
432 func printPostDomTreeText(buf io.Writer, v *BasicBlock, indent int) {
433 fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v)
434 for _, child := range v.pdom.children {
435 printPostDomTreeText(buf, child, indent+1)
439 // printDomTreeDot prints the dominator tree of f in AT&T GraphViz
441 //lint:ignore U1000 used during debugging
442 func printPostDomTreeDot(buf io.Writer, f *Function) {
443 fmt.Fprintln(buf, "//", f)
444 fmt.Fprintln(buf, "digraph pdomtree {")
445 for _, b := range f.Blocks {
447 fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post)
448 // TODO(adonovan): improve appearance of edges
449 // belonging to both dominator tree and CFG.
451 // Dominator tree edge.
453 fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.pdom.pre, v.pre)
456 for _, pred := range b.Preds {
457 fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.pdom.pre, v.pre)
460 fmt.Fprintln(buf, "}")