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