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.
4
5package ssa
6
7// This file defines algorithms related to dominance.
8
9// Dominator tree construction ----------------------------------------
10//
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
14//
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.
19
20import (
21	"bytes"
22	"fmt"
23	"math/big"
24	"os"
25	"sort"
26)
27
28// Idom returns the block that immediately dominates b:
29// its parent in the dominator tree, if any.
30// Neither the entry node (b.Index==0) nor recover node
31// (b==b.Parent().Recover()) have a parent.
32//
33func (b *BasicBlock) Idom() *BasicBlock { return b.dom.idom }
34
35// Dominees returns the list of blocks that b immediately dominates:
36// its children in the dominator tree.
37//
38func (b *BasicBlock) Dominees() []*BasicBlock { return b.dom.children }
39
40// Dominates reports whether b dominates c.
41func (b *BasicBlock) Dominates(c *BasicBlock) bool {
42	return b.dom.pre <= c.dom.pre && c.dom.post <= b.dom.post
43}
44
45type byDomPreorder []*BasicBlock
46
47func (a byDomPreorder) Len() int           { return len(a) }
48func (a byDomPreorder) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
49func (a byDomPreorder) Less(i, j int) bool { return a[i].dom.pre < a[j].dom.pre }
50
51// DomPreorder returns a new slice containing the blocks of f in
52// dominator tree preorder.
53//
54func (f *Function) DomPreorder() []*BasicBlock {
55	n := len(f.Blocks)
56	order := make(byDomPreorder, n)
57	copy(order, f.Blocks)
58	sort.Sort(order)
59	return order
60}
61
62// domInfo contains a BasicBlock's dominance information.
63type domInfo struct {
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
67}
68
69// ltState holds the working state for Lengauer-Tarjan algorithm
70// (during which domInfo.pre is repurposed for CFG DFS preorder number).
71type ltState struct {
72	// Each slice is indexed by b.Index.
73	sdom     []*BasicBlock // b's semidominator
74	parent   []*BasicBlock // b's parent in DFS traversal of CFG
75	ancestor []*BasicBlock // b's ancestor with least sdom
76}
77
78// dfs implements the depth-first search part of the LT algorithm.
79func (lt *ltState) dfs(v *BasicBlock, i int32, preorder []*BasicBlock) int32 {
80	preorder[i] = v
81	v.dom.pre = i // For now: DFS preorder of spanning tree of CFG
82	i++
83	lt.sdom[v.Index] = v
84	lt.link(nil, v)
85	for _, w := range v.Succs {
86		if lt.sdom[w.Index] == nil {
87			lt.parent[w.Index] = v
88			i = lt.dfs(w, i, preorder)
89		}
90	}
91	return i
92}
93
94// eval implements the EVAL part of the LT algorithm.
95func (lt *ltState) eval(v *BasicBlock) *BasicBlock {
96	// TODO(adonovan): opt: do path compression per simple LT.
97	u := v
98	for ; lt.ancestor[v.Index] != nil; v = lt.ancestor[v.Index] {
99		if lt.sdom[v.Index].dom.pre < lt.sdom[u.Index].dom.pre {
100			u = v
101		}
102	}
103	return u
104}
105
106// link implements the LINK part of the LT algorithm.
107func (lt *ltState) link(v, w *BasicBlock) {
108	lt.ancestor[w.Index] = v
109}
110
111// buildDomTree computes the dominator tree of f using the LT algorithm.
112// Precondition: all blocks are reachable (e.g. optimizeBlocks has been run).
113//
114func buildDomTree(f *Function) {
115	// The step numbers refer to the original LT paper; the
116	// reordering is due to Georgiadis.
117
118	// Clear any previous domInfo.
119	for _, b := range f.Blocks {
120		b.dom = domInfo{}
121	}
122
123	n := len(f.Blocks)
124	// Allocate space for 5 contiguous [n]*BasicBlock arrays:
125	// sdom, parent, ancestor, preorder, buckets.
126	space := make([]*BasicBlock, 5*n)
127	lt := ltState{
128		sdom:     space[0:n],
129		parent:   space[n : 2*n],
130		ancestor: space[2*n : 3*n],
131	}
132
133	// Step 1.  Number vertices by depth-first preorder.
134	preorder := space[3*n : 4*n]
135	root := f.Blocks[0]
136	prenum := lt.dfs(root, 0, preorder)
137	recover := f.Recover
138	if recover != nil {
139		lt.dfs(recover, prenum, preorder)
140	}
141
142	buckets := space[4*n : 5*n]
143	copy(buckets, preorder)
144
145	// In reverse preorder...
146	for i := int32(n) - 1; i > 0; i-- {
147		w := preorder[i]
148
149		// Step 3. Implicitly define the immediate dominator of each node.
150		for v := buckets[i]; v != w; v = buckets[v.dom.pre] {
151			u := lt.eval(v)
152			if lt.sdom[u.Index].dom.pre < i {
153				v.dom.idom = u
154			} else {
155				v.dom.idom = w
156			}
157		}
158
159		// Step 2. Compute the semidominators of all nodes.
160		lt.sdom[w.Index] = lt.parent[w.Index]
161		for _, v := range w.Preds {
162			u := lt.eval(v)
163			if lt.sdom[u.Index].dom.pre < lt.sdom[w.Index].dom.pre {
164				lt.sdom[w.Index] = lt.sdom[u.Index]
165			}
166		}
167
168		lt.link(lt.parent[w.Index], w)
169
170		if lt.parent[w.Index] == lt.sdom[w.Index] {
171			w.dom.idom = lt.parent[w.Index]
172		} else {
173			buckets[i] = buckets[lt.sdom[w.Index].dom.pre]
174			buckets[lt.sdom[w.Index].dom.pre] = w
175		}
176	}
177
178	// The final 'Step 3' is now outside the loop.
179	for v := buckets[0]; v != root; v = buckets[v.dom.pre] {
180		v.dom.idom = root
181	}
182
183	// Step 4. Explicitly define the immediate dominator of each
184	// node, in preorder.
185	for _, w := range preorder[1:] {
186		if w == root || w == recover {
187			w.dom.idom = nil
188		} else {
189			if w.dom.idom != lt.sdom[w.Index] {
190				w.dom.idom = w.dom.idom.dom.idom
191			}
192			// Calculate Children relation as inverse of Idom.
193			w.dom.idom.dom.children = append(w.dom.idom.dom.children, w)
194		}
195	}
196
197	pre, post := numberDomTree(root, 0, 0)
198	if recover != nil {
199		numberDomTree(recover, pre, post)
200	}
201
202	// printDomTreeDot(os.Stderr, f)        // debugging
203	// printDomTreeText(os.Stderr, root, 0) // debugging
204
205	if f.Prog.mode&SanityCheckFunctions != 0 {
206		sanityCheckDomTree(f)
207	}
208}
209
210// numberDomTree sets the pre- and post-order numbers of a depth-first
211// traversal of the dominator tree rooted at v.  These are used to
212// answer dominance queries in constant time.
213//
214func numberDomTree(v *BasicBlock, pre, post int32) (int32, int32) {
215	v.dom.pre = pre
216	pre++
217	for _, child := range v.dom.children {
218		pre, post = numberDomTree(child, pre, post)
219	}
220	v.dom.post = post
221	post++
222	return pre, post
223}
224
225// Testing utilities ----------------------------------------
226
227// sanityCheckDomTree checks the correctness of the dominator tree
228// computed by the LT algorithm by comparing against the dominance
229// relation computed by a naive Kildall-style forward dataflow
230// analysis (Algorithm 10.16 from the "Dragon" book).
231//
232func sanityCheckDomTree(f *Function) {
233	n := len(f.Blocks)
234
235	// D[i] is the set of blocks that dominate f.Blocks[i],
236	// represented as a bit-set of block indices.
237	D := make([]big.Int, n)
238
239	one := big.NewInt(1)
240
241	// all is the set of all blocks; constant.
242	var all big.Int
243	all.Set(one).Lsh(&all, uint(n)).Sub(&all, one)
244
245	// Initialization.
246	for i, b := range f.Blocks {
247		if i == 0 || b == f.Recover {
248			// A root is dominated only by itself.
249			D[i].SetBit(&D[0], 0, 1)
250		} else {
251			// All other blocks are (initially) dominated
252			// by every block.
253			D[i].Set(&all)
254		}
255	}
256
257	// Iteration until fixed point.
258	for changed := true; changed; {
259		changed = false
260		for i, b := range f.Blocks {
261			if i == 0 || b == f.Recover {
262				continue
263			}
264			// Compute intersection across predecessors.
265			var x big.Int
266			x.Set(&all)
267			for _, pred := range b.Preds {
268				x.And(&x, &D[pred.Index])
269			}
270			x.SetBit(&x, i, 1) // a block always dominates itself.
271			if D[i].Cmp(&x) != 0 {
272				D[i].Set(&x)
273				changed = true
274			}
275		}
276	}
277
278	// Check the entire relation.  O(n^2).
279	// The Recover block (if any) must be treated specially so we skip it.
280	ok := true
281	for i := 0; i < n; i++ {
282		for j := 0; j < n; j++ {
283			b, c := f.Blocks[i], f.Blocks[j]
284			if c == f.Recover {
285				continue
286			}
287			actual := b.Dominates(c)
288			expected := D[j].Bit(i) == 1
289			if actual != expected {
290				fmt.Fprintf(os.Stderr, "dominates(%s, %s)==%t, want %t\n", b, c, actual, expected)
291				ok = false
292			}
293		}
294	}
295
296	preorder := f.DomPreorder()
297	for _, b := range f.Blocks {
298		if got := preorder[b.dom.pre]; got != b {
299			fmt.Fprintf(os.Stderr, "preorder[%d]==%s, want %s\n", b.dom.pre, got, b)
300			ok = false
301		}
302	}
303
304	if !ok {
305		panic("sanityCheckDomTree failed for " + f.String())
306	}
307
308}
309
310// Printing functions ----------------------------------------
311
312// printDomTree prints the dominator tree as text, using indentation.
313func printDomTreeText(buf *bytes.Buffer, v *BasicBlock, indent int) {
314	fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v)
315	for _, child := range v.dom.children {
316		printDomTreeText(buf, child, indent+1)
317	}
318}
319
320// printDomTreeDot prints the dominator tree of f in AT&T GraphViz
321// (.dot) format.
322func printDomTreeDot(buf *bytes.Buffer, f *Function) {
323	fmt.Fprintln(buf, "//", f)
324	fmt.Fprintln(buf, "digraph domtree {")
325	for i, b := range f.Blocks {
326		v := b.dom
327		fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post)
328		// TODO(adonovan): improve appearance of edges
329		// belonging to both dominator tree and CFG.
330
331		// Dominator tree edge.
332		if i != 0 {
333			fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.dom.pre, v.pre)
334		}
335		// CFG edges.
336		for _, pred := range b.Preds {
337			fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.dom.pre, v.pre)
338		}
339	}
340	fmt.Fprintln(buf, "}")
341}
342