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 /// \brief This file implements a CFG stacking pass. 12 /// 13 /// This pass reorders the blocks in a function to put them into a reverse 14 /// post-order [0], with special care to keep the order as similar as possible 15 /// to the original order, and to keep loops contiguous even in the case of 16 /// split backedges. 17 /// 18 /// Then, it inserts BLOCK and LOOP markers to mark the start of scopes, since 19 /// scope boundaries serve as the labels for WebAssembly's control transfers. 20 /// 21 /// This is sufficient to convert arbitrary CFGs into a form that works on 22 /// WebAssembly, provided that all loops are single-entry. 23 /// 24 /// [0] https://en.wikipedia.org/wiki/Depth-first_search#Vertex_orderings 25 /// 26 //===----------------------------------------------------------------------===// 27 28 #include "WebAssembly.h" 29 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 30 #include "WebAssemblyMachineFunctionInfo.h" 31 #include "WebAssemblySubtarget.h" 32 #include "llvm/ADT/SCCIterator.h" 33 #include "llvm/ADT/SetVector.h" 34 #include "llvm/CodeGen/MachineDominators.h" 35 #include "llvm/CodeGen/MachineFunction.h" 36 #include "llvm/CodeGen/MachineInstrBuilder.h" 37 #include "llvm/CodeGen/MachineLoopInfo.h" 38 #include "llvm/CodeGen/MachineRegisterInfo.h" 39 #include "llvm/CodeGen/Passes.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/raw_ostream.h" 42 using namespace llvm; 43 44 #define DEBUG_TYPE "wasm-cfg-stackify" 45 46 namespace { 47 class WebAssemblyCFGStackify final : public MachineFunctionPass { 48 const char *getPassName() const override { 49 return "WebAssembly CFG Stackify"; 50 } 51 52 void getAnalysisUsage(AnalysisUsage &AU) const override { 53 AU.setPreservesCFG(); 54 AU.addRequired<MachineDominatorTree>(); 55 AU.addPreserved<MachineDominatorTree>(); 56 AU.addRequired<MachineLoopInfo>(); 57 AU.addPreserved<MachineLoopInfo>(); 58 MachineFunctionPass::getAnalysisUsage(AU); 59 } 60 61 bool runOnMachineFunction(MachineFunction &MF) override; 62 63 public: 64 static char ID; // Pass identification, replacement for typeid 65 WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 66 }; 67 } // end anonymous namespace 68 69 char WebAssemblyCFGStackify::ID = 0; 70 FunctionPass *llvm::createWebAssemblyCFGStackify() { 71 return new WebAssemblyCFGStackify(); 72 } 73 74 static void EliminateMultipleEntryLoops(MachineFunction &MF, 75 const MachineLoopInfo &MLI) { 76 SmallPtrSet<MachineBasicBlock *, 8> InSet; 77 for (scc_iterator<MachineFunction *> I = scc_begin(&MF), E = scc_end(&MF); 78 I != E; ++I) { 79 const std::vector<MachineBasicBlock *> &CurrentSCC = *I; 80 81 // Skip trivial SCCs. 82 if (CurrentSCC.size() == 1) 83 continue; 84 85 InSet.insert(CurrentSCC.begin(), CurrentSCC.end()); 86 MachineBasicBlock *Header = nullptr; 87 for (MachineBasicBlock *MBB : CurrentSCC) { 88 for (MachineBasicBlock *Pred : MBB->predecessors()) { 89 if (InSet.count(Pred)) 90 continue; 91 if (!Header) { 92 Header = MBB; 93 break; 94 } 95 // TODO: Implement multiple-entry loops. 96 report_fatal_error("multiple-entry loops are not supported yet"); 97 } 98 } 99 assert(MLI.isLoopHeader(Header)); 100 101 InSet.clear(); 102 } 103 } 104 105 namespace { 106 /// Post-order traversal stack entry. 107 struct POStackEntry { 108 MachineBasicBlock *MBB; 109 SmallVector<MachineBasicBlock *, 0> Succs; 110 111 POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF, 112 const MachineLoopInfo &MLI); 113 }; 114 } // end anonymous namespace 115 116 static bool LoopContains(const MachineLoop *Loop, 117 const MachineBasicBlock *MBB) { 118 return Loop ? Loop->contains(MBB) : true; 119 } 120 121 POStackEntry::POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF, 122 const MachineLoopInfo &MLI) 123 : MBB(MBB), Succs(MBB->successors()) { 124 // RPO is not a unique form, since at every basic block with multiple 125 // successors, the DFS has to pick which order to visit the successors in. 126 // Sort them strategically (see below). 127 MachineLoop *Loop = MLI.getLoopFor(MBB); 128 MachineFunction::iterator Next = next(MachineFunction::iterator(MBB)); 129 MachineBasicBlock *LayoutSucc = Next == MF.end() ? nullptr : &*Next; 130 std::stable_sort( 131 Succs.begin(), Succs.end(), 132 [=, &MLI](const MachineBasicBlock *A, const MachineBasicBlock *B) { 133 if (A == B) 134 return false; 135 136 // Keep loops contiguous by preferring the block that's in the same 137 // loop. 138 bool LoopContainsA = LoopContains(Loop, A); 139 bool LoopContainsB = LoopContains(Loop, B); 140 if (LoopContainsA && !LoopContainsB) 141 return true; 142 if (!LoopContainsA && LoopContainsB) 143 return false; 144 145 // Minimize perturbation by preferring the block which is the immediate 146 // layout successor. 147 if (A == LayoutSucc) 148 return true; 149 if (B == LayoutSucc) 150 return false; 151 152 // TODO: More sophisticated orderings may be profitable here. 153 154 return false; 155 }); 156 } 157 158 /// Return the "bottom" block of a loop. This differs from 159 /// MachineLoop::getBottomBlock in that it works even if the loop is 160 /// discontiguous. 161 static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) { 162 MachineBasicBlock *Bottom = Loop->getHeader(); 163 for (MachineBasicBlock *MBB : Loop->blocks()) 164 if (MBB->getNumber() > Bottom->getNumber()) 165 Bottom = MBB; 166 return Bottom; 167 } 168 169 /// Sort the blocks in RPO, taking special care to make sure that loops are 170 /// contiguous even in the case of split backedges. 171 /// 172 /// TODO: Determine whether RPO is actually worthwhile, or whether we should 173 /// move to just a stable-topological-sort-based approach that would preserve 174 /// more of the original order. 175 static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI) { 176 // Note that we do our own RPO rather than using 177 // "llvm/ADT/PostOrderIterator.h" because we want control over the order that 178 // successors are visited in (see above). Also, we can sort the blocks in the 179 // MachineFunction as we go. 180 SmallPtrSet<MachineBasicBlock *, 16> Visited; 181 SmallVector<POStackEntry, 16> Stack; 182 183 MachineBasicBlock *EntryBlock = &*MF.begin(); 184 Visited.insert(EntryBlock); 185 Stack.push_back(POStackEntry(EntryBlock, MF, MLI)); 186 187 for (;;) { 188 POStackEntry &Entry = Stack.back(); 189 SmallVectorImpl<MachineBasicBlock *> &Succs = Entry.Succs; 190 if (!Succs.empty()) { 191 MachineBasicBlock *Succ = Succs.pop_back_val(); 192 if (Visited.insert(Succ).second) 193 Stack.push_back(POStackEntry(Succ, MF, MLI)); 194 continue; 195 } 196 197 // Put the block in its position in the MachineFunction. 198 MachineBasicBlock &MBB = *Entry.MBB; 199 MBB.moveBefore(&*MF.begin()); 200 201 // Branch instructions may utilize a fallthrough, so update them if a 202 // fallthrough has been added or removed. 203 if (!MBB.empty() && MBB.back().isTerminator() && !MBB.back().isBranch() && 204 !MBB.back().isBarrier()) 205 report_fatal_error( 206 "Non-branch terminator with fallthrough cannot yet be rewritten"); 207 if (MBB.empty() || !MBB.back().isTerminator() || MBB.back().isBranch()) 208 MBB.updateTerminator(); 209 210 Stack.pop_back(); 211 if (Stack.empty()) 212 break; 213 } 214 215 // Now that we've sorted the blocks in RPO, renumber them. 216 MF.RenumberBlocks(); 217 218 #ifndef NDEBUG 219 SmallSetVector<MachineLoop *, 8> OnStack; 220 221 // Insert a sentinel representing the degenerate loop that starts at the 222 // function entry block and includes the entire function as a "loop" that 223 // executes once. 224 OnStack.insert(nullptr); 225 226 for (auto &MBB : MF) { 227 assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative."); 228 229 MachineLoop *Loop = MLI.getLoopFor(&MBB); 230 if (Loop && &MBB == Loop->getHeader()) { 231 // Loop header. The loop predecessor should be sorted above, and the other 232 // predecessors should be backedges below. 233 for (auto Pred : MBB.predecessors()) 234 assert( 235 (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) && 236 "Loop header predecessors must be loop predecessors or backedges"); 237 assert(OnStack.insert(Loop) && "Loops should be declared at most once."); 238 } else { 239 // Not a loop header. All predecessors should be sorted above. 240 for (auto Pred : MBB.predecessors()) 241 assert(Pred->getNumber() < MBB.getNumber() && 242 "Non-loop-header predecessors should be topologically sorted"); 243 assert(OnStack.count(MLI.getLoopFor(&MBB)) && 244 "Blocks must be nested in their loops"); 245 } 246 while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back())) 247 OnStack.pop_back(); 248 } 249 assert(OnStack.pop_back_val() == nullptr && 250 "The function entry block shouldn't actually be a loop header"); 251 assert(OnStack.empty() && 252 "Control flow stack pushes and pops should be balanced."); 253 #endif 254 } 255 256 /// Test whether Pred has any terminators explicitly branching to MBB, as 257 /// opposed to falling through. Note that it's possible (eg. in unoptimized 258 /// code) for a branch instruction to both branch to a block and fallthrough 259 /// to it, so we check the actual branch operands to see if there are any 260 /// explicit mentions. 261 static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 262 MachineBasicBlock *MBB) { 263 for (MachineInstr &MI : Pred->terminators()) 264 for (MachineOperand &MO : MI.explicit_operands()) 265 if (MO.isMBB() && MO.getMBB() == MBB) 266 return true; 267 return false; 268 } 269 270 /// Test whether MI is a child of some other node in an expression tree. 271 static bool IsChild(const MachineInstr *MI, 272 const WebAssemblyFunctionInfo &MFI) { 273 if (MI->getNumOperands() == 0) 274 return false; 275 const MachineOperand &MO = MI->getOperand(0); 276 if (!MO.isReg() || MO.isImplicit() || !MO.isDef()) 277 return false; 278 unsigned Reg = MO.getReg(); 279 return TargetRegisterInfo::isVirtualRegister(Reg) && 280 MFI.isVRegStackified(Reg); 281 } 282 283 /// Insert a BLOCK marker for branches to MBB (if needed). 284 static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF, 285 SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 286 const WebAssemblyInstrInfo &TII, 287 const MachineLoopInfo &MLI, 288 MachineDominatorTree &MDT, 289 WebAssemblyFunctionInfo &MFI) { 290 // First compute the nearest common dominator of all forward non-fallthrough 291 // predecessors so that we minimize the time that the BLOCK is on the stack, 292 // which reduces overall stack height. 293 MachineBasicBlock *Header = nullptr; 294 bool IsBranchedTo = false; 295 int MBBNumber = MBB.getNumber(); 296 for (MachineBasicBlock *Pred : MBB.predecessors()) 297 if (Pred->getNumber() < MBBNumber) { 298 Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 299 if (ExplicitlyBranchesTo(Pred, &MBB)) 300 IsBranchedTo = true; 301 } 302 if (!Header) 303 return; 304 if (!IsBranchedTo) 305 return; 306 307 assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 308 MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB)); 309 310 // If the nearest common dominator is inside a more deeply nested context, 311 // walk out to the nearest scope which isn't more deeply nested. 312 for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 313 if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 314 if (ScopeTop->getNumber() > Header->getNumber()) { 315 // Skip over an intervening scope. 316 I = next(MachineFunction::iterator(ScopeTop)); 317 } else { 318 // We found a scope level at an appropriate depth. 319 Header = ScopeTop; 320 break; 321 } 322 } 323 } 324 325 // If there's a loop which ends just before MBB which contains Header, we can 326 // reuse its label instead of inserting a new BLOCK. 327 for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred); 328 Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop()) 329 if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header)) 330 return; 331 332 // Decide where in Header to put the BLOCK. 333 MachineBasicBlock::iterator InsertPos; 334 MachineLoop *HeaderLoop = MLI.getLoopFor(Header); 335 if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) { 336 // Header is the header of a loop that does not lexically contain MBB, so 337 // the BLOCK needs to be above the LOOP. 338 InsertPos = Header->begin(); 339 } else { 340 // Otherwise, insert the BLOCK as late in Header as we can, but before the 341 // beginning of the local expression tree and any nested BLOCKs. 342 InsertPos = Header->getFirstTerminator(); 343 while (InsertPos != Header->begin() && 344 IsChild(prev(InsertPos), MFI) && 345 prev(InsertPos)->getOpcode() != WebAssembly::LOOP && 346 prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK && 347 prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP) 348 --InsertPos; 349 } 350 351 // Add the BLOCK. 352 BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK)); 353 354 // Mark the end of the block. 355 InsertPos = MBB.begin(); 356 while (InsertPos != MBB.end() && 357 InsertPos->getOpcode() == WebAssembly::END_LOOP) 358 ++InsertPos; 359 BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK)); 360 361 // Track the farthest-spanning scope that ends at this point. 362 int Number = MBB.getNumber(); 363 if (!ScopeTops[Number] || 364 ScopeTops[Number]->getNumber() > Header->getNumber()) 365 ScopeTops[Number] = Header; 366 } 367 368 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 369 static void PlaceLoopMarker( 370 MachineBasicBlock &MBB, MachineFunction &MF, 371 SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 372 DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops, 373 const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) { 374 MachineLoop *Loop = MLI.getLoopFor(&MBB); 375 if (!Loop || Loop->getHeader() != &MBB) 376 return; 377 378 // The operand of a LOOP is the first block after the loop. If the loop is the 379 // bottom of the function, insert a dummy block at the end. 380 MachineBasicBlock *Bottom = LoopBottom(Loop); 381 auto Iter = next(MachineFunction::iterator(Bottom)); 382 if (Iter == MF.end()) { 383 MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 384 // Give it a fake predecessor so that AsmPrinter prints its label. 385 Label->addSuccessor(Label); 386 MF.push_back(Label); 387 Iter = next(MachineFunction::iterator(Bottom)); 388 } 389 MachineBasicBlock *AfterLoop = &*Iter; 390 391 // Mark the beginning of the loop (after the end of any existing loop that 392 // ends here). 393 auto InsertPos = MBB.begin(); 394 while (InsertPos != MBB.end() && 395 InsertPos->getOpcode() == WebAssembly::END_LOOP) 396 ++InsertPos; 397 BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP)); 398 399 // Mark the end of the loop. 400 MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(), 401 TII.get(WebAssembly::END_LOOP)); 402 LoopTops[End] = &MBB; 403 404 assert((!ScopeTops[AfterLoop->getNumber()] || 405 ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 406 "With RPO we should visit the outer-most loop for a block first."); 407 if (!ScopeTops[AfterLoop->getNumber()]) 408 ScopeTops[AfterLoop->getNumber()] = &MBB; 409 } 410 411 static unsigned 412 GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 413 const MachineBasicBlock *MBB) { 414 unsigned Depth = 0; 415 for (auto X : reverse(Stack)) { 416 if (X == MBB) 417 break; 418 ++Depth; 419 } 420 assert(Depth < Stack.size() && "Branch destination should be in scope"); 421 return Depth; 422 } 423 424 /// Insert LOOP and BLOCK markers at appropriate places. 425 static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI, 426 const WebAssemblyInstrInfo &TII, 427 MachineDominatorTree &MDT, 428 WebAssemblyFunctionInfo &MFI) { 429 // For each block whose label represents the end of a scope, record the block 430 // which holds the beginning of the scope. This will allow us to quickly skip 431 // over scoped regions when walking blocks. We allocate one more than the 432 // number of blocks in the function to accommodate for the possible fake block 433 // we may insert at the end. 434 SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1); 435 436 // For eacn LOOP_END, the corresponding LOOP. 437 DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops; 438 439 for (auto &MBB : MF) { 440 // Place the LOOP for MBB if MBB is the header of a loop. 441 PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI); 442 443 // Place the BLOCK for MBB if MBB is branched to from above. 444 PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT, MFI); 445 } 446 447 // Now rewrite references to basic blocks to be depth immediates. 448 SmallVector<const MachineBasicBlock *, 8> Stack; 449 for (auto &MBB : reverse(MF)) { 450 for (auto &MI : reverse(MBB)) { 451 switch (MI.getOpcode()) { 452 case WebAssembly::BLOCK: 453 assert(ScopeTops[Stack.back()->getNumber()] == &MBB && 454 "Block should be balanced"); 455 Stack.pop_back(); 456 break; 457 case WebAssembly::LOOP: 458 assert(Stack.back() == &MBB && "Loop top should be balanced"); 459 Stack.pop_back(); 460 Stack.pop_back(); 461 break; 462 case WebAssembly::END_BLOCK: 463 Stack.push_back(&MBB); 464 break; 465 case WebAssembly::END_LOOP: 466 Stack.push_back(&MBB); 467 Stack.push_back(LoopTops[&MI]); 468 break; 469 default: 470 if (MI.isTerminator()) { 471 // Rewrite MBB operands to be depth immediates. 472 SmallVector<MachineOperand, 4> Ops(MI.operands()); 473 while (MI.getNumOperands() > 0) 474 MI.RemoveOperand(MI.getNumOperands() - 1); 475 for (auto MO : Ops) { 476 if (MO.isMBB()) 477 MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 478 MI.addOperand(MF, MO); 479 } 480 } 481 break; 482 } 483 } 484 } 485 assert(Stack.empty() && "Control flow should be balanced"); 486 } 487 488 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 489 DEBUG(dbgs() << "********** CFG Stackifying **********\n" 490 "********** Function: " 491 << MF.getName() << '\n'); 492 493 const auto &MLI = getAnalysis<MachineLoopInfo>(); 494 auto &MDT = getAnalysis<MachineDominatorTree>(); 495 // Liveness is not tracked for EXPR_STACK physreg. 496 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 497 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 498 MF.getRegInfo().invalidateLiveness(); 499 500 // RPO sorting needs all loops to be single-entry. 501 EliminateMultipleEntryLoops(MF, MLI); 502 503 // Sort the blocks in RPO, with contiguous loops. 504 SortBlocks(MF, MLI); 505 506 // Place the BLOCK and LOOP markers to indicate the beginnings of scopes. 507 PlaceMarkers(MF, MLI, TII, MDT, MFI); 508 509 return true; 510 } 511