1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2950a13cfSDan Gohman //
3950a13cfSDan Gohman //                     The LLVM Compiler Infrastructure
4950a13cfSDan Gohman //
5950a13cfSDan Gohman // This file is distributed under the University of Illinois Open Source
6950a13cfSDan Gohman // License. See LICENSE.TXT for details.
7950a13cfSDan Gohman //
8950a13cfSDan Gohman //===----------------------------------------------------------------------===//
9950a13cfSDan Gohman ///
10950a13cfSDan Gohman /// \file
11950a13cfSDan Gohman /// \brief This file implements a CFG stacking pass.
12950a13cfSDan Gohman ///
13950a13cfSDan Gohman /// This pass reorders the blocks in a function to put them into a reverse
14950a13cfSDan Gohman /// post-order [0], with special care to keep the order as similar as possible
15950a13cfSDan Gohman /// to the original order, and to keep loops contiguous even in the case of
16950a13cfSDan Gohman /// split backedges.
17950a13cfSDan Gohman ///
18950a13cfSDan Gohman /// Then, it inserts BLOCK and LOOP markers to mark the start of scopes, since
19950a13cfSDan Gohman /// scope boundaries serve as the labels for WebAssembly's control transfers.
20950a13cfSDan Gohman ///
21950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on
22950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry.
23950a13cfSDan Gohman ///
24950a13cfSDan Gohman /// [0] https://en.wikipedia.org/wiki/Depth-first_search#Vertex_orderings
25950a13cfSDan Gohman ///
26950a13cfSDan Gohman //===----------------------------------------------------------------------===//
27950a13cfSDan Gohman 
28950a13cfSDan Gohman #include "WebAssembly.h"
29950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
30950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
31950a13cfSDan Gohman #include "llvm/ADT/SCCIterator.h"
32*8fe7e86bSDan Gohman #include "llvm/ADT/SetVector.h"
3332807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
34950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
35950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
36950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h"
37950a13cfSDan Gohman #include "llvm/CodeGen/Passes.h"
38950a13cfSDan Gohman #include "llvm/Support/Debug.h"
39950a13cfSDan Gohman #include "llvm/Support/raw_ostream.h"
40950a13cfSDan Gohman using namespace llvm;
41950a13cfSDan Gohman 
42950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
43950a13cfSDan Gohman 
44950a13cfSDan Gohman namespace {
45950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
46950a13cfSDan Gohman   const char *getPassName() const override {
47950a13cfSDan Gohman     return "WebAssembly CFG Stackify";
48950a13cfSDan Gohman   }
49950a13cfSDan Gohman 
50950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
51950a13cfSDan Gohman     AU.setPreservesCFG();
5232807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
5332807932SDan Gohman     AU.addPreserved<MachineDominatorTree>();
54950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
55950a13cfSDan Gohman     AU.addPreserved<MachineLoopInfo>();
56950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
57950a13cfSDan Gohman   }
58950a13cfSDan Gohman 
59950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
60950a13cfSDan Gohman 
61950a13cfSDan Gohman public:
62950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
63950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
64950a13cfSDan Gohman };
65950a13cfSDan Gohman } // end anonymous namespace
66950a13cfSDan Gohman 
67950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
68950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
69950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
70950a13cfSDan Gohman }
71950a13cfSDan Gohman 
72950a13cfSDan Gohman static void EliminateMultipleEntryLoops(MachineFunction &MF,
73950a13cfSDan Gohman                                         const MachineLoopInfo &MLI) {
74950a13cfSDan Gohman   SmallPtrSet<MachineBasicBlock *, 8> InSet;
75950a13cfSDan Gohman   for (scc_iterator<MachineFunction *> I = scc_begin(&MF), E = scc_end(&MF);
76950a13cfSDan Gohman        I != E; ++I) {
77950a13cfSDan Gohman     const std::vector<MachineBasicBlock *> &CurrentSCC = *I;
78950a13cfSDan Gohman 
79950a13cfSDan Gohman     // Skip trivial SCCs.
80950a13cfSDan Gohman     if (CurrentSCC.size() == 1)
81950a13cfSDan Gohman       continue;
82950a13cfSDan Gohman 
83950a13cfSDan Gohman     InSet.insert(CurrentSCC.begin(), CurrentSCC.end());
84950a13cfSDan Gohman     MachineBasicBlock *Header = nullptr;
85950a13cfSDan Gohman     for (MachineBasicBlock *MBB : CurrentSCC) {
86950a13cfSDan Gohman       for (MachineBasicBlock *Pred : MBB->predecessors()) {
87950a13cfSDan Gohman         if (InSet.count(Pred))
88950a13cfSDan Gohman           continue;
89950a13cfSDan Gohman         if (!Header) {
90950a13cfSDan Gohman           Header = MBB;
91950a13cfSDan Gohman           break;
92950a13cfSDan Gohman         }
93950a13cfSDan Gohman         // TODO: Implement multiple-entry loops.
94950a13cfSDan Gohman         report_fatal_error("multiple-entry loops are not supported yet");
95950a13cfSDan Gohman       }
96950a13cfSDan Gohman     }
97950a13cfSDan Gohman     assert(MLI.isLoopHeader(Header));
98950a13cfSDan Gohman 
99950a13cfSDan Gohman     InSet.clear();
100950a13cfSDan Gohman   }
101950a13cfSDan Gohman }
102950a13cfSDan Gohman 
103950a13cfSDan Gohman namespace {
104950a13cfSDan Gohman /// Post-order traversal stack entry.
105950a13cfSDan Gohman struct POStackEntry {
106950a13cfSDan Gohman   MachineBasicBlock *MBB;
107950a13cfSDan Gohman   SmallVector<MachineBasicBlock *, 0> Succs;
108950a13cfSDan Gohman 
109950a13cfSDan Gohman   POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF,
110950a13cfSDan Gohman                const MachineLoopInfo &MLI);
111950a13cfSDan Gohman };
112950a13cfSDan Gohman } // end anonymous namespace
113950a13cfSDan Gohman 
11432807932SDan Gohman static bool LoopContains(const MachineLoop *Loop,
11532807932SDan Gohman                          const MachineBasicBlock *MBB) {
11632807932SDan Gohman   return Loop ? Loop->contains(MBB) : true;
11732807932SDan Gohman }
11832807932SDan Gohman 
119950a13cfSDan Gohman POStackEntry::POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF,
120950a13cfSDan Gohman                            const MachineLoopInfo &MLI)
121950a13cfSDan Gohman     : MBB(MBB), Succs(MBB->successors()) {
122950a13cfSDan Gohman   // RPO is not a unique form, since at every basic block with multiple
123950a13cfSDan Gohman   // successors, the DFS has to pick which order to visit the successors in.
124950a13cfSDan Gohman   // Sort them strategically (see below).
125950a13cfSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(MBB);
126950a13cfSDan Gohman   MachineFunction::iterator Next = next(MachineFunction::iterator(MBB));
127950a13cfSDan Gohman   MachineBasicBlock *LayoutSucc = Next == MF.end() ? nullptr : &*Next;
128950a13cfSDan Gohman   std::stable_sort(
129950a13cfSDan Gohman       Succs.begin(), Succs.end(),
130950a13cfSDan Gohman       [=, &MLI](const MachineBasicBlock *A, const MachineBasicBlock *B) {
131950a13cfSDan Gohman         if (A == B)
132950a13cfSDan Gohman           return false;
133950a13cfSDan Gohman 
134950a13cfSDan Gohman         // Keep loops contiguous by preferring the block that's in the same
135950a13cfSDan Gohman         // loop.
13632807932SDan Gohman         bool LoopContainsA = LoopContains(Loop, A);
13732807932SDan Gohman         bool LoopContainsB = LoopContains(Loop, B);
13832807932SDan Gohman         if (LoopContainsA && !LoopContainsB)
139950a13cfSDan Gohman           return true;
14032807932SDan Gohman         if (!LoopContainsA && LoopContainsB)
141950a13cfSDan Gohman           return false;
142950a13cfSDan Gohman 
143950a13cfSDan Gohman         // Minimize perturbation by preferring the block which is the immediate
144950a13cfSDan Gohman         // layout successor.
145950a13cfSDan Gohman         if (A == LayoutSucc)
146950a13cfSDan Gohman           return true;
147950a13cfSDan Gohman         if (B == LayoutSucc)
148950a13cfSDan Gohman           return false;
149950a13cfSDan Gohman 
150950a13cfSDan Gohman         // TODO: More sophisticated orderings may be profitable here.
151950a13cfSDan Gohman 
152950a13cfSDan Gohman         return false;
153950a13cfSDan Gohman       });
154950a13cfSDan Gohman }
155950a13cfSDan Gohman 
156*8fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from
157*8fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is
158*8fe7e86bSDan Gohman /// discontiguous.
159*8fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) {
160*8fe7e86bSDan Gohman   MachineBasicBlock *Bottom = Loop->getHeader();
161*8fe7e86bSDan Gohman   for (MachineBasicBlock *MBB : Loop->blocks())
162*8fe7e86bSDan Gohman     if (MBB->getNumber() > Bottom->getNumber())
163*8fe7e86bSDan Gohman       Bottom = MBB;
164*8fe7e86bSDan Gohman   return Bottom;
165*8fe7e86bSDan Gohman }
166*8fe7e86bSDan Gohman 
167950a13cfSDan Gohman /// Sort the blocks in RPO, taking special care to make sure that loops are
168950a13cfSDan Gohman /// contiguous even in the case of split backedges.
169*8fe7e86bSDan Gohman ///
170*8fe7e86bSDan Gohman /// TODO: Determine whether RPO is actually worthwhile, or whether we should
171*8fe7e86bSDan Gohman /// move to just a stable-topological-sort-based approach that would preserve
172*8fe7e86bSDan Gohman /// more of the original order.
173950a13cfSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI) {
174950a13cfSDan Gohman   // Note that we do our own RPO rather than using
175950a13cfSDan Gohman   // "llvm/ADT/PostOrderIterator.h" because we want control over the order that
176950a13cfSDan Gohman   // successors are visited in (see above). Also, we can sort the blocks in the
177950a13cfSDan Gohman   // MachineFunction as we go.
178950a13cfSDan Gohman   SmallPtrSet<MachineBasicBlock *, 16> Visited;
179950a13cfSDan Gohman   SmallVector<POStackEntry, 16> Stack;
180950a13cfSDan Gohman 
18196029f78SDan Gohman   MachineBasicBlock *EntryBlock = &*MF.begin();
18296029f78SDan Gohman   Visited.insert(EntryBlock);
18396029f78SDan Gohman   Stack.push_back(POStackEntry(EntryBlock, MF, MLI));
184950a13cfSDan Gohman 
185950a13cfSDan Gohman   for (;;) {
186950a13cfSDan Gohman     POStackEntry &Entry = Stack.back();
187950a13cfSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &Succs = Entry.Succs;
188950a13cfSDan Gohman     if (!Succs.empty()) {
189950a13cfSDan Gohman       MachineBasicBlock *Succ = Succs.pop_back_val();
190950a13cfSDan Gohman       if (Visited.insert(Succ).second)
191950a13cfSDan Gohman         Stack.push_back(POStackEntry(Succ, MF, MLI));
192950a13cfSDan Gohman       continue;
193950a13cfSDan Gohman     }
194950a13cfSDan Gohman 
195950a13cfSDan Gohman     // Put the block in its position in the MachineFunction.
196950a13cfSDan Gohman     MachineBasicBlock &MBB = *Entry.MBB;
19700406472SNico Weber     MBB.moveBefore(&*MF.begin());
198950a13cfSDan Gohman 
199950a13cfSDan Gohman     // Branch instructions may utilize a fallthrough, so update them if a
200950a13cfSDan Gohman     // fallthrough has been added or removed.
201950a13cfSDan Gohman     if (!MBB.empty() && MBB.back().isTerminator() && !MBB.back().isBranch() &&
202950a13cfSDan Gohman         !MBB.back().isBarrier())
203950a13cfSDan Gohman       report_fatal_error(
204950a13cfSDan Gohman           "Non-branch terminator with fallthrough cannot yet be rewritten");
205950a13cfSDan Gohman     if (MBB.empty() || !MBB.back().isTerminator() || MBB.back().isBranch())
206950a13cfSDan Gohman       MBB.updateTerminator();
207950a13cfSDan Gohman 
208950a13cfSDan Gohman     Stack.pop_back();
209950a13cfSDan Gohman     if (Stack.empty())
210950a13cfSDan Gohman       break;
211950a13cfSDan Gohman   }
212950a13cfSDan Gohman 
213950a13cfSDan Gohman   // Now that we've sorted the blocks in RPO, renumber them.
214950a13cfSDan Gohman   MF.RenumberBlocks();
215950a13cfSDan Gohman 
216950a13cfSDan Gohman #ifndef NDEBUG
217*8fe7e86bSDan Gohman   SmallSetVector<MachineLoop *, 8> OnStack;
218*8fe7e86bSDan Gohman 
219*8fe7e86bSDan Gohman   // Insert a sentinel representing the degenerate loop that starts at the
220*8fe7e86bSDan Gohman   // function entry block and includes the entire function as a "loop" that
221*8fe7e86bSDan Gohman   // executes once.
222*8fe7e86bSDan Gohman   OnStack.insert(nullptr);
223*8fe7e86bSDan Gohman 
224*8fe7e86bSDan Gohman   for (auto &MBB : MF) {
225*8fe7e86bSDan Gohman     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
226*8fe7e86bSDan Gohman 
227*8fe7e86bSDan Gohman     MachineLoop *Loop = MLI.getLoopFor(&MBB);
228*8fe7e86bSDan Gohman     if (Loop && &MBB == Loop->getHeader()) {
229*8fe7e86bSDan Gohman       // Loop header. The loop predecessor should be sorted above, and the other
230*8fe7e86bSDan Gohman       // predecessors should be backedges below.
231*8fe7e86bSDan Gohman       for (auto Pred : MBB.predecessors())
232*8fe7e86bSDan Gohman         assert(
233*8fe7e86bSDan Gohman             (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) &&
234*8fe7e86bSDan Gohman             "Loop header predecessors must be loop predecessors or backedges");
235*8fe7e86bSDan Gohman       assert(OnStack.insert(Loop) && "Loops should be declared at most once.");
23632807932SDan Gohman     } else {
237*8fe7e86bSDan Gohman       // Not a loop header. All predecessors should be sorted above.
238950a13cfSDan Gohman       for (auto Pred : MBB.predecessors())
239950a13cfSDan Gohman         assert(Pred->getNumber() < MBB.getNumber() &&
240*8fe7e86bSDan Gohman                "Non-loop-header predecessors should be topologically sorted");
241*8fe7e86bSDan Gohman       assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
242*8fe7e86bSDan Gohman              "Blocks must be nested in their loops");
243950a13cfSDan Gohman     }
244*8fe7e86bSDan Gohman     while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back()))
245*8fe7e86bSDan Gohman       OnStack.pop_back();
246*8fe7e86bSDan Gohman   }
247*8fe7e86bSDan Gohman   assert(OnStack.pop_back_val() == nullptr &&
248*8fe7e86bSDan Gohman          "The function entry block shouldn't actually be a loop header");
249*8fe7e86bSDan Gohman   assert(OnStack.empty() &&
250*8fe7e86bSDan Gohman          "Control flow stack pushes and pops should be balanced.");
251950a13cfSDan Gohman #endif
252950a13cfSDan Gohman }
253950a13cfSDan Gohman 
25432807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
255*8fe7e86bSDan Gohman static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF,
256*8fe7e86bSDan Gohman                              SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
25732807932SDan Gohman                              const WebAssemblyInstrInfo &TII,
258*8fe7e86bSDan Gohman                              const MachineLoopInfo &MLI,
259*8fe7e86bSDan Gohman                              MachineDominatorTree &MDT) {
260*8fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
261*8fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
262*8fe7e86bSDan Gohman   // which reduces overall stack height.
26332807932SDan Gohman   MachineBasicBlock *Header = nullptr;
26432807932SDan Gohman   bool IsBranchedTo = false;
26532807932SDan Gohman   int MBBNumber = MBB.getNumber();
26632807932SDan Gohman   for (MachineBasicBlock *Pred : MBB.predecessors())
26732807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
26832807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
26932807932SDan Gohman       if (!Pred->isLayoutSuccessor(&MBB) ||
27032807932SDan Gohman           !(Pred->empty() || !Pred->back().isBarrier()))
27132807932SDan Gohman         IsBranchedTo = true;
27232807932SDan Gohman     }
27332807932SDan Gohman   if (!Header)
27432807932SDan Gohman     return;
27532807932SDan Gohman   if (!IsBranchedTo)
27632807932SDan Gohman     return;
27732807932SDan Gohman 
278*8fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
279*8fe7e86bSDan Gohman   MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB));
280*8fe7e86bSDan Gohman 
281*8fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
282*8fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
283*8fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
284*8fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
285*8fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
286*8fe7e86bSDan Gohman         // Skip over an intervening scope.
287*8fe7e86bSDan Gohman         I = next(MachineFunction::iterator(ScopeTop));
288*8fe7e86bSDan Gohman       } else {
289*8fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
290*8fe7e86bSDan Gohman         Header = ScopeTop;
291*8fe7e86bSDan Gohman         break;
292*8fe7e86bSDan Gohman       }
293*8fe7e86bSDan Gohman     }
294*8fe7e86bSDan Gohman   }
295*8fe7e86bSDan Gohman 
296*8fe7e86bSDan Gohman   // If there's a loop which ends just before MBB which contains Header, we can
297*8fe7e86bSDan Gohman   // reuse its label instead of inserting a new BLOCK.
298*8fe7e86bSDan Gohman   for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred);
299*8fe7e86bSDan Gohman        Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop())
300*8fe7e86bSDan Gohman     if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header))
301*8fe7e86bSDan Gohman       return;
302*8fe7e86bSDan Gohman 
303*8fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
30432807932SDan Gohman   MachineBasicBlock::iterator InsertPos;
30532807932SDan Gohman   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
306*8fe7e86bSDan Gohman   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
307*8fe7e86bSDan Gohman     // Header is the header of a loop that does not lexically contain MBB, so
308*8fe7e86bSDan Gohman     // the BLOCK needs to be above the LOOP.
30932807932SDan Gohman     InsertPos = Header->begin();
31032807932SDan Gohman   } else {
311*8fe7e86bSDan Gohman     // Otherwise, insert the BLOCK as late in Header as we can, but before any
312*8fe7e86bSDan Gohman     // existing BLOCKs.
31332807932SDan Gohman     InsertPos = Header->getFirstTerminator();
31432807932SDan Gohman     while (InsertPos != Header->begin() &&
315*8fe7e86bSDan Gohman            prev(InsertPos)->getOpcode() == WebAssembly::BLOCK)
31632807932SDan Gohman       --InsertPos;
31732807932SDan Gohman   }
31832807932SDan Gohman 
319*8fe7e86bSDan Gohman   // Add the BLOCK.
32032807932SDan Gohman   BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK))
32132807932SDan Gohman       .addMBB(&MBB);
322*8fe7e86bSDan Gohman 
323*8fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
324*8fe7e86bSDan Gohman   int Number = MBB.getNumber();
325*8fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
326*8fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
327*8fe7e86bSDan Gohman     ScopeTops[Number] = Header;
328950a13cfSDan Gohman }
329950a13cfSDan Gohman 
330*8fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
331*8fe7e86bSDan Gohman static void PlaceLoopMarker(MachineBasicBlock &MBB, MachineFunction &MF,
332*8fe7e86bSDan Gohman                             SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
33332807932SDan Gohman                             const WebAssemblyInstrInfo &TII,
334*8fe7e86bSDan Gohman                             const MachineLoopInfo &MLI) {
335*8fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
336*8fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
337*8fe7e86bSDan Gohman     return;
338*8fe7e86bSDan Gohman 
339*8fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
340*8fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
341*8fe7e86bSDan Gohman   MachineBasicBlock *Bottom = LoopBottom(Loop);
342e3e4a5ffSDan Gohman   auto Iter = next(MachineFunction::iterator(Bottom));
343e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
344f6857223SDan Gohman     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
345f6857223SDan Gohman     // Give it a fake predecessor so that AsmPrinter prints its label.
346f6857223SDan Gohman     Label->addSuccessor(Label);
347f6857223SDan Gohman     MF.push_back(Label);
348e3e4a5ffSDan Gohman     Iter = next(MachineFunction::iterator(Bottom));
349e3e4a5ffSDan Gohman   }
350*8fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
351950a13cfSDan Gohman   BuildMI(MBB, MBB.begin(), DebugLoc(), TII.get(WebAssembly::LOOP))
352*8fe7e86bSDan Gohman       .addMBB(AfterLoop);
353f6857223SDan Gohman 
354*8fe7e86bSDan Gohman   // Emit a special no-op telling the asm printer that we need a label to close
355*8fe7e86bSDan Gohman   // the loop scope, even though the destination is only reachable by
356*8fe7e86bSDan Gohman   // fallthrough.
357f6857223SDan Gohman   if (!Bottom->back().isBarrier())
358*8fe7e86bSDan Gohman     BuildMI(*Bottom, Bottom->end(), DebugLoc(), TII.get(WebAssembly::LOOP_END));
359*8fe7e86bSDan Gohman 
360*8fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
361*8fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
362*8fe7e86bSDan Gohman          "With RPO we should visit the outer-most loop for a block first.");
363*8fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
364*8fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
365e3e4a5ffSDan Gohman }
366950a13cfSDan Gohman 
367*8fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places.
368*8fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
369*8fe7e86bSDan Gohman                          const WebAssemblyInstrInfo &TII,
370*8fe7e86bSDan Gohman                          MachineDominatorTree &MDT) {
371*8fe7e86bSDan Gohman   // For each block whose label represents the end of a scope, record the block
372*8fe7e86bSDan Gohman   // which holds the beginning of the scope. This will allow us to quickly skip
373*8fe7e86bSDan Gohman   // over scoped regions when walking blocks. We allocate one more than the
374*8fe7e86bSDan Gohman   // number of blocks in the function to accommodate for the possible fake block
375*8fe7e86bSDan Gohman   // we may insert at the end.
376*8fe7e86bSDan Gohman   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
377*8fe7e86bSDan Gohman 
378*8fe7e86bSDan Gohman   for (auto &MBB : MF) {
379*8fe7e86bSDan Gohman     // Place the LOOP for MBB if MBB is the header of a loop.
380*8fe7e86bSDan Gohman     PlaceLoopMarker(MBB, MF, ScopeTops, TII, MLI);
381*8fe7e86bSDan Gohman 
38232807932SDan Gohman     // Place the BLOCK for MBB if MBB is branched to from above.
383*8fe7e86bSDan Gohman     PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT);
384950a13cfSDan Gohman   }
385950a13cfSDan Gohman }
386950a13cfSDan Gohman 
38732807932SDan Gohman #ifndef NDEBUG
38832807932SDan Gohman static bool
38932807932SDan Gohman IsOnStack(const SmallVectorImpl<std::pair<MachineBasicBlock *, bool>> &Stack,
39032807932SDan Gohman           const MachineBasicBlock *MBB) {
39132807932SDan Gohman   for (const auto &Pair : Stack)
39232807932SDan Gohman     if (Pair.first == MBB)
39332807932SDan Gohman       return true;
39432807932SDan Gohman   return false;
39532807932SDan Gohman }
39632807932SDan Gohman #endif
39732807932SDan Gohman 
398950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
399950a13cfSDan Gohman   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
400950a13cfSDan Gohman                   "********** Function: "
401950a13cfSDan Gohman                << MF.getName() << '\n');
402950a13cfSDan Gohman 
403950a13cfSDan Gohman   const auto &MLI = getAnalysis<MachineLoopInfo>();
40432807932SDan Gohman   auto &MDT = getAnalysis<MachineDominatorTree>();
405950a13cfSDan Gohman   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
406950a13cfSDan Gohman 
407950a13cfSDan Gohman   // RPO sorting needs all loops to be single-entry.
408950a13cfSDan Gohman   EliminateMultipleEntryLoops(MF, MLI);
409950a13cfSDan Gohman 
410950a13cfSDan Gohman   // Sort the blocks in RPO, with contiguous loops.
411950a13cfSDan Gohman   SortBlocks(MF, MLI);
412950a13cfSDan Gohman 
413950a13cfSDan Gohman   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
41432807932SDan Gohman   PlaceMarkers(MF, MLI, TII, MDT);
41532807932SDan Gohman 
41632807932SDan Gohman #ifndef NDEBUG
41753d13997SDan Gohman   // Verify that block and loop beginnings and endings are in LIFO order, and
41832807932SDan Gohman   // that all references to blocks are to blocks on the stack at the point of
41932807932SDan Gohman   // the reference.
42032807932SDan Gohman   SmallVector<std::pair<MachineBasicBlock *, bool>, 0> Stack;
42132807932SDan Gohman   for (auto &MBB : MF) {
42232807932SDan Gohman     while (!Stack.empty() && Stack.back().first == &MBB)
42332807932SDan Gohman       if (Stack.back().second) {
42432807932SDan Gohman         assert(Stack.size() >= 2);
42532807932SDan Gohman         Stack.pop_back();
42632807932SDan Gohman         Stack.pop_back();
42732807932SDan Gohman       } else {
42832807932SDan Gohman         assert(Stack.size() >= 1);
42932807932SDan Gohman         Stack.pop_back();
43032807932SDan Gohman       }
43132807932SDan Gohman     for (auto &MI : MBB)
43232807932SDan Gohman       switch (MI.getOpcode()) {
43332807932SDan Gohman       case WebAssembly::LOOP:
43432807932SDan Gohman         Stack.push_back(std::make_pair(&MBB, false));
43532807932SDan Gohman         Stack.push_back(std::make_pair(MI.getOperand(0).getMBB(), true));
43632807932SDan Gohman         break;
43732807932SDan Gohman       case WebAssembly::BLOCK:
43832807932SDan Gohman         Stack.push_back(std::make_pair(MI.getOperand(0).getMBB(), false));
43932807932SDan Gohman         break;
44032807932SDan Gohman       default:
441*8fe7e86bSDan Gohman         // Verify that all referenced blocks are in scope. A reference to a
442*8fe7e86bSDan Gohman         // block with a negative number is invalid, but can happen with inline
443*8fe7e86bSDan Gohman         // asm, so we shouldn't assert on it, but instead let CodeGen properly
444*8fe7e86bSDan Gohman         // fail on it.
44532807932SDan Gohman         for (const MachineOperand &MO : MI.explicit_operands())
446*8fe7e86bSDan Gohman           if (MO.isMBB() && MO.getMBB()->getNumber() >= 0)
44732807932SDan Gohman             assert(IsOnStack(Stack, MO.getMBB()));
44832807932SDan Gohman         break;
44932807932SDan Gohman       }
45032807932SDan Gohman   }
45132807932SDan Gohman   assert(Stack.empty());
45232807932SDan Gohman #endif
453950a13cfSDan Gohman 
454950a13cfSDan Gohman   return true;
455950a13cfSDan Gohman }
456