1 //=- WebAssemblyFixIrreducibleControlFlow.cpp - Fix irreducible control flow -//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements a pass that removes irreducible control flow.
11 /// Irreducible control flow means multiple-entry loops, which this pass
12 /// transforms to have a single entry.
13 ///
14 /// Note that LLVM has a generic pass that lowers irreducible control flow, but
15 /// it linearizes control flow, turning diamonds into two triangles, which is
16 /// both unnecessary and undesirable for WebAssembly.
17 ///
18 /// The big picture: We recursively process each "region", defined as a group
19 /// of blocks with a single entry and no branches back to that entry. A region
20 /// may be the entire function body, or the inner part of a loop, i.e., the
21 /// loop's body without branches back to the loop entry. In each region we fix
22 /// up multi-entry loops by adding a new block that can dispatch to each of the
23 /// loop entries, based on the value of a label "helper" variable, and we
24 /// replace direct branches to the entries with assignments to the label
25 /// variable and a branch to the dispatch block. Then the dispatch block is the
26 /// single entry in the loop containing the previous multiple entries. After
27 /// ensuring all the loops in a region are reducible, we recurse into them. The
28 /// total time complexity of this pass is:
29 ///
30 ///   O(NumBlocks * NumNestedLoops * NumIrreducibleLoops +
31 ///     NumLoops * NumLoops)
32 ///
33 /// This pass is similar to what the Relooper [1] does. Both identify looping
34 /// code that requires multiple entries, and resolve it in a similar way (in
35 /// Relooper terminology, we implement a Multiple shape in a Loop shape). Note
36 /// also that like the Relooper, we implement a "minimal" intervention: we only
37 /// use the "label" helper for the blocks we absolutely must and no others. We
38 /// also prioritize code size and do not duplicate code in order to resolve
39 /// irreducibility. The graph algorithms for finding loops and entries and so
40 /// forth are also similar to the Relooper. The main differences between this
41 /// pass and the Relooper are:
42 ///
43 ///  * We just care about irreducibility, so we just look at loops.
44 ///  * The Relooper emits structured control flow (with ifs etc.), while we
45 ///    emit a CFG.
46 ///
47 /// [1] Alon Zakai. 2011. Emscripten: an LLVM-to-JavaScript compiler. In
48 /// Proceedings of the ACM international conference companion on Object oriented
49 /// programming systems languages and applications companion (SPLASH '11). ACM,
50 /// New York, NY, USA, 301-312. DOI=10.1145/2048147.2048224
51 /// http://doi.acm.org/10.1145/2048147.2048224
52 ///
53 //===----------------------------------------------------------------------===//
54 
55 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
56 #include "WebAssembly.h"
57 #include "WebAssemblySubtarget.h"
58 #include "llvm/CodeGen/MachineFunctionPass.h"
59 #include "llvm/CodeGen/MachineInstrBuilder.h"
60 #include "llvm/Support/Debug.h"
61 using namespace llvm;
62 
63 #define DEBUG_TYPE "wasm-fix-irreducible-control-flow"
64 
65 namespace {
66 
67 using BlockVector = SmallVector<MachineBasicBlock *, 4>;
68 using BlockSet = SmallPtrSet<MachineBasicBlock *, 4>;
69 
70 static BlockVector getSortedEntries(const BlockSet &Entries) {
71   BlockVector SortedEntries(Entries.begin(), Entries.end());
72   llvm::sort(SortedEntries,
73              [](const MachineBasicBlock *A, const MachineBasicBlock *B) {
74                auto ANum = A->getNumber();
75                auto BNum = B->getNumber();
76                return ANum < BNum;
77              });
78   return SortedEntries;
79 }
80 
81 // Calculates reachability in a region. Ignores branches to blocks outside of
82 // the region, and ignores branches to the region entry (for the case where
83 // the region is the inner part of a loop).
84 class ReachabilityGraph {
85 public:
86   ReachabilityGraph(MachineBasicBlock *Entry, const BlockSet &Blocks)
87       : Entry(Entry), Blocks(Blocks) {
88 #ifndef NDEBUG
89     // The region must have a single entry.
90     for (auto *MBB : Blocks) {
91       if (MBB != Entry) {
92         for (auto *Pred : MBB->predecessors()) {
93           assert(inRegion(Pred));
94         }
95       }
96     }
97 #endif
98     calculate();
99   }
100 
101   bool canReach(MachineBasicBlock *From, MachineBasicBlock *To) const {
102     assert(inRegion(From) && inRegion(To));
103     auto I = Reachable.find(From);
104     if (I == Reachable.end())
105       return false;
106     return I->second.count(To);
107   }
108 
109   // "Loopers" are blocks that are in a loop. We detect these by finding blocks
110   // that can reach themselves.
111   const BlockSet &getLoopers() const { return Loopers; }
112 
113   // Get all blocks that are loop entries.
114   const BlockSet &getLoopEntries() const { return LoopEntries; }
115 
116   // Get all blocks that enter a particular loop from outside.
117   const BlockSet &getLoopEnterers(MachineBasicBlock *LoopEntry) const {
118     assert(inRegion(LoopEntry));
119     auto I = LoopEnterers.find(LoopEntry);
120     assert(I != LoopEnterers.end());
121     return I->second;
122   }
123 
124 private:
125   MachineBasicBlock *Entry;
126   const BlockSet &Blocks;
127 
128   BlockSet Loopers, LoopEntries;
129   DenseMap<MachineBasicBlock *, BlockSet> LoopEnterers;
130 
131   bool inRegion(MachineBasicBlock *MBB) const { return Blocks.count(MBB); }
132 
133   // Maps a block to all the other blocks it can reach.
134   DenseMap<MachineBasicBlock *, BlockSet> Reachable;
135 
136   void calculate() {
137     // Reachability computation work list. Contains pairs of recent additions
138     // (A, B) where we just added a link A => B.
139     using BlockPair = std::pair<MachineBasicBlock *, MachineBasicBlock *>;
140     SmallVector<BlockPair, 4> WorkList;
141 
142     // Add all relevant direct branches.
143     for (auto *MBB : Blocks) {
144       for (auto *Succ : MBB->successors()) {
145         if (Succ != Entry && inRegion(Succ)) {
146           Reachable[MBB].insert(Succ);
147           WorkList.emplace_back(MBB, Succ);
148         }
149       }
150     }
151 
152     while (!WorkList.empty()) {
153       MachineBasicBlock *MBB, *Succ;
154       std::tie(MBB, Succ) = WorkList.pop_back_val();
155       assert(inRegion(MBB) && Succ != Entry && inRegion(Succ));
156       if (MBB != Entry) {
157         // We recently added MBB => Succ, and that means we may have enabled
158         // Pred => MBB => Succ.
159         for (auto *Pred : MBB->predecessors()) {
160           if (Reachable[Pred].insert(Succ).second) {
161             WorkList.emplace_back(Pred, Succ);
162           }
163         }
164       }
165     }
166 
167     // Blocks that can return to themselves are in a loop.
168     for (auto *MBB : Blocks) {
169       if (canReach(MBB, MBB)) {
170         Loopers.insert(MBB);
171       }
172     }
173     assert(!Loopers.count(Entry));
174 
175     // Find the loop entries - loopers reachable from blocks not in that loop -
176     // and those outside blocks that reach them, the "loop enterers".
177     for (auto *Looper : Loopers) {
178       for (auto *Pred : Looper->predecessors()) {
179         // Pred can reach Looper. If Looper can reach Pred, it is in the loop;
180         // otherwise, it is a block that enters into the loop.
181         if (!canReach(Looper, Pred)) {
182           LoopEntries.insert(Looper);
183           LoopEnterers[Looper].insert(Pred);
184         }
185       }
186     }
187   }
188 };
189 
190 // Finds the blocks in a single-entry loop, given the loop entry and the
191 // list of blocks that enter the loop.
192 class LoopBlocks {
193 public:
194   LoopBlocks(MachineBasicBlock *Entry, const BlockSet &Enterers)
195       : Entry(Entry), Enterers(Enterers) {
196     calculate();
197   }
198 
199   BlockSet &getBlocks() { return Blocks; }
200 
201 private:
202   MachineBasicBlock *Entry;
203   const BlockSet &Enterers;
204 
205   BlockSet Blocks;
206 
207   void calculate() {
208     // Going backwards from the loop entry, if we ignore the blocks entering
209     // from outside, we will traverse all the blocks in the loop.
210     BlockVector WorkList;
211     BlockSet AddedToWorkList;
212     Blocks.insert(Entry);
213     for (auto *Pred : Entry->predecessors()) {
214       if (!Enterers.count(Pred)) {
215         WorkList.push_back(Pred);
216         AddedToWorkList.insert(Pred);
217       }
218     }
219 
220     while (!WorkList.empty()) {
221       auto *MBB = WorkList.pop_back_val();
222       assert(!Enterers.count(MBB));
223       if (Blocks.insert(MBB).second) {
224         for (auto *Pred : MBB->predecessors()) {
225           if (!AddedToWorkList.count(Pred)) {
226             WorkList.push_back(Pred);
227             AddedToWorkList.insert(Pred);
228           }
229         }
230       }
231     }
232   }
233 };
234 
235 class WebAssemblyFixIrreducibleControlFlow final : public MachineFunctionPass {
236   StringRef getPassName() const override {
237     return "WebAssembly Fix Irreducible Control Flow";
238   }
239 
240   bool runOnMachineFunction(MachineFunction &MF) override;
241 
242   bool processRegion(MachineBasicBlock *Entry, BlockSet &Blocks,
243                      MachineFunction &MF);
244 
245   void makeSingleEntryLoop(BlockSet &Entries, BlockSet &Blocks,
246                            MachineFunction &MF, const ReachabilityGraph &Graph);
247 
248 public:
249   static char ID; // Pass identification, replacement for typeid
250   WebAssemblyFixIrreducibleControlFlow() : MachineFunctionPass(ID) {}
251 };
252 
253 bool WebAssemblyFixIrreducibleControlFlow::processRegion(
254     MachineBasicBlock *Entry, BlockSet &Blocks, MachineFunction &MF) {
255   bool Changed = false;
256   // Remove irreducibility before processing child loops, which may take
257   // multiple iterations.
258   while (true) {
259     ReachabilityGraph Graph(Entry, Blocks);
260 
261     bool FoundIrreducibility = false;
262 
263     for (auto *LoopEntry : getSortedEntries(Graph.getLoopEntries())) {
264       // Find mutual entries - all entries which can reach this one, and
265       // are reached by it (that always includes LoopEntry itself). All mutual
266       // entries must be in the same loop, so if we have more than one, then we
267       // have irreducible control flow.
268       //
269       // (Note that we need to sort the entries here, as otherwise the order can
270       // matter: being mutual is a symmetric relationship, and each set of
271       // mutuals will be handled properly no matter which we see first. However,
272       // there can be multiple disjoint sets of mutuals, and which we process
273       // first changes the output.)
274       //
275       // Note that irreducibility may involve inner loops, e.g. imagine A
276       // starts one loop, and it has B inside it which starts an inner loop.
277       // If we add a branch from all the way on the outside to B, then in a
278       // sense B is no longer an "inner" loop, semantically speaking. We will
279       // fix that irreducibility by adding a block that dispatches to either
280       // either A or B, so B will no longer be an inner loop in our output.
281       // (A fancier approach might try to keep it as such.)
282       //
283       // Note that we still need to recurse into inner loops later, to handle
284       // the case where the irreducibility is entirely nested - we would not
285       // be able to identify that at this point, since the enclosing loop is
286       // a group of blocks all of whom can reach each other. (We'll see the
287       // irreducibility after removing branches to the top of that enclosing
288       // loop.)
289       BlockSet MutualLoopEntries;
290       MutualLoopEntries.insert(LoopEntry);
291       for (auto *OtherLoopEntry : Graph.getLoopEntries()) {
292         if (OtherLoopEntry != LoopEntry &&
293             Graph.canReach(LoopEntry, OtherLoopEntry) &&
294             Graph.canReach(OtherLoopEntry, LoopEntry)) {
295           MutualLoopEntries.insert(OtherLoopEntry);
296         }
297       }
298 
299       if (MutualLoopEntries.size() > 1) {
300         makeSingleEntryLoop(MutualLoopEntries, Blocks, MF, Graph);
301         FoundIrreducibility = true;
302         Changed = true;
303         break;
304       }
305     }
306     // Only go on to actually process the inner loops when we are done
307     // removing irreducible control flow and changing the graph. Modifying
308     // the graph as we go is possible, and that might let us avoid looking at
309     // the already-fixed loops again if we are careful, but all that is
310     // complex and bug-prone. Since irreducible loops are rare, just starting
311     // another iteration is best.
312     if (FoundIrreducibility) {
313       continue;
314     }
315 
316     for (auto *LoopEntry : Graph.getLoopEntries()) {
317       LoopBlocks InnerBlocks(LoopEntry, Graph.getLoopEnterers(LoopEntry));
318       // Each of these calls to processRegion may change the graph, but are
319       // guaranteed not to interfere with each other. The only changes we make
320       // to the graph are to add blocks on the way to a loop entry. As the
321       // loops are disjoint, that means we may only alter branches that exit
322       // another loop, which are ignored when recursing into that other loop
323       // anyhow.
324       if (processRegion(LoopEntry, InnerBlocks.getBlocks(), MF)) {
325         Changed = true;
326       }
327     }
328 
329     return Changed;
330   }
331 }
332 
333 // Given a set of entries to a single loop, create a single entry for that
334 // loop by creating a dispatch block for them, routing control flow using
335 // a helper variable. Also updates Blocks with any new blocks created, so
336 // that we properly track all the blocks in the region. But this does not update
337 // ReachabilityGraph; this will be updated in the caller of this function as
338 // needed.
339 void WebAssemblyFixIrreducibleControlFlow::makeSingleEntryLoop(
340     BlockSet &Entries, BlockSet &Blocks, MachineFunction &MF,
341     const ReachabilityGraph &Graph) {
342   assert(Entries.size() >= 2);
343 
344   // Sort the entries to ensure a deterministic build.
345   BlockVector SortedEntries = getSortedEntries(Entries);
346 
347 #ifndef NDEBUG
348   for (auto Block : SortedEntries)
349     assert(Block->getNumber() != -1);
350   if (SortedEntries.size() > 1) {
351     for (auto I = SortedEntries.begin(), E = SortedEntries.end() - 1; I != E;
352          ++I) {
353       auto ANum = (*I)->getNumber();
354       auto BNum = (*(std::next(I)))->getNumber();
355       assert(ANum != BNum);
356     }
357   }
358 #endif
359 
360   // Create a dispatch block which will contain a jump table to the entries.
361   MachineBasicBlock *Dispatch = MF.CreateMachineBasicBlock();
362   MF.insert(MF.end(), Dispatch);
363   Blocks.insert(Dispatch);
364 
365   // Add the jump table.
366   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
367   MachineInstrBuilder MIB =
368       BuildMI(Dispatch, DebugLoc(), TII.get(WebAssembly::BR_TABLE_I32));
369 
370   // Add the register which will be used to tell the jump table which block to
371   // jump to.
372   MachineRegisterInfo &MRI = MF.getRegInfo();
373   Register Reg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
374   MIB.addReg(Reg);
375 
376   // Compute the indices in the superheader, one for each bad block, and
377   // add them as successors.
378   DenseMap<MachineBasicBlock *, unsigned> Indices;
379   for (auto *Entry : SortedEntries) {
380     auto Pair = Indices.insert(std::make_pair(Entry, 0));
381     assert(Pair.second);
382 
383     unsigned Index = MIB.getInstr()->getNumExplicitOperands() - 1;
384     Pair.first->second = Index;
385 
386     MIB.addMBB(Entry);
387     Dispatch->addSuccessor(Entry);
388   }
389 
390   // Rewrite the problematic successors for every block that wants to reach
391   // the bad blocks. For simplicity, we just introduce a new block for every
392   // edge we need to rewrite. (Fancier things are possible.)
393 
394   BlockVector AllPreds;
395   for (auto *Entry : SortedEntries) {
396     for (auto *Pred : Entry->predecessors()) {
397       if (Pred != Dispatch) {
398         AllPreds.push_back(Pred);
399       }
400     }
401   }
402 
403   // This set stores predecessors within this loop.
404   DenseSet<MachineBasicBlock *> InLoop;
405   for (auto *Pred : AllPreds) {
406     for (auto *Entry : Pred->successors()) {
407       if (!Entries.count(Entry))
408         continue;
409       if (Graph.canReach(Entry, Pred)) {
410         InLoop.insert(Pred);
411         break;
412       }
413     }
414   }
415 
416   // Record if each entry has a layout predecessor. This map stores
417   // <<loop entry, Predecessor is within the loop?>, layout predecessor>
418   DenseMap<PointerIntPair<MachineBasicBlock *, 1, bool>, MachineBasicBlock *>
419       EntryToLayoutPred;
420   for (auto *Pred : AllPreds) {
421     bool PredInLoop = InLoop.count(Pred);
422     for (auto *Entry : Pred->successors())
423       if (Entries.count(Entry) && Pred->isLayoutSuccessor(Entry))
424         EntryToLayoutPred[{Entry, PredInLoop}] = Pred;
425   }
426 
427   // We need to create at most two routing blocks per entry: one for
428   // predecessors outside the loop and one for predecessors inside the loop.
429   // This map stores
430   // <<loop entry, Predecessor is within the loop?>, routing block>
431   DenseMap<PointerIntPair<MachineBasicBlock *, 1, bool>, MachineBasicBlock *>
432       Map;
433   for (auto *Pred : AllPreds) {
434     bool PredInLoop = InLoop.count(Pred);
435     for (auto *Entry : Pred->successors()) {
436       if (!Entries.count(Entry) || Map.count({Entry, PredInLoop}))
437         continue;
438       // If there exists a layout predecessor of this entry and this predecessor
439       // is not that, we rather create a routing block after that layout
440       // predecessor to save a branch.
441       if (auto *OtherPred = EntryToLayoutPred.lookup({Entry, PredInLoop}))
442         if (OtherPred != Pred)
443           continue;
444 
445       // This is a successor we need to rewrite.
446       MachineBasicBlock *Routing = MF.CreateMachineBasicBlock();
447       MF.insert(Pred->isLayoutSuccessor(Entry)
448                     ? MachineFunction::iterator(Entry)
449                     : MF.end(),
450                 Routing);
451       Blocks.insert(Routing);
452 
453       // Set the jump table's register of the index of the block we wish to
454       // jump to, and jump to the jump table.
455       BuildMI(Routing, DebugLoc(), TII.get(WebAssembly::CONST_I32), Reg)
456           .addImm(Indices[Entry]);
457       BuildMI(Routing, DebugLoc(), TII.get(WebAssembly::BR)).addMBB(Dispatch);
458       Routing->addSuccessor(Dispatch);
459       Map[{Entry, PredInLoop}] = Routing;
460     }
461   }
462 
463   for (auto *Pred : AllPreds) {
464     bool PredInLoop = InLoop.count(Pred);
465     // Remap the terminator operands and the successor list.
466     for (MachineInstr &Term : Pred->terminators())
467       for (auto &Op : Term.explicit_uses())
468         if (Op.isMBB() && Indices.count(Op.getMBB()))
469           Op.setMBB(Map[{Op.getMBB(), PredInLoop}]);
470 
471     for (auto *Succ : Pred->successors()) {
472       if (!Entries.count(Succ))
473         continue;
474       auto *Routing = Map[{Succ, PredInLoop}];
475       Pred->replaceSuccessor(Succ, Routing);
476     }
477   }
478 
479   // Create a fake default label, because br_table requires one.
480   MIB.addMBB(MIB.getInstr()
481                  ->getOperand(MIB.getInstr()->getNumExplicitOperands() - 1)
482                  .getMBB());
483 }
484 
485 } // end anonymous namespace
486 
487 char WebAssemblyFixIrreducibleControlFlow::ID = 0;
488 INITIALIZE_PASS(WebAssemblyFixIrreducibleControlFlow, DEBUG_TYPE,
489                 "Removes irreducible control flow", false, false)
490 
491 FunctionPass *llvm::createWebAssemblyFixIrreducibleControlFlow() {
492   return new WebAssemblyFixIrreducibleControlFlow();
493 }
494 
495 bool WebAssemblyFixIrreducibleControlFlow::runOnMachineFunction(
496     MachineFunction &MF) {
497   LLVM_DEBUG(dbgs() << "********** Fixing Irreducible Control Flow **********\n"
498                        "********** Function: "
499                     << MF.getName() << '\n');
500 
501   // Start the recursive process on the entire function body.
502   BlockSet AllBlocks;
503   for (auto &MBB : MF) {
504     AllBlocks.insert(&MBB);
505   }
506 
507   if (LLVM_UNLIKELY(processRegion(&*MF.begin(), AllBlocks, MF))) {
508     // We rewrote part of the function; recompute relevant things.
509     MF.getRegInfo().invalidateLiveness();
510     MF.RenumberBlocks();
511     return true;
512   }
513 
514   return false;
515 }
516