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