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