xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp (revision a187ab2aeb4666d799a24b6c9472e6e67d640e1f)
1 //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements a CFG stacking pass.
12 ///
13 /// This pass reorders the blocks in a function to put them into a reverse
14 /// post-order [0], with special care to keep the order as similar as possible
15 /// to the original order, and to keep loops contiguous even in the case of
16 /// split backedges.
17 ///
18 /// Then, it inserts BLOCK and LOOP markers to mark the start of scopes, since
19 /// scope boundaries serve as the labels for WebAssembly's control transfers.
20 ///
21 /// This is sufficient to convert arbitrary CFGs into a form that works on
22 /// WebAssembly, provided that all loops are single-entry.
23 ///
24 /// [0] https://en.wikipedia.org/wiki/Depth-first_search#Vertex_orderings
25 ///
26 //===----------------------------------------------------------------------===//
27 
28 #include "WebAssembly.h"
29 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
30 #include "WebAssemblyMachineFunctionInfo.h"
31 #include "WebAssemblySubtarget.h"
32 #include "llvm/ADT/SCCIterator.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/CodeGen/MachineDominators.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineLoopInfo.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/Passes.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "wasm-cfg-stackify"
45 
46 namespace {
47 class WebAssemblyCFGStackify final : public MachineFunctionPass {
48   const char *getPassName() const override {
49     return "WebAssembly CFG Stackify";
50   }
51 
52   void getAnalysisUsage(AnalysisUsage &AU) const override {
53     AU.setPreservesCFG();
54     AU.addRequired<MachineDominatorTree>();
55     AU.addPreserved<MachineDominatorTree>();
56     AU.addRequired<MachineLoopInfo>();
57     AU.addPreserved<MachineLoopInfo>();
58     MachineFunctionPass::getAnalysisUsage(AU);
59   }
60 
61   bool runOnMachineFunction(MachineFunction &MF) override;
62 
63 public:
64   static char ID; // Pass identification, replacement for typeid
65   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
66 };
67 } // end anonymous namespace
68 
69 char WebAssemblyCFGStackify::ID = 0;
70 FunctionPass *llvm::createWebAssemblyCFGStackify() {
71   return new WebAssemblyCFGStackify();
72 }
73 
74 static void EliminateMultipleEntryLoops(MachineFunction &MF,
75                                         const MachineLoopInfo &MLI) {
76   SmallPtrSet<MachineBasicBlock *, 8> InSet;
77   for (scc_iterator<MachineFunction *> I = scc_begin(&MF), E = scc_end(&MF);
78        I != E; ++I) {
79     const std::vector<MachineBasicBlock *> &CurrentSCC = *I;
80 
81     // Skip trivial SCCs.
82     if (CurrentSCC.size() == 1)
83       continue;
84 
85     InSet.insert(CurrentSCC.begin(), CurrentSCC.end());
86     MachineBasicBlock *Header = nullptr;
87     for (MachineBasicBlock *MBB : CurrentSCC) {
88       for (MachineBasicBlock *Pred : MBB->predecessors()) {
89         if (InSet.count(Pred))
90           continue;
91         if (!Header) {
92           Header = MBB;
93           break;
94         }
95         // TODO: Implement multiple-entry loops.
96         report_fatal_error("multiple-entry loops are not supported yet");
97       }
98     }
99     assert(MLI.isLoopHeader(Header));
100 
101     InSet.clear();
102   }
103 }
104 
105 namespace {
106 /// Post-order traversal stack entry.
107 struct POStackEntry {
108   MachineBasicBlock *MBB;
109   SmallVector<MachineBasicBlock *, 0> Succs;
110 
111   POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF,
112                const MachineLoopInfo &MLI);
113 };
114 } // end anonymous namespace
115 
116 static bool LoopContains(const MachineLoop *Loop,
117                          const MachineBasicBlock *MBB) {
118   return Loop ? Loop->contains(MBB) : true;
119 }
120 
121 POStackEntry::POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF,
122                            const MachineLoopInfo &MLI)
123     : MBB(MBB), Succs(MBB->successors()) {
124   // RPO is not a unique form, since at every basic block with multiple
125   // successors, the DFS has to pick which order to visit the successors in.
126   // Sort them strategically (see below).
127   MachineLoop *Loop = MLI.getLoopFor(MBB);
128   MachineFunction::iterator Next = next(MachineFunction::iterator(MBB));
129   MachineBasicBlock *LayoutSucc = Next == MF.end() ? nullptr : &*Next;
130   std::stable_sort(
131       Succs.begin(), Succs.end(),
132       [=, &MLI](const MachineBasicBlock *A, const MachineBasicBlock *B) {
133         if (A == B)
134           return false;
135 
136         // Keep loops contiguous by preferring the block that's in the same
137         // loop.
138         bool LoopContainsA = LoopContains(Loop, A);
139         bool LoopContainsB = LoopContains(Loop, B);
140         if (LoopContainsA && !LoopContainsB)
141           return true;
142         if (!LoopContainsA && LoopContainsB)
143           return false;
144 
145         // Minimize perturbation by preferring the block which is the immediate
146         // layout successor.
147         if (A == LayoutSucc)
148           return true;
149         if (B == LayoutSucc)
150           return false;
151 
152         // TODO: More sophisticated orderings may be profitable here.
153 
154         return false;
155       });
156 }
157 
158 /// Return the "bottom" block of a loop. This differs from
159 /// MachineLoop::getBottomBlock in that it works even if the loop is
160 /// discontiguous.
161 static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) {
162   MachineBasicBlock *Bottom = Loop->getHeader();
163   for (MachineBasicBlock *MBB : Loop->blocks())
164     if (MBB->getNumber() > Bottom->getNumber())
165       Bottom = MBB;
166   return Bottom;
167 }
168 
169 /// Sort the blocks in RPO, taking special care to make sure that loops are
170 /// contiguous even in the case of split backedges.
171 ///
172 /// TODO: Determine whether RPO is actually worthwhile, or whether we should
173 /// move to just a stable-topological-sort-based approach that would preserve
174 /// more of the original order.
175 static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI) {
176   // Note that we do our own RPO rather than using
177   // "llvm/ADT/PostOrderIterator.h" because we want control over the order that
178   // successors are visited in (see above). Also, we can sort the blocks in the
179   // MachineFunction as we go.
180   SmallPtrSet<MachineBasicBlock *, 16> Visited;
181   SmallVector<POStackEntry, 16> Stack;
182 
183   MachineBasicBlock *EntryBlock = &*MF.begin();
184   Visited.insert(EntryBlock);
185   Stack.push_back(POStackEntry(EntryBlock, MF, MLI));
186 
187   for (;;) {
188     POStackEntry &Entry = Stack.back();
189     SmallVectorImpl<MachineBasicBlock *> &Succs = Entry.Succs;
190     if (!Succs.empty()) {
191       MachineBasicBlock *Succ = Succs.pop_back_val();
192       if (Visited.insert(Succ).second)
193         Stack.push_back(POStackEntry(Succ, MF, MLI));
194       continue;
195     }
196 
197     // Put the block in its position in the MachineFunction.
198     MachineBasicBlock &MBB = *Entry.MBB;
199     MBB.moveBefore(&*MF.begin());
200 
201     // Branch instructions may utilize a fallthrough, so update them if a
202     // fallthrough has been added or removed.
203     if (!MBB.empty() && MBB.back().isTerminator() && !MBB.back().isBranch() &&
204         !MBB.back().isBarrier())
205       report_fatal_error(
206           "Non-branch terminator with fallthrough cannot yet be rewritten");
207     if (MBB.empty() || !MBB.back().isTerminator() || MBB.back().isBranch())
208       MBB.updateTerminator();
209 
210     Stack.pop_back();
211     if (Stack.empty())
212       break;
213   }
214 
215   // Now that we've sorted the blocks in RPO, renumber them.
216   MF.RenumberBlocks();
217 
218 #ifndef NDEBUG
219   SmallSetVector<MachineLoop *, 8> OnStack;
220 
221   // Insert a sentinel representing the degenerate loop that starts at the
222   // function entry block and includes the entire function as a "loop" that
223   // executes once.
224   OnStack.insert(nullptr);
225 
226   for (auto &MBB : MF) {
227     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
228 
229     MachineLoop *Loop = MLI.getLoopFor(&MBB);
230     if (Loop && &MBB == Loop->getHeader()) {
231       // Loop header. The loop predecessor should be sorted above, and the other
232       // predecessors should be backedges below.
233       for (auto Pred : MBB.predecessors())
234         assert(
235             (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) &&
236             "Loop header predecessors must be loop predecessors or backedges");
237       assert(OnStack.insert(Loop) && "Loops should be declared at most once.");
238     } else {
239       // Not a loop header. All predecessors should be sorted above.
240       for (auto Pred : MBB.predecessors())
241         assert(Pred->getNumber() < MBB.getNumber() &&
242                "Non-loop-header predecessors should be topologically sorted");
243       assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
244              "Blocks must be nested in their loops");
245     }
246     while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back()))
247       OnStack.pop_back();
248   }
249   assert(OnStack.pop_back_val() == nullptr &&
250          "The function entry block shouldn't actually be a loop header");
251   assert(OnStack.empty() &&
252          "Control flow stack pushes and pops should be balanced.");
253 #endif
254 }
255 
256 /// Test whether Pred has any terminators explicitly branching to MBB, as
257 /// opposed to falling through. Note that it's possible (eg. in unoptimized
258 /// code) for a branch instruction to both branch to a block and fallthrough
259 /// to it, so we check the actual branch operands to see if there are any
260 /// explicit mentions.
261 static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
262                                  MachineBasicBlock *MBB) {
263   for (MachineInstr &MI : Pred->terminators())
264     for (MachineOperand &MO : MI.explicit_operands())
265       if (MO.isMBB() && MO.getMBB() == MBB)
266         return true;
267   return false;
268 }
269 
270 /// Test whether MI is a child of some other node in an expression tree.
271 static bool IsChild(const MachineInstr *MI,
272                     const WebAssemblyFunctionInfo &MFI) {
273   if (MI->getNumOperands() == 0)
274     return false;
275   const MachineOperand &MO = MI->getOperand(0);
276   if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
277     return false;
278   unsigned Reg = MO.getReg();
279   return TargetRegisterInfo::isVirtualRegister(Reg) &&
280          MFI.isVRegStackified(Reg);
281 }
282 
283 /// Insert a BLOCK marker for branches to MBB (if needed).
284 static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF,
285                              SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
286                              const WebAssemblyInstrInfo &TII,
287                              const MachineLoopInfo &MLI,
288                              MachineDominatorTree &MDT,
289                              WebAssemblyFunctionInfo &MFI) {
290   // First compute the nearest common dominator of all forward non-fallthrough
291   // predecessors so that we minimize the time that the BLOCK is on the stack,
292   // which reduces overall stack height.
293   MachineBasicBlock *Header = nullptr;
294   bool IsBranchedTo = false;
295   int MBBNumber = MBB.getNumber();
296   for (MachineBasicBlock *Pred : MBB.predecessors())
297     if (Pred->getNumber() < MBBNumber) {
298       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
299       if (ExplicitlyBranchesTo(Pred, &MBB))
300         IsBranchedTo = true;
301     }
302   if (!Header)
303     return;
304   if (!IsBranchedTo)
305     return;
306 
307   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
308   MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB));
309 
310   // If the nearest common dominator is inside a more deeply nested context,
311   // walk out to the nearest scope which isn't more deeply nested.
312   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
313     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
314       if (ScopeTop->getNumber() > Header->getNumber()) {
315         // Skip over an intervening scope.
316         I = next(MachineFunction::iterator(ScopeTop));
317       } else {
318         // We found a scope level at an appropriate depth.
319         Header = ScopeTop;
320         break;
321       }
322     }
323   }
324 
325   // If there's a loop which ends just before MBB which contains Header, we can
326   // reuse its label instead of inserting a new BLOCK.
327   for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred);
328        Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop())
329     if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header))
330       return;
331 
332   // Decide where in Header to put the BLOCK.
333   MachineBasicBlock::iterator InsertPos;
334   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
335   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
336     // Header is the header of a loop that does not lexically contain MBB, so
337     // the BLOCK needs to be above the LOOP, after any END constructs.
338     InsertPos = Header->begin();
339     while (InsertPos->getOpcode() != WebAssembly::LOOP)
340       ++InsertPos;
341   } else {
342     // Otherwise, insert the BLOCK as late in Header as we can, but before the
343     // beginning of the local expression tree and any nested BLOCKs.
344     InsertPos = Header->getFirstTerminator();
345     while (InsertPos != Header->begin() &&
346            IsChild(prev(InsertPos), MFI) &&
347            prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
348            prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
349            prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
350       --InsertPos;
351   }
352 
353   // Add the BLOCK.
354   BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK));
355 
356   // Mark the end of the block.
357   InsertPos = MBB.begin();
358   while (InsertPos != MBB.end() &&
359          InsertPos->getOpcode() == WebAssembly::END_LOOP)
360     ++InsertPos;
361   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK));
362 
363   // Track the farthest-spanning scope that ends at this point.
364   int Number = MBB.getNumber();
365   if (!ScopeTops[Number] ||
366       ScopeTops[Number]->getNumber() > Header->getNumber())
367     ScopeTops[Number] = Header;
368 }
369 
370 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
371 static void PlaceLoopMarker(
372     MachineBasicBlock &MBB, MachineFunction &MF,
373     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
374     DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops,
375     const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
376   MachineLoop *Loop = MLI.getLoopFor(&MBB);
377   if (!Loop || Loop->getHeader() != &MBB)
378     return;
379 
380   // The operand of a LOOP is the first block after the loop. If the loop is the
381   // bottom of the function, insert a dummy block at the end.
382   MachineBasicBlock *Bottom = LoopBottom(Loop);
383   auto Iter = next(MachineFunction::iterator(Bottom));
384   if (Iter == MF.end()) {
385     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
386     // Give it a fake predecessor so that AsmPrinter prints its label.
387     Label->addSuccessor(Label);
388     MF.push_back(Label);
389     Iter = next(MachineFunction::iterator(Bottom));
390   }
391   MachineBasicBlock *AfterLoop = &*Iter;
392 
393   // Mark the beginning of the loop (after the end of any existing loop that
394   // ends here).
395   auto InsertPos = MBB.begin();
396   while (InsertPos != MBB.end() &&
397          InsertPos->getOpcode() == WebAssembly::END_LOOP)
398     ++InsertPos;
399   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP));
400 
401   // Mark the end of the loop.
402   MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
403                               TII.get(WebAssembly::END_LOOP));
404   LoopTops[End] = &MBB;
405 
406   assert((!ScopeTops[AfterLoop->getNumber()] ||
407           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
408          "With RPO we should visit the outer-most loop for a block first.");
409   if (!ScopeTops[AfterLoop->getNumber()])
410     ScopeTops[AfterLoop->getNumber()] = &MBB;
411 }
412 
413 static unsigned
414 GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
415          const MachineBasicBlock *MBB) {
416   unsigned Depth = 0;
417   for (auto X : reverse(Stack)) {
418     if (X == MBB)
419       break;
420     ++Depth;
421   }
422   assert(Depth < Stack.size() && "Branch destination should be in scope");
423   return Depth;
424 }
425 
426 /// Insert LOOP and BLOCK markers at appropriate places.
427 static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
428                          const WebAssemblyInstrInfo &TII,
429                          MachineDominatorTree &MDT,
430                          WebAssemblyFunctionInfo &MFI) {
431   // For each block whose label represents the end of a scope, record the block
432   // which holds the beginning of the scope. This will allow us to quickly skip
433   // over scoped regions when walking blocks. We allocate one more than the
434   // number of blocks in the function to accommodate for the possible fake block
435   // we may insert at the end.
436   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
437 
438   // For eacn LOOP_END, the corresponding LOOP.
439   DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops;
440 
441   for (auto &MBB : MF) {
442     // Place the LOOP for MBB if MBB is the header of a loop.
443     PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
444 
445     // Place the BLOCK for MBB if MBB is branched to from above.
446     PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT, MFI);
447   }
448 
449   // Now rewrite references to basic blocks to be depth immediates.
450   SmallVector<const MachineBasicBlock *, 8> Stack;
451   for (auto &MBB : reverse(MF)) {
452     for (auto &MI : reverse(MBB)) {
453       switch (MI.getOpcode()) {
454       case WebAssembly::BLOCK:
455         assert(ScopeTops[Stack.back()->getNumber()] == &MBB &&
456                "Block should be balanced");
457         Stack.pop_back();
458         break;
459       case WebAssembly::LOOP:
460         assert(Stack.back() == &MBB && "Loop top should be balanced");
461         Stack.pop_back();
462         Stack.pop_back();
463         break;
464       case WebAssembly::END_BLOCK:
465         Stack.push_back(&MBB);
466         break;
467       case WebAssembly::END_LOOP:
468         Stack.push_back(&MBB);
469         Stack.push_back(LoopTops[&MI]);
470         break;
471       default:
472         if (MI.isTerminator()) {
473           // Rewrite MBB operands to be depth immediates.
474           SmallVector<MachineOperand, 4> Ops(MI.operands());
475           while (MI.getNumOperands() > 0)
476             MI.RemoveOperand(MI.getNumOperands() - 1);
477           for (auto MO : Ops) {
478             if (MO.isMBB())
479               MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
480             MI.addOperand(MF, MO);
481           }
482         }
483         break;
484       }
485     }
486   }
487   assert(Stack.empty() && "Control flow should be balanced");
488 }
489 
490 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
491   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
492                   "********** Function: "
493                << MF.getName() << '\n');
494 
495   const auto &MLI = getAnalysis<MachineLoopInfo>();
496   auto &MDT = getAnalysis<MachineDominatorTree>();
497   // Liveness is not tracked for EXPR_STACK physreg.
498   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
499   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
500   MF.getRegInfo().invalidateLiveness();
501 
502   // RPO sorting needs all loops to be single-entry.
503   EliminateMultipleEntryLoops(MF, MLI);
504 
505   // Sort the blocks in RPO, with contiguous loops.
506   SortBlocks(MF, MLI);
507 
508   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
509   PlaceMarkers(MF, MLI, TII, MDT, MFI);
510 
511   return true;
512 }
513