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