Debian Codegraph @

internal/engine/wazevo/ssa/pass_blk_layouts.go

raw
1 package ssa
2
3 import (
4 "fmt"
5 "strings"
6
7 "github.com/tetratelabs/wazero/internal/engine/wazevo/wazevoapi"
8 )
9
10 // passLayoutBlocks implements Builder.LayoutBlocks. This re-organizes builder.reversePostOrderedBasicBlocks.
11 //
12 // TODO: there are tons of room for improvement here. e.g. LLVM has BlockPlacementPass using BlockFrequencyInfo,
13 // BranchProbabilityInfo, and LoopInfo to do a much better job. Also, if we have the profiling instrumentation
14 // like ball-larus algorithm, then we could do profile-guided optimization. Basically all of them are trying
15 // to maximize the fall-through opportunities which is most efficient.
16 //
17 // Here, fallthrough happens when a block ends with jump instruction whose target is the right next block in the
18 // builder.reversePostOrderedBasicBlocks.
19 //
20 // Currently, we just place blocks using the DFS reverse post-order of the dominator tree with the heuristics:
21 // 1. a split edge trampoline towards a loop header will be placed as a fallthrough.
22 // 2. we invert the brz and brnz if it makes the fallthrough more likely.
23 //
24 // This heuristic is done in maybeInvertBranches function.
25 func passLayoutBlocks(b *builder) {
26 // We might end up splitting critical edges which adds more basic blocks,
27 // so we store the currently existing basic blocks in nonSplitBlocks temporarily.
28 // That way we can iterate over the original basic blocks while appending new ones into reversePostOrderedBasicBlocks.
29 nonSplitBlocks := b.blkStack[:0]
30 for i, blk := range b.reversePostOrderedBasicBlocks {
31 if !blk.Valid() {
32 continue
33 }
34 nonSplitBlocks = append(nonSplitBlocks, blk)
35 if i != len(b.reversePostOrderedBasicBlocks)-1 {
36 _ = maybeInvertBranches(b, blk, b.reversePostOrderedBasicBlocks[i+1])
37 }
38 }
39
40 var trampolines []*basicBlock
41
42 // Reset the order slice since we update on the fly by splitting critical edges.
43 b.reversePostOrderedBasicBlocks = b.reversePostOrderedBasicBlocks[:0]
44 uninsertedTrampolines := b.blkStack2[:0]
45 for _, blk := range nonSplitBlocks {
46 for i := range blk.preds {
47 pred := blk.preds[i].blk
48 if pred.visited == 1 || !pred.Valid() {
49 continue
50 } else if pred.reversePostOrder < blk.reversePostOrder {
51 // This means the edge is critical, and this pred is the trampoline and yet to be inserted.
52 // Split edge trampolines must come before the destination in reverse post-order.
53 b.reversePostOrderedBasicBlocks = append(b.reversePostOrderedBasicBlocks, pred)
54 pred.visited = 1 // mark as inserted.
55 }
56 }
57
58 // Now that we've already added all the potential trampoline blocks incoming to this block,
59 // we can add this block itself.
60 b.reversePostOrderedBasicBlocks = append(b.reversePostOrderedBasicBlocks, blk)
61 blk.visited = 1 // mark as inserted.
62
63 if len(blk.success) < 2 {
64 // There won't be critical edge originating from this block.
65 continue
66 } else if blk.currentInstr.opcode == OpcodeBrTable {
67 // We don't split critical edges here, because at the construction site of BrTable, we already split the edges.
68 continue
69 }
70
71 for sidx, succ := range blk.success {
72 if !succ.ReturnBlock() && // If the successor is a return block, we need to split the edge any way because we need "epilogue" to be inserted.
73 // Plus if there's no multiple incoming edges to this successor, (pred, succ) is not critical.
74 len(succ.preds) < 2 {
75 continue
76 }
77
78 // Otherwise, we are sure this is a critical edge. To modify the CFG, we need to find the predecessor info
79 // from the successor.
80 var predInfo *basicBlockPredecessorInfo
81 for i := range succ.preds { // This linear search should not be a problem since the number of predecessors should almost always small.
82 pred := &succ.preds[i]
83 if pred.blk == blk {
84 predInfo = pred
85 break
86 }
87 }
88
89 if predInfo == nil {
90 // This must be a bug in somewhere around branch manipulation.
91 panic("BUG: predecessor info not found while the successor exists in successors list")
92 }
93
94 if wazevoapi.SSALoggingEnabled {
95 fmt.Printf("trying to split edge from %d->%d at %s\n",
96 blk.ID(), succ.ID(), predInfo.branch.Format(b))
97 }
98
99 trampoline := b.splitCriticalEdge(blk, succ, predInfo)
100 // Update the successors slice because the target is no longer the original `succ`.
101 blk.success[sidx] = trampoline
102
103 if wazevoapi.SSAValidationEnabled {
104 trampolines = append(trampolines, trampoline)
105 }
106
107 if wazevoapi.SSALoggingEnabled {
108 fmt.Printf("edge split from %d->%d at %s as %d->%d->%d \n",
109 blk.ID(), succ.ID(), predInfo.branch.Format(b),
110 blk.ID(), trampoline.ID(), succ.ID())
111 }
112
113 fallthroughBranch := blk.currentInstr
114 if fallthroughBranch.opcode == OpcodeJump && BasicBlockID(fallthroughBranch.rValue) == trampoline.id {
115 // This can be lowered as fallthrough at the end of the block.
116 b.reversePostOrderedBasicBlocks = append(b.reversePostOrderedBasicBlocks, trampoline)
117 trampoline.visited = 1 // mark as inserted.
118 } else {
119 uninsertedTrampolines = append(uninsertedTrampolines, trampoline)
120 }
121 }
122
123 for _, trampoline := range uninsertedTrampolines {
124 if trampoline.success[0].reversePostOrder <= trampoline.reversePostOrder { // "<=", not "<" because the target might be itself.
125 // This means the critical edge was backward, so we insert after the current block immediately.
126 b.reversePostOrderedBasicBlocks = append(b.reversePostOrderedBasicBlocks, trampoline)
127 trampoline.visited = 1 // mark as inserted.
128 } // If the target is forward, we can wait to insert until the target is inserted.
129 }
130 uninsertedTrampolines = uninsertedTrampolines[:0] // Reuse the stack for the next block.
131 }
132
133 if wazevoapi.SSALoggingEnabled {
134 var bs []string
135 for _, blk := range b.reversePostOrderedBasicBlocks {
136 bs = append(bs, blk.Name())
137 }
138 fmt.Println("ordered blocks: ", strings.Join(bs, ", "))
139 }
140
141 if wazevoapi.SSAValidationEnabled {
142 for _, trampoline := range trampolines {
143 if trampoline.visited != 1 {
144 panic("BUG: trampoline block not inserted: " + trampoline.formatHeader(b))
145 }
146 trampoline.validate(b)
147 }
148 }
149
150 // Reuse the stack for the next iteration.
151 b.blkStack2 = uninsertedTrampolines[:0]
152 }
153
154 // markFallthroughJumps finds the fallthrough jumps and marks them as such.
155 func (b *builder) markFallthroughJumps() {
156 l := len(b.reversePostOrderedBasicBlocks) - 1
157 for i, blk := range b.reversePostOrderedBasicBlocks {
158 if i < l {
159 cur := blk.currentInstr
160 if cur.opcode == OpcodeJump && BasicBlockID(cur.rValue) == b.reversePostOrderedBasicBlocks[i+1].id {
161 cur.AsFallthroughJump()
162 }
163 }
164 }
165 }
166
167 // maybeInvertBranches inverts the branch instructions if it is likely possible to the fallthrough more likely with simple heuristics.
168 // nextInRPO is the next block in the reverse post-order.
169 //
170 // Returns true if the branch is inverted for testing purpose.
171 func maybeInvertBranches(b *builder, now *basicBlock, nextInRPO *basicBlock) bool {
172 fallthroughBranch := now.currentInstr
173 if fallthroughBranch.opcode == OpcodeBrTable {
174 return false
175 }
176
177 condBranch := fallthroughBranch.prev
178 if condBranch == nil || (condBranch.opcode != OpcodeBrnz && condBranch.opcode != OpcodeBrz) {
179 return false
180 }
181
182 if len(fallthroughBranch.vs.View()) != 0 || len(condBranch.vs.View()) != 0 {
183 // If either one of them has arguments, we don't invert the branches.
184 return false
185 }
186
187 // So this block has two branches (a conditional branch followed by an unconditional branch) at the end.
188 // We can invert the condition of the branch if it makes the fallthrough more likely.
189
190 fallthroughTarget := b.basicBlock(BasicBlockID(fallthroughBranch.rValue))
191 condTarget := b.basicBlock(BasicBlockID(condBranch.rValue))
192
193 if fallthroughTarget.loopHeader {
194 // First, if the tail's target is loopHeader, we don't need to do anything here,
195 // because the edge is likely to be critical edge for complex loops (e.g. loop with branches inside it).
196 // That means, we will split the edge in the end of LayoutBlocks function, and insert the trampoline block
197 // right after this block, which will be fallthrough in any way.
198 return false
199 } else if condTarget.loopHeader {
200 // On the other hand, if the condBranch's target is loopHeader, we invert the condition of the branch
201 // so that we could get the fallthrough to the trampoline block.
202 goto invert
203 }
204
205 if fallthroughTarget == nextInRPO {
206 // Also, if the tail's target is the next block in the reverse post-order, we don't need to do anything here,
207 // because if this is not critical edge, we would end up placing these two blocks adjacent to each other.
208 // Even if it is the critical edge, we place the trampoline block right after this block, which will be fallthrough in any way.
209 return false
210 } else if condTarget == nextInRPO {
211 // If the condBranch's target is the next block in the reverse post-order, we invert the condition of the branch
212 // so that we could get the fallthrough to the block.
213 goto invert
214 } else {
215 return false
216 }
217
218 invert:
219 for i := range fallthroughTarget.preds {
220 pred := &fallthroughTarget.preds[i]
221 if pred.branch == fallthroughBranch {
222 pred.branch = condBranch
223 break
224 }
225 }
226 for i := range condTarget.preds {
227 pred := &condTarget.preds[i]
228 if pred.branch == condBranch {
229 pred.branch = fallthroughBranch
230 break
231 }
232 }
233
234 condBranch.InvertBrx()
235 condBranch.rValue = Value(fallthroughTarget.ID())
236 fallthroughBranch.rValue = Value(condTarget.ID())
237 if wazevoapi.SSALoggingEnabled {
238 fmt.Printf("inverting branches at %d->%d and %d->%d\n",
239 now.ID(), fallthroughTarget.ID(), now.ID(), condTarget.ID())
240 }
241
242 return true
243 }
244
245 // splitCriticalEdge splits the critical edge between the given predecessor (`pred`) and successor (owning `predInfo`).
246 //
247 // - `pred` is the source of the critical edge,
248 // - `succ` is the destination of the critical edge,
249 // - `predInfo` is the predecessor info in the succ.preds slice which represents the critical edge.
250 //
251 // Why splitting critical edges is important? See following links:
252 //
253 // - https://en.wikipedia.org/wiki/Control-flow_graph
254 // - https://nickdesaulniers.github.io/blog/2023/01/27/critical-edge-splitting/
255 //
256 // The returned basic block is the trampoline block which is inserted to split the critical edge.
257 func (b *builder) splitCriticalEdge(pred, succ *basicBlock, predInfo *basicBlockPredecessorInfo) *basicBlock {
258 // In the following, we convert the following CFG:
259 //
260 // pred --(originalBranch)--> succ
261 //
262 // to the following CFG:
263 //
264 // pred --(newBranch)--> trampoline --(originalBranch)-> succ
265 //
266 // where trampoline is a new basic block which is created to split the critical edge.
267
268 trampoline := b.allocateBasicBlock()
269 if int(trampoline.id) >= len(b.dominators) {
270 b.dominators = append(b.dominators, make([]*basicBlock, trampoline.id+1)...)
271 }
272 b.dominators[trampoline.id] = pred
273
274 originalBranch := predInfo.branch
275
276 // Replace originalBranch with the newBranch.
277 newBranch := b.AllocateInstruction()
278 newBranch.opcode = originalBranch.opcode
279 newBranch.rValue = Value(trampoline.ID())
280 switch originalBranch.opcode {
281 case OpcodeJump:
282 case OpcodeBrz, OpcodeBrnz:
283 originalBranch.opcode = OpcodeJump // Trampoline consists of one unconditional branch.
284 newBranch.v = originalBranch.v
285 originalBranch.v = ValueInvalid
286 default:
287 panic("BUG: critical edge shouldn't be originated from br_table")
288 }
289 swapInstruction(pred, originalBranch, newBranch)
290
291 // Replace the original branch with the new branch.
292 trampoline.rootInstr = originalBranch
293 trampoline.currentInstr = originalBranch
294 trampoline.success = append(trampoline.success, succ) // Do not use []*basicBlock{pred} because we might have already allocated the slice.
295 trampoline.preds = append(trampoline.preds, // same as ^.
296 basicBlockPredecessorInfo{blk: pred, branch: newBranch})
297 b.Seal(trampoline)
298
299 // Update the original branch to point to the trampoline.
300 predInfo.blk = trampoline
301 predInfo.branch = originalBranch
302
303 if wazevoapi.SSAValidationEnabled {
304 trampoline.validate(b)
305 }
306
307 if len(trampoline.params.View()) > 0 {
308 panic("trampoline should not have params")
309 }
310
311 // Assign the same order as the original block so that this will be placed before the actual destination.
312 trampoline.reversePostOrder = pred.reversePostOrder
313 return trampoline
314 }
315
316 // swapInstruction replaces `old` in the block `blk` with `New`.
317 func swapInstruction(blk *basicBlock, old, New *Instruction) {
318 if blk.rootInstr == old {
319 blk.rootInstr = New
320 next := old.next
321 New.next = next
322 next.prev = New
323 } else {
324 if blk.currentInstr == old {
325 blk.currentInstr = New
326 }
327 prev := old.prev
328 prev.next, New.prev = New, prev
329 if next := old.next; next != nil {
330 New.next, next.prev = next, New
331 }
332 }
333 old.prev, old.next = nil, nil
334 }