1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the generic RegisterCoalescer interface which 10 // is used as the common interface used by all clients and 11 // implementations of register coalescing. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "RegisterCoalescer.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/LiveInterval.h" 25 #include "llvm/CodeGen/LiveIntervals.h" 26 #include "llvm/CodeGen/LiveRangeEdit.h" 27 #include "llvm/CodeGen/MachineBasicBlock.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineFunctionPass.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineInstrBuilder.h" 32 #include "llvm/CodeGen/MachineLoopInfo.h" 33 #include "llvm/CodeGen/MachineOperand.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/Passes.h" 36 #include "llvm/CodeGen/RegisterClassInfo.h" 37 #include "llvm/CodeGen/SlotIndexes.h" 38 #include "llvm/CodeGen/TargetInstrInfo.h" 39 #include "llvm/CodeGen/TargetOpcodes.h" 40 #include "llvm/CodeGen/TargetRegisterInfo.h" 41 #include "llvm/CodeGen/TargetSubtargetInfo.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/InitializePasses.h" 44 #include "llvm/MC/LaneBitmask.h" 45 #include "llvm/MC/MCInstrDesc.h" 46 #include "llvm/MC/MCRegisterInfo.h" 47 #include "llvm/Pass.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Compiler.h" 50 #include "llvm/Support/Debug.h" 51 #include "llvm/Support/ErrorHandling.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include <algorithm> 54 #include <cassert> 55 #include <iterator> 56 #include <limits> 57 #include <tuple> 58 #include <utility> 59 #include <vector> 60 61 using namespace llvm; 62 63 #define DEBUG_TYPE "regalloc" 64 65 STATISTIC(numJoins , "Number of interval joins performed"); 66 STATISTIC(numCrossRCs , "Number of cross class joins performed"); 67 STATISTIC(numCommutes , "Number of instruction commuting performed"); 68 STATISTIC(numExtends , "Number of copies extended"); 69 STATISTIC(NumReMats , "Number of instructions re-materialized"); 70 STATISTIC(NumInflated , "Number of register classes inflated"); 71 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested"); 72 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved"); 73 STATISTIC(NumShrinkToUses, "Number of shrinkToUses called"); 74 75 static cl::opt<bool> EnableJoining("join-liveintervals", 76 cl::desc("Coalesce copies (default=true)"), 77 cl::init(true), cl::Hidden); 78 79 static cl::opt<bool> UseTerminalRule("terminal-rule", 80 cl::desc("Apply the terminal rule"), 81 cl::init(false), cl::Hidden); 82 83 /// Temporary flag to test critical edge unsplitting. 84 static cl::opt<bool> 85 EnableJoinSplits("join-splitedges", 86 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden); 87 88 /// Temporary flag to test global copy optimization. 89 static cl::opt<cl::boolOrDefault> 90 EnableGlobalCopies("join-globalcopies", 91 cl::desc("Coalesce copies that span blocks (default=subtarget)"), 92 cl::init(cl::BOU_UNSET), cl::Hidden); 93 94 static cl::opt<bool> 95 VerifyCoalescing("verify-coalescing", 96 cl::desc("Verify machine instrs before and after register coalescing"), 97 cl::Hidden); 98 99 static cl::opt<unsigned> LateRematUpdateThreshold( 100 "late-remat-update-threshold", cl::Hidden, 101 cl::desc("During rematerialization for a copy, if the def instruction has " 102 "many other copy uses to be rematerialized, delay the multiple " 103 "separate live interval update work and do them all at once after " 104 "all those rematerialization are done. It will save a lot of " 105 "repeated work. "), 106 cl::init(100)); 107 108 static cl::opt<unsigned> LargeIntervalSizeThreshold( 109 "large-interval-size-threshold", cl::Hidden, 110 cl::desc("If the valnos size of an interval is larger than the threshold, " 111 "it is regarded as a large interval. "), 112 cl::init(100)); 113 114 static cl::opt<unsigned> LargeIntervalFreqThreshold( 115 "large-interval-freq-threshold", cl::Hidden, 116 cl::desc("For a large interval, if it is coalesed with other live " 117 "intervals many times more than the threshold, stop its " 118 "coalescing to control the compile time. "), 119 cl::init(100)); 120 121 namespace { 122 123 class JoinVals; 124 125 class RegisterCoalescer : public MachineFunctionPass, 126 private LiveRangeEdit::Delegate { 127 MachineFunction* MF = nullptr; 128 MachineRegisterInfo* MRI = nullptr; 129 const TargetRegisterInfo* TRI = nullptr; 130 const TargetInstrInfo* TII = nullptr; 131 LiveIntervals *LIS = nullptr; 132 const MachineLoopInfo* Loops = nullptr; 133 AliasAnalysis *AA = nullptr; 134 RegisterClassInfo RegClassInfo; 135 136 /// Debug variable location tracking -- for each VReg, maintain an 137 /// ordered-by-slot-index set of DBG_VALUEs, to help quick 138 /// identification of whether coalescing may change location validity. 139 using DbgValueLoc = std::pair<SlotIndex, MachineInstr*>; 140 DenseMap<unsigned, std::vector<DbgValueLoc>> DbgVRegToValues; 141 142 /// VRegs may be repeatedly coalesced, and have many DBG_VALUEs attached. 143 /// To avoid repeatedly merging sets of DbgValueLocs, instead record 144 /// which vregs have been coalesced, and where to. This map is from 145 /// vreg => {set of vregs merged in}. 146 DenseMap<unsigned, SmallVector<unsigned, 4>> DbgMergedVRegNums; 147 148 /// A LaneMask to remember on which subregister live ranges we need to call 149 /// shrinkToUses() later. 150 LaneBitmask ShrinkMask; 151 152 /// True if the main range of the currently coalesced intervals should be 153 /// checked for smaller live intervals. 154 bool ShrinkMainRange = false; 155 156 /// True if the coalescer should aggressively coalesce global copies 157 /// in favor of keeping local copies. 158 bool JoinGlobalCopies = false; 159 160 /// True if the coalescer should aggressively coalesce fall-thru 161 /// blocks exclusively containing copies. 162 bool JoinSplitEdges = false; 163 164 /// Copy instructions yet to be coalesced. 165 SmallVector<MachineInstr*, 8> WorkList; 166 SmallVector<MachineInstr*, 8> LocalWorkList; 167 168 /// Set of instruction pointers that have been erased, and 169 /// that may be present in WorkList. 170 SmallPtrSet<MachineInstr*, 8> ErasedInstrs; 171 172 /// Dead instructions that are about to be deleted. 173 SmallVector<MachineInstr*, 8> DeadDefs; 174 175 /// Virtual registers to be considered for register class inflation. 176 SmallVector<unsigned, 8> InflateRegs; 177 178 /// The collection of live intervals which should have been updated 179 /// immediately after rematerialiation but delayed until 180 /// lateLiveIntervalUpdate is called. 181 DenseSet<unsigned> ToBeUpdated; 182 183 /// Record how many times the large live interval with many valnos 184 /// has been tried to join with other live interval. 185 DenseMap<unsigned, unsigned long> LargeLIVisitCounter; 186 187 /// Recursively eliminate dead defs in DeadDefs. 188 void eliminateDeadDefs(); 189 190 /// LiveRangeEdit callback for eliminateDeadDefs(). 191 void LRE_WillEraseInstruction(MachineInstr *MI) override; 192 193 /// Coalesce the LocalWorkList. 194 void coalesceLocals(); 195 196 /// Join compatible live intervals 197 void joinAllIntervals(); 198 199 /// Coalesce copies in the specified MBB, putting 200 /// copies that cannot yet be coalesced into WorkList. 201 void copyCoalesceInMBB(MachineBasicBlock *MBB); 202 203 /// Tries to coalesce all copies in CurrList. Returns true if any progress 204 /// was made. 205 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList); 206 207 /// If one def has many copy like uses, and those copy uses are all 208 /// rematerialized, the live interval update needed for those 209 /// rematerializations will be delayed and done all at once instead 210 /// of being done multiple times. This is to save compile cost because 211 /// live interval update is costly. 212 void lateLiveIntervalUpdate(); 213 214 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the 215 /// src/dst of the copy instruction CopyMI. This returns true if the copy 216 /// was successfully coalesced away. If it is not currently possible to 217 /// coalesce this interval, but it may be possible if other things get 218 /// coalesced, then it returns true by reference in 'Again'. 219 bool joinCopy(MachineInstr *CopyMI, bool &Again); 220 221 /// Attempt to join these two intervals. On failure, this 222 /// returns false. The output "SrcInt" will not have been modified, so we 223 /// can use this information below to update aliases. 224 bool joinIntervals(CoalescerPair &CP); 225 226 /// Attempt joining two virtual registers. Return true on success. 227 bool joinVirtRegs(CoalescerPair &CP); 228 229 /// If a live interval has many valnos and is coalesced with other 230 /// live intervals many times, we regard such live interval as having 231 /// high compile time cost. 232 bool isHighCostLiveInterval(LiveInterval &LI); 233 234 /// Attempt joining with a reserved physreg. 235 bool joinReservedPhysReg(CoalescerPair &CP); 236 237 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI. 238 /// Subranges in @p LI which only partially interfere with the desired 239 /// LaneMask are split as necessary. @p LaneMask are the lanes that 240 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange 241 /// lanemasks already adjusted to the coalesced register. 242 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge, 243 LaneBitmask LaneMask, CoalescerPair &CP, 244 unsigned DstIdx); 245 246 /// Join the liveranges of two subregisters. Joins @p RRange into 247 /// @p LRange, @p RRange may be invalid afterwards. 248 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange, 249 LaneBitmask LaneMask, const CoalescerPair &CP); 250 251 /// We found a non-trivially-coalescable copy. If the source value number is 252 /// defined by a copy from the destination reg see if we can merge these two 253 /// destination reg valno# into a single value number, eliminating a copy. 254 /// This returns true if an interval was modified. 255 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI); 256 257 /// Return true if there are definitions of IntB 258 /// other than BValNo val# that can reach uses of AValno val# of IntA. 259 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB, 260 VNInfo *AValNo, VNInfo *BValNo); 261 262 /// We found a non-trivially-coalescable copy. 263 /// If the source value number is defined by a commutable instruction and 264 /// its other operand is coalesced to the copy dest register, see if we 265 /// can transform the copy into a noop by commuting the definition. 266 /// This returns a pair of two flags: 267 /// - the first element is true if an interval was modified, 268 /// - the second element is true if the destination interval needs 269 /// to be shrunk after deleting the copy. 270 std::pair<bool,bool> removeCopyByCommutingDef(const CoalescerPair &CP, 271 MachineInstr *CopyMI); 272 273 /// We found a copy which can be moved to its less frequent predecessor. 274 bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI); 275 276 /// If the source of a copy is defined by a 277 /// trivial computation, replace the copy by rematerialize the definition. 278 bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI, 279 bool &IsDefCopy); 280 281 /// Return true if a copy involving a physreg should be joined. 282 bool canJoinPhys(const CoalescerPair &CP); 283 284 /// Replace all defs and uses of SrcReg to DstReg and update the subregister 285 /// number if it is not zero. If DstReg is a physical register and the 286 /// existing subregister number of the def / use being updated is not zero, 287 /// make sure to set it to the correct physical subregister. 288 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx); 289 290 /// If the given machine operand reads only undefined lanes add an undef 291 /// flag. 292 /// This can happen when undef uses were previously concealed by a copy 293 /// which we coalesced. Example: 294 /// %0:sub0<def,read-undef> = ... 295 /// %1 = COPY %0 <-- Coalescing COPY reveals undef 296 /// = use %1:sub1 <-- hidden undef use 297 void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx, 298 MachineOperand &MO, unsigned SubRegIdx); 299 300 /// Handle copies of undef values. If the undef value is an incoming 301 /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF. 302 /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise, 303 /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point). 304 MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI); 305 306 /// Check whether or not we should apply the terminal rule on the 307 /// destination (Dst) of \p Copy. 308 /// When the terminal rule applies, Copy is not profitable to 309 /// coalesce. 310 /// Dst is terminal if it has exactly one affinity (Dst, Src) and 311 /// at least one interference (Dst, Dst2). If Dst is terminal, the 312 /// terminal rule consists in checking that at least one of 313 /// interfering node, say Dst2, has an affinity of equal or greater 314 /// weight with Src. 315 /// In that case, Dst2 and Dst will not be able to be both coalesced 316 /// with Src. Since Dst2 exposes more coalescing opportunities than 317 /// Dst, we can drop \p Copy. 318 bool applyTerminalRule(const MachineInstr &Copy) const; 319 320 /// Wrapper method for \see LiveIntervals::shrinkToUses. 321 /// This method does the proper fixing of the live-ranges when the afore 322 /// mentioned method returns true. 323 void shrinkToUses(LiveInterval *LI, 324 SmallVectorImpl<MachineInstr * > *Dead = nullptr) { 325 NumShrinkToUses++; 326 if (LIS->shrinkToUses(LI, Dead)) { 327 /// Check whether or not \p LI is composed by multiple connected 328 /// components and if that is the case, fix that. 329 SmallVector<LiveInterval*, 8> SplitLIs; 330 LIS->splitSeparateComponents(*LI, SplitLIs); 331 } 332 } 333 334 /// Wrapper Method to do all the necessary work when an Instruction is 335 /// deleted. 336 /// Optimizations should use this to make sure that deleted instructions 337 /// are always accounted for. 338 void deleteInstr(MachineInstr* MI) { 339 ErasedInstrs.insert(MI); 340 LIS->RemoveMachineInstrFromMaps(*MI); 341 MI->eraseFromParent(); 342 } 343 344 /// Walk over function and initialize the DbgVRegToValues map. 345 void buildVRegToDbgValueMap(MachineFunction &MF); 346 347 /// Test whether, after merging, any DBG_VALUEs would refer to a 348 /// different value number than before merging, and whether this can 349 /// be resolved. If not, mark the DBG_VALUE as being undef. 350 void checkMergingChangesDbgValues(CoalescerPair &CP, LiveRange &LHS, 351 JoinVals &LHSVals, LiveRange &RHS, 352 JoinVals &RHSVals); 353 354 void checkMergingChangesDbgValuesImpl(unsigned Reg, LiveRange &OtherRange, 355 LiveRange &RegRange, JoinVals &Vals2); 356 357 public: 358 static char ID; ///< Class identification, replacement for typeinfo 359 360 RegisterCoalescer() : MachineFunctionPass(ID) { 361 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); 362 } 363 364 void getAnalysisUsage(AnalysisUsage &AU) const override; 365 366 void releaseMemory() override; 367 368 /// This is the pass entry point. 369 bool runOnMachineFunction(MachineFunction&) override; 370 371 /// Implement the dump method. 372 void print(raw_ostream &O, const Module* = nullptr) const override; 373 }; 374 375 } // end anonymous namespace 376 377 char RegisterCoalescer::ID = 0; 378 379 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID; 380 381 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing", 382 "Simple Register Coalescing", false, false) 383 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 384 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 385 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 386 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 387 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing", 388 "Simple Register Coalescing", false, false) 389 390 LLVM_NODISCARD static bool isMoveInstr(const TargetRegisterInfo &tri, 391 const MachineInstr *MI, unsigned &Src, 392 unsigned &Dst, unsigned &SrcSub, 393 unsigned &DstSub) { 394 if (MI->isCopy()) { 395 Dst = MI->getOperand(0).getReg(); 396 DstSub = MI->getOperand(0).getSubReg(); 397 Src = MI->getOperand(1).getReg(); 398 SrcSub = MI->getOperand(1).getSubReg(); 399 } else if (MI->isSubregToReg()) { 400 Dst = MI->getOperand(0).getReg(); 401 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(), 402 MI->getOperand(3).getImm()); 403 Src = MI->getOperand(2).getReg(); 404 SrcSub = MI->getOperand(2).getSubReg(); 405 } else 406 return false; 407 return true; 408 } 409 410 /// Return true if this block should be vacated by the coalescer to eliminate 411 /// branches. The important cases to handle in the coalescer are critical edges 412 /// split during phi elimination which contain only copies. Simple blocks that 413 /// contain non-branches should also be vacated, but this can be handled by an 414 /// earlier pass similar to early if-conversion. 415 static bool isSplitEdge(const MachineBasicBlock *MBB) { 416 if (MBB->pred_size() != 1 || MBB->succ_size() != 1) 417 return false; 418 419 for (const auto &MI : *MBB) { 420 if (!MI.isCopyLike() && !MI.isUnconditionalBranch()) 421 return false; 422 } 423 return true; 424 } 425 426 bool CoalescerPair::setRegisters(const MachineInstr *MI) { 427 SrcReg = DstReg = 0; 428 SrcIdx = DstIdx = 0; 429 NewRC = nullptr; 430 Flipped = CrossClass = false; 431 432 unsigned Src, Dst, SrcSub, DstSub; 433 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) 434 return false; 435 Partial = SrcSub || DstSub; 436 437 // If one register is a physreg, it must be Dst. 438 if (Register::isPhysicalRegister(Src)) { 439 if (Register::isPhysicalRegister(Dst)) 440 return false; 441 std::swap(Src, Dst); 442 std::swap(SrcSub, DstSub); 443 Flipped = true; 444 } 445 446 const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo(); 447 448 if (Register::isPhysicalRegister(Dst)) { 449 // Eliminate DstSub on a physreg. 450 if (DstSub) { 451 Dst = TRI.getSubReg(Dst, DstSub); 452 if (!Dst) return false; 453 DstSub = 0; 454 } 455 456 // Eliminate SrcSub by picking a corresponding Dst superregister. 457 if (SrcSub) { 458 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src)); 459 if (!Dst) return false; 460 } else if (!MRI.getRegClass(Src)->contains(Dst)) { 461 return false; 462 } 463 } else { 464 // Both registers are virtual. 465 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src); 466 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst); 467 468 // Both registers have subreg indices. 469 if (SrcSub && DstSub) { 470 // Copies between different sub-registers are never coalescable. 471 if (Src == Dst && SrcSub != DstSub) 472 return false; 473 474 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub, 475 SrcIdx, DstIdx); 476 if (!NewRC) 477 return false; 478 } else if (DstSub) { 479 // SrcReg will be merged with a sub-register of DstReg. 480 SrcIdx = DstSub; 481 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub); 482 } else if (SrcSub) { 483 // DstReg will be merged with a sub-register of SrcReg. 484 DstIdx = SrcSub; 485 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub); 486 } else { 487 // This is a straight copy without sub-registers. 488 NewRC = TRI.getCommonSubClass(DstRC, SrcRC); 489 } 490 491 // The combined constraint may be impossible to satisfy. 492 if (!NewRC) 493 return false; 494 495 // Prefer SrcReg to be a sub-register of DstReg. 496 // FIXME: Coalescer should support subregs symmetrically. 497 if (DstIdx && !SrcIdx) { 498 std::swap(Src, Dst); 499 std::swap(SrcIdx, DstIdx); 500 Flipped = !Flipped; 501 } 502 503 CrossClass = NewRC != DstRC || NewRC != SrcRC; 504 } 505 // Check our invariants 506 assert(Register::isVirtualRegister(Src) && "Src must be virtual"); 507 assert(!(Register::isPhysicalRegister(Dst) && DstSub) && 508 "Cannot have a physical SubIdx"); 509 SrcReg = Src; 510 DstReg = Dst; 511 return true; 512 } 513 514 bool CoalescerPair::flip() { 515 if (Register::isPhysicalRegister(DstReg)) 516 return false; 517 std::swap(SrcReg, DstReg); 518 std::swap(SrcIdx, DstIdx); 519 Flipped = !Flipped; 520 return true; 521 } 522 523 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const { 524 if (!MI) 525 return false; 526 unsigned Src, Dst, SrcSub, DstSub; 527 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) 528 return false; 529 530 // Find the virtual register that is SrcReg. 531 if (Dst == SrcReg) { 532 std::swap(Src, Dst); 533 std::swap(SrcSub, DstSub); 534 } else if (Src != SrcReg) { 535 return false; 536 } 537 538 // Now check that Dst matches DstReg. 539 if (Register::isPhysicalRegister(DstReg)) { 540 if (!Register::isPhysicalRegister(Dst)) 541 return false; 542 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state."); 543 // DstSub could be set for a physreg from INSERT_SUBREG. 544 if (DstSub) 545 Dst = TRI.getSubReg(Dst, DstSub); 546 // Full copy of Src. 547 if (!SrcSub) 548 return DstReg == Dst; 549 // This is a partial register copy. Check that the parts match. 550 return TRI.getSubReg(DstReg, SrcSub) == Dst; 551 } else { 552 // DstReg is virtual. 553 if (DstReg != Dst) 554 return false; 555 // Registers match, do the subregisters line up? 556 return TRI.composeSubRegIndices(SrcIdx, SrcSub) == 557 TRI.composeSubRegIndices(DstIdx, DstSub); 558 } 559 } 560 561 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const { 562 AU.setPreservesCFG(); 563 AU.addRequired<AAResultsWrapperPass>(); 564 AU.addRequired<LiveIntervals>(); 565 AU.addPreserved<LiveIntervals>(); 566 AU.addPreserved<SlotIndexes>(); 567 AU.addRequired<MachineLoopInfo>(); 568 AU.addPreserved<MachineLoopInfo>(); 569 AU.addPreservedID(MachineDominatorsID); 570 MachineFunctionPass::getAnalysisUsage(AU); 571 } 572 573 void RegisterCoalescer::eliminateDeadDefs() { 574 SmallVector<unsigned, 8> NewRegs; 575 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS, 576 nullptr, this).eliminateDeadDefs(DeadDefs); 577 } 578 579 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) { 580 // MI may be in WorkList. Make sure we don't visit it. 581 ErasedInstrs.insert(MI); 582 } 583 584 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP, 585 MachineInstr *CopyMI) { 586 assert(!CP.isPartial() && "This doesn't work for partial copies."); 587 assert(!CP.isPhys() && "This doesn't work for physreg copies."); 588 589 LiveInterval &IntA = 590 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 591 LiveInterval &IntB = 592 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 593 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); 594 595 // We have a non-trivially-coalescable copy with IntA being the source and 596 // IntB being the dest, thus this defines a value number in IntB. If the 597 // source value number (in IntA) is defined by a copy from B, see if we can 598 // merge these two pieces of B into a single value number, eliminating a copy. 599 // For example: 600 // 601 // A3 = B0 602 // ... 603 // B1 = A3 <- this copy 604 // 605 // In this case, B0 can be extended to where the B1 copy lives, allowing the 606 // B1 value number to be replaced with B0 (which simplifies the B 607 // liveinterval). 608 609 // BValNo is a value number in B that is defined by a copy from A. 'B1' in 610 // the example above. 611 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx); 612 if (BS == IntB.end()) return false; 613 VNInfo *BValNo = BS->valno; 614 615 // Get the location that B is defined at. Two options: either this value has 616 // an unknown definition point or it is defined at CopyIdx. If unknown, we 617 // can't process it. 618 if (BValNo->def != CopyIdx) return false; 619 620 // AValNo is the value number in A that defines the copy, A3 in the example. 621 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true); 622 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx); 623 // The live segment might not exist after fun with physreg coalescing. 624 if (AS == IntA.end()) return false; 625 VNInfo *AValNo = AS->valno; 626 627 // If AValNo is defined as a copy from IntB, we can potentially process this. 628 // Get the instruction that defines this value number. 629 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def); 630 // Don't allow any partial copies, even if isCoalescable() allows them. 631 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy()) 632 return false; 633 634 // Get the Segment in IntB that this value number starts with. 635 LiveInterval::iterator ValS = 636 IntB.FindSegmentContaining(AValNo->def.getPrevSlot()); 637 if (ValS == IntB.end()) 638 return false; 639 640 // Make sure that the end of the live segment is inside the same block as 641 // CopyMI. 642 MachineInstr *ValSEndInst = 643 LIS->getInstructionFromIndex(ValS->end.getPrevSlot()); 644 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent()) 645 return false; 646 647 // Okay, we now know that ValS ends in the same block that the CopyMI 648 // live-range starts. If there are no intervening live segments between them 649 // in IntB, we can merge them. 650 if (ValS+1 != BS) return false; 651 652 LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg, TRI)); 653 654 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start; 655 // We are about to delete CopyMI, so need to remove it as the 'instruction 656 // that defines this value #'. Update the valnum with the new defining 657 // instruction #. 658 BValNo->def = FillerStart; 659 660 // Okay, we can merge them. We need to insert a new liverange: 661 // [ValS.end, BS.begin) of either value number, then we merge the 662 // two value numbers. 663 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo)); 664 665 // Okay, merge "B1" into the same value number as "B0". 666 if (BValNo != ValS->valno) 667 IntB.MergeValueNumberInto(BValNo, ValS->valno); 668 669 // Do the same for the subregister segments. 670 for (LiveInterval::SubRange &S : IntB.subranges()) { 671 // Check for SubRange Segments of the form [1234r,1234d:0) which can be 672 // removed to prevent creating bogus SubRange Segments. 673 LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx); 674 if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) { 675 S.removeSegment(*SS, true); 676 continue; 677 } 678 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx); 679 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo)); 680 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot()); 681 if (SubBValNo != SubValSNo) 682 S.MergeValueNumberInto(SubBValNo, SubValSNo); 683 } 684 685 LLVM_DEBUG(dbgs() << " result = " << IntB << '\n'); 686 687 // If the source instruction was killing the source register before the 688 // merge, unset the isKill marker given the live range has been extended. 689 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true); 690 if (UIdx != -1) { 691 ValSEndInst->getOperand(UIdx).setIsKill(false); 692 } 693 694 // Rewrite the copy. 695 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI); 696 // If the copy instruction was killing the destination register or any 697 // subrange before the merge trim the live range. 698 bool RecomputeLiveRange = AS->end == CopyIdx; 699 if (!RecomputeLiveRange) { 700 for (LiveInterval::SubRange &S : IntA.subranges()) { 701 LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx); 702 if (SS != S.end() && SS->end == CopyIdx) { 703 RecomputeLiveRange = true; 704 break; 705 } 706 } 707 } 708 if (RecomputeLiveRange) 709 shrinkToUses(&IntA); 710 711 ++numExtends; 712 return true; 713 } 714 715 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA, 716 LiveInterval &IntB, 717 VNInfo *AValNo, 718 VNInfo *BValNo) { 719 // If AValNo has PHI kills, conservatively assume that IntB defs can reach 720 // the PHI values. 721 if (LIS->hasPHIKill(IntA, AValNo)) 722 return true; 723 724 for (LiveRange::Segment &ASeg : IntA.segments) { 725 if (ASeg.valno != AValNo) continue; 726 LiveInterval::iterator BI = llvm::upper_bound(IntB, ASeg.start); 727 if (BI != IntB.begin()) 728 --BI; 729 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) { 730 if (BI->valno == BValNo) 731 continue; 732 if (BI->start <= ASeg.start && BI->end > ASeg.start) 733 return true; 734 if (BI->start > ASeg.start && BI->start < ASeg.end) 735 return true; 736 } 737 } 738 return false; 739 } 740 741 /// Copy segments with value number @p SrcValNo from liverange @p Src to live 742 /// range @Dst and use value number @p DstValNo there. 743 static std::pair<bool,bool> 744 addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src, 745 const VNInfo *SrcValNo) { 746 bool Changed = false; 747 bool MergedWithDead = false; 748 for (const LiveRange::Segment &S : Src.segments) { 749 if (S.valno != SrcValNo) 750 continue; 751 // This is adding a segment from Src that ends in a copy that is about 752 // to be removed. This segment is going to be merged with a pre-existing 753 // segment in Dst. This works, except in cases when the corresponding 754 // segment in Dst is dead. For example: adding [192r,208r:1) from Src 755 // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst. 756 // Recognized such cases, so that the segments can be shrunk. 757 LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo); 758 LiveRange::Segment &Merged = *Dst.addSegment(Added); 759 if (Merged.end.isDead()) 760 MergedWithDead = true; 761 Changed = true; 762 } 763 return std::make_pair(Changed, MergedWithDead); 764 } 765 766 std::pair<bool,bool> 767 RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP, 768 MachineInstr *CopyMI) { 769 assert(!CP.isPhys()); 770 771 LiveInterval &IntA = 772 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 773 LiveInterval &IntB = 774 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 775 776 // We found a non-trivially-coalescable copy with IntA being the source and 777 // IntB being the dest, thus this defines a value number in IntB. If the 778 // source value number (in IntA) is defined by a commutable instruction and 779 // its other operand is coalesced to the copy dest register, see if we can 780 // transform the copy into a noop by commuting the definition. For example, 781 // 782 // A3 = op A2 killed B0 783 // ... 784 // B1 = A3 <- this copy 785 // ... 786 // = op A3 <- more uses 787 // 788 // ==> 789 // 790 // B2 = op B0 killed A2 791 // ... 792 // B1 = B2 <- now an identity copy 793 // ... 794 // = op B2 <- more uses 795 796 // BValNo is a value number in B that is defined by a copy from A. 'B1' in 797 // the example above. 798 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); 799 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx); 800 assert(BValNo != nullptr && BValNo->def == CopyIdx); 801 802 // AValNo is the value number in A that defines the copy, A3 in the example. 803 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true)); 804 assert(AValNo && !AValNo->isUnused() && "COPY source not live"); 805 if (AValNo->isPHIDef()) 806 return { false, false }; 807 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def); 808 if (!DefMI) 809 return { false, false }; 810 if (!DefMI->isCommutable()) 811 return { false, false }; 812 // If DefMI is a two-address instruction then commuting it will change the 813 // destination register. 814 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg); 815 assert(DefIdx != -1); 816 unsigned UseOpIdx; 817 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx)) 818 return { false, false }; 819 820 // FIXME: The code below tries to commute 'UseOpIdx' operand with some other 821 // commutable operand which is expressed by 'CommuteAnyOperandIndex'value 822 // passed to the method. That _other_ operand is chosen by 823 // the findCommutedOpIndices() method. 824 // 825 // That is obviously an area for improvement in case of instructions having 826 // more than 2 operands. For example, if some instruction has 3 commutable 827 // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3, 828 // op#2<->op#3) of commute transformation should be considered/tried here. 829 unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex; 830 if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx)) 831 return { false, false }; 832 833 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx); 834 Register NewReg = NewDstMO.getReg(); 835 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill()) 836 return { false, false }; 837 838 // Make sure there are no other definitions of IntB that would reach the 839 // uses which the new definition can reach. 840 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo)) 841 return { false, false }; 842 843 // If some of the uses of IntA.reg is already coalesced away, return false. 844 // It's not possible to determine whether it's safe to perform the coalescing. 845 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) { 846 MachineInstr *UseMI = MO.getParent(); 847 unsigned OpNo = &MO - &UseMI->getOperand(0); 848 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI); 849 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx); 850 if (US == IntA.end() || US->valno != AValNo) 851 continue; 852 // If this use is tied to a def, we can't rewrite the register. 853 if (UseMI->isRegTiedToDefOperand(OpNo)) 854 return { false, false }; 855 } 856 857 LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t' 858 << *DefMI); 859 860 // At this point we have decided that it is legal to do this 861 // transformation. Start by commuting the instruction. 862 MachineBasicBlock *MBB = DefMI->getParent(); 863 MachineInstr *NewMI = 864 TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx); 865 if (!NewMI) 866 return { false, false }; 867 if (Register::isVirtualRegister(IntA.reg) && 868 Register::isVirtualRegister(IntB.reg) && 869 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg))) 870 return { false, false }; 871 if (NewMI != DefMI) { 872 LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI); 873 MachineBasicBlock::iterator Pos = DefMI; 874 MBB->insert(Pos, NewMI); 875 MBB->erase(DefMI); 876 } 877 878 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g. 879 // A = or A, B 880 // ... 881 // B = A 882 // ... 883 // C = killed A 884 // ... 885 // = B 886 887 // Update uses of IntA of the specific Val# with IntB. 888 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg), 889 UE = MRI->use_end(); 890 UI != UE; /* ++UI is below because of possible MI removal */) { 891 MachineOperand &UseMO = *UI; 892 ++UI; 893 if (UseMO.isUndef()) 894 continue; 895 MachineInstr *UseMI = UseMO.getParent(); 896 if (UseMI->isDebugValue()) { 897 // FIXME These don't have an instruction index. Not clear we have enough 898 // info to decide whether to do this replacement or not. For now do it. 899 UseMO.setReg(NewReg); 900 continue; 901 } 902 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true); 903 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx); 904 assert(US != IntA.end() && "Use must be live"); 905 if (US->valno != AValNo) 906 continue; 907 // Kill flags are no longer accurate. They are recomputed after RA. 908 UseMO.setIsKill(false); 909 if (Register::isPhysicalRegister(NewReg)) 910 UseMO.substPhysReg(NewReg, *TRI); 911 else 912 UseMO.setReg(NewReg); 913 if (UseMI == CopyMI) 914 continue; 915 if (!UseMI->isCopy()) 916 continue; 917 if (UseMI->getOperand(0).getReg() != IntB.reg || 918 UseMI->getOperand(0).getSubReg()) 919 continue; 920 921 // This copy will become a noop. If it's defining a new val#, merge it into 922 // BValNo. 923 SlotIndex DefIdx = UseIdx.getRegSlot(); 924 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx); 925 if (!DVNI) 926 continue; 927 LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI); 928 assert(DVNI->def == DefIdx); 929 BValNo = IntB.MergeValueNumberInto(DVNI, BValNo); 930 for (LiveInterval::SubRange &S : IntB.subranges()) { 931 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx); 932 if (!SubDVNI) 933 continue; 934 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx); 935 assert(SubBValNo->def == CopyIdx); 936 S.MergeValueNumberInto(SubDVNI, SubBValNo); 937 } 938 939 deleteInstr(UseMI); 940 } 941 942 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition 943 // is updated. 944 bool ShrinkB = false; 945 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 946 if (IntA.hasSubRanges() || IntB.hasSubRanges()) { 947 if (!IntA.hasSubRanges()) { 948 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg); 949 IntA.createSubRangeFrom(Allocator, Mask, IntA); 950 } else if (!IntB.hasSubRanges()) { 951 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntB.reg); 952 IntB.createSubRangeFrom(Allocator, Mask, IntB); 953 } 954 SlotIndex AIdx = CopyIdx.getRegSlot(true); 955 LaneBitmask MaskA; 956 const SlotIndexes &Indexes = *LIS->getSlotIndexes(); 957 for (LiveInterval::SubRange &SA : IntA.subranges()) { 958 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx); 959 // Even if we are dealing with a full copy, some lanes can 960 // still be undefined. 961 // E.g., 962 // undef A.subLow = ... 963 // B = COPY A <== A.subHigh is undefined here and does 964 // not have a value number. 965 if (!ASubValNo) 966 continue; 967 MaskA |= SA.LaneMask; 968 969 IntB.refineSubRanges( 970 Allocator, SA.LaneMask, 971 [&Allocator, &SA, CopyIdx, ASubValNo, 972 &ShrinkB](LiveInterval::SubRange &SR) { 973 VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator) 974 : SR.getVNInfoAt(CopyIdx); 975 assert(BSubValNo != nullptr); 976 auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo); 977 ShrinkB |= P.second; 978 if (P.first) 979 BSubValNo->def = ASubValNo->def; 980 }, 981 Indexes, *TRI); 982 } 983 // Go over all subranges of IntB that have not been covered by IntA, 984 // and delete the segments starting at CopyIdx. This can happen if 985 // IntA has undef lanes that are defined in IntB. 986 for (LiveInterval::SubRange &SB : IntB.subranges()) { 987 if ((SB.LaneMask & MaskA).any()) 988 continue; 989 if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx)) 990 if (S->start.getBaseIndex() == CopyIdx.getBaseIndex()) 991 SB.removeSegment(*S, true); 992 } 993 } 994 995 BValNo->def = AValNo->def; 996 auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo); 997 ShrinkB |= P.second; 998 LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n'); 999 1000 LIS->removeVRegDefAt(IntA, AValNo->def); 1001 1002 LLVM_DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n'); 1003 ++numCommutes; 1004 return { true, ShrinkB }; 1005 } 1006 1007 /// For copy B = A in BB2, if A is defined by A = B in BB0 which is a 1008 /// predecessor of BB2, and if B is not redefined on the way from A = B 1009 /// in BB0 to B = A in BB2, B = A in BB2 is partially redundant if the 1010 /// execution goes through the path from BB0 to BB2. We may move B = A 1011 /// to the predecessor without such reversed copy. 1012 /// So we will transform the program from: 1013 /// BB0: 1014 /// A = B; BB1: 1015 /// ... ... 1016 /// / \ / 1017 /// BB2: 1018 /// ... 1019 /// B = A; 1020 /// 1021 /// to: 1022 /// 1023 /// BB0: BB1: 1024 /// A = B; ... 1025 /// ... B = A; 1026 /// / \ / 1027 /// BB2: 1028 /// ... 1029 /// 1030 /// A special case is when BB0 and BB2 are the same BB which is the only 1031 /// BB in a loop: 1032 /// BB1: 1033 /// ... 1034 /// BB0/BB2: ---- 1035 /// B = A; | 1036 /// ... | 1037 /// A = B; | 1038 /// |------- 1039 /// | 1040 /// We may hoist B = A from BB0/BB2 to BB1. 1041 /// 1042 /// The major preconditions for correctness to remove such partial 1043 /// redundancy include: 1044 /// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of 1045 /// the PHI is defined by the reversed copy A = B in BB0. 1046 /// 2. No B is referenced from the start of BB2 to B = A. 1047 /// 3. No B is defined from A = B to the end of BB0. 1048 /// 4. BB1 has only one successor. 1049 /// 1050 /// 2 and 4 implicitly ensure B is not live at the end of BB1. 1051 /// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a 1052 /// colder place, which not only prevent endless loop, but also make sure 1053 /// the movement of copy is beneficial. 1054 bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP, 1055 MachineInstr &CopyMI) { 1056 assert(!CP.isPhys()); 1057 if (!CopyMI.isFullCopy()) 1058 return false; 1059 1060 MachineBasicBlock &MBB = *CopyMI.getParent(); 1061 if (MBB.isEHPad()) 1062 return false; 1063 1064 if (MBB.pred_size() != 2) 1065 return false; 1066 1067 LiveInterval &IntA = 1068 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 1069 LiveInterval &IntB = 1070 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 1071 1072 // A is defined by PHI at the entry of MBB. 1073 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true); 1074 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx); 1075 assert(AValNo && !AValNo->isUnused() && "COPY source not live"); 1076 if (!AValNo->isPHIDef()) 1077 return false; 1078 1079 // No B is referenced before CopyMI in MBB. 1080 if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx)) 1081 return false; 1082 1083 // MBB has two predecessors: one contains A = B so no copy will be inserted 1084 // for it. The other one will have a copy moved from MBB. 1085 bool FoundReverseCopy = false; 1086 MachineBasicBlock *CopyLeftBB = nullptr; 1087 for (MachineBasicBlock *Pred : MBB.predecessors()) { 1088 VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred)); 1089 MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def); 1090 if (!DefMI || !DefMI->isFullCopy()) { 1091 CopyLeftBB = Pred; 1092 continue; 1093 } 1094 // Check DefMI is a reverse copy and it is in BB Pred. 1095 if (DefMI->getOperand(0).getReg() != IntA.reg || 1096 DefMI->getOperand(1).getReg() != IntB.reg || 1097 DefMI->getParent() != Pred) { 1098 CopyLeftBB = Pred; 1099 continue; 1100 } 1101 // If there is any other def of B after DefMI and before the end of Pred, 1102 // we need to keep the copy of B = A at the end of Pred if we remove 1103 // B = A from MBB. 1104 bool ValB_Changed = false; 1105 for (auto VNI : IntB.valnos) { 1106 if (VNI->isUnused()) 1107 continue; 1108 if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) { 1109 ValB_Changed = true; 1110 break; 1111 } 1112 } 1113 if (ValB_Changed) { 1114 CopyLeftBB = Pred; 1115 continue; 1116 } 1117 FoundReverseCopy = true; 1118 } 1119 1120 // If no reverse copy is found in predecessors, nothing to do. 1121 if (!FoundReverseCopy) 1122 return false; 1123 1124 // If CopyLeftBB is nullptr, it means every predecessor of MBB contains 1125 // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated. 1126 // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and 1127 // update IntA/IntB. 1128 // 1129 // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so 1130 // MBB is hotter than CopyLeftBB. 1131 if (CopyLeftBB && CopyLeftBB->succ_size() > 1) 1132 return false; 1133 1134 // Now (almost sure it's) ok to move copy. 1135 if (CopyLeftBB) { 1136 // Position in CopyLeftBB where we should insert new copy. 1137 auto InsPos = CopyLeftBB->getFirstTerminator(); 1138 1139 // Make sure that B isn't referenced in the terminators (if any) at the end 1140 // of the predecessor since we're about to insert a new definition of B 1141 // before them. 1142 if (InsPos != CopyLeftBB->end()) { 1143 SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true); 1144 if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB))) 1145 return false; 1146 } 1147 1148 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to " 1149 << printMBBReference(*CopyLeftBB) << '\t' << CopyMI); 1150 1151 // Insert new copy to CopyLeftBB. 1152 MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(), 1153 TII->get(TargetOpcode::COPY), IntB.reg) 1154 .addReg(IntA.reg); 1155 SlotIndex NewCopyIdx = 1156 LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot(); 1157 IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator()); 1158 for (LiveInterval::SubRange &SR : IntB.subranges()) 1159 SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator()); 1160 1161 // If the newly created Instruction has an address of an instruction that was 1162 // deleted before (object recycled by the allocator) it needs to be removed from 1163 // the deleted list. 1164 ErasedInstrs.erase(NewCopyMI); 1165 } else { 1166 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from " 1167 << printMBBReference(MBB) << '\t' << CopyMI); 1168 } 1169 1170 // Remove CopyMI. 1171 // Note: This is fine to remove the copy before updating the live-ranges. 1172 // While updating the live-ranges, we only look at slot indices and 1173 // never go back to the instruction. 1174 // Mark instructions as deleted. 1175 deleteInstr(&CopyMI); 1176 1177 // Update the liveness. 1178 SmallVector<SlotIndex, 8> EndPoints; 1179 VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead(); 1180 LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(), 1181 &EndPoints); 1182 BValNo->markUnused(); 1183 // Extend IntB to the EndPoints of its original live interval. 1184 LIS->extendToIndices(IntB, EndPoints); 1185 1186 // Now, do the same for its subranges. 1187 for (LiveInterval::SubRange &SR : IntB.subranges()) { 1188 EndPoints.clear(); 1189 VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead(); 1190 assert(BValNo && "All sublanes should be live"); 1191 LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints); 1192 BValNo->markUnused(); 1193 // We can have a situation where the result of the original copy is live, 1194 // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes 1195 // the copy appear as an endpoint from pruneValue(), but we don't want it 1196 // to because the copy has been removed. We can go ahead and remove that 1197 // endpoint; there is no other situation here that there could be a use at 1198 // the same place as we know that the copy is a full copy. 1199 for (unsigned I = 0; I != EndPoints.size(); ) { 1200 if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) { 1201 EndPoints[I] = EndPoints.back(); 1202 EndPoints.pop_back(); 1203 continue; 1204 } 1205 ++I; 1206 } 1207 LIS->extendToIndices(SR, EndPoints); 1208 } 1209 // If any dead defs were extended, truncate them. 1210 shrinkToUses(&IntB); 1211 1212 // Finally, update the live-range of IntA. 1213 shrinkToUses(&IntA); 1214 return true; 1215 } 1216 1217 /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just 1218 /// defining a subregister. 1219 static bool definesFullReg(const MachineInstr &MI, unsigned Reg) { 1220 assert(!Register::isPhysicalRegister(Reg) && 1221 "This code cannot handle physreg aliasing"); 1222 for (const MachineOperand &Op : MI.operands()) { 1223 if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg) 1224 continue; 1225 // Return true if we define the full register or don't care about the value 1226 // inside other subregisters. 1227 if (Op.getSubReg() == 0 || Op.isUndef()) 1228 return true; 1229 } 1230 return false; 1231 } 1232 1233 bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP, 1234 MachineInstr *CopyMI, 1235 bool &IsDefCopy) { 1236 IsDefCopy = false; 1237 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg(); 1238 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx(); 1239 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg(); 1240 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx(); 1241 if (Register::isPhysicalRegister(SrcReg)) 1242 return false; 1243 1244 LiveInterval &SrcInt = LIS->getInterval(SrcReg); 1245 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI); 1246 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn(); 1247 if (!ValNo) 1248 return false; 1249 if (ValNo->isPHIDef() || ValNo->isUnused()) 1250 return false; 1251 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def); 1252 if (!DefMI) 1253 return false; 1254 if (DefMI->isCopyLike()) { 1255 IsDefCopy = true; 1256 return false; 1257 } 1258 if (!TII->isAsCheapAsAMove(*DefMI)) 1259 return false; 1260 if (!TII->isTriviallyReMaterializable(*DefMI, AA)) 1261 return false; 1262 if (!definesFullReg(*DefMI, SrcReg)) 1263 return false; 1264 bool SawStore = false; 1265 if (!DefMI->isSafeToMove(AA, SawStore)) 1266 return false; 1267 const MCInstrDesc &MCID = DefMI->getDesc(); 1268 if (MCID.getNumDefs() != 1) 1269 return false; 1270 // Only support subregister destinations when the def is read-undef. 1271 MachineOperand &DstOperand = CopyMI->getOperand(0); 1272 Register CopyDstReg = DstOperand.getReg(); 1273 if (DstOperand.getSubReg() && !DstOperand.isUndef()) 1274 return false; 1275 1276 // If both SrcIdx and DstIdx are set, correct rematerialization would widen 1277 // the register substantially (beyond both source and dest size). This is bad 1278 // for performance since it can cascade through a function, introducing many 1279 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers 1280 // around after a few subreg copies). 1281 if (SrcIdx && DstIdx) 1282 return false; 1283 1284 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF); 1285 if (!DefMI->isImplicitDef()) { 1286 if (Register::isPhysicalRegister(DstReg)) { 1287 unsigned NewDstReg = DstReg; 1288 1289 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(), 1290 DefMI->getOperand(0).getSubReg()); 1291 if (NewDstIdx) 1292 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx); 1293 1294 // Finally, make sure that the physical subregister that will be 1295 // constructed later is permitted for the instruction. 1296 if (!DefRC->contains(NewDstReg)) 1297 return false; 1298 } else { 1299 // Theoretically, some stack frame reference could exist. Just make sure 1300 // it hasn't actually happened. 1301 assert(Register::isVirtualRegister(DstReg) && 1302 "Only expect to deal with virtual or physical registers"); 1303 } 1304 } 1305 1306 DebugLoc DL = CopyMI->getDebugLoc(); 1307 MachineBasicBlock *MBB = CopyMI->getParent(); 1308 MachineBasicBlock::iterator MII = 1309 std::next(MachineBasicBlock::iterator(CopyMI)); 1310 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI); 1311 MachineInstr &NewMI = *std::prev(MII); 1312 NewMI.setDebugLoc(DL); 1313 1314 // In a situation like the following: 1315 // %0:subreg = instr ; DefMI, subreg = DstIdx 1316 // %1 = copy %0:subreg ; CopyMI, SrcIdx = 0 1317 // instead of widening %1 to the register class of %0 simply do: 1318 // %1 = instr 1319 const TargetRegisterClass *NewRC = CP.getNewRC(); 1320 if (DstIdx != 0) { 1321 MachineOperand &DefMO = NewMI.getOperand(0); 1322 if (DefMO.getSubReg() == DstIdx) { 1323 assert(SrcIdx == 0 && CP.isFlipped() 1324 && "Shouldn't have SrcIdx+DstIdx at this point"); 1325 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg); 1326 const TargetRegisterClass *CommonRC = 1327 TRI->getCommonSubClass(DefRC, DstRC); 1328 if (CommonRC != nullptr) { 1329 NewRC = CommonRC; 1330 DstIdx = 0; 1331 DefMO.setSubReg(0); 1332 DefMO.setIsUndef(false); // Only subregs can have def+undef. 1333 } 1334 } 1335 } 1336 1337 // CopyMI may have implicit operands, save them so that we can transfer them 1338 // over to the newly materialized instruction after CopyMI is removed. 1339 SmallVector<MachineOperand, 4> ImplicitOps; 1340 ImplicitOps.reserve(CopyMI->getNumOperands() - 1341 CopyMI->getDesc().getNumOperands()); 1342 for (unsigned I = CopyMI->getDesc().getNumOperands(), 1343 E = CopyMI->getNumOperands(); 1344 I != E; ++I) { 1345 MachineOperand &MO = CopyMI->getOperand(I); 1346 if (MO.isReg()) { 1347 assert(MO.isImplicit() && "No explicit operands after implicit operands."); 1348 // Discard VReg implicit defs. 1349 if (Register::isPhysicalRegister(MO.getReg())) 1350 ImplicitOps.push_back(MO); 1351 } 1352 } 1353 1354 LIS->ReplaceMachineInstrInMaps(*CopyMI, NewMI); 1355 CopyMI->eraseFromParent(); 1356 ErasedInstrs.insert(CopyMI); 1357 1358 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86). 1359 // We need to remember these so we can add intervals once we insert 1360 // NewMI into SlotIndexes. 1361 SmallVector<unsigned, 4> NewMIImplDefs; 1362 for (unsigned i = NewMI.getDesc().getNumOperands(), 1363 e = NewMI.getNumOperands(); 1364 i != e; ++i) { 1365 MachineOperand &MO = NewMI.getOperand(i); 1366 if (MO.isReg() && MO.isDef()) { 1367 assert(MO.isImplicit() && MO.isDead() && 1368 Register::isPhysicalRegister(MO.getReg())); 1369 NewMIImplDefs.push_back(MO.getReg()); 1370 } 1371 } 1372 1373 if (Register::isVirtualRegister(DstReg)) { 1374 unsigned NewIdx = NewMI.getOperand(0).getSubReg(); 1375 1376 if (DefRC != nullptr) { 1377 if (NewIdx) 1378 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx); 1379 else 1380 NewRC = TRI->getCommonSubClass(NewRC, DefRC); 1381 assert(NewRC && "subreg chosen for remat incompatible with instruction"); 1382 } 1383 // Remap subranges to new lanemask and change register class. 1384 LiveInterval &DstInt = LIS->getInterval(DstReg); 1385 for (LiveInterval::SubRange &SR : DstInt.subranges()) { 1386 SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask); 1387 } 1388 MRI->setRegClass(DstReg, NewRC); 1389 1390 // Update machine operands and add flags. 1391 updateRegDefsUses(DstReg, DstReg, DstIdx); 1392 NewMI.getOperand(0).setSubReg(NewIdx); 1393 // updateRegDefUses can add an "undef" flag to the definition, since 1394 // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make 1395 // sure that "undef" is not set. 1396 if (NewIdx == 0) 1397 NewMI.getOperand(0).setIsUndef(false); 1398 // Add dead subregister definitions if we are defining the whole register 1399 // but only part of it is live. 1400 // This could happen if the rematerialization instruction is rematerializing 1401 // more than actually is used in the register. 1402 // An example would be: 1403 // %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs 1404 // ; Copying only part of the register here, but the rest is undef. 1405 // %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit 1406 // ==> 1407 // ; Materialize all the constants but only using one 1408 // %2 = LOAD_CONSTANTS 5, 8 1409 // 1410 // at this point for the part that wasn't defined before we could have 1411 // subranges missing the definition. 1412 if (NewIdx == 0 && DstInt.hasSubRanges()) { 1413 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI); 1414 SlotIndex DefIndex = 1415 CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber()); 1416 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg); 1417 VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator(); 1418 for (LiveInterval::SubRange &SR : DstInt.subranges()) { 1419 if (!SR.liveAt(DefIndex)) 1420 SR.createDeadDef(DefIndex, Alloc); 1421 MaxMask &= ~SR.LaneMask; 1422 } 1423 if (MaxMask.any()) { 1424 LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask); 1425 SR->createDeadDef(DefIndex, Alloc); 1426 } 1427 } 1428 1429 // Make sure that the subrange for resultant undef is removed 1430 // For example: 1431 // %1:sub1<def,read-undef> = LOAD CONSTANT 1 1432 // %2 = COPY %1 1433 // ==> 1434 // %2:sub1<def, read-undef> = LOAD CONSTANT 1 1435 // ; Correct but need to remove the subrange for %2:sub0 1436 // ; as it is now undef 1437 if (NewIdx != 0 && DstInt.hasSubRanges()) { 1438 // The affected subregister segments can be removed. 1439 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI); 1440 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx); 1441 bool UpdatedSubRanges = false; 1442 for (LiveInterval::SubRange &SR : DstInt.subranges()) { 1443 if ((SR.LaneMask & DstMask).none()) { 1444 LLVM_DEBUG(dbgs() 1445 << "Removing undefined SubRange " 1446 << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n"); 1447 // VNI is in ValNo - remove any segments in this SubRange that have this ValNo 1448 if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) { 1449 SR.removeValNo(RmValNo); 1450 UpdatedSubRanges = true; 1451 } 1452 } 1453 } 1454 if (UpdatedSubRanges) 1455 DstInt.removeEmptySubRanges(); 1456 } 1457 } else if (NewMI.getOperand(0).getReg() != CopyDstReg) { 1458 // The New instruction may be defining a sub-register of what's actually 1459 // been asked for. If so it must implicitly define the whole thing. 1460 assert(Register::isPhysicalRegister(DstReg) && 1461 "Only expect virtual or physical registers in remat"); 1462 NewMI.getOperand(0).setIsDead(true); 1463 NewMI.addOperand(MachineOperand::CreateReg( 1464 CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/)); 1465 // Record small dead def live-ranges for all the subregisters 1466 // of the destination register. 1467 // Otherwise, variables that live through may miss some 1468 // interferences, thus creating invalid allocation. 1469 // E.g., i386 code: 1470 // %1 = somedef ; %1 GR8 1471 // %2 = remat ; %2 GR32 1472 // CL = COPY %2.sub_8bit 1473 // = somedef %1 ; %1 GR8 1474 // => 1475 // %1 = somedef ; %1 GR8 1476 // dead ECX = remat ; implicit-def CL 1477 // = somedef %1 ; %1 GR8 1478 // %1 will see the interferences with CL but not with CH since 1479 // no live-ranges would have been created for ECX. 1480 // Fix that! 1481 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI); 1482 for (MCRegUnitIterator Units(NewMI.getOperand(0).getReg(), TRI); 1483 Units.isValid(); ++Units) 1484 if (LiveRange *LR = LIS->getCachedRegUnit(*Units)) 1485 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator()); 1486 } 1487 1488 if (NewMI.getOperand(0).getSubReg()) 1489 NewMI.getOperand(0).setIsUndef(); 1490 1491 // Transfer over implicit operands to the rematerialized instruction. 1492 for (MachineOperand &MO : ImplicitOps) 1493 NewMI.addOperand(MO); 1494 1495 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI); 1496 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) { 1497 unsigned Reg = NewMIImplDefs[i]; 1498 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) 1499 if (LiveRange *LR = LIS->getCachedRegUnit(*Units)) 1500 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator()); 1501 } 1502 1503 LLVM_DEBUG(dbgs() << "Remat: " << NewMI); 1504 ++NumReMats; 1505 1506 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs 1507 // to describe DstReg instead. 1508 if (MRI->use_nodbg_empty(SrcReg)) { 1509 for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) { 1510 MachineInstr *UseMI = UseMO.getParent(); 1511 if (UseMI->isDebugValue()) { 1512 if (Register::isPhysicalRegister(DstReg)) 1513 UseMO.substPhysReg(DstReg, *TRI); 1514 else 1515 UseMO.setReg(DstReg); 1516 // Move the debug value directly after the def of the rematerialized 1517 // value in DstReg. 1518 MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI); 1519 LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI); 1520 } 1521 } 1522 } 1523 1524 if (ToBeUpdated.count(SrcReg)) 1525 return true; 1526 1527 unsigned NumCopyUses = 0; 1528 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) { 1529 if (UseMO.getParent()->isCopyLike()) 1530 NumCopyUses++; 1531 } 1532 if (NumCopyUses < LateRematUpdateThreshold) { 1533 // The source interval can become smaller because we removed a use. 1534 shrinkToUses(&SrcInt, &DeadDefs); 1535 if (!DeadDefs.empty()) 1536 eliminateDeadDefs(); 1537 } else { 1538 ToBeUpdated.insert(SrcReg); 1539 } 1540 return true; 1541 } 1542 1543 MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) { 1544 // ProcessImplicitDefs may leave some copies of <undef> values, it only 1545 // removes local variables. When we have a copy like: 1546 // 1547 // %1 = COPY undef %2 1548 // 1549 // We delete the copy and remove the corresponding value number from %1. 1550 // Any uses of that value number are marked as <undef>. 1551 1552 // Note that we do not query CoalescerPair here but redo isMoveInstr as the 1553 // CoalescerPair may have a new register class with adjusted subreg indices 1554 // at this point. 1555 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 1556 if(!isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) 1557 return nullptr; 1558 1559 SlotIndex Idx = LIS->getInstructionIndex(*CopyMI); 1560 const LiveInterval &SrcLI = LIS->getInterval(SrcReg); 1561 // CopyMI is undef iff SrcReg is not live before the instruction. 1562 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) { 1563 LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx); 1564 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) { 1565 if ((SR.LaneMask & SrcMask).none()) 1566 continue; 1567 if (SR.liveAt(Idx)) 1568 return nullptr; 1569 } 1570 } else if (SrcLI.liveAt(Idx)) 1571 return nullptr; 1572 1573 // If the undef copy defines a live-out value (i.e. an input to a PHI def), 1574 // then replace it with an IMPLICIT_DEF. 1575 LiveInterval &DstLI = LIS->getInterval(DstReg); 1576 SlotIndex RegIndex = Idx.getRegSlot(); 1577 LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex); 1578 assert(Seg != nullptr && "No segment for defining instruction"); 1579 if (VNInfo *V = DstLI.getVNInfoAt(Seg->end)) { 1580 if (V->isPHIDef()) { 1581 CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF)); 1582 for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) { 1583 MachineOperand &MO = CopyMI->getOperand(i-1); 1584 if (MO.isReg() && MO.isUse()) 1585 CopyMI->RemoveOperand(i-1); 1586 } 1587 LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an " 1588 "implicit def\n"); 1589 return CopyMI; 1590 } 1591 } 1592 1593 // Remove any DstReg segments starting at the instruction. 1594 LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n"); 1595 1596 // Remove value or merge with previous one in case of a subregister def. 1597 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) { 1598 VNInfo *VNI = DstLI.getVNInfoAt(RegIndex); 1599 DstLI.MergeValueNumberInto(VNI, PrevVNI); 1600 1601 // The affected subregister segments can be removed. 1602 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx); 1603 for (LiveInterval::SubRange &SR : DstLI.subranges()) { 1604 if ((SR.LaneMask & DstMask).none()) 1605 continue; 1606 1607 VNInfo *SVNI = SR.getVNInfoAt(RegIndex); 1608 assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex)); 1609 SR.removeValNo(SVNI); 1610 } 1611 DstLI.removeEmptySubRanges(); 1612 } else 1613 LIS->removeVRegDefAt(DstLI, RegIndex); 1614 1615 // Mark uses as undef. 1616 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) { 1617 if (MO.isDef() /*|| MO.isUndef()*/) 1618 continue; 1619 const MachineInstr &MI = *MO.getParent(); 1620 SlotIndex UseIdx = LIS->getInstructionIndex(MI); 1621 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg()); 1622 bool isLive; 1623 if (!UseMask.all() && DstLI.hasSubRanges()) { 1624 isLive = false; 1625 for (const LiveInterval::SubRange &SR : DstLI.subranges()) { 1626 if ((SR.LaneMask & UseMask).none()) 1627 continue; 1628 if (SR.liveAt(UseIdx)) { 1629 isLive = true; 1630 break; 1631 } 1632 } 1633 } else 1634 isLive = DstLI.liveAt(UseIdx); 1635 if (isLive) 1636 continue; 1637 MO.setIsUndef(true); 1638 LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI); 1639 } 1640 1641 // A def of a subregister may be a use of the other subregisters, so 1642 // deleting a def of a subregister may also remove uses. Since CopyMI 1643 // is still part of the function (but about to be erased), mark all 1644 // defs of DstReg in it as <undef>, so that shrinkToUses would 1645 // ignore them. 1646 for (MachineOperand &MO : CopyMI->operands()) 1647 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg) 1648 MO.setIsUndef(true); 1649 LIS->shrinkToUses(&DstLI); 1650 1651 return CopyMI; 1652 } 1653 1654 void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx, 1655 MachineOperand &MO, unsigned SubRegIdx) { 1656 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx); 1657 if (MO.isDef()) 1658 Mask = ~Mask; 1659 bool IsUndef = true; 1660 for (const LiveInterval::SubRange &S : Int.subranges()) { 1661 if ((S.LaneMask & Mask).none()) 1662 continue; 1663 if (S.liveAt(UseIdx)) { 1664 IsUndef = false; 1665 break; 1666 } 1667 } 1668 if (IsUndef) { 1669 MO.setIsUndef(true); 1670 // We found out some subregister use is actually reading an undefined 1671 // value. In some cases the whole vreg has become undefined at this 1672 // point so we have to potentially shrink the main range if the 1673 // use was ending a live segment there. 1674 LiveQueryResult Q = Int.Query(UseIdx); 1675 if (Q.valueOut() == nullptr) 1676 ShrinkMainRange = true; 1677 } 1678 } 1679 1680 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg, unsigned DstReg, 1681 unsigned SubIdx) { 1682 bool DstIsPhys = Register::isPhysicalRegister(DstReg); 1683 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg); 1684 1685 if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) { 1686 for (MachineOperand &MO : MRI->reg_operands(DstReg)) { 1687 unsigned SubReg = MO.getSubReg(); 1688 if (SubReg == 0 || MO.isUndef()) 1689 continue; 1690 MachineInstr &MI = *MO.getParent(); 1691 if (MI.isDebugValue()) 1692 continue; 1693 SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true); 1694 addUndefFlag(*DstInt, UseIdx, MO, SubReg); 1695 } 1696 } 1697 1698 SmallPtrSet<MachineInstr*, 8> Visited; 1699 for (MachineRegisterInfo::reg_instr_iterator 1700 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end(); 1701 I != E; ) { 1702 MachineInstr *UseMI = &*(I++); 1703 1704 // Each instruction can only be rewritten once because sub-register 1705 // composition is not always idempotent. When SrcReg != DstReg, rewriting 1706 // the UseMI operands removes them from the SrcReg use-def chain, but when 1707 // SrcReg is DstReg we could encounter UseMI twice if it has multiple 1708 // operands mentioning the virtual register. 1709 if (SrcReg == DstReg && !Visited.insert(UseMI).second) 1710 continue; 1711 1712 SmallVector<unsigned,8> Ops; 1713 bool Reads, Writes; 1714 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops); 1715 1716 // If SrcReg wasn't read, it may still be the case that DstReg is live-in 1717 // because SrcReg is a sub-register. 1718 if (DstInt && !Reads && SubIdx && !UseMI->isDebugValue()) 1719 Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI)); 1720 1721 // Replace SrcReg with DstReg in all UseMI operands. 1722 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1723 MachineOperand &MO = UseMI->getOperand(Ops[i]); 1724 1725 // Adjust <undef> flags in case of sub-register joins. We don't want to 1726 // turn a full def into a read-modify-write sub-register def and vice 1727 // versa. 1728 if (SubIdx && MO.isDef()) 1729 MO.setIsUndef(!Reads); 1730 1731 // A subreg use of a partially undef (super) register may be a complete 1732 // undef use now and then has to be marked that way. 1733 if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) { 1734 if (!DstInt->hasSubRanges()) { 1735 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 1736 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg); 1737 DstInt->createSubRangeFrom(Allocator, Mask, *DstInt); 1738 } 1739 SlotIndex MIIdx = UseMI->isDebugValue() 1740 ? LIS->getSlotIndexes()->getIndexBefore(*UseMI) 1741 : LIS->getInstructionIndex(*UseMI); 1742 SlotIndex UseIdx = MIIdx.getRegSlot(true); 1743 addUndefFlag(*DstInt, UseIdx, MO, SubIdx); 1744 } 1745 1746 if (DstIsPhys) 1747 MO.substPhysReg(DstReg, *TRI); 1748 else 1749 MO.substVirtReg(DstReg, SubIdx, *TRI); 1750 } 1751 1752 LLVM_DEBUG({ 1753 dbgs() << "\t\tupdated: "; 1754 if (!UseMI->isDebugValue()) 1755 dbgs() << LIS->getInstructionIndex(*UseMI) << "\t"; 1756 dbgs() << *UseMI; 1757 }); 1758 } 1759 } 1760 1761 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) { 1762 // Always join simple intervals that are defined by a single copy from a 1763 // reserved register. This doesn't increase register pressure, so it is 1764 // always beneficial. 1765 if (!MRI->isReserved(CP.getDstReg())) { 1766 LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n"); 1767 return false; 1768 } 1769 1770 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg()); 1771 if (JoinVInt.containsOneValue()) 1772 return true; 1773 1774 LLVM_DEBUG( 1775 dbgs() << "\tCannot join complex intervals into reserved register.\n"); 1776 return false; 1777 } 1778 1779 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) { 1780 Again = false; 1781 LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI); 1782 1783 CoalescerPair CP(*TRI); 1784 if (!CP.setRegisters(CopyMI)) { 1785 LLVM_DEBUG(dbgs() << "\tNot coalescable.\n"); 1786 return false; 1787 } 1788 1789 if (CP.getNewRC()) { 1790 auto SrcRC = MRI->getRegClass(CP.getSrcReg()); 1791 auto DstRC = MRI->getRegClass(CP.getDstReg()); 1792 unsigned SrcIdx = CP.getSrcIdx(); 1793 unsigned DstIdx = CP.getDstIdx(); 1794 if (CP.isFlipped()) { 1795 std::swap(SrcIdx, DstIdx); 1796 std::swap(SrcRC, DstRC); 1797 } 1798 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx, 1799 CP.getNewRC(), *LIS)) { 1800 LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n"); 1801 return false; 1802 } 1803 } 1804 1805 // Dead code elimination. This really should be handled by MachineDCE, but 1806 // sometimes dead copies slip through, and we can't generate invalid live 1807 // ranges. 1808 if (!CP.isPhys() && CopyMI->allDefsAreDead()) { 1809 LLVM_DEBUG(dbgs() << "\tCopy is dead.\n"); 1810 DeadDefs.push_back(CopyMI); 1811 eliminateDeadDefs(); 1812 return true; 1813 } 1814 1815 // Eliminate undefs. 1816 if (!CP.isPhys()) { 1817 // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce. 1818 if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) { 1819 if (UndefMI->isImplicitDef()) 1820 return false; 1821 deleteInstr(CopyMI); 1822 return false; // Not coalescable. 1823 } 1824 } 1825 1826 // Coalesced copies are normally removed immediately, but transformations 1827 // like removeCopyByCommutingDef() can inadvertently create identity copies. 1828 // When that happens, just join the values and remove the copy. 1829 if (CP.getSrcReg() == CP.getDstReg()) { 1830 LiveInterval &LI = LIS->getInterval(CP.getSrcReg()); 1831 LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n'); 1832 const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI); 1833 LiveQueryResult LRQ = LI.Query(CopyIdx); 1834 if (VNInfo *DefVNI = LRQ.valueDefined()) { 1835 VNInfo *ReadVNI = LRQ.valueIn(); 1836 assert(ReadVNI && "No value before copy and no <undef> flag."); 1837 assert(ReadVNI != DefVNI && "Cannot read and define the same value."); 1838 LI.MergeValueNumberInto(DefVNI, ReadVNI); 1839 1840 // Process subregister liveranges. 1841 for (LiveInterval::SubRange &S : LI.subranges()) { 1842 LiveQueryResult SLRQ = S.Query(CopyIdx); 1843 if (VNInfo *SDefVNI = SLRQ.valueDefined()) { 1844 VNInfo *SReadVNI = SLRQ.valueIn(); 1845 S.MergeValueNumberInto(SDefVNI, SReadVNI); 1846 } 1847 } 1848 LLVM_DEBUG(dbgs() << "\tMerged values: " << LI << '\n'); 1849 } 1850 deleteInstr(CopyMI); 1851 return true; 1852 } 1853 1854 // Enforce policies. 1855 if (CP.isPhys()) { 1856 LLVM_DEBUG(dbgs() << "\tConsidering merging " 1857 << printReg(CP.getSrcReg(), TRI) << " with " 1858 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'); 1859 if (!canJoinPhys(CP)) { 1860 // Before giving up coalescing, if definition of source is defined by 1861 // trivial computation, try rematerializing it. 1862 bool IsDefCopy; 1863 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy)) 1864 return true; 1865 if (IsDefCopy) 1866 Again = true; // May be possible to coalesce later. 1867 return false; 1868 } 1869 } else { 1870 // When possible, let DstReg be the larger interval. 1871 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() > 1872 LIS->getInterval(CP.getDstReg()).size()) 1873 CP.flip(); 1874 1875 LLVM_DEBUG({ 1876 dbgs() << "\tConsidering merging to " 1877 << TRI->getRegClassName(CP.getNewRC()) << " with "; 1878 if (CP.getDstIdx() && CP.getSrcIdx()) 1879 dbgs() << printReg(CP.getDstReg()) << " in " 1880 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and " 1881 << printReg(CP.getSrcReg()) << " in " 1882 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n'; 1883 else 1884 dbgs() << printReg(CP.getSrcReg(), TRI) << " in " 1885 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; 1886 }); 1887 } 1888 1889 ShrinkMask = LaneBitmask::getNone(); 1890 ShrinkMainRange = false; 1891 1892 // Okay, attempt to join these two intervals. On failure, this returns false. 1893 // Otherwise, if one of the intervals being joined is a physreg, this method 1894 // always canonicalizes DstInt to be it. The output "SrcInt" will not have 1895 // been modified, so we can use this information below to update aliases. 1896 if (!joinIntervals(CP)) { 1897 // Coalescing failed. 1898 1899 // If definition of source is defined by trivial computation, try 1900 // rematerializing it. 1901 bool IsDefCopy; 1902 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy)) 1903 return true; 1904 1905 // If we can eliminate the copy without merging the live segments, do so 1906 // now. 1907 if (!CP.isPartial() && !CP.isPhys()) { 1908 bool Changed = adjustCopiesBackFrom(CP, CopyMI); 1909 bool Shrink = false; 1910 if (!Changed) 1911 std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI); 1912 if (Changed) { 1913 deleteInstr(CopyMI); 1914 if (Shrink) { 1915 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg(); 1916 LiveInterval &DstLI = LIS->getInterval(DstReg); 1917 shrinkToUses(&DstLI); 1918 LLVM_DEBUG(dbgs() << "\t\tshrunk: " << DstLI << '\n'); 1919 } 1920 LLVM_DEBUG(dbgs() << "\tTrivial!\n"); 1921 return true; 1922 } 1923 } 1924 1925 // Try and see if we can partially eliminate the copy by moving the copy to 1926 // its predecessor. 1927 if (!CP.isPartial() && !CP.isPhys()) 1928 if (removePartialRedundancy(CP, *CopyMI)) 1929 return true; 1930 1931 // Otherwise, we are unable to join the intervals. 1932 LLVM_DEBUG(dbgs() << "\tInterference!\n"); 1933 Again = true; // May be possible to coalesce later. 1934 return false; 1935 } 1936 1937 // Coalescing to a virtual register that is of a sub-register class of the 1938 // other. Make sure the resulting register is set to the right register class. 1939 if (CP.isCrossClass()) { 1940 ++numCrossRCs; 1941 MRI->setRegClass(CP.getDstReg(), CP.getNewRC()); 1942 } 1943 1944 // Removing sub-register copies can ease the register class constraints. 1945 // Make sure we attempt to inflate the register class of DstReg. 1946 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC())) 1947 InflateRegs.push_back(CP.getDstReg()); 1948 1949 // CopyMI has been erased by joinIntervals at this point. Remove it from 1950 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back 1951 // to the work list. This keeps ErasedInstrs from growing needlessly. 1952 ErasedInstrs.erase(CopyMI); 1953 1954 // Rewrite all SrcReg operands to DstReg. 1955 // Also update DstReg operands to include DstIdx if it is set. 1956 if (CP.getDstIdx()) 1957 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx()); 1958 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx()); 1959 1960 // Shrink subregister ranges if necessary. 1961 if (ShrinkMask.any()) { 1962 LiveInterval &LI = LIS->getInterval(CP.getDstReg()); 1963 for (LiveInterval::SubRange &S : LI.subranges()) { 1964 if ((S.LaneMask & ShrinkMask).none()) 1965 continue; 1966 LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask) 1967 << ")\n"); 1968 LIS->shrinkToUses(S, LI.reg); 1969 } 1970 LI.removeEmptySubRanges(); 1971 } 1972 1973 // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live 1974 // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval 1975 // is not up-to-date, need to update the merged live interval here. 1976 if (ToBeUpdated.count(CP.getSrcReg())) 1977 ShrinkMainRange = true; 1978 1979 if (ShrinkMainRange) { 1980 LiveInterval &LI = LIS->getInterval(CP.getDstReg()); 1981 shrinkToUses(&LI); 1982 } 1983 1984 // SrcReg is guaranteed to be the register whose live interval that is 1985 // being merged. 1986 LIS->removeInterval(CP.getSrcReg()); 1987 1988 // Update regalloc hint. 1989 TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF); 1990 1991 LLVM_DEBUG({ 1992 dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx()) 1993 << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n'; 1994 dbgs() << "\tResult = "; 1995 if (CP.isPhys()) 1996 dbgs() << printReg(CP.getDstReg(), TRI); 1997 else 1998 dbgs() << LIS->getInterval(CP.getDstReg()); 1999 dbgs() << '\n'; 2000 }); 2001 2002 ++numJoins; 2003 return true; 2004 } 2005 2006 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) { 2007 unsigned DstReg = CP.getDstReg(); 2008 unsigned SrcReg = CP.getSrcReg(); 2009 assert(CP.isPhys() && "Must be a physreg copy"); 2010 assert(MRI->isReserved(DstReg) && "Not a reserved register"); 2011 LiveInterval &RHS = LIS->getInterval(SrcReg); 2012 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n'); 2013 2014 assert(RHS.containsOneValue() && "Invalid join with reserved register"); 2015 2016 // Optimization for reserved registers like ESP. We can only merge with a 2017 // reserved physreg if RHS has a single value that is a copy of DstReg. 2018 // The live range of the reserved register will look like a set of dead defs 2019 // - we don't properly track the live range of reserved registers. 2020 2021 // Deny any overlapping intervals. This depends on all the reserved 2022 // register live ranges to look like dead defs. 2023 if (!MRI->isConstantPhysReg(DstReg)) { 2024 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) { 2025 // Abort if not all the regunits are reserved. 2026 for (MCRegUnitRootIterator RI(*UI, TRI); RI.isValid(); ++RI) { 2027 if (!MRI->isReserved(*RI)) 2028 return false; 2029 } 2030 if (RHS.overlaps(LIS->getRegUnit(*UI))) { 2031 LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(*UI, TRI) 2032 << '\n'); 2033 return false; 2034 } 2035 } 2036 2037 // We must also check for overlaps with regmask clobbers. 2038 BitVector RegMaskUsable; 2039 if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) && 2040 !RegMaskUsable.test(DstReg)) { 2041 LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n"); 2042 return false; 2043 } 2044 } 2045 2046 // Skip any value computations, we are not adding new values to the 2047 // reserved register. Also skip merging the live ranges, the reserved 2048 // register live range doesn't need to be accurate as long as all the 2049 // defs are there. 2050 2051 // Delete the identity copy. 2052 MachineInstr *CopyMI; 2053 if (CP.isFlipped()) { 2054 // Physreg is copied into vreg 2055 // %y = COPY %physreg_x 2056 // ... //< no other def of %physreg_x here 2057 // use %y 2058 // => 2059 // ... 2060 // use %physreg_x 2061 CopyMI = MRI->getVRegDef(SrcReg); 2062 } else { 2063 // VReg is copied into physreg: 2064 // %y = def 2065 // ... //< no other def or use of %physreg_x here 2066 // %physreg_x = COPY %y 2067 // => 2068 // %physreg_x = def 2069 // ... 2070 if (!MRI->hasOneNonDBGUse(SrcReg)) { 2071 LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n"); 2072 return false; 2073 } 2074 2075 if (!LIS->intervalIsInOneMBB(RHS)) { 2076 LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n"); 2077 return false; 2078 } 2079 2080 MachineInstr &DestMI = *MRI->getVRegDef(SrcReg); 2081 CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg); 2082 SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot(); 2083 SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot(); 2084 2085 if (!MRI->isConstantPhysReg(DstReg)) { 2086 // We checked above that there are no interfering defs of the physical 2087 // register. However, for this case, where we intend to move up the def of 2088 // the physical register, we also need to check for interfering uses. 2089 SlotIndexes *Indexes = LIS->getSlotIndexes(); 2090 for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx); 2091 SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) { 2092 MachineInstr *MI = LIS->getInstructionFromIndex(SI); 2093 if (MI->readsRegister(DstReg, TRI)) { 2094 LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI); 2095 return false; 2096 } 2097 } 2098 } 2099 2100 // We're going to remove the copy which defines a physical reserved 2101 // register, so remove its valno, etc. 2102 LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of " 2103 << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n"); 2104 2105 LIS->removePhysRegDefAt(DstReg, CopyRegIdx); 2106 // Create a new dead def at the new def location. 2107 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) { 2108 LiveRange &LR = LIS->getRegUnit(*UI); 2109 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator()); 2110 } 2111 } 2112 2113 deleteInstr(CopyMI); 2114 2115 // We don't track kills for reserved registers. 2116 MRI->clearKillFlags(CP.getSrcReg()); 2117 2118 return true; 2119 } 2120 2121 //===----------------------------------------------------------------------===// 2122 // Interference checking and interval joining 2123 //===----------------------------------------------------------------------===// 2124 // 2125 // In the easiest case, the two live ranges being joined are disjoint, and 2126 // there is no interference to consider. It is quite common, though, to have 2127 // overlapping live ranges, and we need to check if the interference can be 2128 // resolved. 2129 // 2130 // The live range of a single SSA value forms a sub-tree of the dominator tree. 2131 // This means that two SSA values overlap if and only if the def of one value 2132 // is contained in the live range of the other value. As a special case, the 2133 // overlapping values can be defined at the same index. 2134 // 2135 // The interference from an overlapping def can be resolved in these cases: 2136 // 2137 // 1. Coalescable copies. The value is defined by a copy that would become an 2138 // identity copy after joining SrcReg and DstReg. The copy instruction will 2139 // be removed, and the value will be merged with the source value. 2140 // 2141 // There can be several copies back and forth, causing many values to be 2142 // merged into one. We compute a list of ultimate values in the joined live 2143 // range as well as a mappings from the old value numbers. 2144 // 2145 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI 2146 // predecessors have a live out value. It doesn't cause real interference, 2147 // and can be merged into the value it overlaps. Like a coalescable copy, it 2148 // can be erased after joining. 2149 // 2150 // 3. Copy of external value. The overlapping def may be a copy of a value that 2151 // is already in the other register. This is like a coalescable copy, but 2152 // the live range of the source register must be trimmed after erasing the 2153 // copy instruction: 2154 // 2155 // %src = COPY %ext 2156 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext. 2157 // 2158 // 4. Clobbering undefined lanes. Vector registers are sometimes built by 2159 // defining one lane at a time: 2160 // 2161 // %dst:ssub0<def,read-undef> = FOO 2162 // %src = BAR 2163 // %dst:ssub1 = COPY %src 2164 // 2165 // The live range of %src overlaps the %dst value defined by FOO, but 2166 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane 2167 // which was undef anyway. 2168 // 2169 // The value mapping is more complicated in this case. The final live range 2170 // will have different value numbers for both FOO and BAR, but there is no 2171 // simple mapping from old to new values. It may even be necessary to add 2172 // new PHI values. 2173 // 2174 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that 2175 // is live, but never read. This can happen because we don't compute 2176 // individual live ranges per lane. 2177 // 2178 // %dst = FOO 2179 // %src = BAR 2180 // %dst:ssub1 = COPY %src 2181 // 2182 // This kind of interference is only resolved locally. If the clobbered 2183 // lane value escapes the block, the join is aborted. 2184 2185 namespace { 2186 2187 /// Track information about values in a single virtual register about to be 2188 /// joined. Objects of this class are always created in pairs - one for each 2189 /// side of the CoalescerPair (or one for each lane of a side of the coalescer 2190 /// pair) 2191 class JoinVals { 2192 /// Live range we work on. 2193 LiveRange &LR; 2194 2195 /// (Main) register we work on. 2196 const unsigned Reg; 2197 2198 /// Reg (and therefore the values in this liverange) will end up as 2199 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or 2200 /// CP.SrcIdx. 2201 const unsigned SubIdx; 2202 2203 /// The LaneMask that this liverange will occupy the coalesced register. May 2204 /// be smaller than the lanemask produced by SubIdx when merging subranges. 2205 const LaneBitmask LaneMask; 2206 2207 /// This is true when joining sub register ranges, false when joining main 2208 /// ranges. 2209 const bool SubRangeJoin; 2210 2211 /// Whether the current LiveInterval tracks subregister liveness. 2212 const bool TrackSubRegLiveness; 2213 2214 /// Values that will be present in the final live range. 2215 SmallVectorImpl<VNInfo*> &NewVNInfo; 2216 2217 const CoalescerPair &CP; 2218 LiveIntervals *LIS; 2219 SlotIndexes *Indexes; 2220 const TargetRegisterInfo *TRI; 2221 2222 /// Value number assignments. Maps value numbers in LI to entries in 2223 /// NewVNInfo. This is suitable for passing to LiveInterval::join(). 2224 SmallVector<int, 8> Assignments; 2225 2226 public: 2227 /// Conflict resolution for overlapping values. 2228 enum ConflictResolution { 2229 /// No overlap, simply keep this value. 2230 CR_Keep, 2231 2232 /// Merge this value into OtherVNI and erase the defining instruction. 2233 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external 2234 /// values. 2235 CR_Erase, 2236 2237 /// Merge this value into OtherVNI but keep the defining instruction. 2238 /// This is for the special case where OtherVNI is defined by the same 2239 /// instruction. 2240 CR_Merge, 2241 2242 /// Keep this value, and have it replace OtherVNI where possible. This 2243 /// complicates value mapping since OtherVNI maps to two different values 2244 /// before and after this def. 2245 /// Used when clobbering undefined or dead lanes. 2246 CR_Replace, 2247 2248 /// Unresolved conflict. Visit later when all values have been mapped. 2249 CR_Unresolved, 2250 2251 /// Unresolvable conflict. Abort the join. 2252 CR_Impossible 2253 }; 2254 2255 private: 2256 /// Per-value info for LI. The lane bit masks are all relative to the final 2257 /// joined register, so they can be compared directly between SrcReg and 2258 /// DstReg. 2259 struct Val { 2260 ConflictResolution Resolution = CR_Keep; 2261 2262 /// Lanes written by this def, 0 for unanalyzed values. 2263 LaneBitmask WriteLanes; 2264 2265 /// Lanes with defined values in this register. Other lanes are undef and 2266 /// safe to clobber. 2267 LaneBitmask ValidLanes; 2268 2269 /// Value in LI being redefined by this def. 2270 VNInfo *RedefVNI = nullptr; 2271 2272 /// Value in the other live range that overlaps this def, if any. 2273 VNInfo *OtherVNI = nullptr; 2274 2275 /// Is this value an IMPLICIT_DEF that can be erased? 2276 /// 2277 /// IMPLICIT_DEF values should only exist at the end of a basic block that 2278 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be 2279 /// safely erased if they are overlapping a live value in the other live 2280 /// interval. 2281 /// 2282 /// Weird control flow graphs and incomplete PHI handling in 2283 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with 2284 /// longer live ranges. Such IMPLICIT_DEF values should be treated like 2285 /// normal values. 2286 bool ErasableImplicitDef = false; 2287 2288 /// True when the live range of this value will be pruned because of an 2289 /// overlapping CR_Replace value in the other live range. 2290 bool Pruned = false; 2291 2292 /// True once Pruned above has been computed. 2293 bool PrunedComputed = false; 2294 2295 /// True if this value is determined to be identical to OtherVNI 2296 /// (in valuesIdentical). This is used with CR_Erase where the erased 2297 /// copy is redundant, i.e. the source value is already the same as 2298 /// the destination. In such cases the subranges need to be updated 2299 /// properly. See comment at pruneSubRegValues for more info. 2300 bool Identical = false; 2301 2302 Val() = default; 2303 2304 bool isAnalyzed() const { return WriteLanes.any(); } 2305 }; 2306 2307 /// One entry per value number in LI. 2308 SmallVector<Val, 8> Vals; 2309 2310 /// Compute the bitmask of lanes actually written by DefMI. 2311 /// Set Redef if there are any partial register definitions that depend on the 2312 /// previous value of the register. 2313 LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const; 2314 2315 /// Find the ultimate value that VNI was copied from. 2316 std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const; 2317 2318 bool valuesIdentical(VNInfo *Value0, VNInfo *Value1, const JoinVals &Other) const; 2319 2320 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo]. 2321 /// Return a conflict resolution when possible, but leave the hard cases as 2322 /// CR_Unresolved. 2323 /// Recursively calls computeAssignment() on this and Other, guaranteeing that 2324 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning. 2325 /// The recursion always goes upwards in the dominator tree, making loops 2326 /// impossible. 2327 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other); 2328 2329 /// Compute the value assignment for ValNo in RI. 2330 /// This may be called recursively by analyzeValue(), but never for a ValNo on 2331 /// the stack. 2332 void computeAssignment(unsigned ValNo, JoinVals &Other); 2333 2334 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute 2335 /// the extent of the tainted lanes in the block. 2336 /// 2337 /// Multiple values in Other.LR can be affected since partial redefinitions 2338 /// can preserve previously tainted lanes. 2339 /// 2340 /// 1 %dst = VLOAD <-- Define all lanes in %dst 2341 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0 2342 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0 2343 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read 2344 /// 2345 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes) 2346 /// entry to TaintedVals. 2347 /// 2348 /// Returns false if the tainted lanes extend beyond the basic block. 2349 bool 2350 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other, 2351 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent); 2352 2353 /// Return true if MI uses any of the given Lanes from Reg. 2354 /// This does not include partial redefinitions of Reg. 2355 bool usesLanes(const MachineInstr &MI, unsigned, unsigned, LaneBitmask) const; 2356 2357 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will 2358 /// be pruned: 2359 /// 2360 /// %dst = COPY %src 2361 /// %src = COPY %dst <-- This value to be pruned. 2362 /// %dst = COPY %src <-- This value is a copy of a pruned value. 2363 bool isPrunedValue(unsigned ValNo, JoinVals &Other); 2364 2365 public: 2366 JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, LaneBitmask LaneMask, 2367 SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp, 2368 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin, 2369 bool TrackSubRegLiveness) 2370 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask), 2371 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness), 2372 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()), 2373 TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums()) {} 2374 2375 /// Analyze defs in LR and compute a value mapping in NewVNInfo. 2376 /// Returns false if any conflicts were impossible to resolve. 2377 bool mapValues(JoinVals &Other); 2378 2379 /// Try to resolve conflicts that require all values to be mapped. 2380 /// Returns false if any conflicts were impossible to resolve. 2381 bool resolveConflicts(JoinVals &Other); 2382 2383 /// Prune the live range of values in Other.LR where they would conflict with 2384 /// CR_Replace values in LR. Collect end points for restoring the live range 2385 /// after joining. 2386 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints, 2387 bool changeInstrs); 2388 2389 /// Removes subranges starting at copies that get removed. This sometimes 2390 /// happens when undefined subranges are copied around. These ranges contain 2391 /// no useful information and can be removed. 2392 void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask); 2393 2394 /// Pruning values in subranges can lead to removing segments in these 2395 /// subranges started by IMPLICIT_DEFs. The corresponding segments in 2396 /// the main range also need to be removed. This function will mark 2397 /// the corresponding values in the main range as pruned, so that 2398 /// eraseInstrs can do the final cleanup. 2399 /// The parameter @p LI must be the interval whose main range is the 2400 /// live range LR. 2401 void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange); 2402 2403 /// Erase any machine instructions that have been coalesced away. 2404 /// Add erased instructions to ErasedInstrs. 2405 /// Add foreign virtual registers to ShrinkRegs if their live range ended at 2406 /// the erased instrs. 2407 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs, 2408 SmallVectorImpl<unsigned> &ShrinkRegs, 2409 LiveInterval *LI = nullptr); 2410 2411 /// Remove liverange defs at places where implicit defs will be removed. 2412 void removeImplicitDefs(); 2413 2414 /// Get the value assignments suitable for passing to LiveInterval::join. 2415 const int *getAssignments() const { return Assignments.data(); } 2416 2417 /// Get the conflict resolution for a value number. 2418 ConflictResolution getResolution(unsigned Num) const { 2419 return Vals[Num].Resolution; 2420 } 2421 }; 2422 2423 } // end anonymous namespace 2424 2425 LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) 2426 const { 2427 LaneBitmask L; 2428 for (const MachineOperand &MO : DefMI->operands()) { 2429 if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef()) 2430 continue; 2431 L |= TRI->getSubRegIndexLaneMask( 2432 TRI->composeSubRegIndices(SubIdx, MO.getSubReg())); 2433 if (MO.readsReg()) 2434 Redef = true; 2435 } 2436 return L; 2437 } 2438 2439 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain( 2440 const VNInfo *VNI) const { 2441 unsigned TrackReg = Reg; 2442 2443 while (!VNI->isPHIDef()) { 2444 SlotIndex Def = VNI->def; 2445 MachineInstr *MI = Indexes->getInstructionFromIndex(Def); 2446 assert(MI && "No defining instruction"); 2447 if (!MI->isFullCopy()) 2448 return std::make_pair(VNI, TrackReg); 2449 Register SrcReg = MI->getOperand(1).getReg(); 2450 if (!Register::isVirtualRegister(SrcReg)) 2451 return std::make_pair(VNI, TrackReg); 2452 2453 const LiveInterval &LI = LIS->getInterval(SrcReg); 2454 const VNInfo *ValueIn; 2455 // No subrange involved. 2456 if (!SubRangeJoin || !LI.hasSubRanges()) { 2457 LiveQueryResult LRQ = LI.Query(Def); 2458 ValueIn = LRQ.valueIn(); 2459 } else { 2460 // Query subranges. Ensure that all matching ones take us to the same def 2461 // (allowing some of them to be undef). 2462 ValueIn = nullptr; 2463 for (const LiveInterval::SubRange &S : LI.subranges()) { 2464 // Transform lanemask to a mask in the joined live interval. 2465 LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask); 2466 if ((SMask & LaneMask).none()) 2467 continue; 2468 LiveQueryResult LRQ = S.Query(Def); 2469 if (!ValueIn) { 2470 ValueIn = LRQ.valueIn(); 2471 continue; 2472 } 2473 if (LRQ.valueIn() && ValueIn != LRQ.valueIn()) 2474 return std::make_pair(VNI, TrackReg); 2475 } 2476 } 2477 if (ValueIn == nullptr) { 2478 // Reaching an undefined value is legitimate, for example: 2479 // 2480 // 1 undef %0.sub1 = ... ;; %0.sub0 == undef 2481 // 2 %1 = COPY %0 ;; %1 is defined here. 2482 // 3 %0 = COPY %1 ;; Now %0.sub0 has a definition, 2483 // ;; but it's equivalent to "undef". 2484 return std::make_pair(nullptr, SrcReg); 2485 } 2486 VNI = ValueIn; 2487 TrackReg = SrcReg; 2488 } 2489 return std::make_pair(VNI, TrackReg); 2490 } 2491 2492 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1, 2493 const JoinVals &Other) const { 2494 const VNInfo *Orig0; 2495 unsigned Reg0; 2496 std::tie(Orig0, Reg0) = followCopyChain(Value0); 2497 if (Orig0 == Value1 && Reg0 == Other.Reg) 2498 return true; 2499 2500 const VNInfo *Orig1; 2501 unsigned Reg1; 2502 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1); 2503 // If both values are undefined, and the source registers are the same 2504 // register, the values are identical. Filter out cases where only one 2505 // value is defined. 2506 if (Orig0 == nullptr || Orig1 == nullptr) 2507 return Orig0 == Orig1 && Reg0 == Reg1; 2508 2509 // The values are equal if they are defined at the same place and use the 2510 // same register. Note that we cannot compare VNInfos directly as some of 2511 // them might be from a copy created in mergeSubRangeInto() while the other 2512 // is from the original LiveInterval. 2513 return Orig0->def == Orig1->def && Reg0 == Reg1; 2514 } 2515 2516 JoinVals::ConflictResolution 2517 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) { 2518 Val &V = Vals[ValNo]; 2519 assert(!V.isAnalyzed() && "Value has already been analyzed!"); 2520 VNInfo *VNI = LR.getValNumInfo(ValNo); 2521 if (VNI->isUnused()) { 2522 V.WriteLanes = LaneBitmask::getAll(); 2523 return CR_Keep; 2524 } 2525 2526 // Get the instruction defining this value, compute the lanes written. 2527 const MachineInstr *DefMI = nullptr; 2528 if (VNI->isPHIDef()) { 2529 // Conservatively assume that all lanes in a PHI are valid. 2530 LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0) 2531 : TRI->getSubRegIndexLaneMask(SubIdx); 2532 V.ValidLanes = V.WriteLanes = Lanes; 2533 } else { 2534 DefMI = Indexes->getInstructionFromIndex(VNI->def); 2535 assert(DefMI != nullptr); 2536 if (SubRangeJoin) { 2537 // We don't care about the lanes when joining subregister ranges. 2538 V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0); 2539 if (DefMI->isImplicitDef()) { 2540 V.ValidLanes = LaneBitmask::getNone(); 2541 V.ErasableImplicitDef = true; 2542 } 2543 } else { 2544 bool Redef = false; 2545 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef); 2546 2547 // If this is a read-modify-write instruction, there may be more valid 2548 // lanes than the ones written by this instruction. 2549 // This only covers partial redef operands. DefMI may have normal use 2550 // operands reading the register. They don't contribute valid lanes. 2551 // 2552 // This adds ssub1 to the set of valid lanes in %src: 2553 // 2554 // %src:ssub1 = FOO 2555 // 2556 // This leaves only ssub1 valid, making any other lanes undef: 2557 // 2558 // %src:ssub1<def,read-undef> = FOO %src:ssub2 2559 // 2560 // The <read-undef> flag on the def operand means that old lane values are 2561 // not important. 2562 if (Redef) { 2563 V.RedefVNI = LR.Query(VNI->def).valueIn(); 2564 assert((TrackSubRegLiveness || V.RedefVNI) && 2565 "Instruction is reading nonexistent value"); 2566 if (V.RedefVNI != nullptr) { 2567 computeAssignment(V.RedefVNI->id, Other); 2568 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes; 2569 } 2570 } 2571 2572 // An IMPLICIT_DEF writes undef values. 2573 if (DefMI->isImplicitDef()) { 2574 // We normally expect IMPLICIT_DEF values to be live only until the end 2575 // of their block. If the value is really live longer and gets pruned in 2576 // another block, this flag is cleared again. 2577 // 2578 // Clearing the valid lanes is deferred until it is sure this can be 2579 // erased. 2580 V.ErasableImplicitDef = true; 2581 } 2582 } 2583 } 2584 2585 // Find the value in Other that overlaps VNI->def, if any. 2586 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def); 2587 2588 // It is possible that both values are defined by the same instruction, or 2589 // the values are PHIs defined in the same block. When that happens, the two 2590 // values should be merged into one, but not into any preceding value. 2591 // The first value defined or visited gets CR_Keep, the other gets CR_Merge. 2592 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) { 2593 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ"); 2594 2595 // One value stays, the other is merged. Keep the earlier one, or the first 2596 // one we see. 2597 if (OtherVNI->def < VNI->def) 2598 Other.computeAssignment(OtherVNI->id, *this); 2599 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) { 2600 // This is an early-clobber def overlapping a live-in value in the other 2601 // register. Not mergeable. 2602 V.OtherVNI = OtherLRQ.valueIn(); 2603 return CR_Impossible; 2604 } 2605 V.OtherVNI = OtherVNI; 2606 Val &OtherV = Other.Vals[OtherVNI->id]; 2607 // Keep this value, check for conflicts when analyzing OtherVNI. 2608 if (!OtherV.isAnalyzed()) 2609 return CR_Keep; 2610 // Both sides have been analyzed now. 2611 // Allow overlapping PHI values. Any real interference would show up in a 2612 // predecessor, the PHI itself can't introduce any conflicts. 2613 if (VNI->isPHIDef()) 2614 return CR_Merge; 2615 if ((V.ValidLanes & OtherV.ValidLanes).any()) 2616 // Overlapping lanes can't be resolved. 2617 return CR_Impossible; 2618 else 2619 return CR_Merge; 2620 } 2621 2622 // No simultaneous def. Is Other live at the def? 2623 V.OtherVNI = OtherLRQ.valueIn(); 2624 if (!V.OtherVNI) 2625 // No overlap, no conflict. 2626 return CR_Keep; 2627 2628 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ"); 2629 2630 // We have overlapping values, or possibly a kill of Other. 2631 // Recursively compute assignments up the dominator tree. 2632 Other.computeAssignment(V.OtherVNI->id, *this); 2633 Val &OtherV = Other.Vals[V.OtherVNI->id]; 2634 2635 if (OtherV.ErasableImplicitDef) { 2636 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block. 2637 // This shouldn't normally happen, but ProcessImplicitDefs can leave such 2638 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it 2639 // technically. 2640 // 2641 // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try 2642 // to erase the IMPLICIT_DEF instruction. 2643 if (DefMI && 2644 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) { 2645 LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def 2646 << " extends into " 2647 << printMBBReference(*DefMI->getParent()) 2648 << ", keeping it.\n"); 2649 OtherV.ErasableImplicitDef = false; 2650 } else { 2651 // We deferred clearing these lanes in case we needed to save them 2652 OtherV.ValidLanes &= ~OtherV.WriteLanes; 2653 } 2654 } 2655 2656 // Allow overlapping PHI values. Any real interference would show up in a 2657 // predecessor, the PHI itself can't introduce any conflicts. 2658 if (VNI->isPHIDef()) 2659 return CR_Replace; 2660 2661 // Check for simple erasable conflicts. 2662 if (DefMI->isImplicitDef()) { 2663 // We need the def for the subregister if there is nothing else live at the 2664 // subrange at this point. 2665 if (TrackSubRegLiveness 2666 && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)).none()) 2667 return CR_Replace; 2668 return CR_Erase; 2669 } 2670 2671 // Include the non-conflict where DefMI is a coalescable copy that kills 2672 // OtherVNI. We still want the copy erased and value numbers merged. 2673 if (CP.isCoalescable(DefMI)) { 2674 // Some of the lanes copied from OtherVNI may be undef, making them undef 2675 // here too. 2676 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes; 2677 return CR_Erase; 2678 } 2679 2680 // This may not be a real conflict if DefMI simply kills Other and defines 2681 // VNI. 2682 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def) 2683 return CR_Keep; 2684 2685 // Handle the case where VNI and OtherVNI can be proven to be identical: 2686 // 2687 // %other = COPY %ext 2688 // %this = COPY %ext <-- Erase this copy 2689 // 2690 if (DefMI->isFullCopy() && !CP.isPartial() && 2691 valuesIdentical(VNI, V.OtherVNI, Other)) { 2692 V.Identical = true; 2693 return CR_Erase; 2694 } 2695 2696 // The remaining checks apply to the lanes, which aren't tracked here. This 2697 // was already decided to be OK via the following CR_Replace condition. 2698 // CR_Replace. 2699 if (SubRangeJoin) 2700 return CR_Replace; 2701 2702 // If the lanes written by this instruction were all undef in OtherVNI, it is 2703 // still safe to join the live ranges. This can't be done with a simple value 2704 // mapping, though - OtherVNI will map to multiple values: 2705 // 2706 // 1 %dst:ssub0 = FOO <-- OtherVNI 2707 // 2 %src = BAR <-- VNI 2708 // 3 %dst:ssub1 = COPY killed %src <-- Eliminate this copy. 2709 // 4 BAZ killed %dst 2710 // 5 QUUX killed %src 2711 // 2712 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace 2713 // handles this complex value mapping. 2714 if ((V.WriteLanes & OtherV.ValidLanes).none()) 2715 return CR_Replace; 2716 2717 // If the other live range is killed by DefMI and the live ranges are still 2718 // overlapping, it must be because we're looking at an early clobber def: 2719 // 2720 // %dst<def,early-clobber> = ASM killed %src 2721 // 2722 // In this case, it is illegal to merge the two live ranges since the early 2723 // clobber def would clobber %src before it was read. 2724 if (OtherLRQ.isKill()) { 2725 // This case where the def doesn't overlap the kill is handled above. 2726 assert(VNI->def.isEarlyClobber() && 2727 "Only early clobber defs can overlap a kill"); 2728 return CR_Impossible; 2729 } 2730 2731 // VNI is clobbering live lanes in OtherVNI, but there is still the 2732 // possibility that no instructions actually read the clobbered lanes. 2733 // If we're clobbering all the lanes in OtherVNI, at least one must be read. 2734 // Otherwise Other.RI wouldn't be live here. 2735 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none()) 2736 return CR_Impossible; 2737 2738 // We need to verify that no instructions are reading the clobbered lanes. To 2739 // save compile time, we'll only check that locally. Don't allow the tainted 2740 // value to escape the basic block. 2741 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 2742 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB)) 2743 return CR_Impossible; 2744 2745 // There are still some things that could go wrong besides clobbered lanes 2746 // being read, for example OtherVNI may be only partially redefined in MBB, 2747 // and some clobbered lanes could escape the block. Save this analysis for 2748 // resolveConflicts() when all values have been mapped. We need to know 2749 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute 2750 // that now - the recursive analyzeValue() calls must go upwards in the 2751 // dominator tree. 2752 return CR_Unresolved; 2753 } 2754 2755 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) { 2756 Val &V = Vals[ValNo]; 2757 if (V.isAnalyzed()) { 2758 // Recursion should always move up the dominator tree, so ValNo is not 2759 // supposed to reappear before it has been assigned. 2760 assert(Assignments[ValNo] != -1 && "Bad recursion?"); 2761 return; 2762 } 2763 switch ((V.Resolution = analyzeValue(ValNo, Other))) { 2764 case CR_Erase: 2765 case CR_Merge: 2766 // Merge this ValNo into OtherVNI. 2767 assert(V.OtherVNI && "OtherVNI not assigned, can't merge."); 2768 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion"); 2769 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id]; 2770 LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@' 2771 << LR.getValNumInfo(ValNo)->def << " into " 2772 << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@' 2773 << V.OtherVNI->def << " --> @" 2774 << NewVNInfo[Assignments[ValNo]]->def << '\n'); 2775 break; 2776 case CR_Replace: 2777 case CR_Unresolved: { 2778 // The other value is going to be pruned if this join is successful. 2779 assert(V.OtherVNI && "OtherVNI not assigned, can't prune"); 2780 Val &OtherV = Other.Vals[V.OtherVNI->id]; 2781 // We cannot erase an IMPLICIT_DEF if we don't have valid values for all 2782 // its lanes. 2783 if (OtherV.ErasableImplicitDef && 2784 TrackSubRegLiveness && 2785 (OtherV.WriteLanes & ~V.ValidLanes).any()) { 2786 LLVM_DEBUG(dbgs() << "Cannot erase implicit_def with missing values\n"); 2787 2788 OtherV.ErasableImplicitDef = false; 2789 // The valid lanes written by the implicit_def were speculatively cleared 2790 // before, so make this more conservative. It may be better to track this, 2791 // I haven't found a testcase where it matters. 2792 OtherV.ValidLanes = LaneBitmask::getAll(); 2793 } 2794 2795 OtherV.Pruned = true; 2796 LLVM_FALLTHROUGH; 2797 } 2798 default: 2799 // This value number needs to go in the final joined live range. 2800 Assignments[ValNo] = NewVNInfo.size(); 2801 NewVNInfo.push_back(LR.getValNumInfo(ValNo)); 2802 break; 2803 } 2804 } 2805 2806 bool JoinVals::mapValues(JoinVals &Other) { 2807 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2808 computeAssignment(i, Other); 2809 if (Vals[i].Resolution == CR_Impossible) { 2810 LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i 2811 << '@' << LR.getValNumInfo(i)->def << '\n'); 2812 return false; 2813 } 2814 } 2815 return true; 2816 } 2817 2818 bool JoinVals:: 2819 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other, 2820 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) { 2821 VNInfo *VNI = LR.getValNumInfo(ValNo); 2822 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 2823 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB); 2824 2825 // Scan Other.LR from VNI.def to MBBEnd. 2826 LiveInterval::iterator OtherI = Other.LR.find(VNI->def); 2827 assert(OtherI != Other.LR.end() && "No conflict?"); 2828 do { 2829 // OtherI is pointing to a tainted value. Abort the join if the tainted 2830 // lanes escape the block. 2831 SlotIndex End = OtherI->end; 2832 if (End >= MBBEnd) { 2833 LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':' 2834 << OtherI->valno->id << '@' << OtherI->start << '\n'); 2835 return false; 2836 } 2837 LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':' 2838 << OtherI->valno->id << '@' << OtherI->start << " to " 2839 << End << '\n'); 2840 // A dead def is not a problem. 2841 if (End.isDead()) 2842 break; 2843 TaintExtent.push_back(std::make_pair(End, TaintedLanes)); 2844 2845 // Check for another def in the MBB. 2846 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd) 2847 break; 2848 2849 // Lanes written by the new def are no longer tainted. 2850 const Val &OV = Other.Vals[OtherI->valno->id]; 2851 TaintedLanes &= ~OV.WriteLanes; 2852 if (!OV.RedefVNI) 2853 break; 2854 } while (TaintedLanes.any()); 2855 return true; 2856 } 2857 2858 bool JoinVals::usesLanes(const MachineInstr &MI, unsigned Reg, unsigned SubIdx, 2859 LaneBitmask Lanes) const { 2860 if (MI.isDebugInstr()) 2861 return false; 2862 for (const MachineOperand &MO : MI.operands()) { 2863 if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg) 2864 continue; 2865 if (!MO.readsReg()) 2866 continue; 2867 unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg()); 2868 if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any()) 2869 return true; 2870 } 2871 return false; 2872 } 2873 2874 bool JoinVals::resolveConflicts(JoinVals &Other) { 2875 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2876 Val &V = Vals[i]; 2877 assert(V.Resolution != CR_Impossible && "Unresolvable conflict"); 2878 if (V.Resolution != CR_Unresolved) 2879 continue; 2880 LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@' 2881 << LR.getValNumInfo(i)->def << '\n'); 2882 if (SubRangeJoin) 2883 return false; 2884 2885 ++NumLaneConflicts; 2886 assert(V.OtherVNI && "Inconsistent conflict resolution."); 2887 VNInfo *VNI = LR.getValNumInfo(i); 2888 const Val &OtherV = Other.Vals[V.OtherVNI->id]; 2889 2890 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the 2891 // join, those lanes will be tainted with a wrong value. Get the extent of 2892 // the tainted lanes. 2893 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes; 2894 SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent; 2895 if (!taintExtent(i, TaintedLanes, Other, TaintExtent)) 2896 // Tainted lanes would extend beyond the basic block. 2897 return false; 2898 2899 assert(!TaintExtent.empty() && "There should be at least one conflict."); 2900 2901 // Now look at the instructions from VNI->def to TaintExtent (inclusive). 2902 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 2903 MachineBasicBlock::iterator MI = MBB->begin(); 2904 if (!VNI->isPHIDef()) { 2905 MI = Indexes->getInstructionFromIndex(VNI->def); 2906 // No need to check the instruction defining VNI for reads. 2907 ++MI; 2908 } 2909 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) && 2910 "Interference ends on VNI->def. Should have been handled earlier"); 2911 MachineInstr *LastMI = 2912 Indexes->getInstructionFromIndex(TaintExtent.front().first); 2913 assert(LastMI && "Range must end at a proper instruction"); 2914 unsigned TaintNum = 0; 2915 while (true) { 2916 assert(MI != MBB->end() && "Bad LastMI"); 2917 if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) { 2918 LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI); 2919 return false; 2920 } 2921 // LastMI is the last instruction to use the current value. 2922 if (&*MI == LastMI) { 2923 if (++TaintNum == TaintExtent.size()) 2924 break; 2925 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first); 2926 assert(LastMI && "Range must end at a proper instruction"); 2927 TaintedLanes = TaintExtent[TaintNum].second; 2928 } 2929 ++MI; 2930 } 2931 2932 // The tainted lanes are unused. 2933 V.Resolution = CR_Replace; 2934 ++NumLaneResolves; 2935 } 2936 return true; 2937 } 2938 2939 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) { 2940 Val &V = Vals[ValNo]; 2941 if (V.Pruned || V.PrunedComputed) 2942 return V.Pruned; 2943 2944 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge) 2945 return V.Pruned; 2946 2947 // Follow copies up the dominator tree and check if any intermediate value 2948 // has been pruned. 2949 V.PrunedComputed = true; 2950 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this); 2951 return V.Pruned; 2952 } 2953 2954 void JoinVals::pruneValues(JoinVals &Other, 2955 SmallVectorImpl<SlotIndex> &EndPoints, 2956 bool changeInstrs) { 2957 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 2958 SlotIndex Def = LR.getValNumInfo(i)->def; 2959 switch (Vals[i].Resolution) { 2960 case CR_Keep: 2961 break; 2962 case CR_Replace: { 2963 // This value takes precedence over the value in Other.LR. 2964 LIS->pruneValue(Other.LR, Def, &EndPoints); 2965 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF 2966 // instructions are only inserted to provide a live-out value for PHI 2967 // predecessors, so the instruction should simply go away once its value 2968 // has been replaced. 2969 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id]; 2970 bool EraseImpDef = OtherV.ErasableImplicitDef && 2971 OtherV.Resolution == CR_Keep; 2972 if (!Def.isBlock()) { 2973 if (changeInstrs) { 2974 // Remove <def,read-undef> flags. This def is now a partial redef. 2975 // Also remove dead flags since the joined live range will 2976 // continue past this instruction. 2977 for (MachineOperand &MO : 2978 Indexes->getInstructionFromIndex(Def)->operands()) { 2979 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) { 2980 if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef) 2981 MO.setIsUndef(false); 2982 MO.setIsDead(false); 2983 } 2984 } 2985 } 2986 // This value will reach instructions below, but we need to make sure 2987 // the live range also reaches the instruction at Def. 2988 if (!EraseImpDef) 2989 EndPoints.push_back(Def); 2990 } 2991 LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Def 2992 << ": " << Other.LR << '\n'); 2993 break; 2994 } 2995 case CR_Erase: 2996 case CR_Merge: 2997 if (isPrunedValue(i, Other)) { 2998 // This value is ultimately a copy of a pruned value in LR or Other.LR. 2999 // We can no longer trust the value mapping computed by 3000 // computeAssignment(), the value that was originally copied could have 3001 // been replaced. 3002 LIS->pruneValue(LR, Def, &EndPoints); 3003 LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at " 3004 << Def << ": " << LR << '\n'); 3005 } 3006 break; 3007 case CR_Unresolved: 3008 case CR_Impossible: 3009 llvm_unreachable("Unresolved conflicts"); 3010 } 3011 } 3012 } 3013 3014 /// Consider the following situation when coalescing the copy between 3015 /// %31 and %45 at 800. (The vertical lines represent live range segments.) 3016 /// 3017 /// Main range Subrange 0004 (sub2) 3018 /// %31 %45 %31 %45 3019 /// 544 %45 = COPY %28 + + 3020 /// | v1 | v1 3021 /// 560B bb.1: + + 3022 /// 624 = %45.sub2 | v2 | v2 3023 /// 800 %31 = COPY %45 + + + + 3024 /// | v0 | v0 3025 /// 816 %31.sub1 = ... + | 3026 /// 880 %30 = COPY %31 | v1 + 3027 /// 928 %45 = COPY %30 | + + 3028 /// | | v0 | v0 <--+ 3029 /// 992B ; backedge -> bb.1 | + + | 3030 /// 1040 = %31.sub0 + | 3031 /// This value must remain 3032 /// live-out! 3033 /// 3034 /// Assuming that %31 is coalesced into %45, the copy at 928 becomes 3035 /// redundant, since it copies the value from %45 back into it. The 3036 /// conflict resolution for the main range determines that %45.v0 is 3037 /// to be erased, which is ok since %31.v1 is identical to it. 3038 /// The problem happens with the subrange for sub2: it has to be live 3039 /// on exit from the block, but since 928 was actually a point of 3040 /// definition of %45.sub2, %45.sub2 was not live immediately prior 3041 /// to that definition. As a result, when 928 was erased, the value v0 3042 /// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an 3043 /// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2, 3044 /// providing an incorrect value to the use at 624. 3045 /// 3046 /// Since the main-range values %31.v1 and %45.v0 were proved to be 3047 /// identical, the corresponding values in subranges must also be the 3048 /// same. A redundant copy is removed because it's not needed, and not 3049 /// because it copied an undefined value, so any liveness that originated 3050 /// from that copy cannot disappear. When pruning a value that started 3051 /// at the removed copy, the corresponding identical value must be 3052 /// extended to replace it. 3053 void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) { 3054 // Look for values being erased. 3055 bool DidPrune = false; 3056 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 3057 Val &V = Vals[i]; 3058 // We should trigger in all cases in which eraseInstrs() does something. 3059 // match what eraseInstrs() is doing, print a message so 3060 if (V.Resolution != CR_Erase && 3061 (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)) 3062 continue; 3063 3064 // Check subranges at the point where the copy will be removed. 3065 SlotIndex Def = LR.getValNumInfo(i)->def; 3066 SlotIndex OtherDef; 3067 if (V.Identical) 3068 OtherDef = V.OtherVNI->def; 3069 3070 // Print message so mismatches with eraseInstrs() can be diagnosed. 3071 LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Def 3072 << '\n'); 3073 for (LiveInterval::SubRange &S : LI.subranges()) { 3074 LiveQueryResult Q = S.Query(Def); 3075 3076 // If a subrange starts at the copy then an undefined value has been 3077 // copied and we must remove that subrange value as well. 3078 VNInfo *ValueOut = Q.valueOutOrDead(); 3079 if (ValueOut != nullptr && (Q.valueIn() == nullptr || 3080 (V.Identical && V.Resolution == CR_Erase && 3081 ValueOut->def == Def))) { 3082 LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask) 3083 << " at " << Def << "\n"); 3084 SmallVector<SlotIndex,8> EndPoints; 3085 LIS->pruneValue(S, Def, &EndPoints); 3086 DidPrune = true; 3087 // Mark value number as unused. 3088 ValueOut->markUnused(); 3089 3090 if (V.Identical && S.Query(OtherDef).valueOutOrDead()) { 3091 // If V is identical to V.OtherVNI (and S was live at OtherDef), 3092 // then we can't simply prune V from S. V needs to be replaced 3093 // with V.OtherVNI. 3094 LIS->extendToIndices(S, EndPoints); 3095 } 3096 continue; 3097 } 3098 // If a subrange ends at the copy, then a value was copied but only 3099 // partially used later. Shrink the subregister range appropriately. 3100 if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) { 3101 LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane " 3102 << PrintLaneMask(S.LaneMask) << " at " << Def 3103 << "\n"); 3104 ShrinkMask |= S.LaneMask; 3105 } 3106 } 3107 } 3108 if (DidPrune) 3109 LI.removeEmptySubRanges(); 3110 } 3111 3112 /// Check if any of the subranges of @p LI contain a definition at @p Def. 3113 static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) { 3114 for (LiveInterval::SubRange &SR : LI.subranges()) { 3115 if (VNInfo *VNI = SR.Query(Def).valueOutOrDead()) 3116 if (VNI->def == Def) 3117 return true; 3118 } 3119 return false; 3120 } 3121 3122 void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) { 3123 assert(&static_cast<LiveRange&>(LI) == &LR); 3124 3125 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 3126 if (Vals[i].Resolution != CR_Keep) 3127 continue; 3128 VNInfo *VNI = LR.getValNumInfo(i); 3129 if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def)) 3130 continue; 3131 Vals[i].Pruned = true; 3132 ShrinkMainRange = true; 3133 } 3134 } 3135 3136 void JoinVals::removeImplicitDefs() { 3137 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 3138 Val &V = Vals[i]; 3139 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned) 3140 continue; 3141 3142 VNInfo *VNI = LR.getValNumInfo(i); 3143 VNI->markUnused(); 3144 LR.removeValNo(VNI); 3145 } 3146 } 3147 3148 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs, 3149 SmallVectorImpl<unsigned> &ShrinkRegs, 3150 LiveInterval *LI) { 3151 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) { 3152 // Get the def location before markUnused() below invalidates it. 3153 VNInfo *VNI = LR.getValNumInfo(i); 3154 SlotIndex Def = VNI->def; 3155 switch (Vals[i].Resolution) { 3156 case CR_Keep: { 3157 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any 3158 // longer. The IMPLICIT_DEF instructions are only inserted by 3159 // PHIElimination to guarantee that all PHI predecessors have a value. 3160 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned) 3161 break; 3162 // Remove value number i from LR. 3163 // For intervals with subranges, removing a segment from the main range 3164 // may require extending the previous segment: for each definition of 3165 // a subregister, there will be a corresponding def in the main range. 3166 // That def may fall in the middle of a segment from another subrange. 3167 // In such cases, removing this def from the main range must be 3168 // complemented by extending the main range to account for the liveness 3169 // of the other subrange. 3170 // The new end point of the main range segment to be extended. 3171 SlotIndex NewEnd; 3172 if (LI != nullptr) { 3173 LiveRange::iterator I = LR.FindSegmentContaining(Def); 3174 assert(I != LR.end()); 3175 // Do not extend beyond the end of the segment being removed. 3176 // The segment may have been pruned in preparation for joining 3177 // live ranges. 3178 NewEnd = I->end; 3179 } 3180 3181 LR.removeValNo(VNI); 3182 // Note that this VNInfo is reused and still referenced in NewVNInfo, 3183 // make it appear like an unused value number. 3184 VNI->markUnused(); 3185 3186 if (LI != nullptr && LI->hasSubRanges()) { 3187 assert(static_cast<LiveRange*>(LI) == &LR); 3188 // Determine the end point based on the subrange information: 3189 // minimum of (earliest def of next segment, 3190 // latest end point of containing segment) 3191 SlotIndex ED, LE; 3192 for (LiveInterval::SubRange &SR : LI->subranges()) { 3193 LiveRange::iterator I = SR.find(Def); 3194 if (I == SR.end()) 3195 continue; 3196 if (I->start > Def) 3197 ED = ED.isValid() ? std::min(ED, I->start) : I->start; 3198 else 3199 LE = LE.isValid() ? std::max(LE, I->end) : I->end; 3200 } 3201 if (LE.isValid()) 3202 NewEnd = std::min(NewEnd, LE); 3203 if (ED.isValid()) 3204 NewEnd = std::min(NewEnd, ED); 3205 3206 // We only want to do the extension if there was a subrange that 3207 // was live across Def. 3208 if (LE.isValid()) { 3209 LiveRange::iterator S = LR.find(Def); 3210 if (S != LR.begin()) 3211 std::prev(S)->end = NewEnd; 3212 } 3213 } 3214 LLVM_DEBUG({ 3215 dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n'; 3216 if (LI != nullptr) 3217 dbgs() << "\t\t LHS = " << *LI << '\n'; 3218 }); 3219 LLVM_FALLTHROUGH; 3220 } 3221 3222 case CR_Erase: { 3223 MachineInstr *MI = Indexes->getInstructionFromIndex(Def); 3224 assert(MI && "No instruction to erase"); 3225 if (MI->isCopy()) { 3226 Register Reg = MI->getOperand(1).getReg(); 3227 if (Register::isVirtualRegister(Reg) && Reg != CP.getSrcReg() && 3228 Reg != CP.getDstReg()) 3229 ShrinkRegs.push_back(Reg); 3230 } 3231 ErasedInstrs.insert(MI); 3232 LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI); 3233 LIS->RemoveMachineInstrFromMaps(*MI); 3234 MI->eraseFromParent(); 3235 break; 3236 } 3237 default: 3238 break; 3239 } 3240 } 3241 } 3242 3243 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange, 3244 LaneBitmask LaneMask, 3245 const CoalescerPair &CP) { 3246 SmallVector<VNInfo*, 16> NewVNInfo; 3247 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask, 3248 NewVNInfo, CP, LIS, TRI, true, true); 3249 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask, 3250 NewVNInfo, CP, LIS, TRI, true, true); 3251 3252 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs()) 3253 // We should be able to resolve all conflicts here as we could successfully do 3254 // it on the mainrange already. There is however a problem when multiple 3255 // ranges get mapped to the "overflow" lane mask bit which creates unexpected 3256 // interferences. 3257 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) { 3258 // We already determined that it is legal to merge the intervals, so this 3259 // should never fail. 3260 llvm_unreachable("*** Couldn't join subrange!\n"); 3261 } 3262 if (!LHSVals.resolveConflicts(RHSVals) || 3263 !RHSVals.resolveConflicts(LHSVals)) { 3264 // We already determined that it is legal to merge the intervals, so this 3265 // should never fail. 3266 llvm_unreachable("*** Couldn't join subrange!\n"); 3267 } 3268 3269 // The merging algorithm in LiveInterval::join() can't handle conflicting 3270 // value mappings, so we need to remove any live ranges that overlap a 3271 // CR_Replace resolution. Collect a set of end points that can be used to 3272 // restore the live range after joining. 3273 SmallVector<SlotIndex, 8> EndPoints; 3274 LHSVals.pruneValues(RHSVals, EndPoints, false); 3275 RHSVals.pruneValues(LHSVals, EndPoints, false); 3276 3277 LHSVals.removeImplicitDefs(); 3278 RHSVals.removeImplicitDefs(); 3279 3280 LRange.verify(); 3281 RRange.verify(); 3282 3283 // Join RRange into LHS. 3284 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(), 3285 NewVNInfo); 3286 3287 LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask) 3288 << ' ' << LRange << "\n"); 3289 if (EndPoints.empty()) 3290 return; 3291 3292 // Recompute the parts of the live range we had to remove because of 3293 // CR_Replace conflicts. 3294 LLVM_DEBUG({ 3295 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; 3296 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { 3297 dbgs() << EndPoints[i]; 3298 if (i != n-1) 3299 dbgs() << ','; 3300 } 3301 dbgs() << ": " << LRange << '\n'; 3302 }); 3303 LIS->extendToIndices(LRange, EndPoints); 3304 } 3305 3306 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI, 3307 const LiveRange &ToMerge, 3308 LaneBitmask LaneMask, 3309 CoalescerPair &CP, 3310 unsigned ComposeSubRegIdx) { 3311 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 3312 LI.refineSubRanges( 3313 Allocator, LaneMask, 3314 [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) { 3315 if (SR.empty()) { 3316 SR.assign(ToMerge, Allocator); 3317 } else { 3318 // joinSubRegRange() destroys the merged range, so we need a copy. 3319 LiveRange RangeCopy(ToMerge, Allocator); 3320 joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP); 3321 } 3322 }, 3323 *LIS->getSlotIndexes(), *TRI, ComposeSubRegIdx); 3324 } 3325 3326 bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) { 3327 if (LI.valnos.size() < LargeIntervalSizeThreshold) 3328 return false; 3329 auto &Counter = LargeLIVisitCounter[LI.reg]; 3330 if (Counter < LargeIntervalFreqThreshold) { 3331 Counter++; 3332 return false; 3333 } 3334 return true; 3335 } 3336 3337 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) { 3338 SmallVector<VNInfo*, 16> NewVNInfo; 3339 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg()); 3340 LiveInterval &LHS = LIS->getInterval(CP.getDstReg()); 3341 bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC()); 3342 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(), 3343 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness); 3344 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(), 3345 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness); 3346 3347 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n'); 3348 3349 if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS)) 3350 return false; 3351 3352 // First compute NewVNInfo and the simple value mappings. 3353 // Detect impossible conflicts early. 3354 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) 3355 return false; 3356 3357 // Some conflicts can only be resolved after all values have been mapped. 3358 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals)) 3359 return false; 3360 3361 // All clear, the live ranges can be merged. 3362 if (RHS.hasSubRanges() || LHS.hasSubRanges()) { 3363 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 3364 3365 // Transform lanemasks from the LHS to masks in the coalesced register and 3366 // create initial subranges if necessary. 3367 unsigned DstIdx = CP.getDstIdx(); 3368 if (!LHS.hasSubRanges()) { 3369 LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask() 3370 : TRI->getSubRegIndexLaneMask(DstIdx); 3371 // LHS must support subregs or we wouldn't be in this codepath. 3372 assert(Mask.any()); 3373 LHS.createSubRangeFrom(Allocator, Mask, LHS); 3374 } else if (DstIdx != 0) { 3375 // Transform LHS lanemasks to new register class if necessary. 3376 for (LiveInterval::SubRange &R : LHS.subranges()) { 3377 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask); 3378 R.LaneMask = Mask; 3379 } 3380 } 3381 LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHS 3382 << '\n'); 3383 3384 // Determine lanemasks of RHS in the coalesced register and merge subranges. 3385 unsigned SrcIdx = CP.getSrcIdx(); 3386 if (!RHS.hasSubRanges()) { 3387 LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask() 3388 : TRI->getSubRegIndexLaneMask(SrcIdx); 3389 mergeSubRangeInto(LHS, RHS, Mask, CP, DstIdx); 3390 } else { 3391 // Pair up subranges and merge. 3392 for (LiveInterval::SubRange &R : RHS.subranges()) { 3393 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask); 3394 mergeSubRangeInto(LHS, R, Mask, CP, DstIdx); 3395 } 3396 } 3397 LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n"); 3398 3399 // Pruning implicit defs from subranges may result in the main range 3400 // having stale segments. 3401 LHSVals.pruneMainSegments(LHS, ShrinkMainRange); 3402 3403 LHSVals.pruneSubRegValues(LHS, ShrinkMask); 3404 RHSVals.pruneSubRegValues(LHS, ShrinkMask); 3405 } 3406 3407 // The merging algorithm in LiveInterval::join() can't handle conflicting 3408 // value mappings, so we need to remove any live ranges that overlap a 3409 // CR_Replace resolution. Collect a set of end points that can be used to 3410 // restore the live range after joining. 3411 SmallVector<SlotIndex, 8> EndPoints; 3412 LHSVals.pruneValues(RHSVals, EndPoints, true); 3413 RHSVals.pruneValues(LHSVals, EndPoints, true); 3414 3415 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external 3416 // registers to require trimming. 3417 SmallVector<unsigned, 8> ShrinkRegs; 3418 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS); 3419 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs); 3420 while (!ShrinkRegs.empty()) 3421 shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val())); 3422 3423 // Scan and mark undef any DBG_VALUEs that would refer to a different value. 3424 checkMergingChangesDbgValues(CP, LHS, LHSVals, RHS, RHSVals); 3425 3426 // Join RHS into LHS. 3427 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo); 3428 3429 // Kill flags are going to be wrong if the live ranges were overlapping. 3430 // Eventually, we should simply clear all kill flags when computing live 3431 // ranges. They are reinserted after register allocation. 3432 MRI->clearKillFlags(LHS.reg); 3433 MRI->clearKillFlags(RHS.reg); 3434 3435 if (!EndPoints.empty()) { 3436 // Recompute the parts of the live range we had to remove because of 3437 // CR_Replace conflicts. 3438 LLVM_DEBUG({ 3439 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: "; 3440 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) { 3441 dbgs() << EndPoints[i]; 3442 if (i != n-1) 3443 dbgs() << ','; 3444 } 3445 dbgs() << ": " << LHS << '\n'; 3446 }); 3447 LIS->extendToIndices((LiveRange&)LHS, EndPoints); 3448 } 3449 3450 return true; 3451 } 3452 3453 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) { 3454 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP); 3455 } 3456 3457 void RegisterCoalescer::buildVRegToDbgValueMap(MachineFunction &MF) 3458 { 3459 const SlotIndexes &Slots = *LIS->getSlotIndexes(); 3460 SmallVector<MachineInstr *, 8> ToInsert; 3461 3462 // After collecting a block of DBG_VALUEs into ToInsert, enter them into the 3463 // vreg => DbgValueLoc map. 3464 auto CloseNewDVRange = [this, &ToInsert](SlotIndex Slot) { 3465 for (auto *X : ToInsert) 3466 DbgVRegToValues[X->getOperand(0).getReg()].push_back({Slot, X}); 3467 3468 ToInsert.clear(); 3469 }; 3470 3471 // Iterate over all instructions, collecting them into the ToInsert vector. 3472 // Once a non-debug instruction is found, record the slot index of the 3473 // collected DBG_VALUEs. 3474 for (auto &MBB : MF) { 3475 SlotIndex CurrentSlot = Slots.getMBBStartIdx(&MBB); 3476 3477 for (auto &MI : MBB) { 3478 if (MI.isDebugValue() && MI.getOperand(0).isReg() && 3479 MI.getOperand(0).getReg().isVirtual()) { 3480 ToInsert.push_back(&MI); 3481 } else if (!MI.isDebugInstr()) { 3482 CurrentSlot = Slots.getInstructionIndex(MI); 3483 CloseNewDVRange(CurrentSlot); 3484 } 3485 } 3486 3487 // Close range of DBG_VALUEs at the end of blocks. 3488 CloseNewDVRange(Slots.getMBBEndIdx(&MBB)); 3489 } 3490 3491 // Sort all DBG_VALUEs we've seen by slot number. 3492 for (auto &Pair : DbgVRegToValues) 3493 llvm::sort(Pair.second); 3494 } 3495 3496 void RegisterCoalescer::checkMergingChangesDbgValues(CoalescerPair &CP, 3497 LiveRange &LHS, 3498 JoinVals &LHSVals, 3499 LiveRange &RHS, 3500 JoinVals &RHSVals) { 3501 auto ScanForDstReg = [&](unsigned Reg) { 3502 checkMergingChangesDbgValuesImpl(Reg, RHS, LHS, LHSVals); 3503 }; 3504 3505 auto ScanForSrcReg = [&](unsigned Reg) { 3506 checkMergingChangesDbgValuesImpl(Reg, LHS, RHS, RHSVals); 3507 }; 3508 3509 // Scan for potentially unsound DBG_VALUEs: examine first the register number 3510 // Reg, and then any other vregs that may have been merged into it. 3511 auto PerformScan = [this](unsigned Reg, std::function<void(unsigned)> Func) { 3512 Func(Reg); 3513 if (DbgMergedVRegNums.count(Reg)) 3514 for (unsigned X : DbgMergedVRegNums[Reg]) 3515 Func(X); 3516 }; 3517 3518 // Scan for unsound updates of both the source and destination register. 3519 PerformScan(CP.getSrcReg(), ScanForSrcReg); 3520 PerformScan(CP.getDstReg(), ScanForDstReg); 3521 } 3522 3523 void RegisterCoalescer::checkMergingChangesDbgValuesImpl(unsigned Reg, 3524 LiveRange &OtherLR, 3525 LiveRange &RegLR, 3526 JoinVals &RegVals) { 3527 // Are there any DBG_VALUEs to examine? 3528 auto VRegMapIt = DbgVRegToValues.find(Reg); 3529 if (VRegMapIt == DbgVRegToValues.end()) 3530 return; 3531 3532 auto &DbgValueSet = VRegMapIt->second; 3533 auto DbgValueSetIt = DbgValueSet.begin(); 3534 auto SegmentIt = OtherLR.begin(); 3535 3536 bool LastUndefResult = false; 3537 SlotIndex LastUndefIdx; 3538 3539 // If the "Other" register is live at a slot Idx, test whether Reg can 3540 // safely be merged with it, or should be marked undef. 3541 auto ShouldUndef = [&RegVals, &RegLR, &LastUndefResult, 3542 &LastUndefIdx](SlotIndex Idx) -> bool { 3543 // Our worst-case performance typically happens with asan, causing very 3544 // many DBG_VALUEs of the same location. Cache a copy of the most recent 3545 // result for this edge-case. 3546 if (LastUndefIdx == Idx) 3547 return LastUndefResult; 3548 3549 // If the other range was live, and Reg's was not, the register coalescer 3550 // will not have tried to resolve any conflicts. We don't know whether 3551 // the DBG_VALUE will refer to the same value number, so it must be made 3552 // undef. 3553 auto OtherIt = RegLR.find(Idx); 3554 if (OtherIt == RegLR.end()) 3555 return true; 3556 3557 // Both the registers were live: examine the conflict resolution record for 3558 // the value number Reg refers to. CR_Keep meant that this value number 3559 // "won" and the merged register definitely refers to that value. CR_Erase 3560 // means the value number was a redundant copy of the other value, which 3561 // was coalesced and Reg deleted. It's safe to refer to the other register 3562 // (which will be the source of the copy). 3563 auto Resolution = RegVals.getResolution(OtherIt->valno->id); 3564 LastUndefResult = Resolution != JoinVals::CR_Keep && 3565 Resolution != JoinVals::CR_Erase; 3566 LastUndefIdx = Idx; 3567 return LastUndefResult; 3568 }; 3569 3570 // Iterate over both the live-range of the "Other" register, and the set of 3571 // DBG_VALUEs for Reg at the same time. Advance whichever one has the lowest 3572 // slot index. This relies on the DbgValueSet being ordered. 3573 while (DbgValueSetIt != DbgValueSet.end() && SegmentIt != OtherLR.end()) { 3574 if (DbgValueSetIt->first < SegmentIt->end) { 3575 // "Other" is live and there is a DBG_VALUE of Reg: test if we should 3576 // set it undef. 3577 if (DbgValueSetIt->first >= SegmentIt->start && 3578 DbgValueSetIt->second->getOperand(0).getReg() != 0 && 3579 ShouldUndef(DbgValueSetIt->first)) { 3580 // Mark undef, erase record of this DBG_VALUE to avoid revisiting. 3581 DbgValueSetIt->second->getOperand(0).setReg(0); 3582 continue; 3583 } 3584 ++DbgValueSetIt; 3585 } else { 3586 ++SegmentIt; 3587 } 3588 } 3589 } 3590 3591 namespace { 3592 3593 /// Information concerning MBB coalescing priority. 3594 struct MBBPriorityInfo { 3595 MachineBasicBlock *MBB; 3596 unsigned Depth; 3597 bool IsSplit; 3598 3599 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit) 3600 : MBB(mbb), Depth(depth), IsSplit(issplit) {} 3601 }; 3602 3603 } // end anonymous namespace 3604 3605 /// C-style comparator that sorts first based on the loop depth of the basic 3606 /// block (the unsigned), and then on the MBB number. 3607 /// 3608 /// EnableGlobalCopies assumes that the primary sort key is loop depth. 3609 static int compareMBBPriority(const MBBPriorityInfo *LHS, 3610 const MBBPriorityInfo *RHS) { 3611 // Deeper loops first 3612 if (LHS->Depth != RHS->Depth) 3613 return LHS->Depth > RHS->Depth ? -1 : 1; 3614 3615 // Try to unsplit critical edges next. 3616 if (LHS->IsSplit != RHS->IsSplit) 3617 return LHS->IsSplit ? -1 : 1; 3618 3619 // Prefer blocks that are more connected in the CFG. This takes care of 3620 // the most difficult copies first while intervals are short. 3621 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size(); 3622 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size(); 3623 if (cl != cr) 3624 return cl > cr ? -1 : 1; 3625 3626 // As a last resort, sort by block number. 3627 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1; 3628 } 3629 3630 /// \returns true if the given copy uses or defines a local live range. 3631 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) { 3632 if (!Copy->isCopy()) 3633 return false; 3634 3635 if (Copy->getOperand(1).isUndef()) 3636 return false; 3637 3638 Register SrcReg = Copy->getOperand(1).getReg(); 3639 Register DstReg = Copy->getOperand(0).getReg(); 3640 if (Register::isPhysicalRegister(SrcReg) || 3641 Register::isPhysicalRegister(DstReg)) 3642 return false; 3643 3644 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg)) 3645 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg)); 3646 } 3647 3648 void RegisterCoalescer::lateLiveIntervalUpdate() { 3649 for (unsigned reg : ToBeUpdated) { 3650 if (!LIS->hasInterval(reg)) 3651 continue; 3652 LiveInterval &LI = LIS->getInterval(reg); 3653 shrinkToUses(&LI, &DeadDefs); 3654 if (!DeadDefs.empty()) 3655 eliminateDeadDefs(); 3656 } 3657 ToBeUpdated.clear(); 3658 } 3659 3660 bool RegisterCoalescer:: 3661 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) { 3662 bool Progress = false; 3663 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) { 3664 if (!CurrList[i]) 3665 continue; 3666 // Skip instruction pointers that have already been erased, for example by 3667 // dead code elimination. 3668 if (ErasedInstrs.count(CurrList[i])) { 3669 CurrList[i] = nullptr; 3670 continue; 3671 } 3672 bool Again = false; 3673 bool Success = joinCopy(CurrList[i], Again); 3674 Progress |= Success; 3675 if (Success || !Again) 3676 CurrList[i] = nullptr; 3677 } 3678 return Progress; 3679 } 3680 3681 /// Check if DstReg is a terminal node. 3682 /// I.e., it does not have any affinity other than \p Copy. 3683 static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy, 3684 const MachineRegisterInfo *MRI) { 3685 assert(Copy.isCopyLike()); 3686 // Check if the destination of this copy as any other affinity. 3687 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg)) 3688 if (&MI != &Copy && MI.isCopyLike()) 3689 return false; 3690 return true; 3691 } 3692 3693 bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const { 3694 assert(Copy.isCopyLike()); 3695 if (!UseTerminalRule) 3696 return false; 3697 unsigned DstReg, DstSubReg, SrcReg, SrcSubReg; 3698 if (!isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg)) 3699 return false; 3700 // Check if the destination of this copy has any other affinity. 3701 if (Register::isPhysicalRegister(DstReg) || 3702 // If SrcReg is a physical register, the copy won't be coalesced. 3703 // Ignoring it may have other side effect (like missing 3704 // rematerialization). So keep it. 3705 Register::isPhysicalRegister(SrcReg) || !isTerminalReg(DstReg, Copy, MRI)) 3706 return false; 3707 3708 // DstReg is a terminal node. Check if it interferes with any other 3709 // copy involving SrcReg. 3710 const MachineBasicBlock *OrigBB = Copy.getParent(); 3711 const LiveInterval &DstLI = LIS->getInterval(DstReg); 3712 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) { 3713 // Technically we should check if the weight of the new copy is 3714 // interesting compared to the other one and update the weight 3715 // of the copies accordingly. However, this would only work if 3716 // we would gather all the copies first then coalesce, whereas 3717 // right now we interleave both actions. 3718 // For now, just consider the copies that are in the same block. 3719 if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB) 3720 continue; 3721 unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg; 3722 if (!isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg, 3723 OtherSubReg)) 3724 return false; 3725 if (OtherReg == SrcReg) 3726 OtherReg = OtherSrcReg; 3727 // Check if OtherReg is a non-terminal. 3728 if (Register::isPhysicalRegister(OtherReg) || 3729 isTerminalReg(OtherReg, MI, MRI)) 3730 continue; 3731 // Check that OtherReg interfere with DstReg. 3732 if (LIS->getInterval(OtherReg).overlaps(DstLI)) { 3733 LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg) 3734 << '\n'); 3735 return true; 3736 } 3737 } 3738 return false; 3739 } 3740 3741 void 3742 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) { 3743 LLVM_DEBUG(dbgs() << MBB->getName() << ":\n"); 3744 3745 // Collect all copy-like instructions in MBB. Don't start coalescing anything 3746 // yet, it might invalidate the iterator. 3747 const unsigned PrevSize = WorkList.size(); 3748 if (JoinGlobalCopies) { 3749 SmallVector<MachineInstr*, 2> LocalTerminals; 3750 SmallVector<MachineInstr*, 2> GlobalTerminals; 3751 // Coalesce copies bottom-up to coalesce local defs before local uses. They 3752 // are not inherently easier to resolve, but slightly preferable until we 3753 // have local live range splitting. In particular this is required by 3754 // cmp+jmp macro fusion. 3755 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); 3756 MII != E; ++MII) { 3757 if (!MII->isCopyLike()) 3758 continue; 3759 bool ApplyTerminalRule = applyTerminalRule(*MII); 3760 if (isLocalCopy(&(*MII), LIS)) { 3761 if (ApplyTerminalRule) 3762 LocalTerminals.push_back(&(*MII)); 3763 else 3764 LocalWorkList.push_back(&(*MII)); 3765 } else { 3766 if (ApplyTerminalRule) 3767 GlobalTerminals.push_back(&(*MII)); 3768 else 3769 WorkList.push_back(&(*MII)); 3770 } 3771 } 3772 // Append the copies evicted by the terminal rule at the end of the list. 3773 LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end()); 3774 WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end()); 3775 } 3776 else { 3777 SmallVector<MachineInstr*, 2> Terminals; 3778 for (MachineInstr &MII : *MBB) 3779 if (MII.isCopyLike()) { 3780 if (applyTerminalRule(MII)) 3781 Terminals.push_back(&MII); 3782 else 3783 WorkList.push_back(&MII); 3784 } 3785 // Append the copies evicted by the terminal rule at the end of the list. 3786 WorkList.append(Terminals.begin(), Terminals.end()); 3787 } 3788 // Try coalescing the collected copies immediately, and remove the nulls. 3789 // This prevents the WorkList from getting too large since most copies are 3790 // joinable on the first attempt. 3791 MutableArrayRef<MachineInstr*> 3792 CurrList(WorkList.begin() + PrevSize, WorkList.end()); 3793 if (copyCoalesceWorkList(CurrList)) 3794 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(), 3795 nullptr), WorkList.end()); 3796 } 3797 3798 void RegisterCoalescer::coalesceLocals() { 3799 copyCoalesceWorkList(LocalWorkList); 3800 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) { 3801 if (LocalWorkList[j]) 3802 WorkList.push_back(LocalWorkList[j]); 3803 } 3804 LocalWorkList.clear(); 3805 } 3806 3807 void RegisterCoalescer::joinAllIntervals() { 3808 LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n"); 3809 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around."); 3810 3811 std::vector<MBBPriorityInfo> MBBs; 3812 MBBs.reserve(MF->size()); 3813 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) { 3814 MachineBasicBlock *MBB = &*I; 3815 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB), 3816 JoinSplitEdges && isSplitEdge(MBB))); 3817 } 3818 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority); 3819 3820 // Coalesce intervals in MBB priority order. 3821 unsigned CurrDepth = std::numeric_limits<unsigned>::max(); 3822 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) { 3823 // Try coalescing the collected local copies for deeper loops. 3824 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) { 3825 coalesceLocals(); 3826 CurrDepth = MBBs[i].Depth; 3827 } 3828 copyCoalesceInMBB(MBBs[i].MBB); 3829 } 3830 lateLiveIntervalUpdate(); 3831 coalesceLocals(); 3832 3833 // Joining intervals can allow other intervals to be joined. Iteratively join 3834 // until we make no progress. 3835 while (copyCoalesceWorkList(WorkList)) 3836 /* empty */ ; 3837 lateLiveIntervalUpdate(); 3838 } 3839 3840 void RegisterCoalescer::releaseMemory() { 3841 ErasedInstrs.clear(); 3842 WorkList.clear(); 3843 DeadDefs.clear(); 3844 InflateRegs.clear(); 3845 LargeLIVisitCounter.clear(); 3846 } 3847 3848 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) { 3849 MF = &fn; 3850 MRI = &fn.getRegInfo(); 3851 const TargetSubtargetInfo &STI = fn.getSubtarget(); 3852 TRI = STI.getRegisterInfo(); 3853 TII = STI.getInstrInfo(); 3854 LIS = &getAnalysis<LiveIntervals>(); 3855 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3856 Loops = &getAnalysis<MachineLoopInfo>(); 3857 if (EnableGlobalCopies == cl::BOU_UNSET) 3858 JoinGlobalCopies = STI.enableJoinGlobalCopies(); 3859 else 3860 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE); 3861 3862 // The MachineScheduler does not currently require JoinSplitEdges. This will 3863 // either be enabled unconditionally or replaced by a more general live range 3864 // splitting optimization. 3865 JoinSplitEdges = EnableJoinSplits; 3866 3867 LLVM_DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n" 3868 << "********** Function: " << MF->getName() << '\n'); 3869 3870 if (VerifyCoalescing) 3871 MF->verify(this, "Before register coalescing"); 3872 3873 DbgVRegToValues.clear(); 3874 DbgMergedVRegNums.clear(); 3875 buildVRegToDbgValueMap(fn); 3876 3877 RegClassInfo.runOnMachineFunction(fn); 3878 3879 // Join (coalesce) intervals if requested. 3880 if (EnableJoining) 3881 joinAllIntervals(); 3882 3883 // After deleting a lot of copies, register classes may be less constrained. 3884 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 -> 3885 // DPR inflation. 3886 array_pod_sort(InflateRegs.begin(), InflateRegs.end()); 3887 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()), 3888 InflateRegs.end()); 3889 LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() 3890 << " regs.\n"); 3891 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) { 3892 unsigned Reg = InflateRegs[i]; 3893 if (MRI->reg_nodbg_empty(Reg)) 3894 continue; 3895 if (MRI->recomputeRegClass(Reg)) { 3896 LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to " 3897 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n'); 3898 ++NumInflated; 3899 3900 LiveInterval &LI = LIS->getInterval(Reg); 3901 if (LI.hasSubRanges()) { 3902 // If the inflated register class does not support subregisters anymore 3903 // remove the subranges. 3904 if (!MRI->shouldTrackSubRegLiveness(Reg)) { 3905 LI.clearSubRanges(); 3906 } else { 3907 #ifndef NDEBUG 3908 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg); 3909 // If subranges are still supported, then the same subregs 3910 // should still be supported. 3911 for (LiveInterval::SubRange &S : LI.subranges()) { 3912 assert((S.LaneMask & ~MaxMask).none()); 3913 } 3914 #endif 3915 } 3916 } 3917 } 3918 } 3919 3920 LLVM_DEBUG(dump()); 3921 if (VerifyCoalescing) 3922 MF->verify(this, "After register coalescing"); 3923 return true; 3924 } 3925 3926 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const { 3927 LIS->print(O, m); 3928 } 3929