1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2950a13cfSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6950a13cfSDan Gohman //
7950a13cfSDan Gohman //===----------------------------------------------------------------------===//
8950a13cfSDan Gohman ///
9950a13cfSDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file implements a CFG stacking pass.
11950a13cfSDan Gohman ///
12e76fa9ecSHeejin Ahn /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes,
13e76fa9ecSHeejin Ahn /// since scope boundaries serve as the labels for WebAssembly's control
14e76fa9ecSHeejin Ahn /// transfers.
15950a13cfSDan Gohman ///
16950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on
17950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry.
18950a13cfSDan Gohman ///
19e76fa9ecSHeejin Ahn /// In case we use exceptions, this pass also fixes mismatches in unwind
20e76fa9ecSHeejin Ahn /// destinations created during transforming CFG into wasm structured format.
21e76fa9ecSHeejin Ahn ///
22950a13cfSDan Gohman //===----------------------------------------------------------------------===//
23950a13cfSDan Gohman 
246bda14b3SChandler Carruth #include "WebAssembly.h"
25e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h"
26ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
27276f9e8cSHeejin Ahn #include "WebAssemblySortRegion.h"
28950a13cfSDan Gohman #include "WebAssemblySubtarget.h"
294fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
30c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h"
3132807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
32950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
33904cd3e0SReid Kleckner #include "llvm/CodeGen/MachineLoopInfo.h"
34e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h"
35fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h"
36950a13cfSDan Gohman using namespace llvm;
37276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo;
38950a13cfSDan Gohman 
39950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify"
40950a13cfSDan Gohman 
41c4ac74fbSHeejin Ahn STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found");
42c4ac74fbSHeejin Ahn 
43950a13cfSDan Gohman namespace {
44950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass {
45117296c0SMehdi Amini   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
46950a13cfSDan Gohman 
47950a13cfSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
4832807932SDan Gohman     AU.addRequired<MachineDominatorTree>();
49950a13cfSDan Gohman     AU.addRequired<MachineLoopInfo>();
50e76fa9ecSHeejin Ahn     AU.addRequired<WebAssemblyExceptionInfo>();
51950a13cfSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
52950a13cfSDan Gohman   }
53950a13cfSDan Gohman 
54950a13cfSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
55950a13cfSDan Gohman 
56e76fa9ecSHeejin Ahn   // For each block whose label represents the end of a scope, record the block
57e76fa9ecSHeejin Ahn   // which holds the beginning of the scope. This will allow us to quickly skip
58e76fa9ecSHeejin Ahn   // over scoped regions when walking blocks.
59e76fa9ecSHeejin Ahn   SmallVector<MachineBasicBlock *, 8> ScopeTops;
601cc52357SHeejin Ahn   void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) {
611cc52357SHeejin Ahn     int EndNo = End->getNumber();
621cc52357SHeejin Ahn     if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > Begin->getNumber())
631cc52357SHeejin Ahn       ScopeTops[EndNo] = Begin;
641cc52357SHeejin Ahn   }
65e76fa9ecSHeejin Ahn 
66c4ac74fbSHeejin Ahn   // Placing markers.
67e76fa9ecSHeejin Ahn   void placeMarkers(MachineFunction &MF);
68e76fa9ecSHeejin Ahn   void placeBlockMarker(MachineBasicBlock &MBB);
69e76fa9ecSHeejin Ahn   void placeLoopMarker(MachineBasicBlock &MBB);
70e76fa9ecSHeejin Ahn   void placeTryMarker(MachineBasicBlock &MBB);
71cf699b45SHeejin Ahn   void removeUnnecessaryInstrs(MachineFunction &MF);
72c4ac74fbSHeejin Ahn   bool fixUnwindMismatches(MachineFunction &MF);
73e76fa9ecSHeejin Ahn   void rewriteDepthImmediates(MachineFunction &MF);
74e76fa9ecSHeejin Ahn   void fixEndsAtEndOfFunction(MachineFunction &MF);
75e76fa9ecSHeejin Ahn 
76e76fa9ecSHeejin Ahn   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY).
77e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
78e76fa9ecSHeejin Ahn   // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY.
79e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
80e76fa9ecSHeejin Ahn   // <TRY marker, EH pad> map
81e76fa9ecSHeejin Ahn   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
82e76fa9ecSHeejin Ahn   // <EH pad, TRY marker> map
83e76fa9ecSHeejin Ahn   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
84e76fa9ecSHeejin Ahn 
85c4ac74fbSHeejin Ahn   // There can be an appendix block at the end of each function, shared for:
86c4ac74fbSHeejin Ahn   // - creating a correct signature for fallthrough returns
87c4ac74fbSHeejin Ahn   // - target for rethrows that need to unwind to the caller, but are trapped
88c4ac74fbSHeejin Ahn   //   inside another try/catch
89c4ac74fbSHeejin Ahn   MachineBasicBlock *AppendixBB = nullptr;
90c4ac74fbSHeejin Ahn   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
91c4ac74fbSHeejin Ahn     if (!AppendixBB) {
92c4ac74fbSHeejin Ahn       AppendixBB = MF.CreateMachineBasicBlock();
93c4ac74fbSHeejin Ahn       // Give it a fake predecessor so that AsmPrinter prints its label.
94c4ac74fbSHeejin Ahn       AppendixBB->addSuccessor(AppendixBB);
95c4ac74fbSHeejin Ahn       MF.push_back(AppendixBB);
96c4ac74fbSHeejin Ahn     }
97c4ac74fbSHeejin Ahn     return AppendixBB;
98c4ac74fbSHeejin Ahn   }
99c4ac74fbSHeejin Ahn 
100cf699b45SHeejin Ahn   // Helper functions to register / unregister scope information created by
101cf699b45SHeejin Ahn   // marker instructions.
102e76fa9ecSHeejin Ahn   void registerScope(MachineInstr *Begin, MachineInstr *End);
103e76fa9ecSHeejin Ahn   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
104e76fa9ecSHeejin Ahn                         MachineBasicBlock *EHPad);
105cf699b45SHeejin Ahn   void unregisterScope(MachineInstr *Begin);
106e76fa9ecSHeejin Ahn 
107950a13cfSDan Gohman public:
108950a13cfSDan Gohman   static char ID; // Pass identification, replacement for typeid
109950a13cfSDan Gohman   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
110e76fa9ecSHeejin Ahn   ~WebAssemblyCFGStackify() override { releaseMemory(); }
111e76fa9ecSHeejin Ahn   void releaseMemory() override;
112950a13cfSDan Gohman };
113950a13cfSDan Gohman } // end anonymous namespace
114950a13cfSDan Gohman 
115950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0;
11640926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
117c4ac74fbSHeejin Ahn                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
118f208f631SHeejin Ahn                 false)
11940926451SJacob Gravelle 
120950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() {
121950a13cfSDan Gohman   return new WebAssemblyCFGStackify();
122950a13cfSDan Gohman }
123950a13cfSDan Gohman 
124b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as
125b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized
126b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough
127b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any
128b3aa1ecaSDan Gohman /// explicit mentions.
12918c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
13035e4a289SDan Gohman                                  MachineBasicBlock *MBB) {
131b3aa1ecaSDan Gohman   for (MachineInstr &MI : Pred->terminators())
132b3aa1ecaSDan Gohman     for (MachineOperand &MO : MI.explicit_operands())
133b3aa1ecaSDan Gohman       if (MO.isMBB() && MO.getMBB() == MBB)
134b3aa1ecaSDan Gohman         return true;
135b3aa1ecaSDan Gohman   return false;
136b3aa1ecaSDan Gohman }
137b3aa1ecaSDan Gohman 
138e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB,
139e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
140e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
141e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only
142e76fa9ecSHeejin Ahn // used for sanity checking.
1431cc52357SHeejin Ahn template <typename Container>
144e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
1451cc52357SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
1461cc52357SHeejin Ahn                      const Container &AfterSet) {
147e76fa9ecSHeejin Ahn   auto InsertPos = MBB->end();
148e76fa9ecSHeejin Ahn   while (InsertPos != MBB->begin()) {
149e76fa9ecSHeejin Ahn     if (BeforeSet.count(&*std::prev(InsertPos))) {
150e76fa9ecSHeejin Ahn #ifndef NDEBUG
151e76fa9ecSHeejin Ahn       // Sanity check
152e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
153e76fa9ecSHeejin Ahn         assert(!AfterSet.count(&*std::prev(Pos)));
154e76fa9ecSHeejin Ahn #endif
155e76fa9ecSHeejin Ahn       break;
156e76fa9ecSHeejin Ahn     }
157e76fa9ecSHeejin Ahn     --InsertPos;
158e76fa9ecSHeejin Ahn   }
159e76fa9ecSHeejin Ahn   return InsertPos;
160e76fa9ecSHeejin Ahn }
161e76fa9ecSHeejin Ahn 
162e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB,
163e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
164e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains
165e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only
166e76fa9ecSHeejin Ahn // used for sanity checking.
1671cc52357SHeejin Ahn template <typename Container>
168e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator
1691cc52357SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
1701cc52357SHeejin Ahn                    const Container &AfterSet) {
171e76fa9ecSHeejin Ahn   auto InsertPos = MBB->begin();
172e76fa9ecSHeejin Ahn   while (InsertPos != MBB->end()) {
173e76fa9ecSHeejin Ahn     if (AfterSet.count(&*InsertPos)) {
174e76fa9ecSHeejin Ahn #ifndef NDEBUG
175e76fa9ecSHeejin Ahn       // Sanity check
176e76fa9ecSHeejin Ahn       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
177e76fa9ecSHeejin Ahn         assert(!BeforeSet.count(&*Pos));
178e76fa9ecSHeejin Ahn #endif
179e76fa9ecSHeejin Ahn       break;
180e76fa9ecSHeejin Ahn     }
181e76fa9ecSHeejin Ahn     ++InsertPos;
182e76fa9ecSHeejin Ahn   }
183e76fa9ecSHeejin Ahn   return InsertPos;
184e76fa9ecSHeejin Ahn }
185e76fa9ecSHeejin Ahn 
186e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
187e76fa9ecSHeejin Ahn                                            MachineInstr *End) {
188e76fa9ecSHeejin Ahn   BeginToEnd[Begin] = End;
189e76fa9ecSHeejin Ahn   EndToBegin[End] = Begin;
190e76fa9ecSHeejin Ahn }
191e76fa9ecSHeejin Ahn 
192e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
193e76fa9ecSHeejin Ahn                                               MachineInstr *End,
194e76fa9ecSHeejin Ahn                                               MachineBasicBlock *EHPad) {
195e76fa9ecSHeejin Ahn   registerScope(Begin, End);
196e76fa9ecSHeejin Ahn   TryToEHPad[Begin] = EHPad;
197e76fa9ecSHeejin Ahn   EHPadToTry[EHPad] = Begin;
198e76fa9ecSHeejin Ahn }
199e76fa9ecSHeejin Ahn 
200cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
201cf699b45SHeejin Ahn   assert(BeginToEnd.count(Begin));
202cf699b45SHeejin Ahn   MachineInstr *End = BeginToEnd[Begin];
203cf699b45SHeejin Ahn   assert(EndToBegin.count(End));
204cf699b45SHeejin Ahn   BeginToEnd.erase(Begin);
205cf699b45SHeejin Ahn   EndToBegin.erase(End);
206cf699b45SHeejin Ahn   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
207cf699b45SHeejin Ahn   if (EHPad) {
208cf699b45SHeejin Ahn     assert(EHPadToTry.count(EHPad));
209cf699b45SHeejin Ahn     TryToEHPad.erase(Begin);
210cf699b45SHeejin Ahn     EHPadToTry.erase(EHPad);
211cf699b45SHeejin Ahn   }
212cf699b45SHeejin Ahn }
213cf699b45SHeejin Ahn 
21432807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed).
215c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and
216c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later.
217e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
21844a5a4b1SHeejin Ahn   assert(!MBB.isEHPad());
219e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
220e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
221e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
222e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
223e76fa9ecSHeejin Ahn 
2248fe7e86bSDan Gohman   // First compute the nearest common dominator of all forward non-fallthrough
2258fe7e86bSDan Gohman   // predecessors so that we minimize the time that the BLOCK is on the stack,
2268fe7e86bSDan Gohman   // which reduces overall stack height.
22732807932SDan Gohman   MachineBasicBlock *Header = nullptr;
22832807932SDan Gohman   bool IsBranchedTo = false;
22932807932SDan Gohman   int MBBNumber = MBB.getNumber();
230e76fa9ecSHeejin Ahn   for (MachineBasicBlock *Pred : MBB.predecessors()) {
23132807932SDan Gohman     if (Pred->getNumber() < MBBNumber) {
23232807932SDan Gohman       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
23352e240a0SHeejin Ahn       if (explicitlyBranchesTo(Pred, &MBB))
23432807932SDan Gohman         IsBranchedTo = true;
23532807932SDan Gohman     }
236e76fa9ecSHeejin Ahn   }
23732807932SDan Gohman   if (!Header)
23832807932SDan Gohman     return;
23932807932SDan Gohman   if (!IsBranchedTo)
24032807932SDan Gohman     return;
24132807932SDan Gohman 
2428fe7e86bSDan Gohman   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
2435c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
2448fe7e86bSDan Gohman 
2458fe7e86bSDan Gohman   // If the nearest common dominator is inside a more deeply nested context,
2468fe7e86bSDan Gohman   // walk out to the nearest scope which isn't more deeply nested.
2478fe7e86bSDan Gohman   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
2488fe7e86bSDan Gohman     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
2498fe7e86bSDan Gohman       if (ScopeTop->getNumber() > Header->getNumber()) {
2508fe7e86bSDan Gohman         // Skip over an intervening scope.
2515c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
2528fe7e86bSDan Gohman       } else {
2538fe7e86bSDan Gohman         // We found a scope level at an appropriate depth.
2548fe7e86bSDan Gohman         Header = ScopeTop;
2558fe7e86bSDan Gohman         break;
2568fe7e86bSDan Gohman       }
2578fe7e86bSDan Gohman     }
2588fe7e86bSDan Gohman   }
2598fe7e86bSDan Gohman 
2608fe7e86bSDan Gohman   // Decide where in Header to put the BLOCK.
261e76fa9ecSHeejin Ahn 
262e76fa9ecSHeejin Ahn   // Instructions that should go before the BLOCK.
263e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
264e76fa9ecSHeejin Ahn   // Instructions that should go after the BLOCK.
265e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
266e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
26744a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
26844a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the BLOCK, because the loop is
26944a5a4b1SHeejin Ahn     // nested in this BLOCK. Otherwise it should be before the BLOCK.
27044a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
27144a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
27244a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
273e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
274e76fa9ecSHeejin Ahn #ifndef NDEBUG
275e76fa9ecSHeejin Ahn       else
276e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
277e76fa9ecSHeejin Ahn #endif
278e76fa9ecSHeejin Ahn     }
279e76fa9ecSHeejin Ahn 
280834debffSHeejin Ahn     // If there is a previously placed BLOCK/TRY marker and its corresponding
281834debffSHeejin Ahn     // END marker is before the current BLOCK's END marker, that should be
282834debffSHeejin Ahn     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
283834debffSHeejin Ahn     // marker.
28444a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
285834debffSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY) {
286834debffSHeejin Ahn       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
287e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
288834debffSHeejin Ahn #ifndef NDEBUG
289834debffSHeejin Ahn       else
290834debffSHeejin Ahn         BeforeSet.insert(&MI);
291834debffSHeejin Ahn #endif
292834debffSHeejin Ahn     }
293e76fa9ecSHeejin Ahn 
294e76fa9ecSHeejin Ahn #ifndef NDEBUG
295e76fa9ecSHeejin Ahn     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
296e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
297e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
298e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
299e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
300e76fa9ecSHeejin Ahn #endif
301e76fa9ecSHeejin Ahn 
302e76fa9ecSHeejin Ahn     // Terminators should go after the BLOCK.
303e76fa9ecSHeejin Ahn     if (MI.isTerminator())
304e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
305e76fa9ecSHeejin Ahn   }
306e76fa9ecSHeejin Ahn 
307e76fa9ecSHeejin Ahn   // Local expression tree should go after the BLOCK.
308e76fa9ecSHeejin Ahn   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
309e76fa9ecSHeejin Ahn        --I) {
310409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
311409b4391SYury Delendik       continue;
312e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
313e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
314e76fa9ecSHeejin Ahn     else
315e76fa9ecSHeejin Ahn       break;
31632807932SDan Gohman   }
31732807932SDan Gohman 
3188fe7e86bSDan Gohman   // Add the BLOCK.
3192cb27072SThomas Lively   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
32018c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
32192401cc1SHeejin Ahn   MachineInstr *Begin =
32292401cc1SHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
3232726b88cSDan Gohman               TII.get(WebAssembly::BLOCK))
324d6f48786SHeejin Ahn           .addImm(int64_t(ReturnType));
3251d68e80fSDan Gohman 
326e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_BLOCK.
327e76fa9ecSHeejin Ahn   BeforeSet.clear();
328e76fa9ecSHeejin Ahn   AfterSet.clear();
329e76fa9ecSHeejin Ahn   for (auto &MI : MBB) {
330e76fa9ecSHeejin Ahn #ifndef NDEBUG
331e76fa9ecSHeejin Ahn     // END_BLOCK should precede existing LOOP and TRY markers.
332e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
333e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
334e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
335e76fa9ecSHeejin Ahn #endif
336e76fa9ecSHeejin Ahn 
337e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and the header of the
338e76fa9ecSHeejin Ahn     // loop is above this block's header, the END_LOOP should be placed after
339e76fa9ecSHeejin Ahn     // the BLOCK, because the loop contains this block. Otherwise the END_LOOP
340e76fa9ecSHeejin Ahn     // should be placed before the BLOCK. The same for END_TRY.
341e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP ||
342e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY) {
343e76fa9ecSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
344e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
345e76fa9ecSHeejin Ahn #ifndef NDEBUG
346e76fa9ecSHeejin Ahn       else
347e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
348e76fa9ecSHeejin Ahn #endif
349e76fa9ecSHeejin Ahn     }
350e76fa9ecSHeejin Ahn   }
351e76fa9ecSHeejin Ahn 
3521d68e80fSDan Gohman   // Mark the end of the block.
35318c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
35410b31358SDerek Schuff   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
3552726b88cSDan Gohman                               TII.get(WebAssembly::END_BLOCK));
356e76fa9ecSHeejin Ahn   registerScope(Begin, End);
3578fe7e86bSDan Gohman 
3588fe7e86bSDan Gohman   // Track the farthest-spanning scope that ends at this point.
3591cc52357SHeejin Ahn   updateScopeTops(Header, &MBB);
360950a13cfSDan Gohman }
361950a13cfSDan Gohman 
3628fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
363e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
364e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
365e76fa9ecSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
366276f9e8cSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
367276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
368e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
369e76fa9ecSHeejin Ahn 
3708fe7e86bSDan Gohman   MachineLoop *Loop = MLI.getLoopFor(&MBB);
3718fe7e86bSDan Gohman   if (!Loop || Loop->getHeader() != &MBB)
3728fe7e86bSDan Gohman     return;
3738fe7e86bSDan Gohman 
3748fe7e86bSDan Gohman   // The operand of a LOOP is the first block after the loop. If the loop is the
3758fe7e86bSDan Gohman   // bottom of the function, insert a dummy block at the end.
376276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
3775c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
378e3e4a5ffSDan Gohman   if (Iter == MF.end()) {
379c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
3805c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
381e3e4a5ffSDan Gohman   }
3828fe7e86bSDan Gohman   MachineBasicBlock *AfterLoop = &*Iter;
383f6857223SDan Gohman 
384e76fa9ecSHeejin Ahn   // Decide where in Header to put the LOOP.
385e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
386e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
387e76fa9ecSHeejin Ahn   for (const auto &MI : MBB) {
388e76fa9ecSHeejin Ahn     // LOOP marker should be after any existing loop that ends here. Otherwise
389e76fa9ecSHeejin Ahn     // we assume the instruction belongs to the loop.
390e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
391e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
392e76fa9ecSHeejin Ahn #ifndef NDEBUG
393e76fa9ecSHeejin Ahn     else
394e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
395e76fa9ecSHeejin Ahn #endif
396e76fa9ecSHeejin Ahn   }
397e76fa9ecSHeejin Ahn 
398e76fa9ecSHeejin Ahn   // Mark the beginning of the loop.
39918c56a07SHeejin Ahn   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
40010b31358SDerek Schuff   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
4012726b88cSDan Gohman                                 TII.get(WebAssembly::LOOP))
4022cb27072SThomas Lively                             .addImm(int64_t(WebAssembly::BlockType::Void));
4031d68e80fSDan Gohman 
404e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_LOOP.
405e76fa9ecSHeejin Ahn   BeforeSet.clear();
406e76fa9ecSHeejin Ahn   AfterSet.clear();
407e76fa9ecSHeejin Ahn #ifndef NDEBUG
408e76fa9ecSHeejin Ahn   for (const auto &MI : MBB)
409e76fa9ecSHeejin Ahn     // Existing END_LOOP markers belong to parent loops of this loop
410e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP)
411e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
412e76fa9ecSHeejin Ahn #endif
413e76fa9ecSHeejin Ahn 
414e76fa9ecSHeejin Ahn   // Mark the end of the loop (using arbitrary debug location that branched to
415e76fa9ecSHeejin Ahn   // the loop end as its location).
41618c56a07SHeejin Ahn   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
41767f74aceSHeejin Ahn   DebugLoc EndDL = AfterLoop->pred_empty()
41867f74aceSHeejin Ahn                        ? DebugLoc()
41967f74aceSHeejin Ahn                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
420e76fa9ecSHeejin Ahn   MachineInstr *End =
421e76fa9ecSHeejin Ahn       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
422e76fa9ecSHeejin Ahn   registerScope(Begin, End);
4238fe7e86bSDan Gohman 
4248fe7e86bSDan Gohman   assert((!ScopeTops[AfterLoop->getNumber()] ||
4258fe7e86bSDan Gohman           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
426442bfcecSDan Gohman          "With block sorting the outermost loop for a block should be first.");
4271cc52357SHeejin Ahn   updateScopeTops(&MBB, AfterLoop);
428e3e4a5ffSDan Gohman }
429950a13cfSDan Gohman 
430e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
43144a5a4b1SHeejin Ahn   assert(MBB.isEHPad());
432e76fa9ecSHeejin Ahn   MachineFunction &MF = *MBB.getParent();
433e76fa9ecSHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
434e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
435276f9e8cSHeejin Ahn   const auto &MLI = getAnalysis<MachineLoopInfo>();
436e76fa9ecSHeejin Ahn   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
437276f9e8cSHeejin Ahn   SortRegionInfo SRI(MLI, WEI);
438e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
439e76fa9ecSHeejin Ahn 
440e76fa9ecSHeejin Ahn   // Compute the nearest common dominator of all unwind predecessors
441e76fa9ecSHeejin Ahn   MachineBasicBlock *Header = nullptr;
442e76fa9ecSHeejin Ahn   int MBBNumber = MBB.getNumber();
443e76fa9ecSHeejin Ahn   for (auto *Pred : MBB.predecessors()) {
444e76fa9ecSHeejin Ahn     if (Pred->getNumber() < MBBNumber) {
445e76fa9ecSHeejin Ahn       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
44618c56a07SHeejin Ahn       assert(!explicitlyBranchesTo(Pred, &MBB) &&
447e76fa9ecSHeejin Ahn              "Explicit branch to an EH pad!");
448e76fa9ecSHeejin Ahn     }
449e76fa9ecSHeejin Ahn   }
450e76fa9ecSHeejin Ahn   if (!Header)
451e76fa9ecSHeejin Ahn     return;
452e76fa9ecSHeejin Ahn 
453e76fa9ecSHeejin Ahn   // If this try is at the bottom of the function, insert a dummy block at the
454e76fa9ecSHeejin Ahn   // end.
455e76fa9ecSHeejin Ahn   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
456e76fa9ecSHeejin Ahn   assert(WE);
457276f9e8cSHeejin Ahn   MachineBasicBlock *Bottom = SRI.getBottom(WE);
458e76fa9ecSHeejin Ahn 
4595c644c9bSHeejin Ahn   auto Iter = std::next(Bottom->getIterator());
460e76fa9ecSHeejin Ahn   if (Iter == MF.end()) {
461c4ac74fbSHeejin Ahn     getAppendixBlock(MF);
4625c644c9bSHeejin Ahn     Iter = std::next(Bottom->getIterator());
463e76fa9ecSHeejin Ahn   }
46420cf0749SHeejin Ahn   MachineBasicBlock *Cont = &*Iter;
465e76fa9ecSHeejin Ahn 
46620cf0749SHeejin Ahn   assert(Cont != &MF.front());
4675c644c9bSHeejin Ahn   MachineBasicBlock *LayoutPred = Cont->getPrevNode();
468e76fa9ecSHeejin Ahn 
469e76fa9ecSHeejin Ahn   // If the nearest common dominator is inside a more deeply nested context,
470e76fa9ecSHeejin Ahn   // walk out to the nearest scope which isn't more deeply nested.
471e76fa9ecSHeejin Ahn   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
472e76fa9ecSHeejin Ahn     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
473e76fa9ecSHeejin Ahn       if (ScopeTop->getNumber() > Header->getNumber()) {
474e76fa9ecSHeejin Ahn         // Skip over an intervening scope.
4755c644c9bSHeejin Ahn         I = std::next(ScopeTop->getIterator());
476e76fa9ecSHeejin Ahn       } else {
477e76fa9ecSHeejin Ahn         // We found a scope level at an appropriate depth.
478e76fa9ecSHeejin Ahn         Header = ScopeTop;
479e76fa9ecSHeejin Ahn         break;
480e76fa9ecSHeejin Ahn       }
481e76fa9ecSHeejin Ahn     }
482e76fa9ecSHeejin Ahn   }
483e76fa9ecSHeejin Ahn 
484e76fa9ecSHeejin Ahn   // Decide where in Header to put the TRY.
485e76fa9ecSHeejin Ahn 
48644a5a4b1SHeejin Ahn   // Instructions that should go before the TRY.
487e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
48844a5a4b1SHeejin Ahn   // Instructions that should go after the TRY.
489e76fa9ecSHeejin Ahn   SmallPtrSet<const MachineInstr *, 4> AfterSet;
490e76fa9ecSHeejin Ahn   for (const auto &MI : *Header) {
49144a5a4b1SHeejin Ahn     // If there is a previously placed LOOP marker and the bottom block of the
49244a5a4b1SHeejin Ahn     // loop is above MBB, it should be after the TRY, because the loop is nested
49344a5a4b1SHeejin Ahn     // in this TRY. Otherwise it should be before the TRY.
494e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP) {
49544a5a4b1SHeejin Ahn       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
49644a5a4b1SHeejin Ahn       if (MBB.getNumber() > LoopBottom->getNumber())
497e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
498e76fa9ecSHeejin Ahn #ifndef NDEBUG
499e76fa9ecSHeejin Ahn       else
500e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
501e76fa9ecSHeejin Ahn #endif
502e76fa9ecSHeejin Ahn     }
503e76fa9ecSHeejin Ahn 
50444a5a4b1SHeejin Ahn     // All previously inserted BLOCK/TRY markers should be after the TRY because
50544a5a4b1SHeejin Ahn     // they are all nested trys.
50644a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::BLOCK ||
50744a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::TRY)
508e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
509e76fa9ecSHeejin Ahn 
510e76fa9ecSHeejin Ahn #ifndef NDEBUG
51144a5a4b1SHeejin Ahn     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
51244a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
51344a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::END_LOOP ||
514e76fa9ecSHeejin Ahn         MI.getOpcode() == WebAssembly::END_TRY)
515e76fa9ecSHeejin Ahn       BeforeSet.insert(&MI);
516e76fa9ecSHeejin Ahn #endif
517e76fa9ecSHeejin Ahn 
518e76fa9ecSHeejin Ahn     // Terminators should go after the TRY.
519e76fa9ecSHeejin Ahn     if (MI.isTerminator())
520e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
521e76fa9ecSHeejin Ahn   }
522e76fa9ecSHeejin Ahn 
5236a37c5d6SHeejin Ahn   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
5246a37c5d6SHeejin Ahn   // contain the call within it. So the call should go after the TRY. The
5256a37c5d6SHeejin Ahn   // exception is when the header's terminator is a rethrow instruction, in
5266a37c5d6SHeejin Ahn   // which case that instruction, not a call instruction before it, is gonna
5276a37c5d6SHeejin Ahn   // throw.
5286a37c5d6SHeejin Ahn   MachineInstr *ThrowingCall = nullptr;
5296a37c5d6SHeejin Ahn   if (MBB.isPredecessor(Header)) {
5306a37c5d6SHeejin Ahn     auto TermPos = Header->getFirstTerminator();
5316a37c5d6SHeejin Ahn     if (TermPos == Header->end() ||
5326a37c5d6SHeejin Ahn         TermPos->getOpcode() != WebAssembly::RETHROW) {
5336a37c5d6SHeejin Ahn       for (auto &MI : reverse(*Header)) {
5346a37c5d6SHeejin Ahn         if (MI.isCall()) {
5356a37c5d6SHeejin Ahn           AfterSet.insert(&MI);
5366a37c5d6SHeejin Ahn           ThrowingCall = &MI;
5376a37c5d6SHeejin Ahn           // Possibly throwing calls are usually wrapped by EH_LABEL
5386a37c5d6SHeejin Ahn           // instructions. We don't want to split them and the call.
5396a37c5d6SHeejin Ahn           if (MI.getIterator() != Header->begin() &&
5406a37c5d6SHeejin Ahn               std::prev(MI.getIterator())->isEHLabel()) {
5416a37c5d6SHeejin Ahn             AfterSet.insert(&*std::prev(MI.getIterator()));
5426a37c5d6SHeejin Ahn             ThrowingCall = &*std::prev(MI.getIterator());
5436a37c5d6SHeejin Ahn           }
5446a37c5d6SHeejin Ahn           break;
5456a37c5d6SHeejin Ahn         }
5466a37c5d6SHeejin Ahn       }
5476a37c5d6SHeejin Ahn     }
5486a37c5d6SHeejin Ahn   }
5496a37c5d6SHeejin Ahn 
550e76fa9ecSHeejin Ahn   // Local expression tree should go after the TRY.
5516a37c5d6SHeejin Ahn   // For BLOCK placement, we start the search from the previous instruction of a
5526a37c5d6SHeejin Ahn   // BB's terminator, but in TRY's case, we should start from the previous
5536a37c5d6SHeejin Ahn   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
5546a37c5d6SHeejin Ahn   // because the return values of the call's previous instructions can be
5556a37c5d6SHeejin Ahn   // stackified and consumed by the throwing call.
5566a37c5d6SHeejin Ahn   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
5576a37c5d6SHeejin Ahn                                     : Header->getFirstTerminator();
5586a37c5d6SHeejin Ahn   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
559409b4391SYury Delendik     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
560409b4391SYury Delendik       continue;
561e76fa9ecSHeejin Ahn     if (WebAssembly::isChild(*std::prev(I), MFI))
562e76fa9ecSHeejin Ahn       AfterSet.insert(&*std::prev(I));
563e76fa9ecSHeejin Ahn     else
564e76fa9ecSHeejin Ahn       break;
565e76fa9ecSHeejin Ahn   }
566e76fa9ecSHeejin Ahn 
567e76fa9ecSHeejin Ahn   // Add the TRY.
56818c56a07SHeejin Ahn   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
569e76fa9ecSHeejin Ahn   MachineInstr *Begin =
570e76fa9ecSHeejin Ahn       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
571e76fa9ecSHeejin Ahn               TII.get(WebAssembly::TRY))
5722cb27072SThomas Lively           .addImm(int64_t(WebAssembly::BlockType::Void));
573e76fa9ecSHeejin Ahn 
574e76fa9ecSHeejin Ahn   // Decide where in Header to put the END_TRY.
575e76fa9ecSHeejin Ahn   BeforeSet.clear();
576e76fa9ecSHeejin Ahn   AfterSet.clear();
57720cf0749SHeejin Ahn   for (const auto &MI : *Cont) {
578e76fa9ecSHeejin Ahn #ifndef NDEBUG
57944a5a4b1SHeejin Ahn     // END_TRY should precede existing LOOP and BLOCK markers.
58044a5a4b1SHeejin Ahn     if (MI.getOpcode() == WebAssembly::LOOP ||
58144a5a4b1SHeejin Ahn         MI.getOpcode() == WebAssembly::BLOCK)
582e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
583e76fa9ecSHeejin Ahn 
584e76fa9ecSHeejin Ahn     // All END_TRY markers placed earlier belong to exceptions that contains
585e76fa9ecSHeejin Ahn     // this one.
586e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_TRY)
587e76fa9ecSHeejin Ahn       AfterSet.insert(&MI);
588e76fa9ecSHeejin Ahn #endif
589e76fa9ecSHeejin Ahn 
590e76fa9ecSHeejin Ahn     // If there is a previously placed END_LOOP marker and its header is after
591e76fa9ecSHeejin Ahn     // where TRY marker is, this loop is contained within the 'catch' part, so
592e76fa9ecSHeejin Ahn     // the END_TRY marker should go after that. Otherwise, the whole try-catch
593e76fa9ecSHeejin Ahn     // is contained within this loop, so the END_TRY should go before that.
594e76fa9ecSHeejin Ahn     if (MI.getOpcode() == WebAssembly::END_LOOP) {
595222718fdSHeejin Ahn       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
596222718fdSHeejin Ahn       // are in the same BB, LOOP is always before TRY.
597222718fdSHeejin Ahn       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
598e76fa9ecSHeejin Ahn         BeforeSet.insert(&MI);
599e76fa9ecSHeejin Ahn #ifndef NDEBUG
600e76fa9ecSHeejin Ahn       else
601e76fa9ecSHeejin Ahn         AfterSet.insert(&MI);
602e76fa9ecSHeejin Ahn #endif
603e76fa9ecSHeejin Ahn     }
60444a5a4b1SHeejin Ahn 
60544a5a4b1SHeejin Ahn     // It is not possible for an END_BLOCK to be already in this block.
606e76fa9ecSHeejin Ahn   }
607e76fa9ecSHeejin Ahn 
608e76fa9ecSHeejin Ahn   // Mark the end of the TRY.
60920cf0749SHeejin Ahn   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
610e76fa9ecSHeejin Ahn   MachineInstr *End =
61120cf0749SHeejin Ahn       BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
612e76fa9ecSHeejin Ahn               TII.get(WebAssembly::END_TRY));
613e76fa9ecSHeejin Ahn   registerTryScope(Begin, End, &MBB);
614e76fa9ecSHeejin Ahn 
61582da1ffcSHeejin Ahn   // Track the farthest-spanning scope that ends at this point. We create two
61682da1ffcSHeejin Ahn   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
61782da1ffcSHeejin Ahn   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
61882da1ffcSHeejin Ahn   // markers should not span across 'catch'. For example, this should not
61982da1ffcSHeejin Ahn   // happen:
62082da1ffcSHeejin Ahn   //
62182da1ffcSHeejin Ahn   // try
62282da1ffcSHeejin Ahn   //   block     --|  (X)
62382da1ffcSHeejin Ahn   // catch         |
62482da1ffcSHeejin Ahn   //   end_block --|
62582da1ffcSHeejin Ahn   // end_try
6261cc52357SHeejin Ahn   for (auto *End : {&MBB, Cont})
6271cc52357SHeejin Ahn     updateScopeTops(Header, End);
62882da1ffcSHeejin Ahn }
629e76fa9ecSHeejin Ahn 
630cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
631cf699b45SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
632cf699b45SHeejin Ahn 
633cf699b45SHeejin Ahn   // When there is an unconditional branch right before a catch instruction and
634cf699b45SHeejin Ahn   // it branches to the end of end_try marker, we don't need the branch, because
635cf699b45SHeejin Ahn   // it there is no exception, the control flow transfers to that point anyway.
636cf699b45SHeejin Ahn   // bb0:
637cf699b45SHeejin Ahn   //   try
638cf699b45SHeejin Ahn   //     ...
639cf699b45SHeejin Ahn   //     br bb2      <- Not necessary
640*c93b9559SHeejin Ahn   // bb1 (ehpad):
641cf699b45SHeejin Ahn   //   catch
642cf699b45SHeejin Ahn   //     ...
643*c93b9559SHeejin Ahn   // bb2:            <- Continuation BB
644cf699b45SHeejin Ahn   //   end
645*c93b9559SHeejin Ahn   //
646*c93b9559SHeejin Ahn   // A more involved case: When the BB where 'end' is located is an another EH
647*c93b9559SHeejin Ahn   // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example,
648*c93b9559SHeejin Ahn   // bb0:
649*c93b9559SHeejin Ahn   //   try
650*c93b9559SHeejin Ahn   //     try
651*c93b9559SHeejin Ahn   //       ...
652*c93b9559SHeejin Ahn   //       br bb3      <- Not necessary
653*c93b9559SHeejin Ahn   // bb1 (ehpad):
654*c93b9559SHeejin Ahn   //     catch
655*c93b9559SHeejin Ahn   // bb2 (ehpad):
656*c93b9559SHeejin Ahn   //     end
657*c93b9559SHeejin Ahn   //   catch
658*c93b9559SHeejin Ahn   //     ...
659*c93b9559SHeejin Ahn   // bb3:            <- Continuation BB
660*c93b9559SHeejin Ahn   //   end
661*c93b9559SHeejin Ahn   //
662*c93b9559SHeejin Ahn   // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is
663*c93b9559SHeejin Ahn   // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the
664*c93b9559SHeejin Ahn   // code can be deleted. This is why we run 'while' until 'Cont' is not an EH
665*c93b9559SHeejin Ahn   // pad.
666cf699b45SHeejin Ahn   for (auto &MBB : MF) {
667cf699b45SHeejin Ahn     if (!MBB.isEHPad())
668cf699b45SHeejin Ahn       continue;
669cf699b45SHeejin Ahn 
670cf699b45SHeejin Ahn     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
671cf699b45SHeejin Ahn     SmallVector<MachineOperand, 4> Cond;
6725c644c9bSHeejin Ahn     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
673*c93b9559SHeejin Ahn 
674*c93b9559SHeejin Ahn     MachineBasicBlock *Cont = &MBB;
675*c93b9559SHeejin Ahn     while (Cont->isEHPad()) {
676*c93b9559SHeejin Ahn       MachineInstr *Try = EHPadToTry[Cont];
677*c93b9559SHeejin Ahn       MachineInstr *EndTry = BeginToEnd[Try];
678*c93b9559SHeejin Ahn       Cont = EndTry->getParent();
679*c93b9559SHeejin Ahn     }
680*c93b9559SHeejin Ahn 
681cf699b45SHeejin Ahn     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
6823fe6ea46SHeejin Ahn     // This condition means either
6833fe6ea46SHeejin Ahn     // 1. This BB ends with a single unconditional branch whose destinaion is
6843fe6ea46SHeejin Ahn     //    Cont.
6853fe6ea46SHeejin Ahn     // 2. This BB ends with a conditional branch followed by an unconditional
6863fe6ea46SHeejin Ahn     //    branch, and the unconditional branch's destination is Cont.
6873fe6ea46SHeejin Ahn     // In both cases, we want to remove the last (= unconditional) branch.
688cf699b45SHeejin Ahn     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
6893fe6ea46SHeejin Ahn                        (!Cond.empty() && FBB && FBB == Cont))) {
6903fe6ea46SHeejin Ahn       bool ErasedUncondBr = false;
691a5099ad9SHeejin Ahn       (void)ErasedUncondBr;
6923fe6ea46SHeejin Ahn       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
6933fe6ea46SHeejin Ahn            I != E; --I) {
6943fe6ea46SHeejin Ahn         auto PrevI = std::prev(I);
6953fe6ea46SHeejin Ahn         if (PrevI->isTerminator()) {
6963fe6ea46SHeejin Ahn           assert(PrevI->getOpcode() == WebAssembly::BR);
6973fe6ea46SHeejin Ahn           PrevI->eraseFromParent();
6983fe6ea46SHeejin Ahn           ErasedUncondBr = true;
6993fe6ea46SHeejin Ahn           break;
7003fe6ea46SHeejin Ahn         }
7013fe6ea46SHeejin Ahn       }
7023fe6ea46SHeejin Ahn       assert(ErasedUncondBr && "Unconditional branch not erased!");
7033fe6ea46SHeejin Ahn     }
704cf699b45SHeejin Ahn   }
705cf699b45SHeejin Ahn 
706cf699b45SHeejin Ahn   // When there are block / end_block markers that overlap with try / end_try
707cf699b45SHeejin Ahn   // markers, and the block and try markers' return types are the same, the
708cf699b45SHeejin Ahn   // block /end_block markers are not necessary, because try / end_try markers
709cf699b45SHeejin Ahn   // also can serve as boundaries for branches.
710cf699b45SHeejin Ahn   // block         <- Not necessary
711cf699b45SHeejin Ahn   //   try
712cf699b45SHeejin Ahn   //     ...
713cf699b45SHeejin Ahn   //   catch
714cf699b45SHeejin Ahn   //     ...
715cf699b45SHeejin Ahn   //   end
716cf699b45SHeejin Ahn   // end           <- Not necessary
717cf699b45SHeejin Ahn   SmallVector<MachineInstr *, 32> ToDelete;
718cf699b45SHeejin Ahn   for (auto &MBB : MF) {
719cf699b45SHeejin Ahn     for (auto &MI : MBB) {
720cf699b45SHeejin Ahn       if (MI.getOpcode() != WebAssembly::TRY)
721cf699b45SHeejin Ahn         continue;
722cf699b45SHeejin Ahn 
723cf699b45SHeejin Ahn       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
724cf699b45SHeejin Ahn       MachineBasicBlock *TryBB = Try->getParent();
725cf699b45SHeejin Ahn       MachineBasicBlock *Cont = EndTry->getParent();
726cf699b45SHeejin Ahn       int64_t RetType = Try->getOperand(0).getImm();
7275c644c9bSHeejin Ahn       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
728cf699b45SHeejin Ahn            B != TryBB->begin() && E != Cont->end() &&
729cf699b45SHeejin Ahn            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
730cf699b45SHeejin Ahn            E->getOpcode() == WebAssembly::END_BLOCK &&
731cf699b45SHeejin Ahn            std::prev(B)->getOperand(0).getImm() == RetType;
732cf699b45SHeejin Ahn            --B, ++E) {
733cf699b45SHeejin Ahn         ToDelete.push_back(&*std::prev(B));
734cf699b45SHeejin Ahn         ToDelete.push_back(&*E);
735cf699b45SHeejin Ahn       }
736cf699b45SHeejin Ahn     }
737cf699b45SHeejin Ahn   }
738cf699b45SHeejin Ahn   for (auto *MI : ToDelete) {
739cf699b45SHeejin Ahn     if (MI->getOpcode() == WebAssembly::BLOCK)
740cf699b45SHeejin Ahn       unregisterScope(MI);
741cf699b45SHeejin Ahn     MI->eraseFromParent();
742cf699b45SHeejin Ahn   }
743cf699b45SHeejin Ahn }
744cf699b45SHeejin Ahn 
74583c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class.
74683c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) {
74783c26eaeSHeejin Ahn   if (RC == &WebAssembly::I32RegClass)
74883c26eaeSHeejin Ahn     return WebAssembly::COPY_I32;
74983c26eaeSHeejin Ahn   if (RC == &WebAssembly::I64RegClass)
75083c26eaeSHeejin Ahn     return WebAssembly::COPY_I64;
75183c26eaeSHeejin Ahn   if (RC == &WebAssembly::F32RegClass)
75283c26eaeSHeejin Ahn     return WebAssembly::COPY_F32;
75383c26eaeSHeejin Ahn   if (RC == &WebAssembly::F64RegClass)
75483c26eaeSHeejin Ahn     return WebAssembly::COPY_F64;
75583c26eaeSHeejin Ahn   if (RC == &WebAssembly::V128RegClass)
75683c26eaeSHeejin Ahn     return WebAssembly::COPY_V128;
75760653e24SHeejin Ahn   if (RC == &WebAssembly::FUNCREFRegClass)
75860653e24SHeejin Ahn     return WebAssembly::COPY_FUNCREF;
75960653e24SHeejin Ahn   if (RC == &WebAssembly::EXTERNREFRegClass)
76060653e24SHeejin Ahn     return WebAssembly::COPY_EXTERNREF;
76183c26eaeSHeejin Ahn   llvm_unreachable("Unexpected register class");
76283c26eaeSHeejin Ahn }
76383c26eaeSHeejin Ahn 
76461d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that
76561d5c76aSHeejin Ahn // have their uses in Split.
7669e4eadebSHeejin Ahn // FIXME This function will be used when fixing unwind mismatches, but the old
7679e4eadebSHeejin Ahn // version of that function was removed for the moment and the new version has
7689e4eadebSHeejin Ahn // not yet been added. So 'LLVM_ATTRIBUTE_UNUSED' is added to suppress the
7699e4eadebSHeejin Ahn // warning. Remove the attribute after the new functionality is added.
7709e4eadebSHeejin Ahn LLVM_ATTRIBUTE_UNUSED static void
7711cc52357SHeejin Ahn unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, MachineBasicBlock &Split) {
7721cc52357SHeejin Ahn   MachineFunction &MF = *MBB.getParent();
7731cc52357SHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
7741cc52357SHeejin Ahn   auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
7751cc52357SHeejin Ahn   auto &MRI = MF.getRegInfo();
7761cc52357SHeejin Ahn 
77761d5c76aSHeejin Ahn   for (auto &MI : Split) {
77861d5c76aSHeejin Ahn     for (auto &MO : MI.explicit_uses()) {
77961d5c76aSHeejin Ahn       if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg()))
78061d5c76aSHeejin Ahn         continue;
78161d5c76aSHeejin Ahn       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
78261d5c76aSHeejin Ahn         if (Def->getParent() == &MBB)
78361d5c76aSHeejin Ahn           MFI.unstackifyVReg(MO.getReg());
78461d5c76aSHeejin Ahn     }
78561d5c76aSHeejin Ahn   }
78683c26eaeSHeejin Ahn 
78783c26eaeSHeejin Ahn   // In RegStackify, when a register definition is used multiple times,
78883c26eaeSHeejin Ahn   //    Reg = INST ...
78983c26eaeSHeejin Ahn   //    INST ..., Reg, ...
79083c26eaeSHeejin Ahn   //    INST ..., Reg, ...
79183c26eaeSHeejin Ahn   //    INST ..., Reg, ...
79283c26eaeSHeejin Ahn   //
79383c26eaeSHeejin Ahn   // we introduce a TEE, which has the following form:
79483c26eaeSHeejin Ahn   //    DefReg = INST ...
79583c26eaeSHeejin Ahn   //    TeeReg, Reg = TEE_... DefReg
79683c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
79783c26eaeSHeejin Ahn   //    INST ..., Reg, ...
79883c26eaeSHeejin Ahn   //    INST ..., Reg, ...
79983c26eaeSHeejin Ahn   // with DefReg and TeeReg stackified but Reg not stackified.
80083c26eaeSHeejin Ahn   //
80183c26eaeSHeejin Ahn   // But the invariant that TeeReg should be stackified can be violated while we
80283c26eaeSHeejin Ahn   // unstackify registers in the split BB above. In this case, we convert TEEs
80383c26eaeSHeejin Ahn   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
80483c26eaeSHeejin Ahn   //    DefReg = INST ...
80583c26eaeSHeejin Ahn   //    TeeReg = COPY DefReg
80683c26eaeSHeejin Ahn   //    Reg = COPY DefReg
80783c26eaeSHeejin Ahn   //    INST ..., TeeReg, ...
80883c26eaeSHeejin Ahn   //    INST ..., Reg, ...
80983c26eaeSHeejin Ahn   //    INST ..., Reg, ...
81083c26eaeSHeejin Ahn   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
81183c26eaeSHeejin Ahn     MachineInstr &MI = *I++;
81283c26eaeSHeejin Ahn     if (!WebAssembly::isTee(MI.getOpcode()))
81383c26eaeSHeejin Ahn       continue;
81483c26eaeSHeejin Ahn     Register TeeReg = MI.getOperand(0).getReg();
81583c26eaeSHeejin Ahn     Register Reg = MI.getOperand(1).getReg();
81683c26eaeSHeejin Ahn     Register DefReg = MI.getOperand(2).getReg();
81783c26eaeSHeejin Ahn     if (!MFI.isVRegStackified(TeeReg)) {
81883c26eaeSHeejin Ahn       // Now we are not using TEE anymore, so unstackify DefReg too
81983c26eaeSHeejin Ahn       MFI.unstackifyVReg(DefReg);
82083c26eaeSHeejin Ahn       unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg));
82183c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
82283c26eaeSHeejin Ahn           .addReg(DefReg);
82383c26eaeSHeejin Ahn       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
82483c26eaeSHeejin Ahn       MI.eraseFromParent();
82583c26eaeSHeejin Ahn     }
82683c26eaeSHeejin Ahn   }
82761d5c76aSHeejin Ahn }
82861d5c76aSHeejin Ahn 
829c4ac74fbSHeejin Ahn bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) {
8309e4eadebSHeejin Ahn   // TODO Implement this
831c4ac74fbSHeejin Ahn   return false;
832c4ac74fbSHeejin Ahn }
833c4ac74fbSHeejin Ahn 
8341d68e80fSDan Gohman static unsigned
83518c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack,
8361d68e80fSDan Gohman          const MachineBasicBlock *MBB) {
8371d68e80fSDan Gohman   unsigned Depth = 0;
8381d68e80fSDan Gohman   for (auto X : reverse(Stack)) {
8391d68e80fSDan Gohman     if (X == MBB)
8401d68e80fSDan Gohman       break;
8411d68e80fSDan Gohman     ++Depth;
8421d68e80fSDan Gohman   }
8431d68e80fSDan Gohman   assert(Depth < Stack.size() && "Branch destination should be in scope");
8441d68e80fSDan Gohman   return Depth;
8451d68e80fSDan Gohman }
8461d68e80fSDan Gohman 
8472726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable,
8482726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar,
8492726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of
8502726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks
8512726b88cSDan Gohman /// that end at the function end need to have a return type signature that
8522726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function
8532726b88cSDan Gohman /// checks for such cases and fixes up the signatures.
854e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
855e76fa9ecSHeejin Ahn   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
8562726b88cSDan Gohman 
8572726b88cSDan Gohman   if (MFI.getResults().empty())
8582726b88cSDan Gohman     return;
8592726b88cSDan Gohman 
8602cb27072SThomas Lively   // MCInstLower will add the proper types to multivalue signatures based on the
8612cb27072SThomas Lively   // function return type
8622cb27072SThomas Lively   WebAssembly::BlockType RetType =
8632cb27072SThomas Lively       MFI.getResults().size() > 1
8642cb27072SThomas Lively           ? WebAssembly::BlockType::Multivalue
8652cb27072SThomas Lively           : WebAssembly::BlockType(
8662cb27072SThomas Lively                 WebAssembly::toValType(MFI.getResults().front()));
8672726b88cSDan Gohman 
868d25c17f3SHeejin Ahn   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
869d25c17f3SHeejin Ahn   Worklist.push_back(MF.rbegin()->rbegin());
870d25c17f3SHeejin Ahn 
871d25c17f3SHeejin Ahn   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
872d25c17f3SHeejin Ahn     auto *MBB = It->getParent();
873d25c17f3SHeejin Ahn     while (It != MBB->rend()) {
874d25c17f3SHeejin Ahn       MachineInstr &MI = *It++;
875801bf7ebSShiva Chen       if (MI.isPosition() || MI.isDebugInstr())
8762726b88cSDan Gohman         continue;
8772cb27072SThomas Lively       switch (MI.getOpcode()) {
878d25c17f3SHeejin Ahn       case WebAssembly::END_TRY: {
879d25c17f3SHeejin Ahn         // If a 'try''s return type is fixed, both its try body and catch body
880d25c17f3SHeejin Ahn         // should satisfy the return type, so we need to search 'end'
881d25c17f3SHeejin Ahn         // instructions before its corresponding 'catch' too.
882d25c17f3SHeejin Ahn         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
883d25c17f3SHeejin Ahn         assert(EHPad);
8849f8b2576SHeejin Ahn         auto NextIt =
8859f8b2576SHeejin Ahn             std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
8869f8b2576SHeejin Ahn         if (NextIt != EHPad->rend())
8879f8b2576SHeejin Ahn           Worklist.push_back(NextIt);
888d25c17f3SHeejin Ahn         LLVM_FALLTHROUGH;
889d25c17f3SHeejin Ahn       }
8902cb27072SThomas Lively       case WebAssembly::END_BLOCK:
8912cb27072SThomas Lively       case WebAssembly::END_LOOP:
89218c56a07SHeejin Ahn         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
8932726b88cSDan Gohman         continue;
8942cb27072SThomas Lively       default:
895d25c17f3SHeejin Ahn         // Something other than an `end`. We're done for this BB.
8962726b88cSDan Gohman         return;
8972726b88cSDan Gohman       }
8982726b88cSDan Gohman     }
899d25c17f3SHeejin Ahn     // We've reached the beginning of a BB. Continue the search in the previous
900d25c17f3SHeejin Ahn     // BB.
901d25c17f3SHeejin Ahn     Worklist.push_back(MBB->getPrevNode()->rbegin());
902d25c17f3SHeejin Ahn   };
903d25c17f3SHeejin Ahn 
904d25c17f3SHeejin Ahn   while (!Worklist.empty())
905d25c17f3SHeejin Ahn     Process(Worklist.pop_back_val());
9062cb27072SThomas Lively }
9072726b88cSDan Gohman 
908d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body
909d934cb88SDan Gohman // were a block.
91018c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF,
911d934cb88SDan Gohman                                 const WebAssemblyInstrInfo &TII) {
91210b31358SDerek Schuff   BuildMI(MF.back(), MF.back().end(),
91310b31358SDerek Schuff           MF.back().findPrevDebugLoc(MF.back().end()),
914d934cb88SDan Gohman           TII.get(WebAssembly::END_FUNCTION));
915d934cb88SDan Gohman }
916d934cb88SDan Gohman 
917e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places.
918e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
919e76fa9ecSHeejin Ahn   // We allocate one more than the number of blocks in the function to
920e76fa9ecSHeejin Ahn   // accommodate for the possible fake block we may insert at the end.
921e76fa9ecSHeejin Ahn   ScopeTops.resize(MF.getNumBlockIDs() + 1);
9228fe7e86bSDan Gohman   // Place the LOOP for MBB if MBB is the header of a loop.
923e76fa9ecSHeejin Ahn   for (auto &MBB : MF)
924e76fa9ecSHeejin Ahn     placeLoopMarker(MBB);
92544a5a4b1SHeejin Ahn 
926d6f48786SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
92744a5a4b1SHeejin Ahn   for (auto &MBB : MF) {
92844a5a4b1SHeejin Ahn     if (MBB.isEHPad()) {
92944a5a4b1SHeejin Ahn       // Place the TRY for MBB if MBB is the EH pad of an exception.
930e76fa9ecSHeejin Ahn       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
931e76fa9ecSHeejin Ahn           MF.getFunction().hasPersonalityFn())
932e76fa9ecSHeejin Ahn         placeTryMarker(MBB);
93344a5a4b1SHeejin Ahn     } else {
93432807932SDan Gohman       // Place the BLOCK for MBB if MBB is branched to from above.
935e76fa9ecSHeejin Ahn       placeBlockMarker(MBB);
936950a13cfSDan Gohman     }
93744a5a4b1SHeejin Ahn   }
938c4ac74fbSHeejin Ahn   // Fix mismatches in unwind destinations induced by linearizing the code.
939daeead4bSHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
940daeead4bSHeejin Ahn       MF.getFunction().hasPersonalityFn())
941c4ac74fbSHeejin Ahn     fixUnwindMismatches(MF);
94244a5a4b1SHeejin Ahn }
943950a13cfSDan Gohman 
944e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
9451d68e80fSDan Gohman   // Now rewrite references to basic blocks to be depth immediates.
9461d68e80fSDan Gohman   SmallVector<const MachineBasicBlock *, 8> Stack;
9471d68e80fSDan Gohman   for (auto &MBB : reverse(MF)) {
948e76fa9ecSHeejin Ahn     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) {
949e76fa9ecSHeejin Ahn       MachineInstr &MI = *I;
9501d68e80fSDan Gohman       switch (MI.getOpcode()) {
9511d68e80fSDan Gohman       case WebAssembly::BLOCK:
952e76fa9ecSHeejin Ahn       case WebAssembly::TRY:
953e76fa9ecSHeejin Ahn         assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <=
954e76fa9ecSHeejin Ahn                    MBB.getNumber() &&
955e76fa9ecSHeejin Ahn                "Block/try marker should be balanced");
956e76fa9ecSHeejin Ahn         Stack.pop_back();
957e76fa9ecSHeejin Ahn         break;
958e76fa9ecSHeejin Ahn 
9591d68e80fSDan Gohman       case WebAssembly::LOOP:
9601d68e80fSDan Gohman         assert(Stack.back() == &MBB && "Loop top should be balanced");
9611d68e80fSDan Gohman         Stack.pop_back();
9621d68e80fSDan Gohman         break;
963e76fa9ecSHeejin Ahn 
9641d68e80fSDan Gohman       case WebAssembly::END_BLOCK:
965e76fa9ecSHeejin Ahn       case WebAssembly::END_TRY:
9661d68e80fSDan Gohman         Stack.push_back(&MBB);
9671d68e80fSDan Gohman         break;
968e76fa9ecSHeejin Ahn 
9691d68e80fSDan Gohman       case WebAssembly::END_LOOP:
970e76fa9ecSHeejin Ahn         Stack.push_back(EndToBegin[&MI]->getParent());
9711d68e80fSDan Gohman         break;
972e76fa9ecSHeejin Ahn 
9731d68e80fSDan Gohman       default:
9741d68e80fSDan Gohman         if (MI.isTerminator()) {
9751d68e80fSDan Gohman           // Rewrite MBB operands to be depth immediates.
9761d68e80fSDan Gohman           SmallVector<MachineOperand, 4> Ops(MI.operands());
9771d68e80fSDan Gohman           while (MI.getNumOperands() > 0)
9781d68e80fSDan Gohman             MI.RemoveOperand(MI.getNumOperands() - 1);
9791d68e80fSDan Gohman           for (auto MO : Ops) {
9801d68e80fSDan Gohman             if (MO.isMBB())
98118c56a07SHeejin Ahn               MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB()));
9821d68e80fSDan Gohman             MI.addOperand(MF, MO);
98332807932SDan Gohman           }
9841d68e80fSDan Gohman         }
9851d68e80fSDan Gohman         break;
9861d68e80fSDan Gohman       }
9871d68e80fSDan Gohman     }
9881d68e80fSDan Gohman   }
9891d68e80fSDan Gohman   assert(Stack.empty() && "Control flow should be balanced");
990e76fa9ecSHeejin Ahn }
9912726b88cSDan Gohman 
992e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() {
993e76fa9ecSHeejin Ahn   ScopeTops.clear();
994e76fa9ecSHeejin Ahn   BeginToEnd.clear();
995e76fa9ecSHeejin Ahn   EndToBegin.clear();
996e76fa9ecSHeejin Ahn   TryToEHPad.clear();
997e76fa9ecSHeejin Ahn   EHPadToTry.clear();
998c4ac74fbSHeejin Ahn   AppendixBB = nullptr;
9991d68e80fSDan Gohman }
100032807932SDan Gohman 
1001950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1002d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1003950a13cfSDan Gohman                        "********** Function: "
1004950a13cfSDan Gohman                     << MF.getName() << '\n');
1005cf699b45SHeejin Ahn   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1006950a13cfSDan Gohman 
1007e76fa9ecSHeejin Ahn   releaseMemory();
1008e76fa9ecSHeejin Ahn 
1009e040533eSDan Gohman   // Liveness is not tracked for VALUE_STACK physreg.
10109c3bf318SDerek Schuff   MF.getRegInfo().invalidateLiveness();
1011950a13cfSDan Gohman 
1012e76fa9ecSHeejin Ahn   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1013e76fa9ecSHeejin Ahn   placeMarkers(MF);
1014e76fa9ecSHeejin Ahn 
1015c4ac74fbSHeejin Ahn   // Remove unnecessary instructions possibly introduced by try/end_trys.
1016cf699b45SHeejin Ahn   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1017cf699b45SHeejin Ahn       MF.getFunction().hasPersonalityFn())
1018cf699b45SHeejin Ahn     removeUnnecessaryInstrs(MF);
1019cf699b45SHeejin Ahn 
1020e76fa9ecSHeejin Ahn   // Convert MBB operands in terminators to relative depth immediates.
1021e76fa9ecSHeejin Ahn   rewriteDepthImmediates(MF);
1022e76fa9ecSHeejin Ahn 
1023e76fa9ecSHeejin Ahn   // Fix up block/loop/try signatures at the end of the function to conform to
1024e76fa9ecSHeejin Ahn   // WebAssembly's rules.
1025e76fa9ecSHeejin Ahn   fixEndsAtEndOfFunction(MF);
1026e76fa9ecSHeejin Ahn 
1027e76fa9ecSHeejin Ahn   // Add an end instruction at the end of the function body.
1028e76fa9ecSHeejin Ahn   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1029e76fa9ecSHeejin Ahn   if (!MF.getSubtarget<WebAssemblySubtarget>()
1030e76fa9ecSHeejin Ahn            .getTargetTriple()
1031e76fa9ecSHeejin Ahn            .isOSBinFormatELF())
103218c56a07SHeejin Ahn     appendEndToFunction(MF, TII);
103332807932SDan Gohman 
10341aaa481fSHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1035950a13cfSDan Gohman   return true;
1036950a13cfSDan Gohman }
1037