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"
30ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
31950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
32950a13cfSDan Gohman #include "llvm/ADT/SCCIterator.h"
338fe7e86bSDan Gohman #include "llvm/ADT/SetVector.h"
3432807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
35950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
36950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
37950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h"
389c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.h"
39950a13cfSDan Gohman #include "llvm/CodeGen/Passes.h"
40950a13cfSDan Gohman #include "llvm/Support/Debug.h"
41950a13cfSDan Gohman #include "llvm/Support/raw_ostream.h"
42950a13cfSDan Gohman using namespace llvm;
43950a13cfSDan Gohman 
44950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
45950a13cfSDan Gohman 
46950a13cfSDan Gohman namespace {
47950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
48950a13cfSDan Gohman   const char *getPassName() const override {
49950a13cfSDan Gohman     return "WebAssembly CFG Stackify";
50950a13cfSDan Gohman   }
51950a13cfSDan Gohman 
52950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
53950a13cfSDan Gohman     AU.setPreservesCFG();
5432807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
5532807932SDan Gohman     AU.addPreserved<MachineDominatorTree>();
56950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
57950a13cfSDan Gohman     AU.addPreserved<MachineLoopInfo>();
58950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
59950a13cfSDan Gohman   }
60950a13cfSDan Gohman 
61950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
62950a13cfSDan Gohman 
63950a13cfSDan Gohman public:
64950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
65950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
66950a13cfSDan Gohman };
67950a13cfSDan Gohman } // end anonymous namespace
68950a13cfSDan Gohman 
69950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
70950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
71950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
72950a13cfSDan Gohman }
73950a13cfSDan Gohman 
74950a13cfSDan Gohman static void EliminateMultipleEntryLoops(MachineFunction &MF,
75950a13cfSDan Gohman                                         const MachineLoopInfo &MLI) {
76950a13cfSDan Gohman   SmallPtrSet<MachineBasicBlock *, 8> InSet;
77950a13cfSDan Gohman   for (scc_iterator<MachineFunction *> I = scc_begin(&MF), E = scc_end(&MF);
78950a13cfSDan Gohman        I != E; ++I) {
79950a13cfSDan Gohman     const std::vector<MachineBasicBlock *> &CurrentSCC = *I;
80950a13cfSDan Gohman 
81950a13cfSDan Gohman     // Skip trivial SCCs.
82950a13cfSDan Gohman     if (CurrentSCC.size() == 1)
83950a13cfSDan Gohman       continue;
84950a13cfSDan Gohman 
85950a13cfSDan Gohman     InSet.insert(CurrentSCC.begin(), CurrentSCC.end());
86950a13cfSDan Gohman     MachineBasicBlock *Header = nullptr;
87950a13cfSDan Gohman     for (MachineBasicBlock *MBB : CurrentSCC) {
88950a13cfSDan Gohman       for (MachineBasicBlock *Pred : MBB->predecessors()) {
89950a13cfSDan Gohman         if (InSet.count(Pred))
90950a13cfSDan Gohman           continue;
91950a13cfSDan Gohman         if (!Header) {
92950a13cfSDan Gohman           Header = MBB;
93950a13cfSDan Gohman           break;
94950a13cfSDan Gohman         }
95950a13cfSDan Gohman         // TODO: Implement multiple-entry loops.
96950a13cfSDan Gohman         report_fatal_error("multiple-entry loops are not supported yet");
97950a13cfSDan Gohman       }
98950a13cfSDan Gohman     }
99950a13cfSDan Gohman     assert(MLI.isLoopHeader(Header));
100950a13cfSDan Gohman 
101950a13cfSDan Gohman     InSet.clear();
102950a13cfSDan Gohman   }
103950a13cfSDan Gohman }
104950a13cfSDan Gohman 
105950a13cfSDan Gohman namespace {
106950a13cfSDan Gohman /// Post-order traversal stack entry.
107950a13cfSDan Gohman struct POStackEntry {
108950a13cfSDan Gohman   MachineBasicBlock *MBB;
109950a13cfSDan Gohman   SmallVector<MachineBasicBlock *, 0> Succs;
110950a13cfSDan Gohman 
111950a13cfSDan Gohman   POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF,
112950a13cfSDan Gohman                const MachineLoopInfo &MLI);
113950a13cfSDan Gohman };
114950a13cfSDan Gohman } // end anonymous namespace
115950a13cfSDan Gohman 
11632807932SDan Gohman static bool LoopContains(const MachineLoop *Loop,
11732807932SDan Gohman                          const MachineBasicBlock *MBB) {
11832807932SDan Gohman   return Loop ? Loop->contains(MBB) : true;
11932807932SDan Gohman }
12032807932SDan Gohman 
121950a13cfSDan Gohman POStackEntry::POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF,
122950a13cfSDan Gohman                            const MachineLoopInfo &MLI)
123950a13cfSDan Gohman     : MBB(MBB), Succs(MBB->successors()) {
124950a13cfSDan Gohman   // RPO is not a unique form, since at every basic block with multiple
125950a13cfSDan Gohman   // successors, the DFS has to pick which order to visit the successors in.
126950a13cfSDan Gohman   // Sort them strategically (see below).
127950a13cfSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(MBB);
128950a13cfSDan Gohman   MachineFunction::iterator Next = next(MachineFunction::iterator(MBB));
129950a13cfSDan Gohman   MachineBasicBlock *LayoutSucc = Next == MF.end() ? nullptr : &*Next;
130950a13cfSDan Gohman   std::stable_sort(
131950a13cfSDan Gohman       Succs.begin(), Succs.end(),
132950a13cfSDan Gohman       [=, &MLI](const MachineBasicBlock *A, const MachineBasicBlock *B) {
133950a13cfSDan Gohman         if (A == B)
134950a13cfSDan Gohman           return false;
135950a13cfSDan Gohman 
136950a13cfSDan Gohman         // Keep loops contiguous by preferring the block that's in the same
137950a13cfSDan Gohman         // loop.
13832807932SDan Gohman         bool LoopContainsA = LoopContains(Loop, A);
13932807932SDan Gohman         bool LoopContainsB = LoopContains(Loop, B);
14032807932SDan Gohman         if (LoopContainsA && !LoopContainsB)
141950a13cfSDan Gohman           return true;
14232807932SDan Gohman         if (!LoopContainsA && LoopContainsB)
143950a13cfSDan Gohman           return false;
144950a13cfSDan Gohman 
145950a13cfSDan Gohman         // Minimize perturbation by preferring the block which is the immediate
146950a13cfSDan Gohman         // layout successor.
147950a13cfSDan Gohman         if (A == LayoutSucc)
148950a13cfSDan Gohman           return true;
149950a13cfSDan Gohman         if (B == LayoutSucc)
150950a13cfSDan Gohman           return false;
151950a13cfSDan Gohman 
152950a13cfSDan Gohman         // TODO: More sophisticated orderings may be profitable here.
153950a13cfSDan Gohman 
154950a13cfSDan Gohman         return false;
155950a13cfSDan Gohman       });
156950a13cfSDan Gohman }
157950a13cfSDan Gohman 
1588fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from
1598fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is
1608fe7e86bSDan Gohman /// discontiguous.
1618fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) {
1628fe7e86bSDan Gohman   MachineBasicBlock *Bottom = Loop->getHeader();
1638fe7e86bSDan Gohman   for (MachineBasicBlock *MBB : Loop->blocks())
1648fe7e86bSDan Gohman     if (MBB->getNumber() > Bottom->getNumber())
1658fe7e86bSDan Gohman       Bottom = MBB;
1668fe7e86bSDan Gohman   return Bottom;
1678fe7e86bSDan Gohman }
1688fe7e86bSDan Gohman 
169950a13cfSDan Gohman /// Sort the blocks in RPO, taking special care to make sure that loops are
170950a13cfSDan Gohman /// contiguous even in the case of split backedges.
1718fe7e86bSDan Gohman ///
1728fe7e86bSDan Gohman /// TODO: Determine whether RPO is actually worthwhile, or whether we should
1738fe7e86bSDan Gohman /// move to just a stable-topological-sort-based approach that would preserve
1748fe7e86bSDan Gohman /// more of the original order.
175950a13cfSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI) {
176950a13cfSDan Gohman   // Note that we do our own RPO rather than using
177950a13cfSDan Gohman   // "llvm/ADT/PostOrderIterator.h" because we want control over the order that
178950a13cfSDan Gohman   // successors are visited in (see above). Also, we can sort the blocks in the
179950a13cfSDan Gohman   // MachineFunction as we go.
180950a13cfSDan Gohman   SmallPtrSet<MachineBasicBlock *, 16> Visited;
181950a13cfSDan Gohman   SmallVector<POStackEntry, 16> Stack;
182950a13cfSDan Gohman 
18396029f78SDan Gohman   MachineBasicBlock *EntryBlock = &*MF.begin();
18496029f78SDan Gohman   Visited.insert(EntryBlock);
18596029f78SDan Gohman   Stack.push_back(POStackEntry(EntryBlock, MF, MLI));
186950a13cfSDan Gohman 
187950a13cfSDan Gohman   for (;;) {
188950a13cfSDan Gohman     POStackEntry &Entry = Stack.back();
189950a13cfSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &Succs = Entry.Succs;
190950a13cfSDan Gohman     if (!Succs.empty()) {
191950a13cfSDan Gohman       MachineBasicBlock *Succ = Succs.pop_back_val();
192950a13cfSDan Gohman       if (Visited.insert(Succ).second)
193950a13cfSDan Gohman         Stack.push_back(POStackEntry(Succ, MF, MLI));
194950a13cfSDan Gohman       continue;
195950a13cfSDan Gohman     }
196950a13cfSDan Gohman 
197950a13cfSDan Gohman     // Put the block in its position in the MachineFunction.
198950a13cfSDan Gohman     MachineBasicBlock &MBB = *Entry.MBB;
19900406472SNico Weber     MBB.moveBefore(&*MF.begin());
200950a13cfSDan Gohman 
201950a13cfSDan Gohman     // Branch instructions may utilize a fallthrough, so update them if a
202950a13cfSDan Gohman     // fallthrough has been added or removed.
203950a13cfSDan Gohman     if (!MBB.empty() && MBB.back().isTerminator() && !MBB.back().isBranch() &&
204950a13cfSDan Gohman         !MBB.back().isBarrier())
205950a13cfSDan Gohman       report_fatal_error(
206950a13cfSDan Gohman           "Non-branch terminator with fallthrough cannot yet be rewritten");
207950a13cfSDan Gohman     if (MBB.empty() || !MBB.back().isTerminator() || MBB.back().isBranch())
208950a13cfSDan Gohman       MBB.updateTerminator();
209950a13cfSDan Gohman 
210950a13cfSDan Gohman     Stack.pop_back();
211950a13cfSDan Gohman     if (Stack.empty())
212950a13cfSDan Gohman       break;
213950a13cfSDan Gohman   }
214950a13cfSDan Gohman 
215950a13cfSDan Gohman   // Now that we've sorted the blocks in RPO, renumber them.
216950a13cfSDan Gohman   MF.RenumberBlocks();
217950a13cfSDan Gohman 
218950a13cfSDan Gohman #ifndef NDEBUG
2198fe7e86bSDan Gohman   SmallSetVector<MachineLoop *, 8> OnStack;
2208fe7e86bSDan Gohman 
2218fe7e86bSDan Gohman   // Insert a sentinel representing the degenerate loop that starts at the
2228fe7e86bSDan Gohman   // function entry block and includes the entire function as a "loop" that
2238fe7e86bSDan Gohman   // executes once.
2248fe7e86bSDan Gohman   OnStack.insert(nullptr);
2258fe7e86bSDan Gohman 
2268fe7e86bSDan Gohman   for (auto &MBB : MF) {
2278fe7e86bSDan Gohman     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
2288fe7e86bSDan Gohman 
2298fe7e86bSDan Gohman     MachineLoop *Loop = MLI.getLoopFor(&MBB);
2308fe7e86bSDan Gohman     if (Loop && &MBB == Loop->getHeader()) {
2318fe7e86bSDan Gohman       // Loop header. The loop predecessor should be sorted above, and the other
2328fe7e86bSDan Gohman       // predecessors should be backedges below.
2338fe7e86bSDan Gohman       for (auto Pred : MBB.predecessors())
2348fe7e86bSDan Gohman         assert(
2358fe7e86bSDan Gohman             (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) &&
2368fe7e86bSDan Gohman             "Loop header predecessors must be loop predecessors or backedges");
2378fe7e86bSDan Gohman       assert(OnStack.insert(Loop) && "Loops should be declared at most once.");
23832807932SDan Gohman     } else {
2398fe7e86bSDan Gohman       // Not a loop header. All predecessors should be sorted above.
240950a13cfSDan Gohman       for (auto Pred : MBB.predecessors())
241950a13cfSDan Gohman         assert(Pred->getNumber() < MBB.getNumber() &&
2428fe7e86bSDan Gohman                "Non-loop-header predecessors should be topologically sorted");
2438fe7e86bSDan Gohman       assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
2448fe7e86bSDan Gohman              "Blocks must be nested in their loops");
245950a13cfSDan Gohman     }
2468fe7e86bSDan Gohman     while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back()))
2478fe7e86bSDan Gohman       OnStack.pop_back();
2488fe7e86bSDan Gohman   }
2498fe7e86bSDan Gohman   assert(OnStack.pop_back_val() == nullptr &&
2508fe7e86bSDan Gohman          "The function entry block shouldn't actually be a loop header");
2518fe7e86bSDan Gohman   assert(OnStack.empty() &&
2528fe7e86bSDan Gohman          "Control flow stack pushes and pops should be balanced.");
253950a13cfSDan Gohman #endif
254950a13cfSDan Gohman }
255950a13cfSDan Gohman 
256b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
257b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
258b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
259b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
260b3aa1ecaSDan Gohman /// explicit mentions.
26135e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
26235e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
263b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
264b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
265b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
266b3aa1ecaSDan Gohman         return true;
267b3aa1ecaSDan Gohman   return false;
268b3aa1ecaSDan Gohman }
269b3aa1ecaSDan Gohman 
270ed0f1138SDan Gohman /// Test whether MI is a child of some other node in an expression tree.
271ed0f1138SDan Gohman static bool IsChild(const MachineInstr *MI,
272ed0f1138SDan Gohman                     const WebAssemblyFunctionInfo &MFI) {
273ed0f1138SDan Gohman   if (MI->getNumOperands() == 0)
274ed0f1138SDan Gohman     return false;
275ed0f1138SDan Gohman   const MachineOperand &MO = MI->getOperand(0);
276ed0f1138SDan Gohman   if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
277ed0f1138SDan Gohman     return false;
278ed0f1138SDan Gohman   unsigned Reg = MO.getReg();
279ed0f1138SDan Gohman   return TargetRegisterInfo::isVirtualRegister(Reg) &&
280ed0f1138SDan Gohman          MFI.isVRegStackified(Reg);
281ed0f1138SDan Gohman }
282ed0f1138SDan Gohman 
28332807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
2848fe7e86bSDan Gohman static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF,
2858fe7e86bSDan Gohman                              SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
28632807932SDan Gohman                              const WebAssemblyInstrInfo &TII,
2878fe7e86bSDan Gohman                              const MachineLoopInfo &MLI,
288ed0f1138SDan Gohman                              MachineDominatorTree &MDT,
289ed0f1138SDan Gohman                              WebAssemblyFunctionInfo &MFI) {
2908fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2918fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2928fe7e86bSDan Gohman   // which reduces overall stack height.
29332807932SDan Gohman   MachineBasicBlock *Header = nullptr;
29432807932SDan Gohman   bool IsBranchedTo = false;
29532807932SDan Gohman   int MBBNumber = MBB.getNumber();
29632807932SDan Gohman   for (MachineBasicBlock *Pred : MBB.predecessors())
29732807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
29832807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
299b3aa1ecaSDan Gohman       if (ExplicitlyBranchesTo(Pred, &MBB))
30032807932SDan Gohman         IsBranchedTo = true;
30132807932SDan Gohman     }
30232807932SDan Gohman   if (!Header)
30332807932SDan Gohman     return;
30432807932SDan Gohman   if (!IsBranchedTo)
30532807932SDan Gohman     return;
30632807932SDan Gohman 
3078fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
3088fe7e86bSDan Gohman   MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB));
3098fe7e86bSDan Gohman 
3108fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
3118fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
3128fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
3138fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
3148fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
3158fe7e86bSDan Gohman         // Skip over an intervening scope.
3168fe7e86bSDan Gohman         I = next(MachineFunction::iterator(ScopeTop));
3178fe7e86bSDan Gohman       } else {
3188fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
3198fe7e86bSDan Gohman         Header = ScopeTop;
3208fe7e86bSDan Gohman         break;
3218fe7e86bSDan Gohman       }
3228fe7e86bSDan Gohman     }
3238fe7e86bSDan Gohman   }
3248fe7e86bSDan Gohman 
3258fe7e86bSDan Gohman   // If there's a loop which ends just before MBB which contains Header, we can
3268fe7e86bSDan Gohman   // reuse its label instead of inserting a new BLOCK.
3278fe7e86bSDan Gohman   for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred);
3288fe7e86bSDan Gohman        Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop())
3298fe7e86bSDan Gohman     if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header))
3308fe7e86bSDan Gohman       return;
3318fe7e86bSDan Gohman 
3328fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
33332807932SDan Gohman   MachineBasicBlock::iterator InsertPos;
33432807932SDan Gohman   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
3358fe7e86bSDan Gohman   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
3368fe7e86bSDan Gohman     // Header is the header of a loop that does not lexically contain MBB, so
337*a187ab2aSDan Gohman     // the BLOCK needs to be above the LOOP, after any END constructs.
33832807932SDan Gohman     InsertPos = Header->begin();
339*a187ab2aSDan Gohman     while (InsertPos->getOpcode() != WebAssembly::LOOP)
340*a187ab2aSDan Gohman       ++InsertPos;
34132807932SDan Gohman   } else {
3428887d1faSDan Gohman     // Otherwise, insert the BLOCK as late in Header as we can, but before the
3438887d1faSDan Gohman     // beginning of the local expression tree and any nested BLOCKs.
34432807932SDan Gohman     InsertPos = Header->getFirstTerminator();
34532807932SDan Gohman     while (InsertPos != Header->begin() &&
346ed0f1138SDan Gohman            IsChild(prev(InsertPos), MFI) &&
3471d68e80fSDan Gohman            prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
3481d68e80fSDan Gohman            prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
3491d68e80fSDan Gohman            prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
35032807932SDan Gohman       --InsertPos;
35132807932SDan Gohman   }
35232807932SDan Gohman 
3538fe7e86bSDan Gohman   // Add the BLOCK.
3541d68e80fSDan Gohman   BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK));
3551d68e80fSDan Gohman 
3561d68e80fSDan Gohman   // Mark the end of the block.
3571d68e80fSDan Gohman   InsertPos = MBB.begin();
3581d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
3591d68e80fSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP)
3601d68e80fSDan Gohman     ++InsertPos;
3611d68e80fSDan Gohman   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK));
3628fe7e86bSDan Gohman 
3638fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3648fe7e86bSDan Gohman   int Number = MBB.getNumber();
3658fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
3668fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
3678fe7e86bSDan Gohman     ScopeTops[Number] = Header;
368950a13cfSDan Gohman }
369950a13cfSDan Gohman 
3708fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
3711d68e80fSDan Gohman static void PlaceLoopMarker(
3721d68e80fSDan Gohman     MachineBasicBlock &MBB, MachineFunction &MF,
3738fe7e86bSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
3741d68e80fSDan Gohman     DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops,
3751d68e80fSDan Gohman     const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
3768fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3778fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3788fe7e86bSDan Gohman     return;
3798fe7e86bSDan Gohman 
3808fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
3818fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
3828fe7e86bSDan Gohman   MachineBasicBlock *Bottom = LoopBottom(Loop);
383e3e4a5ffSDan Gohman   auto Iter = next(MachineFunction::iterator(Bottom));
384e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
385f6857223SDan Gohman     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
386f6857223SDan Gohman     // Give it a fake predecessor so that AsmPrinter prints its label.
387f6857223SDan Gohman     Label->addSuccessor(Label);
388f6857223SDan Gohman     MF.push_back(Label);
389e3e4a5ffSDan Gohman     Iter = next(MachineFunction::iterator(Bottom));
390e3e4a5ffSDan Gohman   }
3918fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
392f6857223SDan Gohman 
3931d68e80fSDan Gohman   // Mark the beginning of the loop (after the end of any existing loop that
3941d68e80fSDan Gohman   // ends here).
3951d68e80fSDan Gohman   auto InsertPos = MBB.begin();
3961d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
3971d68e80fSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP)
3981d68e80fSDan Gohman     ++InsertPos;
3991d68e80fSDan Gohman   BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP));
4001d68e80fSDan Gohman 
4011d68e80fSDan Gohman   // Mark the end of the loop.
4021d68e80fSDan Gohman   MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
4031d68e80fSDan Gohman                               TII.get(WebAssembly::END_LOOP));
4041d68e80fSDan Gohman   LoopTops[End] = &MBB;
4058fe7e86bSDan Gohman 
4068fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4078fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
4088fe7e86bSDan Gohman          "With RPO we should visit the outer-most loop for a block first.");
4098fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
4108fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
411e3e4a5ffSDan Gohman }
412950a13cfSDan Gohman 
4131d68e80fSDan Gohman static unsigned
4141d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
4151d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
4161d68e80fSDan Gohman   unsigned Depth = 0;
4171d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
4181d68e80fSDan Gohman     if (X == MBB)
4191d68e80fSDan Gohman       break;
4201d68e80fSDan Gohman     ++Depth;
4211d68e80fSDan Gohman   }
4221d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
4231d68e80fSDan Gohman   return Depth;
4241d68e80fSDan Gohman }
4251d68e80fSDan Gohman 
4268fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places.
4278fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
4288fe7e86bSDan Gohman                          const WebAssemblyInstrInfo &TII,
429ed0f1138SDan Gohman                          MachineDominatorTree &MDT,
430ed0f1138SDan Gohman                          WebAssemblyFunctionInfo &MFI) {
4318fe7e86bSDan Gohman   // For each block whose label represents the end of a scope, record the block
4328fe7e86bSDan Gohman   // which holds the beginning of the scope. This will allow us to quickly skip
4338fe7e86bSDan Gohman   // over scoped regions when walking blocks. We allocate one more than the
4348fe7e86bSDan Gohman   // number of blocks in the function to accommodate for the possible fake block
4358fe7e86bSDan Gohman   // we may insert at the end.
4368fe7e86bSDan Gohman   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
4378fe7e86bSDan Gohman 
4381d68e80fSDan Gohman   // For eacn LOOP_END, the corresponding LOOP.
4391d68e80fSDan Gohman   DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops;
4401d68e80fSDan Gohman 
4418fe7e86bSDan Gohman   for (auto &MBB : MF) {
4428fe7e86bSDan Gohman     // Place the LOOP for MBB if MBB is the header of a loop.
4431d68e80fSDan Gohman     PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
4448fe7e86bSDan Gohman 
44532807932SDan Gohman     // Place the BLOCK for MBB if MBB is branched to from above.
446ed0f1138SDan Gohman     PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT, MFI);
447950a13cfSDan Gohman   }
448950a13cfSDan Gohman 
4491d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
4501d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
4511d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
4521d68e80fSDan Gohman     for (auto &MI : reverse(MBB)) {
4531d68e80fSDan Gohman       switch (MI.getOpcode()) {
4541d68e80fSDan Gohman       case WebAssembly::BLOCK:
4551d68e80fSDan Gohman         assert(ScopeTops[Stack.back()->getNumber()] == &MBB &&
4561d68e80fSDan Gohman                "Block should be balanced");
4571d68e80fSDan Gohman         Stack.pop_back();
4581d68e80fSDan Gohman         break;
4591d68e80fSDan Gohman       case WebAssembly::LOOP:
4601d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
4611d68e80fSDan Gohman         Stack.pop_back();
4621d68e80fSDan Gohman         Stack.pop_back();
4631d68e80fSDan Gohman         break;
4641d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
4651d68e80fSDan Gohman         Stack.push_back(&MBB);
4661d68e80fSDan Gohman         break;
4671d68e80fSDan Gohman       case WebAssembly::END_LOOP:
4681d68e80fSDan Gohman         Stack.push_back(&MBB);
4691d68e80fSDan Gohman         Stack.push_back(LoopTops[&MI]);
4701d68e80fSDan Gohman         break;
4711d68e80fSDan Gohman       default:
4721d68e80fSDan Gohman         if (MI.isTerminator()) {
4731d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
4741d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
4751d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
4761d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
4771d68e80fSDan Gohman           for (auto MO : Ops) {
4781d68e80fSDan Gohman             if (MO.isMBB())
4791d68e80fSDan Gohman               MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
4801d68e80fSDan Gohman             MI.addOperand(MF, MO);
48132807932SDan Gohman           }
4821d68e80fSDan Gohman         }
4831d68e80fSDan Gohman         break;
4841d68e80fSDan Gohman       }
4851d68e80fSDan Gohman     }
4861d68e80fSDan Gohman   }
4871d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
4881d68e80fSDan Gohman }
48932807932SDan Gohman 
490950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
491950a13cfSDan Gohman   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
492950a13cfSDan Gohman                   "********** Function: "
493950a13cfSDan Gohman                << MF.getName() << '\n');
494950a13cfSDan Gohman 
495950a13cfSDan Gohman   const auto &MLI = getAnalysis<MachineLoopInfo>();
49632807932SDan Gohman   auto &MDT = getAnalysis<MachineDominatorTree>();
4979c3bf318SDerek Schuff   // Liveness is not tracked for EXPR_STACK physreg.
498950a13cfSDan Gohman   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
499ed0f1138SDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
5009c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
501950a13cfSDan Gohman 
502950a13cfSDan Gohman   // RPO sorting needs all loops to be single-entry.
503950a13cfSDan Gohman   EliminateMultipleEntryLoops(MF, MLI);
504950a13cfSDan Gohman 
505950a13cfSDan Gohman   // Sort the blocks in RPO, with contiguous loops.
506950a13cfSDan Gohman   SortBlocks(MF, MLI);
507950a13cfSDan Gohman 
508950a13cfSDan Gohman   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
509ed0f1138SDan Gohman   PlaceMarkers(MF, MLI, TII, MDT, MFI);
51032807932SDan Gohman 
511950a13cfSDan Gohman   return true;
512950a13cfSDan Gohman }
513