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