17a7e6055SDimitry Andric //===-- WebAssemblyCFGSort.cpp - CFG Sorting ------------------------------===//
27a7e6055SDimitry Andric //
37a7e6055SDimitry Andric //                     The LLVM Compiler Infrastructure
47a7e6055SDimitry Andric //
57a7e6055SDimitry Andric // This file is distributed under the University of Illinois Open Source
67a7e6055SDimitry Andric // License. See LICENSE.TXT for details.
77a7e6055SDimitry Andric //
87a7e6055SDimitry Andric //===----------------------------------------------------------------------===//
97a7e6055SDimitry Andric ///
107a7e6055SDimitry Andric /// \file
114ba319b5SDimitry Andric /// This file implements a CFG sorting pass.
127a7e6055SDimitry Andric ///
137a7e6055SDimitry Andric /// This pass reorders the blocks in a function to put them into topological
14*b5893f02SDimitry Andric /// order, ignoring loop backedges, and without any loop or exception being
15*b5893f02SDimitry Andric /// interrupted by a block not dominated by the its header, with special care
16*b5893f02SDimitry Andric /// to keep the order as similar as possible to the original order.
177a7e6055SDimitry Andric ///
187a7e6055SDimitry Andric ////===----------------------------------------------------------------------===//
197a7e6055SDimitry Andric 
207a7e6055SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
21db17bf38SDimitry Andric #include "WebAssembly.h"
22*b5893f02SDimitry Andric #include "WebAssemblyExceptionInfo.h"
237a7e6055SDimitry Andric #include "WebAssemblySubtarget.h"
247a7e6055SDimitry Andric #include "WebAssemblyUtilities.h"
257a7e6055SDimitry Andric #include "llvm/ADT/PriorityQueue.h"
267a7e6055SDimitry Andric #include "llvm/ADT/SetVector.h"
277a7e6055SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
287a7e6055SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
297a7e6055SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
307a7e6055SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
317a7e6055SDimitry Andric #include "llvm/CodeGen/Passes.h"
327a7e6055SDimitry Andric #include "llvm/Support/Debug.h"
337a7e6055SDimitry Andric #include "llvm/Support/raw_ostream.h"
347a7e6055SDimitry Andric using namespace llvm;
357a7e6055SDimitry Andric 
367a7e6055SDimitry Andric #define DEBUG_TYPE "wasm-cfg-sort"
377a7e6055SDimitry Andric 
387a7e6055SDimitry Andric namespace {
39*b5893f02SDimitry Andric 
40*b5893f02SDimitry Andric // Wrapper for loops and exceptions
41*b5893f02SDimitry Andric class Region {
42*b5893f02SDimitry Andric public:
43*b5893f02SDimitry Andric   virtual ~Region() = default;
44*b5893f02SDimitry Andric   virtual MachineBasicBlock *getHeader() const = 0;
45*b5893f02SDimitry Andric   virtual bool contains(const MachineBasicBlock *MBB) const = 0;
46*b5893f02SDimitry Andric   virtual unsigned getNumBlocks() const = 0;
47*b5893f02SDimitry Andric   using block_iterator = typename ArrayRef<MachineBasicBlock *>::const_iterator;
48*b5893f02SDimitry Andric   virtual iterator_range<block_iterator> blocks() const = 0;
49*b5893f02SDimitry Andric   virtual bool isLoop() const = 0;
50*b5893f02SDimitry Andric };
51*b5893f02SDimitry Andric 
52*b5893f02SDimitry Andric template <typename T> class ConcreteRegion : public Region {
53*b5893f02SDimitry Andric   const T *Region;
54*b5893f02SDimitry Andric 
55*b5893f02SDimitry Andric public:
ConcreteRegion(const T * Region)56*b5893f02SDimitry Andric   ConcreteRegion(const T *Region) : Region(Region) {}
getHeader() const57*b5893f02SDimitry Andric   MachineBasicBlock *getHeader() const override { return Region->getHeader(); }
contains(const MachineBasicBlock * MBB) const58*b5893f02SDimitry Andric   bool contains(const MachineBasicBlock *MBB) const override {
59*b5893f02SDimitry Andric     return Region->contains(MBB);
60*b5893f02SDimitry Andric   }
getNumBlocks() const61*b5893f02SDimitry Andric   unsigned getNumBlocks() const override { return Region->getNumBlocks(); }
blocks() const62*b5893f02SDimitry Andric   iterator_range<block_iterator> blocks() const override {
63*b5893f02SDimitry Andric     return Region->blocks();
64*b5893f02SDimitry Andric   }
isLoop() const65*b5893f02SDimitry Andric   bool isLoop() const override { return false; }
66*b5893f02SDimitry Andric };
67*b5893f02SDimitry Andric 
isLoop() const68*b5893f02SDimitry Andric template <> bool ConcreteRegion<MachineLoop>::isLoop() const { return true; }
69*b5893f02SDimitry Andric 
70*b5893f02SDimitry Andric // This class has information of nested Regions; this is analogous to what
71*b5893f02SDimitry Andric // LoopInfo is for loops.
72*b5893f02SDimitry Andric class RegionInfo {
73*b5893f02SDimitry Andric   const MachineLoopInfo &MLI;
74*b5893f02SDimitry Andric   const WebAssemblyExceptionInfo &WEI;
75*b5893f02SDimitry Andric   std::vector<const Region *> Regions;
76*b5893f02SDimitry Andric   DenseMap<const MachineLoop *, std::unique_ptr<Region>> LoopMap;
77*b5893f02SDimitry Andric   DenseMap<const WebAssemblyException *, std::unique_ptr<Region>> ExceptionMap;
78*b5893f02SDimitry Andric 
79*b5893f02SDimitry Andric public:
RegionInfo(const MachineLoopInfo & MLI,const WebAssemblyExceptionInfo & WEI)80*b5893f02SDimitry Andric   RegionInfo(const MachineLoopInfo &MLI, const WebAssemblyExceptionInfo &WEI)
81*b5893f02SDimitry Andric       : MLI(MLI), WEI(WEI) {}
82*b5893f02SDimitry Andric 
83*b5893f02SDimitry Andric   // Returns a smallest loop or exception that contains MBB
getRegionFor(const MachineBasicBlock * MBB)84*b5893f02SDimitry Andric   const Region *getRegionFor(const MachineBasicBlock *MBB) {
85*b5893f02SDimitry Andric     const auto *ML = MLI.getLoopFor(MBB);
86*b5893f02SDimitry Andric     const auto *WE = WEI.getExceptionFor(MBB);
87*b5893f02SDimitry Andric     if (!ML && !WE)
88*b5893f02SDimitry Andric       return nullptr;
89*b5893f02SDimitry Andric     if ((ML && !WE) || (ML && WE && ML->getNumBlocks() < WE->getNumBlocks())) {
90*b5893f02SDimitry Andric       // If the smallest region containing MBB is a loop
91*b5893f02SDimitry Andric       if (LoopMap.count(ML))
92*b5893f02SDimitry Andric         return LoopMap[ML].get();
93*b5893f02SDimitry Andric       LoopMap[ML] = llvm::make_unique<ConcreteRegion<MachineLoop>>(ML);
94*b5893f02SDimitry Andric       return LoopMap[ML].get();
95*b5893f02SDimitry Andric     } else {
96*b5893f02SDimitry Andric       // If the smallest region containing MBB is an exception
97*b5893f02SDimitry Andric       if (ExceptionMap.count(WE))
98*b5893f02SDimitry Andric         return ExceptionMap[WE].get();
99*b5893f02SDimitry Andric       ExceptionMap[WE] =
100*b5893f02SDimitry Andric           llvm::make_unique<ConcreteRegion<WebAssemblyException>>(WE);
101*b5893f02SDimitry Andric       return ExceptionMap[WE].get();
102*b5893f02SDimitry Andric     }
103*b5893f02SDimitry Andric   }
104*b5893f02SDimitry Andric };
105*b5893f02SDimitry Andric 
1067a7e6055SDimitry Andric class WebAssemblyCFGSort final : public MachineFunctionPass {
getPassName() const1077a7e6055SDimitry Andric   StringRef getPassName() const override { return "WebAssembly CFG Sort"; }
1087a7e6055SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1097a7e6055SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
1107a7e6055SDimitry Andric     AU.setPreservesCFG();
1117a7e6055SDimitry Andric     AU.addRequired<MachineDominatorTree>();
1127a7e6055SDimitry Andric     AU.addPreserved<MachineDominatorTree>();
1137a7e6055SDimitry Andric     AU.addRequired<MachineLoopInfo>();
1147a7e6055SDimitry Andric     AU.addPreserved<MachineLoopInfo>();
115*b5893f02SDimitry Andric     AU.addRequired<WebAssemblyExceptionInfo>();
116*b5893f02SDimitry Andric     AU.addPreserved<WebAssemblyExceptionInfo>();
1177a7e6055SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
1187a7e6055SDimitry Andric   }
1197a7e6055SDimitry Andric 
1207a7e6055SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
1217a7e6055SDimitry Andric 
1227a7e6055SDimitry Andric public:
1237a7e6055SDimitry Andric   static char ID; // Pass identification, replacement for typeid
WebAssemblyCFGSort()1247a7e6055SDimitry Andric   WebAssemblyCFGSort() : MachineFunctionPass(ID) {}
1257a7e6055SDimitry Andric };
1267a7e6055SDimitry Andric } // end anonymous namespace
1277a7e6055SDimitry Andric 
1287a7e6055SDimitry Andric char WebAssemblyCFGSort::ID = 0;
1294ba319b5SDimitry Andric INITIALIZE_PASS(WebAssemblyCFGSort, DEBUG_TYPE,
1304ba319b5SDimitry Andric                 "Reorders blocks in topological order", false, false)
1314ba319b5SDimitry Andric 
createWebAssemblyCFGSort()1327a7e6055SDimitry Andric FunctionPass *llvm::createWebAssemblyCFGSort() {
1337a7e6055SDimitry Andric   return new WebAssemblyCFGSort();
1347a7e6055SDimitry Andric }
1357a7e6055SDimitry Andric 
MaybeUpdateTerminator(MachineBasicBlock * MBB)1367a7e6055SDimitry Andric static void MaybeUpdateTerminator(MachineBasicBlock *MBB) {
1377a7e6055SDimitry Andric #ifndef NDEBUG
1387a7e6055SDimitry Andric   bool AnyBarrier = false;
1397a7e6055SDimitry Andric #endif
1407a7e6055SDimitry Andric   bool AllAnalyzable = true;
1417a7e6055SDimitry Andric   for (const MachineInstr &Term : MBB->terminators()) {
1427a7e6055SDimitry Andric #ifndef NDEBUG
1437a7e6055SDimitry Andric     AnyBarrier |= Term.isBarrier();
1447a7e6055SDimitry Andric #endif
1457a7e6055SDimitry Andric     AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
1467a7e6055SDimitry Andric   }
1477a7e6055SDimitry Andric   assert((AnyBarrier || AllAnalyzable) &&
1487a7e6055SDimitry Andric          "AnalyzeBranch needs to analyze any block with a fallthrough");
1497a7e6055SDimitry Andric   if (AllAnalyzable)
1507a7e6055SDimitry Andric     MBB->updateTerminator();
1517a7e6055SDimitry Andric }
1527a7e6055SDimitry Andric 
1537a7e6055SDimitry Andric namespace {
154*b5893f02SDimitry Andric // EH pads are selected first regardless of the block comparison order.
155*b5893f02SDimitry Andric // When only one of the BBs is an EH pad, we give a higher priority to it, to
156*b5893f02SDimitry Andric // prevent common mismatches between possibly throwing calls and ehpads they
157*b5893f02SDimitry Andric // unwind to, as in the example below:
158*b5893f02SDimitry Andric //
159*b5893f02SDimitry Andric // bb0:
160*b5893f02SDimitry Andric //   call @foo      // If this throws, unwind to bb2
161*b5893f02SDimitry Andric // bb1:
162*b5893f02SDimitry Andric //   call @bar      // If this throws, unwind to bb3
163*b5893f02SDimitry Andric // bb2 (ehpad):
164*b5893f02SDimitry Andric //   handler_bb2
165*b5893f02SDimitry Andric // bb3 (ehpad):
166*b5893f02SDimitry Andric //   handler_bb3
167*b5893f02SDimitry Andric // continuing code
168*b5893f02SDimitry Andric //
169*b5893f02SDimitry Andric // Because this pass tries to preserve the original BB order, this order will
170*b5893f02SDimitry Andric // not change. But this will result in this try-catch structure in CFGStackify,
171*b5893f02SDimitry Andric // resulting in a mismatch:
172*b5893f02SDimitry Andric // try
173*b5893f02SDimitry Andric //   try
174*b5893f02SDimitry Andric //     call @foo
175*b5893f02SDimitry Andric //     call @bar    // This should unwind to bb3, not bb2!
176*b5893f02SDimitry Andric //   catch
177*b5893f02SDimitry Andric //     handler_bb2
178*b5893f02SDimitry Andric //   end
179*b5893f02SDimitry Andric // catch
180*b5893f02SDimitry Andric //   handler_bb3
181*b5893f02SDimitry Andric // end
182*b5893f02SDimitry Andric // continuing code
183*b5893f02SDimitry Andric //
184*b5893f02SDimitry Andric // If we give a higher priority to an EH pad whenever it is ready in this
185*b5893f02SDimitry Andric // example, when both bb1 and bb2 are ready, we would pick up bb2 first.
186*b5893f02SDimitry Andric 
1877a7e6055SDimitry Andric /// Sort blocks by their number.
1887a7e6055SDimitry Andric struct CompareBlockNumbers {
operator ()__anon676071ee0211::CompareBlockNumbers1897a7e6055SDimitry Andric   bool operator()(const MachineBasicBlock *A,
1907a7e6055SDimitry Andric                   const MachineBasicBlock *B) const {
191*b5893f02SDimitry Andric     if (A->isEHPad() && !B->isEHPad())
192*b5893f02SDimitry Andric       return false;
193*b5893f02SDimitry Andric     if (!A->isEHPad() && B->isEHPad())
194*b5893f02SDimitry Andric       return true;
195*b5893f02SDimitry Andric 
1967a7e6055SDimitry Andric     return A->getNumber() > B->getNumber();
1977a7e6055SDimitry Andric   }
1987a7e6055SDimitry Andric };
1997a7e6055SDimitry Andric /// Sort blocks by their number in the opposite order..
2007a7e6055SDimitry Andric struct CompareBlockNumbersBackwards {
operator ()__anon676071ee0211::CompareBlockNumbersBackwards2017a7e6055SDimitry Andric   bool operator()(const MachineBasicBlock *A,
2027a7e6055SDimitry Andric                   const MachineBasicBlock *B) const {
203*b5893f02SDimitry Andric     // We give a higher priority to an EH pad
204*b5893f02SDimitry Andric     if (A->isEHPad() && !B->isEHPad())
205*b5893f02SDimitry Andric       return false;
206*b5893f02SDimitry Andric     if (!A->isEHPad() && B->isEHPad())
207*b5893f02SDimitry Andric       return true;
208*b5893f02SDimitry Andric 
2097a7e6055SDimitry Andric     return A->getNumber() < B->getNumber();
2107a7e6055SDimitry Andric   }
2117a7e6055SDimitry Andric };
212*b5893f02SDimitry Andric /// Bookkeeping for a region to help ensure that we don't mix blocks not
213*b5893f02SDimitry Andric /// dominated by the its header among its blocks.
2147a7e6055SDimitry Andric struct Entry {
215*b5893f02SDimitry Andric   const Region *TheRegion;
2167a7e6055SDimitry Andric   unsigned NumBlocksLeft;
2177a7e6055SDimitry Andric 
2187a7e6055SDimitry Andric   /// List of blocks not dominated by Loop's header that are deferred until
2197a7e6055SDimitry Andric   /// after all of Loop's blocks have been seen.
2207a7e6055SDimitry Andric   std::vector<MachineBasicBlock *> Deferred;
2217a7e6055SDimitry Andric 
Entry__anon676071ee0211::Entry222*b5893f02SDimitry Andric   explicit Entry(const class Region *R)
223*b5893f02SDimitry Andric       : TheRegion(R), NumBlocksLeft(R->getNumBlocks()) {}
2247a7e6055SDimitry Andric };
2257a7e6055SDimitry Andric } // end anonymous namespace
2267a7e6055SDimitry Andric 
227*b5893f02SDimitry Andric /// Sort the blocks, taking special care to make sure that regions are not
2287a7e6055SDimitry Andric /// interrupted by blocks not dominated by their header.
2297a7e6055SDimitry Andric /// TODO: There are many opportunities for improving the heuristics here.
2307a7e6055SDimitry Andric /// Explore them.
SortBlocks(MachineFunction & MF,const MachineLoopInfo & MLI,const WebAssemblyExceptionInfo & WEI,const MachineDominatorTree & MDT)2317a7e6055SDimitry Andric static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
232*b5893f02SDimitry Andric                        const WebAssemblyExceptionInfo &WEI,
2337a7e6055SDimitry Andric                        const MachineDominatorTree &MDT) {
2347a7e6055SDimitry Andric   // Prepare for a topological sort: Record the number of predecessors each
2357a7e6055SDimitry Andric   // block has, ignoring loop backedges.
2367a7e6055SDimitry Andric   MF.RenumberBlocks();
2377a7e6055SDimitry Andric   SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
2387a7e6055SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
2397a7e6055SDimitry Andric     unsigned N = MBB.pred_size();
2407a7e6055SDimitry Andric     if (MachineLoop *L = MLI.getLoopFor(&MBB))
2417a7e6055SDimitry Andric       if (L->getHeader() == &MBB)
2427a7e6055SDimitry Andric         for (const MachineBasicBlock *Pred : MBB.predecessors())
2437a7e6055SDimitry Andric           if (L->contains(Pred))
2447a7e6055SDimitry Andric             --N;
2457a7e6055SDimitry Andric     NumPredsLeft[MBB.getNumber()] = N;
2467a7e6055SDimitry Andric   }
2477a7e6055SDimitry Andric 
2487a7e6055SDimitry Andric   // Topological sort the CFG, with additional constraints:
249*b5893f02SDimitry Andric   //  - Between a region header and the last block in the region, there can be
250*b5893f02SDimitry Andric   //    no blocks not dominated by its header.
2517a7e6055SDimitry Andric   //  - It's desirable to preserve the original block order when possible.
2527a7e6055SDimitry Andric   // We use two ready lists; Preferred and Ready. Preferred has recently
253c4394386SDimitry Andric   // processed successors, to help preserve block sequences from the original
254*b5893f02SDimitry Andric   // order. Ready has the remaining ready blocks. EH blocks are picked first
255*b5893f02SDimitry Andric   // from both queues.
2567a7e6055SDimitry Andric   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
2577a7e6055SDimitry Andric                 CompareBlockNumbers>
2587a7e6055SDimitry Andric       Preferred;
2597a7e6055SDimitry Andric   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
2607a7e6055SDimitry Andric                 CompareBlockNumbersBackwards>
2617a7e6055SDimitry Andric       Ready;
262*b5893f02SDimitry Andric 
263*b5893f02SDimitry Andric   RegionInfo SUI(MLI, WEI);
264*b5893f02SDimitry Andric   SmallVector<Entry, 4> Entries;
2657a7e6055SDimitry Andric   for (MachineBasicBlock *MBB = &MF.front();;) {
266*b5893f02SDimitry Andric     const Region *R = SUI.getRegionFor(MBB);
267*b5893f02SDimitry Andric     if (R) {
268*b5893f02SDimitry Andric       // If MBB is a region header, add it to the active region list. We can't
269*b5893f02SDimitry Andric       // put any blocks that it doesn't dominate until we see the end of the
270*b5893f02SDimitry Andric       // region.
271*b5893f02SDimitry Andric       if (R->getHeader() == MBB)
272*b5893f02SDimitry Andric         Entries.push_back(Entry(R));
273*b5893f02SDimitry Andric       // For each active region the block is in, decrement the count. If MBB is
274*b5893f02SDimitry Andric       // the last block in an active region, take it off the list and pick up
275*b5893f02SDimitry Andric       // any blocks deferred because the header didn't dominate them.
276*b5893f02SDimitry Andric       for (Entry &E : Entries)
277*b5893f02SDimitry Andric         if (E.TheRegion->contains(MBB) && --E.NumBlocksLeft == 0)
2787a7e6055SDimitry Andric           for (auto DeferredBlock : E.Deferred)
2797a7e6055SDimitry Andric             Ready.push(DeferredBlock);
280*b5893f02SDimitry Andric       while (!Entries.empty() && Entries.back().NumBlocksLeft == 0)
281*b5893f02SDimitry Andric         Entries.pop_back();
2827a7e6055SDimitry Andric     }
2837a7e6055SDimitry Andric     // The main topological sort logic.
2847a7e6055SDimitry Andric     for (MachineBasicBlock *Succ : MBB->successors()) {
2857a7e6055SDimitry Andric       // Ignore backedges.
2867a7e6055SDimitry Andric       if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
2877a7e6055SDimitry Andric         if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
2887a7e6055SDimitry Andric           continue;
2897a7e6055SDimitry Andric       // Decrement the predecessor count. If it's now zero, it's ready.
2907a7e6055SDimitry Andric       if (--NumPredsLeft[Succ->getNumber()] == 0)
2917a7e6055SDimitry Andric         Preferred.push(Succ);
2927a7e6055SDimitry Andric     }
2937a7e6055SDimitry Andric     // Determine the block to follow MBB. First try to find a preferred block,
2947a7e6055SDimitry Andric     // to preserve the original block order when possible.
2957a7e6055SDimitry Andric     MachineBasicBlock *Next = nullptr;
2967a7e6055SDimitry Andric     while (!Preferred.empty()) {
2977a7e6055SDimitry Andric       Next = Preferred.top();
2987a7e6055SDimitry Andric       Preferred.pop();
299*b5893f02SDimitry Andric       // If X isn't dominated by the top active region header, defer it until
300*b5893f02SDimitry Andric       // that region is done.
301*b5893f02SDimitry Andric       if (!Entries.empty() &&
302*b5893f02SDimitry Andric           !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
303*b5893f02SDimitry Andric         Entries.back().Deferred.push_back(Next);
3047a7e6055SDimitry Andric         Next = nullptr;
3057a7e6055SDimitry Andric         continue;
3067a7e6055SDimitry Andric       }
3077a7e6055SDimitry Andric       // If Next was originally ordered before MBB, and it isn't because it was
3087a7e6055SDimitry Andric       // loop-rotated above the header, it's not preferred.
3097a7e6055SDimitry Andric       if (Next->getNumber() < MBB->getNumber() &&
310*b5893f02SDimitry Andric           (!R || !R->contains(Next) ||
311*b5893f02SDimitry Andric            R->getHeader()->getNumber() < Next->getNumber())) {
3127a7e6055SDimitry Andric         Ready.push(Next);
3137a7e6055SDimitry Andric         Next = nullptr;
3147a7e6055SDimitry Andric         continue;
3157a7e6055SDimitry Andric       }
3167a7e6055SDimitry Andric       break;
3177a7e6055SDimitry Andric     }
3187a7e6055SDimitry Andric     // If we didn't find a suitable block in the Preferred list, check the
3197a7e6055SDimitry Andric     // general Ready list.
3207a7e6055SDimitry Andric     if (!Next) {
3217a7e6055SDimitry Andric       // If there are no more blocks to process, we're done.
3227a7e6055SDimitry Andric       if (Ready.empty()) {
3237a7e6055SDimitry Andric         MaybeUpdateTerminator(MBB);
3247a7e6055SDimitry Andric         break;
3257a7e6055SDimitry Andric       }
3267a7e6055SDimitry Andric       for (;;) {
3277a7e6055SDimitry Andric         Next = Ready.top();
3287a7e6055SDimitry Andric         Ready.pop();
329*b5893f02SDimitry Andric         // If Next isn't dominated by the top active region header, defer it
330*b5893f02SDimitry Andric         // until that region is done.
331*b5893f02SDimitry Andric         if (!Entries.empty() &&
332*b5893f02SDimitry Andric             !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
333*b5893f02SDimitry Andric           Entries.back().Deferred.push_back(Next);
3347a7e6055SDimitry Andric           continue;
3357a7e6055SDimitry Andric         }
3367a7e6055SDimitry Andric         break;
3377a7e6055SDimitry Andric       }
3387a7e6055SDimitry Andric     }
3397a7e6055SDimitry Andric     // Move the next block into place and iterate.
3407a7e6055SDimitry Andric     Next->moveAfter(MBB);
3417a7e6055SDimitry Andric     MaybeUpdateTerminator(MBB);
3427a7e6055SDimitry Andric     MBB = Next;
3437a7e6055SDimitry Andric   }
344*b5893f02SDimitry Andric   assert(Entries.empty() && "Active sort region list not finished");
3457a7e6055SDimitry Andric   MF.RenumberBlocks();
3467a7e6055SDimitry Andric 
3477a7e6055SDimitry Andric #ifndef NDEBUG
348*b5893f02SDimitry Andric   SmallSetVector<const Region *, 8> OnStack;
3497a7e6055SDimitry Andric 
3507a7e6055SDimitry Andric   // Insert a sentinel representing the degenerate loop that starts at the
3517a7e6055SDimitry Andric   // function entry block and includes the entire function as a "loop" that
3527a7e6055SDimitry Andric   // executes once.
3537a7e6055SDimitry Andric   OnStack.insert(nullptr);
3547a7e6055SDimitry Andric 
3557a7e6055SDimitry Andric   for (auto &MBB : MF) {
3567a7e6055SDimitry Andric     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
357*b5893f02SDimitry Andric     const Region *Region = SUI.getRegionFor(&MBB);
3587a7e6055SDimitry Andric 
359*b5893f02SDimitry Andric     if (Region && &MBB == Region->getHeader()) {
360*b5893f02SDimitry Andric       if (Region->isLoop()) {
361*b5893f02SDimitry Andric         // Loop header. The loop predecessor should be sorted above, and the
362*b5893f02SDimitry Andric         // other predecessors should be backedges below.
3637a7e6055SDimitry Andric         for (auto Pred : MBB.predecessors())
3647a7e6055SDimitry Andric           assert(
365*b5893f02SDimitry Andric               (Pred->getNumber() < MBB.getNumber() || Region->contains(Pred)) &&
366*b5893f02SDimitry Andric               "Loop header predecessors must be loop predecessors or "
367*b5893f02SDimitry Andric               "backedges");
3687a7e6055SDimitry Andric       } else {
3697a7e6055SDimitry Andric         // Not a loop header. All predecessors should be sorted above.
3707a7e6055SDimitry Andric         for (auto Pred : MBB.predecessors())
3717a7e6055SDimitry Andric           assert(Pred->getNumber() < MBB.getNumber() &&
3727a7e6055SDimitry Andric                  "Non-loop-header predecessors should be topologically sorted");
373*b5893f02SDimitry Andric       }
374*b5893f02SDimitry Andric       assert(OnStack.insert(Region) &&
375*b5893f02SDimitry Andric              "Regions should be declared at most once.");
376*b5893f02SDimitry Andric 
377*b5893f02SDimitry Andric     } else {
378*b5893f02SDimitry Andric       // Not a loop header. All predecessors should be sorted above.
379*b5893f02SDimitry Andric       for (auto Pred : MBB.predecessors())
380*b5893f02SDimitry Andric         assert(Pred->getNumber() < MBB.getNumber() &&
381*b5893f02SDimitry Andric                "Non-loop-header predecessors should be topologically sorted");
382*b5893f02SDimitry Andric       assert(OnStack.count(SUI.getRegionFor(&MBB)) &&
383*b5893f02SDimitry Andric              "Blocks must be nested in their regions");
3847a7e6055SDimitry Andric     }
3854ba319b5SDimitry Andric     while (OnStack.size() > 1 && &MBB == WebAssembly::getBottom(OnStack.back()))
3867a7e6055SDimitry Andric       OnStack.pop_back();
3877a7e6055SDimitry Andric   }
3887a7e6055SDimitry Andric   assert(OnStack.pop_back_val() == nullptr &&
389*b5893f02SDimitry Andric          "The function entry block shouldn't actually be a region header");
3907a7e6055SDimitry Andric   assert(OnStack.empty() &&
3917a7e6055SDimitry Andric          "Control flow stack pushes and pops should be balanced.");
3927a7e6055SDimitry Andric #endif
3937a7e6055SDimitry Andric }
3947a7e6055SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)3957a7e6055SDimitry Andric bool WebAssemblyCFGSort::runOnMachineFunction(MachineFunction &MF) {
3964ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** CFG Sorting **********\n"
3977a7e6055SDimitry Andric                        "********** Function: "
3987a7e6055SDimitry Andric                     << MF.getName() << '\n');
3997a7e6055SDimitry Andric 
4007a7e6055SDimitry Andric   const auto &MLI = getAnalysis<MachineLoopInfo>();
401*b5893f02SDimitry Andric   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
4027a7e6055SDimitry Andric   auto &MDT = getAnalysis<MachineDominatorTree>();
4037a7e6055SDimitry Andric   // Liveness is not tracked for VALUE_STACK physreg.
4047a7e6055SDimitry Andric   MF.getRegInfo().invalidateLiveness();
4057a7e6055SDimitry Andric 
406*b5893f02SDimitry Andric   // Sort the blocks, with contiguous sort regions.
407*b5893f02SDimitry Andric   SortBlocks(MF, MLI, WEI, MDT);
4087a7e6055SDimitry Andric 
4097a7e6055SDimitry Andric   return true;
4107a7e6055SDimitry Andric }
411