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