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 ///
13442bfcecSDan Gohman /// This pass reorders the blocks in a function to put them into topological
14442bfcecSDan Gohman /// order, ignoring loop backedges, and without any loop being interrupted
15442bfcecSDan Gohman /// by a block not dominated by the loop header, with special care to keep the
16442bfcecSDan Gohman /// order as similar as possible to the original order.
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 //===----------------------------------------------------------------------===//
25950a13cfSDan Gohman 
26950a13cfSDan Gohman #include "WebAssembly.h"
27950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
28ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
29950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
30442bfcecSDan Gohman #include "llvm/ADT/PriorityQueue.h"
318fe7e86bSDan Gohman #include "llvm/ADT/SetVector.h"
3232807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
33950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
34950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
35950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h"
369c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.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 {
46117296c0SMehdi Amini   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
47950a13cfSDan Gohman 
48950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
49950a13cfSDan Gohman     AU.setPreservesCFG();
5032807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
5132807932SDan Gohman     AU.addPreserved<MachineDominatorTree>();
52950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
53950a13cfSDan Gohman     AU.addPreserved<MachineLoopInfo>();
54950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
55950a13cfSDan Gohman   }
56950a13cfSDan Gohman 
57950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
58950a13cfSDan Gohman 
59950a13cfSDan Gohman public:
60950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
61950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
62950a13cfSDan Gohman };
63950a13cfSDan Gohman } // end anonymous namespace
64950a13cfSDan Gohman 
65950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
66950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
67950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
68950a13cfSDan Gohman }
69950a13cfSDan Gohman 
708fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from
718fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is
728fe7e86bSDan Gohman /// discontiguous.
738fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) {
748fe7e86bSDan Gohman   MachineBasicBlock *Bottom = Loop->getHeader();
758fe7e86bSDan Gohman   for (MachineBasicBlock *MBB : Loop->blocks())
768fe7e86bSDan Gohman     if (MBB->getNumber() > Bottom->getNumber())
778fe7e86bSDan Gohman       Bottom = MBB;
788fe7e86bSDan Gohman   return Bottom;
798fe7e86bSDan Gohman }
808fe7e86bSDan Gohman 
81442bfcecSDan Gohman static void MaybeUpdateTerminator(MachineBasicBlock *MBB) {
82442bfcecSDan Gohman #ifndef NDEBUG
83442bfcecSDan Gohman   bool AnyBarrier = false;
84442bfcecSDan Gohman #endif
85442bfcecSDan Gohman   bool AllAnalyzable = true;
86442bfcecSDan Gohman   for (const MachineInstr &Term : MBB->terminators()) {
87442bfcecSDan Gohman #ifndef NDEBUG
88442bfcecSDan Gohman     AnyBarrier |= Term.isBarrier();
89442bfcecSDan Gohman #endif
90442bfcecSDan Gohman     AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
91442bfcecSDan Gohman   }
92442bfcecSDan Gohman   assert((AnyBarrier || AllAnalyzable) &&
93442bfcecSDan Gohman          "AnalyzeBranch needs to analyze any block with a fallthrough");
94442bfcecSDan Gohman   if (AllAnalyzable)
95442bfcecSDan Gohman     MBB->updateTerminator();
96442bfcecSDan Gohman }
97950a13cfSDan Gohman 
98442bfcecSDan Gohman namespace {
99442bfcecSDan Gohman /// Sort blocks by their number.
100442bfcecSDan Gohman struct CompareBlockNumbers {
101442bfcecSDan Gohman   bool operator()(const MachineBasicBlock *A,
102442bfcecSDan Gohman                   const MachineBasicBlock *B) const {
103442bfcecSDan Gohman     return A->getNumber() > B->getNumber();
104442bfcecSDan Gohman   }
105442bfcecSDan Gohman };
106442bfcecSDan Gohman /// Sort blocks by their number in the opposite order..
107442bfcecSDan Gohman struct CompareBlockNumbersBackwards {
108442bfcecSDan Gohman   bool operator()(const MachineBasicBlock *A,
109442bfcecSDan Gohman                   const MachineBasicBlock *B) const {
110442bfcecSDan Gohman     return A->getNumber() < B->getNumber();
111442bfcecSDan Gohman   }
112442bfcecSDan Gohman };
113442bfcecSDan Gohman /// Bookkeeping for a loop to help ensure that we don't mix blocks not dominated
114442bfcecSDan Gohman /// by the loop header among the loop's blocks.
115442bfcecSDan Gohman struct Entry {
116442bfcecSDan Gohman   const MachineLoop *Loop;
117442bfcecSDan Gohman   unsigned NumBlocksLeft;
118950a13cfSDan Gohman 
119442bfcecSDan Gohman   /// List of blocks not dominated by Loop's header that are deferred until
120442bfcecSDan Gohman   /// after all of Loop's blocks have been seen.
121442bfcecSDan Gohman   std::vector<MachineBasicBlock *> Deferred;
122442bfcecSDan Gohman 
123442bfcecSDan Gohman   explicit Entry(const MachineLoop *L)
124442bfcecSDan Gohman       : Loop(L), NumBlocksLeft(L->getNumBlocks()) {}
125442bfcecSDan Gohman };
126442bfcecSDan Gohman }
127442bfcecSDan Gohman 
128442bfcecSDan Gohman /// Sort the blocks, taking special care to make sure that loops are not
129442bfcecSDan Gohman /// interrupted by blocks not dominated by their header.
130442bfcecSDan Gohman /// TODO: There are many opportunities for improving the heuristics here.
131442bfcecSDan Gohman /// Explore them.
132442bfcecSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
133442bfcecSDan Gohman                        const MachineDominatorTree &MDT) {
134442bfcecSDan Gohman   // Prepare for a topological sort: Record the number of predecessors each
135442bfcecSDan Gohman   // block has, ignoring loop backedges.
136442bfcecSDan Gohman   MF.RenumberBlocks();
137442bfcecSDan Gohman   SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
138442bfcecSDan Gohman   for (MachineBasicBlock &MBB : MF) {
139442bfcecSDan Gohman     unsigned N = MBB.pred_size();
140442bfcecSDan Gohman     if (MachineLoop *L = MLI.getLoopFor(&MBB))
141442bfcecSDan Gohman       if (L->getHeader() == &MBB)
142442bfcecSDan Gohman         for (const MachineBasicBlock *Pred : MBB.predecessors())
143442bfcecSDan Gohman           if (L->contains(Pred))
144442bfcecSDan Gohman             --N;
145442bfcecSDan Gohman     NumPredsLeft[MBB.getNumber()] = N;
146442bfcecSDan Gohman   }
147442bfcecSDan Gohman 
148442bfcecSDan Gohman   // Topological sort the CFG, with additional constraints:
149442bfcecSDan Gohman   //  - Between a loop header and the last block in the loop, there can be
150442bfcecSDan Gohman   //    no blocks not dominated by the loop header.
151442bfcecSDan Gohman   //  - It's desirable to preserve the original block order when possible.
152442bfcecSDan Gohman   // We use two ready lists; Preferred and Ready. Preferred has recently
153442bfcecSDan Gohman   // processed sucessors, to help preserve block sequences from the original
154442bfcecSDan Gohman   // order. Ready has the remaining ready blocks.
155442bfcecSDan Gohman   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
156442bfcecSDan Gohman                 CompareBlockNumbers>
157442bfcecSDan Gohman       Preferred;
158442bfcecSDan Gohman   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
159442bfcecSDan Gohman                 CompareBlockNumbersBackwards>
160442bfcecSDan Gohman       Ready;
161442bfcecSDan Gohman   SmallVector<Entry, 4> Loops;
162442bfcecSDan Gohman   for (MachineBasicBlock *MBB = &MF.front();;) {
163442bfcecSDan Gohman     const MachineLoop *L = MLI.getLoopFor(MBB);
164442bfcecSDan Gohman     if (L) {
165442bfcecSDan Gohman       // If MBB is a loop header, add it to the active loop list. We can't put
166442bfcecSDan Gohman       // any blocks that it doesn't dominate until we see the end of the loop.
167442bfcecSDan Gohman       if (L->getHeader() == MBB)
168442bfcecSDan Gohman         Loops.push_back(Entry(L));
169442bfcecSDan Gohman       // For each active loop the block is in, decrement the count. If MBB is
170442bfcecSDan Gohman       // the last block in an active loop, take it off the list and pick up any
171442bfcecSDan Gohman       // blocks deferred because the header didn't dominate them.
172442bfcecSDan Gohman       for (Entry &E : Loops)
173442bfcecSDan Gohman         if (E.Loop->contains(MBB) && --E.NumBlocksLeft == 0)
174442bfcecSDan Gohman           for (auto DeferredBlock : E.Deferred)
175442bfcecSDan Gohman             Ready.push(DeferredBlock);
176442bfcecSDan Gohman       while (!Loops.empty() && Loops.back().NumBlocksLeft == 0)
177442bfcecSDan Gohman         Loops.pop_back();
178442bfcecSDan Gohman     }
179442bfcecSDan Gohman     // The main topological sort logic.
180442bfcecSDan Gohman     for (MachineBasicBlock *Succ : MBB->successors()) {
181442bfcecSDan Gohman       // Ignore backedges.
182442bfcecSDan Gohman       if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
183442bfcecSDan Gohman         if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
184442bfcecSDan Gohman           continue;
185442bfcecSDan Gohman       // Decrement the predecessor count. If it's now zero, it's ready.
186442bfcecSDan Gohman       if (--NumPredsLeft[Succ->getNumber()] == 0)
187442bfcecSDan Gohman         Preferred.push(Succ);
188442bfcecSDan Gohman     }
189442bfcecSDan Gohman     // Determine the block to follow MBB. First try to find a preferred block,
190442bfcecSDan Gohman     // to preserve the original block order when possible.
191442bfcecSDan Gohman     MachineBasicBlock *Next = nullptr;
192442bfcecSDan Gohman     while (!Preferred.empty()) {
193442bfcecSDan Gohman       Next = Preferred.top();
194442bfcecSDan Gohman       Preferred.pop();
195442bfcecSDan Gohman       // If X isn't dominated by the top active loop header, defer it until that
196442bfcecSDan Gohman       // loop is done.
197442bfcecSDan Gohman       if (!Loops.empty() &&
198442bfcecSDan Gohman           !MDT.dominates(Loops.back().Loop->getHeader(), Next)) {
199442bfcecSDan Gohman         Loops.back().Deferred.push_back(Next);
200442bfcecSDan Gohman         Next = nullptr;
201950a13cfSDan Gohman         continue;
202950a13cfSDan Gohman       }
203442bfcecSDan Gohman       // If Next was originally ordered before MBB, and it isn't because it was
204442bfcecSDan Gohman       // loop-rotated above the header, it's not preferred.
205442bfcecSDan Gohman       if (Next->getNumber() < MBB->getNumber() &&
206442bfcecSDan Gohman           (!L || !L->contains(Next) ||
207442bfcecSDan Gohman            L->getHeader()->getNumber() < Next->getNumber())) {
208442bfcecSDan Gohman         Ready.push(Next);
209442bfcecSDan Gohman         Next = nullptr;
210442bfcecSDan Gohman         continue;
211442bfcecSDan Gohman       }
212950a13cfSDan Gohman       break;
213950a13cfSDan Gohman     }
214442bfcecSDan Gohman     // If we didn't find a suitable block in the Preferred list, check the
215442bfcecSDan Gohman     // general Ready list.
216442bfcecSDan Gohman     if (!Next) {
217442bfcecSDan Gohman       // If there are no more blocks to process, we're done.
218442bfcecSDan Gohman       if (Ready.empty()) {
219442bfcecSDan Gohman         MaybeUpdateTerminator(MBB);
220442bfcecSDan Gohman         break;
221442bfcecSDan Gohman       }
222442bfcecSDan Gohman       for (;;) {
223442bfcecSDan Gohman         Next = Ready.top();
224442bfcecSDan Gohman         Ready.pop();
225442bfcecSDan Gohman         // If Next isn't dominated by the top active loop header, defer it until
226442bfcecSDan Gohman         // that loop is done.
227442bfcecSDan Gohman         if (!Loops.empty() &&
228442bfcecSDan Gohman             !MDT.dominates(Loops.back().Loop->getHeader(), Next)) {
229442bfcecSDan Gohman           Loops.back().Deferred.push_back(Next);
230442bfcecSDan Gohman           continue;
231442bfcecSDan Gohman         }
232442bfcecSDan Gohman         break;
233442bfcecSDan Gohman       }
234442bfcecSDan Gohman     }
235442bfcecSDan Gohman     // Move the next block into place and iterate.
236442bfcecSDan Gohman     Next->moveAfter(MBB);
237442bfcecSDan Gohman     MaybeUpdateTerminator(MBB);
238442bfcecSDan Gohman     MBB = Next;
239442bfcecSDan Gohman   }
240442bfcecSDan Gohman   assert(Loops.empty() && "Active loop list not finished");
241950a13cfSDan Gohman   MF.RenumberBlocks();
242950a13cfSDan Gohman 
243950a13cfSDan Gohman #ifndef NDEBUG
2448fe7e86bSDan Gohman   SmallSetVector<MachineLoop *, 8> OnStack;
2458fe7e86bSDan Gohman 
2468fe7e86bSDan Gohman   // Insert a sentinel representing the degenerate loop that starts at the
2478fe7e86bSDan Gohman   // function entry block and includes the entire function as a "loop" that
2488fe7e86bSDan Gohman   // executes once.
2498fe7e86bSDan Gohman   OnStack.insert(nullptr);
2508fe7e86bSDan Gohman 
2518fe7e86bSDan Gohman   for (auto &MBB : MF) {
2528fe7e86bSDan Gohman     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
2538fe7e86bSDan Gohman 
2548fe7e86bSDan Gohman     MachineLoop *Loop = MLI.getLoopFor(&MBB);
2558fe7e86bSDan Gohman     if (Loop && &MBB == Loop->getHeader()) {
2568fe7e86bSDan Gohman       // Loop header. The loop predecessor should be sorted above, and the other
2578fe7e86bSDan Gohman       // predecessors should be backedges below.
2588fe7e86bSDan Gohman       for (auto Pred : MBB.predecessors())
2598fe7e86bSDan Gohman         assert(
2608fe7e86bSDan Gohman             (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) &&
2618fe7e86bSDan Gohman             "Loop header predecessors must be loop predecessors or backedges");
2628fe7e86bSDan Gohman       assert(OnStack.insert(Loop) && "Loops should be declared at most once.");
26332807932SDan Gohman     } else {
2648fe7e86bSDan Gohman       // Not a loop header. All predecessors should be sorted above.
265950a13cfSDan Gohman       for (auto Pred : MBB.predecessors())
266950a13cfSDan Gohman         assert(Pred->getNumber() < MBB.getNumber() &&
2678fe7e86bSDan Gohman                "Non-loop-header predecessors should be topologically sorted");
2688fe7e86bSDan Gohman       assert(OnStack.count(MLI.getLoopFor(&MBB)) &&
2698fe7e86bSDan Gohman              "Blocks must be nested in their loops");
270950a13cfSDan Gohman     }
2718fe7e86bSDan Gohman     while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back()))
2728fe7e86bSDan Gohman       OnStack.pop_back();
2738fe7e86bSDan Gohman   }
2748fe7e86bSDan Gohman   assert(OnStack.pop_back_val() == nullptr &&
2758fe7e86bSDan Gohman          "The function entry block shouldn't actually be a loop header");
2768fe7e86bSDan Gohman   assert(OnStack.empty() &&
2778fe7e86bSDan Gohman          "Control flow stack pushes and pops should be balanced.");
278950a13cfSDan Gohman #endif
279950a13cfSDan Gohman }
280950a13cfSDan Gohman 
281b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
282b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
283b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
284b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
285b3aa1ecaSDan Gohman /// explicit mentions.
28635e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred,
28735e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
288b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
289b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
290b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
291b3aa1ecaSDan Gohman         return true;
292b3aa1ecaSDan Gohman   return false;
293b3aa1ecaSDan Gohman }
294b3aa1ecaSDan Gohman 
295ed0f1138SDan Gohman /// Test whether MI is a child of some other node in an expression tree.
296500d0469SDuncan P. N. Exon Smith static bool IsChild(const MachineInstr &MI,
297ed0f1138SDan Gohman                     const WebAssemblyFunctionInfo &MFI) {
298500d0469SDuncan P. N. Exon Smith   if (MI.getNumOperands() == 0)
299ed0f1138SDan Gohman     return false;
300500d0469SDuncan P. N. Exon Smith   const MachineOperand &MO = MI.getOperand(0);
301ed0f1138SDan Gohman   if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
302ed0f1138SDan Gohman     return false;
303ed0f1138SDan Gohman   unsigned Reg = MO.getReg();
304ed0f1138SDan Gohman   return TargetRegisterInfo::isVirtualRegister(Reg) &&
305ed0f1138SDan Gohman          MFI.isVRegStackified(Reg);
306ed0f1138SDan Gohman }
307ed0f1138SDan Gohman 
30832807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
3093a643e8dSDan Gohman static void PlaceBlockMarker(
3103a643e8dSDan Gohman     MachineBasicBlock &MBB, MachineFunction &MF,
3118fe7e86bSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
312*2726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &BlockTops,
313*2726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops,
31432807932SDan Gohman     const WebAssemblyInstrInfo &TII,
3158fe7e86bSDan Gohman     const MachineLoopInfo &MLI,
316ed0f1138SDan Gohman     MachineDominatorTree &MDT,
317ed0f1138SDan Gohman     WebAssemblyFunctionInfo &MFI) {
3188fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
3198fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
3208fe7e86bSDan Gohman   // which reduces overall stack height.
32132807932SDan Gohman   MachineBasicBlock *Header = nullptr;
32232807932SDan Gohman   bool IsBranchedTo = false;
32332807932SDan Gohman   int MBBNumber = MBB.getNumber();
32432807932SDan Gohman   for (MachineBasicBlock *Pred : MBB.predecessors())
32532807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
32632807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
327b3aa1ecaSDan Gohman       if (ExplicitlyBranchesTo(Pred, &MBB))
32832807932SDan Gohman         IsBranchedTo = true;
32932807932SDan Gohman     }
33032807932SDan Gohman   if (!Header)
33132807932SDan Gohman     return;
33232807932SDan Gohman   if (!IsBranchedTo)
33332807932SDan Gohman     return;
33432807932SDan Gohman 
3358fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
336ef0a45aaSBenjamin Kramer   MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
3378fe7e86bSDan Gohman 
3388fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
3398fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
3408fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
3418fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
3428fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
3438fe7e86bSDan Gohman         // Skip over an intervening scope.
344ef0a45aaSBenjamin Kramer         I = std::next(MachineFunction::iterator(ScopeTop));
3458fe7e86bSDan Gohman       } else {
3468fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
3478fe7e86bSDan Gohman         Header = ScopeTop;
3488fe7e86bSDan Gohman         break;
3498fe7e86bSDan Gohman       }
3508fe7e86bSDan Gohman     }
3518fe7e86bSDan Gohman   }
3528fe7e86bSDan Gohman 
3538fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
35432807932SDan Gohman   MachineBasicBlock::iterator InsertPos;
35532807932SDan Gohman   MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
3568fe7e86bSDan Gohman   if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
3578fe7e86bSDan Gohman     // Header is the header of a loop that does not lexically contain MBB, so
358a187ab2aSDan Gohman     // the BLOCK needs to be above the LOOP, after any END constructs.
35932807932SDan Gohman     InsertPos = Header->begin();
3603a643e8dSDan Gohman     while (InsertPos->getOpcode() == WebAssembly::END_BLOCK ||
3613a643e8dSDan Gohman            InsertPos->getOpcode() == WebAssembly::END_LOOP)
362a187ab2aSDan Gohman       ++InsertPos;
36332807932SDan Gohman   } else {
3648887d1faSDan Gohman     // Otherwise, insert the BLOCK as late in Header as we can, but before the
3658887d1faSDan Gohman     // beginning of the local expression tree and any nested BLOCKs.
36632807932SDan Gohman     InsertPos = Header->getFirstTerminator();
367ef0a45aaSBenjamin Kramer     while (InsertPos != Header->begin() &&
368ef0a45aaSBenjamin Kramer            IsChild(*std::prev(InsertPos), MFI) &&
369ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
370ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
371ef0a45aaSBenjamin Kramer            std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
37232807932SDan Gohman       --InsertPos;
37332807932SDan Gohman   }
37432807932SDan Gohman 
3758fe7e86bSDan Gohman   // Add the BLOCK.
376*2726b88cSDan Gohman   MachineInstr *Begin = BuildMI(*Header, InsertPos, DebugLoc(),
377*2726b88cSDan Gohman                                 TII.get(WebAssembly::BLOCK))
378*2726b88cSDan Gohman       .addImm(WebAssembly::Void);
3791d68e80fSDan Gohman 
3801d68e80fSDan Gohman   // Mark the end of the block.
3811d68e80fSDan Gohman   InsertPos = MBB.begin();
3821d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
3833a643e8dSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP &&
384*2726b88cSDan Gohman          LoopTops[&*InsertPos]->getParent()->getNumber() >= Header->getNumber())
3851d68e80fSDan Gohman     ++InsertPos;
386*2726b88cSDan Gohman   MachineInstr *End = BuildMI(MBB, InsertPos, DebugLoc(),
387*2726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
388*2726b88cSDan Gohman   BlockTops[End] = Begin;
3898fe7e86bSDan Gohman 
3908fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3918fe7e86bSDan Gohman   int Number = MBB.getNumber();
3928fe7e86bSDan Gohman   if (!ScopeTops[Number] ||
3938fe7e86bSDan Gohman       ScopeTops[Number]->getNumber() > Header->getNumber())
3948fe7e86bSDan Gohman     ScopeTops[Number] = Header;
395950a13cfSDan Gohman }
396950a13cfSDan Gohman 
3978fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
3981d68e80fSDan Gohman static void PlaceLoopMarker(
3991d68e80fSDan Gohman     MachineBasicBlock &MBB, MachineFunction &MF,
4008fe7e86bSDan Gohman     SmallVectorImpl<MachineBasicBlock *> &ScopeTops,
401*2726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops,
4021d68e80fSDan Gohman     const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
4038fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
4048fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
4058fe7e86bSDan Gohman     return;
4068fe7e86bSDan Gohman 
4078fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
4088fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
4098fe7e86bSDan Gohman   MachineBasicBlock *Bottom = LoopBottom(Loop);
410ef0a45aaSBenjamin Kramer   auto Iter = std::next(MachineFunction::iterator(Bottom));
411e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
412f6857223SDan Gohman     MachineBasicBlock *Label = MF.CreateMachineBasicBlock();
413f6857223SDan Gohman     // Give it a fake predecessor so that AsmPrinter prints its label.
414f6857223SDan Gohman     Label->addSuccessor(Label);
415f6857223SDan Gohman     MF.push_back(Label);
416ef0a45aaSBenjamin Kramer     Iter = std::next(MachineFunction::iterator(Bottom));
417e3e4a5ffSDan Gohman   }
4188fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
419f6857223SDan Gohman 
4201d68e80fSDan Gohman   // Mark the beginning of the loop (after the end of any existing loop that
4211d68e80fSDan Gohman   // ends here).
4221d68e80fSDan Gohman   auto InsertPos = MBB.begin();
4231d68e80fSDan Gohman   while (InsertPos != MBB.end() &&
4241d68e80fSDan Gohman          InsertPos->getOpcode() == WebAssembly::END_LOOP)
4251d68e80fSDan Gohman     ++InsertPos;
426*2726b88cSDan Gohman   MachineInstr *Begin = BuildMI(MBB, InsertPos, DebugLoc(),
427*2726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
428*2726b88cSDan Gohman       .addImm(WebAssembly::Void);
4291d68e80fSDan Gohman 
4301d68e80fSDan Gohman   // Mark the end of the loop.
4311d68e80fSDan Gohman   MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
4321d68e80fSDan Gohman                               TII.get(WebAssembly::END_LOOP));
433*2726b88cSDan Gohman   LoopTops[End] = Begin;
4348fe7e86bSDan Gohman 
4358fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4368fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
437442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4388fe7e86bSDan Gohman   if (!ScopeTops[AfterLoop->getNumber()])
4398fe7e86bSDan Gohman     ScopeTops[AfterLoop->getNumber()] = &MBB;
440e3e4a5ffSDan Gohman }
441950a13cfSDan Gohman 
4421d68e80fSDan Gohman static unsigned
4431d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
4441d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
4451d68e80fSDan Gohman   unsigned Depth = 0;
4461d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
4471d68e80fSDan Gohman     if (X == MBB)
4481d68e80fSDan Gohman       break;
4491d68e80fSDan Gohman     ++Depth;
4501d68e80fSDan Gohman   }
4511d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
4521d68e80fSDan Gohman   return Depth;
4531d68e80fSDan Gohman }
4541d68e80fSDan Gohman 
455*2726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
456*2726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
457*2726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
458*2726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
459*2726b88cSDan Gohman /// that end at the function end need to have a return type signature that
460*2726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
461*2726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
462*2726b88cSDan Gohman static void FixEndsAtEndOfFunction(
463*2726b88cSDan Gohman     MachineFunction &MF,
464*2726b88cSDan Gohman     const WebAssemblyFunctionInfo &MFI,
465*2726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &BlockTops,
466*2726b88cSDan Gohman     DenseMap<const MachineInstr *, MachineInstr *> &LoopTops) {
467*2726b88cSDan Gohman   assert(MFI.getResults().size() <= 1);
468*2726b88cSDan Gohman 
469*2726b88cSDan Gohman   if (MFI.getResults().empty())
470*2726b88cSDan Gohman     return;
471*2726b88cSDan Gohman 
472*2726b88cSDan Gohman   WebAssembly::ExprType retType;
473*2726b88cSDan Gohman   switch (MFI.getResults().front().SimpleTy) {
474*2726b88cSDan Gohman   case MVT::i32: retType = WebAssembly::I32; break;
475*2726b88cSDan Gohman   case MVT::i64: retType = WebAssembly::I64; break;
476*2726b88cSDan Gohman   case MVT::f32: retType = WebAssembly::F32; break;
477*2726b88cSDan Gohman   case MVT::f64: retType = WebAssembly::F64; break;
478*2726b88cSDan Gohman   case MVT::v16i8: retType = WebAssembly::I8x16; break;
479*2726b88cSDan Gohman   case MVT::v8i16: retType = WebAssembly::I16x8; break;
480*2726b88cSDan Gohman   case MVT::v4i32: retType = WebAssembly::I32x4; break;
481*2726b88cSDan Gohman   case MVT::v2i64: retType = WebAssembly::I64x2; break;
482*2726b88cSDan Gohman   case MVT::v4f32: retType = WebAssembly::F32x4; break;
483*2726b88cSDan Gohman   case MVT::v2f64: retType = WebAssembly::F64x2; break;
484*2726b88cSDan Gohman   default: llvm_unreachable("unexpected return type");
485*2726b88cSDan Gohman   }
486*2726b88cSDan Gohman 
487*2726b88cSDan Gohman   for (MachineBasicBlock &MBB : reverse(MF)) {
488*2726b88cSDan Gohman     for (MachineInstr &MI : reverse(MBB)) {
489*2726b88cSDan Gohman       if (MI.isPosition() || MI.isDebugValue())
490*2726b88cSDan Gohman         continue;
491*2726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_BLOCK) {
492*2726b88cSDan Gohman         BlockTops[&MI]->getOperand(0).setImm(int32_t(retType));
493*2726b88cSDan Gohman         continue;
494*2726b88cSDan Gohman       }
495*2726b88cSDan Gohman       if (MI.getOpcode() == WebAssembly::END_LOOP) {
496*2726b88cSDan Gohman         LoopTops[&MI]->getOperand(0).setImm(int32_t(retType));
497*2726b88cSDan Gohman         continue;
498*2726b88cSDan Gohman       }
499*2726b88cSDan Gohman       // Something other than an `end`. We're done.
500*2726b88cSDan Gohman       return;
501*2726b88cSDan Gohman     }
502*2726b88cSDan Gohman   }
503*2726b88cSDan Gohman }
504*2726b88cSDan Gohman 
5058fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places.
5068fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
5078fe7e86bSDan Gohman                          const WebAssemblyInstrInfo &TII,
508ed0f1138SDan Gohman                          MachineDominatorTree &MDT,
509ed0f1138SDan Gohman                          WebAssemblyFunctionInfo &MFI) {
5108fe7e86bSDan Gohman   // For each block whose label represents the end of a scope, record the block
5118fe7e86bSDan Gohman   // which holds the beginning of the scope. This will allow us to quickly skip
5128fe7e86bSDan Gohman   // over scoped regions when walking blocks. We allocate one more than the
5138fe7e86bSDan Gohman   // number of blocks in the function to accommodate for the possible fake block
5148fe7e86bSDan Gohman   // we may insert at the end.
5158fe7e86bSDan Gohman   SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1);
5168fe7e86bSDan Gohman 
517*2726b88cSDan Gohman   // For each LOOP_END, the corresponding LOOP.
518*2726b88cSDan Gohman   DenseMap<const MachineInstr *, MachineInstr *> LoopTops;
519*2726b88cSDan Gohman 
520*2726b88cSDan Gohman   // For each END_BLOCK, the corresponding BLOCK.
521*2726b88cSDan Gohman   DenseMap<const MachineInstr *, MachineInstr *> BlockTops;
5221d68e80fSDan Gohman 
5238fe7e86bSDan Gohman   for (auto &MBB : MF) {
5248fe7e86bSDan Gohman     // Place the LOOP for MBB if MBB is the header of a loop.
5251d68e80fSDan Gohman     PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
5268fe7e86bSDan Gohman 
52732807932SDan Gohman     // Place the BLOCK for MBB if MBB is branched to from above.
528*2726b88cSDan Gohman     PlaceBlockMarker(MBB, MF, ScopeTops, BlockTops, LoopTops, TII, MLI, MDT, MFI);
529950a13cfSDan Gohman   }
530950a13cfSDan Gohman 
5311d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
5321d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
5331d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
5341d68e80fSDan Gohman     for (auto &MI : reverse(MBB)) {
5351d68e80fSDan Gohman       switch (MI.getOpcode()) {
5361d68e80fSDan Gohman       case WebAssembly::BLOCK:
5373a643e8dSDan Gohman         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() &&
5381d68e80fSDan Gohman                "Block should be balanced");
5391d68e80fSDan Gohman         Stack.pop_back();
5401d68e80fSDan Gohman         break;
5411d68e80fSDan Gohman       case WebAssembly::LOOP:
5421d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
5431d68e80fSDan Gohman         Stack.pop_back();
5441d68e80fSDan Gohman         break;
5451d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
5461d68e80fSDan Gohman         Stack.push_back(&MBB);
5471d68e80fSDan Gohman         break;
5481d68e80fSDan Gohman       case WebAssembly::END_LOOP:
549*2726b88cSDan Gohman         Stack.push_back(LoopTops[&MI]->getParent());
5501d68e80fSDan Gohman         break;
5511d68e80fSDan Gohman       default:
5521d68e80fSDan Gohman         if (MI.isTerminator()) {
5531d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
5541d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
5551d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
5561d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
5571d68e80fSDan Gohman           for (auto MO : Ops) {
5581d68e80fSDan Gohman             if (MO.isMBB())
5591d68e80fSDan Gohman               MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
5601d68e80fSDan Gohman             MI.addOperand(MF, MO);
56132807932SDan Gohman           }
5621d68e80fSDan Gohman         }
5631d68e80fSDan Gohman         break;
5641d68e80fSDan Gohman       }
5651d68e80fSDan Gohman     }
5661d68e80fSDan Gohman   }
5671d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
568*2726b88cSDan Gohman 
569*2726b88cSDan Gohman   // Fix up block/loop signatures at the end of the function to conform to
570*2726b88cSDan Gohman   // WebAssembly's rules.
571*2726b88cSDan Gohman   FixEndsAtEndOfFunction(MF, MFI, BlockTops, LoopTops);
5721d68e80fSDan Gohman }
57332807932SDan Gohman 
574950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
575950a13cfSDan Gohman   DEBUG(dbgs() << "********** CFG Stackifying **********\n"
576950a13cfSDan Gohman                   "********** Function: "
577950a13cfSDan Gohman                << MF.getName() << '\n');
578950a13cfSDan Gohman 
579950a13cfSDan Gohman   const auto &MLI = getAnalysis<MachineLoopInfo>();
58032807932SDan Gohman   auto &MDT = getAnalysis<MachineDominatorTree>();
581e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
582950a13cfSDan Gohman   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
583ed0f1138SDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
5849c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
585950a13cfSDan Gohman 
586442bfcecSDan Gohman   // Sort the blocks, with contiguous loops.
587442bfcecSDan Gohman   SortBlocks(MF, MLI, MDT);
588950a13cfSDan Gohman 
589950a13cfSDan Gohman   // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
590ed0f1138SDan Gohman   PlaceMarkers(MF, MLI, TII, MDT, MFI);
59132807932SDan Gohman 
592950a13cfSDan Gohman   return true;
593950a13cfSDan Gohman }
594