xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp (revision 0818c2801ecc5cb07b680bb77e24df90f35c74b9)
1 //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements a CFG stacking pass.
11 ///
12 /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes,
13 /// since scope boundaries serve as the labels for WebAssembly's control
14 /// transfers.
15 ///
16 /// This is sufficient to convert arbitrary CFGs into a form that works on
17 /// WebAssembly, provided that all loops are single-entry.
18 ///
19 /// In case we use exceptions, this pass also fixes mismatches in unwind
20 /// destinations created during transforming CFG into wasm structured format.
21 ///
22 //===----------------------------------------------------------------------===//
23 
24 #include "Utils/WebAssemblyTypeUtilities.h"
25 #include "WebAssembly.h"
26 #include "WebAssemblyExceptionInfo.h"
27 #include "WebAssemblyMachineFunctionInfo.h"
28 #include "WebAssemblySortRegion.h"
29 #include "WebAssemblySubtarget.h"
30 #include "WebAssemblyUtilities.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/WasmEHFuncInfo.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 using namespace llvm;
39 using WebAssembly::SortRegionInfo;
40 
41 #define DEBUG_TYPE "wasm-cfg-stackify"
42 
43 STATISTIC(NumCallUnwindMismatches, "Number of call unwind mismatches found");
44 STATISTIC(NumCatchUnwindMismatches, "Number of catch unwind mismatches found");
45 
46 namespace {
47 class WebAssemblyCFGStackify final : public MachineFunctionPass {
48   MachineDominatorTree *MDT;
49 
50   StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
51 
52   void getAnalysisUsage(AnalysisUsage &AU) const override {
53     AU.addRequired<MachineDominatorTreeWrapperPass>();
54     AU.addRequired<MachineLoopInfoWrapperPass>();
55     AU.addRequired<WebAssemblyExceptionInfo>();
56     MachineFunctionPass::getAnalysisUsage(AU);
57   }
58 
59   bool runOnMachineFunction(MachineFunction &MF) override;
60 
61   // For each block whose label represents the end of a scope, record the block
62   // which holds the beginning of the scope. This will allow us to quickly skip
63   // over scoped regions when walking blocks.
64   SmallVector<MachineBasicBlock *, 8> ScopeTops;
65   void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) {
66     int BeginNo = Begin->getNumber();
67     int EndNo = End->getNumber();
68     if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > BeginNo)
69       ScopeTops[EndNo] = Begin;
70   }
71 
72   // Placing markers.
73   void placeMarkers(MachineFunction &MF);
74   void placeBlockMarker(MachineBasicBlock &MBB);
75   void placeLoopMarker(MachineBasicBlock &MBB);
76   void placeTryMarker(MachineBasicBlock &MBB);
77 
78   // Exception handling related functions
79   bool fixCallUnwindMismatches(MachineFunction &MF);
80   bool fixCatchUnwindMismatches(MachineFunction &MF);
81   void addNestedTryDelegate(MachineInstr *RangeBegin, MachineInstr *RangeEnd,
82                             MachineBasicBlock *UnwindDest);
83   void recalculateScopeTops(MachineFunction &MF);
84   void removeUnnecessaryInstrs(MachineFunction &MF);
85 
86   // Wrap-up
87   using EndMarkerInfo =
88       std::pair<const MachineBasicBlock *, const MachineInstr *>;
89   unsigned getBranchDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
90                           const MachineBasicBlock *MBB);
91   unsigned getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
92                             const MachineBasicBlock *MBB);
93   unsigned
94   getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> &Stack,
95                   const SmallVectorImpl<const MachineBasicBlock *> &EHPadStack);
96   void rewriteDepthImmediates(MachineFunction &MF);
97   void fixEndsAtEndOfFunction(MachineFunction &MF);
98   void cleanupFunctionData(MachineFunction &MF);
99 
100   // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY) or DELEGATE
101   // (in case of TRY).
102   DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd;
103   // For each END_(BLOCK|LOOP|TRY) or DELEGATE, the corresponding
104   // BLOCK|LOOP|TRY.
105   DenseMap<const MachineInstr *, MachineInstr *> EndToBegin;
106   // <TRY marker, EH pad> map
107   DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad;
108   // <EH pad, TRY marker> map
109   DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry;
110 
111   // We need an appendix block to place 'end_loop' or 'end_try' marker when the
112   // loop / exception bottom block is the last block in a function
113   MachineBasicBlock *AppendixBB = nullptr;
114   MachineBasicBlock *getAppendixBlock(MachineFunction &MF) {
115     if (!AppendixBB) {
116       AppendixBB = MF.CreateMachineBasicBlock();
117       // Give it a fake predecessor so that AsmPrinter prints its label.
118       AppendixBB->addSuccessor(AppendixBB);
119       MF.push_back(AppendixBB);
120     }
121     return AppendixBB;
122   }
123 
124   // Before running rewriteDepthImmediates function, 'delegate' has a BB as its
125   // destination operand. getFakeCallerBlock() returns a fake BB that will be
126   // used for the operand when 'delegate' needs to rethrow to the caller. This
127   // will be rewritten as an immediate value that is the number of block depths
128   // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end
129   // of the pass.
130   MachineBasicBlock *FakeCallerBB = nullptr;
131   MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) {
132     if (!FakeCallerBB)
133       FakeCallerBB = MF.CreateMachineBasicBlock();
134     return FakeCallerBB;
135   }
136 
137   // Helper functions to register / unregister scope information created by
138   // marker instructions.
139   void registerScope(MachineInstr *Begin, MachineInstr *End);
140   void registerTryScope(MachineInstr *Begin, MachineInstr *End,
141                         MachineBasicBlock *EHPad);
142   void unregisterScope(MachineInstr *Begin);
143 
144 public:
145   static char ID; // Pass identification, replacement for typeid
146   WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
147   ~WebAssemblyCFGStackify() override { releaseMemory(); }
148   void releaseMemory() override;
149 };
150 } // end anonymous namespace
151 
152 char WebAssemblyCFGStackify::ID = 0;
153 INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
154                 "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false,
155                 false)
156 
157 FunctionPass *llvm::createWebAssemblyCFGStackify() {
158   return new WebAssemblyCFGStackify();
159 }
160 
161 /// Test whether Pred has any terminators explicitly branching to MBB, as
162 /// opposed to falling through. Note that it's possible (eg. in unoptimized
163 /// code) for a branch instruction to both branch to a block and fallthrough
164 /// to it, so we check the actual branch operands to see if there are any
165 /// explicit mentions.
166 static bool explicitlyBranchesTo(MachineBasicBlock *Pred,
167                                  MachineBasicBlock *MBB) {
168   for (MachineInstr &MI : Pred->terminators())
169     for (MachineOperand &MO : MI.explicit_operands())
170       if (MO.isMBB() && MO.getMBB() == MBB)
171         return true;
172   return false;
173 }
174 
175 // Returns an iterator to the earliest position possible within the MBB,
176 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
177 // contains instructions that should go before the marker, and AfterSet contains
178 // ones that should go after the marker. In this function, AfterSet is only
179 // used for validation checking.
180 template <typename Container>
181 static MachineBasicBlock::iterator
182 getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
183                      const Container &AfterSet) {
184   auto InsertPos = MBB->end();
185   while (InsertPos != MBB->begin()) {
186     if (BeforeSet.count(&*std::prev(InsertPos))) {
187 #ifndef NDEBUG
188       // Validation check
189       for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos)
190         assert(!AfterSet.count(&*std::prev(Pos)));
191 #endif
192       break;
193     }
194     --InsertPos;
195   }
196   return InsertPos;
197 }
198 
199 // Returns an iterator to the latest position possible within the MBB,
200 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet
201 // contains instructions that should go before the marker, and AfterSet contains
202 // ones that should go after the marker. In this function, BeforeSet is only
203 // used for validation checking.
204 template <typename Container>
205 static MachineBasicBlock::iterator
206 getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet,
207                    const Container &AfterSet) {
208   auto InsertPos = MBB->begin();
209   while (InsertPos != MBB->end()) {
210     if (AfterSet.count(&*InsertPos)) {
211 #ifndef NDEBUG
212       // Validation check
213       for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos)
214         assert(!BeforeSet.count(&*Pos));
215 #endif
216       break;
217     }
218     ++InsertPos;
219   }
220   return InsertPos;
221 }
222 
223 void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin,
224                                            MachineInstr *End) {
225   BeginToEnd[Begin] = End;
226   EndToBegin[End] = Begin;
227 }
228 
229 // When 'End' is not an 'end_try' but a 'delegate', EHPad is nullptr.
230 void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin,
231                                               MachineInstr *End,
232                                               MachineBasicBlock *EHPad) {
233   registerScope(Begin, End);
234   TryToEHPad[Begin] = EHPad;
235   EHPadToTry[EHPad] = Begin;
236 }
237 
238 void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) {
239   assert(BeginToEnd.count(Begin));
240   MachineInstr *End = BeginToEnd[Begin];
241   assert(EndToBegin.count(End));
242   BeginToEnd.erase(Begin);
243   EndToBegin.erase(End);
244   MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin);
245   if (EHPad) {
246     assert(EHPadToTry.count(EHPad));
247     TryToEHPad.erase(Begin);
248     EHPadToTry.erase(EHPad);
249   }
250 }
251 
252 /// Insert a BLOCK marker for branches to MBB (if needed).
253 // TODO Consider a more generalized way of handling block (and also loop and
254 // try) signatures when we implement the multi-value proposal later.
255 void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) {
256   assert(!MBB.isEHPad());
257   MachineFunction &MF = *MBB.getParent();
258   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
259   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
260 
261   // First compute the nearest common dominator of all forward non-fallthrough
262   // predecessors so that we minimize the time that the BLOCK is on the stack,
263   // which reduces overall stack height.
264   MachineBasicBlock *Header = nullptr;
265   bool IsBranchedTo = false;
266   int MBBNumber = MBB.getNumber();
267   for (MachineBasicBlock *Pred : MBB.predecessors()) {
268     if (Pred->getNumber() < MBBNumber) {
269       Header = Header ? MDT->findNearestCommonDominator(Header, Pred) : Pred;
270       if (explicitlyBranchesTo(Pred, &MBB))
271         IsBranchedTo = true;
272     }
273   }
274   if (!Header)
275     return;
276   if (!IsBranchedTo)
277     return;
278 
279   assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
280   MachineBasicBlock *LayoutPred = MBB.getPrevNode();
281 
282   // If the nearest common dominator is inside a more deeply nested context,
283   // walk out to the nearest scope which isn't more deeply nested.
284   for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
285     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
286       if (ScopeTop->getNumber() > Header->getNumber()) {
287         // Skip over an intervening scope.
288         I = std::next(ScopeTop->getIterator());
289       } else {
290         // We found a scope level at an appropriate depth.
291         Header = ScopeTop;
292         break;
293       }
294     }
295   }
296 
297   // Decide where in MBB to put the BLOCK.
298 
299   // Instructions that should go before the BLOCK.
300   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
301   // Instructions that should go after the BLOCK.
302   SmallPtrSet<const MachineInstr *, 4> AfterSet;
303   for (const auto &MI : *Header) {
304     // If there is a previously placed LOOP marker and the bottom block of the
305     // loop is above MBB, it should be after the BLOCK, because the loop is
306     // nested in this BLOCK. Otherwise it should be before the BLOCK.
307     if (MI.getOpcode() == WebAssembly::LOOP) {
308       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
309       if (MBB.getNumber() > LoopBottom->getNumber())
310         AfterSet.insert(&MI);
311 #ifndef NDEBUG
312       else
313         BeforeSet.insert(&MI);
314 #endif
315     }
316 
317     // If there is a previously placed BLOCK/TRY marker and its corresponding
318     // END marker is before the current BLOCK's END marker, that should be
319     // placed after this BLOCK. Otherwise it should be placed before this BLOCK
320     // marker.
321     if (MI.getOpcode() == WebAssembly::BLOCK ||
322         MI.getOpcode() == WebAssembly::TRY) {
323       if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber())
324         AfterSet.insert(&MI);
325 #ifndef NDEBUG
326       else
327         BeforeSet.insert(&MI);
328 #endif
329     }
330 
331 #ifndef NDEBUG
332     // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK.
333     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
334         MI.getOpcode() == WebAssembly::END_LOOP ||
335         MI.getOpcode() == WebAssembly::END_TRY)
336       BeforeSet.insert(&MI);
337 #endif
338 
339     // Terminators should go after the BLOCK.
340     if (MI.isTerminator())
341       AfterSet.insert(&MI);
342   }
343 
344   // Local expression tree should go after the BLOCK.
345   for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E;
346        --I) {
347     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
348       continue;
349     if (WebAssembly::isChild(*std::prev(I), MFI))
350       AfterSet.insert(&*std::prev(I));
351     else
352       break;
353   }
354 
355   // Add the BLOCK.
356   WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void;
357   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
358   MachineInstr *Begin =
359       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
360               TII.get(WebAssembly::BLOCK))
361           .addImm(int64_t(ReturnType));
362 
363   // Decide where in MBB to put the END_BLOCK.
364   BeforeSet.clear();
365   AfterSet.clear();
366   for (auto &MI : MBB) {
367 #ifndef NDEBUG
368     // END_BLOCK should precede existing LOOP markers.
369     if (MI.getOpcode() == WebAssembly::LOOP)
370       AfterSet.insert(&MI);
371 #endif
372 
373     // If there is a previously placed END_LOOP marker and the header of the
374     // loop is above this block's header, the END_LOOP should be placed after
375     // the END_BLOCK, because the loop contains this block. Otherwise the
376     // END_LOOP should be placed before the END_BLOCK. The same for END_TRY.
377     if (MI.getOpcode() == WebAssembly::END_LOOP ||
378         MI.getOpcode() == WebAssembly::END_TRY) {
379       if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber())
380         BeforeSet.insert(&MI);
381 #ifndef NDEBUG
382       else
383         AfterSet.insert(&MI);
384 #endif
385     }
386   }
387 
388   // Mark the end of the block.
389   InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
390   MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
391                               TII.get(WebAssembly::END_BLOCK));
392   registerScope(Begin, End);
393 
394   // Track the farthest-spanning scope that ends at this point.
395   updateScopeTops(Header, &MBB);
396 }
397 
398 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
399 void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) {
400   MachineFunction &MF = *MBB.getParent();
401   const auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
402   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
403   SortRegionInfo SRI(MLI, WEI);
404   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
405 
406   MachineLoop *Loop = MLI.getLoopFor(&MBB);
407   if (!Loop || Loop->getHeader() != &MBB)
408     return;
409 
410   // The operand of a LOOP is the first block after the loop. If the loop is the
411   // bottom of the function, insert a dummy block at the end.
412   MachineBasicBlock *Bottom = SRI.getBottom(Loop);
413   auto Iter = std::next(Bottom->getIterator());
414   if (Iter == MF.end()) {
415     getAppendixBlock(MF);
416     Iter = std::next(Bottom->getIterator());
417   }
418   MachineBasicBlock *AfterLoop = &*Iter;
419 
420   // Decide where in Header to put the LOOP.
421   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
422   SmallPtrSet<const MachineInstr *, 4> AfterSet;
423   for (const auto &MI : MBB) {
424     // LOOP marker should be after any existing loop that ends here. Otherwise
425     // we assume the instruction belongs to the loop.
426     if (MI.getOpcode() == WebAssembly::END_LOOP)
427       BeforeSet.insert(&MI);
428 #ifndef NDEBUG
429     else
430       AfterSet.insert(&MI);
431 #endif
432   }
433 
434   // Mark the beginning of the loop.
435   auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet);
436   MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
437                                 TII.get(WebAssembly::LOOP))
438                             .addImm(int64_t(WebAssembly::BlockType::Void));
439 
440   // Decide where in MBB to put the END_LOOP.
441   BeforeSet.clear();
442   AfterSet.clear();
443 #ifndef NDEBUG
444   for (const auto &MI : MBB)
445     // Existing END_LOOP markers belong to parent loops of this loop
446     if (MI.getOpcode() == WebAssembly::END_LOOP)
447       AfterSet.insert(&MI);
448 #endif
449 
450   // Mark the end of the loop (using arbitrary debug location that branched to
451   // the loop end as its location).
452   InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet);
453   DebugLoc EndDL = AfterLoop->pred_empty()
454                        ? DebugLoc()
455                        : (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
456   MachineInstr *End =
457       BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP));
458   registerScope(Begin, End);
459 
460   assert((!ScopeTops[AfterLoop->getNumber()] ||
461           ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
462          "With block sorting the outermost loop for a block should be first.");
463   updateScopeTops(&MBB, AfterLoop);
464 }
465 
466 void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) {
467   assert(MBB.isEHPad());
468   MachineFunction &MF = *MBB.getParent();
469   auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
470   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
471   const auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
472   const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
473   SortRegionInfo SRI(MLI, WEI);
474   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
475 
476   // Compute the nearest common dominator of all unwind predecessors
477   MachineBasicBlock *Header = nullptr;
478   int MBBNumber = MBB.getNumber();
479   for (auto *Pred : MBB.predecessors()) {
480     if (Pred->getNumber() < MBBNumber) {
481       Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
482       assert(!explicitlyBranchesTo(Pred, &MBB) &&
483              "Explicit branch to an EH pad!");
484     }
485   }
486   if (!Header)
487     return;
488 
489   // If this try is at the bottom of the function, insert a dummy block at the
490   // end.
491   WebAssemblyException *WE = WEI.getExceptionFor(&MBB);
492   assert(WE);
493   MachineBasicBlock *Bottom = SRI.getBottom(WE);
494   auto Iter = std::next(Bottom->getIterator());
495   if (Iter == MF.end()) {
496     getAppendixBlock(MF);
497     Iter = std::next(Bottom->getIterator());
498   }
499   MachineBasicBlock *Cont = &*Iter;
500 
501   // If the nearest common dominator is inside a more deeply nested context,
502   // walk out to the nearest scope which isn't more deeply nested.
503   for (MachineFunction::iterator I(Bottom), E(Header); I != E; --I) {
504     if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
505       if (ScopeTop->getNumber() > Header->getNumber()) {
506         // Skip over an intervening scope.
507         I = std::next(ScopeTop->getIterator());
508       } else {
509         // We found a scope level at an appropriate depth.
510         Header = ScopeTop;
511         break;
512       }
513     }
514   }
515 
516   // Decide where in Header to put the TRY.
517 
518   // Instructions that should go before the TRY.
519   SmallPtrSet<const MachineInstr *, 4> BeforeSet;
520   // Instructions that should go after the TRY.
521   SmallPtrSet<const MachineInstr *, 4> AfterSet;
522   for (const auto &MI : *Header) {
523     // If there is a previously placed LOOP marker and the bottom block of the
524     // loop is above MBB, it should be after the TRY, because the loop is nested
525     // in this TRY. Otherwise it should be before the TRY.
526     if (MI.getOpcode() == WebAssembly::LOOP) {
527       auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode();
528       if (MBB.getNumber() > LoopBottom->getNumber())
529         AfterSet.insert(&MI);
530 #ifndef NDEBUG
531       else
532         BeforeSet.insert(&MI);
533 #endif
534     }
535 
536     // All previously inserted BLOCK/TRY markers should be after the TRY because
537     // they are all nested blocks/trys.
538     if (MI.getOpcode() == WebAssembly::BLOCK ||
539         MI.getOpcode() == WebAssembly::TRY)
540       AfterSet.insert(&MI);
541 
542 #ifndef NDEBUG
543     // All END_(BLOCK/LOOP/TRY) markers should be before the TRY.
544     if (MI.getOpcode() == WebAssembly::END_BLOCK ||
545         MI.getOpcode() == WebAssembly::END_LOOP ||
546         MI.getOpcode() == WebAssembly::END_TRY)
547       BeforeSet.insert(&MI);
548 #endif
549 
550     // Terminators should go after the TRY.
551     if (MI.isTerminator())
552       AfterSet.insert(&MI);
553   }
554 
555   // If Header unwinds to MBB (= Header contains 'invoke'), the try block should
556   // contain the call within it. So the call should go after the TRY. The
557   // exception is when the header's terminator is a rethrow instruction, in
558   // which case that instruction, not a call instruction before it, is gonna
559   // throw.
560   MachineInstr *ThrowingCall = nullptr;
561   if (MBB.isPredecessor(Header)) {
562     auto TermPos = Header->getFirstTerminator();
563     if (TermPos == Header->end() ||
564         TermPos->getOpcode() != WebAssembly::RETHROW) {
565       for (auto &MI : reverse(*Header)) {
566         if (MI.isCall()) {
567           AfterSet.insert(&MI);
568           ThrowingCall = &MI;
569           // Possibly throwing calls are usually wrapped by EH_LABEL
570           // instructions. We don't want to split them and the call.
571           if (MI.getIterator() != Header->begin() &&
572               std::prev(MI.getIterator())->isEHLabel()) {
573             AfterSet.insert(&*std::prev(MI.getIterator()));
574             ThrowingCall = &*std::prev(MI.getIterator());
575           }
576           break;
577         }
578       }
579     }
580   }
581 
582   // Local expression tree should go after the TRY.
583   // For BLOCK placement, we start the search from the previous instruction of a
584   // BB's terminator, but in TRY's case, we should start from the previous
585   // instruction of a call that can throw, or a EH_LABEL that precedes the call,
586   // because the return values of the call's previous instructions can be
587   // stackified and consumed by the throwing call.
588   auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall)
589                                     : Header->getFirstTerminator();
590   for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) {
591     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
592       continue;
593     if (WebAssembly::isChild(*std::prev(I), MFI))
594       AfterSet.insert(&*std::prev(I));
595     else
596       break;
597   }
598 
599   // Add the TRY.
600   auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet);
601   MachineInstr *Begin =
602       BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
603               TII.get(WebAssembly::TRY))
604           .addImm(int64_t(WebAssembly::BlockType::Void));
605 
606   // Decide where in Cont to put the END_TRY.
607   BeforeSet.clear();
608   AfterSet.clear();
609   for (const auto &MI : *Cont) {
610 #ifndef NDEBUG
611     // END_TRY should precede existing LOOP markers.
612     if (MI.getOpcode() == WebAssembly::LOOP)
613       AfterSet.insert(&MI);
614 
615     // All END_TRY markers placed earlier belong to exceptions that contains
616     // this one.
617     if (MI.getOpcode() == WebAssembly::END_TRY)
618       AfterSet.insert(&MI);
619 #endif
620 
621     // If there is a previously placed END_LOOP marker and its header is after
622     // where TRY marker is, this loop is contained within the 'catch' part, so
623     // the END_TRY marker should go after that. Otherwise, the whole try-catch
624     // is contained within this loop, so the END_TRY should go before that.
625     if (MI.getOpcode() == WebAssembly::END_LOOP) {
626       // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they
627       // are in the same BB, LOOP is always before TRY.
628       if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber())
629         BeforeSet.insert(&MI);
630 #ifndef NDEBUG
631       else
632         AfterSet.insert(&MI);
633 #endif
634     }
635 
636     // It is not possible for an END_BLOCK to be already in this block.
637   }
638 
639   // Mark the end of the TRY.
640   InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet);
641   MachineInstr *End = BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(),
642                               TII.get(WebAssembly::END_TRY));
643   registerTryScope(Begin, End, &MBB);
644 
645   // Track the farthest-spanning scope that ends at this point. We create two
646   // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB
647   // with 'try'). We need to create 'catch' -> 'try' mapping here too because
648   // markers should not span across 'catch'. For example, this should not
649   // happen:
650   //
651   // try
652   //   block     --|  (X)
653   // catch         |
654   //   end_block --|
655   // end_try
656   for (auto *End : {&MBB, Cont})
657     updateScopeTops(Header, End);
658 }
659 
660 void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) {
661   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
662 
663   // When there is an unconditional branch right before a catch instruction and
664   // it branches to the end of end_try marker, we don't need the branch, because
665   // if there is no exception, the control flow transfers to that point anyway.
666   // bb0:
667   //   try
668   //     ...
669   //     br bb2      <- Not necessary
670   // bb1 (ehpad):
671   //   catch
672   //     ...
673   // bb2:            <- Continuation BB
674   //   end
675   //
676   // A more involved case: When the BB where 'end' is located is an another EH
677   // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example,
678   // bb0:
679   //   try
680   //     try
681   //       ...
682   //       br bb3      <- Not necessary
683   // bb1 (ehpad):
684   //     catch
685   // bb2 (ehpad):
686   //     end
687   //   catch
688   //     ...
689   // bb3:            <- Continuation BB
690   //   end
691   //
692   // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is
693   // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the
694   // code can be deleted. This is why we run 'while' until 'Cont' is not an EH
695   // pad.
696   for (auto &MBB : MF) {
697     if (!MBB.isEHPad())
698       continue;
699 
700     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
701     SmallVector<MachineOperand, 4> Cond;
702     MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode();
703 
704     MachineBasicBlock *Cont = &MBB;
705     while (Cont->isEHPad()) {
706       MachineInstr *Try = EHPadToTry[Cont];
707       MachineInstr *EndTry = BeginToEnd[Try];
708       // We started from an EH pad, so the end marker cannot be a delegate
709       assert(EndTry->getOpcode() != WebAssembly::DELEGATE);
710       Cont = EndTry->getParent();
711     }
712 
713     bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond);
714     // This condition means either
715     // 1. This BB ends with a single unconditional branch whose destinaion is
716     //    Cont.
717     // 2. This BB ends with a conditional branch followed by an unconditional
718     //    branch, and the unconditional branch's destination is Cont.
719     // In both cases, we want to remove the last (= unconditional) branch.
720     if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) ||
721                        (!Cond.empty() && FBB && FBB == Cont))) {
722       bool ErasedUncondBr = false;
723       (void)ErasedUncondBr;
724       for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin();
725            I != E; --I) {
726         auto PrevI = std::prev(I);
727         if (PrevI->isTerminator()) {
728           assert(PrevI->getOpcode() == WebAssembly::BR);
729           PrevI->eraseFromParent();
730           ErasedUncondBr = true;
731           break;
732         }
733       }
734       assert(ErasedUncondBr && "Unconditional branch not erased!");
735     }
736   }
737 
738   // When there are block / end_block markers that overlap with try / end_try
739   // markers, and the block and try markers' return types are the same, the
740   // block /end_block markers are not necessary, because try / end_try markers
741   // also can serve as boundaries for branches.
742   // block         <- Not necessary
743   //   try
744   //     ...
745   //   catch
746   //     ...
747   //   end
748   // end           <- Not necessary
749   SmallVector<MachineInstr *, 32> ToDelete;
750   for (auto &MBB : MF) {
751     for (auto &MI : MBB) {
752       if (MI.getOpcode() != WebAssembly::TRY)
753         continue;
754       MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try];
755       if (EndTry->getOpcode() == WebAssembly::DELEGATE)
756         continue;
757 
758       MachineBasicBlock *TryBB = Try->getParent();
759       MachineBasicBlock *Cont = EndTry->getParent();
760       int64_t RetType = Try->getOperand(0).getImm();
761       for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator());
762            B != TryBB->begin() && E != Cont->end() &&
763            std::prev(B)->getOpcode() == WebAssembly::BLOCK &&
764            E->getOpcode() == WebAssembly::END_BLOCK &&
765            std::prev(B)->getOperand(0).getImm() == RetType;
766            --B, ++E) {
767         ToDelete.push_back(&*std::prev(B));
768         ToDelete.push_back(&*E);
769       }
770     }
771   }
772   for (auto *MI : ToDelete) {
773     if (MI->getOpcode() == WebAssembly::BLOCK)
774       unregisterScope(MI);
775     MI->eraseFromParent();
776   }
777 }
778 
779 // When MBB is split into MBB and Split, we should unstackify defs in MBB that
780 // have their uses in Split.
781 static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB,
782                                          MachineBasicBlock &Split) {
783   MachineFunction &MF = *MBB.getParent();
784   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
785   auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
786   auto &MRI = MF.getRegInfo();
787 
788   for (auto &MI : Split) {
789     for (auto &MO : MI.explicit_uses()) {
790       if (!MO.isReg() || MO.getReg().isPhysical())
791         continue;
792       if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg()))
793         if (Def->getParent() == &MBB)
794           MFI.unstackifyVReg(MO.getReg());
795     }
796   }
797 
798   // In RegStackify, when a register definition is used multiple times,
799   //    Reg = INST ...
800   //    INST ..., Reg, ...
801   //    INST ..., Reg, ...
802   //    INST ..., Reg, ...
803   //
804   // we introduce a TEE, which has the following form:
805   //    DefReg = INST ...
806   //    TeeReg, Reg = TEE_... DefReg
807   //    INST ..., TeeReg, ...
808   //    INST ..., Reg, ...
809   //    INST ..., Reg, ...
810   // with DefReg and TeeReg stackified but Reg not stackified.
811   //
812   // But the invariant that TeeReg should be stackified can be violated while we
813   // unstackify registers in the split BB above. In this case, we convert TEEs
814   // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals.
815   //    DefReg = INST ...
816   //    TeeReg = COPY DefReg
817   //    Reg = COPY DefReg
818   //    INST ..., TeeReg, ...
819   //    INST ..., Reg, ...
820   //    INST ..., Reg, ...
821   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
822     if (!WebAssembly::isTee(MI.getOpcode()))
823       continue;
824     Register TeeReg = MI.getOperand(0).getReg();
825     Register Reg = MI.getOperand(1).getReg();
826     Register DefReg = MI.getOperand(2).getReg();
827     if (!MFI.isVRegStackified(TeeReg)) {
828       // Now we are not using TEE anymore, so unstackify DefReg too
829       MFI.unstackifyVReg(DefReg);
830       unsigned CopyOpc =
831           WebAssembly::getCopyOpcodeForRegClass(MRI.getRegClass(DefReg));
832       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg)
833           .addReg(DefReg);
834       BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg);
835       MI.eraseFromParent();
836     }
837   }
838 }
839 
840 // Wrap the given range of instruction with try-delegate. RangeBegin and
841 // RangeEnd are inclusive.
842 void WebAssemblyCFGStackify::addNestedTryDelegate(
843     MachineInstr *RangeBegin, MachineInstr *RangeEnd,
844     MachineBasicBlock *UnwindDest) {
845   auto *BeginBB = RangeBegin->getParent();
846   auto *EndBB = RangeEnd->getParent();
847   MachineFunction &MF = *BeginBB->getParent();
848   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
849   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
850 
851   // Local expression tree before the first call of this range should go
852   // after the nested TRY.
853   SmallPtrSet<const MachineInstr *, 4> AfterSet;
854   AfterSet.insert(RangeBegin);
855   for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin();
856        I != E; --I) {
857     if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition())
858       continue;
859     if (WebAssembly::isChild(*std::prev(I), MFI))
860       AfterSet.insert(&*std::prev(I));
861     else
862       break;
863   }
864 
865   // Create the nested try instruction.
866   auto TryPos = getLatestInsertPos(
867       BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet);
868   MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(),
869                               TII.get(WebAssembly::TRY))
870                           .addImm(int64_t(WebAssembly::BlockType::Void));
871 
872   // Create a BB to insert the 'delegate' instruction.
873   MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock();
874   // If the destination of 'delegate' is not the caller, adds the destination to
875   // the BB's successors.
876   if (UnwindDest != FakeCallerBB)
877     DelegateBB->addSuccessor(UnwindDest);
878 
879   auto SplitPos = std::next(RangeEnd->getIterator());
880   if (SplitPos == EndBB->end()) {
881     // If the range's end instruction is at the end of the BB, insert the new
882     // delegate BB after the current BB.
883     MF.insert(std::next(EndBB->getIterator()), DelegateBB);
884     EndBB->addSuccessor(DelegateBB);
885 
886   } else {
887     // When the split pos is in the middle of a BB, we split the BB into two and
888     // put the 'delegate' BB in between. We normally create a split BB and make
889     // it a successor of the original BB (PostSplit == true), but in case the BB
890     // is an EH pad and the split pos is before 'catch', we should preserve the
891     // BB's property, including that it is an EH pad, in the later part of the
892     // BB, where 'catch' is. In this case we set PostSplit to false.
893     bool PostSplit = true;
894     if (EndBB->isEHPad()) {
895       for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end();
896            I != E; ++I) {
897         if (WebAssembly::isCatch(I->getOpcode())) {
898           PostSplit = false;
899           break;
900         }
901       }
902     }
903 
904     MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr;
905     if (PostSplit) {
906       // If the range's end instruction is in the middle of the BB, we split the
907       // BB into two and insert the delegate BB in between.
908       // - Before:
909       // bb:
910       //   range_end
911       //   other_insts
912       //
913       // - After:
914       // pre_bb: (previous 'bb')
915       //   range_end
916       // delegate_bb: (new)
917       //   delegate
918       // post_bb: (new)
919       //   other_insts
920       PreBB = EndBB;
921       PostBB = MF.CreateMachineBasicBlock();
922       MF.insert(std::next(PreBB->getIterator()), PostBB);
923       MF.insert(std::next(PreBB->getIterator()), DelegateBB);
924       PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end());
925       PostBB->transferSuccessors(PreBB);
926     } else {
927       // - Before:
928       // ehpad:
929       //   range_end
930       //   catch
931       //   ...
932       //
933       // - After:
934       // pre_bb: (new)
935       //   range_end
936       // delegate_bb: (new)
937       //   delegate
938       // post_bb: (previous 'ehpad')
939       //   catch
940       //   ...
941       assert(EndBB->isEHPad());
942       PreBB = MF.CreateMachineBasicBlock();
943       PostBB = EndBB;
944       MF.insert(PostBB->getIterator(), PreBB);
945       MF.insert(PostBB->getIterator(), DelegateBB);
946       PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos);
947       // We don't need to transfer predecessors of the EH pad to 'PreBB',
948       // because an EH pad's predecessors are all through unwind edges and they
949       // should still unwind to the EH pad, not PreBB.
950     }
951     unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB);
952     PreBB->addSuccessor(DelegateBB);
953     PreBB->addSuccessor(PostBB);
954   }
955 
956   // Add 'delegate' instruction in the delegate BB created above.
957   MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(),
958                                    TII.get(WebAssembly::DELEGATE))
959                                .addMBB(UnwindDest);
960   registerTryScope(Try, Delegate, nullptr);
961 }
962 
963 bool WebAssemblyCFGStackify::fixCallUnwindMismatches(MachineFunction &MF) {
964   // Linearizing the control flow by placing TRY / END_TRY markers can create
965   // mismatches in unwind destinations for throwing instructions, such as calls.
966   //
967   // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate'
968   // instruction delegates an exception to an outer 'catch'. It can target not
969   // only 'catch' but all block-like structures including another 'delegate',
970   // but with slightly different semantics than branches. When it targets a
971   // 'catch', it will delegate the exception to that catch. It is being
972   // discussed how to define the semantics when 'delegate''s target is a non-try
973   // block: it will either be a validation failure or it will target the next
974   // outer try-catch. But anyway our LLVM backend currently does not generate
975   // such code. The example below illustrates where the 'delegate' instruction
976   // in the middle will delegate the exception to, depending on the value of N.
977   // try
978   //   try
979   //     block
980   //       try
981   //         try
982   //           call @foo
983   //         delegate N    ;; Where will this delegate to?
984   //       catch           ;; N == 0
985   //       end
986   //     end               ;; N == 1 (invalid; will not be generated)
987   //   delegate            ;; N == 2
988   // catch                 ;; N == 3
989   // end
990   //                       ;; N == 4 (to caller)
991 
992   // 1. When an instruction may throw, but the EH pad it will unwind to can be
993   //    different from the original CFG.
994   //
995   // Example: we have the following CFG:
996   // bb0:
997   //   call @foo    ; if it throws, unwind to bb2
998   // bb1:
999   //   call @bar    ; if it throws, unwind to bb3
1000   // bb2 (ehpad):
1001   //   catch
1002   //   ...
1003   // bb3 (ehpad)
1004   //   catch
1005   //   ...
1006   //
1007   // And the CFG is sorted in this order. Then after placing TRY markers, it
1008   // will look like: (BB markers are omitted)
1009   // try
1010   //   try
1011   //     call @foo
1012   //     call @bar   ;; if it throws, unwind to bb3
1013   //   catch         ;; ehpad (bb2)
1014   //     ...
1015   //   end_try
1016   // catch           ;; ehpad (bb3)
1017   //   ...
1018   // end_try
1019   //
1020   // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it
1021   // is supposed to end up. We solve this problem by wrapping the mismatching
1022   // call with an inner try-delegate that rethrows the exception to the right
1023   // 'catch'.
1024   //
1025   // try
1026   //   try
1027   //     call @foo
1028   //     try               ;; (new)
1029   //       call @bar
1030   //     delegate 1 (bb3)  ;; (new)
1031   //   catch               ;; ehpad (bb2)
1032   //     ...
1033   //   end_try
1034   // catch                 ;; ehpad (bb3)
1035   //   ...
1036   // end_try
1037   //
1038   // ---
1039   // 2. The same as 1, but in this case an instruction unwinds to a caller
1040   //    function and not another EH pad.
1041   //
1042   // Example: we have the following CFG:
1043   // bb0:
1044   //   call @foo       ; if it throws, unwind to bb2
1045   // bb1:
1046   //   call @bar       ; if it throws, unwind to caller
1047   // bb2 (ehpad):
1048   //   catch
1049   //   ...
1050   //
1051   // And the CFG is sorted in this order. Then after placing TRY markers, it
1052   // will look like:
1053   // try
1054   //   call @foo
1055   //   call @bar     ;; if it throws, unwind to caller
1056   // catch           ;; ehpad (bb2)
1057   //   ...
1058   // end_try
1059   //
1060   // Now if bar() throws, it is going to end up ip in bb2, when it is supposed
1061   // throw up to the caller. We solve this problem in the same way, but in this
1062   // case 'delegate's immediate argument is the number of block depths + 1,
1063   // which means it rethrows to the caller.
1064   // try
1065   //   call @foo
1066   //   try                  ;; (new)
1067   //     call @bar
1068   //   delegate 1 (caller)  ;; (new)
1069   // catch                  ;; ehpad (bb2)
1070   //   ...
1071   // end_try
1072   //
1073   // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the
1074   // caller, it will take a fake BB generated by getFakeCallerBlock(), which
1075   // will be converted to a correct immediate argument later.
1076   //
1077   // In case there are multiple calls in a BB that may throw to the caller, they
1078   // can be wrapped together in one nested try-delegate scope. (In 1, this
1079   // couldn't happen, because may-throwing instruction there had an unwind
1080   // destination, i.e., it was an invoke before, and there could be only one
1081   // invoke within a BB.)
1082 
1083   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1084   // Range of intructions to be wrapped in a new nested try/catch. A range
1085   // exists in a single BB and does not span multiple BBs.
1086   using TryRange = std::pair<MachineInstr *, MachineInstr *>;
1087   // In original CFG, <unwind destination BB, a vector of try ranges>
1088   DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges;
1089 
1090   // Gather possibly throwing calls (i.e., previously invokes) whose current
1091   // unwind destination is not the same as the original CFG. (Case 1)
1092 
1093   for (auto &MBB : reverse(MF)) {
1094     bool SeenThrowableInstInBB = false;
1095     for (auto &MI : reverse(MBB)) {
1096       if (MI.getOpcode() == WebAssembly::TRY)
1097         EHPadStack.pop_back();
1098       else if (WebAssembly::isCatch(MI.getOpcode()))
1099         EHPadStack.push_back(MI.getParent());
1100 
1101       // In this loop we only gather calls that have an EH pad to unwind. So
1102       // there will be at most 1 such call (= invoke) in a BB, so after we've
1103       // seen one, we can skip the rest of BB. Also if MBB has no EH pad
1104       // successor or MI does not throw, this is not an invoke.
1105       if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() ||
1106           !WebAssembly::mayThrow(MI))
1107         continue;
1108       SeenThrowableInstInBB = true;
1109 
1110       // If the EH pad on the stack top is where this instruction should unwind
1111       // next, we're good.
1112       MachineBasicBlock *UnwindDest = getFakeCallerBlock(MF);
1113       for (auto *Succ : MBB.successors()) {
1114         // Even though semantically a BB can have multiple successors in case an
1115         // exception is not caught by a catchpad, in our backend implementation
1116         // it is guaranteed that a BB can have at most one EH pad successor. For
1117         // details, refer to comments in findWasmUnwindDestinations function in
1118         // SelectionDAGBuilder.cpp.
1119         if (Succ->isEHPad()) {
1120           UnwindDest = Succ;
1121           break;
1122         }
1123       }
1124       if (EHPadStack.back() == UnwindDest)
1125         continue;
1126 
1127       // Include EH_LABELs in the range before and after the invoke
1128       MachineInstr *RangeBegin = &MI, *RangeEnd = &MI;
1129       if (RangeBegin->getIterator() != MBB.begin() &&
1130           std::prev(RangeBegin->getIterator())->isEHLabel())
1131         RangeBegin = &*std::prev(RangeBegin->getIterator());
1132       if (std::next(RangeEnd->getIterator()) != MBB.end() &&
1133           std::next(RangeEnd->getIterator())->isEHLabel())
1134         RangeEnd = &*std::next(RangeEnd->getIterator());
1135 
1136       // If not, record the range.
1137       UnwindDestToTryRanges[UnwindDest].push_back(
1138           TryRange(RangeBegin, RangeEnd));
1139       LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << MBB.getName()
1140                         << "\nCall = " << MI
1141                         << "\nOriginal dest = " << UnwindDest->getName()
1142                         << "  Current dest = " << EHPadStack.back()->getName()
1143                         << "\n\n");
1144     }
1145   }
1146 
1147   assert(EHPadStack.empty());
1148 
1149   // Gather possibly throwing calls that are supposed to unwind up to the caller
1150   // if they throw, but currently unwind to an incorrect destination. Unlike the
1151   // loop above, there can be multiple calls within a BB that unwind to the
1152   // caller, which we should group together in a range. (Case 2)
1153 
1154   MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive
1155 
1156   // Record the range.
1157   auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) {
1158     UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back(
1159         TryRange(RangeBegin, RangeEnd));
1160     LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = "
1161                       << RangeBegin->getParent()->getName()
1162                       << "\nRange begin = " << *RangeBegin
1163                       << "Range end = " << *RangeEnd
1164                       << "\nOriginal dest = caller  Current dest = "
1165                       << CurrentDest->getName() << "\n\n");
1166     RangeBegin = RangeEnd = nullptr; // Reset range pointers
1167   };
1168 
1169   for (auto &MBB : reverse(MF)) {
1170     bool SeenThrowableInstInBB = false;
1171     for (auto &MI : reverse(MBB)) {
1172       bool MayThrow = WebAssembly::mayThrow(MI);
1173 
1174       // If MBB has an EH pad successor and this is the last instruction that
1175       // may throw, this instruction unwinds to the EH pad and not to the
1176       // caller.
1177       if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB)
1178         SeenThrowableInstInBB = true;
1179 
1180       // We wrap up the current range when we see a marker even if we haven't
1181       // finished a BB.
1182       else if (RangeEnd && WebAssembly::isMarker(MI.getOpcode()))
1183         RecordCallerMismatchRange(EHPadStack.back());
1184 
1185       // If EHPadStack is empty, that means it correctly unwinds to the caller
1186       // if it throws, so we're good. If MI does not throw, we're good too.
1187       else if (EHPadStack.empty() || !MayThrow) {
1188       }
1189 
1190       // We found an instruction that unwinds to the caller but currently has an
1191       // incorrect unwind destination. Create a new range or increment the
1192       // currently existing range.
1193       else {
1194         if (!RangeEnd)
1195           RangeBegin = RangeEnd = &MI;
1196         else
1197           RangeBegin = &MI;
1198       }
1199 
1200       // Update EHPadStack.
1201       if (MI.getOpcode() == WebAssembly::TRY)
1202         EHPadStack.pop_back();
1203       else if (WebAssembly::isCatch(MI.getOpcode()))
1204         EHPadStack.push_back(MI.getParent());
1205     }
1206 
1207     if (RangeEnd)
1208       RecordCallerMismatchRange(EHPadStack.back());
1209   }
1210 
1211   assert(EHPadStack.empty());
1212 
1213   // We don't have any unwind destination mismatches to resolve.
1214   if (UnwindDestToTryRanges.empty())
1215     return false;
1216 
1217   // Now we fix the mismatches by wrapping calls with inner try-delegates.
1218   for (auto &P : UnwindDestToTryRanges) {
1219     NumCallUnwindMismatches += P.second.size();
1220     MachineBasicBlock *UnwindDest = P.first;
1221     auto &TryRanges = P.second;
1222 
1223     for (auto Range : TryRanges) {
1224       MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr;
1225       std::tie(RangeBegin, RangeEnd) = Range;
1226       auto *MBB = RangeBegin->getParent();
1227 
1228       // If this BB has an EH pad successor, i.e., ends with an 'invoke', and if
1229       // the current range contains the invoke, now we are going to wrap the
1230       // invoke with try-delegate, making the 'delegate' BB the new successor
1231       // instead, so remove the EH pad succesor here. The BB may not have an EH
1232       // pad successor if calls in this BB throw to the caller.
1233       if (UnwindDest != getFakeCallerBlock(MF)) {
1234         MachineBasicBlock *EHPad = nullptr;
1235         for (auto *Succ : MBB->successors()) {
1236           if (Succ->isEHPad()) {
1237             EHPad = Succ;
1238             break;
1239           }
1240         }
1241         if (EHPad)
1242           MBB->removeSuccessor(EHPad);
1243       }
1244 
1245       addNestedTryDelegate(RangeBegin, RangeEnd, UnwindDest);
1246     }
1247   }
1248 
1249   return true;
1250 }
1251 
1252 bool WebAssemblyCFGStackify::fixCatchUnwindMismatches(MachineFunction &MF) {
1253   // There is another kind of unwind destination mismatches besides call unwind
1254   // mismatches, which we will call "catch unwind mismatches". See this example
1255   // after the marker placement:
1256   // try
1257   //   try
1258   //     call @foo
1259   //   catch __cpp_exception  ;; ehpad A (next unwind dest: caller)
1260   //     ...
1261   //   end_try
1262   // catch_all                ;; ehpad B
1263   //   ...
1264   // end_try
1265   //
1266   // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo'
1267   // throws a foreign exception that is not caught by ehpad A, and its next
1268   // destination should be the caller. But after control flow linearization,
1269   // another EH pad can be placed in between (e.g. ehpad B here), making the
1270   // next unwind destination incorrect. In this case, the  foreign exception
1271   // will instead go to ehpad B and will be caught there instead. In this
1272   // example the correct next unwind destination is the caller, but it can be
1273   // another outer catch in other cases.
1274   //
1275   // There is no specific 'call' or 'throw' instruction to wrap with a
1276   // try-delegate, so we wrap the whole try-catch-end with a try-delegate and
1277   // make it rethrow to the right destination, as in the example below:
1278   // try
1279   //   try                     ;; (new)
1280   //     try
1281   //       call @foo
1282   //     catch __cpp_exception ;; ehpad A (next unwind dest: caller)
1283   //       ...
1284   //     end_try
1285   //   delegate 1 (caller)     ;; (new)
1286   // catch_all                 ;; ehpad B
1287   //   ...
1288   // end_try
1289 
1290   const auto *EHInfo = MF.getWasmEHFuncInfo();
1291   assert(EHInfo);
1292   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1293   // For EH pads that have catch unwind mismatches, a map of <EH pad, its
1294   // correct unwind destination>.
1295   DenseMap<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest;
1296 
1297   for (auto &MBB : reverse(MF)) {
1298     for (auto &MI : reverse(MBB)) {
1299       if (MI.getOpcode() == WebAssembly::TRY)
1300         EHPadStack.pop_back();
1301       else if (MI.getOpcode() == WebAssembly::DELEGATE)
1302         EHPadStack.push_back(&MBB);
1303       else if (WebAssembly::isCatch(MI.getOpcode())) {
1304         auto *EHPad = &MBB;
1305 
1306         // catch_all always catches an exception, so we don't need to do
1307         // anything
1308         if (MI.getOpcode() == WebAssembly::CATCH_ALL_LEGACY) {
1309         }
1310 
1311         // This can happen when the unwind dest was removed during the
1312         // optimization, e.g. because it was unreachable.
1313         else if (EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) {
1314           LLVM_DEBUG(dbgs() << "EHPad (" << EHPad->getName()
1315                             << "'s unwind destination does not exist anymore"
1316                             << "\n\n");
1317         }
1318 
1319         // The EHPad's next unwind destination is the caller, but we incorrectly
1320         // unwind to another EH pad.
1321         else if (!EHPadStack.empty() && !EHInfo->hasUnwindDest(EHPad)) {
1322           EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF);
1323           LLVM_DEBUG(dbgs()
1324                      << "- Catch unwind mismatch:\nEHPad = " << EHPad->getName()
1325                      << "  Original dest = caller  Current dest = "
1326                      << EHPadStack.back()->getName() << "\n\n");
1327         }
1328 
1329         // The EHPad's next unwind destination is an EH pad, whereas we
1330         // incorrectly unwind to another EH pad.
1331         else if (!EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) {
1332           auto *UnwindDest = EHInfo->getUnwindDest(EHPad);
1333           if (EHPadStack.back() != UnwindDest) {
1334             EHPadToUnwindDest[EHPad] = UnwindDest;
1335             LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = "
1336                               << EHPad->getName() << "  Original dest = "
1337                               << UnwindDest->getName() << "  Current dest = "
1338                               << EHPadStack.back()->getName() << "\n\n");
1339           }
1340         }
1341 
1342         EHPadStack.push_back(EHPad);
1343       }
1344     }
1345   }
1346 
1347   assert(EHPadStack.empty());
1348   if (EHPadToUnwindDest.empty())
1349     return false;
1350   NumCatchUnwindMismatches += EHPadToUnwindDest.size();
1351   SmallPtrSet<MachineBasicBlock *, 4> NewEndTryBBs;
1352 
1353   for (auto &[EHPad, UnwindDest] : EHPadToUnwindDest) {
1354     MachineInstr *Try = EHPadToTry[EHPad];
1355     MachineInstr *EndTry = BeginToEnd[Try];
1356     addNestedTryDelegate(Try, EndTry, UnwindDest);
1357     NewEndTryBBs.insert(EndTry->getParent());
1358   }
1359 
1360   // Adding a try-delegate wrapping an existing try-catch-end can make existing
1361   // branch destination BBs invalid. For example,
1362   //
1363   // - Before:
1364   // bb0:
1365   //   block
1366   //     br bb3
1367   // bb1:
1368   //     try
1369   //       ...
1370   // bb2: (ehpad)
1371   //     catch
1372   // bb3:
1373   //     end_try
1374   //   end_block   ;; 'br bb3' targets here
1375   //
1376   // Suppose this try-catch-end has a catch unwind mismatch, so we need to wrap
1377   // this with a try-delegate. Then this becomes:
1378   //
1379   // - After:
1380   // bb0:
1381   //   block
1382   //     br bb3    ;; invalid destination!
1383   // bb1:
1384   //     try       ;; (new instruction)
1385   //       try
1386   //         ...
1387   // bb2: (ehpad)
1388   //       catch
1389   // bb3:
1390   //       end_try ;; 'br bb3' still incorrectly targets here!
1391   // delegate_bb:  ;; (new BB)
1392   //     delegate  ;; (new instruction)
1393   // split_bb:     ;; (new BB)
1394   //   end_block
1395   //
1396   // Now 'br bb3' incorrectly branches to an inner scope.
1397   //
1398   // As we can see in this case, when branches target a BB that has both
1399   // 'end_try' and 'end_block' and the BB is split to insert a 'delegate', we
1400   // have to remap existing branch destinations so that they target not the
1401   // 'end_try' BB but the new 'end_block' BB. There can be multiple 'delegate's
1402   // in between, so we try to find the next BB with 'end_block' instruction. In
1403   // this example, the 'br bb3' instruction should be remapped to 'br split_bb'.
1404   for (auto &MBB : MF) {
1405     for (auto &MI : MBB) {
1406       if (MI.isTerminator()) {
1407         for (auto &MO : MI.operands()) {
1408           if (MO.isMBB() && NewEndTryBBs.count(MO.getMBB())) {
1409             auto *BrDest = MO.getMBB();
1410             bool FoundEndBlock = false;
1411             for (; std::next(BrDest->getIterator()) != MF.end();
1412                  BrDest = BrDest->getNextNode()) {
1413               for (const auto &MI : *BrDest) {
1414                 if (MI.getOpcode() == WebAssembly::END_BLOCK) {
1415                   FoundEndBlock = true;
1416                   break;
1417                 }
1418               }
1419               if (FoundEndBlock)
1420                 break;
1421             }
1422             assert(FoundEndBlock);
1423             MO.setMBB(BrDest);
1424           }
1425         }
1426       }
1427     }
1428   }
1429 
1430   return true;
1431 }
1432 
1433 void WebAssemblyCFGStackify::recalculateScopeTops(MachineFunction &MF) {
1434   // Renumber BBs and recalculate ScopeTop info because new BBs might have been
1435   // created and inserted during fixing unwind mismatches.
1436   MF.RenumberBlocks();
1437   MDT->updateBlockNumbers();
1438   ScopeTops.clear();
1439   ScopeTops.resize(MF.getNumBlockIDs());
1440   for (auto &MBB : reverse(MF)) {
1441     for (auto &MI : reverse(MBB)) {
1442       if (ScopeTops[MBB.getNumber()])
1443         break;
1444       switch (MI.getOpcode()) {
1445       case WebAssembly::END_BLOCK:
1446       case WebAssembly::END_LOOP:
1447       case WebAssembly::END_TRY:
1448       case WebAssembly::DELEGATE:
1449         updateScopeTops(EndToBegin[&MI]->getParent(), &MBB);
1450         break;
1451       case WebAssembly::CATCH_LEGACY:
1452       case WebAssembly::CATCH_ALL_LEGACY:
1453         updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB);
1454         break;
1455       }
1456     }
1457   }
1458 }
1459 
1460 /// In normal assembly languages, when the end of a function is unreachable,
1461 /// because the function ends in an infinite loop or a noreturn call or similar,
1462 /// it isn't necessary to worry about the function return type at the end of
1463 /// the function, because it's never reached. However, in WebAssembly, blocks
1464 /// that end at the function end need to have a return type signature that
1465 /// matches the function signature, even though it's unreachable. This function
1466 /// checks for such cases and fixes up the signatures.
1467 void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) {
1468   const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
1469 
1470   if (MFI.getResults().empty())
1471     return;
1472 
1473   // MCInstLower will add the proper types to multivalue signatures based on the
1474   // function return type
1475   WebAssembly::BlockType RetType =
1476       MFI.getResults().size() > 1
1477           ? WebAssembly::BlockType::Multivalue
1478           : WebAssembly::BlockType(
1479                 WebAssembly::toValType(MFI.getResults().front()));
1480 
1481   SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist;
1482   Worklist.push_back(MF.rbegin()->rbegin());
1483 
1484   auto Process = [&](MachineBasicBlock::reverse_iterator It) {
1485     auto *MBB = It->getParent();
1486     while (It != MBB->rend()) {
1487       MachineInstr &MI = *It++;
1488       if (MI.isPosition() || MI.isDebugInstr())
1489         continue;
1490       switch (MI.getOpcode()) {
1491       case WebAssembly::END_TRY: {
1492         // If a 'try''s return type is fixed, both its try body and catch body
1493         // should satisfy the return type, so we need to search 'end'
1494         // instructions before its corresponding 'catch' too.
1495         auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]);
1496         assert(EHPad);
1497         auto NextIt =
1498             std::next(WebAssembly::findCatch(EHPad)->getReverseIterator());
1499         if (NextIt != EHPad->rend())
1500           Worklist.push_back(NextIt);
1501         [[fallthrough]];
1502       }
1503       case WebAssembly::END_BLOCK:
1504       case WebAssembly::END_LOOP:
1505       case WebAssembly::DELEGATE:
1506         EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType));
1507         continue;
1508       default:
1509         // Something other than an `end`. We're done for this BB.
1510         return;
1511       }
1512     }
1513     // We've reached the beginning of a BB. Continue the search in the previous
1514     // BB.
1515     Worklist.push_back(MBB->getPrevNode()->rbegin());
1516   };
1517 
1518   while (!Worklist.empty())
1519     Process(Worklist.pop_back_val());
1520 }
1521 
1522 // WebAssembly functions end with an end instruction, as if the function body
1523 // were a block.
1524 static void appendEndToFunction(MachineFunction &MF,
1525                                 const WebAssemblyInstrInfo &TII) {
1526   BuildMI(MF.back(), MF.back().end(),
1527           MF.back().findPrevDebugLoc(MF.back().end()),
1528           TII.get(WebAssembly::END_FUNCTION));
1529 }
1530 
1531 /// Insert BLOCK/LOOP/TRY markers at appropriate places.
1532 void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) {
1533   // We allocate one more than the number of blocks in the function to
1534   // accommodate for the possible fake block we may insert at the end.
1535   ScopeTops.resize(MF.getNumBlockIDs() + 1);
1536   // Place the LOOP for MBB if MBB is the header of a loop.
1537   for (auto &MBB : MF)
1538     placeLoopMarker(MBB);
1539 
1540   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1541   for (auto &MBB : MF) {
1542     if (MBB.isEHPad()) {
1543       // Place the TRY for MBB if MBB is the EH pad of an exception.
1544       if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1545           MF.getFunction().hasPersonalityFn())
1546         placeTryMarker(MBB);
1547     } else {
1548       // Place the BLOCK for MBB if MBB is branched to from above.
1549       placeBlockMarker(MBB);
1550     }
1551   }
1552   // Fix mismatches in unwind destinations induced by linearizing the code.
1553   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1554       MF.getFunction().hasPersonalityFn()) {
1555     bool MismatchFixed = fixCallUnwindMismatches(MF);
1556     MismatchFixed |= fixCatchUnwindMismatches(MF);
1557     if (MismatchFixed)
1558       recalculateScopeTops(MF);
1559   }
1560 }
1561 
1562 unsigned WebAssemblyCFGStackify::getBranchDepth(
1563     const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
1564   unsigned Depth = 0;
1565   for (auto X : reverse(Stack)) {
1566     if (X.first == MBB)
1567       break;
1568     ++Depth;
1569   }
1570   assert(Depth < Stack.size() && "Branch destination should be in scope");
1571   return Depth;
1572 }
1573 
1574 unsigned WebAssemblyCFGStackify::getDelegateDepth(
1575     const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) {
1576   if (MBB == FakeCallerBB)
1577     return Stack.size();
1578   // Delegate's destination is either a catch or a another delegate BB. When the
1579   // destination is another delegate, we can compute the argument in the same
1580   // way as branches, because the target delegate BB only contains the single
1581   // delegate instruction.
1582   if (!MBB->isEHPad()) // Target is a delegate BB
1583     return getBranchDepth(Stack, MBB);
1584 
1585   // When the delegate's destination is a catch BB, we need to use its
1586   // corresponding try's end_try BB because Stack contains each marker's end BB.
1587   // Also we need to check if the end marker instruction matches, because a
1588   // single BB can contain multiple end markers, like this:
1589   // bb:
1590   //   END_BLOCK
1591   //   END_TRY
1592   //   END_BLOCK
1593   //   END_TRY
1594   //   ...
1595   //
1596   // In case of branches getting the immediate that targets any of these is
1597   // fine, but delegate has to exactly target the correct try.
1598   unsigned Depth = 0;
1599   const MachineInstr *EndTry = BeginToEnd[EHPadToTry[MBB]];
1600   for (auto X : reverse(Stack)) {
1601     if (X.first == EndTry->getParent() && X.second == EndTry)
1602       break;
1603     ++Depth;
1604   }
1605   assert(Depth < Stack.size() && "Delegate destination should be in scope");
1606   return Depth;
1607 }
1608 
1609 unsigned WebAssemblyCFGStackify::getRethrowDepth(
1610     const SmallVectorImpl<EndMarkerInfo> &Stack,
1611     const SmallVectorImpl<const MachineBasicBlock *> &EHPadStack) {
1612   unsigned Depth = 0;
1613   // In our current implementation, rethrows always rethrow the exception caught
1614   // by the innermost enclosing catch. This means while traversing Stack in the
1615   // reverse direction, when we encounter END_TRY, we should check if the
1616   // END_TRY corresponds to the current innermost EH pad. For example:
1617   // try
1618   //   ...
1619   // catch         ;; (a)
1620   //   try
1621   //     rethrow 1 ;; (b)
1622   //   catch       ;; (c)
1623   //     rethrow 0 ;; (d)
1624   //   end         ;; (e)
1625   // end           ;; (f)
1626   //
1627   // When we are at 'rethrow' (d), while reversely traversing Stack the first
1628   // 'end' we encounter is the 'end' (e), which corresponds to the 'catch' (c).
1629   // And 'rethrow' (d) rethrows the exception caught by 'catch' (c), so we stop
1630   // there and the depth should be 0. But when we are at 'rethrow' (b), it
1631   // rethrows the exception caught by 'catch' (a), so when traversing Stack
1632   // reversely, we should skip the 'end' (e) and choose 'end' (f), which
1633   // corresponds to 'catch' (a).
1634   for (auto X : reverse(Stack)) {
1635     const MachineInstr *End = X.second;
1636     if (End->getOpcode() == WebAssembly::END_TRY) {
1637       auto *EHPad = TryToEHPad[EndToBegin[End]];
1638       if (EHPadStack.back() == EHPad)
1639         break;
1640     }
1641     ++Depth;
1642   }
1643   assert(Depth < Stack.size() && "Rethrow destination should be in scope");
1644   return Depth;
1645 }
1646 
1647 void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) {
1648   // Now rewrite references to basic blocks to be depth immediates.
1649   SmallVector<EndMarkerInfo, 8> Stack;
1650   SmallVector<const MachineBasicBlock *, 8> EHPadStack;
1651 
1652   auto RewriteOperands = [&](MachineInstr &MI) {
1653     // Rewrite MBB operands to be depth immediates.
1654     SmallVector<MachineOperand, 4> Ops(MI.operands());
1655     while (MI.getNumOperands() > 0)
1656       MI.removeOperand(MI.getNumOperands() - 1);
1657     for (auto MO : Ops) {
1658       if (MO.isMBB()) {
1659         if (MI.getOpcode() == WebAssembly::DELEGATE)
1660           MO = MachineOperand::CreateImm(getDelegateDepth(Stack, MO.getMBB()));
1661         else
1662           MO = MachineOperand::CreateImm(getBranchDepth(Stack, MO.getMBB()));
1663       }
1664       MI.addOperand(MF, MO);
1665     }
1666   };
1667 
1668   for (auto &MBB : reverse(MF)) {
1669     for (MachineInstr &MI : llvm::reverse(MBB)) {
1670       switch (MI.getOpcode()) {
1671       case WebAssembly::BLOCK:
1672       case WebAssembly::TRY:
1673         assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <=
1674                    MBB.getNumber() &&
1675                "Block/try marker should be balanced");
1676         Stack.pop_back();
1677         break;
1678 
1679       case WebAssembly::LOOP:
1680         assert(Stack.back().first == &MBB && "Loop top should be balanced");
1681         Stack.pop_back();
1682         break;
1683 
1684       case WebAssembly::END_TRY: {
1685         auto *EHPad = TryToEHPad[EndToBegin[&MI]];
1686         EHPadStack.push_back(EHPad);
1687         [[fallthrough]];
1688       }
1689       case WebAssembly::END_BLOCK:
1690         Stack.push_back(std::make_pair(&MBB, &MI));
1691         break;
1692 
1693       case WebAssembly::END_LOOP:
1694         Stack.push_back(std::make_pair(EndToBegin[&MI]->getParent(), &MI));
1695         break;
1696 
1697       case WebAssembly::CATCH_LEGACY:
1698       case WebAssembly::CATCH_ALL_LEGACY:
1699         EHPadStack.pop_back();
1700         break;
1701 
1702       case WebAssembly::RETHROW:
1703         MI.getOperand(0).setImm(getRethrowDepth(Stack, EHPadStack));
1704         break;
1705 
1706       case WebAssembly::DELEGATE:
1707         RewriteOperands(MI);
1708         Stack.push_back(std::make_pair(&MBB, &MI));
1709         break;
1710 
1711       default:
1712         if (MI.isTerminator())
1713           RewriteOperands(MI);
1714         break;
1715       }
1716     }
1717   }
1718   assert(Stack.empty() && "Control flow should be balanced");
1719 }
1720 
1721 void WebAssemblyCFGStackify::cleanupFunctionData(MachineFunction &MF) {
1722   if (FakeCallerBB)
1723     MF.deleteMachineBasicBlock(FakeCallerBB);
1724   AppendixBB = FakeCallerBB = nullptr;
1725 }
1726 
1727 void WebAssemblyCFGStackify::releaseMemory() {
1728   ScopeTops.clear();
1729   BeginToEnd.clear();
1730   EndToBegin.clear();
1731   TryToEHPad.clear();
1732   EHPadToTry.clear();
1733 }
1734 
1735 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
1736   LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
1737                        "********** Function: "
1738                     << MF.getName() << '\n');
1739   const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo();
1740   MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1741 
1742   releaseMemory();
1743 
1744   // Liveness is not tracked for VALUE_STACK physreg.
1745   MF.getRegInfo().invalidateLiveness();
1746 
1747   // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes.
1748   placeMarkers(MF);
1749 
1750   // Remove unnecessary instructions possibly introduced by try/end_trys.
1751   if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm &&
1752       MF.getFunction().hasPersonalityFn())
1753     removeUnnecessaryInstrs(MF);
1754 
1755   // Convert MBB operands in terminators to relative depth immediates.
1756   rewriteDepthImmediates(MF);
1757 
1758   // Fix up block/loop/try signatures at the end of the function to conform to
1759   // WebAssembly's rules.
1760   fixEndsAtEndOfFunction(MF);
1761 
1762   // Add an end instruction at the end of the function body.
1763   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1764   appendEndToFunction(MF, TII);
1765 
1766   cleanupFunctionData(MF);
1767 
1768   MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified();
1769   return true;
1770 }
1771