xref: /src/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGSort.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
171d5a254SDimitry Andric //===-- WebAssemblyCFGSort.cpp - CFG Sorting ------------------------------===//
271d5a254SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
671d5a254SDimitry Andric //
771d5a254SDimitry Andric //===----------------------------------------------------------------------===//
871d5a254SDimitry Andric ///
971d5a254SDimitry Andric /// \file
10eb11fae6SDimitry Andric /// This file implements a CFG sorting pass.
1171d5a254SDimitry Andric ///
1271d5a254SDimitry Andric /// This pass reorders the blocks in a function to put them into topological
13d8e91e46SDimitry Andric /// order, ignoring loop backedges, and without any loop or exception being
14d8e91e46SDimitry Andric /// interrupted by a block not dominated by the its header, with special care
15d8e91e46SDimitry Andric /// to keep the order as similar as possible to the original order.
1671d5a254SDimitry Andric ///
1771d5a254SDimitry Andric ////===----------------------------------------------------------------------===//
1871d5a254SDimitry Andric 
1971d5a254SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
207ab83427SDimitry Andric #include "WebAssembly.h"
21d8e91e46SDimitry Andric #include "WebAssemblyExceptionInfo.h"
22b60736ecSDimitry Andric #include "WebAssemblySortRegion.h"
2371d5a254SDimitry Andric #include "WebAssemblySubtarget.h"
24b1c73532SDimitry Andric #include "WebAssemblyUtilities.h"
2571d5a254SDimitry Andric #include "llvm/ADT/PriorityQueue.h"
2671d5a254SDimitry Andric #include "llvm/ADT/SetVector.h"
2771d5a254SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
2871d5a254SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
2971d5a254SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
3071d5a254SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
3171d5a254SDimitry Andric #include "llvm/CodeGen/Passes.h"
32344a3780SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
3371d5a254SDimitry Andric #include "llvm/Support/Debug.h"
3471d5a254SDimitry Andric #include "llvm/Support/raw_ostream.h"
3571d5a254SDimitry Andric using namespace llvm;
36b60736ecSDimitry Andric using WebAssembly::SortRegion;
37b60736ecSDimitry Andric using WebAssembly::SortRegionInfo;
3871d5a254SDimitry Andric 
3971d5a254SDimitry Andric #define DEBUG_TYPE "wasm-cfg-sort"
4071d5a254SDimitry Andric 
41e6d15924SDimitry Andric // Option to disable EH pad first sorting. Only for testing unwind destination
42e6d15924SDimitry Andric // mismatches in CFGStackify.
43e6d15924SDimitry Andric static cl::opt<bool> WasmDisableEHPadSort(
44e6d15924SDimitry Andric     "wasm-disable-ehpad-sort", cl::ReallyHidden,
45e6d15924SDimitry Andric     cl::desc(
46e6d15924SDimitry Andric         "WebAssembly: Disable EH pad-first sort order. Testing purpose only."),
47e6d15924SDimitry Andric     cl::init(false));
48e6d15924SDimitry Andric 
4971d5a254SDimitry Andric namespace {
50d8e91e46SDimitry Andric 
5171d5a254SDimitry Andric class WebAssemblyCFGSort final : public MachineFunctionPass {
getPassName() const5271d5a254SDimitry Andric   StringRef getPassName() const override { return "WebAssembly CFG Sort"; }
5371d5a254SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const5471d5a254SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
5571d5a254SDimitry Andric     AU.setPreservesCFG();
56ac9a064cSDimitry Andric     AU.addRequired<MachineDominatorTreeWrapperPass>();
57ac9a064cSDimitry Andric     AU.addPreserved<MachineDominatorTreeWrapperPass>();
58ac9a064cSDimitry Andric     AU.addRequired<MachineLoopInfoWrapperPass>();
59ac9a064cSDimitry Andric     AU.addPreserved<MachineLoopInfoWrapperPass>();
60d8e91e46SDimitry Andric     AU.addRequired<WebAssemblyExceptionInfo>();
61d8e91e46SDimitry Andric     AU.addPreserved<WebAssemblyExceptionInfo>();
6271d5a254SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
6371d5a254SDimitry Andric   }
6471d5a254SDimitry Andric 
6571d5a254SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
6671d5a254SDimitry Andric 
6771d5a254SDimitry Andric public:
6871d5a254SDimitry Andric   static char ID; // Pass identification, replacement for typeid
WebAssemblyCFGSort()6971d5a254SDimitry Andric   WebAssemblyCFGSort() : MachineFunctionPass(ID) {}
7071d5a254SDimitry Andric };
7171d5a254SDimitry Andric } // end anonymous namespace
7271d5a254SDimitry Andric 
7371d5a254SDimitry Andric char WebAssemblyCFGSort::ID = 0;
74eb11fae6SDimitry Andric INITIALIZE_PASS(WebAssemblyCFGSort, DEBUG_TYPE,
75eb11fae6SDimitry Andric                 "Reorders blocks in topological order", false, false)
76eb11fae6SDimitry Andric 
createWebAssemblyCFGSort()7771d5a254SDimitry Andric FunctionPass *llvm::createWebAssemblyCFGSort() {
7871d5a254SDimitry Andric   return new WebAssemblyCFGSort();
7971d5a254SDimitry Andric }
8071d5a254SDimitry Andric 
maybeUpdateTerminator(MachineBasicBlock * MBB)81e6d15924SDimitry Andric static void maybeUpdateTerminator(MachineBasicBlock *MBB) {
8271d5a254SDimitry Andric #ifndef NDEBUG
8371d5a254SDimitry Andric   bool AnyBarrier = false;
8471d5a254SDimitry Andric #endif
8571d5a254SDimitry Andric   bool AllAnalyzable = true;
8671d5a254SDimitry Andric   for (const MachineInstr &Term : MBB->terminators()) {
8771d5a254SDimitry Andric #ifndef NDEBUG
8871d5a254SDimitry Andric     AnyBarrier |= Term.isBarrier();
8971d5a254SDimitry Andric #endif
9071d5a254SDimitry Andric     AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
9171d5a254SDimitry Andric   }
9271d5a254SDimitry Andric   assert((AnyBarrier || AllAnalyzable) &&
93cfca06d7SDimitry Andric          "analyzeBranch needs to analyze any block with a fallthrough");
94cfca06d7SDimitry Andric 
95cfca06d7SDimitry Andric   // Find the layout successor from the original block order.
96cfca06d7SDimitry Andric   MachineFunction *MF = MBB->getParent();
97cfca06d7SDimitry Andric   MachineBasicBlock *OriginalSuccessor =
98cfca06d7SDimitry Andric       unsigned(MBB->getNumber() + 1) < MF->getNumBlockIDs()
99cfca06d7SDimitry Andric           ? MF->getBlockNumbered(MBB->getNumber() + 1)
100cfca06d7SDimitry Andric           : nullptr;
101cfca06d7SDimitry Andric 
10271d5a254SDimitry Andric   if (AllAnalyzable)
103cfca06d7SDimitry Andric     MBB->updateTerminator(OriginalSuccessor);
10471d5a254SDimitry Andric }
10571d5a254SDimitry Andric 
10671d5a254SDimitry Andric namespace {
107d8e91e46SDimitry Andric // EH pads are selected first regardless of the block comparison order.
108d8e91e46SDimitry Andric // When only one of the BBs is an EH pad, we give a higher priority to it, to
109d8e91e46SDimitry Andric // prevent common mismatches between possibly throwing calls and ehpads they
110d8e91e46SDimitry Andric // unwind to, as in the example below:
111d8e91e46SDimitry Andric //
112d8e91e46SDimitry Andric // bb0:
113d8e91e46SDimitry Andric //   call @foo      // If this throws, unwind to bb2
114d8e91e46SDimitry Andric // bb1:
115d8e91e46SDimitry Andric //   call @bar      // If this throws, unwind to bb3
116d8e91e46SDimitry Andric // bb2 (ehpad):
117d8e91e46SDimitry Andric //   handler_bb2
118d8e91e46SDimitry Andric // bb3 (ehpad):
119d8e91e46SDimitry Andric //   handler_bb3
120d8e91e46SDimitry Andric // continuing code
121d8e91e46SDimitry Andric //
122d8e91e46SDimitry Andric // Because this pass tries to preserve the original BB order, this order will
123d8e91e46SDimitry Andric // not change. But this will result in this try-catch structure in CFGStackify,
124d8e91e46SDimitry Andric // resulting in a mismatch:
125d8e91e46SDimitry Andric // try
126d8e91e46SDimitry Andric //   try
127d8e91e46SDimitry Andric //     call @foo
128d8e91e46SDimitry Andric //     call @bar    // This should unwind to bb3, not bb2!
129d8e91e46SDimitry Andric //   catch
130d8e91e46SDimitry Andric //     handler_bb2
131d8e91e46SDimitry Andric //   end
132d8e91e46SDimitry Andric // catch
133d8e91e46SDimitry Andric //   handler_bb3
134d8e91e46SDimitry Andric // end
135d8e91e46SDimitry Andric // continuing code
136d8e91e46SDimitry Andric //
137d8e91e46SDimitry Andric // If we give a higher priority to an EH pad whenever it is ready in this
138d8e91e46SDimitry Andric // example, when both bb1 and bb2 are ready, we would pick up bb2 first.
139d8e91e46SDimitry Andric 
14071d5a254SDimitry Andric /// Sort blocks by their number.
14171d5a254SDimitry Andric struct CompareBlockNumbers {
operator ()__anon929dcc5e0211::CompareBlockNumbers14271d5a254SDimitry Andric   bool operator()(const MachineBasicBlock *A,
14371d5a254SDimitry Andric                   const MachineBasicBlock *B) const {
144e6d15924SDimitry Andric     if (!WasmDisableEHPadSort) {
145d8e91e46SDimitry Andric       if (A->isEHPad() && !B->isEHPad())
146d8e91e46SDimitry Andric         return false;
147d8e91e46SDimitry Andric       if (!A->isEHPad() && B->isEHPad())
148d8e91e46SDimitry Andric         return true;
149e6d15924SDimitry Andric     }
150d8e91e46SDimitry Andric 
15171d5a254SDimitry Andric     return A->getNumber() > B->getNumber();
15271d5a254SDimitry Andric   }
15371d5a254SDimitry Andric };
15471d5a254SDimitry Andric /// Sort blocks by their number in the opposite order..
15571d5a254SDimitry Andric struct CompareBlockNumbersBackwards {
operator ()__anon929dcc5e0211::CompareBlockNumbersBackwards15671d5a254SDimitry Andric   bool operator()(const MachineBasicBlock *A,
15771d5a254SDimitry Andric                   const MachineBasicBlock *B) const {
158e6d15924SDimitry Andric     if (!WasmDisableEHPadSort) {
159d8e91e46SDimitry Andric       if (A->isEHPad() && !B->isEHPad())
160d8e91e46SDimitry Andric         return false;
161d8e91e46SDimitry Andric       if (!A->isEHPad() && B->isEHPad())
162d8e91e46SDimitry Andric         return true;
163e6d15924SDimitry Andric     }
164d8e91e46SDimitry Andric 
16571d5a254SDimitry Andric     return A->getNumber() < B->getNumber();
16671d5a254SDimitry Andric   }
16771d5a254SDimitry Andric };
168d8e91e46SDimitry Andric /// Bookkeeping for a region to help ensure that we don't mix blocks not
169d8e91e46SDimitry Andric /// dominated by the its header among its blocks.
17071d5a254SDimitry Andric struct Entry {
171b60736ecSDimitry Andric   const SortRegion *TheRegion;
17271d5a254SDimitry Andric   unsigned NumBlocksLeft;
17371d5a254SDimitry Andric 
17471d5a254SDimitry Andric   /// List of blocks not dominated by Loop's header that are deferred until
17571d5a254SDimitry Andric   /// after all of Loop's blocks have been seen.
17671d5a254SDimitry Andric   std::vector<MachineBasicBlock *> Deferred;
17771d5a254SDimitry Andric 
Entry__anon929dcc5e0211::Entry178b60736ecSDimitry Andric   explicit Entry(const SortRegion *R)
179d8e91e46SDimitry Andric       : TheRegion(R), NumBlocksLeft(R->getNumBlocks()) {}
18071d5a254SDimitry Andric };
18171d5a254SDimitry Andric } // end anonymous namespace
18271d5a254SDimitry Andric 
183d8e91e46SDimitry Andric /// Sort the blocks, taking special care to make sure that regions are not
18471d5a254SDimitry Andric /// interrupted by blocks not dominated by their header.
18571d5a254SDimitry Andric /// TODO: There are many opportunities for improving the heuristics here.
18671d5a254SDimitry Andric /// Explore them.
sortBlocks(MachineFunction & MF,const MachineLoopInfo & MLI,const WebAssemblyExceptionInfo & WEI,const MachineDominatorTree & MDT)187e6d15924SDimitry Andric static void sortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
188d8e91e46SDimitry Andric                        const WebAssemblyExceptionInfo &WEI,
18971d5a254SDimitry Andric                        const MachineDominatorTree &MDT) {
190cfca06d7SDimitry Andric   // Remember original layout ordering, so we can update terminators after
191cfca06d7SDimitry Andric   // reordering to point to the original layout successor.
192cfca06d7SDimitry Andric   MF.RenumberBlocks();
193cfca06d7SDimitry Andric 
19471d5a254SDimitry Andric   // Prepare for a topological sort: Record the number of predecessors each
19571d5a254SDimitry Andric   // block has, ignoring loop backedges.
19671d5a254SDimitry Andric   SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
19771d5a254SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
19871d5a254SDimitry Andric     unsigned N = MBB.pred_size();
19971d5a254SDimitry Andric     if (MachineLoop *L = MLI.getLoopFor(&MBB))
20071d5a254SDimitry Andric       if (L->getHeader() == &MBB)
20171d5a254SDimitry Andric         for (const MachineBasicBlock *Pred : MBB.predecessors())
20271d5a254SDimitry Andric           if (L->contains(Pred))
20371d5a254SDimitry Andric             --N;
20471d5a254SDimitry Andric     NumPredsLeft[MBB.getNumber()] = N;
20571d5a254SDimitry Andric   }
20671d5a254SDimitry Andric 
20771d5a254SDimitry Andric   // Topological sort the CFG, with additional constraints:
208d8e91e46SDimitry Andric   //  - Between a region header and the last block in the region, there can be
209d8e91e46SDimitry Andric   //    no blocks not dominated by its header.
21071d5a254SDimitry Andric   //  - It's desirable to preserve the original block order when possible.
21171d5a254SDimitry Andric   // We use two ready lists; Preferred and Ready. Preferred has recently
212ca089b24SDimitry Andric   // processed successors, to help preserve block sequences from the original
213d8e91e46SDimitry Andric   // order. Ready has the remaining ready blocks. EH blocks are picked first
214d8e91e46SDimitry Andric   // from both queues.
21571d5a254SDimitry Andric   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
21671d5a254SDimitry Andric                 CompareBlockNumbers>
21771d5a254SDimitry Andric       Preferred;
21871d5a254SDimitry Andric   PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
21971d5a254SDimitry Andric                 CompareBlockNumbersBackwards>
22071d5a254SDimitry Andric       Ready;
221d8e91e46SDimitry Andric 
222344a3780SDimitry Andric   const auto *EHInfo = MF.getWasmEHFuncInfo();
223b60736ecSDimitry Andric   SortRegionInfo SRI(MLI, WEI);
224d8e91e46SDimitry Andric   SmallVector<Entry, 4> Entries;
22571d5a254SDimitry Andric   for (MachineBasicBlock *MBB = &MF.front();;) {
226b60736ecSDimitry Andric     const SortRegion *R = SRI.getRegionFor(MBB);
227d8e91e46SDimitry Andric     if (R) {
228d8e91e46SDimitry Andric       // If MBB is a region header, add it to the active region list. We can't
229d8e91e46SDimitry Andric       // put any blocks that it doesn't dominate until we see the end of the
230d8e91e46SDimitry Andric       // region.
231d8e91e46SDimitry Andric       if (R->getHeader() == MBB)
232d8e91e46SDimitry Andric         Entries.push_back(Entry(R));
233d8e91e46SDimitry Andric       // For each active region the block is in, decrement the count. If MBB is
234d8e91e46SDimitry Andric       // the last block in an active region, take it off the list and pick up
235d8e91e46SDimitry Andric       // any blocks deferred because the header didn't dominate them.
236d8e91e46SDimitry Andric       for (Entry &E : Entries)
237d8e91e46SDimitry Andric         if (E.TheRegion->contains(MBB) && --E.NumBlocksLeft == 0)
238e3b55780SDimitry Andric           for (auto *DeferredBlock : E.Deferred)
23971d5a254SDimitry Andric             Ready.push(DeferredBlock);
240d8e91e46SDimitry Andric       while (!Entries.empty() && Entries.back().NumBlocksLeft == 0)
241d8e91e46SDimitry Andric         Entries.pop_back();
24271d5a254SDimitry Andric     }
24371d5a254SDimitry Andric     // The main topological sort logic.
24471d5a254SDimitry Andric     for (MachineBasicBlock *Succ : MBB->successors()) {
24571d5a254SDimitry Andric       // Ignore backedges.
24671d5a254SDimitry Andric       if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
24771d5a254SDimitry Andric         if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
24871d5a254SDimitry Andric           continue;
24971d5a254SDimitry Andric       // Decrement the predecessor count. If it's now zero, it's ready.
250344a3780SDimitry Andric       if (--NumPredsLeft[Succ->getNumber()] == 0) {
251344a3780SDimitry Andric         // When we are in a SortRegion, we allow sorting of not only BBs that
252344a3780SDimitry Andric         // belong to the current (innermost) region but also BBs that are
253344a3780SDimitry Andric         // dominated by the current region header. But we should not do this for
254344a3780SDimitry Andric         // exceptions because there can be cases in which, for example:
255344a3780SDimitry Andric         // EHPad A's unwind destination (where the exception lands when it is
256344a3780SDimitry Andric         // not caught by EHPad A) is EHPad B, so EHPad B does not belong to the
257344a3780SDimitry Andric         // exception dominated by EHPad A. But EHPad B is dominated by EHPad A,
258344a3780SDimitry Andric         // so EHPad B can be sorted within EHPad A's exception. This is
259344a3780SDimitry Andric         // incorrect because we may end up delegating/rethrowing to an inner
260344a3780SDimitry Andric         // scope in CFGStackify. So here we make sure those unwind destinations
261344a3780SDimitry Andric         // are deferred until their unwind source's exception is sorted.
262344a3780SDimitry Andric         if (EHInfo && EHInfo->hasUnwindSrcs(Succ)) {
263344a3780SDimitry Andric           SmallPtrSet<MachineBasicBlock *, 4> UnwindSrcs =
264344a3780SDimitry Andric               EHInfo->getUnwindSrcs(Succ);
265344a3780SDimitry Andric           bool IsDeferred = false;
266344a3780SDimitry Andric           for (Entry &E : Entries) {
267344a3780SDimitry Andric             if (UnwindSrcs.count(E.TheRegion->getHeader())) {
268344a3780SDimitry Andric               E.Deferred.push_back(Succ);
269344a3780SDimitry Andric               IsDeferred = true;
270344a3780SDimitry Andric               break;
271344a3780SDimitry Andric             }
272344a3780SDimitry Andric           }
273344a3780SDimitry Andric           if (IsDeferred)
274344a3780SDimitry Andric             continue;
275344a3780SDimitry Andric         }
27671d5a254SDimitry Andric         Preferred.push(Succ);
27771d5a254SDimitry Andric       }
278344a3780SDimitry Andric     }
27971d5a254SDimitry Andric     // Determine the block to follow MBB. First try to find a preferred block,
28071d5a254SDimitry Andric     // to preserve the original block order when possible.
28171d5a254SDimitry Andric     MachineBasicBlock *Next = nullptr;
28271d5a254SDimitry Andric     while (!Preferred.empty()) {
28371d5a254SDimitry Andric       Next = Preferred.top();
28471d5a254SDimitry Andric       Preferred.pop();
285d8e91e46SDimitry Andric       // If X isn't dominated by the top active region header, defer it until
286d8e91e46SDimitry Andric       // that region is done.
287d8e91e46SDimitry Andric       if (!Entries.empty() &&
288d8e91e46SDimitry Andric           !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
289d8e91e46SDimitry Andric         Entries.back().Deferred.push_back(Next);
29071d5a254SDimitry Andric         Next = nullptr;
29171d5a254SDimitry Andric         continue;
29271d5a254SDimitry Andric       }
29371d5a254SDimitry Andric       // If Next was originally ordered before MBB, and it isn't because it was
29471d5a254SDimitry Andric       // loop-rotated above the header, it's not preferred.
29571d5a254SDimitry Andric       if (Next->getNumber() < MBB->getNumber() &&
2961d5ae102SDimitry Andric           (WasmDisableEHPadSort || !Next->isEHPad()) &&
297d8e91e46SDimitry Andric           (!R || !R->contains(Next) ||
298d8e91e46SDimitry Andric            R->getHeader()->getNumber() < Next->getNumber())) {
29971d5a254SDimitry Andric         Ready.push(Next);
30071d5a254SDimitry Andric         Next = nullptr;
30171d5a254SDimitry Andric         continue;
30271d5a254SDimitry Andric       }
30371d5a254SDimitry Andric       break;
30471d5a254SDimitry Andric     }
30571d5a254SDimitry Andric     // If we didn't find a suitable block in the Preferred list, check the
30671d5a254SDimitry Andric     // general Ready list.
30771d5a254SDimitry Andric     if (!Next) {
30871d5a254SDimitry Andric       // If there are no more blocks to process, we're done.
30971d5a254SDimitry Andric       if (Ready.empty()) {
310e6d15924SDimitry Andric         maybeUpdateTerminator(MBB);
31171d5a254SDimitry Andric         break;
31271d5a254SDimitry Andric       }
31371d5a254SDimitry Andric       for (;;) {
31471d5a254SDimitry Andric         Next = Ready.top();
31571d5a254SDimitry Andric         Ready.pop();
316d8e91e46SDimitry Andric         // If Next isn't dominated by the top active region header, defer it
317d8e91e46SDimitry Andric         // until that region is done.
318d8e91e46SDimitry Andric         if (!Entries.empty() &&
319d8e91e46SDimitry Andric             !MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
320d8e91e46SDimitry Andric           Entries.back().Deferred.push_back(Next);
32171d5a254SDimitry Andric           continue;
32271d5a254SDimitry Andric         }
32371d5a254SDimitry Andric         break;
32471d5a254SDimitry Andric       }
32571d5a254SDimitry Andric     }
32671d5a254SDimitry Andric     // Move the next block into place and iterate.
32771d5a254SDimitry Andric     Next->moveAfter(MBB);
328e6d15924SDimitry Andric     maybeUpdateTerminator(MBB);
32971d5a254SDimitry Andric     MBB = Next;
33071d5a254SDimitry Andric   }
331d8e91e46SDimitry Andric   assert(Entries.empty() && "Active sort region list not finished");
33271d5a254SDimitry Andric   MF.RenumberBlocks();
33371d5a254SDimitry Andric 
33471d5a254SDimitry Andric #ifndef NDEBUG
335b60736ecSDimitry Andric   SmallSetVector<const SortRegion *, 8> OnStack;
33671d5a254SDimitry Andric 
33771d5a254SDimitry Andric   // Insert a sentinel representing the degenerate loop that starts at the
33871d5a254SDimitry Andric   // function entry block and includes the entire function as a "loop" that
33971d5a254SDimitry Andric   // executes once.
34071d5a254SDimitry Andric   OnStack.insert(nullptr);
34171d5a254SDimitry Andric 
34271d5a254SDimitry Andric   for (auto &MBB : MF) {
34371d5a254SDimitry Andric     assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
344b60736ecSDimitry Andric     const SortRegion *Region = SRI.getRegionFor(&MBB);
34571d5a254SDimitry Andric 
346d8e91e46SDimitry Andric     if (Region && &MBB == Region->getHeader()) {
347cfca06d7SDimitry Andric       // Region header.
348d8e91e46SDimitry Andric       if (Region->isLoop()) {
349d8e91e46SDimitry Andric         // Loop header. The loop predecessor should be sorted above, and the
350d8e91e46SDimitry Andric         // other predecessors should be backedges below.
351e3b55780SDimitry Andric         for (auto *Pred : MBB.predecessors())
35271d5a254SDimitry Andric           assert(
353d8e91e46SDimitry Andric               (Pred->getNumber() < MBB.getNumber() || Region->contains(Pred)) &&
354d8e91e46SDimitry Andric               "Loop header predecessors must be loop predecessors or "
355d8e91e46SDimitry Andric               "backedges");
35671d5a254SDimitry Andric       } else {
357cfca06d7SDimitry Andric         // Exception header. All predecessors should be sorted above.
358e3b55780SDimitry Andric         for (auto *Pred : MBB.predecessors())
35971d5a254SDimitry Andric           assert(Pred->getNumber() < MBB.getNumber() &&
36071d5a254SDimitry Andric                  "Non-loop-header predecessors should be topologically sorted");
361d8e91e46SDimitry Andric       }
362d8e91e46SDimitry Andric       assert(OnStack.insert(Region) &&
363d8e91e46SDimitry Andric              "Regions should be declared at most once.");
364d8e91e46SDimitry Andric 
365d8e91e46SDimitry Andric     } else {
366cfca06d7SDimitry Andric       // Not a region header. All predecessors should be sorted above.
367e3b55780SDimitry Andric       for (auto *Pred : MBB.predecessors())
368d8e91e46SDimitry Andric         assert(Pred->getNumber() < MBB.getNumber() &&
369d8e91e46SDimitry Andric                "Non-loop-header predecessors should be topologically sorted");
370b60736ecSDimitry Andric       assert(OnStack.count(SRI.getRegionFor(&MBB)) &&
371d8e91e46SDimitry Andric              "Blocks must be nested in their regions");
37271d5a254SDimitry Andric     }
373b60736ecSDimitry Andric     while (OnStack.size() > 1 && &MBB == SRI.getBottom(OnStack.back()))
37471d5a254SDimitry Andric       OnStack.pop_back();
37571d5a254SDimitry Andric   }
37671d5a254SDimitry Andric   assert(OnStack.pop_back_val() == nullptr &&
377d8e91e46SDimitry Andric          "The function entry block shouldn't actually be a region header");
37871d5a254SDimitry Andric   assert(OnStack.empty() &&
37971d5a254SDimitry Andric          "Control flow stack pushes and pops should be balanced.");
38071d5a254SDimitry Andric #endif
38171d5a254SDimitry Andric }
38271d5a254SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)38371d5a254SDimitry Andric bool WebAssemblyCFGSort::runOnMachineFunction(MachineFunction &MF) {
384eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "********** CFG Sorting **********\n"
38571d5a254SDimitry Andric                        "********** Function: "
38671d5a254SDimitry Andric                     << MF.getName() << '\n');
38771d5a254SDimitry Andric 
388ac9a064cSDimitry Andric   const auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
389d8e91e46SDimitry Andric   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
390ac9a064cSDimitry Andric   auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
39171d5a254SDimitry Andric   // Liveness is not tracked for VALUE_STACK physreg.
39271d5a254SDimitry Andric   MF.getRegInfo().invalidateLiveness();
39371d5a254SDimitry Andric 
394d8e91e46SDimitry Andric   // Sort the blocks, with contiguous sort regions.
395e6d15924SDimitry Andric   sortBlocks(MF, MLI, WEI, MDT);
39671d5a254SDimitry Andric 
39771d5a254SDimitry Andric   return true;
39871d5a254SDimitry Andric }
399