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"
328fe7e86bSDan 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 
1568fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from
1578fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is
1588fe7e86bSDan Gohman /// discontiguous.
1598fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) {
1608fe7e86bSDan Gohman   MachineBasicBlock *Bottom = Loop->getHeader();
1618fe7e86bSDan Gohman   for (MachineBasicBlock *MBB : Loop->blocks())
1628fe7e86bSDan Gohman     if (MBB->getNumber() > Bottom->getNumber())
1638fe7e86bSDan Gohman       Bottom = MBB;
1648fe7e86bSDan Gohman   return Bottom;
1658fe7e86bSDan Gohman }
1668fe7e86bSDan 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.
1698fe7e86bSDan Gohman ///
1708fe7e86bSDan Gohman /// TODO: Determine whether RPO is actually worthwhile, or whether we should
1718fe7e86bSDan Gohman /// move to just a stable-topological-sort-based approach that would preserve
1728fe7e86bSDan 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
2178fe7e86bSDan Gohman   SmallSetVector<MachineLoop *, 8> OnStack;
2188fe7e86bSDan Gohman 
2198fe7e86bSDan Gohman   // Insert a sentinel representing the degenerate loop that starts at the
2208fe7e86bSDan Gohman   // function entry block and includes the entire function as a "loop" that
2218fe7e86bSDan Gohman   // executes once.
2228fe7e86bSDan Gohman   OnStack.insert(nullptr);
2238fe7e86bSDan Gohman 
2248fe7e86bSDan Gohman   for (auto &MBB : MF) {
2258fe7e86bSDan Gohman     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
2268fe7e86bSDan Gohman 
2278fe7e86bSDan Gohman     MachineLoop *Loop = MLI.getLoopFor(&MBB);
2288fe7e86bSDan Gohman     if (Loop && &MBB == Loop->getHeader()) {
2298fe7e86bSDan Gohman       // Loop header. The loop predecessor should be sorted above, and the other
2308fe7e86bSDan Gohman       // predecessors should be backedges below.
2318fe7e86bSDan Gohman       for (auto Pred : MBB.predecessors())
2328fe7e86bSDan Gohman         assert(
2338fe7e86bSDan Gohman             (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) &&
2348fe7e86bSDan Gohman             "Loop header predecessors must be loop predecessors or backedges");
2358fe7e86bSDan Gohman       assert(OnStack.insert(Loop) && "Loops should be declared at most once.");
23632807932SDan Gohman     } else {
2378fe7e86bSDan 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() &&
2408fe7e86bSDan Gohman                "Non-loop-header predecessors should be topologically sorted");
2418fe7e86bSDan Gohman       assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
2428fe7e86bSDan Gohman              "Blocks must be nested in their loops");
243950a13cfSDan Gohman     }
2448fe7e86bSDan Gohman     while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back()))
2458fe7e86bSDan Gohman       OnStack.pop_back();
2468fe7e86bSDan Gohman   }
2478fe7e86bSDan Gohman   assert(OnStack.pop_back_val() == nullptr &&
2488fe7e86bSDan Gohman          "The function entry block shouldn't actually be a loop header");
2498fe7e86bSDan Gohman   assert(OnStack.empty() &&
2508fe7e86bSDan Gohman          "Control flow stack pushes and pops should be balanced.");
251950a13cfSDan Gohman #endif
252950a13cfSDan Gohman }
253950a13cfSDan Gohman 
254*b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
255*b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
256*b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
257*b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
258*b3aa1ecaSDan Gohman /// explicit mentions.
259*b3aa1ecaSDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, MachineBasicBlock *MBB) {
260*b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
261*b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
262*b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
263*b3aa1ecaSDan Gohman         return true;
264*b3aa1ecaSDan Gohman   return false;
265*b3aa1ecaSDan Gohman }
266*b3aa1ecaSDan Gohman 
26732807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
2688fe7e86bSDan Gohman static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF,
2698fe7e86bSDan Gohman                              SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
27032807932SDan Gohman                              const WebAssemblyInstrInfo &TII,
2718fe7e86bSDan Gohman                              const MachineLoopInfo &MLI,
2728fe7e86bSDan Gohman                              MachineDominatorTree &MDT) {
2738fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2748fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2758fe7e86bSDan Gohman   // which reduces overall stack height.
27632807932SDan Gohman   MachineBasicBlock *Header = nullptr;
27732807932SDan Gohman   bool IsBranchedTo = false;
27832807932SDan Gohman   int MBBNumber = MBB.getNumber();
27932807932SDan Gohman   for (MachineBasicBlock *Pred : MBB.predecessors())
28032807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
28132807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
282*b3aa1ecaSDan Gohman       if (ExplicitlyBranchesTo(Pred, &MBB))
28332807932SDan Gohman         IsBranchedTo = true;
28432807932SDan Gohman     }
28532807932SDan Gohman   if (!Header)
28632807932SDan Gohman     return;
28732807932SDan Gohman   if (!IsBranchedTo)
28832807932SDan Gohman     return;
28932807932SDan Gohman 
2908fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2918fe7e86bSDan Gohman   MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB));
2928fe7e86bSDan Gohman 
2938fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2948fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2958fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2968fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2978fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2988fe7e86bSDan Gohman         // Skip over an intervening scope.
2998fe7e86bSDan Gohman         I = next(MachineFunction::iterator(ScopeTop));
3008fe7e86bSDan Gohman       } else {
3018fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
3028fe7e86bSDan Gohman         Header = ScopeTop;
3038fe7e86bSDan Gohman         break;
3048fe7e86bSDan Gohman       }
3058fe7e86bSDan Gohman     }
3068fe7e86bSDan Gohman   }
3078fe7e86bSDan Gohman 
3088fe7e86bSDan Gohman   // If there's a loop which ends just before MBB which contains Header, we can
3098fe7e86bSDan Gohman   // reuse its label instead of inserting a new BLOCK.
3108fe7e86bSDan Gohman   for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred);
3118fe7e86bSDan Gohman        Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop())
3128fe7e86bSDan Gohman     if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header))
3138fe7e86bSDan Gohman       return;
3148fe7e86bSDan Gohman 
3158fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
31632807932SDan Gohman   MachineBasicBlock::iterator InsertPos;
31732807932SDan Gohman   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
3188fe7e86bSDan Gohman   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
3198fe7e86bSDan Gohman     // Header is the header of a loop that does not lexically contain MBB, so
3208fe7e86bSDan Gohman     // the BLOCK needs to be above the LOOP.
32132807932SDan Gohman     InsertPos = Header->begin();
32232807932SDan Gohman   } else {
3238fe7e86bSDan Gohman     // Otherwise, insert the BLOCK as late in Header as we can, but before any
3248fe7e86bSDan Gohman     // existing BLOCKs.
32532807932SDan Gohman     InsertPos = Header->getFirstTerminator();
32632807932SDan Gohman     while (InsertPos != Header->begin() &&
3278fe7e86bSDan Gohman            prev(InsertPos)->getOpcode() == WebAssembly::BLOCK)
32832807932SDan Gohman       --InsertPos;
32932807932SDan Gohman   }
33032807932SDan Gohman 
3318fe7e86bSDan Gohman   // Add the BLOCK.
33232807932SDan Gohman   BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK))
33332807932SDan Gohman       .addMBB(&MBB);
3348fe7e86bSDan Gohman 
3358fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3368fe7e86bSDan Gohman   int Number = MBB.getNumber();
3378fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
3388fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
3398fe7e86bSDan Gohman     ScopeTops[Number] = Header;
340950a13cfSDan Gohman }
341950a13cfSDan Gohman 
3428fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
3438fe7e86bSDan Gohman static void PlaceLoopMarker(MachineBasicBlock &MBB, MachineFunction &MF,
3448fe7e86bSDan Gohman                             SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
34532807932SDan Gohman                             const WebAssemblyInstrInfo &TII,
3468fe7e86bSDan Gohman                             const MachineLoopInfo &MLI) {
3478fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3488fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3498fe7e86bSDan Gohman     return;
3508fe7e86bSDan Gohman 
3518fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
3528fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
3538fe7e86bSDan Gohman   MachineBasicBlock *Bottom = LoopBottom(Loop);
354e3e4a5ffSDan Gohman   auto Iter = next(MachineFunction::iterator(Bottom));
355e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
356f6857223SDan Gohman     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
357f6857223SDan Gohman     // Give it a fake predecessor so that AsmPrinter prints its label.
358f6857223SDan Gohman     Label->addSuccessor(Label);
359f6857223SDan Gohman     MF.push_back(Label);
360e3e4a5ffSDan Gohman     Iter = next(MachineFunction::iterator(Bottom));
361e3e4a5ffSDan Gohman   }
3628fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
363950a13cfSDan Gohman   BuildMI(MBB, MBB.begin(), DebugLoc(), TII.get(WebAssembly::LOOP))
3648fe7e86bSDan Gohman       .addMBB(AfterLoop);
365f6857223SDan Gohman 
3668fe7e86bSDan Gohman   // Emit a special no-op telling the asm printer that we need a label to close
3678fe7e86bSDan Gohman   // the loop scope, even though the destination is only reachable by
3688fe7e86bSDan Gohman   // fallthrough.
369f6857223SDan Gohman   if (!Bottom->back().isBarrier())
3708fe7e86bSDan Gohman     BuildMI(*Bottom, Bottom->end(), DebugLoc(), TII.get(WebAssembly::LOOP_END));
3718fe7e86bSDan Gohman 
3728fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
3738fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
3748fe7e86bSDan Gohman          "With RPO we should visit the outer-most loop for a block first.");
3758fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
3768fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
377e3e4a5ffSDan Gohman }
378950a13cfSDan Gohman 
3798fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places.
3808fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
3818fe7e86bSDan Gohman                          const WebAssemblyInstrInfo &TII,
3828fe7e86bSDan Gohman                          MachineDominatorTree &MDT) {
3838fe7e86bSDan Gohman   // For each block whose label represents the end of a scope, record the block
3848fe7e86bSDan Gohman   // which holds the beginning of the scope. This will allow us to quickly skip
3858fe7e86bSDan Gohman   // over scoped regions when walking blocks. We allocate one more than the
3868fe7e86bSDan Gohman   // number of blocks in the function to accommodate for the possible fake block
3878fe7e86bSDan Gohman   // we may insert at the end.
3888fe7e86bSDan Gohman   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
3898fe7e86bSDan Gohman 
3908fe7e86bSDan Gohman   for (auto &MBB : MF) {
3918fe7e86bSDan Gohman     // Place the LOOP for MBB if MBB is the header of a loop.
3928fe7e86bSDan Gohman     PlaceLoopMarker(MBB, MF, ScopeTops, TII, MLI);
3938fe7e86bSDan Gohman 
39432807932SDan Gohman     // Place the BLOCK for MBB if MBB is branched to from above.
3958fe7e86bSDan Gohman     PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT);
396950a13cfSDan Gohman   }
397950a13cfSDan Gohman }
398950a13cfSDan Gohman 
39932807932SDan Gohman #ifndef NDEBUG
40032807932SDan Gohman static bool
40132807932SDan Gohman IsOnStack(const SmallVectorImpl<std::pair<MachineBasicBlock *, bool>> &Stack,
40232807932SDan Gohman           const MachineBasicBlock *MBB) {
40332807932SDan Gohman   for (const auto &Pair : Stack)
40432807932SDan Gohman     if (Pair.first == MBB)
40532807932SDan Gohman       return true;
40632807932SDan Gohman   return false;
40732807932SDan Gohman }
40832807932SDan Gohman #endif
40932807932SDan Gohman 
410950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
411950a13cfSDan Gohman   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
412950a13cfSDan Gohman                   "********** Function: "
413950a13cfSDan Gohman                << MF.getName() << '\n');
414950a13cfSDan Gohman 
415950a13cfSDan Gohman   const auto &MLI = getAnalysis<MachineLoopInfo>();
41632807932SDan Gohman   auto &MDT = getAnalysis<MachineDominatorTree>();
417950a13cfSDan Gohman   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
418950a13cfSDan Gohman 
419950a13cfSDan Gohman   // RPO sorting needs all loops to be single-entry.
420950a13cfSDan Gohman   EliminateMultipleEntryLoops(MF, MLI);
421950a13cfSDan Gohman 
422950a13cfSDan Gohman   // Sort the blocks in RPO, with contiguous loops.
423950a13cfSDan Gohman   SortBlocks(MF, MLI);
424950a13cfSDan Gohman 
425950a13cfSDan Gohman   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
42632807932SDan Gohman   PlaceMarkers(MF, MLI, TII, MDT);
42732807932SDan Gohman 
42832807932SDan Gohman #ifndef NDEBUG
42953d13997SDan Gohman   // Verify that block and loop beginnings and endings are in LIFO order, and
43032807932SDan Gohman   // that all references to blocks are to blocks on the stack at the point of
43132807932SDan Gohman   // the reference.
43232807932SDan Gohman   SmallVector<std::pair<MachineBasicBlock *, bool>, 0> Stack;
43332807932SDan Gohman   for (auto &MBB : MF) {
43432807932SDan Gohman     while (!Stack.empty() && Stack.back().first == &MBB)
43532807932SDan Gohman       if (Stack.back().second) {
43632807932SDan Gohman         assert(Stack.size() >= 2);
43732807932SDan Gohman         Stack.pop_back();
43832807932SDan Gohman         Stack.pop_back();
43932807932SDan Gohman       } else {
44032807932SDan Gohman         assert(Stack.size() >= 1);
44132807932SDan Gohman         Stack.pop_back();
44232807932SDan Gohman       }
44332807932SDan Gohman     for (auto &MI : MBB)
44432807932SDan Gohman       switch (MI.getOpcode()) {
44532807932SDan Gohman       case WebAssembly::LOOP:
44632807932SDan Gohman         Stack.push_back(std::make_pair(&MBB, false));
44732807932SDan Gohman         Stack.push_back(std::make_pair(MI.getOperand(0).getMBB(), true));
44832807932SDan Gohman         break;
44932807932SDan Gohman       case WebAssembly::BLOCK:
45032807932SDan Gohman         Stack.push_back(std::make_pair(MI.getOperand(0).getMBB(), false));
45132807932SDan Gohman         break;
45232807932SDan Gohman       default:
4538fe7e86bSDan Gohman         // Verify that all referenced blocks are in scope. A reference to a
4548fe7e86bSDan Gohman         // block with a negative number is invalid, but can happen with inline
4558fe7e86bSDan Gohman         // asm, so we shouldn't assert on it, but instead let CodeGen properly
4568fe7e86bSDan Gohman         // fail on it.
45732807932SDan Gohman         for (const MachineOperand &MO : MI.explicit_operands())
4588fe7e86bSDan Gohman           if (MO.isMBB() && MO.getMBB()->getNumber() >= 0)
45932807932SDan Gohman             assert(IsOnStack(Stack, MO.getMBB()));
46032807932SDan Gohman         break;
46132807932SDan Gohman       }
46232807932SDan Gohman   }
46332807932SDan Gohman   assert(Stack.empty());
46432807932SDan Gohman #endif
465950a13cfSDan Gohman 
466950a13cfSDan Gohman   return true;
467950a13cfSDan Gohman }
468