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 "MCTargetDesc/WebAssemblyMCTargetDesc.h" 25 #include "WebAssembly.h" 26 #include "WebAssemblyExceptionInfo.h" 27 #include "WebAssemblyMachineFunctionInfo.h" 28 #include "WebAssemblySubtarget.h" 29 #include "WebAssemblyUtilities.h" 30 #include "llvm/CodeGen/MachineDominators.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineLoopInfo.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/Passes.h" 36 #include "llvm/CodeGen/WasmEHFuncInfo.h" 37 #include "llvm/MC/MCAsmInfo.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <cstring> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "wasm-cfg-stackify" 44 45 namespace { 46 class WebAssemblyCFGStackify final : public MachineFunctionPass { 47 StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 48 49 void getAnalysisUsage(AnalysisUsage &AU) const override { 50 AU.addRequired<MachineDominatorTree>(); 51 AU.addRequired<MachineLoopInfo>(); 52 AU.addRequired<WebAssemblyExceptionInfo>(); 53 MachineFunctionPass::getAnalysisUsage(AU); 54 } 55 56 bool runOnMachineFunction(MachineFunction &MF) override; 57 58 // For each block whose label represents the end of a scope, record the block 59 // which holds the beginning of the scope. This will allow us to quickly skip 60 // over scoped regions when walking blocks. 61 SmallVector<MachineBasicBlock *, 8> ScopeTops; 62 63 void placeMarkers(MachineFunction &MF); 64 void placeBlockMarker(MachineBasicBlock &MBB); 65 void placeLoopMarker(MachineBasicBlock &MBB); 66 void placeTryMarker(MachineBasicBlock &MBB); 67 void removeUnnecessaryInstrs(MachineFunction &MF); 68 void rewriteDepthImmediates(MachineFunction &MF); 69 void fixEndsAtEndOfFunction(MachineFunction &MF); 70 71 // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY). 72 DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 73 // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY. 74 DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 75 // <TRY marker, EH pad> map 76 DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 77 // <EH pad, TRY marker> map 78 DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 79 80 // Helper functions to register / unregister scope information created by 81 // marker instructions. 82 void registerScope(MachineInstr *Begin, MachineInstr *End); 83 void registerTryScope(MachineInstr *Begin, MachineInstr *End, 84 MachineBasicBlock *EHPad); 85 void unregisterScope(MachineInstr *Begin); 86 87 public: 88 static char ID; // Pass identification, replacement for typeid 89 WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 90 ~WebAssemblyCFGStackify() override { releaseMemory(); } 91 void releaseMemory() override; 92 }; 93 } // end anonymous namespace 94 95 char WebAssemblyCFGStackify::ID = 0; 96 INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 97 "Insert BLOCK and LOOP markers for WebAssembly scopes", false, 98 false) 99 100 FunctionPass *llvm::createWebAssemblyCFGStackify() { 101 return new WebAssemblyCFGStackify(); 102 } 103 104 /// Test whether Pred has any terminators explicitly branching to MBB, as 105 /// opposed to falling through. Note that it's possible (eg. in unoptimized 106 /// code) for a branch instruction to both branch to a block and fallthrough 107 /// to it, so we check the actual branch operands to see if there are any 108 /// explicit mentions. 109 static bool explicitlyBranchesTo(MachineBasicBlock *Pred, 110 MachineBasicBlock *MBB) { 111 for (MachineInstr &MI : Pred->terminators()) 112 for (MachineOperand &MO : MI.explicit_operands()) 113 if (MO.isMBB() && MO.getMBB() == MBB) 114 return true; 115 return false; 116 } 117 118 // Returns an iterator to the earliest position possible within the MBB, 119 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 120 // contains instructions that should go before the marker, and AfterSet contains 121 // ones that should go after the marker. In this function, AfterSet is only 122 // used for sanity checking. 123 static MachineBasicBlock::iterator 124 getEarliestInsertPos(MachineBasicBlock *MBB, 125 const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 126 const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 127 auto InsertPos = MBB->end(); 128 while (InsertPos != MBB->begin()) { 129 if (BeforeSet.count(&*std::prev(InsertPos))) { 130 #ifndef NDEBUG 131 // Sanity check 132 for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 133 assert(!AfterSet.count(&*std::prev(Pos))); 134 #endif 135 break; 136 } 137 --InsertPos; 138 } 139 return InsertPos; 140 } 141 142 // Returns an iterator to the latest position possible within the MBB, 143 // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 144 // contains instructions that should go before the marker, and AfterSet contains 145 // ones that should go after the marker. In this function, BeforeSet is only 146 // used for sanity checking. 147 static MachineBasicBlock::iterator 148 getLatestInsertPos(MachineBasicBlock *MBB, 149 const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 150 const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 151 auto InsertPos = MBB->begin(); 152 while (InsertPos != MBB->end()) { 153 if (AfterSet.count(&*InsertPos)) { 154 #ifndef NDEBUG 155 // Sanity check 156 for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 157 assert(!BeforeSet.count(&*Pos)); 158 #endif 159 break; 160 } 161 ++InsertPos; 162 } 163 return InsertPos; 164 } 165 166 void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 167 MachineInstr *End) { 168 BeginToEnd[Begin] = End; 169 EndToBegin[End] = Begin; 170 } 171 172 void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 173 MachineInstr *End, 174 MachineBasicBlock *EHPad) { 175 registerScope(Begin, End); 176 TryToEHPad[Begin] = EHPad; 177 EHPadToTry[EHPad] = Begin; 178 } 179 180 void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 181 assert(BeginToEnd.count(Begin)); 182 MachineInstr *End = BeginToEnd[Begin]; 183 assert(EndToBegin.count(End)); 184 BeginToEnd.erase(Begin); 185 EndToBegin.erase(End); 186 MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 187 if (EHPad) { 188 assert(EHPadToTry.count(EHPad)); 189 TryToEHPad.erase(Begin); 190 EHPadToTry.erase(EHPad); 191 } 192 } 193 194 /// Insert a BLOCK marker for branches to MBB (if needed). 195 void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 196 // This should have been handled in placeTryMarker. 197 if (MBB.isEHPad()) 198 return; 199 200 MachineFunction &MF = *MBB.getParent(); 201 auto &MDT = getAnalysis<MachineDominatorTree>(); 202 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 203 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 204 205 // First compute the nearest common dominator of all forward non-fallthrough 206 // predecessors so that we minimize the time that the BLOCK is on the stack, 207 // which reduces overall stack height. 208 MachineBasicBlock *Header = nullptr; 209 bool IsBranchedTo = false; 210 bool IsBrOnExn = false; 211 MachineInstr *BrOnExn = nullptr; 212 int MBBNumber = MBB.getNumber(); 213 for (MachineBasicBlock *Pred : MBB.predecessors()) { 214 if (Pred->getNumber() < MBBNumber) { 215 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 216 if (explicitlyBranchesTo(Pred, &MBB)) { 217 IsBranchedTo = true; 218 if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) { 219 IsBrOnExn = true; 220 assert(!BrOnExn && "There should be only one br_on_exn per block"); 221 BrOnExn = &*Pred->getFirstTerminator(); 222 } 223 } 224 } 225 } 226 if (!Header) 227 return; 228 if (!IsBranchedTo) 229 return; 230 231 assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 232 MachineBasicBlock *LayoutPred = MBB.getPrevNode(); 233 234 // If the nearest common dominator is inside a more deeply nested context, 235 // walk out to the nearest scope which isn't more deeply nested. 236 for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 237 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 238 if (ScopeTop->getNumber() > Header->getNumber()) { 239 // Skip over an intervening scope. 240 I = std::next(ScopeTop->getIterator()); 241 } else { 242 // We found a scope level at an appropriate depth. 243 Header = ScopeTop; 244 break; 245 } 246 } 247 } 248 249 // Decide where in Header to put the BLOCK. 250 251 // Instructions that should go before the BLOCK. 252 SmallPtrSet<const MachineInstr *, 4> BeforeSet; 253 // Instructions that should go after the BLOCK. 254 SmallPtrSet<const MachineInstr *, 4> AfterSet; 255 for (const auto &MI : *Header) { 256 // If there is a previously placed LOOP/TRY marker and the bottom block of 257 // the loop/exception is above MBB, it should be after the BLOCK, because 258 // the loop/exception is nested in this block. Otherwise it should be before 259 // the BLOCK. 260 if (MI.getOpcode() == WebAssembly::LOOP || 261 MI.getOpcode() == WebAssembly::TRY) { 262 auto *BottomBB = BeginToEnd[&MI]->getParent()->getPrevNode(); 263 if (MBB.getNumber() > BottomBB->getNumber()) 264 AfterSet.insert(&MI); 265 #ifndef NDEBUG 266 else 267 BeforeSet.insert(&MI); 268 #endif 269 } 270 271 // All previously inserted BLOCK markers should be after the BLOCK because 272 // they are all nested blocks. 273 if (MI.getOpcode() == WebAssembly::BLOCK) 274 AfterSet.insert(&MI); 275 276 #ifndef NDEBUG 277 // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 278 if (MI.getOpcode() == WebAssembly::END_BLOCK || 279 MI.getOpcode() == WebAssembly::END_LOOP || 280 MI.getOpcode() == WebAssembly::END_TRY) 281 BeforeSet.insert(&MI); 282 #endif 283 284 // Terminators should go after the BLOCK. 285 if (MI.isTerminator()) 286 AfterSet.insert(&MI); 287 } 288 289 // Local expression tree should go after the BLOCK. 290 for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 291 --I) { 292 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 293 continue; 294 if (WebAssembly::isChild(*std::prev(I), MFI)) 295 AfterSet.insert(&*std::prev(I)); 296 else 297 break; 298 } 299 300 // Add the BLOCK. 301 302 // 'br_on_exn' extracts except_ref object and pushes variable number of values 303 // depending on its tag. For C++ exception, its a single i32 value, and the 304 // generated code will be in the form of: 305 // block i32 306 // br_on_exn 0, $__cpp_exception 307 // rethrow 308 // end_block 309 WebAssembly::ExprType ReturnType = WebAssembly::ExprType::Void; 310 if (IsBrOnExn) { 311 const char *TagName = BrOnExn->getOperand(1).getSymbolName(); 312 if (std::strcmp(TagName, "__cpp_exception") != 0) 313 llvm_unreachable("Only C++ exception is supported"); 314 ReturnType = WebAssembly::ExprType::I32; 315 } 316 317 auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 318 MachineInstr *Begin = 319 BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 320 TII.get(WebAssembly::BLOCK)) 321 .addImm(int64_t(ReturnType)); 322 323 // Decide where in Header to put the END_BLOCK. 324 BeforeSet.clear(); 325 AfterSet.clear(); 326 for (auto &MI : MBB) { 327 #ifndef NDEBUG 328 // END_BLOCK should precede existing LOOP and TRY markers. 329 if (MI.getOpcode() == WebAssembly::LOOP || 330 MI.getOpcode() == WebAssembly::TRY) 331 AfterSet.insert(&MI); 332 #endif 333 334 // If there is a previously placed END_LOOP marker and the header of the 335 // loop is above this block's header, the END_LOOP should be placed after 336 // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 337 // should be placed before the BLOCK. The same for END_TRY. 338 if (MI.getOpcode() == WebAssembly::END_LOOP || 339 MI.getOpcode() == WebAssembly::END_TRY) { 340 if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 341 BeforeSet.insert(&MI); 342 #ifndef NDEBUG 343 else 344 AfterSet.insert(&MI); 345 #endif 346 } 347 } 348 349 // Mark the end of the block. 350 InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 351 MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 352 TII.get(WebAssembly::END_BLOCK)); 353 registerScope(Begin, End); 354 355 // Track the farthest-spanning scope that ends at this point. 356 int Number = MBB.getNumber(); 357 if (!ScopeTops[Number] || 358 ScopeTops[Number]->getNumber() > Header->getNumber()) 359 ScopeTops[Number] = Header; 360 } 361 362 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 363 void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 364 MachineFunction &MF = *MBB.getParent(); 365 const auto &MLI = getAnalysis<MachineLoopInfo>(); 366 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 367 368 MachineLoop *Loop = MLI.getLoopFor(&MBB); 369 if (!Loop || Loop->getHeader() != &MBB) 370 return; 371 372 // The operand of a LOOP is the first block after the loop. If the loop is the 373 // bottom of the function, insert a dummy block at the end. 374 MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop); 375 auto Iter = std::next(Bottom->getIterator()); 376 if (Iter == MF.end()) { 377 MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 378 // Give it a fake predecessor so that AsmPrinter prints its label. 379 Label->addSuccessor(Label); 380 MF.push_back(Label); 381 Iter = std::next(Bottom->getIterator()); 382 } 383 MachineBasicBlock *AfterLoop = &*Iter; 384 385 // Decide where in Header to put the LOOP. 386 SmallPtrSet<const MachineInstr *, 4> BeforeSet; 387 SmallPtrSet<const MachineInstr *, 4> AfterSet; 388 for (const auto &MI : MBB) { 389 // LOOP marker should be after any existing loop that ends here. Otherwise 390 // we assume the instruction belongs to the loop. 391 if (MI.getOpcode() == WebAssembly::END_LOOP) 392 BeforeSet.insert(&MI); 393 #ifndef NDEBUG 394 else 395 AfterSet.insert(&MI); 396 #endif 397 } 398 399 // Mark the beginning of the loop. 400 auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 401 MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 402 TII.get(WebAssembly::LOOP)) 403 .addImm(int64_t(WebAssembly::ExprType::Void)); 404 405 // Decide where in Header to put the END_LOOP. 406 BeforeSet.clear(); 407 AfterSet.clear(); 408 #ifndef NDEBUG 409 for (const auto &MI : MBB) 410 // Existing END_LOOP markers belong to parent loops of this loop 411 if (MI.getOpcode() == WebAssembly::END_LOOP) 412 AfterSet.insert(&MI); 413 #endif 414 415 // Mark the end of the loop (using arbitrary debug location that branched to 416 // the loop end as its location). 417 InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 418 DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 419 MachineInstr *End = 420 BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 421 registerScope(Begin, End); 422 423 assert((!ScopeTops[AfterLoop->getNumber()] || 424 ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 425 "With block sorting the outermost loop for a block should be first."); 426 if (!ScopeTops[AfterLoop->getNumber()]) 427 ScopeTops[AfterLoop->getNumber()] = &MBB; 428 } 429 430 void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 431 if (!MBB.isEHPad()) 432 return; 433 434 MachineFunction &MF = *MBB.getParent(); 435 auto &MDT = getAnalysis<MachineDominatorTree>(); 436 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 437 const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 438 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 439 440 // Compute the nearest common dominator of all unwind predecessors 441 MachineBasicBlock *Header = nullptr; 442 int MBBNumber = MBB.getNumber(); 443 for (auto *Pred : MBB.predecessors()) { 444 if (Pred->getNumber() < MBBNumber) { 445 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 446 assert(!explicitlyBranchesTo(Pred, &MBB) && 447 "Explicit branch to an EH pad!"); 448 } 449 } 450 if (!Header) 451 return; 452 453 // If this try is at the bottom of the function, insert a dummy block at the 454 // end. 455 WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 456 assert(WE); 457 MachineBasicBlock *Bottom = WebAssembly::getBottom(WE); 458 459 auto Iter = std::next(Bottom->getIterator()); 460 if (Iter == MF.end()) { 461 MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 462 // Give it a fake predecessor so that AsmPrinter prints its label. 463 Label->addSuccessor(Label); 464 MF.push_back(Label); 465 Iter = std::next(Bottom->getIterator()); 466 } 467 MachineBasicBlock *Cont = &*Iter; 468 469 assert(Cont != &MF.front()); 470 MachineBasicBlock *LayoutPred = Cont->getPrevNode(); 471 472 // If the nearest common dominator is inside a more deeply nested context, 473 // walk out to the nearest scope which isn't more deeply nested. 474 for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 475 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 476 if (ScopeTop->getNumber() > Header->getNumber()) { 477 // Skip over an intervening scope. 478 I = std::next(ScopeTop->getIterator()); 479 } else { 480 // We found a scope level at an appropriate depth. 481 Header = ScopeTop; 482 break; 483 } 484 } 485 } 486 487 // Decide where in Header to put the TRY. 488 489 // Instructions that should go before the BLOCK. 490 SmallPtrSet<const MachineInstr *, 4> BeforeSet; 491 // Instructions that should go after the BLOCK. 492 SmallPtrSet<const MachineInstr *, 4> AfterSet; 493 for (const auto &MI : *Header) { 494 // If there is a previously placed LOOP marker and the bottom block of 495 // the loop is above MBB, the LOOP should be after the TRY, because the 496 // loop is nested in this try. Otherwise it should be before the TRY. 497 if (MI.getOpcode() == WebAssembly::LOOP) { 498 if (MBB.getNumber() > Bottom->getNumber()) 499 AfterSet.insert(&MI); 500 #ifndef NDEBUG 501 else 502 BeforeSet.insert(&MI); 503 #endif 504 } 505 506 // All previously inserted TRY markers should be after the TRY because they 507 // are all nested trys. 508 if (MI.getOpcode() == WebAssembly::TRY) 509 AfterSet.insert(&MI); 510 511 #ifndef NDEBUG 512 // All END_(LOOP/TRY) markers should be before the TRY. 513 if (MI.getOpcode() == WebAssembly::END_LOOP || 514 MI.getOpcode() == WebAssembly::END_TRY) 515 BeforeSet.insert(&MI); 516 #endif 517 518 // Terminators should go after the TRY. 519 if (MI.isTerminator()) 520 AfterSet.insert(&MI); 521 } 522 523 // Local expression tree should go after the TRY. 524 for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 525 --I) { 526 if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 527 continue; 528 if (WebAssembly::isChild(*std::prev(I), MFI)) 529 AfterSet.insert(&*std::prev(I)); 530 else 531 break; 532 } 533 534 // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 535 // contain the call within it. So the call should go after the TRY. The 536 // exception is when the header's terminator is a rethrow instruction, in 537 // which case that instruction, not a call instruction before it, is gonna 538 // throw. 539 if (MBB.isPredecessor(Header)) { 540 auto TermPos = Header->getFirstTerminator(); 541 if (TermPos == Header->end() || 542 TermPos->getOpcode() != WebAssembly::RETHROW) { 543 for (const auto &MI : reverse(*Header)) { 544 if (MI.isCall()) { 545 AfterSet.insert(&MI); 546 break; 547 } 548 } 549 } 550 } 551 552 // Add the TRY. 553 auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 554 MachineInstr *Begin = 555 BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 556 TII.get(WebAssembly::TRY)) 557 .addImm(int64_t(WebAssembly::ExprType::Void)); 558 559 // Decide where in Header to put the END_TRY. 560 BeforeSet.clear(); 561 AfterSet.clear(); 562 for (const auto &MI : *Cont) { 563 #ifndef NDEBUG 564 // END_TRY should precede existing LOOP markers. 565 if (MI.getOpcode() == WebAssembly::LOOP) 566 AfterSet.insert(&MI); 567 568 // All END_TRY markers placed earlier belong to exceptions that contains 569 // this one. 570 if (MI.getOpcode() == WebAssembly::END_TRY) 571 AfterSet.insert(&MI); 572 #endif 573 574 // If there is a previously placed END_LOOP marker and its header is after 575 // where TRY marker is, this loop is contained within the 'catch' part, so 576 // the END_TRY marker should go after that. Otherwise, the whole try-catch 577 // is contained within this loop, so the END_TRY should go before that. 578 if (MI.getOpcode() == WebAssembly::END_LOOP) { 579 if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 580 BeforeSet.insert(&MI); 581 #ifndef NDEBUG 582 else 583 AfterSet.insert(&MI); 584 #endif 585 } 586 } 587 588 // Mark the end of the TRY. 589 InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet); 590 MachineInstr *End = 591 BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(), 592 TII.get(WebAssembly::END_TRY)); 593 registerTryScope(Begin, End, &MBB); 594 595 // Track the farthest-spanning scope that ends at this point. We create two 596 // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB 597 // with 'try'). We need to create 'catch' -> 'try' mapping here too because 598 // markers should not span across 'catch'. For example, this should not 599 // happen: 600 // 601 // try 602 // block --| (X) 603 // catch | 604 // end_block --| 605 // end_try 606 for (int Number : {Cont->getNumber(), MBB.getNumber()}) { 607 if (!ScopeTops[Number] || 608 ScopeTops[Number]->getNumber() > Header->getNumber()) 609 ScopeTops[Number] = Header; 610 } 611 } 612 613 void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) { 614 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 615 616 // When there is an unconditional branch right before a catch instruction and 617 // it branches to the end of end_try marker, we don't need the branch, because 618 // it there is no exception, the control flow transfers to that point anyway. 619 // bb0: 620 // try 621 // ... 622 // br bb2 <- Not necessary 623 // bb1: 624 // catch 625 // ... 626 // bb2: 627 // end 628 for (auto &MBB : MF) { 629 if (!MBB.isEHPad()) 630 continue; 631 632 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 633 SmallVector<MachineOperand, 4> Cond; 634 MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode(); 635 MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent(); 636 bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 637 if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) || 638 (!Cond.empty() && FBB && FBB == Cont))) 639 TII.removeBranch(*EHPadLayoutPred); 640 } 641 642 // When there are block / end_block markers that overlap with try / end_try 643 // markers, and the block and try markers' return types are the same, the 644 // block /end_block markers are not necessary, because try / end_try markers 645 // also can serve as boundaries for branches. 646 // block <- Not necessary 647 // try 648 // ... 649 // catch 650 // ... 651 // end 652 // end <- Not necessary 653 SmallVector<MachineInstr *, 32> ToDelete; 654 for (auto &MBB : MF) { 655 for (auto &MI : MBB) { 656 if (MI.getOpcode() != WebAssembly::TRY) 657 continue; 658 659 MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try]; 660 MachineBasicBlock *TryBB = Try->getParent(); 661 MachineBasicBlock *Cont = EndTry->getParent(); 662 int64_t RetType = Try->getOperand(0).getImm(); 663 for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator()); 664 B != TryBB->begin() && E != Cont->end() && 665 std::prev(B)->getOpcode() == WebAssembly::BLOCK && 666 E->getOpcode() == WebAssembly::END_BLOCK && 667 std::prev(B)->getOperand(0).getImm() == RetType; 668 --B, ++E) { 669 ToDelete.push_back(&*std::prev(B)); 670 ToDelete.push_back(&*E); 671 } 672 } 673 } 674 for (auto *MI : ToDelete) { 675 if (MI->getOpcode() == WebAssembly::BLOCK) 676 unregisterScope(MI); 677 MI->eraseFromParent(); 678 } 679 } 680 681 static unsigned 682 getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 683 const MachineBasicBlock *MBB) { 684 unsigned Depth = 0; 685 for (auto X : reverse(Stack)) { 686 if (X == MBB) 687 break; 688 ++Depth; 689 } 690 assert(Depth < Stack.size() && "Branch destination should be in scope"); 691 return Depth; 692 } 693 694 /// In normal assembly languages, when the end of a function is unreachable, 695 /// because the function ends in an infinite loop or a noreturn call or similar, 696 /// it isn't necessary to worry about the function return type at the end of 697 /// the function, because it's never reached. However, in WebAssembly, blocks 698 /// that end at the function end need to have a return type signature that 699 /// matches the function signature, even though it's unreachable. This function 700 /// checks for such cases and fixes up the signatures. 701 void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 702 const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 703 assert(MFI.getResults().size() <= 1); 704 705 if (MFI.getResults().empty()) 706 return; 707 708 WebAssembly::ExprType RetType; 709 switch (MFI.getResults().front().SimpleTy) { 710 case MVT::i32: 711 RetType = WebAssembly::ExprType::I32; 712 break; 713 case MVT::i64: 714 RetType = WebAssembly::ExprType::I64; 715 break; 716 case MVT::f32: 717 RetType = WebAssembly::ExprType::F32; 718 break; 719 case MVT::f64: 720 RetType = WebAssembly::ExprType::F64; 721 break; 722 case MVT::v16i8: 723 case MVT::v8i16: 724 case MVT::v4i32: 725 case MVT::v2i64: 726 case MVT::v4f32: 727 case MVT::v2f64: 728 RetType = WebAssembly::ExprType::V128; 729 break; 730 case MVT::ExceptRef: 731 RetType = WebAssembly::ExprType::ExceptRef; 732 break; 733 default: 734 llvm_unreachable("unexpected return type"); 735 } 736 737 for (MachineBasicBlock &MBB : reverse(MF)) { 738 for (MachineInstr &MI : reverse(MBB)) { 739 if (MI.isPosition() || MI.isDebugInstr()) 740 continue; 741 if (MI.getOpcode() == WebAssembly::END_BLOCK) { 742 EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType)); 743 continue; 744 } 745 if (MI.getOpcode() == WebAssembly::END_LOOP) { 746 EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType)); 747 continue; 748 } 749 // Something other than an `end`. We're done. 750 return; 751 } 752 } 753 } 754 755 // WebAssembly functions end with an end instruction, as if the function body 756 // were a block. 757 static void appendEndToFunction(MachineFunction &MF, 758 const WebAssemblyInstrInfo &TII) { 759 BuildMI(MF.back(), MF.back().end(), 760 MF.back().findPrevDebugLoc(MF.back().end()), 761 TII.get(WebAssembly::END_FUNCTION)); 762 } 763 764 /// Insert LOOP/TRY/BLOCK markers at appropriate places. 765 void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 766 // We allocate one more than the number of blocks in the function to 767 // accommodate for the possible fake block we may insert at the end. 768 ScopeTops.resize(MF.getNumBlockIDs() + 1); 769 // Place the LOOP for MBB if MBB is the header of a loop. 770 for (auto &MBB : MF) 771 placeLoopMarker(MBB); 772 // Place the TRY for MBB if MBB is the EH pad of an exception. 773 const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 774 if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 775 MF.getFunction().hasPersonalityFn()) 776 for (auto &MBB : MF) 777 placeTryMarker(MBB); 778 // Place the BLOCK for MBB if MBB is branched to from above. 779 for (auto &MBB : MF) 780 placeBlockMarker(MBB); 781 } 782 783 void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 784 // Now rewrite references to basic blocks to be depth immediates. 785 SmallVector<const MachineBasicBlock *, 8> Stack; 786 for (auto &MBB : reverse(MF)) { 787 for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 788 MachineInstr &MI = *I; 789 switch (MI.getOpcode()) { 790 case WebAssembly::BLOCK: 791 case WebAssembly::TRY: 792 assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 793 MBB.getNumber() && 794 "Block/try marker should be balanced"); 795 Stack.pop_back(); 796 break; 797 798 case WebAssembly::LOOP: 799 assert(Stack.back() == &MBB && "Loop top should be balanced"); 800 Stack.pop_back(); 801 break; 802 803 case WebAssembly::END_BLOCK: 804 case WebAssembly::END_TRY: 805 Stack.push_back(&MBB); 806 break; 807 808 case WebAssembly::END_LOOP: 809 Stack.push_back(EndToBegin[&MI]->getParent()); 810 break; 811 812 default: 813 if (MI.isTerminator()) { 814 // Rewrite MBB operands to be depth immediates. 815 SmallVector<MachineOperand, 4> Ops(MI.operands()); 816 while (MI.getNumOperands() > 0) 817 MI.RemoveOperand(MI.getNumOperands() - 1); 818 for (auto MO : Ops) { 819 if (MO.isMBB()) 820 MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB())); 821 MI.addOperand(MF, MO); 822 } 823 } 824 break; 825 } 826 } 827 } 828 assert(Stack.empty() && "Control flow should be balanced"); 829 } 830 831 void WebAssemblyCFGStackify::releaseMemory() { 832 ScopeTops.clear(); 833 BeginToEnd.clear(); 834 EndToBegin.clear(); 835 TryToEHPad.clear(); 836 EHPadToTry.clear(); 837 } 838 839 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 840 LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 841 "********** Function: " 842 << MF.getName() << '\n'); 843 const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 844 845 releaseMemory(); 846 847 // Liveness is not tracked for VALUE_STACK physreg. 848 MF.getRegInfo().invalidateLiveness(); 849 850 // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 851 placeMarkers(MF); 852 853 if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 854 MF.getFunction().hasPersonalityFn()) 855 // Remove unnecessary instructions. 856 removeUnnecessaryInstrs(MF); 857 858 // Convert MBB operands in terminators to relative depth immediates. 859 rewriteDepthImmediates(MF); 860 861 // Fix up block/loop/try signatures at the end of the function to conform to 862 // WebAssembly's rules. 863 fixEndsAtEndOfFunction(MF); 864 865 // Add an end instruction at the end of the function body. 866 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 867 if (!MF.getSubtarget<WebAssemblySubtarget>() 868 .getTargetTriple() 869 .isOSBinFormatELF()) 870 appendEndToFunction(MF, TII); 871 872 return true; 873 } 874