1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==// 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 file implements the generic RegisterCoalescer interface which 11 // is used as the common interface used by all clients and 12 // implementations of register coalescing. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "RegisterCoalescer.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 22 #include "llvm/CodeGen/LiveRangeEdit.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineInstr.h" 25 #include "llvm/CodeGen/MachineLoopInfo.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/CodeGen/Passes.h" 28 #include "llvm/CodeGen/RegisterClassInfo.h" 29 #include "llvm/CodeGen/VirtRegMap.h" 30 #include "llvm/IR/Value.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetInstrInfo.h" 37 #include "llvm/Target/TargetMachine.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 #include <cmath> 42 using namespace llvm; 43 44 #define DEBUG_TYPE "regalloc" 45 46 STATISTIC(numJoins , "Number of interval joins performed"); 47 STATISTIC(numCrossRCs , "Number of cross class joins performed"); 48 STATISTIC(numCommutes , "Number of instruction commuting performed"); 49 STATISTIC(numExtends , "Number of copies extended"); 50 STATISTIC(NumReMats , "Number of instructions re-materialized"); 51 STATISTIC(NumInflated , "Number of register classes inflated"); 52 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested"); 53 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved"); 54 55 static cl::opt<bool> 56 EnableJoining("join-liveintervals", 57 cl::desc("Coalesce copies (default=true)"), 58 cl::init(true)); 59 60 static cl::opt<bool> UseTerminalRule("terminal-rule", 61 cl::desc("Apply the terminal rule"), 62 cl::init(false), cl::Hidden); 63 64 /// Temporary flag to test critical edge unsplitting. 65 static cl::opt<bool> 66 EnableJoinSplits("join-splitedges", 67 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden); 68 69 /// Temporary flag to test global copy optimization. 70 static cl::opt<cl::boolOrDefault> 71 EnableGlobalCopies("join-globalcopies", 72 cl::desc("Coalesce copies that span blocks (default=subtarget)"), 73 cl::init(cl::BOU_UNSET), cl::Hidden); 74 75 static cl::opt<bool> 76 VerifyCoalescing("verify-coalescing", 77 cl::desc("Verify machine instrs before and after register coalescing"), 78 cl::Hidden); 79 80 namespace { 81 class RegisterCoalescer : public MachineFunctionPass, 82 private LiveRangeEdit::Delegate { 83 MachineFunction* MF; 84 MachineRegisterInfo* MRI; 85 const TargetMachine* TM; 86 const TargetRegisterInfo* TRI; 87 const TargetInstrInfo* TII; 88 LiveIntervals *LIS; 89 const MachineLoopInfo* Loops; 90 AliasAnalysis *AA; 91 RegisterClassInfo RegClassInfo; 92 93 /// A LaneMask to remember on which subregister live ranges we need to call 94 /// shrinkToUses() later. 95 LaneBitmask ShrinkMask; 96 97 /// True if the main range of the currently coalesced intervals should be 98 /// checked for smaller live intervals. 99 bool ShrinkMainRange; 100 101 /// \brief True if the coalescer should aggressively coalesce global copies 102 /// in favor of keeping local copies. 103 bool JoinGlobalCopies; 104 105 /// \brief True if the coalescer should aggressively coalesce fall-thru 106 /// blocks exclusively containing copies. 107 bool JoinSplitEdges; 108 109 /// Copy instructions yet to be coalesced. 110 SmallVector<MachineInstr*, 8> WorkList; 111 SmallVector<MachineInstr*, 8> LocalWorkList; 112 113 /// Set of instruction pointers that have been erased, and 114 /// that may be present in WorkList. 115 SmallPtrSet<MachineInstr*, 8> ErasedInstrs; 116 117 /// Dead instructions that are about to be deleted. 118 SmallVector<MachineInstr*, 8> DeadDefs; 119 120 /// Virtual registers to be considered for register class inflation. 121 SmallVector<unsigned, 8> InflateRegs; 122 123 /// Recursively eliminate dead defs in DeadDefs. 124 void eliminateDeadDefs(); 125 126 /// LiveRangeEdit callback for eliminateDeadDefs(). 127 void LRE_WillEraseInstruction(MachineInstr *MI) override; 128 129 /// Coalesce the LocalWorkList. 130 void coalesceLocals(); 131 132 /// Join compatible live intervals 133 void joinAllIntervals(); 134 135 /// Coalesce copies in the specified MBB, putting 136 /// copies that cannot yet be coalesced into WorkList. 137 void copyCoalesceInMBB(MachineBasicBlock *MBB); 138 139 /// Tries to coalesce all copies in CurrList. Returns true if any progress 140 /// was made. 141 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList); 142 143 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the 144 /// src/dst of the copy instruction CopyMI. This returns true if the copy 145 /// was successfully coalesced away. If it is not currently possible to 146 /// coalesce this interval, but it may be possible if other things get 147 /// coalesced, then it returns true by reference in 'Again'. 148 bool joinCopy(MachineInstr *TheCopy, bool &Again); 149 150 /// Attempt to join these two intervals. On failure, this 151 /// returns false. The output "SrcInt" will not have been modified, so we 152 /// can use this information below to update aliases. 153 bool joinIntervals(CoalescerPair &CP); 154 155 /// Attempt joining two virtual registers. Return true on success. 156 bool joinVirtRegs(CoalescerPair &CP); 157 158 /// Attempt joining with a reserved physreg. 159 bool joinReservedPhysReg(CoalescerPair &CP); 160 161 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI. 162 /// Subranges in @p LI which only partially interfere with the desired 163 /// LaneMask are split as necessary. @p LaneMask are the lanes that 164 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange 165 /// lanemasks already adjusted to the coalesced register. 166 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge, 167 LaneBitmask LaneMask, CoalescerPair &CP); 168 169 /// Join the liveranges of two subregisters. Joins @p RRange into 170 /// @p LRange, @p RRange may be invalid afterwards. 171 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange, 172 LaneBitmask LaneMask, const CoalescerPair &CP); 173 174 /// We found a non-trivially-coalescable copy. If the source value number is 175 /// defined by a copy from the destination reg see if we can merge these two 176 /// destination reg valno# into a single value number, eliminating a copy. 177 /// This returns true if an interval was modified. 178 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI); 179 180 /// Return true if there are definitions of IntB 181 /// other than BValNo val# that can reach uses of AValno val# of IntA. 182 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB, 183 VNInfo *AValNo, VNInfo *BValNo); 184 185 /// We found a non-trivially-coalescable copy. 186 /// If the source value number is defined by a commutable instruction and 187 /// its other operand is coalesced to the copy dest register, see if we 188 /// can transform the copy into a noop by commuting the definition. 189 /// This returns true if an interval was modified. 190 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI); 191 192 /// If the source of a copy is defined by a 193 /// trivial computation, replace the copy by rematerialize the definition. 194 bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI, 195 bool &IsDefCopy); 196 197 /// Return true if a copy involving a physreg should be joined. 198 bool canJoinPhys(const CoalescerPair &CP); 199 200 /// Replace all defs and uses of SrcReg to DstReg and update the subregister 201 /// number if it is not zero. If DstReg is a physical register and the 202 /// existing subregister number of the def / use being updated is not zero, 203 /// make sure to set it to the correct physical subregister. 204 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx); 205 206 /// If the given machine operand reads only undefined lanes add an undef 207 /// flag. 208 /// This can happen when undef uses were previously concealed by a copy 209 /// which we coalesced. Example: 210 /// %vreg0:sub0<def,read-undef> = ... 211 /// %vreg1 = COPY %vreg0 <-- Coalescing COPY reveals undef 212 /// = use %vreg1:sub1 <-- hidden undef use 213 void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx, 214 MachineOperand &MO, unsigned SubRegIdx); 215 216 /// Handle copies of undef values. 217 /// Returns true if @p CopyMI was a copy of an undef value and eliminated. 218 bool eliminateUndefCopy(MachineInstr *CopyMI); 219 220 /// Check whether or not we should apply the terminal rule on the 221 /// destination (Dst) of \p Copy. 222 /// When the terminal rule applies, Copy is not profitable to 223 /// coalesce. 224 /// Dst is terminal if it has exactly one affinity (Dst, Src) and 225 /// at least one interference (Dst, Dst2). If Dst is terminal, the 226 /// terminal rule consists in checking that at least one of 227 /// interfering node, say Dst2, has an affinity of equal or greater 228 /// weight with Src. 229 /// In that case, Dst2 and Dst will not be able to be both coalesced 230 /// with Src. Since Dst2 exposes more coalescing opportunities than 231 /// Dst, we can drop \p Copy. 232 bool applyTerminalRule(const MachineInstr &Copy) const; 233 234 /// Wrapper method for \see LiveIntervals::shrinkToUses. 235 /// This method does the proper fixing of the live-ranges when the afore 236 /// mentioned method returns true. 237 void shrinkToUses(LiveInterval *LI, 238 SmallVectorImpl<MachineInstr * > *Dead = nullptr) { 239 if (LIS->shrinkToUses(LI, Dead)) { 240 /// Check whether or not \p LI is composed by multiple connected 241 /// components and if that is the case, fix that. 242 SmallVector<LiveInterval*, 8> SplitLIs; 243 LIS->splitSeparateComponents(*LI, SplitLIs); 244 } 245 } 246 247 public: 248 static char ID; ///< Class identification, replacement for typeinfo 249 RegisterCoalescer() : MachineFunctionPass(ID) { 250 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); 251 } 252 253 void getAnalysisUsage(AnalysisUsage &AU) const override; 254 255 void releaseMemory() override; 256 257 /// This is the pass entry point. 258 bool runOnMachineFunction(MachineFunction&) override; 259 260 /// Implement the dump method. 261 void print(raw_ostream &O, const Module* = nullptr) const override; 262 }; 263 } // end anonymous namespace 264 265 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID; 266 267 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing", 268 "Simple Register Coalescing", false, false) 269 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 270 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 271 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 272 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 273 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing", 274 "Simple Register Coalescing", false, false) 275 276 char RegisterCoalescer::ID = 0; 277 278 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI, 279 unsigned &Src, unsigned &Dst, 280 unsigned &SrcSub, unsigned &DstSub) { 281 if (MI->isCopy()) { 282 Dst = MI->getOperand(0).getReg(); 283 DstSub = MI->getOperand(0).getSubReg(); 284 Src = MI->getOperand(1).getReg(); 285 SrcSub = MI->getOperand(1).getSubReg(); 286 } else if (MI->isSubregToReg()) { 287 Dst = MI->getOperand(0).getReg(); 288 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(), 289 MI->getOperand(3).getImm()); 290 Src = MI->getOperand(2).getReg(); 291 SrcSub = MI->getOperand(2).getSubReg(); 292 } else 293 return false; 294 return true; 295 } 296 297 /// Return true if this block should be vacated by the coalescer to eliminate 298 /// branches. The important cases to handle in the coalescer are critical edges 299 /// split during phi elimination which contain only copies. Simple blocks that 300 /// contain non-branches should also be vacated, but this can be handled by an 301 /// earlier pass similar to early if-conversion. 302 static bool isSplitEdge(const MachineBasicBlock *MBB) { 303 if (MBB->pred_size() != 1 || MBB->succ_size() != 1) 304 return false; 305 306 for (const auto &MI : *MBB) { 307 if (!MI.isCopyLike() && !MI.isUnconditionalBranch()) 308 return false; 309 } 310 return true; 311 } 312 313 bool CoalescerPair::setRegisters(const MachineInstr *MI) { 314 SrcReg = DstReg = 0; 315 SrcIdx = DstIdx = 0; 316 NewRC = nullptr; 317 Flipped = CrossClass = false; 318 319 unsigned Src, Dst, SrcSub, DstSub; 320 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) 321 return false; 322 Partial = SrcSub || DstSub; 323 324 // If one register is a physreg, it must be Dst. 325 if (TargetRegisterInfo::isPhysicalRegister(Src)) { 326 if (TargetRegisterInfo::isPhysicalRegister(Dst)) 327 return false; 328 std::swap(Src, Dst); 329 std::swap(SrcSub, DstSub); 330 Flipped = true; 331 } 332 333 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); 334 335 if (TargetRegisterInfo::isPhysicalRegister(Dst)) { 336 // Eliminate DstSub on a physreg. 337 if (DstSub) { 338 Dst = TRI.getSubReg(Dst, DstSub); 339 if (!Dst) return false; 340 DstSub = 0; 341 } 342 343 // Eliminate SrcSub by picking a corresponding Dst superregister. 344 if (SrcSub) { 345 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src)); 346 if (!Dst) return false; 347 } else if (!MRI.getRegClass(Src)->contains(Dst)) { 348 return false; 349 } 350 } else { 351 // Both registers are virtual. 352 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src); 353 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst); 354 355 // Both registers have subreg indices. 356 if (SrcSub && DstSub) { 357 // Copies between different sub-registers are never coalescable. 358 if (Src == Dst && SrcSub != DstSub) 359 return false; 360 361 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub, 362 SrcIdx, DstIdx); 363 if (!NewRC) 364 return false; 365 } else if (DstSub) { 366 // SrcReg will be merged with a sub-register of DstReg. 367 SrcIdx = DstSub; 368 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub); 369 } else if (SrcSub) { 370 // DstReg will be merged with a sub-register of SrcReg. 371 DstIdx = SrcSub; 372 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub); 373 } else { 374 // This is a straight copy without sub-registers. 375 NewRC = TRI.getCommonSubClass(DstRC, SrcRC); 376 } 377 378 // The combined constraint may be impossible to satisfy. 379 if (!NewRC) 380 return false; 381 382 // Prefer SrcReg to be a sub-register of DstReg. 383 // FIXME: Coalescer should support subregs symmetrically. 384 if (DstIdx && !SrcIdx) { 385 std::swap(Src, Dst); 386 std::swap(SrcIdx, DstIdx); 387 Flipped = !Flipped; 388 } 389 390 CrossClass = NewRC != DstRC || NewRC != SrcRC; 391 } 392 // Check our invariants 393 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual"); 394 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) && 395 "Cannot have a physical SubIdx"); 396 SrcReg = Src; 397 DstReg = Dst; 398 return true; 399 } 400 401 bool CoalescerPair::flip() { 402 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) 403 return false; 404 std::swap(SrcReg, DstReg); 405 std::swap(SrcIdx, DstIdx); 406 Flipped = !Flipped; 407 return true; 408 } 409 410 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const { 411 if (!MI) 412 return false; 413 unsigned Src, Dst, SrcSub, DstSub; 414 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) 415 return false; 416 417 // Find the virtual register that is SrcReg. 418 if (Dst == SrcReg) { 419 std::swap(Src, Dst); 420 std::swap(SrcSub, DstSub); 421 } else if (Src != SrcReg) { 422 return false; 423 } 424 425 // Now check that Dst matches DstReg. 426 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { 427 if (!TargetRegisterInfo::isPhysicalRegister(Dst)) 428 return false; 429 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state."); 430 // DstSub could be set for a physreg from INSERT_SUBREG. 431 if (DstSub) 432 Dst = TRI.getSubReg(Dst, DstSub); 433 // Full copy of Src. 434 if (!SrcSub) 435 return DstReg == Dst; 436 // This is a partial register copy. Check that the parts match. 437 return TRI.getSubReg(DstReg, SrcSub) == Dst; 438 } else { 439 // DstReg is virtual. 440 if (DstReg != Dst) 441 return false; 442 // Registers match, do the subregisters line up? 443 return TRI.composeSubRegIndices(SrcIdx, SrcSub) == 444 TRI.composeSubRegIndices(DstIdx, DstSub); 445 } 446 } 447 448 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const { 449 AU.setPreservesCFG(); 450 AU.addRequired<AAResultsWrapperPass>(); 451 AU.addRequired<LiveIntervals>(); 452 AU.addPreserved<LiveIntervals>(); 453 AU.addPreserved<SlotIndexes>(); 454 AU.addRequired<MachineLoopInfo>(); 455 AU.addPreserved<MachineLoopInfo>(); 456 AU.addPreservedID(MachineDominatorsID); 457 MachineFunctionPass::getAnalysisUsage(AU); 458 } 459 460 void RegisterCoalescer::eliminateDeadDefs() { 461 SmallVector<unsigned, 8> NewRegs; 462 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS, 463 nullptr, this).eliminateDeadDefs(DeadDefs); 464 } 465 466 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) { 467 // MI may be in WorkList. Make sure we don't visit it. 468 ErasedInstrs.insert(MI); 469 } 470 471 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP, 472 MachineInstr *CopyMI) { 473 assert(!CP.isPartial() && "This doesn't work for partial copies."); 474 assert(!CP.isPhys() && "This doesn't work for physreg copies."); 475 476 LiveInterval &IntA = 477 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 478 LiveInterval &IntB = 479 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 480 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); 481 482 // We have a non-trivially-coalescable copy with IntA being the source and 483 // IntB being the dest, thus this defines a value number in IntB. If the 484 // source value number (in IntA) is defined by a copy from B, see if we can 485 // merge these two pieces of B into a single value number, eliminating a copy. 486 // For example: 487 // 488 // A3 = B0 489 // ... 490 // B1 = A3 <- this copy 491 // 492 // In this case, B0 can be extended to where the B1 copy lives, allowing the 493 // B1 value number to be replaced with B0 (which simplifies the B 494 // liveinterval). 495 496 // BValNo is a value number in B that is defined by a copy from A. 'B1' in 497 // the example above. 498 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx); 499 if (BS == IntB.end()) return false; 500 VNInfo *BValNo = BS->valno; 501 502 // Get the location that B is defined at. Two options: either this value has 503 // an unknown definition point or it is defined at CopyIdx. If unknown, we 504 // can't process it. 505 if (BValNo->def != CopyIdx) return false; 506 507 // AValNo is the value number in A that defines the copy, A3 in the example. 508 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true); 509 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx); 510 // The live segment might not exist after fun with physreg coalescing. 511 if (AS == IntA.end()) return false; 512 VNInfo *AValNo = AS->valno; 513 514 // If AValNo is defined as a copy from IntB, we can potentially process this. 515 // Get the instruction that defines this value number. 516 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def); 517 // Don't allow any partial copies, even if isCoalescable() allows them. 518 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy()) 519 return false; 520 521 // Get the Segment in IntB that this value number starts with. 522 LiveInterval::iterator ValS = 523 IntB.FindSegmentContaining(AValNo->def.getPrevSlot()); 524 if (ValS == IntB.end()) 525 return false; 526 527 // Make sure that the end of the live segment is inside the same block as 528 // CopyMI. 529 MachineInstr *ValSEndInst = 530 LIS->getInstructionFromIndex(ValS->end.getPrevSlot()); 531 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent()) 532 return false; 533 534 // Okay, we now know that ValS ends in the same block that the CopyMI 535 // live-range starts. If there are no intervening live segments between them 536 // in IntB, we can merge them. 537 if (ValS+1 != BS) return false; 538 539 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI)); 540 541 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start; 542 // We are about to delete CopyMI, so need to remove it as the 'instruction 543 // that defines this value #'. Update the valnum with the new defining 544 // instruction #. 545 BValNo->def = FillerStart; 546 547 // Okay, we can merge them. We need to insert a new liverange: 548 // [ValS.end, BS.begin) of either value number, then we merge the 549 // two value numbers. 550 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo)); 551 552 // Okay, merge "B1" into the same value number as "B0". 553 if (BValNo != ValS->valno) 554 IntB.MergeValueNumberInto(BValNo, ValS->valno); 555 556 // Do the same for the subregister segments. 557 for (LiveInterval::SubRange &S : IntB.subranges()) { 558 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx); 559 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo)); 560 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot()); 561 if (SubBValNo != SubValSNo) 562 S.MergeValueNumberInto(SubBValNo, SubValSNo); 563 } 564 565 DEBUG(dbgs() << " result = " << IntB << '\n'); 566 567 // If the source instruction was killing the source register before the 568 // merge, unset the isKill marker given the live range has been extended. 569 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true); 570 if (UIdx != -1) { 571 ValSEndInst->getOperand(UIdx).setIsKill(false); 572 } 573 574 // Rewrite the copy. If the copy instruction was killing the destination 575 // register before the merge, find the last use and trim the live range. That 576 // will also add the isKill marker. 577 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI); 578 if (AS->end == CopyIdx) 579 shrinkToUses(&IntA); 580 581 ++numExtends; 582 return true; 583 } 584 585 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA, 586 LiveInterval &IntB, 587 VNInfo *AValNo, 588 VNInfo *BValNo) { 589 // If AValNo has PHI kills, conservatively assume that IntB defs can reach 590 // the PHI values. 591 if (LIS->hasPHIKill(IntA, AValNo)) 592 return true; 593 594 for (LiveRange::Segment &ASeg : IntA.segments) { 595 if (ASeg.valno != AValNo) continue; 596 LiveInterval::iterator BI = 597 std::upper_bound(IntB.begin(), IntB.end(), ASeg.start); 598 if (BI != IntB.begin()) 599 --BI; 600 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) { 601 if (BI->valno == BValNo) 602 continue; 603 if (BI->start <= ASeg.start && BI->end > ASeg.start) 604 return true; 605 if (BI->start > ASeg.start && BI->start < ASeg.end) 606 return true; 607 } 608 } 609 return false; 610 } 611 612 /// Copy segements with value number @p SrcValNo from liverange @p Src to live 613 /// range @Dst and use value number @p DstValNo there. 614 static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, 615 const LiveRange &Src, const VNInfo *SrcValNo) 616 { 617 for (const LiveRange::Segment &S : Src.segments) { 618 if (S.valno != SrcValNo) 619 continue; 620 Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo)); 621 } 622 } 623 624 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP, 625 MachineInstr *CopyMI) { 626 assert(!CP.isPhys()); 627 628 LiveInterval &IntA = 629 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 630 LiveInterval &IntB = 631 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 632 633 // We found a non-trivially-coalescable copy with IntA being the source and 634 // IntB being the dest, thus this defines a value number in IntB. If the 635 // source value number (in IntA) is defined by a commutable instruction and 636 // its other operand is coalesced to the copy dest register, see if we can 637 // transform the copy into a noop by commuting the definition. For example, 638 // 639 // A3 = op A2 B0<kill> 640 // ... 641 // B1 = A3 <- this copy 642 // ... 643 // = op A3 <- more uses 644 // 645 // ==> 646 // 647 // B2 = op B0 A2<kill> 648 // ... 649 // B1 = B2 <- now an identity copy 650 // ... 651 // = op B2 <- more uses 652 653 // BValNo is a value number in B that is defined by a copy from A. 'B1' in 654 // the example above. 655 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); 656 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx); 657 assert(BValNo != nullptr && BValNo->def == CopyIdx); 658 659 // AValNo is the value number in A that defines the copy, A3 in the example. 660 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true)); 661 assert(AValNo && !AValNo->isUnused() && "COPY source not live"); 662 if (AValNo->isPHIDef()) 663 return false; 664 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def); 665 if (!DefMI) 666 return false; 667 if (!DefMI->isCommutable()) 668 return false; 669 // If DefMI is a two-address instruction then commuting it will change the 670 // destination register. 671 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg); 672 assert(DefIdx != -1); 673 unsigned UseOpIdx; 674 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx)) 675 return false; 676 677 // FIXME: The code below tries to commute 'UseOpIdx' operand with some other 678 // commutable operand which is expressed by 'CommuteAnyOperandIndex'value 679 // passed to the method. That _other_ operand is chosen by 680 // the findCommutedOpIndices() method. 681 // 682 // That is obviously an area for improvement in case of instructions having 683 // more than 2 operands. For example, if some instruction has 3 commutable 684 // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3, 685 // op#2<->op#3) of commute transformation should be considered/tried here. 686 unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex; 687 if (!TII->findCommutedOpIndices(DefMI, UseOpIdx, NewDstIdx)) 688 return false; 689 690 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx); 691 unsigned NewReg = NewDstMO.getReg(); 692 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill()) 693 return false; 694 695 // Make sure there are no other definitions of IntB that would reach the 696 // uses which the new definition can reach. 697 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo)) 698 return false; 699 700 // If some of the uses of IntA.reg is already coalesced away, return false. 701 // It's not possible to determine whether it's safe to perform the coalescing. 702 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) { 703 MachineInstr *UseMI = MO.getParent(); 704 unsigned OpNo = &MO - &UseMI->getOperand(0); 705 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI); 706 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx); 707 if (US == IntA.end() || US->valno != AValNo) 708 continue; 709 // If this use is tied to a def, we can't rewrite the register. 710 if (UseMI->isRegTiedToDefOperand(OpNo)) 711 return false; 712 } 713 714 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t' 715 << *DefMI); 716 717 // At this point we have decided that it is legal to do this 718 // transformation. Start by commuting the instruction. 719 MachineBasicBlock *MBB = DefMI->getParent(); 720 MachineInstr *NewMI = 721 TII->commuteInstruction(DefMI, false, UseOpIdx, NewDstIdx); 722 if (!NewMI) 723 return false; 724 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) && 725 TargetRegisterInfo::isVirtualRegister(IntB.reg) && 726 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg))) 727 return false; 728 if (NewMI != DefMI) { 729 LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI); 730 MachineBasicBlock::iterator Pos = DefMI; 731 MBB->insert(Pos, NewMI); 732 MBB->erase(DefMI); 733 } 734 735 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g. 736 // A = or A, B 737 // ... 738 // B = A 739 // ... 740 // C = A<kill> 741 // ... 742 // = B 743 744 // Update uses of IntA of the specific Val# with IntB. 745 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg), 746 UE = MRI->use_end(); 747 UI != UE; /* ++UI is below because of possible MI removal */) { 748 MachineOperand &UseMO = *UI; 749 ++UI; 750 if (UseMO.isUndef()) 751 continue; 752 MachineInstr *UseMI = UseMO.getParent(); 753 if (UseMI->isDebugValue()) { 754 // FIXME These don't have an instruction index. Not clear we have enough 755 // info to decide whether to do this replacement or not. For now do it. 756 UseMO.setReg(NewReg); 757 continue; 758 } 759 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true); 760 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx); 761 assert(US != IntA.end() && "Use must be live"); 762 if (US->valno != AValNo) 763 continue; 764 // Kill flags are no longer accurate. They are recomputed after RA. 765 UseMO.setIsKill(false); 766 if (TargetRegisterInfo::isPhysicalRegister(NewReg)) 767 UseMO.substPhysReg(NewReg, *TRI); 768 else 769 UseMO.setReg(NewReg); 770 if (UseMI == CopyMI) 771 continue; 772 if (!UseMI->isCopy()) 773 continue; 774 if (UseMI->getOperand(0).getReg() != IntB.reg || 775 UseMI->getOperand(0).getSubReg()) 776 continue; 777 778 // This copy will become a noop. If it's defining a new val#, merge it into 779 // BValNo. 780 SlotIndex DefIdx = UseIdx.getRegSlot(); 781 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx); 782 if (!DVNI) 783 continue; 784 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI); 785 assert(DVNI->def == DefIdx); 786 BValNo = IntB.MergeValueNumberInto(DVNI, BValNo); 787 for (LiveInterval::SubRange &S : IntB.subranges()) { 788 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx); 789 if (!SubDVNI) 790 continue; 791 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx); 792 assert(SubBValNo->def == CopyIdx); 793 S.MergeValueNumberInto(SubDVNI, SubBValNo); 794 } 795 796 ErasedInstrs.insert(UseMI); 797 LIS->RemoveMachineInstrFromMaps(*UseMI); 798 UseMI->eraseFromParent(); 799 } 800 801 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition 802 // is updated. 803 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 804 if (IntB.hasSubRanges()) { 805 if (!IntA.hasSubRanges()) { 806 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg); 807 IntA.createSubRangeFrom(Allocator, Mask, IntA); 808 } 809 SlotIndex AIdx = CopyIdx.getRegSlot(true); 810 for (LiveInterval::SubRange &SA : IntA.subranges()) { 811 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx); 812 assert(ASubValNo != nullptr); 813 814 LaneBitmask AMask = SA.LaneMask; 815 for (LiveInterval::SubRange &SB : IntB.subranges()) { 816 LaneBitmask BMask = SB.LaneMask; 817 LaneBitmask Common = BMask & AMask; 818 if (Common == 0) 819 continue; 820 821 DEBUG( dbgs() << "\t\tCopy_Merge " << PrintLaneMask(BMask) 822 << " into " << PrintLaneMask(Common) << '\n'); 823 LaneBitmask BRest = BMask & ~AMask; 824 LiveInterval::SubRange *CommonRange; 825 if (BRest != 0) { 826 SB.LaneMask = BRest; 827 DEBUG(dbgs() << "\t\tReduce Lane to " << PrintLaneMask(BRest) 828 << '\n'); 829 // Duplicate SubRange for newly merged common stuff. 830 CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB); 831 } else { 832 // We van reuse the L SubRange. 833 SB.LaneMask = Common; 834 CommonRange = &SB; 835 } 836 LiveRange RangeCopy(SB, Allocator); 837 838 VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx); 839 assert(BSubValNo->def == CopyIdx); 840 BSubValNo->def = ASubValNo->def; 841 addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo); 842 AMask &= ~BMask; 843 } 844 if (AMask != 0) { 845 DEBUG(dbgs() << "\t\tNew Lane " << PrintLaneMask(AMask) << '\n'); 846 LiveRange *NewRange = IntB.createSubRange(Allocator, AMask); 847 VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator); 848 addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo); 849 } 850 } 851 } 852 853 BValNo->def = AValNo->def; 854 addSegmentsWithValNo(IntB, BValNo, IntA, AValNo); 855 DEBUG(dbgs() << "\t\textended: " << IntB << '\n'); 856 857 LIS->removeVRegDefAt(IntA, AValNo->def); 858 859 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n'); 860 ++numCommutes; 861 return true; 862 } 863 864 /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just 865 /// defining a subregister. 866 static bool definesFullReg(const MachineInstr &MI, unsigned Reg) { 867 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && 868 "This code cannot handle physreg aliasing"); 869 for (const MachineOperand &Op : MI.operands()) { 870 if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg) 871 continue; 872 // Return true if we define the full register or don't care about the value 873 // inside other subregisters. 874 if (Op.getSubReg() == 0 || Op.isUndef()) 875 return true; 876 } 877 return false; 878 } 879 880 bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP, 881 MachineInstr *CopyMI, 882 bool &IsDefCopy) { 883 IsDefCopy = false; 884 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg(); 885 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx(); 886 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg(); 887 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx(); 888 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)) 889 return false; 890 891 LiveInterval &SrcInt = LIS->getInterval(SrcReg); 892 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI); 893 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn(); 894 assert(ValNo && "CopyMI input register not live"); 895 if (ValNo->isPHIDef() || ValNo->isUnused()) 896 return false; 897 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def); 898 if (!DefMI) 899 return false; 900 if (DefMI->isCopyLike()) { 901 IsDefCopy = true; 902 return false; 903 } 904 if (!TII->isAsCheapAsAMove(DefMI)) 905 return false; 906 if (!TII->isTriviallyReMaterializable(DefMI, AA)) 907 return false; 908 if (!definesFullReg(*DefMI, SrcReg)) 909 return false; 910 bool SawStore = false; 911 if (!DefMI->isSafeToMove(AA, SawStore)) 912 return false; 913 const MCInstrDesc &MCID = DefMI->getDesc(); 914 if (MCID.getNumDefs() != 1) 915 return false; 916 // Only support subregister destinations when the def is read-undef. 917 MachineOperand &DstOperand = CopyMI->getOperand(0); 918 unsigned CopyDstReg = DstOperand.getReg(); 919 if (DstOperand.getSubReg() && !DstOperand.isUndef()) 920 return false; 921 922 // If both SrcIdx and DstIdx are set, correct rematerialization would widen 923 // the register substantially (beyond both source and dest size). This is bad 924 // for performance since it can cascade through a function, introducing many 925 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers 926 // around after a few subreg copies). 927 if (SrcIdx && DstIdx) 928 return false; 929 930 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF); 931 if (!DefMI->isImplicitDef()) { 932 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { 933 unsigned NewDstReg = DstReg; 934 935 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(), 936 DefMI->getOperand(0).getSubReg()); 937 if (NewDstIdx) 938 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx); 939 940 // Finally, make sure that the physical subregister that will be 941 // constructed later is permitted for the instruction. 942 if (!DefRC->contains(NewDstReg)) 943 return false; 944 } else { 945 // Theoretically, some stack frame reference could exist. Just make sure 946 // it hasn't actually happened. 947 assert(TargetRegisterInfo::isVirtualRegister(DstReg) && 948 "Only expect to deal with virtual or physical registers"); 949 } 950 } 951 952 DebugLoc DL = CopyMI->getDebugLoc(); 953 MachineBasicBlock *MBB = CopyMI->getParent(); 954 MachineBasicBlock::iterator MII = 955 std::next(MachineBasicBlock::iterator(CopyMI)); 956 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI); 957 MachineInstr *NewMI = std::prev(MII); 958 NewMI->setDebugLoc(DL); 959 960 // In a situation like the following: 961 // %vreg0:subreg = instr ; DefMI, subreg = DstIdx 962 // %vreg1 = copy %vreg0:subreg ; CopyMI, SrcIdx = 0 963 // instead of widening %vreg1 to the register class of %vreg0 simply do: 964 // %vreg1 = instr 965 const TargetRegisterClass *NewRC = CP.getNewRC(); 966 if (DstIdx != 0) { 967 MachineOperand &DefMO = NewMI->getOperand(0); 968 if (DefMO.getSubReg() == DstIdx) { 969 assert(SrcIdx == 0 && CP.isFlipped() 970 && "Shouldn't have SrcIdx+DstIdx at this point"); 971 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg); 972 const TargetRegisterClass *CommonRC = 973 TRI->getCommonSubClass(DefRC, DstRC); 974 if (CommonRC != nullptr) { 975 NewRC = CommonRC; 976 DstIdx = 0; 977 DefMO.setSubReg(0); 978 } 979 } 980 } 981 982 LIS->ReplaceMachineInstrInMaps(*CopyMI, *NewMI); 983 CopyMI->eraseFromParent(); 984 ErasedInstrs.insert(CopyMI); 985 986 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86). 987 // We need to remember these so we can add intervals once we insert 988 // NewMI into SlotIndexes. 989 SmallVector<unsigned, 4> NewMIImplDefs; 990 for (unsigned i = NewMI->getDesc().getNumOperands(), 991 e = NewMI->getNumOperands(); i != e; ++i) { 992 MachineOperand &MO = NewMI->getOperand(i); 993 if (MO.isReg() && MO.isDef()) { 994 assert(MO.isImplicit() && MO.isDead() && 995 TargetRegisterInfo::isPhysicalRegister(MO.getReg())); 996 NewMIImplDefs.push_back(MO.getReg()); 997 } 998 } 999 1000 if (TargetRegisterInfo::isVirtualRegister(DstReg)) { 1001 unsigned NewIdx = NewMI->getOperand(0).getSubReg(); 1002 1003 if (DefRC != nullptr) { 1004 if (NewIdx) 1005 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx); 1006 else 1007 NewRC = TRI->getCommonSubClass(NewRC, DefRC); 1008 assert(NewRC && "subreg chosen for remat incompatible with instruction"); 1009 } 1010 // Remap subranges to new lanemask and change register class. 1011 LiveInterval &DstInt = LIS->getInterval(DstReg); 1012 for (LiveInterval::SubRange &SR : DstInt.subranges()) { 1013 SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask); 1014 } 1015 MRI->setRegClass(DstReg, NewRC); 1016 1017 // Update machine operands and add flags. 1018 updateRegDefsUses(DstReg, DstReg, DstIdx); 1019 NewMI->getOperand(0).setSubReg(NewIdx); 1020 // Add dead subregister definitions if we are defining the whole register 1021 // but only part of it is live. 1022 // This could happen if the rematerialization instruction is rematerializing 1023 // more than actually is used in the register. 1024 // An example would be: 1025 // vreg1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs 1026 // ; Copying only part of the register here, but the rest is undef. 1027 // vreg2:sub_16bit<def, read-undef> = COPY vreg1:sub_16bit 1028 // ==> 1029 // ; Materialize all the constants but only using one 1030 // vreg2 = LOAD_CONSTANTS 5, 8 1031 // 1032 // at this point for the part that wasn't defined before we could have 1033 // subranges missing the definition. 1034 if (NewIdx == 0 && DstInt.hasSubRanges()) { 1035 SlotIndex CurrIdx = LIS->getInstructionIndex(*NewMI); 1036 SlotIndex DefIndex = CurrIdx.getRegSlot(NewMI->getOperand(0).isEarlyClobber()); 1037 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg); 1038 VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator(); 1039 for (LiveInterval::SubRange &SR : DstInt.subranges()) { 1040 if (!SR.liveAt(DefIndex)) 1041 SR.createDeadDef(DefIndex, Alloc); 1042 MaxMask &= ~SR.LaneMask; 1043 } 1044 if (MaxMask != 0) { 1045 LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask); 1046 SR->createDeadDef(DefIndex, Alloc); 1047 } 1048 } 1049 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) { 1050 // The New instruction may be defining a sub-register of what's actually 1051 // been asked for. If so it must implicitly define the whole thing. 1052 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) && 1053 "Only expect virtual or physical registers in remat"); 1054 NewMI->getOperand(0).setIsDead(true); 1055 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg, 1056 true /*IsDef*/, 1057 true /*IsImp*/, 1058 false /*IsKill*/)); 1059 // Record small dead def live-ranges for all the subregisters 1060 // of the destination register. 1061 // Otherwise, variables that live through may miss some 1062 // interferences, thus creating invalid allocation. 1063 // E.g., i386 code: 1064 // vreg1 = somedef ; vreg1 GR8 1065 // vreg2 = remat ; vreg2 GR32 1066 // CL = COPY vreg2.sub_8bit 1067 // = somedef vreg1 ; vreg1 GR8 1068 // => 1069 // vreg1 = somedef ; vreg1 GR8 1070 // ECX<def, dead> = remat ; CL<imp-def> 1071 // = somedef vreg1 ; vreg1 GR8 1072 // vreg1 will see the inteferences with CL but not with CH since 1073 // no live-ranges would have been created for ECX. 1074 // Fix that! 1075 SlotIndex NewMIIdx = LIS->getInstructionIndex(*NewMI); 1076 for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI); 1077 Units.isValid(); ++Units) 1078 if (LiveRange *LR = LIS->getCachedRegUnit(*Units)) 1079 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator()); 1080 } 1081 1082 if (NewMI->getOperand(0).getSubReg()) 1083 NewMI->getOperand(0).setIsUndef(); 1084 1085 // CopyMI may have implicit operands, transfer them over to the newly 1086 // rematerialized instruction. And update implicit def interval valnos. 1087 for (unsigned i = CopyMI->getDesc().getNumOperands(), 1088 e = CopyMI->getNumOperands(); i != e; ++i) { 1089 MachineOperand &MO = CopyMI->getOperand(i); 1090 if (MO.isReg()) { 1091 assert(MO.isImplicit() && "No explicit operands after implict operands."); 1092 // Discard VReg implicit defs. 1093 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) { 1094 NewMI->addOperand(MO); 1095 } 1096 } 1097 } 1098 1099 SlotIndex NewMIIdx = LIS->getInstructionIndex(*NewMI); 1100 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) { 1101 unsigned Reg = NewMIImplDefs[i]; 1102 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) 1103 if (LiveRange *LR = LIS->getCachedRegUnit(*Units)) 1104 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator()); 1105 } 1106 1107 DEBUG(dbgs() << "Remat: " << *NewMI); 1108 ++NumReMats; 1109 1110 // The source interval can become smaller because we removed a use. 1111 shrinkToUses(&SrcInt, &DeadDefs); 1112 if (!DeadDefs.empty()) { 1113 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs 1114 // to describe DstReg instead. 1115 for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) { 1116 MachineInstr *UseMI = UseMO.getParent(); 1117 if (UseMI->isDebugValue()) { 1118 UseMO.setReg(DstReg); 1119 DEBUG(dbgs() << "\t\tupdated: " << *UseMI); 1120 } 1121 } 1122 eliminateDeadDefs(); 1123 } 1124 1125 return true; 1126 } 1127 1128 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) { 1129 // ProcessImpicitDefs may leave some copies of <undef> values, it only removes 1130 // local variables. When we have a copy like: 1131 // 1132 // %vreg1 = COPY %vreg2<undef> 1133 // 1134 // We delete the copy and remove the corresponding value number from %vreg1. 1135 // Any uses of that value number are marked as <undef>. 1136 1137 // Note that we do not query CoalescerPair here but redo isMoveInstr as the 1138 // CoalescerPair may have a new register class with adjusted subreg indices 1139 // at this point. 1140 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 1141 isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx); 1142 1143 SlotIndex Idx = LIS->getInstructionIndex(*CopyMI); 1144 const LiveInterval &SrcLI = LIS->getInterval(SrcReg); 1145 // CopyMI is undef iff SrcReg is not live before the instruction. 1146 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) { 1147 LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx); 1148 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) { 1149 if ((SR.LaneMask & SrcMask) == 0) 1150 continue; 1151 if (SR.liveAt(Idx)) 1152 return false; 1153 } 1154 } else if (SrcLI.liveAt(Idx)) 1155 return false; 1156 1157 DEBUG(dbgs() << "\tEliminating copy of <undef> value\n"); 1158 1159 // Remove any DstReg segments starting at the instruction. 1160 LiveInterval &DstLI = LIS->getInterval(DstReg); 1161 SlotIndex RegIndex = Idx.getRegSlot(); 1162 // Remove value or merge with previous one in case of a subregister def. 1163 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) { 1164 VNInfo *VNI = DstLI.getVNInfoAt(RegIndex); 1165 DstLI.MergeValueNumberInto(VNI, PrevVNI); 1166 1167 // The affected subregister segments can be removed. 1168 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx); 1169 for (LiveInterval::SubRange &SR : DstLI.subranges()) { 1170 if ((SR.LaneMask & DstMask) == 0) 1171 continue; 1172 1173 VNInfo *SVNI = SR.getVNInfoAt(RegIndex); 1174 assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex)); 1175 SR.removeValNo(SVNI); 1176 } 1177 DstLI.removeEmptySubRanges(); 1178 } else 1179 LIS->removeVRegDefAt(DstLI, RegIndex); 1180 1181 // Mark uses as undef. 1182 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) { 1183 if (MO.isDef() /*|| MO.isUndef()*/) 1184 continue; 1185 const MachineInstr &MI = *MO.getParent(); 1186 SlotIndex UseIdx = LIS->getInstructionIndex(MI); 1187 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg()); 1188 bool isLive; 1189 if (UseMask != ~0u && DstLI.hasSubRanges()) { 1190 isLive = false; 1191 for (const LiveInterval::SubRange &SR : DstLI.subranges()) { 1192 if ((SR.LaneMask & UseMask) == 0) 1193 continue; 1194 if (SR.liveAt(UseIdx)) { 1195 isLive = true; 1196 break; 1197 } 1198 } 1199 } else 1200 isLive = DstLI.liveAt(UseIdx); 1201 if (isLive) 1202 continue; 1203 MO.setIsUndef(true); 1204 DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI); 1205 } 1206 return true; 1207 } 1208 1209 void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx, 1210 MachineOperand &MO, unsigned SubRegIdx) { 1211 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx); 1212 if (MO.isDef()) 1213 Mask = ~Mask; 1214 bool IsUndef = true; 1215 for (const LiveInterval::SubRange &S : Int.subranges()) { 1216 if ((S.LaneMask & Mask) == 0) 1217 continue; 1218 if (S.liveAt(UseIdx)) { 1219 IsUndef = false; 1220 break; 1221 } 1222 } 1223 if (IsUndef) { 1224 MO.setIsUndef(true); 1225 // We found out some subregister use is actually reading an undefined 1226 // value. In some cases the whole vreg has become undefined at this 1227 // point so we have to potentially shrink the main range if the 1228 // use was ending a live segment there. 1229 LiveQueryResult Q = Int.Query(UseIdx); 1230 if (Q.valueOut() == nullptr) 1231 ShrinkMainRange = true; 1232 } 1233 } 1234 1235 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg, 1236 unsigned DstReg, 1237 unsigned SubIdx) { 1238 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 1239 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg); 1240 1241 if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) { 1242 for (MachineOperand &MO : MRI->reg_operands(DstReg)) { 1243 unsigned SubReg = MO.getSubReg(); 1244 if (SubReg == 0 || MO.isUndef()) 1245 continue; 1246 MachineInstr &MI = *MO.getParent(); 1247 if (MI.isDebugValue()) 1248 continue; 1249 SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true); 1250 addUndefFlag(*DstInt, UseIdx, MO, SubReg); 1251 } 1252 } 1253 1254 SmallPtrSet<MachineInstr*, 8> Visited; 1255 for (MachineRegisterInfo::reg_instr_iterator 1256 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end(); 1257 I != E; ) { 1258 MachineInstr *UseMI = &*(I++); 1259 1260 // Each instruction can only be rewritten once because sub-register 1261 // composition is not always idempotent. When SrcReg != DstReg, rewriting 1262 // the UseMI operands removes them from the SrcReg use-def chain, but when 1263 // SrcReg is DstReg we could encounter UseMI twice if it has multiple 1264 // operands mentioning the virtual register. 1265 if (SrcReg == DstReg && !Visited.insert(UseMI).second) 1266 continue; 1267 1268 SmallVector<unsigned,8> Ops; 1269 bool Reads, Writes; 1270 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops); 1271 1272 // If SrcReg wasn't read, it may still be the case that DstReg is live-in 1273 // because SrcReg is a sub-register. 1274 if (DstInt && !Reads && SubIdx) 1275 Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI)); 1276 1277 // Replace SrcReg with DstReg in all UseMI operands. 1278 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1279 MachineOperand &MO = UseMI->getOperand(Ops[i]); 1280 1281 // Adjust <undef> flags in case of sub-register joins. We don't want to 1282 // turn a full def into a read-modify-write sub-register def and vice 1283 // versa. 1284 if (SubIdx && MO.isDef()) 1285 MO.setIsUndef(!Reads); 1286 1287 // A subreg use of a partially undef (super) register may be a complete 1288 // undef use now and then has to be marked that way. 1289 if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) { 1290 if (!DstInt->hasSubRanges()) { 1291 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 1292 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg); 1293 DstInt->createSubRangeFrom(Allocator, Mask, *DstInt); 1294 } 1295 SlotIndex MIIdx = UseMI->isDebugValue() 1296 ? LIS->getSlotIndexes()->getIndexBefore(*UseMI) 1297 : LIS->getInstructionIndex(*UseMI); 1298 SlotIndex UseIdx = MIIdx.getRegSlot(true); 1299 addUndefFlag(*DstInt, UseIdx, MO, SubIdx); 1300 } 1301 1302 if (DstIsPhys) 1303 MO.substPhysReg(DstReg, *TRI); 1304 else 1305 MO.substVirtReg(DstReg, SubIdx, *TRI); 1306 } 1307 1308 DEBUG({ 1309 dbgs() << "\t\tupdated: "; 1310 if (!UseMI->isDebugValue()) 1311 dbgs() << LIS->getInstructionIndex(*UseMI) << "\t"; 1312 dbgs() << *UseMI; 1313 }); 1314 } 1315 } 1316 1317 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) { 1318 // Always join simple intervals that are defined by a single copy from a 1319 // reserved register. This doesn't increase register pressure, so it is 1320 // always beneficial. 1321 if (!MRI->isReserved(CP.getDstReg())) { 1322 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n"); 1323 return false; 1324 } 1325 1326 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg()); 1327 if (JoinVInt.containsOneValue()) 1328 return true; 1329 1330 DEBUG(dbgs() << "\tCannot join complex intervals into reserved register.\n"); 1331 return false; 1332 } 1333 1334 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) { 1335 1336 Again = false; 1337 DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI); 1338 1339 CoalescerPair CP(*TRI); 1340 if (!CP.setRegisters(CopyMI)) { 1341 DEBUG(dbgs() << "\tNot coalescable.\n"); 1342 return false; 1343 } 1344 1345 if (CP.getNewRC()) { 1346 auto SrcRC = MRI->getRegClass(CP.getSrcReg()); 1347 auto DstRC = MRI->getRegClass(CP.getDstReg()); 1348 unsigned SrcIdx = CP.getSrcIdx(); 1349 unsigned DstIdx = CP.getDstIdx(); 1350 if (CP.isFlipped()) { 1351 std::swap(SrcIdx, DstIdx); 1352 std::swap(SrcRC, DstRC); 1353 } 1354 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx, 1355 CP.getNewRC())) { 1356 DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n"); 1357 return false; 1358 } 1359 } 1360 1361 // Dead code elimination. This really should be handled by MachineDCE, but 1362 // sometimes dead copies slip through, and we can't generate invalid live 1363 // ranges. 1364 if (!CP.isPhys() && CopyMI->allDefsAreDead()) { 1365 DEBUG(dbgs() << "\tCopy is dead.\n"); 1366 DeadDefs.push_back(CopyMI); 1367 eliminateDeadDefs(); 1368 return true; 1369 } 1370 1371 // Eliminate undefs. 1372 if (!CP.isPhys() && eliminateUndefCopy(CopyMI)) { 1373 LIS->RemoveMachineInstrFromMaps(*CopyMI); 1374 CopyMI->eraseFromParent(); 1375 return false; // Not coalescable. 1376 } 1377 1378 // Coalesced copies are normally removed immediately, but transformations 1379 // like removeCopyByCommutingDef() can inadvertently create identity copies. 1380 // When that happens, just join the values and remove the copy. 1381 if (CP.getSrcReg() == CP.getDstReg()) { 1382 LiveInterval &LI = LIS->getInterval(CP.getSrcReg()); 1383 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n'); 1384 const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI); 1385 LiveQueryResult LRQ = LI.Query(CopyIdx); 1386 if (VNInfo *DefVNI = LRQ.valueDefined()) { 1387 VNInfo *ReadVNI = LRQ.valueIn(); 1388 assert(ReadVNI && "No value before copy and no <undef> flag."); 1389 assert(ReadVNI != DefVNI && "Cannot read and define the same value."); 1390 LI.MergeValueNumberInto(DefVNI, ReadVNI); 1391 1392 // Process subregister liveranges. 1393 for (LiveInterval::SubRange &S : LI.subranges()) { 1394 LiveQueryResult SLRQ = S.Query(CopyIdx); 1395 if (VNInfo *SDefVNI = SLRQ.valueDefined()) { 1396 VNInfo *SReadVNI = SLRQ.valueIn(); 1397 S.MergeValueNumberInto(SDefVNI, SReadVNI); 1398 } 1399 } 1400 DEBUG(dbgs() << "\tMerged values: " << LI << '\n'); 1401 } 1402 LIS->RemoveMachineInstrFromMaps(*CopyMI); 1403 CopyMI->eraseFromParent(); 1404 return true; 1405 } 1406 1407 // Enforce policies. 1408 if (CP.isPhys()) { 1409 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI) 1410 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) 1411 << '\n'); 1412 if (!canJoinPhys(CP)) { 1413 // Before giving up coalescing, if definition of source is defined by 1414 // trivial computation, try rematerializing it. 1415 bool IsDefCopy; 1416 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy)) 1417 return true; 1418 if (IsDefCopy) 1419 Again = true; // May be possible to coalesce later. 1420 return false; 1421 } 1422 } else { 1423 // When possible, let DstReg be the larger interval. 1424 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() > 1425 LIS->getInterval(CP.getDstReg()).size()) 1426 CP.flip(); 1427 1428 DEBUG({ 1429 dbgs() << "\tConsidering merging to " 1430 << TRI->getRegClassName(CP.getNewRC()) << " with "; 1431 if (CP.getDstIdx() && CP.getSrcIdx()) 1432 dbgs() << PrintReg(CP.getDstReg()) << " in " 1433 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and " 1434 << PrintReg(CP.getSrcReg()) << " in " 1435 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n'; 1436 else 1437 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in " 1438 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; 1439 }); 1440 } 1441 1442 ShrinkMask = 0; 1443 ShrinkMainRange = false; 1444 1445 // Okay, attempt to join these two intervals. On failure, this returns false. 1446 // Otherwise, if one of the intervals being joined is a physreg, this method 1447 // always canonicalizes DstInt to be it. The output "SrcInt" will not have 1448 // been modified, so we can use this information below to update aliases. 1449 if (!joinIntervals(CP)) { 1450 // Coalescing failed. 1451 1452 // If definition of source is defined by trivial computation, try 1453 // rematerializing it. 1454 bool IsDefCopy; 1455 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy)) 1456 return true; 1457 1458 // If we can eliminate the copy without merging the live segments, do so 1459 // now. 1460 if (!CP.isPartial() && !CP.isPhys()) { 1461 if (adjustCopiesBackFrom(CP, CopyMI) || 1462 removeCopyByCommutingDef(CP, CopyMI)) { 1463 LIS->RemoveMachineInstrFromMaps(*CopyMI); 1464 CopyMI->eraseFromParent(); 1465 DEBUG(dbgs() << "\tTrivial!\n"); 1466 return true; 1467 } 1468 } 1469 1470 // Otherwise, we are unable to join the intervals. 1471 DEBUG(dbgs() << "\tInterference!\n"); 1472 Again = true; // May be possible to coalesce later. 1473 return false; 1474 } 1475 1476 // Coalescing to a virtual register that is of a sub-register class of the 1477 // other. Make sure the resulting register is set to the right register class. 1478 if (CP.isCrossClass()) { 1479 ++numCrossRCs; 1480 MRI->setRegClass(CP.getDstReg(), CP.getNewRC()); 1481 } 1482 1483 // Removing sub-register copies can ease the register class constraints. 1484 // Make sure we attempt to inflate the register class of DstReg. 1485 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC())) 1486 InflateRegs.push_back(CP.getDstReg()); 1487 1488 // CopyMI has been erased by joinIntervals at this point. Remove it from 1489 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back 1490 // to the work list. This keeps ErasedInstrs from growing needlessly. 1491 ErasedInstrs.erase(CopyMI); 1492 1493 // Rewrite all SrcReg operands to DstReg. 1494 // Also update DstReg operands to include DstIdx if it is set. 1495 if (CP.getDstIdx()) 1496 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx()); 1497 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx()); 1498 1499 // Shrink subregister ranges if necessary. 1500 if (ShrinkMask != 0) { 1501 LiveInterval &LI = LIS->getInterval(CP.getDstReg()); 1502 for (LiveInterval::SubRange &S : LI.subranges()) { 1503 if ((S.LaneMask & ShrinkMask) == 0) 1504 continue; 1505 DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask) 1506 << ")\n"); 1507 LIS->shrinkToUses(S, LI.reg); 1508 } 1509 LI.removeEmptySubRanges(); 1510 } 1511 if (ShrinkMainRange) { 1512 LiveInterval &LI = LIS->getInterval(CP.getDstReg()); 1513 shrinkToUses(&LI); 1514 } 1515 1516 // SrcReg is guaranteed to be the register whose live interval that is 1517 // being merged. 1518 LIS->removeInterval(CP.getSrcReg()); 1519 1520 // Update regalloc hint. 1521 TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF); 1522 1523 DEBUG({ 1524 dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx()) 1525 << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; 1526 dbgs() << "\tResult = "; 1527 if (CP.isPhys()) 1528 dbgs() << PrintReg(CP.getDstReg(), TRI); 1529 else 1530 dbgs() << LIS->getInterval(CP.getDstReg()); 1531 dbgs() << '\n'; 1532 }); 1533 1534 ++numJoins; 1535 return true; 1536 } 1537 1538 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) { 1539 unsigned DstReg = CP.getDstReg(); 1540 assert(CP.isPhys() && "Must be a physreg copy"); 1541 assert(MRI->isReserved(DstReg) && "Not a reserved register"); 1542 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg()); 1543 DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n'); 1544 1545 assert(RHS.containsOneValue() && "Invalid join with reserved register"); 1546 1547 // Optimization for reserved registers like ESP. We can only merge with a 1548 // reserved physreg if RHS has a single value that is a copy of DstReg. 1549 // The live range of the reserved register will look like a set of dead defs 1550 // - we don't properly track the live range of reserved registers. 1551 1552 // Deny any overlapping intervals. This depends on all the reserved 1553 // register live ranges to look like dead defs. 1554 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) 1555 if (RHS.overlaps(LIS->getRegUnit(*UI))) { 1556 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n'); 1557 return false; 1558 } 1559 1560 // Skip any value computations, we are not adding new values to the 1561 // reserved register. Also skip merging the live ranges, the reserved 1562 // register live range doesn't need to be accurate as long as all the 1563 // defs are there. 1564 1565 // Delete the identity copy. 1566 MachineInstr *CopyMI; 1567 if (CP.isFlipped()) { 1568 CopyMI = MRI->getVRegDef(RHS.reg); 1569 } else { 1570 if (!MRI->hasOneNonDBGUse(RHS.reg)) { 1571 DEBUG(dbgs() << "\t\tMultiple vreg uses!\n"); 1572 return false; 1573 } 1574 1575 MachineInstr *DestMI = MRI->getVRegDef(RHS.reg); 1576 CopyMI = &*MRI->use_instr_nodbg_begin(RHS.reg); 1577 const SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); 1578 const SlotIndex DestRegIdx = LIS->getInstructionIndex(*DestMI).getRegSlot(); 1579 1580 // We checked above that there are no interfering defs of the physical 1581 // register. However, for this case, where we intent to move up the def of 1582 // the physical register, we also need to check for interfering uses. 1583 SlotIndexes *Indexes = LIS->getSlotIndexes(); 1584 for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx); 1585 SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) { 1586 MachineInstr *MI = LIS->getInstructionFromIndex(SI); 1587 if (MI->readsRegister(DstReg, TRI)) { 1588 DEBUG(dbgs() << "\t\tInterference (read): " << *MI); 1589 return false; 1590 } 1591 1592 // We must also check for clobbers caused by regmasks. 1593 for (const auto &MO : MI->operands()) { 1594 if (MO.isRegMask() && MO.clobbersPhysReg(DstReg)) { 1595 DEBUG(dbgs() << "\t\tInterference (regmask clobber): " << *MI); 1596 return false; 1597 } 1598 } 1599 } 1600 1601 // We're going to remove the copy which defines a physical reserved 1602 // register, so remove its valno, etc. 1603 DEBUG(dbgs() << "\t\tRemoving phys reg def of " << DstReg << " at " 1604 << CopyRegIdx << "\n"); 1605 1606 LIS->removePhysRegDefAt(DstReg, CopyRegIdx); 1607 // Create a new dead def at the new def location. 1608 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) { 1609 LiveRange &LR = LIS->getRegUnit(*UI); 1610 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator()); 1611 } 1612 } 1613 1614 LIS->RemoveMachineInstrFromMaps(*CopyMI); 1615 CopyMI->eraseFromParent(); 1616 1617 // We don't track kills for reserved registers. 1618 MRI->clearKillFlags(CP.getSrcReg()); 1619 1620 return true; 1621 } 1622 1623 //===----------------------------------------------------------------------===// 1624 // Interference checking and interval joining 1625 //===----------------------------------------------------------------------===// 1626 // 1627 // In the easiest case, the two live ranges being joined are disjoint, and 1628 // there is no interference to consider. It is quite common, though, to have 1629 // overlapping live ranges, and we need to check if the interference can be 1630 // resolved. 1631 // 1632 // The live range of a single SSA value forms a sub-tree of the dominator tree. 1633 // This means that two SSA values overlap if and only if the def of one value 1634 // is contained in the live range of the other value. As a special case, the 1635 // overlapping values can be defined at the same index. 1636 // 1637 // The interference from an overlapping def can be resolved in these cases: 1638 // 1639 // 1. Coalescable copies. The value is defined by a copy that would become an 1640 // identity copy after joining SrcReg and DstReg. The copy instruction will 1641 // be removed, and the value will be merged with the source value. 1642 // 1643 // There can be several copies back and forth, causing many values to be 1644 // merged into one. We compute a list of ultimate values in the joined live 1645 // range as well as a mappings from the old value numbers. 1646 // 1647 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI 1648 // predecessors have a live out value. It doesn't cause real interference, 1649 // and can be merged into the value it overlaps. Like a coalescable copy, it 1650 // can be erased after joining. 1651 // 1652 // 3. Copy of external value. The overlapping def may be a copy of a value that 1653 // is already in the other register. This is like a coalescable copy, but 1654 // the live range of the source register must be trimmed after erasing the 1655 // copy instruction: 1656 // 1657 // %src = COPY %ext 1658 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext. 1659 // 1660 // 4. Clobbering undefined lanes. Vector registers are sometimes built by 1661 // defining one lane at a time: 1662 // 1663 // %dst:ssub0<def,read-undef> = FOO 1664 // %src = BAR 1665 // %dst:ssub1<def> = COPY %src 1666 // 1667 // The live range of %src overlaps the %dst value defined by FOO, but 1668 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane 1669 // which was undef anyway. 1670 // 1671 // The value mapping is more complicated in this case. The final live range 1672 // will have different value numbers for both FOO and BAR, but there is no 1673 // simple mapping from old to new values. It may even be necessary to add 1674 // new PHI values. 1675 // 1676 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that 1677 // is live, but never read. This can happen because we don't compute 1678 // individual live ranges per lane. 1679 // 1680 // %dst<def> = FOO 1681 // %src = BAR 1682 // %dst:ssub1<def> = COPY %src 1683 // 1684 // This kind of interference is only resolved locally. If the clobbered 1685 // lane value escapes the block, the join is aborted. 1686 1687 namespace { 1688 /// Track information about values in a single virtual register about to be 1689 /// joined. Objects of this class are always created in pairs - one for each 1690 /// side of the CoalescerPair (or one for each lane of a side of the coalescer 1691 /// pair) 1692 class JoinVals { 1693 /// Live range we work on. 1694 LiveRange &LR; 1695 /// (Main) register we work on. 1696 const unsigned Reg; 1697 1698 /// Reg (and therefore the values in this liverange) will end up as 1699 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or 1700 /// CP.SrcIdx. 1701 const unsigned SubIdx; 1702 /// The LaneMask that this liverange will occupy the coalesced register. May 1703 /// be smaller than the lanemask produced by SubIdx when merging subranges. 1704 const LaneBitmask LaneMask; 1705 1706 /// This is true when joining sub register ranges, false when joining main 1707 /// ranges. 1708 const bool SubRangeJoin; 1709 /// Whether the current LiveInterval tracks subregister liveness. 1710 const bool TrackSubRegLiveness; 1711 1712 /// Values that will be present in the final live range. 1713 SmallVectorImpl<VNInfo*> &NewVNInfo; 1714 1715 const CoalescerPair &CP; 1716 LiveIntervals *LIS; 1717 SlotIndexes *Indexes; 1718 const TargetRegisterInfo *TRI; 1719 1720 /// Value number assignments. Maps value numbers in LI to entries in 1721 /// NewVNInfo. This is suitable for passing to LiveInterval::join(). 1722 SmallVector<int, 8> Assignments; 1723 1724 /// Conflict resolution for overlapping values. 1725 enum ConflictResolution { 1726 /// No overlap, simply keep this value. 1727 CR_Keep, 1728 1729 /// Merge this value into OtherVNI and erase the defining instruction. 1730 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external 1731 /// values. 1732 CR_Erase, 1733 1734 /// Merge this value into OtherVNI but keep the defining instruction. 1735 /// This is for the special case where OtherVNI is defined by the same 1736 /// instruction. 1737 CR_Merge, 1738 1739 /// Keep this value, and have it replace OtherVNI where possible. This 1740 /// complicates value mapping since OtherVNI maps to two different values 1741 /// before and after this def. 1742 /// Used when clobbering undefined or dead lanes. 1743 CR_Replace, 1744 1745 /// Unresolved conflict. Visit later when all values have been mapped. 1746 CR_Unresolved, 1747 1748 /// Unresolvable conflict. Abort the join. 1749 CR_Impossible 1750 }; 1751 1752 /// Per-value info for LI. The lane bit masks are all relative to the final 1753 /// joined register, so they can be compared directly between SrcReg and 1754 /// DstReg. 1755 struct Val { 1756 ConflictResolution Resolution; 1757 1758 /// Lanes written by this def, 0 for unanalyzed values. 1759 LaneBitmask WriteLanes; 1760 1761 /// Lanes with defined values in this register. Other lanes are undef and 1762 /// safe to clobber. 1763 LaneBitmask ValidLanes; 1764 1765 /// Value in LI being redefined by this def. 1766 VNInfo *RedefVNI; 1767 1768 /// Value in the other live range that overlaps this def, if any. 1769 VNInfo *OtherVNI; 1770 1771 /// Is this value an IMPLICIT_DEF that can be erased? 1772 /// 1773 /// IMPLICIT_DEF values should only exist at the end of a basic block that 1774 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be 1775 /// safely erased if they are overlapping a live value in the other live 1776 /// interval. 1777 /// 1778 /// Weird control flow graphs and incomplete PHI handling in 1779 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with 1780 /// longer live ranges. Such IMPLICIT_DEF values should be treated like 1781 /// normal values. 1782 bool ErasableImplicitDef; 1783 1784 /// True when the live range of this value will be pruned because of an 1785 /// overlapping CR_Replace value in the other live range. 1786 bool Pruned; 1787 1788 /// True once Pruned above has been computed. 1789 bool PrunedComputed; 1790 1791 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0), 1792 RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false), 1793 Pruned(false), PrunedComputed(false) {} 1794 1795 bool isAnalyzed() const { return WriteLanes != 0; } 1796 }; 1797 1798 /// One entry per value number in LI. 1799 SmallVector<Val, 8> Vals; 1800 1801 /// Compute the bitmask of lanes actually written by DefMI. 1802 /// Set Redef if there are any partial register definitions that depend on the 1803 /// previous value of the register. 1804 LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const; 1805 1806 /// Find the ultimate value that VNI was copied from. 1807 std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const; 1808 1809 bool valuesIdentical(VNInfo *Val0, VNInfo *Val1, const JoinVals &Other) const; 1810 1811 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo]. 1812 /// Return a conflict resolution when possible, but leave the hard cases as 1813 /// CR_Unresolved. 1814 /// Recursively calls computeAssignment() on this and Other, guaranteeing that 1815 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning. 1816 /// The recursion always goes upwards in the dominator tree, making loops 1817 /// impossible. 1818 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other); 1819 1820 /// Compute the value assignment for ValNo in RI. 1821 /// This may be called recursively by analyzeValue(), but never for a ValNo on 1822 /// the stack. 1823 void computeAssignment(unsigned ValNo, JoinVals &Other); 1824 1825 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute 1826 /// the extent of the tainted lanes in the block. 1827 /// 1828 /// Multiple values in Other.LR can be affected since partial redefinitions 1829 /// can preserve previously tainted lanes. 1830 /// 1831 /// 1 %dst = VLOAD <-- Define all lanes in %dst 1832 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0 1833 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0 1834 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read 1835 /// 1836 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes) 1837 /// entry to TaintedVals. 1838 /// 1839 /// Returns false if the tainted lanes extend beyond the basic block. 1840 bool taintExtent(unsigned, LaneBitmask, JoinVals&, 1841 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask> >&); 1842 1843 /// Return true if MI uses any of the given Lanes from Reg. 1844 /// This does not include partial redefinitions of Reg. 1845 bool usesLanes(const MachineInstr *MI, unsigned, unsigned, LaneBitmask) const; 1846 1847 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will 1848 /// be pruned: 1849 /// 1850 /// %dst = COPY %src 1851 /// %src = COPY %dst <-- This value to be pruned. 1852 /// %dst = COPY %src <-- This value is a copy of a pruned value. 1853 bool isPrunedValue(unsigned ValNo, JoinVals &Other); 1854 1855 public: 1856 JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, LaneBitmask LaneMask, 1857 SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp, 1858 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin, 1859 bool TrackSubRegLiveness) 1860 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask), 1861 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness), 1862 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()), 1863 TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums()) 1864 {} 1865 1866 /// Analyze defs in LR and compute a value mapping in NewVNInfo. 1867 /// Returns false if any conflicts were impossible to resolve. 1868 bool mapValues(JoinVals &Other); 1869 1870 /// Try to resolve conflicts that require all values to be mapped. 1871 /// Returns false if any conflicts were impossible to resolve. 1872 bool resolveConflicts(JoinVals &Other); 1873 1874 /// Prune the live range of values in Other.LR where they would conflict with 1875 /// CR_Replace values in LR. Collect end points for restoring the live range 1876 /// after joining. 1877 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints, 1878 bool changeInstrs); 1879 1880 /// Removes subranges starting at copies that get removed. This sometimes 1881 /// happens when undefined subranges are copied around. These ranges contain 1882 /// no useful information and can be removed. 1883 void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask); 1884 1885 /// Erase any machine instructions that have been coalesced away. 1886 /// Add erased instructions to ErasedInstrs. 1887 /// Add foreign virtual registers to ShrinkRegs if their live range ended at 1888 /// the erased instrs. 1889 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs, 1890 SmallVectorImpl<unsigned> &ShrinkRegs); 1891 1892 /// Remove liverange defs at places where implicit defs will be removed. 1893 void removeImplicitDefs(); 1894 1895 /// Get the value assignments suitable for passing to LiveInterval::join. 1896 const int *getAssignments() const { return Assignments.data(); } 1897 }; 1898 } // end anonymous namespace 1899 1900 LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) 1901 const { 1902 LaneBitmask L = 0; 1903 for (const MachineOperand &MO : DefMI->operands()) { 1904 if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef()) 1905 continue; 1906 L |= TRI->getSubRegIndexLaneMask( 1907 TRI->composeSubRegIndices(SubIdx, MO.getSubReg())); 1908 if (MO.readsReg()) 1909 Redef = true; 1910 } 1911 return L; 1912 } 1913 1914 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain( 1915 const VNInfo *VNI) const { 1916 unsigned Reg = this->Reg; 1917 1918 while (!VNI->isPHIDef()) { 1919 SlotIndex Def = VNI->def; 1920 MachineInstr *MI = Indexes->getInstructionFromIndex(Def); 1921 assert(MI && "No defining instruction"); 1922 if (!MI->isFullCopy()) 1923 return std::make_pair(VNI, Reg); 1924 unsigned SrcReg = MI->getOperand(1).getReg(); 1925 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) 1926 return std::make_pair(VNI, Reg); 1927 1928 const LiveInterval &LI = LIS->getInterval(SrcReg); 1929 const VNInfo *ValueIn; 1930 // No subrange involved. 1931 if (!SubRangeJoin || !LI.hasSubRanges()) { 1932 LiveQueryResult LRQ = LI.Query(Def); 1933 ValueIn = LRQ.valueIn(); 1934 } else { 1935 // Query subranges. Pick the first matching one. 1936 ValueIn = nullptr; 1937 for (const LiveInterval::SubRange &S : LI.subranges()) { 1938 // Transform lanemask to a mask in the joined live interval. 1939 LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask); 1940 if ((SMask & LaneMask) == 0) 1941 continue; 1942 LiveQueryResult LRQ = S.Query(Def); 1943 ValueIn = LRQ.valueIn(); 1944 break; 1945 } 1946 } 1947 if (ValueIn == nullptr) 1948 break; 1949 VNI = ValueIn; 1950 Reg = SrcReg; 1951 } 1952 return std::make_pair(VNI, Reg); 1953 } 1954 1955 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1, 1956 const JoinVals &Other) const { 1957 const VNInfo *Orig0; 1958 unsigned Reg0; 1959 std::tie(Orig0, Reg0) = followCopyChain(Value0); 1960 if (Orig0 == Value1) 1961 return true; 1962 1963 const VNInfo *Orig1; 1964 unsigned Reg1; 1965 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1); 1966 1967 // The values are equal if they are defined at the same place and use the 1968 // same register. Note that we cannot compare VNInfos directly as some of 1969 // them might be from a copy created in mergeSubRangeInto() while the other 1970 // is from the original LiveInterval. 1971 return Orig0->def == Orig1->def && Reg0 == Reg1; 1972 } 1973 1974 JoinVals::ConflictResolution 1975 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) { 1976 Val &V = Vals[ValNo]; 1977 assert(!V.isAnalyzed() && "Value has already been analyzed!"); 1978 VNInfo *VNI = LR.getValNumInfo(ValNo); 1979 if (VNI->isUnused()) { 1980 V.WriteLanes = ~0u; 1981 return CR_Keep; 1982 } 1983 1984 // Get the instruction defining this value, compute the lanes written. 1985 const MachineInstr *DefMI = nullptr; 1986 if (VNI->isPHIDef()) { 1987 // Conservatively assume that all lanes in a PHI are valid. 1988 LaneBitmask Lanes = SubRangeJoin ? 1 : TRI->getSubRegIndexLaneMask(SubIdx); 1989 V.ValidLanes = V.WriteLanes = Lanes; 1990 } else { 1991 DefMI = Indexes->getInstructionFromIndex(VNI->def); 1992 assert(DefMI != nullptr); 1993 if (SubRangeJoin) { 1994 // We don't care about the lanes when joining subregister ranges. 1995 V.WriteLanes = V.ValidLanes = 1; 1996 if (DefMI->isImplicitDef()) { 1997 V.ValidLanes = 0; 1998 V.ErasableImplicitDef = true; 1999 } 2000 } else { 2001 bool Redef = false; 2002 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef); 2003 2004 // If this is a read-modify-write instruction, there may be more valid 2005 // lanes than the ones written by this instruction. 2006 // This only covers partial redef operands. DefMI may have normal use 2007 // operands reading the register. They don't contribute valid lanes. 2008 // 2009 // This adds ssub1 to the set of valid lanes in %src: 2010 // 2011 // %src:ssub1<def> = FOO 2012 // 2013 // This leaves only ssub1 valid, making any other lanes undef: 2014 // 2015 // %src:ssub1<def,read-undef> = FOO %src:ssub2 2016 // 2017 // The <read-undef> flag on the def operand means that old lane values are 2018 // not important. 2019 if (Redef) { 2020 V.RedefVNI = LR.Query(VNI->def).valueIn(); 2021 assert((TrackSubRegLiveness || V.RedefVNI) && 2022 "Instruction is reading nonexistent value"); 2023 if (V.RedefVNI != nullptr) { 2024 computeAssignment(V.RedefVNI->id, Other); 2025 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes; 2026 } 2027 } 2028 2029 // An IMPLICIT_DEF writes undef values. 2030 if (DefMI->isImplicitDef()) { 2031 // We normally expect IMPLICIT_DEF values to be live only until the end 2032 // of their block. If the value is really live longer and gets pruned in 2033 // another block, this flag is cleared again. 2034 V.ErasableImplicitDef = true; 2035 V.ValidLanes &= ~V.WriteLanes; 2036 } 2037 } 2038 } 2039 2040 // Find the value in Other that overlaps VNI->def, if any. 2041 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def); 2042 2043 // It is possible that both values are defined by the same instruction, or 2044 // the values are PHIs defined in the same block. When that happens, the two 2045 // values should be merged into one, but not into any preceding value. 2046 // The first value defined or visited gets CR_Keep, the other gets CR_Merge. 2047 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) { 2048 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ"); 2049 2050 // One value stays, the other is merged. Keep the earlier one, or the first 2051 // one we see. 2052 if (OtherVNI->def < VNI->def) 2053 Other.computeAssignment(OtherVNI->id, *this); 2054 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) { 2055 // This is an early-clobber def overlapping a live-in value in the other 2056 // register. Not mergeable. 2057 V.OtherVNI = OtherLRQ.valueIn(); 2058 return CR_Impossible; 2059 } 2060 V.OtherVNI = OtherVNI; 2061 Val &OtherV = Other.Vals[OtherVNI->id]; 2062 // Keep this value, check for conflicts when analyzing OtherVNI. 2063 if (!OtherV.isAnalyzed()) 2064 return CR_Keep; 2065 // Both sides have been analyzed now. 2066 // Allow overlapping PHI values. Any real interference would show up in a 2067 // predecessor, the PHI itself can't introduce any conflicts. 2068 if (VNI->isPHIDef()) 2069 return CR_Merge; 2070 if (V.ValidLanes & OtherV.ValidLanes) 2071 // Overlapping lanes can't be resolved. 2072 return CR_Impossible; 2073 else 2074 return CR_Merge; 2075 } 2076 2077 // No simultaneous def. Is Other live at the def? 2078 V.OtherVNI = OtherLRQ.valueIn(); 2079 if (!V.OtherVNI) 2080 // No overlap, no conflict. 2081 return CR_Keep; 2082 2083 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ"); 2084 2085 // We have overlapping values, or possibly a kill of Other. 2086 // Recursively compute assignments up the dominator tree. 2087 Other.computeAssignment(V.OtherVNI->id, *this); 2088 Val &OtherV = Other.Vals[V.OtherVNI->id]; 2089 2090 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block. 2091 // This shouldn't normally happen, but ProcessImplicitDefs can leave such 2092 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it 2093 // technically. 2094 // 2095 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try 2096 // to erase the IMPLICIT_DEF instruction. 2097 if (OtherV.ErasableImplicitDef && DefMI && 2098 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) { 2099 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def 2100 << " extends into BB#" << DefMI->getParent()->getNumber() 2101 << ", keeping it.\n"); 2102 OtherV.ErasableImplicitDef = false; 2103 } 2104 2105 // Allow overlapping PHI values. Any real interference would show up in a 2106 // predecessor, the PHI itself can't introduce any conflicts. 2107 if (VNI->isPHIDef()) 2108 return CR_Replace; 2109 2110 // Check for simple erasable conflicts. 2111 if (DefMI->isImplicitDef()) { 2112 // We need the def for the subregister if there is nothing else live at the 2113 // subrange at this point. 2114 if (TrackSubRegLiveness 2115 && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)) == 0) 2116 return CR_Replace; 2117 return CR_Erase; 2118 } 2119 2120 // Include the non-conflict where DefMI is a coalescable copy that kills 2121 // OtherVNI. We still want the copy erased and value numbers merged. 2122 if (CP.isCoalescable(DefMI)) { 2123 // Some of the lanes copied from OtherVNI may be undef, making them undef 2124 // here too. 2125 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes; 2126 return CR_Erase; 2127 } 2128 2129 // This may not be a real conflict if DefMI simply kills Other and defines 2130 // VNI. 2131 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def) 2132 return CR_Keep; 2133 2134 // Handle the case where VNI and OtherVNI can be proven to be identical: 2135 // 2136 // %other = COPY %ext 2137 // %this = COPY %ext <-- Erase this copy 2138 // 2139 if (DefMI->isFullCopy() && !CP.isPartial() 2140 && valuesIdentical(VNI, V.OtherVNI, Other)) 2141 return CR_Erase; 2142 2143 // If the lanes written by this instruction were all undef in OtherVNI, it is 2144 // still safe to join the live ranges. This can't be done with a simple value 2145 // mapping, though - OtherVNI will map to multiple values: 2146 // 2147 // 1 %dst:ssub0 = FOO <-- OtherVNI 2148 // 2 %src = BAR <-- VNI 2149 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy. 2150 // 4 BAZ %dst<kill> 2151 // 5 QUUX %src<kill> 2152 // 2153 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace 2154 // handles this complex value mapping. 2155 if ((V.WriteLanes & OtherV.ValidLanes) == 0) 2156 return CR_Replace; 2157 2158 // If the other live range is killed by DefMI and the live ranges are still 2159 // overlapping, it must be because we're looking at an early clobber def: 2160 // 2161 // %dst<def,early-clobber> = ASM %src<kill> 2162 // 2163 // In this case, it is illegal to merge the two live ranges since the early 2164 // clobber def would clobber %src before it was read. 2165 if (OtherLRQ.isKill()) { 2166 // This case where the def doesn't overlap the kill is handled above. 2167 assert(VNI->def.isEarlyClobber() && 2168 "Only early clobber defs can overlap a kill"); 2169 return CR_Impossible; 2170 } 2171 2172 // VNI is clobbering live lanes in OtherVNI, but there is still the 2173 // possibility that no instructions actually read the clobbered lanes. 2174 // If we're clobbering all the lanes in OtherVNI, at least one must be read. 2175 // Otherwise Other.RI wouldn't be live here. 2176 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0) 2177 return CR_Impossible; 2178 2179 // We need to verify that no instructions are reading the clobbered lanes. To 2180 // save compile time, we'll only check that locally. Don't allow the tainted 2181 // value to escape the basic block. 2182 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 2183 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB)) 2184 return CR_Impossible; 2185 2186 // There are still some things that could go wrong besides clobbered lanes 2187 // being read, for example OtherVNI may be only partially redefined in MBB, 2188 // and some clobbered lanes could escape the block. Save this analysis for 2189 // resolveConflicts() when all values have been mapped. We need to know 2190 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute 2191 // that now - the recursive analyzeValue() calls must go upwards in the 2192 // dominator tree. 2193 return CR_Unresolved; 2194 } 2195 2196 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) { 2197 Val &V = Vals[ValNo]; 2198 if (V.isAnalyzed()) { 2199 // Recursion should always move up the dominator tree, so ValNo is not 2200 // supposed to reappear before it has been assigned. 2201 assert(Assignments[ValNo] != -1 && "Bad recursion?"); 2202 return; 2203 } 2204 switch ((V.Resolution = analyzeValue(ValNo, Other))) { 2205 case CR_Erase: 2206 case CR_Merge: 2207 // Merge this ValNo into OtherVNI. 2208 assert(V.OtherVNI && "OtherVNI not assigned, can't merge."); 2209 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion"); 2210 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id]; 2211 DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@' 2212 << LR.getValNumInfo(ValNo)->def << " into " 2213 << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@' 2214 << V.OtherVNI->def << " --> @" 2215 << NewVNInfo[Assignments[ValNo]]->def << '\n'); 2216 break; 2217 case CR_Replace: 2218 case CR_Unresolved: { 2219 // The other value is going to be pruned if this join is successful. 2220 assert(V.OtherVNI && "OtherVNI not assigned, can't prune"); 2221 Val &OtherV = Other.Vals[V.OtherVNI->id]; 2222 // We cannot erase an IMPLICIT_DEF if we don't have valid values for all 2223 // its lanes. 2224 if ((OtherV.WriteLanes & ~V.ValidLanes) != 0 && TrackSubRegLiveness) 2225 OtherV.ErasableImplicitDef = false; 2226 OtherV.Pruned = true; 2227 } 2228 // Fall through. 2229 default: 2230 // This value number needs to go in the final joined live range. 2231 Assignments[ValNo] = NewVNInfo.size(); 2232 NewVNInfo.push_back(LR.getValNumInfo(ValNo)); 2233 break; 2234 } 2235 } 2236 2237 bool JoinVals::mapValues(JoinVals &Other) { 2238 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2239 computeAssignment(i, Other); 2240 if (Vals[i].Resolution == CR_Impossible) { 2241 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i 2242 << '@' << LR.getValNumInfo(i)->def << '\n'); 2243 return false; 2244 } 2245 } 2246 return true; 2247 } 2248 2249 bool JoinVals:: 2250 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other, 2251 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask> > &TaintExtent) { 2252 VNInfo *VNI = LR.getValNumInfo(ValNo); 2253 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 2254 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB); 2255 2256 // Scan Other.LR from VNI.def to MBBEnd. 2257 LiveInterval::iterator OtherI = Other.LR.find(VNI->def); 2258 assert(OtherI != Other.LR.end() && "No conflict?"); 2259 do { 2260 // OtherI is pointing to a tainted value. Abort the join if the tainted 2261 // lanes escape the block. 2262 SlotIndex End = OtherI->end; 2263 if (End >= MBBEnd) { 2264 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':' 2265 << OtherI->valno->id << '@' << OtherI->start << '\n'); 2266 return false; 2267 } 2268 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':' 2269 << OtherI->valno->id << '@' << OtherI->start 2270 << " to " << End << '\n'); 2271 // A dead def is not a problem. 2272 if (End.isDead()) 2273 break; 2274 TaintExtent.push_back(std::make_pair(End, TaintedLanes)); 2275 2276 // Check for another def in the MBB. 2277 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd) 2278 break; 2279 2280 // Lanes written by the new def are no longer tainted. 2281 const Val &OV = Other.Vals[OtherI->valno->id]; 2282 TaintedLanes &= ~OV.WriteLanes; 2283 if (!OV.RedefVNI) 2284 break; 2285 } while (TaintedLanes); 2286 return true; 2287 } 2288 2289 bool JoinVals::usesLanes(const MachineInstr *MI, unsigned Reg, unsigned SubIdx, 2290 LaneBitmask Lanes) const { 2291 if (MI->isDebugValue()) 2292 return false; 2293 for (const MachineOperand &MO : MI->operands()) { 2294 if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg) 2295 continue; 2296 if (!MO.readsReg()) 2297 continue; 2298 if (Lanes & TRI->getSubRegIndexLaneMask( 2299 TRI->composeSubRegIndices(SubIdx, MO.getSubReg()))) 2300 return true; 2301 } 2302 return false; 2303 } 2304 2305 bool JoinVals::resolveConflicts(JoinVals &Other) { 2306 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2307 Val &V = Vals[i]; 2308 assert (V.Resolution != CR_Impossible && "Unresolvable conflict"); 2309 if (V.Resolution != CR_Unresolved) 2310 continue; 2311 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i 2312 << '@' << LR.getValNumInfo(i)->def << '\n'); 2313 if (SubRangeJoin) 2314 return false; 2315 2316 ++NumLaneConflicts; 2317 assert(V.OtherVNI && "Inconsistent conflict resolution."); 2318 VNInfo *VNI = LR.getValNumInfo(i); 2319 const Val &OtherV = Other.Vals[V.OtherVNI->id]; 2320 2321 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the 2322 // join, those lanes will be tainted with a wrong value. Get the extent of 2323 // the tainted lanes. 2324 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes; 2325 SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent; 2326 if (!taintExtent(i, TaintedLanes, Other, TaintExtent)) 2327 // Tainted lanes would extend beyond the basic block. 2328 return false; 2329 2330 assert(!TaintExtent.empty() && "There should be at least one conflict."); 2331 2332 // Now look at the instructions from VNI->def to TaintExtent (inclusive). 2333 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 2334 MachineBasicBlock::iterator MI = MBB->begin(); 2335 if (!VNI->isPHIDef()) { 2336 MI = Indexes->getInstructionFromIndex(VNI->def); 2337 // No need to check the instruction defining VNI for reads. 2338 ++MI; 2339 } 2340 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) && 2341 "Interference ends on VNI->def. Should have been handled earlier"); 2342 MachineInstr *LastMI = 2343 Indexes->getInstructionFromIndex(TaintExtent.front().first); 2344 assert(LastMI && "Range must end at a proper instruction"); 2345 unsigned TaintNum = 0; 2346 for(;;) { 2347 assert(MI != MBB->end() && "Bad LastMI"); 2348 if (usesLanes(MI, Other.Reg, Other.SubIdx, TaintedLanes)) { 2349 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI); 2350 return false; 2351 } 2352 // LastMI is the last instruction to use the current value. 2353 if (&*MI == LastMI) { 2354 if (++TaintNum == TaintExtent.size()) 2355 break; 2356 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first); 2357 assert(LastMI && "Range must end at a proper instruction"); 2358 TaintedLanes = TaintExtent[TaintNum].second; 2359 } 2360 ++MI; 2361 } 2362 2363 // The tainted lanes are unused. 2364 V.Resolution = CR_Replace; 2365 ++NumLaneResolves; 2366 } 2367 return true; 2368 } 2369 2370 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) { 2371 Val &V = Vals[ValNo]; 2372 if (V.Pruned || V.PrunedComputed) 2373 return V.Pruned; 2374 2375 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge) 2376 return V.Pruned; 2377 2378 // Follow copies up the dominator tree and check if any intermediate value 2379 // has been pruned. 2380 V.PrunedComputed = true; 2381 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this); 2382 return V.Pruned; 2383 } 2384 2385 void JoinVals::pruneValues(JoinVals &Other, 2386 SmallVectorImpl<SlotIndex> &EndPoints, 2387 bool changeInstrs) { 2388 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2389 SlotIndex Def = LR.getValNumInfo(i)->def; 2390 switch (Vals[i].Resolution) { 2391 case CR_Keep: 2392 break; 2393 case CR_Replace: { 2394 // This value takes precedence over the value in Other.LR. 2395 LIS->pruneValue(Other.LR, Def, &EndPoints); 2396 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF 2397 // instructions are only inserted to provide a live-out value for PHI 2398 // predecessors, so the instruction should simply go away once its value 2399 // has been replaced. 2400 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id]; 2401 bool EraseImpDef = OtherV.ErasableImplicitDef && 2402 OtherV.Resolution == CR_Keep; 2403 if (!Def.isBlock()) { 2404 if (changeInstrs) { 2405 // Remove <def,read-undef> flags. This def is now a partial redef. 2406 // Also remove <def,dead> flags since the joined live range will 2407 // continue past this instruction. 2408 for (MachineOperand &MO : 2409 Indexes->getInstructionFromIndex(Def)->operands()) { 2410 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) { 2411 MO.setIsUndef(EraseImpDef); 2412 MO.setIsDead(false); 2413 } 2414 } 2415 } 2416 // This value will reach instructions below, but we need to make sure 2417 // the live range also reaches the instruction at Def. 2418 if (!EraseImpDef) 2419 EndPoints.push_back(Def); 2420 } 2421 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def 2422 << ": " << Other.LR << '\n'); 2423 break; 2424 } 2425 case CR_Erase: 2426 case CR_Merge: 2427 if (isPrunedValue(i, Other)) { 2428 // This value is ultimately a copy of a pruned value in LR or Other.LR. 2429 // We can no longer trust the value mapping computed by 2430 // computeAssignment(), the value that was originally copied could have 2431 // been replaced. 2432 LIS->pruneValue(LR, Def, &EndPoints); 2433 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at " 2434 << Def << ": " << LR << '\n'); 2435 } 2436 break; 2437 case CR_Unresolved: 2438 case CR_Impossible: 2439 llvm_unreachable("Unresolved conflicts"); 2440 } 2441 } 2442 } 2443 2444 void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) 2445 { 2446 // Look for values being erased. 2447 bool DidPrune = false; 2448 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2449 if (Vals[i].Resolution != CR_Erase) 2450 continue; 2451 2452 // Check subranges at the point where the copy will be removed. 2453 SlotIndex Def = LR.getValNumInfo(i)->def; 2454 for (LiveInterval::SubRange &S : LI.subranges()) { 2455 LiveQueryResult Q = S.Query(Def); 2456 2457 // If a subrange starts at the copy then an undefined value has been 2458 // copied and we must remove that subrange value as well. 2459 VNInfo *ValueOut = Q.valueOutOrDead(); 2460 if (ValueOut != nullptr && Q.valueIn() == nullptr) { 2461 DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask) 2462 << " at " << Def << "\n"); 2463 LIS->pruneValue(S, Def, nullptr); 2464 DidPrune = true; 2465 // Mark value number as unused. 2466 ValueOut->markUnused(); 2467 continue; 2468 } 2469 // If a subrange ends at the copy, then a value was copied but only 2470 // partially used later. Shrink the subregister range appropriately. 2471 if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) { 2472 DEBUG(dbgs() << "\t\tDead uses at sublane " << PrintLaneMask(S.LaneMask) 2473 << " at " << Def << "\n"); 2474 ShrinkMask |= S.LaneMask; 2475 } 2476 } 2477 } 2478 if (DidPrune) 2479 LI.removeEmptySubRanges(); 2480 } 2481 2482 void JoinVals::removeImplicitDefs() { 2483 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2484 Val &V = Vals[i]; 2485 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned) 2486 continue; 2487 2488 VNInfo *VNI = LR.getValNumInfo(i); 2489 VNI->markUnused(); 2490 LR.removeValNo(VNI); 2491 } 2492 } 2493 2494 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs, 2495 SmallVectorImpl<unsigned> &ShrinkRegs) { 2496 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2497 // Get the def location before markUnused() below invalidates it. 2498 SlotIndex Def = LR.getValNumInfo(i)->def; 2499 switch (Vals[i].Resolution) { 2500 case CR_Keep: { 2501 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any 2502 // longer. The IMPLICIT_DEF instructions are only inserted by 2503 // PHIElimination to guarantee that all PHI predecessors have a value. 2504 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned) 2505 break; 2506 // Remove value number i from LR. 2507 VNInfo *VNI = LR.getValNumInfo(i); 2508 LR.removeValNo(VNI); 2509 // Note that this VNInfo is reused and still referenced in NewVNInfo, 2510 // make it appear like an unused value number. 2511 VNI->markUnused(); 2512 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n'); 2513 // FALL THROUGH. 2514 } 2515 2516 case CR_Erase: { 2517 MachineInstr *MI = Indexes->getInstructionFromIndex(Def); 2518 assert(MI && "No instruction to erase"); 2519 if (MI->isCopy()) { 2520 unsigned Reg = MI->getOperand(1).getReg(); 2521 if (TargetRegisterInfo::isVirtualRegister(Reg) && 2522 Reg != CP.getSrcReg() && Reg != CP.getDstReg()) 2523 ShrinkRegs.push_back(Reg); 2524 } 2525 ErasedInstrs.insert(MI); 2526 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI); 2527 LIS->RemoveMachineInstrFromMaps(*MI); 2528 MI->eraseFromParent(); 2529 break; 2530 } 2531 default: 2532 break; 2533 } 2534 } 2535 } 2536 2537 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange, 2538 LaneBitmask LaneMask, 2539 const CoalescerPair &CP) { 2540 SmallVector<VNInfo*, 16> NewVNInfo; 2541 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask, 2542 NewVNInfo, CP, LIS, TRI, true, true); 2543 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask, 2544 NewVNInfo, CP, LIS, TRI, true, true); 2545 2546 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs()) 2547 // We should be able to resolve all conflicts here as we could successfully do 2548 // it on the mainrange already. There is however a problem when multiple 2549 // ranges get mapped to the "overflow" lane mask bit which creates unexpected 2550 // interferences. 2551 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) { 2552 // We already determined that it is legal to merge the intervals, so this 2553 // should never fail. 2554 llvm_unreachable("*** Couldn't join subrange!\n"); 2555 } 2556 if (!LHSVals.resolveConflicts(RHSVals) || 2557 !RHSVals.resolveConflicts(LHSVals)) { 2558 // We already determined that it is legal to merge the intervals, so this 2559 // should never fail. 2560 llvm_unreachable("*** Couldn't join subrange!\n"); 2561 } 2562 2563 // The merging algorithm in LiveInterval::join() can't handle conflicting 2564 // value mappings, so we need to remove any live ranges that overlap a 2565 // CR_Replace resolution. Collect a set of end points that can be used to 2566 // restore the live range after joining. 2567 SmallVector<SlotIndex, 8> EndPoints; 2568 LHSVals.pruneValues(RHSVals, EndPoints, false); 2569 RHSVals.pruneValues(LHSVals, EndPoints, false); 2570 2571 LHSVals.removeImplicitDefs(); 2572 RHSVals.removeImplicitDefs(); 2573 2574 LRange.verify(); 2575 RRange.verify(); 2576 2577 // Join RRange into LHS. 2578 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(), 2579 NewVNInfo); 2580 2581 DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n"); 2582 if (EndPoints.empty()) 2583 return; 2584 2585 // Recompute the parts of the live range we had to remove because of 2586 // CR_Replace conflicts. 2587 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size() 2588 << " points: " << LRange << '\n'); 2589 LIS->extendToIndices(LRange, EndPoints); 2590 } 2591 2592 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI, 2593 const LiveRange &ToMerge, 2594 LaneBitmask LaneMask, 2595 CoalescerPair &CP) { 2596 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 2597 for (LiveInterval::SubRange &R : LI.subranges()) { 2598 LaneBitmask RMask = R.LaneMask; 2599 // LaneMask of subregisters common to subrange R and ToMerge. 2600 LaneBitmask Common = RMask & LaneMask; 2601 // There is nothing to do without common subregs. 2602 if (Common == 0) 2603 continue; 2604 2605 DEBUG(dbgs() << "\t\tCopy+Merge " << PrintLaneMask(RMask) << " into " 2606 << PrintLaneMask(Common) << '\n'); 2607 // LaneMask of subregisters contained in the R range but not in ToMerge, 2608 // they have to split into their own subrange. 2609 LaneBitmask LRest = RMask & ~LaneMask; 2610 LiveInterval::SubRange *CommonRange; 2611 if (LRest != 0) { 2612 R.LaneMask = LRest; 2613 DEBUG(dbgs() << "\t\tReduce Lane to " << PrintLaneMask(LRest) << '\n'); 2614 // Duplicate SubRange for newly merged common stuff. 2615 CommonRange = LI.createSubRangeFrom(Allocator, Common, R); 2616 } else { 2617 // Reuse the existing range. 2618 R.LaneMask = Common; 2619 CommonRange = &R; 2620 } 2621 LiveRange RangeCopy(ToMerge, Allocator); 2622 joinSubRegRanges(*CommonRange, RangeCopy, Common, CP); 2623 LaneMask &= ~RMask; 2624 } 2625 2626 if (LaneMask != 0) { 2627 DEBUG(dbgs() << "\t\tNew Lane " << PrintLaneMask(LaneMask) << '\n'); 2628 LI.createSubRangeFrom(Allocator, LaneMask, ToMerge); 2629 } 2630 } 2631 2632 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) { 2633 SmallVector<VNInfo*, 16> NewVNInfo; 2634 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg()); 2635 LiveInterval &LHS = LIS->getInterval(CP.getDstReg()); 2636 bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC()); 2637 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), 0, NewVNInfo, CP, LIS, 2638 TRI, false, TrackSubRegLiveness); 2639 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), 0, NewVNInfo, CP, LIS, 2640 TRI, false, TrackSubRegLiveness); 2641 2642 DEBUG(dbgs() << "\t\tRHS = " << RHS 2643 << "\n\t\tLHS = " << LHS 2644 << '\n'); 2645 2646 // First compute NewVNInfo and the simple value mappings. 2647 // Detect impossible conflicts early. 2648 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) 2649 return false; 2650 2651 // Some conflicts can only be resolved after all values have been mapped. 2652 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals)) 2653 return false; 2654 2655 // All clear, the live ranges can be merged. 2656 if (RHS.hasSubRanges() || LHS.hasSubRanges()) { 2657 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 2658 2659 // Transform lanemasks from the LHS to masks in the coalesced register and 2660 // create initial subranges if necessary. 2661 unsigned DstIdx = CP.getDstIdx(); 2662 if (!LHS.hasSubRanges()) { 2663 LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask() 2664 : TRI->getSubRegIndexLaneMask(DstIdx); 2665 // LHS must support subregs or we wouldn't be in this codepath. 2666 assert(Mask != 0); 2667 LHS.createSubRangeFrom(Allocator, Mask, LHS); 2668 } else if (DstIdx != 0) { 2669 // Transform LHS lanemasks to new register class if necessary. 2670 for (LiveInterval::SubRange &R : LHS.subranges()) { 2671 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask); 2672 R.LaneMask = Mask; 2673 } 2674 } 2675 DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg()) 2676 << ' ' << LHS << '\n'); 2677 2678 // Determine lanemasks of RHS in the coalesced register and merge subranges. 2679 unsigned SrcIdx = CP.getSrcIdx(); 2680 if (!RHS.hasSubRanges()) { 2681 LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask() 2682 : TRI->getSubRegIndexLaneMask(SrcIdx); 2683 mergeSubRangeInto(LHS, RHS, Mask, CP); 2684 } else { 2685 // Pair up subranges and merge. 2686 for (LiveInterval::SubRange &R : RHS.subranges()) { 2687 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask); 2688 mergeSubRangeInto(LHS, R, Mask, CP); 2689 } 2690 } 2691 DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n"); 2692 2693 LHSVals.pruneSubRegValues(LHS, ShrinkMask); 2694 RHSVals.pruneSubRegValues(LHS, ShrinkMask); 2695 } 2696 2697 // The merging algorithm in LiveInterval::join() can't handle conflicting 2698 // value mappings, so we need to remove any live ranges that overlap a 2699 // CR_Replace resolution. Collect a set of end points that can be used to 2700 // restore the live range after joining. 2701 SmallVector<SlotIndex, 8> EndPoints; 2702 LHSVals.pruneValues(RHSVals, EndPoints, true); 2703 RHSVals.pruneValues(LHSVals, EndPoints, true); 2704 2705 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external 2706 // registers to require trimming. 2707 SmallVector<unsigned, 8> ShrinkRegs; 2708 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs); 2709 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs); 2710 while (!ShrinkRegs.empty()) 2711 shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val())); 2712 2713 // Join RHS into LHS. 2714 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo); 2715 2716 // Kill flags are going to be wrong if the live ranges were overlapping. 2717 // Eventually, we should simply clear all kill flags when computing live 2718 // ranges. They are reinserted after register allocation. 2719 MRI->clearKillFlags(LHS.reg); 2720 MRI->clearKillFlags(RHS.reg); 2721 2722 if (!EndPoints.empty()) { 2723 // Recompute the parts of the live range we had to remove because of 2724 // CR_Replace conflicts. 2725 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size() 2726 << " points: " << LHS << '\n'); 2727 LIS->extendToIndices((LiveRange&)LHS, EndPoints); 2728 } 2729 2730 return true; 2731 } 2732 2733 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) { 2734 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP); 2735 } 2736 2737 namespace { 2738 /// Information concerning MBB coalescing priority. 2739 struct MBBPriorityInfo { 2740 MachineBasicBlock *MBB; 2741 unsigned Depth; 2742 bool IsSplit; 2743 2744 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit) 2745 : MBB(mbb), Depth(depth), IsSplit(issplit) {} 2746 }; 2747 } 2748 2749 /// C-style comparator that sorts first based on the loop depth of the basic 2750 /// block (the unsigned), and then on the MBB number. 2751 /// 2752 /// EnableGlobalCopies assumes that the primary sort key is loop depth. 2753 static int compareMBBPriority(const MBBPriorityInfo *LHS, 2754 const MBBPriorityInfo *RHS) { 2755 // Deeper loops first 2756 if (LHS->Depth != RHS->Depth) 2757 return LHS->Depth > RHS->Depth ? -1 : 1; 2758 2759 // Try to unsplit critical edges next. 2760 if (LHS->IsSplit != RHS->IsSplit) 2761 return LHS->IsSplit ? -1 : 1; 2762 2763 // Prefer blocks that are more connected in the CFG. This takes care of 2764 // the most difficult copies first while intervals are short. 2765 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size(); 2766 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size(); 2767 if (cl != cr) 2768 return cl > cr ? -1 : 1; 2769 2770 // As a last resort, sort by block number. 2771 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1; 2772 } 2773 2774 /// \returns true if the given copy uses or defines a local live range. 2775 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) { 2776 if (!Copy->isCopy()) 2777 return false; 2778 2779 if (Copy->getOperand(1).isUndef()) 2780 return false; 2781 2782 unsigned SrcReg = Copy->getOperand(1).getReg(); 2783 unsigned DstReg = Copy->getOperand(0).getReg(); 2784 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) 2785 || TargetRegisterInfo::isPhysicalRegister(DstReg)) 2786 return false; 2787 2788 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg)) 2789 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg)); 2790 } 2791 2792 bool RegisterCoalescer:: 2793 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) { 2794 bool Progress = false; 2795 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) { 2796 if (!CurrList[i]) 2797 continue; 2798 // Skip instruction pointers that have already been erased, for example by 2799 // dead code elimination. 2800 if (ErasedInstrs.erase(CurrList[i])) { 2801 CurrList[i] = nullptr; 2802 continue; 2803 } 2804 bool Again = false; 2805 bool Success = joinCopy(CurrList[i], Again); 2806 Progress |= Success; 2807 if (Success || !Again) 2808 CurrList[i] = nullptr; 2809 } 2810 return Progress; 2811 } 2812 2813 /// Check if DstReg is a terminal node. 2814 /// I.e., it does not have any affinity other than \p Copy. 2815 static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy, 2816 const MachineRegisterInfo *MRI) { 2817 assert(Copy.isCopyLike()); 2818 // Check if the destination of this copy as any other affinity. 2819 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg)) 2820 if (&MI != &Copy && MI.isCopyLike()) 2821 return false; 2822 return true; 2823 } 2824 2825 bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const { 2826 assert(Copy.isCopyLike()); 2827 if (!UseTerminalRule) 2828 return false; 2829 unsigned DstReg, DstSubReg, SrcReg, SrcSubReg; 2830 isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg); 2831 // Check if the destination of this copy has any other affinity. 2832 if (TargetRegisterInfo::isPhysicalRegister(DstReg) || 2833 // If SrcReg is a physical register, the copy won't be coalesced. 2834 // Ignoring it may have other side effect (like missing 2835 // rematerialization). So keep it. 2836 TargetRegisterInfo::isPhysicalRegister(SrcReg) || 2837 !isTerminalReg(DstReg, Copy, MRI)) 2838 return false; 2839 2840 // DstReg is a terminal node. Check if it interferes with any other 2841 // copy involving SrcReg. 2842 const MachineBasicBlock *OrigBB = Copy.getParent(); 2843 const LiveInterval &DstLI = LIS->getInterval(DstReg); 2844 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) { 2845 // Technically we should check if the weight of the new copy is 2846 // interesting compared to the other one and update the weight 2847 // of the copies accordingly. However, this would only work if 2848 // we would gather all the copies first then coalesce, whereas 2849 // right now we interleave both actions. 2850 // For now, just consider the copies that are in the same block. 2851 if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB) 2852 continue; 2853 unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg; 2854 isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg, 2855 OtherSubReg); 2856 if (OtherReg == SrcReg) 2857 OtherReg = OtherSrcReg; 2858 // Check if OtherReg is a non-terminal. 2859 if (TargetRegisterInfo::isPhysicalRegister(OtherReg) || 2860 isTerminalReg(OtherReg, MI, MRI)) 2861 continue; 2862 // Check that OtherReg interfere with DstReg. 2863 if (LIS->getInterval(OtherReg).overlaps(DstLI)) { 2864 DEBUG(dbgs() << "Apply terminal rule for: " << PrintReg(DstReg) << '\n'); 2865 return true; 2866 } 2867 } 2868 return false; 2869 } 2870 2871 void 2872 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) { 2873 DEBUG(dbgs() << MBB->getName() << ":\n"); 2874 2875 // Collect all copy-like instructions in MBB. Don't start coalescing anything 2876 // yet, it might invalidate the iterator. 2877 const unsigned PrevSize = WorkList.size(); 2878 if (JoinGlobalCopies) { 2879 SmallVector<MachineInstr*, 2> LocalTerminals; 2880 SmallVector<MachineInstr*, 2> GlobalTerminals; 2881 // Coalesce copies bottom-up to coalesce local defs before local uses. They 2882 // are not inherently easier to resolve, but slightly preferable until we 2883 // have local live range splitting. In particular this is required by 2884 // cmp+jmp macro fusion. 2885 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); 2886 MII != E; ++MII) { 2887 if (!MII->isCopyLike()) 2888 continue; 2889 bool ApplyTerminalRule = applyTerminalRule(*MII); 2890 if (isLocalCopy(&(*MII), LIS)) { 2891 if (ApplyTerminalRule) 2892 LocalTerminals.push_back(&(*MII)); 2893 else 2894 LocalWorkList.push_back(&(*MII)); 2895 } else { 2896 if (ApplyTerminalRule) 2897 GlobalTerminals.push_back(&(*MII)); 2898 else 2899 WorkList.push_back(&(*MII)); 2900 } 2901 } 2902 // Append the copies evicted by the terminal rule at the end of the list. 2903 LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end()); 2904 WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end()); 2905 } 2906 else { 2907 SmallVector<MachineInstr*, 2> Terminals; 2908 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); 2909 MII != E; ++MII) 2910 if (MII->isCopyLike()) { 2911 if (applyTerminalRule(*MII)) 2912 Terminals.push_back(&(*MII)); 2913 else 2914 WorkList.push_back(MII); 2915 } 2916 // Append the copies evicted by the terminal rule at the end of the list. 2917 WorkList.append(Terminals.begin(), Terminals.end()); 2918 } 2919 // Try coalescing the collected copies immediately, and remove the nulls. 2920 // This prevents the WorkList from getting too large since most copies are 2921 // joinable on the first attempt. 2922 MutableArrayRef<MachineInstr*> 2923 CurrList(WorkList.begin() + PrevSize, WorkList.end()); 2924 if (copyCoalesceWorkList(CurrList)) 2925 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(), 2926 (MachineInstr*)nullptr), WorkList.end()); 2927 } 2928 2929 void RegisterCoalescer::coalesceLocals() { 2930 copyCoalesceWorkList(LocalWorkList); 2931 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) { 2932 if (LocalWorkList[j]) 2933 WorkList.push_back(LocalWorkList[j]); 2934 } 2935 LocalWorkList.clear(); 2936 } 2937 2938 void RegisterCoalescer::joinAllIntervals() { 2939 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n"); 2940 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around."); 2941 2942 std::vector<MBBPriorityInfo> MBBs; 2943 MBBs.reserve(MF->size()); 2944 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) { 2945 MachineBasicBlock *MBB = &*I; 2946 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB), 2947 JoinSplitEdges && isSplitEdge(MBB))); 2948 } 2949 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority); 2950 2951 // Coalesce intervals in MBB priority order. 2952 unsigned CurrDepth = UINT_MAX; 2953 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) { 2954 // Try coalescing the collected local copies for deeper loops. 2955 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) { 2956 coalesceLocals(); 2957 CurrDepth = MBBs[i].Depth; 2958 } 2959 copyCoalesceInMBB(MBBs[i].MBB); 2960 } 2961 coalesceLocals(); 2962 2963 // Joining intervals can allow other intervals to be joined. Iteratively join 2964 // until we make no progress. 2965 while (copyCoalesceWorkList(WorkList)) 2966 /* empty */ ; 2967 } 2968 2969 void RegisterCoalescer::releaseMemory() { 2970 ErasedInstrs.clear(); 2971 WorkList.clear(); 2972 DeadDefs.clear(); 2973 InflateRegs.clear(); 2974 } 2975 2976 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) { 2977 MF = &fn; 2978 MRI = &fn.getRegInfo(); 2979 TM = &fn.getTarget(); 2980 const TargetSubtargetInfo &STI = fn.getSubtarget(); 2981 TRI = STI.getRegisterInfo(); 2982 TII = STI.getInstrInfo(); 2983 LIS = &getAnalysis<LiveIntervals>(); 2984 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 2985 Loops = &getAnalysis<MachineLoopInfo>(); 2986 if (EnableGlobalCopies == cl::BOU_UNSET) 2987 JoinGlobalCopies = STI.enableJoinGlobalCopies(); 2988 else 2989 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE); 2990 2991 // The MachineScheduler does not currently require JoinSplitEdges. This will 2992 // either be enabled unconditionally or replaced by a more general live range 2993 // splitting optimization. 2994 JoinSplitEdges = EnableJoinSplits; 2995 2996 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n" 2997 << "********** Function: " << MF->getName() << '\n'); 2998 2999 if (VerifyCoalescing) 3000 MF->verify(this, "Before register coalescing"); 3001 3002 RegClassInfo.runOnMachineFunction(fn); 3003 3004 // Join (coalesce) intervals if requested. 3005 if (EnableJoining) 3006 joinAllIntervals(); 3007 3008 // After deleting a lot of copies, register classes may be less constrained. 3009 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 -> 3010 // DPR inflation. 3011 array_pod_sort(InflateRegs.begin(), InflateRegs.end()); 3012 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()), 3013 InflateRegs.end()); 3014 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n"); 3015 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) { 3016 unsigned Reg = InflateRegs[i]; 3017 if (MRI->reg_nodbg_empty(Reg)) 3018 continue; 3019 if (MRI->recomputeRegClass(Reg)) { 3020 DEBUG(dbgs() << PrintReg(Reg) << " inflated to " 3021 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n'); 3022 ++NumInflated; 3023 3024 LiveInterval &LI = LIS->getInterval(Reg); 3025 if (LI.hasSubRanges()) { 3026 // If the inflated register class does not support subregisters anymore 3027 // remove the subranges. 3028 if (!MRI->shouldTrackSubRegLiveness(Reg)) { 3029 LI.clearSubRanges(); 3030 } else { 3031 #ifndef NDEBUG 3032 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg); 3033 // If subranges are still supported, then the same subregs 3034 // should still be supported. 3035 for (LiveInterval::SubRange &S : LI.subranges()) { 3036 assert((S.LaneMask & ~MaxMask) == 0); 3037 } 3038 #endif 3039 } 3040 } 3041 } 3042 } 3043 3044 DEBUG(dump()); 3045 if (VerifyCoalescing) 3046 MF->verify(this, "After register coalescing"); 3047 return true; 3048 } 3049 3050 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const { 3051 LIS->print(O, m); 3052 } 3053