1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass moves instructions into successor blocks when possible, so that 11 // they aren't executed on paths where their results aren't needed. 12 // 13 // This pass is not intended to be a replacement or a complete alternative 14 // for an LLVM-IR-level sinking pass. It is only designed to sink simple 15 // constructs that are not exposed before lowering and instruction selection. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/Passes.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/CodeGen/MachineDominators.h" 24 #include "llvm/CodeGen/MachineLoopInfo.h" 25 #include "llvm/CodeGen/MachineRegisterInfo.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/Target/TargetInstrInfo.h" 30 #include "llvm/Target/TargetMachine.h" 31 #include "llvm/Target/TargetRegisterInfo.h" 32 using namespace llvm; 33 34 #define DEBUG_TYPE "machine-sink" 35 36 static cl::opt<bool> 37 SplitEdges("machine-sink-split", 38 cl::desc("Split critical edges during machine sinking"), 39 cl::init(true), cl::Hidden); 40 41 STATISTIC(NumSunk, "Number of machine instructions sunk"); 42 STATISTIC(NumSplit, "Number of critical edges split"); 43 STATISTIC(NumCoalesces, "Number of copies coalesced"); 44 45 namespace { 46 class MachineSinking : public MachineFunctionPass { 47 const TargetInstrInfo *TII; 48 const TargetRegisterInfo *TRI; 49 MachineRegisterInfo *MRI; // Machine register information 50 MachineDominatorTree *DT; // Machine dominator tree 51 MachineLoopInfo *LI; 52 AliasAnalysis *AA; 53 54 // Remember which edges have been considered for breaking. 55 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8> 56 CEBCandidates; 57 58 public: 59 static char ID; // Pass identification 60 MachineSinking() : MachineFunctionPass(ID) { 61 initializeMachineSinkingPass(*PassRegistry::getPassRegistry()); 62 } 63 64 bool runOnMachineFunction(MachineFunction &MF) override; 65 66 void getAnalysisUsage(AnalysisUsage &AU) const override { 67 AU.setPreservesCFG(); 68 MachineFunctionPass::getAnalysisUsage(AU); 69 AU.addRequired<AliasAnalysis>(); 70 AU.addRequired<MachineDominatorTree>(); 71 AU.addRequired<MachineLoopInfo>(); 72 AU.addPreserved<MachineDominatorTree>(); 73 AU.addPreserved<MachineLoopInfo>(); 74 } 75 76 void releaseMemory() override { 77 CEBCandidates.clear(); 78 } 79 80 private: 81 bool ProcessBlock(MachineBasicBlock &MBB); 82 bool isWorthBreakingCriticalEdge(MachineInstr *MI, 83 MachineBasicBlock *From, 84 MachineBasicBlock *To); 85 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI, 86 MachineBasicBlock *From, 87 MachineBasicBlock *To, 88 bool BreakPHIEdge); 89 bool SinkInstruction(MachineInstr *MI, bool &SawStore); 90 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB, 91 MachineBasicBlock *DefMBB, 92 bool &BreakPHIEdge, bool &LocalUse) const; 93 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB, 94 bool &BreakPHIEdge); 95 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI, 96 MachineBasicBlock *MBB, 97 MachineBasicBlock *SuccToSinkTo); 98 99 bool PerformTrivialForwardCoalescing(MachineInstr *MI, 100 MachineBasicBlock *MBB); 101 }; 102 } // end anonymous namespace 103 104 char MachineSinking::ID = 0; 105 char &llvm::MachineSinkingID = MachineSinking::ID; 106 INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink", 107 "Machine code sinking", false, false) 108 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 109 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 110 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 111 INITIALIZE_PASS_END(MachineSinking, "machine-sink", 112 "Machine code sinking", false, false) 113 114 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI, 115 MachineBasicBlock *MBB) { 116 if (!MI->isCopy()) 117 return false; 118 119 unsigned SrcReg = MI->getOperand(1).getReg(); 120 unsigned DstReg = MI->getOperand(0).getReg(); 121 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || 122 !TargetRegisterInfo::isVirtualRegister(DstReg) || 123 !MRI->hasOneNonDBGUse(SrcReg)) 124 return false; 125 126 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg); 127 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg); 128 if (SRC != DRC) 129 return false; 130 131 MachineInstr *DefMI = MRI->getVRegDef(SrcReg); 132 if (DefMI->isCopyLike()) 133 return false; 134 DEBUG(dbgs() << "Coalescing: " << *DefMI); 135 DEBUG(dbgs() << "*** to: " << *MI); 136 MRI->replaceRegWith(DstReg, SrcReg); 137 MI->eraseFromParent(); 138 ++NumCoalesces; 139 return true; 140 } 141 142 /// AllUsesDominatedByBlock - Return true if all uses of the specified register 143 /// occur in blocks dominated by the specified block. If any use is in the 144 /// definition block, then return false since it is never legal to move def 145 /// after uses. 146 bool 147 MachineSinking::AllUsesDominatedByBlock(unsigned Reg, 148 MachineBasicBlock *MBB, 149 MachineBasicBlock *DefMBB, 150 bool &BreakPHIEdge, 151 bool &LocalUse) const { 152 assert(TargetRegisterInfo::isVirtualRegister(Reg) && 153 "Only makes sense for vregs"); 154 155 // Ignore debug uses because debug info doesn't affect the code. 156 if (MRI->use_nodbg_empty(Reg)) 157 return true; 158 159 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken 160 // into and they are all PHI nodes. In this case, machine-sink must break 161 // the critical edge first. e.g. 162 // 163 // BB#1: derived from LLVM BB %bb4.preheader 164 // Predecessors according to CFG: BB#0 165 // ... 166 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead> 167 // ... 168 // JE_4 <BB#37>, %EFLAGS<imp-use> 169 // Successors according to CFG: BB#37 BB#2 170 // 171 // BB#2: derived from LLVM BB %bb.nph 172 // Predecessors according to CFG: BB#0 BB#1 173 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1> 174 BreakPHIEdge = true; 175 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 176 MachineInstr *UseInst = MO.getParent(); 177 unsigned OpNo = &MO - &UseInst->getOperand(0); 178 MachineBasicBlock *UseBlock = UseInst->getParent(); 179 if (!(UseBlock == MBB && UseInst->isPHI() && 180 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) { 181 BreakPHIEdge = false; 182 break; 183 } 184 } 185 if (BreakPHIEdge) 186 return true; 187 188 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 189 // Determine the block of the use. 190 MachineInstr *UseInst = MO.getParent(); 191 unsigned OpNo = &MO - &UseInst->getOperand(0); 192 MachineBasicBlock *UseBlock = UseInst->getParent(); 193 if (UseInst->isPHI()) { 194 // PHI nodes use the operand in the predecessor block, not the block with 195 // the PHI. 196 UseBlock = UseInst->getOperand(OpNo+1).getMBB(); 197 } else if (UseBlock == DefMBB) { 198 LocalUse = true; 199 return false; 200 } 201 202 // Check that it dominates. 203 if (!DT->dominates(MBB, UseBlock)) 204 return false; 205 } 206 207 return true; 208 } 209 210 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) { 211 if (skipOptnoneFunction(*MF.getFunction())) 212 return false; 213 214 DEBUG(dbgs() << "******** Machine Sinking ********\n"); 215 216 const TargetMachine &TM = MF.getTarget(); 217 TII = TM.getInstrInfo(); 218 TRI = TM.getRegisterInfo(); 219 MRI = &MF.getRegInfo(); 220 DT = &getAnalysis<MachineDominatorTree>(); 221 LI = &getAnalysis<MachineLoopInfo>(); 222 AA = &getAnalysis<AliasAnalysis>(); 223 224 bool EverMadeChange = false; 225 226 while (1) { 227 bool MadeChange = false; 228 229 // Process all basic blocks. 230 CEBCandidates.clear(); 231 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); 232 I != E; ++I) 233 MadeChange |= ProcessBlock(*I); 234 235 // If this iteration over the code changed anything, keep iterating. 236 if (!MadeChange) break; 237 EverMadeChange = true; 238 } 239 return EverMadeChange; 240 } 241 242 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) { 243 // Can't sink anything out of a block that has less than two successors. 244 if (MBB.succ_size() <= 1 || MBB.empty()) return false; 245 246 // Don't bother sinking code out of unreachable blocks. In addition to being 247 // unprofitable, it can also lead to infinite looping, because in an 248 // unreachable loop there may be nowhere to stop. 249 if (!DT->isReachableFromEntry(&MBB)) return false; 250 251 bool MadeChange = false; 252 253 // Walk the basic block bottom-up. Remember if we saw a store. 254 MachineBasicBlock::iterator I = MBB.end(); 255 --I; 256 bool ProcessedBegin, SawStore = false; 257 do { 258 MachineInstr *MI = I; // The instruction to sink. 259 260 // Predecrement I (if it's not begin) so that it isn't invalidated by 261 // sinking. 262 ProcessedBegin = I == MBB.begin(); 263 if (!ProcessedBegin) 264 --I; 265 266 if (MI->isDebugValue()) 267 continue; 268 269 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB); 270 if (Joined) { 271 MadeChange = true; 272 continue; 273 } 274 275 if (SinkInstruction(MI, SawStore)) 276 ++NumSunk, MadeChange = true; 277 278 // If we just processed the first instruction in the block, we're done. 279 } while (!ProcessedBegin); 280 281 return MadeChange; 282 } 283 284 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI, 285 MachineBasicBlock *From, 286 MachineBasicBlock *To) { 287 // FIXME: Need much better heuristics. 288 289 // If the pass has already considered breaking this edge (during this pass 290 // through the function), then let's go ahead and break it. This means 291 // sinking multiple "cheap" instructions into the same block. 292 if (!CEBCandidates.insert(std::make_pair(From, To))) 293 return true; 294 295 if (!MI->isCopy() && !TII->isAsCheapAsAMove(MI)) 296 return true; 297 298 // MI is cheap, we probably don't want to break the critical edge for it. 299 // However, if this would allow some definitions of its source operands 300 // to be sunk then it's probably worth it. 301 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 302 const MachineOperand &MO = MI->getOperand(i); 303 if (!MO.isReg() || !MO.isUse()) 304 continue; 305 unsigned Reg = MO.getReg(); 306 if (Reg == 0) 307 continue; 308 309 // We don't move live definitions of physical registers, 310 // so sinking their uses won't enable any opportunities. 311 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 312 continue; 313 314 // If this instruction is the only user of a virtual register, 315 // check if breaking the edge will enable sinking 316 // both this instruction and the defining instruction. 317 if (MRI->hasOneNonDBGUse(Reg)) { 318 // If the definition resides in same MBB, 319 // claim it's likely we can sink these together. 320 // If definition resides elsewhere, we aren't 321 // blocking it from being sunk so don't break the edge. 322 MachineInstr *DefMI = MRI->getVRegDef(Reg); 323 if (DefMI->getParent() == MI->getParent()) 324 return true; 325 } 326 } 327 328 return false; 329 } 330 331 MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI, 332 MachineBasicBlock *FromBB, 333 MachineBasicBlock *ToBB, 334 bool BreakPHIEdge) { 335 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB)) 336 return nullptr; 337 338 // Avoid breaking back edge. From == To means backedge for single BB loop. 339 if (!SplitEdges || FromBB == ToBB) 340 return nullptr; 341 342 // Check for backedges of more "complex" loops. 343 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) && 344 LI->isLoopHeader(ToBB)) 345 return nullptr; 346 347 // It's not always legal to break critical edges and sink the computation 348 // to the edge. 349 // 350 // BB#1: 351 // v1024 352 // Beq BB#3 353 // <fallthrough> 354 // BB#2: 355 // ... no uses of v1024 356 // <fallthrough> 357 // BB#3: 358 // ... 359 // = v1024 360 // 361 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted: 362 // 363 // BB#1: 364 // ... 365 // Bne BB#2 366 // BB#4: 367 // v1024 = 368 // B BB#3 369 // BB#2: 370 // ... no uses of v1024 371 // <fallthrough> 372 // BB#3: 373 // ... 374 // = v1024 375 // 376 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3 377 // flow. We need to ensure the new basic block where the computation is 378 // sunk to dominates all the uses. 379 // It's only legal to break critical edge and sink the computation to the 380 // new block if all the predecessors of "To", except for "From", are 381 // not dominated by "From". Given SSA property, this means these 382 // predecessors are dominated by "To". 383 // 384 // There is no need to do this check if all the uses are PHI nodes. PHI 385 // sources are only defined on the specific predecessor edges. 386 if (!BreakPHIEdge) { 387 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(), 388 E = ToBB->pred_end(); PI != E; ++PI) { 389 if (*PI == FromBB) 390 continue; 391 if (!DT->dominates(ToBB, *PI)) 392 return nullptr; 393 } 394 } 395 396 return FromBB->SplitCriticalEdge(ToBB, this); 397 } 398 399 static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) { 400 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence(); 401 } 402 403 /// collectDebgValues - Scan instructions following MI and collect any 404 /// matching DBG_VALUEs. 405 static void collectDebugValues(MachineInstr *MI, 406 SmallVectorImpl<MachineInstr *> &DbgValues) { 407 DbgValues.clear(); 408 if (!MI->getOperand(0).isReg()) 409 return; 410 411 MachineBasicBlock::iterator DI = MI; ++DI; 412 for (MachineBasicBlock::iterator DE = MI->getParent()->end(); 413 DI != DE; ++DI) { 414 if (!DI->isDebugValue()) 415 return; 416 if (DI->getOperand(0).isReg() && 417 DI->getOperand(0).getReg() == MI->getOperand(0).getReg()) 418 DbgValues.push_back(DI); 419 } 420 } 421 422 /// isPostDominatedBy - Return true if A is post dominated by B. 423 static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) { 424 425 // FIXME - Use real post dominator. 426 if (A->succ_size() != 2) 427 return false; 428 MachineBasicBlock::succ_iterator I = A->succ_begin(); 429 if (B == *I) 430 ++I; 431 MachineBasicBlock *OtherSuccBlock = *I; 432 if (OtherSuccBlock->succ_size() != 1 || 433 *(OtherSuccBlock->succ_begin()) != B) 434 return false; 435 436 return true; 437 } 438 439 /// isProfitableToSinkTo - Return true if it is profitable to sink MI. 440 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI, 441 MachineBasicBlock *MBB, 442 MachineBasicBlock *SuccToSinkTo) { 443 assert (MI && "Invalid MachineInstr!"); 444 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB"); 445 446 if (MBB == SuccToSinkTo) 447 return false; 448 449 // It is profitable if SuccToSinkTo does not post dominate current block. 450 if (!isPostDominatedBy(MBB, SuccToSinkTo)) 451 return true; 452 453 // Check if only use in post dominated block is PHI instruction. 454 bool NonPHIUse = false; 455 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) { 456 MachineBasicBlock *UseBlock = UseInst.getParent(); 457 if (UseBlock == SuccToSinkTo && !UseInst.isPHI()) 458 NonPHIUse = true; 459 } 460 if (!NonPHIUse) 461 return true; 462 463 // If SuccToSinkTo post dominates then also it may be profitable if MI 464 // can further profitably sinked into another block in next round. 465 bool BreakPHIEdge = false; 466 // FIXME - If finding successor is compile time expensive then catch results. 467 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge)) 468 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2); 469 470 // If SuccToSinkTo is final destination and it is a post dominator of current 471 // block then it is not profitable to sink MI into SuccToSinkTo block. 472 return false; 473 } 474 475 /// FindSuccToSinkTo - Find a successor to sink this instruction to. 476 MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI, 477 MachineBasicBlock *MBB, 478 bool &BreakPHIEdge) { 479 480 assert (MI && "Invalid MachineInstr!"); 481 assert (MBB && "Invalid MachineBasicBlock!"); 482 483 // Loop over all the operands of the specified instruction. If there is 484 // anything we can't handle, bail out. 485 486 // SuccToSinkTo - This is the successor to sink this instruction to, once we 487 // decide. 488 MachineBasicBlock *SuccToSinkTo = nullptr; 489 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 490 const MachineOperand &MO = MI->getOperand(i); 491 if (!MO.isReg()) continue; // Ignore non-register operands. 492 493 unsigned Reg = MO.getReg(); 494 if (Reg == 0) continue; 495 496 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 497 if (MO.isUse()) { 498 // If the physreg has no defs anywhere, it's just an ambient register 499 // and we can freely move its uses. Alternatively, if it's allocatable, 500 // it could get allocated to something with a def during allocation. 501 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent())) 502 return nullptr; 503 } else if (!MO.isDead()) { 504 // A def that isn't dead. We can't move it. 505 return nullptr; 506 } 507 } else { 508 // Virtual register uses are always safe to sink. 509 if (MO.isUse()) continue; 510 511 // If it's not safe to move defs of the register class, then abort. 512 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg))) 513 return nullptr; 514 515 // FIXME: This picks a successor to sink into based on having one 516 // successor that dominates all the uses. However, there are cases where 517 // sinking can happen but where the sink point isn't a successor. For 518 // example: 519 // 520 // x = computation 521 // if () {} else {} 522 // use x 523 // 524 // the instruction could be sunk over the whole diamond for the 525 // if/then/else (or loop, etc), allowing it to be sunk into other blocks 526 // after that. 527 528 // Virtual register defs can only be sunk if all their uses are in blocks 529 // dominated by one of the successors. 530 if (SuccToSinkTo) { 531 // If a previous operand picked a block to sink to, then this operand 532 // must be sinkable to the same block. 533 bool LocalUse = false; 534 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, 535 BreakPHIEdge, LocalUse)) 536 return nullptr; 537 538 continue; 539 } 540 541 // Otherwise, we should look at all the successors and decide which one 542 // we should sink to. 543 // We give successors with smaller loop depth higher priority. 544 SmallVector<MachineBasicBlock*, 4> Succs(MBB->succ_begin(), MBB->succ_end()); 545 // Sort Successors according to their loop depth. 546 std::stable_sort( 547 Succs.begin(), Succs.end(), 548 [this](const MachineBasicBlock *LHS, const MachineBasicBlock *RHS) { 549 return LI->getLoopDepth(LHS) < LI->getLoopDepth(RHS); 550 }); 551 for (SmallVectorImpl<MachineBasicBlock *>::iterator SI = Succs.begin(), 552 E = Succs.end(); SI != E; ++SI) { 553 MachineBasicBlock *SuccBlock = *SI; 554 bool LocalUse = false; 555 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, 556 BreakPHIEdge, LocalUse)) { 557 SuccToSinkTo = SuccBlock; 558 break; 559 } 560 if (LocalUse) 561 // Def is used locally, it's never safe to move this def. 562 return nullptr; 563 } 564 565 // If we couldn't find a block to sink to, ignore this instruction. 566 if (!SuccToSinkTo) 567 return nullptr; 568 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo)) 569 return nullptr; 570 } 571 } 572 573 // It is not possible to sink an instruction into its own block. This can 574 // happen with loops. 575 if (MBB == SuccToSinkTo) 576 return nullptr; 577 578 // It's not safe to sink instructions to EH landing pad. Control flow into 579 // landing pad is implicitly defined. 580 if (SuccToSinkTo && SuccToSinkTo->isLandingPad()) 581 return nullptr; 582 583 return SuccToSinkTo; 584 } 585 586 /// SinkInstruction - Determine whether it is safe to sink the specified machine 587 /// instruction out of its current block into a successor. 588 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) { 589 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to 590 // be close to the source to make it easier to coalesce. 591 if (AvoidsSinking(MI, MRI)) 592 return false; 593 594 // Check if it's safe to move the instruction. 595 if (!MI->isSafeToMove(TII, AA, SawStore)) 596 return false; 597 598 // FIXME: This should include support for sinking instructions within the 599 // block they are currently in to shorten the live ranges. We often get 600 // instructions sunk into the top of a large block, but it would be better to 601 // also sink them down before their first use in the block. This xform has to 602 // be careful not to *increase* register pressure though, e.g. sinking 603 // "x = y + z" down if it kills y and z would increase the live ranges of y 604 // and z and only shrink the live range of x. 605 606 bool BreakPHIEdge = false; 607 MachineBasicBlock *ParentBlock = MI->getParent(); 608 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge); 609 610 // If there are no outputs, it must have side-effects. 611 if (!SuccToSinkTo) 612 return false; 613 614 615 // If the instruction to move defines a dead physical register which is live 616 // when leaving the basic block, don't move it because it could turn into a 617 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>) 618 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { 619 const MachineOperand &MO = MI->getOperand(I); 620 if (!MO.isReg()) continue; 621 unsigned Reg = MO.getReg(); 622 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue; 623 if (SuccToSinkTo->isLiveIn(Reg)) 624 return false; 625 } 626 627 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo); 628 629 // If the block has multiple predecessors, this is a critical edge. 630 // Decide if we can sink along it or need to break the edge. 631 if (SuccToSinkTo->pred_size() > 1) { 632 // We cannot sink a load across a critical edge - there may be stores in 633 // other code paths. 634 bool TryBreak = false; 635 bool store = true; 636 if (!MI->isSafeToMove(TII, AA, store)) { 637 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n"); 638 TryBreak = true; 639 } 640 641 // We don't want to sink across a critical edge if we don't dominate the 642 // successor. We could be introducing calculations to new code paths. 643 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) { 644 DEBUG(dbgs() << " *** NOTE: Critical edge found\n"); 645 TryBreak = true; 646 } 647 648 // Don't sink instructions into a loop. 649 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) { 650 DEBUG(dbgs() << " *** NOTE: Loop header found\n"); 651 TryBreak = true; 652 } 653 654 // Otherwise we are OK with sinking along a critical edge. 655 if (!TryBreak) 656 DEBUG(dbgs() << "Sinking along critical edge.\n"); 657 else { 658 MachineBasicBlock *NewSucc = 659 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge); 660 if (!NewSucc) { 661 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to " 662 "break critical edge\n"); 663 return false; 664 } else { 665 DEBUG(dbgs() << " *** Splitting critical edge:" 666 " BB#" << ParentBlock->getNumber() 667 << " -- BB#" << NewSucc->getNumber() 668 << " -- BB#" << SuccToSinkTo->getNumber() << '\n'); 669 SuccToSinkTo = NewSucc; 670 ++NumSplit; 671 BreakPHIEdge = false; 672 } 673 } 674 } 675 676 if (BreakPHIEdge) { 677 // BreakPHIEdge is true if all the uses are in the successor MBB being 678 // sunken into and they are all PHI nodes. In this case, machine-sink must 679 // break the critical edge first. 680 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock, 681 SuccToSinkTo, BreakPHIEdge); 682 if (!NewSucc) { 683 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to " 684 "break critical edge\n"); 685 return false; 686 } 687 688 DEBUG(dbgs() << " *** Splitting critical edge:" 689 " BB#" << ParentBlock->getNumber() 690 << " -- BB#" << NewSucc->getNumber() 691 << " -- BB#" << SuccToSinkTo->getNumber() << '\n'); 692 SuccToSinkTo = NewSucc; 693 ++NumSplit; 694 } 695 696 // Determine where to insert into. Skip phi nodes. 697 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin(); 698 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI()) 699 ++InsertPos; 700 701 // collect matching debug values. 702 SmallVector<MachineInstr *, 2> DbgValuesToSink; 703 collectDebugValues(MI, DbgValuesToSink); 704 705 // Move the instruction. 706 SuccToSinkTo->splice(InsertPos, ParentBlock, MI, 707 ++MachineBasicBlock::iterator(MI)); 708 709 // Move debug values. 710 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(), 711 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) { 712 MachineInstr *DbgMI = *DBI; 713 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI, 714 ++MachineBasicBlock::iterator(DbgMI)); 715 } 716 717 // Conservatively, clear any kill flags, since it's possible that they are no 718 // longer correct. 719 MI->clearKillInfo(); 720 721 return true; 722 } 723