1 //===- MachineSink.cpp - Sinking for machine instructions -----------------===// 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 // This pass moves instructions into successor blocks when possible, so that 10 // they aren't executed on paths where their results aren't needed. 11 // 12 // This pass is not intended to be a replacement or a complete alternative 13 // for an LLVM-IR-level sinking pass. It is only designed to sink simple 14 // constructs that are not exposed before lowering and instruction selection. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/SparseBitVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/MachineBasicBlock.h" 25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 27 #include "llvm/CodeGen/MachineDominators.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineFunctionPass.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/CodeGen/MachineOperand.h" 33 #include "llvm/CodeGen/MachinePostDominators.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/TargetInstrInfo.h" 36 #include "llvm/CodeGen/TargetRegisterInfo.h" 37 #include "llvm/CodeGen/TargetSubtargetInfo.h" 38 #include "llvm/IR/BasicBlock.h" 39 #include "llvm/IR/DebugInfoMetadata.h" 40 #include "llvm/IR/LLVMContext.h" 41 #include "llvm/MC/MCRegisterInfo.h" 42 #include "llvm/Pass.h" 43 #include "llvm/Support/BranchProbability.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/Debug.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <algorithm> 48 #include <cassert> 49 #include <cstdint> 50 #include <map> 51 #include <utility> 52 #include <vector> 53 54 using namespace llvm; 55 56 #define DEBUG_TYPE "machine-sink" 57 58 static cl::opt<bool> 59 SplitEdges("machine-sink-split", 60 cl::desc("Split critical edges during machine sinking"), 61 cl::init(true), cl::Hidden); 62 63 static cl::opt<bool> 64 UseBlockFreqInfo("machine-sink-bfi", 65 cl::desc("Use block frequency info to find successors to sink"), 66 cl::init(true), cl::Hidden); 67 68 static cl::opt<unsigned> SplitEdgeProbabilityThreshold( 69 "machine-sink-split-probability-threshold", 70 cl::desc( 71 "Percentage threshold for splitting single-instruction critical edge. " 72 "If the branch threshold is higher than this threshold, we allow " 73 "speculative execution of up to 1 instruction to avoid branching to " 74 "splitted critical edge"), 75 cl::init(40), cl::Hidden); 76 77 STATISTIC(NumSunk, "Number of machine instructions sunk"); 78 STATISTIC(NumSplit, "Number of critical edges split"); 79 STATISTIC(NumCoalesces, "Number of copies coalesced"); 80 STATISTIC(NumPostRACopySink, "Number of copies sunk after RA"); 81 82 namespace { 83 84 class MachineSinking : public MachineFunctionPass { 85 const TargetInstrInfo *TII; 86 const TargetRegisterInfo *TRI; 87 MachineRegisterInfo *MRI; // Machine register information 88 MachineDominatorTree *DT; // Machine dominator tree 89 MachinePostDominatorTree *PDT; // Machine post dominator tree 90 MachineLoopInfo *LI; 91 const MachineBlockFrequencyInfo *MBFI; 92 const MachineBranchProbabilityInfo *MBPI; 93 AliasAnalysis *AA; 94 95 // Remember which edges have been considered for breaking. 96 SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8> 97 CEBCandidates; 98 // Remember which edges we are about to split. 99 // This is different from CEBCandidates since those edges 100 // will be split. 101 SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit; 102 103 SparseBitVector<> RegsToClearKillFlags; 104 105 using AllSuccsCache = 106 std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>; 107 108 public: 109 static char ID; // Pass identification 110 111 MachineSinking() : MachineFunctionPass(ID) { 112 initializeMachineSinkingPass(*PassRegistry::getPassRegistry()); 113 } 114 115 bool runOnMachineFunction(MachineFunction &MF) override; 116 117 void getAnalysisUsage(AnalysisUsage &AU) const override { 118 MachineFunctionPass::getAnalysisUsage(AU); 119 AU.addRequired<AAResultsWrapperPass>(); 120 AU.addRequired<MachineDominatorTree>(); 121 AU.addRequired<MachinePostDominatorTree>(); 122 AU.addRequired<MachineLoopInfo>(); 123 AU.addRequired<MachineBranchProbabilityInfo>(); 124 AU.addPreserved<MachineLoopInfo>(); 125 if (UseBlockFreqInfo) 126 AU.addRequired<MachineBlockFrequencyInfo>(); 127 } 128 129 void releaseMemory() override { 130 CEBCandidates.clear(); 131 } 132 133 private: 134 bool ProcessBlock(MachineBasicBlock &MBB); 135 bool isWorthBreakingCriticalEdge(MachineInstr &MI, 136 MachineBasicBlock *From, 137 MachineBasicBlock *To); 138 139 /// Postpone the splitting of the given critical 140 /// edge (\p From, \p To). 141 /// 142 /// We do not split the edges on the fly. Indeed, this invalidates 143 /// the dominance information and thus triggers a lot of updates 144 /// of that information underneath. 145 /// Instead, we postpone all the splits after each iteration of 146 /// the main loop. That way, the information is at least valid 147 /// for the lifetime of an iteration. 148 /// 149 /// \return True if the edge is marked as toSplit, false otherwise. 150 /// False can be returned if, for instance, this is not profitable. 151 bool PostponeSplitCriticalEdge(MachineInstr &MI, 152 MachineBasicBlock *From, 153 MachineBasicBlock *To, 154 bool BreakPHIEdge); 155 bool SinkInstruction(MachineInstr &MI, bool &SawStore, 156 157 AllSuccsCache &AllSuccessors); 158 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB, 159 MachineBasicBlock *DefMBB, 160 bool &BreakPHIEdge, bool &LocalUse) const; 161 MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB, 162 bool &BreakPHIEdge, AllSuccsCache &AllSuccessors); 163 bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI, 164 MachineBasicBlock *MBB, 165 MachineBasicBlock *SuccToSinkTo, 166 AllSuccsCache &AllSuccessors); 167 168 bool PerformTrivialForwardCoalescing(MachineInstr &MI, 169 MachineBasicBlock *MBB); 170 171 SmallVector<MachineBasicBlock *, 4> & 172 GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB, 173 AllSuccsCache &AllSuccessors) const; 174 }; 175 176 } // end anonymous namespace 177 178 char MachineSinking::ID = 0; 179 180 char &llvm::MachineSinkingID = MachineSinking::ID; 181 182 INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE, 183 "Machine code sinking", false, false) 184 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 185 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 186 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 187 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 188 INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE, 189 "Machine code sinking", false, false) 190 191 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI, 192 MachineBasicBlock *MBB) { 193 if (!MI.isCopy()) 194 return false; 195 196 Register SrcReg = MI.getOperand(1).getReg(); 197 Register DstReg = MI.getOperand(0).getReg(); 198 if (!Register::isVirtualRegister(SrcReg) || 199 !Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg)) 200 return false; 201 202 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg); 203 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg); 204 if (SRC != DRC) 205 return false; 206 207 MachineInstr *DefMI = MRI->getVRegDef(SrcReg); 208 if (DefMI->isCopyLike()) 209 return false; 210 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI); 211 LLVM_DEBUG(dbgs() << "*** to: " << MI); 212 MRI->replaceRegWith(DstReg, SrcReg); 213 MI.eraseFromParent(); 214 215 // Conservatively, clear any kill flags, since it's possible that they are no 216 // longer correct. 217 MRI->clearKillFlags(SrcReg); 218 219 ++NumCoalesces; 220 return true; 221 } 222 223 /// AllUsesDominatedByBlock - Return true if all uses of the specified register 224 /// occur in blocks dominated by the specified block. If any use is in the 225 /// definition block, then return false since it is never legal to move def 226 /// after uses. 227 bool 228 MachineSinking::AllUsesDominatedByBlock(unsigned Reg, 229 MachineBasicBlock *MBB, 230 MachineBasicBlock *DefMBB, 231 bool &BreakPHIEdge, 232 bool &LocalUse) const { 233 assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs"); 234 235 // Ignore debug uses because debug info doesn't affect the code. 236 if (MRI->use_nodbg_empty(Reg)) 237 return true; 238 239 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken 240 // into and they are all PHI nodes. In this case, machine-sink must break 241 // the critical edge first. e.g. 242 // 243 // %bb.1: derived from LLVM BB %bb4.preheader 244 // Predecessors according to CFG: %bb.0 245 // ... 246 // %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags 247 // ... 248 // JE_4 <%bb.37>, implicit %eflags 249 // Successors according to CFG: %bb.37 %bb.2 250 // 251 // %bb.2: derived from LLVM BB %bb.nph 252 // Predecessors according to CFG: %bb.0 %bb.1 253 // %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1 254 BreakPHIEdge = true; 255 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 256 MachineInstr *UseInst = MO.getParent(); 257 unsigned OpNo = &MO - &UseInst->getOperand(0); 258 MachineBasicBlock *UseBlock = UseInst->getParent(); 259 if (!(UseBlock == MBB && UseInst->isPHI() && 260 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) { 261 BreakPHIEdge = false; 262 break; 263 } 264 } 265 if (BreakPHIEdge) 266 return true; 267 268 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 269 // Determine the block of the use. 270 MachineInstr *UseInst = MO.getParent(); 271 unsigned OpNo = &MO - &UseInst->getOperand(0); 272 MachineBasicBlock *UseBlock = UseInst->getParent(); 273 if (UseInst->isPHI()) { 274 // PHI nodes use the operand in the predecessor block, not the block with 275 // the PHI. 276 UseBlock = UseInst->getOperand(OpNo+1).getMBB(); 277 } else if (UseBlock == DefMBB) { 278 LocalUse = true; 279 return false; 280 } 281 282 // Check that it dominates. 283 if (!DT->dominates(MBB, UseBlock)) 284 return false; 285 } 286 287 return true; 288 } 289 290 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) { 291 if (skipFunction(MF.getFunction())) 292 return false; 293 294 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n"); 295 296 TII = MF.getSubtarget().getInstrInfo(); 297 TRI = MF.getSubtarget().getRegisterInfo(); 298 MRI = &MF.getRegInfo(); 299 DT = &getAnalysis<MachineDominatorTree>(); 300 PDT = &getAnalysis<MachinePostDominatorTree>(); 301 LI = &getAnalysis<MachineLoopInfo>(); 302 MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr; 303 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 304 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 305 306 bool EverMadeChange = false; 307 308 while (true) { 309 bool MadeChange = false; 310 311 // Process all basic blocks. 312 CEBCandidates.clear(); 313 ToSplit.clear(); 314 for (auto &MBB: MF) 315 MadeChange |= ProcessBlock(MBB); 316 317 // If we have anything we marked as toSplit, split it now. 318 for (auto &Pair : ToSplit) { 319 auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this); 320 if (NewSucc != nullptr) { 321 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: " 322 << printMBBReference(*Pair.first) << " -- " 323 << printMBBReference(*NewSucc) << " -- " 324 << printMBBReference(*Pair.second) << '\n'); 325 MadeChange = true; 326 ++NumSplit; 327 } else 328 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n"); 329 } 330 // If this iteration over the code changed anything, keep iterating. 331 if (!MadeChange) break; 332 EverMadeChange = true; 333 } 334 335 // Now clear any kill flags for recorded registers. 336 for (auto I : RegsToClearKillFlags) 337 MRI->clearKillFlags(I); 338 RegsToClearKillFlags.clear(); 339 340 return EverMadeChange; 341 } 342 343 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) { 344 // Can't sink anything out of a block that has less than two successors. 345 if (MBB.succ_size() <= 1 || MBB.empty()) return false; 346 347 // Don't bother sinking code out of unreachable blocks. In addition to being 348 // unprofitable, it can also lead to infinite looping, because in an 349 // unreachable loop there may be nowhere to stop. 350 if (!DT->isReachableFromEntry(&MBB)) return false; 351 352 bool MadeChange = false; 353 354 // Cache all successors, sorted by frequency info and loop depth. 355 AllSuccsCache AllSuccessors; 356 357 // Walk the basic block bottom-up. Remember if we saw a store. 358 MachineBasicBlock::iterator I = MBB.end(); 359 --I; 360 bool ProcessedBegin, SawStore = false; 361 do { 362 MachineInstr &MI = *I; // The instruction to sink. 363 364 // Predecrement I (if it's not begin) so that it isn't invalidated by 365 // sinking. 366 ProcessedBegin = I == MBB.begin(); 367 if (!ProcessedBegin) 368 --I; 369 370 if (MI.isDebugInstr()) 371 continue; 372 373 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB); 374 if (Joined) { 375 MadeChange = true; 376 continue; 377 } 378 379 if (SinkInstruction(MI, SawStore, AllSuccessors)) { 380 ++NumSunk; 381 MadeChange = true; 382 } 383 384 // If we just processed the first instruction in the block, we're done. 385 } while (!ProcessedBegin); 386 387 return MadeChange; 388 } 389 390 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI, 391 MachineBasicBlock *From, 392 MachineBasicBlock *To) { 393 // FIXME: Need much better heuristics. 394 395 // If the pass has already considered breaking this edge (during this pass 396 // through the function), then let's go ahead and break it. This means 397 // sinking multiple "cheap" instructions into the same block. 398 if (!CEBCandidates.insert(std::make_pair(From, To)).second) 399 return true; 400 401 if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI)) 402 return true; 403 404 if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <= 405 BranchProbability(SplitEdgeProbabilityThreshold, 100)) 406 return true; 407 408 // MI is cheap, we probably don't want to break the critical edge for it. 409 // However, if this would allow some definitions of its source operands 410 // to be sunk then it's probably worth it. 411 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 412 const MachineOperand &MO = MI.getOperand(i); 413 if (!MO.isReg() || !MO.isUse()) 414 continue; 415 Register Reg = MO.getReg(); 416 if (Reg == 0) 417 continue; 418 419 // We don't move live definitions of physical registers, 420 // so sinking their uses won't enable any opportunities. 421 if (Register::isPhysicalRegister(Reg)) 422 continue; 423 424 // If this instruction is the only user of a virtual register, 425 // check if breaking the edge will enable sinking 426 // both this instruction and the defining instruction. 427 if (MRI->hasOneNonDBGUse(Reg)) { 428 // If the definition resides in same MBB, 429 // claim it's likely we can sink these together. 430 // If definition resides elsewhere, we aren't 431 // blocking it from being sunk so don't break the edge. 432 MachineInstr *DefMI = MRI->getVRegDef(Reg); 433 if (DefMI->getParent() == MI.getParent()) 434 return true; 435 } 436 } 437 438 return false; 439 } 440 441 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI, 442 MachineBasicBlock *FromBB, 443 MachineBasicBlock *ToBB, 444 bool BreakPHIEdge) { 445 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB)) 446 return false; 447 448 // Avoid breaking back edge. From == To means backedge for single BB loop. 449 if (!SplitEdges || FromBB == ToBB) 450 return false; 451 452 // Check for backedges of more "complex" loops. 453 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) && 454 LI->isLoopHeader(ToBB)) 455 return false; 456 457 // It's not always legal to break critical edges and sink the computation 458 // to the edge. 459 // 460 // %bb.1: 461 // v1024 462 // Beq %bb.3 463 // <fallthrough> 464 // %bb.2: 465 // ... no uses of v1024 466 // <fallthrough> 467 // %bb.3: 468 // ... 469 // = v1024 470 // 471 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted: 472 // 473 // %bb.1: 474 // ... 475 // Bne %bb.2 476 // %bb.4: 477 // v1024 = 478 // B %bb.3 479 // %bb.2: 480 // ... no uses of v1024 481 // <fallthrough> 482 // %bb.3: 483 // ... 484 // = v1024 485 // 486 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3 487 // flow. We need to ensure the new basic block where the computation is 488 // sunk to dominates all the uses. 489 // It's only legal to break critical edge and sink the computation to the 490 // new block if all the predecessors of "To", except for "From", are 491 // not dominated by "From". Given SSA property, this means these 492 // predecessors are dominated by "To". 493 // 494 // There is no need to do this check if all the uses are PHI nodes. PHI 495 // sources are only defined on the specific predecessor edges. 496 if (!BreakPHIEdge) { 497 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(), 498 E = ToBB->pred_end(); PI != E; ++PI) { 499 if (*PI == FromBB) 500 continue; 501 if (!DT->dominates(ToBB, *PI)) 502 return false; 503 } 504 } 505 506 ToSplit.insert(std::make_pair(FromBB, ToBB)); 507 508 return true; 509 } 510 511 /// isProfitableToSinkTo - Return true if it is profitable to sink MI. 512 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI, 513 MachineBasicBlock *MBB, 514 MachineBasicBlock *SuccToSinkTo, 515 AllSuccsCache &AllSuccessors) { 516 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB"); 517 518 if (MBB == SuccToSinkTo) 519 return false; 520 521 // It is profitable if SuccToSinkTo does not post dominate current block. 522 if (!PDT->dominates(SuccToSinkTo, MBB)) 523 return true; 524 525 // It is profitable to sink an instruction from a deeper loop to a shallower 526 // loop, even if the latter post-dominates the former (PR21115). 527 if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo)) 528 return true; 529 530 // Check if only use in post dominated block is PHI instruction. 531 bool NonPHIUse = false; 532 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) { 533 MachineBasicBlock *UseBlock = UseInst.getParent(); 534 if (UseBlock == SuccToSinkTo && !UseInst.isPHI()) 535 NonPHIUse = true; 536 } 537 if (!NonPHIUse) 538 return true; 539 540 // If SuccToSinkTo post dominates then also it may be profitable if MI 541 // can further profitably sinked into another block in next round. 542 bool BreakPHIEdge = false; 543 // FIXME - If finding successor is compile time expensive then cache results. 544 if (MachineBasicBlock *MBB2 = 545 FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors)) 546 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors); 547 548 // If SuccToSinkTo is final destination and it is a post dominator of current 549 // block then it is not profitable to sink MI into SuccToSinkTo block. 550 return false; 551 } 552 553 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly 554 /// computing it if it was not already cached. 555 SmallVector<MachineBasicBlock *, 4> & 556 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB, 557 AllSuccsCache &AllSuccessors) const { 558 // Do we have the sorted successors in cache ? 559 auto Succs = AllSuccessors.find(MBB); 560 if (Succs != AllSuccessors.end()) 561 return Succs->second; 562 563 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(), 564 MBB->succ_end()); 565 566 // Handle cases where sinking can happen but where the sink point isn't a 567 // successor. For example: 568 // 569 // x = computation 570 // if () {} else {} 571 // use x 572 // 573 const std::vector<MachineDomTreeNode *> &Children = 574 DT->getNode(MBB)->getChildren(); 575 for (const auto &DTChild : Children) 576 // DomTree children of MBB that have MBB as immediate dominator are added. 577 if (DTChild->getIDom()->getBlock() == MI.getParent() && 578 // Skip MBBs already added to the AllSuccs vector above. 579 !MBB->isSuccessor(DTChild->getBlock())) 580 AllSuccs.push_back(DTChild->getBlock()); 581 582 // Sort Successors according to their loop depth or block frequency info. 583 llvm::stable_sort( 584 AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) { 585 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0; 586 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0; 587 bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0; 588 return HasBlockFreq ? LHSFreq < RHSFreq 589 : LI->getLoopDepth(L) < LI->getLoopDepth(R); 590 }); 591 592 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs)); 593 594 return it.first->second; 595 } 596 597 /// FindSuccToSinkTo - Find a successor to sink this instruction to. 598 MachineBasicBlock * 599 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB, 600 bool &BreakPHIEdge, 601 AllSuccsCache &AllSuccessors) { 602 assert (MBB && "Invalid MachineBasicBlock!"); 603 604 // Loop over all the operands of the specified instruction. If there is 605 // anything we can't handle, bail out. 606 607 // SuccToSinkTo - This is the successor to sink this instruction to, once we 608 // decide. 609 MachineBasicBlock *SuccToSinkTo = nullptr; 610 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 611 const MachineOperand &MO = MI.getOperand(i); 612 if (!MO.isReg()) continue; // Ignore non-register operands. 613 614 Register Reg = MO.getReg(); 615 if (Reg == 0) continue; 616 617 if (Register::isPhysicalRegister(Reg)) { 618 if (MO.isUse()) { 619 // If the physreg has no defs anywhere, it's just an ambient register 620 // and we can freely move its uses. Alternatively, if it's allocatable, 621 // it could get allocated to something with a def during allocation. 622 if (!MRI->isConstantPhysReg(Reg)) 623 return nullptr; 624 } else if (!MO.isDead()) { 625 // A def that isn't dead. We can't move it. 626 return nullptr; 627 } 628 } else { 629 // Virtual register uses are always safe to sink. 630 if (MO.isUse()) continue; 631 632 // If it's not safe to move defs of the register class, then abort. 633 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg))) 634 return nullptr; 635 636 // Virtual register defs can only be sunk if all their uses are in blocks 637 // dominated by one of the successors. 638 if (SuccToSinkTo) { 639 // If a previous operand picked a block to sink to, then this operand 640 // must be sinkable to the same block. 641 bool LocalUse = false; 642 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, 643 BreakPHIEdge, LocalUse)) 644 return nullptr; 645 646 continue; 647 } 648 649 // Otherwise, we should look at all the successors and decide which one 650 // we should sink to. If we have reliable block frequency information 651 // (frequency != 0) available, give successors with smaller frequencies 652 // higher priority, otherwise prioritize smaller loop depths. 653 for (MachineBasicBlock *SuccBlock : 654 GetAllSortedSuccessors(MI, MBB, AllSuccessors)) { 655 bool LocalUse = false; 656 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, 657 BreakPHIEdge, LocalUse)) { 658 SuccToSinkTo = SuccBlock; 659 break; 660 } 661 if (LocalUse) 662 // Def is used locally, it's never safe to move this def. 663 return nullptr; 664 } 665 666 // If we couldn't find a block to sink to, ignore this instruction. 667 if (!SuccToSinkTo) 668 return nullptr; 669 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors)) 670 return nullptr; 671 } 672 } 673 674 // It is not possible to sink an instruction into its own block. This can 675 // happen with loops. 676 if (MBB == SuccToSinkTo) 677 return nullptr; 678 679 // It's not safe to sink instructions to EH landing pad. Control flow into 680 // landing pad is implicitly defined. 681 if (SuccToSinkTo && SuccToSinkTo->isEHPad()) 682 return nullptr; 683 684 return SuccToSinkTo; 685 } 686 687 /// Return true if MI is likely to be usable as a memory operation by the 688 /// implicit null check optimization. 689 /// 690 /// This is a "best effort" heuristic, and should not be relied upon for 691 /// correctness. This returning true does not guarantee that the implicit null 692 /// check optimization is legal over MI, and this returning false does not 693 /// guarantee MI cannot possibly be used to do a null check. 694 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI, 695 const TargetInstrInfo *TII, 696 const TargetRegisterInfo *TRI) { 697 using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate; 698 699 auto *MBB = MI.getParent(); 700 if (MBB->pred_size() != 1) 701 return false; 702 703 auto *PredMBB = *MBB->pred_begin(); 704 auto *PredBB = PredMBB->getBasicBlock(); 705 706 // Frontends that don't use implicit null checks have no reason to emit 707 // branches with make.implicit metadata, and this function should always 708 // return false for them. 709 if (!PredBB || 710 !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit)) 711 return false; 712 713 const MachineOperand *BaseOp; 714 int64_t Offset; 715 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI)) 716 return false; 717 718 if (!BaseOp->isReg()) 719 return false; 720 721 if (!(MI.mayLoad() && !MI.isPredicable())) 722 return false; 723 724 MachineBranchPredicate MBP; 725 if (TII->analyzeBranchPredicate(*PredMBB, MBP, false)) 726 return false; 727 728 return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 && 729 (MBP.Predicate == MachineBranchPredicate::PRED_NE || 730 MBP.Predicate == MachineBranchPredicate::PRED_EQ) && 731 MBP.LHS.getReg() == BaseOp->getReg(); 732 } 733 734 /// Sink an instruction and its associated debug instructions. If the debug 735 /// instructions to be sunk are already known, they can be provided in DbgVals. 736 static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo, 737 MachineBasicBlock::iterator InsertPos, 738 SmallVectorImpl<MachineInstr *> *DbgVals = nullptr) { 739 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 740 const TargetInstrInfo &TII = *MI.getMF()->getSubtarget().getInstrInfo(); 741 742 // If debug values are provided use those, otherwise call collectDebugValues. 743 SmallVector<MachineInstr *, 2> DbgValuesToSink; 744 if (DbgVals) 745 DbgValuesToSink.insert(DbgValuesToSink.begin(), 746 DbgVals->begin(), DbgVals->end()); 747 else 748 MI.collectDebugValues(DbgValuesToSink); 749 750 // If we cannot find a location to use (merge with), then we erase the debug 751 // location to prevent debug-info driven tools from potentially reporting 752 // wrong location information. 753 if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end()) 754 MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(), 755 InsertPos->getDebugLoc())); 756 else 757 MI.setDebugLoc(DebugLoc()); 758 759 // Move the instruction. 760 MachineBasicBlock *ParentBlock = MI.getParent(); 761 SuccToSinkTo.splice(InsertPos, ParentBlock, MI, 762 ++MachineBasicBlock::iterator(MI)); 763 764 // Sink a copy of debug users to the insert position. Mark the original 765 // DBG_VALUE location as 'undef', indicating that any earlier variable 766 // location should be terminated as we've optimised away the value at this 767 // point. 768 // If the sunk instruction is a copy, try to forward the copy instead of 769 // leaving an 'undef' DBG_VALUE in the original location. Don't do this if 770 // there's any subregister weirdness involved. 771 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(), 772 DBE = DbgValuesToSink.end(); 773 DBI != DBE; ++DBI) { 774 MachineInstr *DbgMI = *DBI; 775 MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(*DBI); 776 SuccToSinkTo.insert(InsertPos, NewDbgMI); 777 778 // Copy DBG_VALUE operand and set the original to undef. We then check to 779 // see whether this is something that can be copy-forwarded. If it isn't, 780 // continue around the loop. 781 MachineOperand DbgMO = DbgMI->getOperand(0); 782 DbgMI->getOperand(0).setReg(0); 783 784 const MachineOperand *SrcMO = nullptr, *DstMO = nullptr; 785 if (!TII.isCopyInstr(MI, SrcMO, DstMO)) 786 continue; 787 788 // Check validity of forwarding this copy. 789 bool PostRA = MRI.getNumVirtRegs() == 0; 790 791 // Trying to forward between physical and virtual registers is too hard. 792 if (DbgMO.getReg().isVirtual() != SrcMO->getReg().isVirtual()) 793 continue; 794 795 // Only try virtual register copy-forwarding before regalloc, and physical 796 // register copy-forwarding after regalloc. 797 bool arePhysRegs = !DbgMO.getReg().isVirtual(); 798 if (arePhysRegs != PostRA) 799 continue; 800 801 // Pre-regalloc, only forward if all subregisters agree (or there are no 802 // subregs at all). More analysis might recover some forwardable copies. 803 if (!PostRA && (DbgMO.getSubReg() != SrcMO->getSubReg() || 804 DbgMO.getSubReg() != DstMO->getSubReg())) 805 continue; 806 807 // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register 808 // of this copy. Only forward the copy if the DBG_VALUE operand exactly 809 // matches the copy destination. 810 if (PostRA && DbgMO.getReg() != DstMO->getReg()) 811 continue; 812 813 DbgMI->getOperand(0).setReg(SrcMO->getReg()); 814 DbgMI->getOperand(0).setSubReg(SrcMO->getSubReg()); 815 } 816 } 817 818 /// SinkInstruction - Determine whether it is safe to sink the specified machine 819 /// instruction out of its current block into a successor. 820 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore, 821 AllSuccsCache &AllSuccessors) { 822 // Don't sink instructions that the target prefers not to sink. 823 if (!TII->shouldSink(MI)) 824 return false; 825 826 // Check if it's safe to move the instruction. 827 if (!MI.isSafeToMove(AA, SawStore)) 828 return false; 829 830 // Convergent operations may not be made control-dependent on additional 831 // values. 832 if (MI.isConvergent()) 833 return false; 834 835 // Don't break implicit null checks. This is a performance heuristic, and not 836 // required for correctness. 837 if (SinkingPreventsImplicitNullCheck(MI, TII, TRI)) 838 return false; 839 840 // FIXME: This should include support for sinking instructions within the 841 // block they are currently in to shorten the live ranges. We often get 842 // instructions sunk into the top of a large block, but it would be better to 843 // also sink them down before their first use in the block. This xform has to 844 // be careful not to *increase* register pressure though, e.g. sinking 845 // "x = y + z" down if it kills y and z would increase the live ranges of y 846 // and z and only shrink the live range of x. 847 848 bool BreakPHIEdge = false; 849 MachineBasicBlock *ParentBlock = MI.getParent(); 850 MachineBasicBlock *SuccToSinkTo = 851 FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors); 852 853 // If there are no outputs, it must have side-effects. 854 if (!SuccToSinkTo) 855 return false; 856 857 // If the instruction to move defines a dead physical register which is live 858 // when leaving the basic block, don't move it because it could turn into a 859 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>) 860 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { 861 const MachineOperand &MO = MI.getOperand(I); 862 if (!MO.isReg()) continue; 863 Register Reg = MO.getReg(); 864 if (Reg == 0 || !Register::isPhysicalRegister(Reg)) 865 continue; 866 if (SuccToSinkTo->isLiveIn(Reg)) 867 return false; 868 } 869 870 LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo); 871 872 // If the block has multiple predecessors, this is a critical edge. 873 // Decide if we can sink along it or need to break the edge. 874 if (SuccToSinkTo->pred_size() > 1) { 875 // We cannot sink a load across a critical edge - there may be stores in 876 // other code paths. 877 bool TryBreak = false; 878 bool store = true; 879 if (!MI.isSafeToMove(AA, store)) { 880 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n"); 881 TryBreak = true; 882 } 883 884 // We don't want to sink across a critical edge if we don't dominate the 885 // successor. We could be introducing calculations to new code paths. 886 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) { 887 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n"); 888 TryBreak = true; 889 } 890 891 // Don't sink instructions into a loop. 892 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) { 893 LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n"); 894 TryBreak = true; 895 } 896 897 // Otherwise we are OK with sinking along a critical edge. 898 if (!TryBreak) 899 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n"); 900 else { 901 // Mark this edge as to be split. 902 // If the edge can actually be split, the next iteration of the main loop 903 // will sink MI in the newly created block. 904 bool Status = 905 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge); 906 if (!Status) 907 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to " 908 "break critical edge\n"); 909 // The instruction will not be sunk this time. 910 return false; 911 } 912 } 913 914 if (BreakPHIEdge) { 915 // BreakPHIEdge is true if all the uses are in the successor MBB being 916 // sunken into and they are all PHI nodes. In this case, machine-sink must 917 // break the critical edge first. 918 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock, 919 SuccToSinkTo, BreakPHIEdge); 920 if (!Status) 921 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to " 922 "break critical edge\n"); 923 // The instruction will not be sunk this time. 924 return false; 925 } 926 927 // Determine where to insert into. Skip phi nodes. 928 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin(); 929 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI()) 930 ++InsertPos; 931 932 performSink(MI, *SuccToSinkTo, InsertPos); 933 934 // Conservatively, clear any kill flags, since it's possible that they are no 935 // longer correct. 936 // Note that we have to clear the kill flags for any register this instruction 937 // uses as we may sink over another instruction which currently kills the 938 // used registers. 939 for (MachineOperand &MO : MI.operands()) { 940 if (MO.isReg() && MO.isUse()) 941 RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags. 942 } 943 944 return true; 945 } 946 947 //===----------------------------------------------------------------------===// 948 // This pass is not intended to be a replacement or a complete alternative 949 // for the pre-ra machine sink pass. It is only designed to sink COPY 950 // instructions which should be handled after RA. 951 // 952 // This pass sinks COPY instructions into a successor block, if the COPY is not 953 // used in the current block and the COPY is live-in to a single successor 954 // (i.e., doesn't require the COPY to be duplicated). This avoids executing the 955 // copy on paths where their results aren't needed. This also exposes 956 // additional opportunites for dead copy elimination and shrink wrapping. 957 // 958 // These copies were either not handled by or are inserted after the MachineSink 959 // pass. As an example of the former case, the MachineSink pass cannot sink 960 // COPY instructions with allocatable source registers; for AArch64 these type 961 // of copy instructions are frequently used to move function parameters (PhyReg) 962 // into virtual registers in the entry block. 963 // 964 // For the machine IR below, this pass will sink %w19 in the entry into its 965 // successor (%bb.1) because %w19 is only live-in in %bb.1. 966 // %bb.0: 967 // %wzr = SUBSWri %w1, 1 968 // %w19 = COPY %w0 969 // Bcc 11, %bb.2 970 // %bb.1: 971 // Live Ins: %w19 972 // BL @fun 973 // %w0 = ADDWrr %w0, %w19 974 // RET %w0 975 // %bb.2: 976 // %w0 = COPY %wzr 977 // RET %w0 978 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be 979 // able to see %bb.0 as a candidate. 980 //===----------------------------------------------------------------------===// 981 namespace { 982 983 class PostRAMachineSinking : public MachineFunctionPass { 984 public: 985 bool runOnMachineFunction(MachineFunction &MF) override; 986 987 static char ID; 988 PostRAMachineSinking() : MachineFunctionPass(ID) {} 989 StringRef getPassName() const override { return "PostRA Machine Sink"; } 990 991 void getAnalysisUsage(AnalysisUsage &AU) const override { 992 AU.setPreservesCFG(); 993 MachineFunctionPass::getAnalysisUsage(AU); 994 } 995 996 MachineFunctionProperties getRequiredProperties() const override { 997 return MachineFunctionProperties().set( 998 MachineFunctionProperties::Property::NoVRegs); 999 } 1000 1001 private: 1002 /// Track which register units have been modified and used. 1003 LiveRegUnits ModifiedRegUnits, UsedRegUnits; 1004 1005 /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an 1006 /// entry in this map for each unit it touches. 1007 DenseMap<unsigned, TinyPtrVector<MachineInstr *>> SeenDbgInstrs; 1008 1009 /// Sink Copy instructions unused in the same block close to their uses in 1010 /// successors. 1011 bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF, 1012 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII); 1013 }; 1014 } // namespace 1015 1016 char PostRAMachineSinking::ID = 0; 1017 char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID; 1018 1019 INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink", 1020 "PostRA Machine Sink", false, false) 1021 1022 static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg, 1023 const TargetRegisterInfo *TRI) { 1024 LiveRegUnits LiveInRegUnits(*TRI); 1025 LiveInRegUnits.addLiveIns(MBB); 1026 return !LiveInRegUnits.available(Reg); 1027 } 1028 1029 static MachineBasicBlock * 1030 getSingleLiveInSuccBB(MachineBasicBlock &CurBB, 1031 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs, 1032 unsigned Reg, const TargetRegisterInfo *TRI) { 1033 // Try to find a single sinkable successor in which Reg is live-in. 1034 MachineBasicBlock *BB = nullptr; 1035 for (auto *SI : SinkableBBs) { 1036 if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) { 1037 // If BB is set here, Reg is live-in to at least two sinkable successors, 1038 // so quit. 1039 if (BB) 1040 return nullptr; 1041 BB = SI; 1042 } 1043 } 1044 // Reg is not live-in to any sinkable successors. 1045 if (!BB) 1046 return nullptr; 1047 1048 // Check if any register aliased with Reg is live-in in other successors. 1049 for (auto *SI : CurBB.successors()) { 1050 if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI)) 1051 return nullptr; 1052 } 1053 return BB; 1054 } 1055 1056 static MachineBasicBlock * 1057 getSingleLiveInSuccBB(MachineBasicBlock &CurBB, 1058 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs, 1059 ArrayRef<unsigned> DefedRegsInCopy, 1060 const TargetRegisterInfo *TRI) { 1061 MachineBasicBlock *SingleBB = nullptr; 1062 for (auto DefReg : DefedRegsInCopy) { 1063 MachineBasicBlock *BB = 1064 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI); 1065 if (!BB || (SingleBB && SingleBB != BB)) 1066 return nullptr; 1067 SingleBB = BB; 1068 } 1069 return SingleBB; 1070 } 1071 1072 static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB, 1073 SmallVectorImpl<unsigned> &UsedOpsInCopy, 1074 LiveRegUnits &UsedRegUnits, 1075 const TargetRegisterInfo *TRI) { 1076 for (auto U : UsedOpsInCopy) { 1077 MachineOperand &MO = MI->getOperand(U); 1078 Register SrcReg = MO.getReg(); 1079 if (!UsedRegUnits.available(SrcReg)) { 1080 MachineBasicBlock::iterator NI = std::next(MI->getIterator()); 1081 for (MachineInstr &UI : make_range(NI, CurBB.end())) { 1082 if (UI.killsRegister(SrcReg, TRI)) { 1083 UI.clearRegisterKills(SrcReg, TRI); 1084 MO.setIsKill(true); 1085 break; 1086 } 1087 } 1088 } 1089 } 1090 } 1091 1092 static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB, 1093 SmallVectorImpl<unsigned> &UsedOpsInCopy, 1094 SmallVectorImpl<unsigned> &DefedRegsInCopy) { 1095 MachineFunction &MF = *SuccBB->getParent(); 1096 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1097 for (unsigned DefReg : DefedRegsInCopy) 1098 for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S) 1099 SuccBB->removeLiveIn(*S); 1100 for (auto U : UsedOpsInCopy) { 1101 Register Reg = MI->getOperand(U).getReg(); 1102 if (!SuccBB->isLiveIn(Reg)) 1103 SuccBB->addLiveIn(Reg); 1104 } 1105 } 1106 1107 static bool hasRegisterDependency(MachineInstr *MI, 1108 SmallVectorImpl<unsigned> &UsedOpsInCopy, 1109 SmallVectorImpl<unsigned> &DefedRegsInCopy, 1110 LiveRegUnits &ModifiedRegUnits, 1111 LiveRegUnits &UsedRegUnits) { 1112 bool HasRegDependency = false; 1113 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1114 MachineOperand &MO = MI->getOperand(i); 1115 if (!MO.isReg()) 1116 continue; 1117 Register Reg = MO.getReg(); 1118 if (!Reg) 1119 continue; 1120 if (MO.isDef()) { 1121 if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) { 1122 HasRegDependency = true; 1123 break; 1124 } 1125 DefedRegsInCopy.push_back(Reg); 1126 1127 // FIXME: instead of isUse(), readsReg() would be a better fix here, 1128 // For example, we can ignore modifications in reg with undef. However, 1129 // it's not perfectly clear if skipping the internal read is safe in all 1130 // other targets. 1131 } else if (MO.isUse()) { 1132 if (!ModifiedRegUnits.available(Reg)) { 1133 HasRegDependency = true; 1134 break; 1135 } 1136 UsedOpsInCopy.push_back(i); 1137 } 1138 } 1139 return HasRegDependency; 1140 } 1141 1142 static SmallSet<unsigned, 4> getRegUnits(unsigned Reg, 1143 const TargetRegisterInfo *TRI) { 1144 SmallSet<unsigned, 4> RegUnits; 1145 for (auto RI = MCRegUnitIterator(Reg, TRI); RI.isValid(); ++RI) 1146 RegUnits.insert(*RI); 1147 return RegUnits; 1148 } 1149 1150 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB, 1151 MachineFunction &MF, 1152 const TargetRegisterInfo *TRI, 1153 const TargetInstrInfo *TII) { 1154 SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs; 1155 // FIXME: For now, we sink only to a successor which has a single predecessor 1156 // so that we can directly sink COPY instructions to the successor without 1157 // adding any new block or branch instruction. 1158 for (MachineBasicBlock *SI : CurBB.successors()) 1159 if (!SI->livein_empty() && SI->pred_size() == 1) 1160 SinkableBBs.insert(SI); 1161 1162 if (SinkableBBs.empty()) 1163 return false; 1164 1165 bool Changed = false; 1166 1167 // Track which registers have been modified and used between the end of the 1168 // block and the current instruction. 1169 ModifiedRegUnits.clear(); 1170 UsedRegUnits.clear(); 1171 SeenDbgInstrs.clear(); 1172 1173 for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) { 1174 MachineInstr *MI = &*I; 1175 ++I; 1176 1177 // Track the operand index for use in Copy. 1178 SmallVector<unsigned, 2> UsedOpsInCopy; 1179 // Track the register number defed in Copy. 1180 SmallVector<unsigned, 2> DefedRegsInCopy; 1181 1182 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching 1183 // for DBG_VALUEs later, record them when they're encountered. 1184 if (MI->isDebugValue()) { 1185 auto &MO = MI->getOperand(0); 1186 if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) { 1187 // Bail if we can already tell the sink would be rejected, rather 1188 // than needlessly accumulating lots of DBG_VALUEs. 1189 if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy, 1190 ModifiedRegUnits, UsedRegUnits)) 1191 continue; 1192 1193 // Record debug use of each reg unit. 1194 SmallSet<unsigned, 4> Units = getRegUnits(MO.getReg(), TRI); 1195 for (unsigned Reg : Units) 1196 SeenDbgInstrs[Reg].push_back(MI); 1197 } 1198 continue; 1199 } 1200 1201 if (MI->isDebugInstr()) 1202 continue; 1203 1204 // Do not move any instruction across function call. 1205 if (MI->isCall()) 1206 return false; 1207 1208 if (!MI->isCopy() || !MI->getOperand(0).isRenamable()) { 1209 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, 1210 TRI); 1211 continue; 1212 } 1213 1214 // Don't sink the COPY if it would violate a register dependency. 1215 if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy, 1216 ModifiedRegUnits, UsedRegUnits)) { 1217 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, 1218 TRI); 1219 continue; 1220 } 1221 assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) && 1222 "Unexpect SrcReg or DefReg"); 1223 MachineBasicBlock *SuccBB = 1224 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI); 1225 // Don't sink if we cannot find a single sinkable successor in which Reg 1226 // is live-in. 1227 if (!SuccBB) { 1228 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, 1229 TRI); 1230 continue; 1231 } 1232 assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) && 1233 "Unexpected predecessor"); 1234 1235 // Collect DBG_VALUEs that must sink with this copy. We've previously 1236 // recorded which reg units that DBG_VALUEs read, if this instruction 1237 // writes any of those units then the corresponding DBG_VALUEs must sink. 1238 SetVector<MachineInstr *> DbgValsToSinkSet; 1239 SmallVector<MachineInstr *, 4> DbgValsToSink; 1240 for (auto &MO : MI->operands()) { 1241 if (!MO.isReg() || !MO.isDef()) 1242 continue; 1243 1244 SmallSet<unsigned, 4> Units = getRegUnits(MO.getReg(), TRI); 1245 for (unsigned Reg : Units) 1246 for (auto *MI : SeenDbgInstrs.lookup(Reg)) 1247 DbgValsToSinkSet.insert(MI); 1248 } 1249 DbgValsToSink.insert(DbgValsToSink.begin(), DbgValsToSinkSet.begin(), 1250 DbgValsToSinkSet.end()); 1251 1252 // Clear the kill flag if SrcReg is killed between MI and the end of the 1253 // block. 1254 clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI); 1255 MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI(); 1256 performSink(*MI, *SuccBB, InsertPos, &DbgValsToSink); 1257 updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy); 1258 1259 Changed = true; 1260 ++NumPostRACopySink; 1261 } 1262 return Changed; 1263 } 1264 1265 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) { 1266 if (skipFunction(MF.getFunction())) 1267 return false; 1268 1269 bool Changed = false; 1270 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1271 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1272 1273 ModifiedRegUnits.init(*TRI); 1274 UsedRegUnits.init(*TRI); 1275 for (auto &BB : MF) 1276 Changed |= tryToSinkCopy(BB, MF, TRI, TII); 1277 1278 return Changed; 1279 } 1280