1 //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===// 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 is an extremely simple MachineInstr-level copy propagation pass. 10 // 11 // This pass forwards the source of COPYs to the users of their destinations 12 // when doing so is legal. For example: 13 // 14 // %reg1 = COPY %reg0 15 // ... 16 // ... = OP %reg1 17 // 18 // If 19 // - %reg0 has not been clobbered by the time of the use of %reg1 20 // - the register class constraints are satisfied 21 // - the COPY def is the only value that reaches OP 22 // then this pass replaces the above with: 23 // 24 // %reg1 = COPY %reg0 25 // ... 26 // ... = OP %reg0 27 // 28 // This pass also removes some redundant COPYs. For example: 29 // 30 // %R1 = COPY %R0 31 // ... // No clobber of %R1 32 // %R0 = COPY %R1 <<< Removed 33 // 34 // or 35 // 36 // %R1 = COPY %R0 37 // ... // No clobber of %R0 38 // %R1 = COPY %R0 <<< Removed 39 // 40 // or 41 // 42 // $R0 = OP ... 43 // ... // No read/clobber of $R0 and $R1 44 // $R1 = COPY $R0 // $R0 is killed 45 // Replace $R0 with $R1 and remove the COPY 46 // $R1 = OP ... 47 // ... 48 // 49 //===----------------------------------------------------------------------===// 50 51 #include "llvm/ADT/DenseMap.h" 52 #include "llvm/ADT/STLExtras.h" 53 #include "llvm/ADT/SetVector.h" 54 #include "llvm/ADT/SmallSet.h" 55 #include "llvm/ADT/SmallVector.h" 56 #include "llvm/ADT/Statistic.h" 57 #include "llvm/ADT/iterator_range.h" 58 #include "llvm/CodeGen/MachineBasicBlock.h" 59 #include "llvm/CodeGen/MachineFunction.h" 60 #include "llvm/CodeGen/MachineFunctionPass.h" 61 #include "llvm/CodeGen/MachineInstr.h" 62 #include "llvm/CodeGen/MachineOperand.h" 63 #include "llvm/CodeGen/MachineRegisterInfo.h" 64 #include "llvm/CodeGen/TargetInstrInfo.h" 65 #include "llvm/CodeGen/TargetRegisterInfo.h" 66 #include "llvm/CodeGen/TargetSubtargetInfo.h" 67 #include "llvm/InitializePasses.h" 68 #include "llvm/MC/MCRegisterInfo.h" 69 #include "llvm/Pass.h" 70 #include "llvm/Support/Debug.h" 71 #include "llvm/Support/DebugCounter.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include <cassert> 74 #include <iterator> 75 76 using namespace llvm; 77 78 #define DEBUG_TYPE "machine-cp" 79 80 STATISTIC(NumDeletes, "Number of dead copies deleted"); 81 STATISTIC(NumCopyForwards, "Number of copy uses forwarded"); 82 STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated"); 83 STATISTIC(SpillageChainsLength, "Length of spillage chains"); 84 STATISTIC(NumSpillageChains, "Number of spillage chains"); 85 DEBUG_COUNTER(FwdCounter, "machine-cp-fwd", 86 "Controls which register COPYs are forwarded"); 87 88 static cl::opt<bool> MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false), 89 cl::Hidden); 90 static cl::opt<cl::boolOrDefault> 91 EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden); 92 93 namespace { 94 95 static std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI, 96 const TargetInstrInfo &TII, 97 bool UseCopyInstr) { 98 if (UseCopyInstr) 99 return TII.isCopyInstr(MI); 100 101 if (MI.isCopy()) 102 return std::optional<DestSourcePair>( 103 DestSourcePair{MI.getOperand(0), MI.getOperand(1)}); 104 105 return std::nullopt; 106 } 107 108 class CopyTracker { 109 struct CopyInfo { 110 MachineInstr *MI, *LastSeenUseInCopy; 111 SmallVector<MCRegister, 4> DefRegs; 112 bool Avail; 113 }; 114 115 DenseMap<MCRegister, CopyInfo> Copies; 116 117 public: 118 /// Mark all of the given registers and their subregisters as unavailable for 119 /// copying. 120 void markRegsUnavailable(ArrayRef<MCRegister> Regs, 121 const TargetRegisterInfo &TRI) { 122 for (MCRegister Reg : Regs) { 123 // Source of copy is no longer available for propagation. 124 for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) { 125 auto CI = Copies.find(*RUI); 126 if (CI != Copies.end()) 127 CI->second.Avail = false; 128 } 129 } 130 } 131 132 /// Remove register from copy maps. 133 void invalidateRegister(MCRegister Reg, const TargetRegisterInfo &TRI, 134 const TargetInstrInfo &TII, bool UseCopyInstr) { 135 // Since Reg might be a subreg of some registers, only invalidate Reg is not 136 // enough. We have to find the COPY defines Reg or registers defined by Reg 137 // and invalidate all of them. 138 SmallSet<MCRegister, 8> RegsToInvalidate; 139 RegsToInvalidate.insert(Reg); 140 for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) { 141 auto I = Copies.find(*RUI); 142 if (I != Copies.end()) { 143 if (MachineInstr *MI = I->second.MI) { 144 std::optional<DestSourcePair> CopyOperands = 145 isCopyInstr(*MI, TII, UseCopyInstr); 146 assert(CopyOperands && "Expect copy"); 147 148 RegsToInvalidate.insert( 149 CopyOperands->Destination->getReg().asMCReg()); 150 RegsToInvalidate.insert(CopyOperands->Source->getReg().asMCReg()); 151 } 152 RegsToInvalidate.insert(I->second.DefRegs.begin(), 153 I->second.DefRegs.end()); 154 } 155 } 156 for (MCRegister InvalidReg : RegsToInvalidate) 157 for (MCRegUnitIterator RUI(InvalidReg, &TRI); RUI.isValid(); ++RUI) 158 Copies.erase(*RUI); 159 } 160 161 /// Clobber a single register, removing it from the tracker's copy maps. 162 void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI, 163 const TargetInstrInfo &TII, bool UseCopyInstr) { 164 for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) { 165 auto I = Copies.find(*RUI); 166 if (I != Copies.end()) { 167 // When we clobber the source of a copy, we need to clobber everything 168 // it defined. 169 markRegsUnavailable(I->second.DefRegs, TRI); 170 // When we clobber the destination of a copy, we need to clobber the 171 // whole register it defined. 172 if (MachineInstr *MI = I->second.MI) { 173 std::optional<DestSourcePair> CopyOperands = 174 isCopyInstr(*MI, TII, UseCopyInstr); 175 markRegsUnavailable({CopyOperands->Destination->getReg().asMCReg()}, 176 TRI); 177 } 178 // Now we can erase the copy. 179 Copies.erase(I); 180 } 181 } 182 } 183 184 /// Add this copy's registers into the tracker's copy maps. 185 void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI, 186 const TargetInstrInfo &TII, bool UseCopyInstr) { 187 std::optional<DestSourcePair> CopyOperands = 188 isCopyInstr(*MI, TII, UseCopyInstr); 189 assert(CopyOperands && "Tracking non-copy?"); 190 191 MCRegister Src = CopyOperands->Source->getReg().asMCReg(); 192 MCRegister Def = CopyOperands->Destination->getReg().asMCReg(); 193 194 // Remember Def is defined by the copy. 195 for (MCRegUnitIterator RUI(Def, &TRI); RUI.isValid(); ++RUI) 196 Copies[*RUI] = {MI, nullptr, {}, true}; 197 198 // Remember source that's copied to Def. Once it's clobbered, then 199 // it's no longer available for copy propagation. 200 for (MCRegUnitIterator RUI(Src, &TRI); RUI.isValid(); ++RUI) { 201 auto I = Copies.insert({*RUI, {nullptr, nullptr, {}, false}}); 202 auto &Copy = I.first->second; 203 if (!is_contained(Copy.DefRegs, Def)) 204 Copy.DefRegs.push_back(Def); 205 Copy.LastSeenUseInCopy = MI; 206 } 207 } 208 209 bool hasAnyCopies() { 210 return !Copies.empty(); 211 } 212 213 MachineInstr *findCopyForUnit(MCRegister RegUnit, 214 const TargetRegisterInfo &TRI, 215 bool MustBeAvailable = false) { 216 auto CI = Copies.find(RegUnit); 217 if (CI == Copies.end()) 218 return nullptr; 219 if (MustBeAvailable && !CI->second.Avail) 220 return nullptr; 221 return CI->second.MI; 222 } 223 224 MachineInstr *findCopyDefViaUnit(MCRegister RegUnit, 225 const TargetRegisterInfo &TRI) { 226 auto CI = Copies.find(RegUnit); 227 if (CI == Copies.end()) 228 return nullptr; 229 if (CI->second.DefRegs.size() != 1) 230 return nullptr; 231 MCRegUnitIterator RUI(CI->second.DefRegs[0], &TRI); 232 return findCopyForUnit(*RUI, TRI, true); 233 } 234 235 MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg, 236 const TargetRegisterInfo &TRI, 237 const TargetInstrInfo &TII, 238 bool UseCopyInstr) { 239 MCRegUnitIterator RUI(Reg, &TRI); 240 MachineInstr *AvailCopy = findCopyDefViaUnit(*RUI, TRI); 241 242 if (!AvailCopy) 243 return nullptr; 244 245 std::optional<DestSourcePair> CopyOperands = 246 isCopyInstr(*AvailCopy, TII, UseCopyInstr); 247 Register AvailSrc = CopyOperands->Source->getReg(); 248 Register AvailDef = CopyOperands->Destination->getReg(); 249 if (!TRI.isSubRegisterEq(AvailSrc, Reg)) 250 return nullptr; 251 252 for (const MachineInstr &MI : 253 make_range(AvailCopy->getReverseIterator(), I.getReverseIterator())) 254 for (const MachineOperand &MO : MI.operands()) 255 if (MO.isRegMask()) 256 // FIXME: Shall we simultaneously invalidate AvailSrc or AvailDef? 257 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef)) 258 return nullptr; 259 260 return AvailCopy; 261 } 262 263 MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister Reg, 264 const TargetRegisterInfo &TRI, 265 const TargetInstrInfo &TII, bool UseCopyInstr) { 266 // We check the first RegUnit here, since we'll only be interested in the 267 // copy if it copies the entire register anyway. 268 MCRegUnitIterator RUI(Reg, &TRI); 269 MachineInstr *AvailCopy = 270 findCopyForUnit(*RUI, TRI, /*MustBeAvailable=*/true); 271 272 if (!AvailCopy) 273 return nullptr; 274 275 std::optional<DestSourcePair> CopyOperands = 276 isCopyInstr(*AvailCopy, TII, UseCopyInstr); 277 Register AvailSrc = CopyOperands->Source->getReg(); 278 Register AvailDef = CopyOperands->Destination->getReg(); 279 if (!TRI.isSubRegisterEq(AvailDef, Reg)) 280 return nullptr; 281 282 // Check that the available copy isn't clobbered by any regmasks between 283 // itself and the destination. 284 for (const MachineInstr &MI : 285 make_range(AvailCopy->getIterator(), DestCopy.getIterator())) 286 for (const MachineOperand &MO : MI.operands()) 287 if (MO.isRegMask()) 288 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef)) 289 return nullptr; 290 291 return AvailCopy; 292 } 293 294 // Find last COPY that defines Reg before Current MachineInstr. 295 MachineInstr *findLastSeenDefInCopy(const MachineInstr &Current, 296 MCRegister Reg, 297 const TargetRegisterInfo &TRI, 298 const TargetInstrInfo &TII, 299 bool UseCopyInstr) { 300 MCRegUnitIterator RUI(Reg, &TRI); 301 auto CI = Copies.find(*RUI); 302 if (CI == Copies.end() || !CI->second.Avail) 303 return nullptr; 304 305 MachineInstr *DefCopy = CI->second.MI; 306 std::optional<DestSourcePair> CopyOperands = 307 isCopyInstr(*DefCopy, TII, UseCopyInstr); 308 Register Def = CopyOperands->Destination->getReg(); 309 if (!TRI.isSubRegisterEq(Def, Reg)) 310 return nullptr; 311 312 for (const MachineInstr &MI : 313 make_range(static_cast<const MachineInstr *>(DefCopy)->getIterator(), 314 Current.getIterator())) 315 for (const MachineOperand &MO : MI.operands()) 316 if (MO.isRegMask()) 317 if (MO.clobbersPhysReg(Def)) { 318 LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " 319 << printReg(Def, &TRI) << "\n"); 320 return nullptr; 321 } 322 323 return DefCopy; 324 } 325 326 // Find last COPY that uses Reg. 327 MachineInstr *findLastSeenUseInCopy(MCRegister Reg, 328 const TargetRegisterInfo &TRI) { 329 MCRegUnitIterator RUI(Reg, &TRI); 330 auto CI = Copies.find(*RUI); 331 if (CI == Copies.end()) 332 return nullptr; 333 return CI->second.LastSeenUseInCopy; 334 } 335 336 void clear() { 337 Copies.clear(); 338 } 339 }; 340 341 class MachineCopyPropagation : public MachineFunctionPass { 342 const TargetRegisterInfo *TRI; 343 const TargetInstrInfo *TII; 344 const MachineRegisterInfo *MRI; 345 346 // Return true if this is a copy instruction and false otherwise. 347 bool UseCopyInstr; 348 349 public: 350 static char ID; // Pass identification, replacement for typeid 351 352 MachineCopyPropagation(bool CopyInstr = false) 353 : MachineFunctionPass(ID), UseCopyInstr(CopyInstr || MCPUseCopyInstr) { 354 initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry()); 355 } 356 357 void getAnalysisUsage(AnalysisUsage &AU) const override { 358 AU.setPreservesCFG(); 359 MachineFunctionPass::getAnalysisUsage(AU); 360 } 361 362 bool runOnMachineFunction(MachineFunction &MF) override; 363 364 MachineFunctionProperties getRequiredProperties() const override { 365 return MachineFunctionProperties().set( 366 MachineFunctionProperties::Property::NoVRegs); 367 } 368 369 private: 370 typedef enum { DebugUse = false, RegularUse = true } DebugType; 371 372 void ReadRegister(MCRegister Reg, MachineInstr &Reader, DebugType DT); 373 void ForwardCopyPropagateBlock(MachineBasicBlock &MBB); 374 void BackwardCopyPropagateBlock(MachineBasicBlock &MBB); 375 void EliminateSpillageCopies(MachineBasicBlock &MBB); 376 bool eraseIfRedundant(MachineInstr &Copy, MCRegister Src, MCRegister Def); 377 void forwardUses(MachineInstr &MI); 378 void propagateDefs(MachineInstr &MI); 379 bool isForwardableRegClassCopy(const MachineInstr &Copy, 380 const MachineInstr &UseI, unsigned UseIdx); 381 bool isBackwardPropagatableRegClassCopy(const MachineInstr &Copy, 382 const MachineInstr &UseI, 383 unsigned UseIdx); 384 bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use); 385 bool hasOverlappingMultipleDef(const MachineInstr &MI, 386 const MachineOperand &MODef, Register Def); 387 388 /// Candidates for deletion. 389 SmallSetVector<MachineInstr *, 8> MaybeDeadCopies; 390 391 /// Multimap tracking debug users in current BB 392 DenseMap<MachineInstr *, SmallSet<MachineInstr *, 2>> CopyDbgUsers; 393 394 CopyTracker Tracker; 395 396 bool Changed; 397 }; 398 399 } // end anonymous namespace 400 401 char MachineCopyPropagation::ID = 0; 402 403 char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID; 404 405 INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE, 406 "Machine Copy Propagation Pass", false, false) 407 408 void MachineCopyPropagation::ReadRegister(MCRegister Reg, MachineInstr &Reader, 409 DebugType DT) { 410 // If 'Reg' is defined by a copy, the copy is no longer a candidate 411 // for elimination. If a copy is "read" by a debug user, record the user 412 // for propagation. 413 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) { 414 if (MachineInstr *Copy = Tracker.findCopyForUnit(*RUI, *TRI)) { 415 if (DT == RegularUse) { 416 LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump()); 417 MaybeDeadCopies.remove(Copy); 418 } else { 419 CopyDbgUsers[Copy].insert(&Reader); 420 } 421 } 422 } 423 } 424 425 /// Return true if \p PreviousCopy did copy register \p Src to register \p Def. 426 /// This fact may have been obscured by sub register usage or may not be true at 427 /// all even though Src and Def are subregisters of the registers used in 428 /// PreviousCopy. e.g. 429 /// isNopCopy("ecx = COPY eax", AX, CX) == true 430 /// isNopCopy("ecx = COPY eax", AH, CL) == false 431 static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src, 432 MCRegister Def, const TargetRegisterInfo *TRI, 433 const TargetInstrInfo *TII, bool UseCopyInstr) { 434 435 std::optional<DestSourcePair> CopyOperands = 436 isCopyInstr(PreviousCopy, *TII, UseCopyInstr); 437 MCRegister PreviousSrc = CopyOperands->Source->getReg().asMCReg(); 438 MCRegister PreviousDef = CopyOperands->Destination->getReg().asMCReg(); 439 if (Src == PreviousSrc && Def == PreviousDef) 440 return true; 441 if (!TRI->isSubRegister(PreviousSrc, Src)) 442 return false; 443 unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src); 444 return SubIdx == TRI->getSubRegIndex(PreviousDef, Def); 445 } 446 447 /// Remove instruction \p Copy if there exists a previous copy that copies the 448 /// register \p Src to the register \p Def; This may happen indirectly by 449 /// copying the super registers. 450 bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy, 451 MCRegister Src, MCRegister Def) { 452 // Avoid eliminating a copy from/to a reserved registers as we cannot predict 453 // the value (Example: The sparc zero register is writable but stays zero). 454 if (MRI->isReserved(Src) || MRI->isReserved(Def)) 455 return false; 456 457 // Search for an existing copy. 458 MachineInstr *PrevCopy = 459 Tracker.findAvailCopy(Copy, Def, *TRI, *TII, UseCopyInstr); 460 if (!PrevCopy) 461 return false; 462 463 auto PrevCopyOperands = isCopyInstr(*PrevCopy, *TII, UseCopyInstr); 464 // Check that the existing copy uses the correct sub registers. 465 if (PrevCopyOperands->Destination->isDead()) 466 return false; 467 if (!isNopCopy(*PrevCopy, Src, Def, TRI, TII, UseCopyInstr)) 468 return false; 469 470 LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump()); 471 472 // Copy was redundantly redefining either Src or Def. Remove earlier kill 473 // flags between Copy and PrevCopy because the value will be reused now. 474 std::optional<DestSourcePair> CopyOperands = 475 isCopyInstr(Copy, *TII, UseCopyInstr); 476 assert(CopyOperands); 477 478 Register CopyDef = CopyOperands->Destination->getReg(); 479 assert(CopyDef == Src || CopyDef == Def); 480 for (MachineInstr &MI : 481 make_range(PrevCopy->getIterator(), Copy.getIterator())) 482 MI.clearRegisterKills(CopyDef, TRI); 483 484 Copy.eraseFromParent(); 485 Changed = true; 486 ++NumDeletes; 487 return true; 488 } 489 490 bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy( 491 const MachineInstr &Copy, const MachineInstr &UseI, unsigned UseIdx) { 492 std::optional<DestSourcePair> CopyOperands = 493 isCopyInstr(Copy, *TII, UseCopyInstr); 494 Register Def = CopyOperands->Destination->getReg(); 495 496 if (const TargetRegisterClass *URC = 497 UseI.getRegClassConstraint(UseIdx, TII, TRI)) 498 return URC->contains(Def); 499 500 // We don't process further if UseI is a COPY, since forward copy propagation 501 // should handle that. 502 return false; 503 } 504 505 /// Decide whether we should forward the source of \param Copy to its use in 506 /// \param UseI based on the physical register class constraints of the opcode 507 /// and avoiding introducing more cross-class COPYs. 508 bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy, 509 const MachineInstr &UseI, 510 unsigned UseIdx) { 511 std::optional<DestSourcePair> CopyOperands = 512 isCopyInstr(Copy, *TII, UseCopyInstr); 513 Register CopySrcReg = CopyOperands->Source->getReg(); 514 515 // If the new register meets the opcode register constraints, then allow 516 // forwarding. 517 if (const TargetRegisterClass *URC = 518 UseI.getRegClassConstraint(UseIdx, TII, TRI)) 519 return URC->contains(CopySrcReg); 520 521 auto UseICopyOperands = isCopyInstr(UseI, *TII, UseCopyInstr); 522 if (!UseICopyOperands) 523 return false; 524 525 /// COPYs don't have register class constraints, so if the user instruction 526 /// is a COPY, we just try to avoid introducing additional cross-class 527 /// COPYs. For example: 528 /// 529 /// RegClassA = COPY RegClassB // Copy parameter 530 /// ... 531 /// RegClassB = COPY RegClassA // UseI parameter 532 /// 533 /// which after forwarding becomes 534 /// 535 /// RegClassA = COPY RegClassB 536 /// ... 537 /// RegClassB = COPY RegClassB 538 /// 539 /// so we have reduced the number of cross-class COPYs and potentially 540 /// introduced a nop COPY that can be removed. 541 542 // Allow forwarding if src and dst belong to any common class, so long as they 543 // don't belong to any (possibly smaller) common class that requires copies to 544 // go via a different class. 545 Register UseDstReg = UseICopyOperands->Destination->getReg(); 546 bool Found = false; 547 bool IsCrossClass = false; 548 for (const TargetRegisterClass *RC : TRI->regclasses()) { 549 if (RC->contains(CopySrcReg) && RC->contains(UseDstReg)) { 550 Found = true; 551 if (TRI->getCrossCopyRegClass(RC) != RC) { 552 IsCrossClass = true; 553 break; 554 } 555 } 556 } 557 if (!Found) 558 return false; 559 if (!IsCrossClass) 560 return true; 561 // The forwarded copy would be cross-class. Only do this if the original copy 562 // was also cross-class. 563 Register CopyDstReg = CopyOperands->Destination->getReg(); 564 for (const TargetRegisterClass *RC : TRI->regclasses()) { 565 if (RC->contains(CopySrcReg) && RC->contains(CopyDstReg) && 566 TRI->getCrossCopyRegClass(RC) != RC) 567 return true; 568 } 569 return false; 570 } 571 572 /// Check that \p MI does not have implicit uses that overlap with it's \p Use 573 /// operand (the register being replaced), since these can sometimes be 574 /// implicitly tied to other operands. For example, on AMDGPU: 575 /// 576 /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use> 577 /// 578 /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no 579 /// way of knowing we need to update the latter when updating the former. 580 bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI, 581 const MachineOperand &Use) { 582 for (const MachineOperand &MIUse : MI.uses()) 583 if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() && 584 MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg())) 585 return true; 586 587 return false; 588 } 589 590 /// For an MI that has multiple definitions, check whether \p MI has 591 /// a definition that overlaps with another of its definitions. 592 /// For example, on ARM: umull r9, r9, lr, r0 593 /// The umull instruction is unpredictable unless RdHi and RdLo are different. 594 bool MachineCopyPropagation::hasOverlappingMultipleDef( 595 const MachineInstr &MI, const MachineOperand &MODef, Register Def) { 596 for (const MachineOperand &MIDef : MI.defs()) { 597 if ((&MIDef != &MODef) && MIDef.isReg() && 598 TRI->regsOverlap(Def, MIDef.getReg())) 599 return true; 600 } 601 602 return false; 603 } 604 605 /// Look for available copies whose destination register is used by \p MI and 606 /// replace the use in \p MI with the copy's source register. 607 void MachineCopyPropagation::forwardUses(MachineInstr &MI) { 608 if (!Tracker.hasAnyCopies()) 609 return; 610 611 // Look for non-tied explicit vreg uses that have an active COPY 612 // instruction that defines the physical register allocated to them. 613 // Replace the vreg with the source of the active COPY. 614 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd; 615 ++OpIdx) { 616 MachineOperand &MOUse = MI.getOperand(OpIdx); 617 // Don't forward into undef use operands since doing so can cause problems 618 // with the machine verifier, since it doesn't treat undef reads as reads, 619 // so we can end up with a live range that ends on an undef read, leading to 620 // an error that the live range doesn't end on a read of the live range 621 // register. 622 if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() || 623 MOUse.isImplicit()) 624 continue; 625 626 if (!MOUse.getReg()) 627 continue; 628 629 // Check that the register is marked 'renamable' so we know it is safe to 630 // rename it without violating any constraints that aren't expressed in the 631 // IR (e.g. ABI or opcode requirements). 632 if (!MOUse.isRenamable()) 633 continue; 634 635 MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg().asMCReg(), 636 *TRI, *TII, UseCopyInstr); 637 if (!Copy) 638 continue; 639 640 std::optional<DestSourcePair> CopyOperands = 641 isCopyInstr(*Copy, *TII, UseCopyInstr); 642 Register CopyDstReg = CopyOperands->Destination->getReg(); 643 const MachineOperand &CopySrc = *CopyOperands->Source; 644 Register CopySrcReg = CopySrc.getReg(); 645 646 // When the use is a subregister of the COPY destination, 647 // record the subreg index. 648 unsigned SubregIdx = 0; 649 650 // This can only occur when we are dealing with physical registers. 651 if (MOUse.getReg() != CopyDstReg) { 652 SubregIdx = TRI->getSubRegIndex(CopyDstReg, MOUse.getReg()); 653 if (!SubregIdx) 654 continue; 655 } 656 657 // Don't forward COPYs of reserved regs unless they are constant. 658 if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg)) 659 continue; 660 661 if (!isForwardableRegClassCopy(*Copy, MI, OpIdx)) 662 continue; 663 664 if (hasImplicitOverlap(MI, MOUse)) 665 continue; 666 667 // Check that the instruction is not a copy that partially overwrites the 668 // original copy source that we are about to use. The tracker mechanism 669 // cannot cope with that. 670 if (isCopyInstr(MI, *TII, UseCopyInstr) && 671 MI.modifiesRegister(CopySrcReg, TRI) && 672 !MI.definesRegister(CopySrcReg)) { 673 LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI); 674 continue; 675 } 676 677 if (!DebugCounter::shouldExecute(FwdCounter)) { 678 LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n " 679 << MI); 680 continue; 681 } 682 683 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI) 684 << "\n with " << printReg(CopySrcReg, TRI) 685 << "\n in " << MI << " from " << *Copy); 686 687 if (SubregIdx) 688 MOUse.setReg(TRI->getSubReg(CopySrcReg, SubregIdx)); 689 else 690 MOUse.setReg(CopySrcReg); 691 692 if (!CopySrc.isRenamable()) 693 MOUse.setIsRenamable(false); 694 MOUse.setIsUndef(CopySrc.isUndef()); 695 696 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n"); 697 698 // Clear kill markers that may have been invalidated. 699 for (MachineInstr &KMI : 700 make_range(Copy->getIterator(), std::next(MI.getIterator()))) 701 KMI.clearRegisterKills(CopySrcReg, TRI); 702 703 ++NumCopyForwards; 704 Changed = true; 705 } 706 } 707 708 void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) { 709 LLVM_DEBUG(dbgs() << "MCP: ForwardCopyPropagateBlock " << MBB.getName() 710 << "\n"); 711 712 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) { 713 // Analyze copies (which don't overlap themselves). 714 std::optional<DestSourcePair> CopyOperands = 715 isCopyInstr(MI, *TII, UseCopyInstr); 716 if (CopyOperands) { 717 718 Register RegSrc = CopyOperands->Source->getReg(); 719 Register RegDef = CopyOperands->Destination->getReg(); 720 721 if (!TRI->regsOverlap(RegDef, RegSrc)) { 722 assert(RegDef.isPhysical() && RegSrc.isPhysical() && 723 "MachineCopyPropagation should be run after register allocation!"); 724 725 MCRegister Def = RegDef.asMCReg(); 726 MCRegister Src = RegSrc.asMCReg(); 727 728 // The two copies cancel out and the source of the first copy 729 // hasn't been overridden, eliminate the second one. e.g. 730 // %ecx = COPY %eax 731 // ... nothing clobbered eax. 732 // %eax = COPY %ecx 733 // => 734 // %ecx = COPY %eax 735 // 736 // or 737 // 738 // %ecx = COPY %eax 739 // ... nothing clobbered eax. 740 // %ecx = COPY %eax 741 // => 742 // %ecx = COPY %eax 743 if (eraseIfRedundant(MI, Def, Src) || eraseIfRedundant(MI, Src, Def)) 744 continue; 745 746 forwardUses(MI); 747 748 // Src may have been changed by forwardUses() 749 CopyOperands = isCopyInstr(MI, *TII, UseCopyInstr); 750 Src = CopyOperands->Source->getReg().asMCReg(); 751 752 // If Src is defined by a previous copy, the previous copy cannot be 753 // eliminated. 754 ReadRegister(Src, MI, RegularUse); 755 for (const MachineOperand &MO : MI.implicit_operands()) { 756 if (!MO.isReg() || !MO.readsReg()) 757 continue; 758 MCRegister Reg = MO.getReg().asMCReg(); 759 if (!Reg) 760 continue; 761 ReadRegister(Reg, MI, RegularUse); 762 } 763 764 LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI.dump()); 765 766 // Copy is now a candidate for deletion. 767 if (!MRI->isReserved(Def)) 768 MaybeDeadCopies.insert(&MI); 769 770 // If 'Def' is previously source of another copy, then this earlier copy's 771 // source is no longer available. e.g. 772 // %xmm9 = copy %xmm2 773 // ... 774 // %xmm2 = copy %xmm0 775 // ... 776 // %xmm2 = copy %xmm9 777 Tracker.clobberRegister(Def, *TRI, *TII, UseCopyInstr); 778 for (const MachineOperand &MO : MI.implicit_operands()) { 779 if (!MO.isReg() || !MO.isDef()) 780 continue; 781 MCRegister Reg = MO.getReg().asMCReg(); 782 if (!Reg) 783 continue; 784 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr); 785 } 786 787 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr); 788 789 continue; 790 } 791 } 792 793 // Clobber any earlyclobber regs first. 794 for (const MachineOperand &MO : MI.operands()) 795 if (MO.isReg() && MO.isEarlyClobber()) { 796 MCRegister Reg = MO.getReg().asMCReg(); 797 // If we have a tied earlyclobber, that means it is also read by this 798 // instruction, so we need to make sure we don't remove it as dead 799 // later. 800 if (MO.isTied()) 801 ReadRegister(Reg, MI, RegularUse); 802 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr); 803 } 804 805 forwardUses(MI); 806 807 // Not a copy. 808 SmallVector<Register, 2> Defs; 809 const MachineOperand *RegMask = nullptr; 810 for (const MachineOperand &MO : MI.operands()) { 811 if (MO.isRegMask()) 812 RegMask = &MO; 813 if (!MO.isReg()) 814 continue; 815 Register Reg = MO.getReg(); 816 if (!Reg) 817 continue; 818 819 assert(!Reg.isVirtual() && 820 "MachineCopyPropagation should be run after register allocation!"); 821 822 if (MO.isDef() && !MO.isEarlyClobber()) { 823 Defs.push_back(Reg.asMCReg()); 824 continue; 825 } else if (MO.readsReg()) 826 ReadRegister(Reg.asMCReg(), MI, MO.isDebug() ? DebugUse : RegularUse); 827 } 828 829 // The instruction has a register mask operand which means that it clobbers 830 // a large set of registers. Treat clobbered registers the same way as 831 // defined registers. 832 if (RegMask) { 833 // Erase any MaybeDeadCopies whose destination register is clobbered. 834 for (SmallSetVector<MachineInstr *, 8>::iterator DI = 835 MaybeDeadCopies.begin(); 836 DI != MaybeDeadCopies.end();) { 837 MachineInstr *MaybeDead = *DI; 838 std::optional<DestSourcePair> CopyOperands = 839 isCopyInstr(*MaybeDead, *TII, UseCopyInstr); 840 MCRegister Reg = CopyOperands->Destination->getReg().asMCReg(); 841 assert(!MRI->isReserved(Reg)); 842 843 if (!RegMask->clobbersPhysReg(Reg)) { 844 ++DI; 845 continue; 846 } 847 848 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: "; 849 MaybeDead->dump()); 850 851 // Make sure we invalidate any entries in the copy maps before erasing 852 // the instruction. 853 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr); 854 855 // erase() will return the next valid iterator pointing to the next 856 // element after the erased one. 857 DI = MaybeDeadCopies.erase(DI); 858 MaybeDead->eraseFromParent(); 859 Changed = true; 860 ++NumDeletes; 861 } 862 } 863 864 // Any previous copy definition or reading the Defs is no longer available. 865 for (MCRegister Reg : Defs) 866 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr); 867 } 868 869 // If MBB doesn't have successors, delete the copies whose defs are not used. 870 // If MBB does have successors, then conservative assume the defs are live-out 871 // since we don't want to trust live-in lists. 872 if (MBB.succ_empty()) { 873 for (MachineInstr *MaybeDead : MaybeDeadCopies) { 874 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: "; 875 MaybeDead->dump()); 876 877 std::optional<DestSourcePair> CopyOperands = 878 isCopyInstr(*MaybeDead, *TII, UseCopyInstr); 879 assert(CopyOperands); 880 881 Register SrcReg = CopyOperands->Source->getReg(); 882 Register DestReg = CopyOperands->Destination->getReg(); 883 assert(!MRI->isReserved(DestReg)); 884 885 // Update matching debug values, if any. 886 SmallVector<MachineInstr *> MaybeDeadDbgUsers( 887 CopyDbgUsers[MaybeDead].begin(), CopyDbgUsers[MaybeDead].end()); 888 MRI->updateDbgUsersToReg(DestReg.asMCReg(), SrcReg.asMCReg(), 889 MaybeDeadDbgUsers); 890 891 MaybeDead->eraseFromParent(); 892 Changed = true; 893 ++NumDeletes; 894 } 895 } 896 897 MaybeDeadCopies.clear(); 898 CopyDbgUsers.clear(); 899 Tracker.clear(); 900 } 901 902 static bool isBackwardPropagatableCopy(const DestSourcePair &CopyOperands, 903 const MachineRegisterInfo &MRI, 904 const TargetInstrInfo &TII) { 905 Register Def = CopyOperands.Destination->getReg(); 906 Register Src = CopyOperands.Source->getReg(); 907 908 if (!Def || !Src) 909 return false; 910 911 if (MRI.isReserved(Def) || MRI.isReserved(Src)) 912 return false; 913 914 return CopyOperands.Source->isRenamable() && CopyOperands.Source->isKill(); 915 } 916 917 void MachineCopyPropagation::propagateDefs(MachineInstr &MI) { 918 if (!Tracker.hasAnyCopies()) 919 return; 920 921 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx != OpEnd; 922 ++OpIdx) { 923 MachineOperand &MODef = MI.getOperand(OpIdx); 924 925 if (!MODef.isReg() || MODef.isUse()) 926 continue; 927 928 // Ignore non-trivial cases. 929 if (MODef.isTied() || MODef.isUndef() || MODef.isImplicit()) 930 continue; 931 932 if (!MODef.getReg()) 933 continue; 934 935 // We only handle if the register comes from a vreg. 936 if (!MODef.isRenamable()) 937 continue; 938 939 MachineInstr *Copy = Tracker.findAvailBackwardCopy( 940 MI, MODef.getReg().asMCReg(), *TRI, *TII, UseCopyInstr); 941 if (!Copy) 942 continue; 943 944 std::optional<DestSourcePair> CopyOperands = 945 isCopyInstr(*Copy, *TII, UseCopyInstr); 946 Register Def = CopyOperands->Destination->getReg(); 947 Register Src = CopyOperands->Source->getReg(); 948 949 if (MODef.getReg() != Src) 950 continue; 951 952 if (!isBackwardPropagatableRegClassCopy(*Copy, MI, OpIdx)) 953 continue; 954 955 if (hasImplicitOverlap(MI, MODef)) 956 continue; 957 958 if (hasOverlappingMultipleDef(MI, MODef, Def)) 959 continue; 960 961 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MODef.getReg(), TRI) 962 << "\n with " << printReg(Def, TRI) << "\n in " 963 << MI << " from " << *Copy); 964 965 MODef.setReg(Def); 966 MODef.setIsRenamable(CopyOperands->Destination->isRenamable()); 967 968 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n"); 969 MaybeDeadCopies.insert(Copy); 970 Changed = true; 971 ++NumCopyBackwardPropagated; 972 } 973 } 974 975 void MachineCopyPropagation::BackwardCopyPropagateBlock( 976 MachineBasicBlock &MBB) { 977 LLVM_DEBUG(dbgs() << "MCP: BackwardCopyPropagateBlock " << MBB.getName() 978 << "\n"); 979 980 for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(MBB))) { 981 // Ignore non-trivial COPYs. 982 std::optional<DestSourcePair> CopyOperands = 983 isCopyInstr(MI, *TII, UseCopyInstr); 984 if (CopyOperands && MI.getNumOperands() == 2) { 985 Register DefReg = CopyOperands->Destination->getReg(); 986 Register SrcReg = CopyOperands->Source->getReg(); 987 988 if (!TRI->regsOverlap(DefReg, SrcReg)) { 989 // Unlike forward cp, we don't invoke propagateDefs here, 990 // just let forward cp do COPY-to-COPY propagation. 991 if (isBackwardPropagatableCopy(*CopyOperands, *MRI, *TII)) { 992 Tracker.invalidateRegister(SrcReg.asMCReg(), *TRI, *TII, 993 UseCopyInstr); 994 Tracker.invalidateRegister(DefReg.asMCReg(), *TRI, *TII, 995 UseCopyInstr); 996 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr); 997 continue; 998 } 999 } 1000 } 1001 1002 // Invalidate any earlyclobber regs first. 1003 for (const MachineOperand &MO : MI.operands()) 1004 if (MO.isReg() && MO.isEarlyClobber()) { 1005 MCRegister Reg = MO.getReg().asMCReg(); 1006 if (!Reg) 1007 continue; 1008 Tracker.invalidateRegister(Reg, *TRI, *TII, UseCopyInstr); 1009 } 1010 1011 propagateDefs(MI); 1012 for (const MachineOperand &MO : MI.operands()) { 1013 if (!MO.isReg()) 1014 continue; 1015 1016 if (!MO.getReg()) 1017 continue; 1018 1019 if (MO.isDef()) 1020 Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII, 1021 UseCopyInstr); 1022 1023 if (MO.readsReg()) { 1024 if (MO.isDebug()) { 1025 // Check if the register in the debug instruction is utilized 1026 // in a copy instruction, so we can update the debug info if the 1027 // register is changed. 1028 for (MCRegUnitIterator RUI(MO.getReg().asMCReg(), TRI); RUI.isValid(); 1029 ++RUI) { 1030 if (auto *Copy = Tracker.findCopyDefViaUnit(*RUI, *TRI)) { 1031 CopyDbgUsers[Copy].insert(&MI); 1032 } 1033 } 1034 } else { 1035 Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII, 1036 UseCopyInstr); 1037 } 1038 } 1039 } 1040 } 1041 1042 for (auto *Copy : MaybeDeadCopies) { 1043 std::optional<DestSourcePair> CopyOperands = 1044 isCopyInstr(*Copy, *TII, UseCopyInstr); 1045 Register Src = CopyOperands->Source->getReg(); 1046 Register Def = CopyOperands->Destination->getReg(); 1047 SmallVector<MachineInstr *> MaybeDeadDbgUsers(CopyDbgUsers[Copy].begin(), 1048 CopyDbgUsers[Copy].end()); 1049 1050 MRI->updateDbgUsersToReg(Src.asMCReg(), Def.asMCReg(), MaybeDeadDbgUsers); 1051 Copy->eraseFromParent(); 1052 ++NumDeletes; 1053 } 1054 1055 MaybeDeadCopies.clear(); 1056 CopyDbgUsers.clear(); 1057 Tracker.clear(); 1058 } 1059 1060 static void LLVM_ATTRIBUTE_UNUSED printSpillReloadChain( 1061 DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &SpillChain, 1062 DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &ReloadChain, 1063 MachineInstr *Leader) { 1064 auto &SC = SpillChain[Leader]; 1065 auto &RC = ReloadChain[Leader]; 1066 for (auto I = SC.rbegin(), E = SC.rend(); I != E; ++I) 1067 (*I)->dump(); 1068 for (MachineInstr *MI : RC) 1069 MI->dump(); 1070 } 1071 1072 // Remove spill-reload like copy chains. For example 1073 // r0 = COPY r1 1074 // r1 = COPY r2 1075 // r2 = COPY r3 1076 // r3 = COPY r4 1077 // <def-use r4> 1078 // r4 = COPY r3 1079 // r3 = COPY r2 1080 // r2 = COPY r1 1081 // r1 = COPY r0 1082 // will be folded into 1083 // r0 = COPY r1 1084 // r1 = COPY r4 1085 // <def-use r4> 1086 // r4 = COPY r1 1087 // r1 = COPY r0 1088 // TODO: Currently we don't track usage of r0 outside the chain, so we 1089 // conservatively keep its value as it was before the rewrite. 1090 // 1091 // The algorithm is trying to keep 1092 // property#1: No Def of spill COPY in the chain is used or defined until the 1093 // paired reload COPY in the chain uses the Def. 1094 // 1095 // property#2: NO Source of COPY in the chain is used or defined until the next 1096 // COPY in the chain defines the Source, except the innermost spill-reload 1097 // pair. 1098 // 1099 // The algorithm is conducted by checking every COPY inside the MBB, assuming 1100 // the COPY is a reload COPY, then try to find paired spill COPY by searching 1101 // the COPY defines the Src of the reload COPY backward. If such pair is found, 1102 // it either belongs to an existing chain or a new chain depends on 1103 // last available COPY uses the Def of the reload COPY. 1104 // Implementation notes, we use CopyTracker::findLastDefCopy(Reg, ...) to find 1105 // out last COPY that defines Reg; we use CopyTracker::findLastUseCopy(Reg, ...) 1106 // to find out last COPY that uses Reg. When we are encountered with a Non-COPY 1107 // instruction, we check registers in the operands of this instruction. If this 1108 // Reg is defined by a COPY, we untrack this Reg via 1109 // CopyTracker::clobberRegister(Reg, ...). 1110 void MachineCopyPropagation::EliminateSpillageCopies(MachineBasicBlock &MBB) { 1111 // ChainLeader maps MI inside a spill-reload chain to its innermost reload COPY. 1112 // Thus we can track if a MI belongs to an existing spill-reload chain. 1113 DenseMap<MachineInstr *, MachineInstr *> ChainLeader; 1114 // SpillChain maps innermost reload COPY of a spill-reload chain to a sequence 1115 // of COPYs that forms spills of a spill-reload chain. 1116 // ReloadChain maps innermost reload COPY of a spill-reload chain to a 1117 // sequence of COPYs that forms reloads of a spill-reload chain. 1118 DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain; 1119 // If a COPY's Source has use or def until next COPY defines the Source, 1120 // we put the COPY in this set to keep property#2. 1121 DenseSet<const MachineInstr *> CopySourceInvalid; 1122 1123 auto TryFoldSpillageCopies = 1124 [&, this](const SmallVectorImpl<MachineInstr *> &SC, 1125 const SmallVectorImpl<MachineInstr *> &RC) { 1126 assert(SC.size() == RC.size() && "Spill-reload should be paired"); 1127 1128 // We need at least 3 pairs of copies for the transformation to apply, 1129 // because the first outermost pair cannot be removed since we don't 1130 // recolor outside of the chain and that we need at least one temporary 1131 // spill slot to shorten the chain. If we only have a chain of two 1132 // pairs, we already have the shortest sequence this code can handle: 1133 // the outermost pair for the temporary spill slot, and the pair that 1134 // use that temporary spill slot for the other end of the chain. 1135 // TODO: We might be able to simplify to one spill-reload pair if collecting 1136 // more infomation about the outermost COPY. 1137 if (SC.size() <= 2) 1138 return; 1139 1140 // If violate property#2, we don't fold the chain. 1141 for (const MachineInstr *Spill : make_range(SC.begin() + 1, SC.end())) 1142 if (CopySourceInvalid.count(Spill)) 1143 return; 1144 1145 for (const MachineInstr *Reload : make_range(RC.begin(), RC.end() - 1)) 1146 if (CopySourceInvalid.count(Reload)) 1147 return; 1148 1149 auto CheckCopyConstraint = [this](Register Def, Register Src) { 1150 for (const TargetRegisterClass *RC : TRI->regclasses()) { 1151 if (RC->contains(Def) && RC->contains(Src)) 1152 return true; 1153 } 1154 return false; 1155 }; 1156 1157 auto UpdateReg = [](MachineInstr *MI, const MachineOperand *Old, 1158 const MachineOperand *New) { 1159 for (MachineOperand &MO : MI->operands()) { 1160 if (&MO == Old) 1161 MO.setReg(New->getReg()); 1162 } 1163 }; 1164 1165 std::optional<DestSourcePair> InnerMostSpillCopy = 1166 isCopyInstr(*SC[0], *TII, UseCopyInstr); 1167 std::optional<DestSourcePair> OuterMostSpillCopy = 1168 isCopyInstr(*SC.back(), *TII, UseCopyInstr); 1169 std::optional<DestSourcePair> InnerMostReloadCopy = 1170 isCopyInstr(*RC[0], *TII, UseCopyInstr); 1171 std::optional<DestSourcePair> OuterMostReloadCopy = 1172 isCopyInstr(*RC.back(), *TII, UseCopyInstr); 1173 if (!CheckCopyConstraint(OuterMostSpillCopy->Source->getReg(), 1174 InnerMostSpillCopy->Source->getReg()) || 1175 !CheckCopyConstraint(InnerMostReloadCopy->Destination->getReg(), 1176 OuterMostReloadCopy->Destination->getReg())) 1177 return; 1178 1179 SpillageChainsLength += SC.size() + RC.size(); 1180 NumSpillageChains += 1; 1181 UpdateReg(SC[0], InnerMostSpillCopy->Destination, 1182 OuterMostSpillCopy->Source); 1183 UpdateReg(RC[0], InnerMostReloadCopy->Source, 1184 OuterMostReloadCopy->Destination); 1185 1186 for (size_t I = 1; I < SC.size() - 1; ++I) { 1187 SC[I]->eraseFromParent(); 1188 RC[I]->eraseFromParent(); 1189 NumDeletes += 2; 1190 } 1191 }; 1192 1193 auto IsFoldableCopy = [this](const MachineInstr &MaybeCopy) { 1194 if (MaybeCopy.getNumImplicitOperands() > 0) 1195 return false; 1196 std::optional<DestSourcePair> CopyOperands = 1197 isCopyInstr(MaybeCopy, *TII, UseCopyInstr); 1198 if (!CopyOperands) 1199 return false; 1200 Register Src = CopyOperands->Source->getReg(); 1201 Register Def = CopyOperands->Destination->getReg(); 1202 return Src && Def && !TRI->regsOverlap(Src, Def) && 1203 CopyOperands->Source->isRenamable() && 1204 CopyOperands->Destination->isRenamable(); 1205 }; 1206 1207 auto IsSpillReloadPair = [&, this](const MachineInstr &Spill, 1208 const MachineInstr &Reload) { 1209 if (!IsFoldableCopy(Spill) || !IsFoldableCopy(Reload)) 1210 return false; 1211 std::optional<DestSourcePair> SpillCopy = 1212 isCopyInstr(Spill, *TII, UseCopyInstr); 1213 std::optional<DestSourcePair> ReloadCopy = 1214 isCopyInstr(Reload, *TII, UseCopyInstr); 1215 if (!SpillCopy || !ReloadCopy) 1216 return false; 1217 return SpillCopy->Source->getReg() == ReloadCopy->Destination->getReg() && 1218 SpillCopy->Destination->getReg() == ReloadCopy->Source->getReg(); 1219 }; 1220 1221 auto IsChainedCopy = [&, this](const MachineInstr &Prev, 1222 const MachineInstr &Current) { 1223 if (!IsFoldableCopy(Prev) || !IsFoldableCopy(Current)) 1224 return false; 1225 std::optional<DestSourcePair> PrevCopy = 1226 isCopyInstr(Prev, *TII, UseCopyInstr); 1227 std::optional<DestSourcePair> CurrentCopy = 1228 isCopyInstr(Current, *TII, UseCopyInstr); 1229 if (!PrevCopy || !CurrentCopy) 1230 return false; 1231 return PrevCopy->Source->getReg() == CurrentCopy->Destination->getReg(); 1232 }; 1233 1234 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) { 1235 std::optional<DestSourcePair> CopyOperands = 1236 isCopyInstr(MI, *TII, UseCopyInstr); 1237 1238 // Update track information via non-copy instruction. 1239 SmallSet<Register, 8> RegsToClobber; 1240 if (!CopyOperands) { 1241 for (const MachineOperand &MO : MI.operands()) { 1242 if (!MO.isReg()) 1243 continue; 1244 Register Reg = MO.getReg(); 1245 if (!Reg) 1246 continue; 1247 MachineInstr *LastUseCopy = 1248 Tracker.findLastSeenUseInCopy(Reg.asMCReg(), *TRI); 1249 if (LastUseCopy) { 1250 LLVM_DEBUG(dbgs() << "MCP: Copy source of\n"); 1251 LLVM_DEBUG(LastUseCopy->dump()); 1252 LLVM_DEBUG(dbgs() << "might be invalidated by\n"); 1253 LLVM_DEBUG(MI.dump()); 1254 CopySourceInvalid.insert(LastUseCopy); 1255 } 1256 // Must be noted Tracker.clobberRegister(Reg, ...) removes tracking of 1257 // Reg, i.e, COPY that defines Reg is removed from the mapping as well 1258 // as marking COPYs that uses Reg unavailable. 1259 // We don't invoke CopyTracker::clobberRegister(Reg, ...) if Reg is not 1260 // defined by a previous COPY, since we don't want to make COPYs uses 1261 // Reg unavailable. 1262 if (Tracker.findLastSeenDefInCopy(MI, Reg.asMCReg(), *TRI, *TII, 1263 UseCopyInstr)) 1264 // Thus we can keep the property#1. 1265 RegsToClobber.insert(Reg); 1266 } 1267 for (Register Reg : RegsToClobber) { 1268 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr); 1269 LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Reg, TRI) 1270 << "\n"); 1271 } 1272 continue; 1273 } 1274 1275 Register Src = CopyOperands->Source->getReg(); 1276 Register Def = CopyOperands->Destination->getReg(); 1277 // Check if we can find a pair spill-reload copy. 1278 LLVM_DEBUG(dbgs() << "MCP: Searching paired spill for reload: "); 1279 LLVM_DEBUG(MI.dump()); 1280 MachineInstr *MaybeSpill = 1281 Tracker.findLastSeenDefInCopy(MI, Src.asMCReg(), *TRI, *TII, UseCopyInstr); 1282 bool MaybeSpillIsChained = ChainLeader.count(MaybeSpill); 1283 if (!MaybeSpillIsChained && MaybeSpill && 1284 IsSpillReloadPair(*MaybeSpill, MI)) { 1285 // Check if we already have an existing chain. Now we have a 1286 // spill-reload pair. 1287 // L2: r2 = COPY r3 1288 // L5: r3 = COPY r2 1289 // Looking for a valid COPY before L5 which uses r3. 1290 // This can be serverial cases. 1291 // Case #1: 1292 // No COPY is found, which can be r3 is def-use between (L2, L5), we 1293 // create a new chain for L2 and L5. 1294 // Case #2: 1295 // L2: r2 = COPY r3 1296 // L5: r3 = COPY r2 1297 // Such COPY is found and is L2, we create a new chain for L2 and L5. 1298 // Case #3: 1299 // L2: r2 = COPY r3 1300 // L3: r1 = COPY r3 1301 // L5: r3 = COPY r2 1302 // we create a new chain for L2 and L5. 1303 // Case #4: 1304 // L2: r2 = COPY r3 1305 // L3: r1 = COPY r3 1306 // L4: r3 = COPY r1 1307 // L5: r3 = COPY r2 1308 // Such COPY won't be found since L4 defines r3. we create a new chain 1309 // for L2 and L5. 1310 // Case #5: 1311 // L2: r2 = COPY r3 1312 // L3: r3 = COPY r1 1313 // L4: r1 = COPY r3 1314 // L5: r3 = COPY r2 1315 // COPY is found and is L4 which belongs to an existing chain, we add 1316 // L2 and L5 to this chain. 1317 LLVM_DEBUG(dbgs() << "MCP: Found spill: "); 1318 LLVM_DEBUG(MaybeSpill->dump()); 1319 MachineInstr *MaybePrevReload = 1320 Tracker.findLastSeenUseInCopy(Def.asMCReg(), *TRI); 1321 auto Leader = ChainLeader.find(MaybePrevReload); 1322 MachineInstr *L = nullptr; 1323 if (Leader == ChainLeader.end() || 1324 (MaybePrevReload && !IsChainedCopy(*MaybePrevReload, MI))) { 1325 L = &MI; 1326 assert(!SpillChain.count(L) && 1327 "SpillChain should not have contained newly found chain"); 1328 } else { 1329 assert(MaybePrevReload && 1330 "Found a valid leader through nullptr should not happend"); 1331 L = Leader->second; 1332 assert(SpillChain[L].size() > 0 && 1333 "Existing chain's length should be larger than zero"); 1334 } 1335 assert(!ChainLeader.count(&MI) && !ChainLeader.count(MaybeSpill) && 1336 "Newly found paired spill-reload should not belong to any chain " 1337 "at this point"); 1338 ChainLeader.insert({MaybeSpill, L}); 1339 ChainLeader.insert({&MI, L}); 1340 SpillChain[L].push_back(MaybeSpill); 1341 ReloadChain[L].push_back(&MI); 1342 LLVM_DEBUG(dbgs() << "MCP: Chain " << L << " now is:\n"); 1343 LLVM_DEBUG(printSpillReloadChain(SpillChain, ReloadChain, L)); 1344 } else if (MaybeSpill && !MaybeSpillIsChained) { 1345 // MaybeSpill is unable to pair with MI. That's to say adding MI makes 1346 // the chain invalid. 1347 // The COPY defines Src is no longer considered as a candidate of a 1348 // valid chain. Since we expect the Def of a spill copy isn't used by 1349 // any COPY instruction until a reload copy. For example: 1350 // L1: r1 = COPY r2 1351 // L2: r3 = COPY r1 1352 // If we later have 1353 // L1: r1 = COPY r2 1354 // L2: r3 = COPY r1 1355 // L3: r2 = COPY r1 1356 // L1 and L3 can't be a valid spill-reload pair. 1357 // Thus we keep the property#1. 1358 LLVM_DEBUG(dbgs() << "MCP: Not paired spill-reload:\n"); 1359 LLVM_DEBUG(MaybeSpill->dump()); 1360 LLVM_DEBUG(MI.dump()); 1361 Tracker.clobberRegister(Src.asMCReg(), *TRI, *TII, UseCopyInstr); 1362 LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Src, TRI) 1363 << "\n"); 1364 } 1365 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr); 1366 } 1367 1368 for (auto I = SpillChain.begin(), E = SpillChain.end(); I != E; ++I) { 1369 auto &SC = I->second; 1370 assert(ReloadChain.count(I->first) && 1371 "Reload chain of the same leader should exist"); 1372 auto &RC = ReloadChain[I->first]; 1373 TryFoldSpillageCopies(SC, RC); 1374 } 1375 1376 MaybeDeadCopies.clear(); 1377 CopyDbgUsers.clear(); 1378 Tracker.clear(); 1379 } 1380 1381 bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) { 1382 if (skipFunction(MF.getFunction())) 1383 return false; 1384 1385 bool isSpillageCopyElimEnabled = false; 1386 switch (EnableSpillageCopyElimination) { 1387 case cl::BOU_UNSET: 1388 isSpillageCopyElimEnabled = 1389 MF.getSubtarget().enableSpillageCopyElimination(); 1390 break; 1391 case cl::BOU_TRUE: 1392 isSpillageCopyElimEnabled = true; 1393 break; 1394 case cl::BOU_FALSE: 1395 isSpillageCopyElimEnabled = false; 1396 break; 1397 } 1398 1399 Changed = false; 1400 1401 TRI = MF.getSubtarget().getRegisterInfo(); 1402 TII = MF.getSubtarget().getInstrInfo(); 1403 MRI = &MF.getRegInfo(); 1404 1405 for (MachineBasicBlock &MBB : MF) { 1406 if (isSpillageCopyElimEnabled) 1407 EliminateSpillageCopies(MBB); 1408 BackwardCopyPropagateBlock(MBB); 1409 ForwardCopyPropagateBlock(MBB); 1410 } 1411 1412 return Changed; 1413 } 1414 1415 MachineFunctionPass * 1416 llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) { 1417 return new MachineCopyPropagation(UseCopyInstr); 1418 } 1419