1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "LiveDebugVariables.h"
19 #include "VirtRegMap.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Value.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/LiveRangeEdit.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegisterClassInfo.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegisterInfo.h"
52 STATISTIC(numJoins , "Number of interval joins performed");
53 STATISTIC(numCrossRCs , "Number of cross class joins performed");
54 STATISTIC(numCommutes , "Number of instruction commuting performed");
55 STATISTIC(numExtends , "Number of copies extended");
56 STATISTIC(NumReMats , "Number of instructions re-materialized");
57 STATISTIC(NumInflated , "Number of register classes inflated");
60 EnableJoining("join-liveintervals",
61 cl::desc("Coalesce copies (default=true)"),
65 VerifyCoalescing("verify-coalescing",
66 cl::desc("Verify machine instrs before and after register coalescing"),
69 // Temporary option for testing new coalescer algo.
71 NewCoalescer("new-coalescer", cl::Hidden,
72 cl::desc("Use new coalescer algorithm"));
75 class RegisterCoalescer : public MachineFunctionPass,
76 private LiveRangeEdit::Delegate {
78 MachineRegisterInfo* MRI;
79 const TargetMachine* TM;
80 const TargetRegisterInfo* TRI;
81 const TargetInstrInfo* TII;
83 LiveDebugVariables *LDV;
84 const MachineLoopInfo* Loops;
86 RegisterClassInfo RegClassInfo;
88 /// WorkList - Copy instructions yet to be coalesced.
89 SmallVector<MachineInstr*, 8> WorkList;
91 /// ErasedInstrs - Set of instruction pointers that have been erased, and
92 /// that may be present in WorkList.
93 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
95 /// Dead instructions that are about to be deleted.
96 SmallVector<MachineInstr*, 8> DeadDefs;
98 /// Virtual registers to be considered for register class inflation.
99 SmallVector<unsigned, 8> InflateRegs;
101 /// Recursively eliminate dead defs in DeadDefs.
102 void eliminateDeadDefs();
104 /// LiveRangeEdit callback.
105 void LRE_WillEraseInstruction(MachineInstr *MI);
107 /// joinAllIntervals - join compatible live intervals
108 void joinAllIntervals();
110 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
111 /// copies that cannot yet be coalesced into WorkList.
112 void copyCoalesceInMBB(MachineBasicBlock *MBB);
114 /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
115 /// position From. Return true if any progress was made.
116 bool copyCoalesceWorkList(unsigned From = 0);
118 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
119 /// which are the src/dst of the copy instruction CopyMI. This returns
120 /// true if the copy was successfully coalesced away. If it is not
121 /// currently possible to coalesce this interval, but it may be possible if
122 /// other things get coalesced, then it returns true by reference in
124 bool joinCopy(MachineInstr *TheCopy, bool &Again);
126 /// joinIntervals - Attempt to join these two intervals. On failure, this
127 /// returns false. The output "SrcInt" will not have been modified, so we
128 /// can use this information below to update aliases.
129 bool joinIntervals(CoalescerPair &CP);
131 /// Attempt joining two virtual registers. Return true on success.
132 bool joinVirtRegs(CoalescerPair &CP);
134 /// Attempt joining with a reserved physreg.
135 bool joinReservedPhysReg(CoalescerPair &CP);
137 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
138 /// the source value number is defined by a copy from the destination reg
139 /// see if we can merge these two destination reg valno# into a single
140 /// value number, eliminating a copy.
141 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
143 /// hasOtherReachingDefs - Return true if there are definitions of IntB
144 /// other than BValNo val# that can reach uses of AValno val# of IntA.
145 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
146 VNInfo *AValNo, VNInfo *BValNo);
148 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
149 /// If the source value number is defined by a commutable instruction and
150 /// its other operand is coalesced to the copy dest register, see if we
151 /// can transform the copy into a noop by commuting the definition.
152 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
154 /// reMaterializeTrivialDef - If the source of a copy is defined by a
155 /// trivial computation, replace the copy by rematerialize the definition.
156 bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
157 MachineInstr *CopyMI);
159 /// canJoinPhys - Return true if a physreg copy should be joined.
160 bool canJoinPhys(CoalescerPair &CP);
162 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
163 /// update the subregister number if it is not zero. If DstReg is a
164 /// physical register and the existing subregister number of the def / use
165 /// being updated is not zero, make sure to set it to the correct physical
167 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
169 /// eliminateUndefCopy - Handle copies of undef values.
170 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
173 static char ID; // Class identification, replacement for typeinfo
174 RegisterCoalescer() : MachineFunctionPass(ID) {
175 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
178 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
180 virtual void releaseMemory();
182 /// runOnMachineFunction - pass entry point
183 virtual bool runOnMachineFunction(MachineFunction&);
185 /// print - Implement the dump method.
186 virtual void print(raw_ostream &O, const Module* = 0) const;
188 } /// end anonymous namespace
190 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
192 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
193 "Simple Register Coalescing", false, false)
194 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
195 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
196 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
197 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
198 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
199 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
200 "Simple Register Coalescing", false, false)
202 char RegisterCoalescer::ID = 0;
204 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
207 return tri.composeSubRegIndices(a, b);
210 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
211 unsigned &Src, unsigned &Dst,
212 unsigned &SrcSub, unsigned &DstSub) {
214 Dst = MI->getOperand(0).getReg();
215 DstSub = MI->getOperand(0).getSubReg();
216 Src = MI->getOperand(1).getReg();
217 SrcSub = MI->getOperand(1).getSubReg();
218 } else if (MI->isSubregToReg()) {
219 Dst = MI->getOperand(0).getReg();
220 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
221 MI->getOperand(3).getImm());
222 Src = MI->getOperand(2).getReg();
223 SrcSub = MI->getOperand(2).getSubReg();
229 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
233 Flipped = CrossClass = false;
235 unsigned Src, Dst, SrcSub, DstSub;
236 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
238 Partial = SrcSub || DstSub;
240 // If one register is a physreg, it must be Dst.
241 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
242 if (TargetRegisterInfo::isPhysicalRegister(Dst))
245 std::swap(SrcSub, DstSub);
249 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
251 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
252 // Eliminate DstSub on a physreg.
254 Dst = TRI.getSubReg(Dst, DstSub);
255 if (!Dst) return false;
259 // Eliminate SrcSub by picking a corresponding Dst superregister.
261 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
262 if (!Dst) return false;
264 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
268 // Both registers are virtual.
269 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
270 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
272 // Both registers have subreg indices.
273 if (SrcSub && DstSub) {
274 // Copies between different sub-registers are never coalescable.
275 if (Src == Dst && SrcSub != DstSub)
278 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
283 // SrcReg will be merged with a sub-register of DstReg.
285 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
287 // DstReg will be merged with a sub-register of SrcReg.
289 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
291 // This is a straight copy without sub-registers.
292 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
295 // The combined constraint may be impossible to satisfy.
299 // Prefer SrcReg to be a sub-register of DstReg.
300 // FIXME: Coalescer should support subregs symmetrically.
301 if (DstIdx && !SrcIdx) {
303 std::swap(SrcIdx, DstIdx);
307 CrossClass = NewRC != DstRC || NewRC != SrcRC;
309 // Check our invariants
310 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
311 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
312 "Cannot have a physical SubIdx");
318 bool CoalescerPair::flip() {
319 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
321 std::swap(SrcReg, DstReg);
322 std::swap(SrcIdx, DstIdx);
327 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
330 unsigned Src, Dst, SrcSub, DstSub;
331 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
334 // Find the virtual register that is SrcReg.
337 std::swap(SrcSub, DstSub);
338 } else if (Src != SrcReg) {
342 // Now check that Dst matches DstReg.
343 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
344 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
346 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
347 // DstSub could be set for a physreg from INSERT_SUBREG.
349 Dst = TRI.getSubReg(Dst, DstSub);
352 return DstReg == Dst;
353 // This is a partial register copy. Check that the parts match.
354 return TRI.getSubReg(DstReg, SrcSub) == Dst;
356 // DstReg is virtual.
359 // Registers match, do the subregisters line up?
360 return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
364 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
365 AU.setPreservesCFG();
366 AU.addRequired<AliasAnalysis>();
367 AU.addRequired<LiveIntervals>();
368 AU.addPreserved<LiveIntervals>();
369 AU.addRequired<LiveDebugVariables>();
370 AU.addPreserved<LiveDebugVariables>();
371 AU.addPreserved<SlotIndexes>();
372 AU.addRequired<MachineLoopInfo>();
373 AU.addPreserved<MachineLoopInfo>();
374 AU.addPreservedID(MachineDominatorsID);
375 MachineFunctionPass::getAnalysisUsage(AU);
378 void RegisterCoalescer::eliminateDeadDefs() {
379 SmallVector<LiveInterval*, 8> NewRegs;
380 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
383 // Callback from eliminateDeadDefs().
384 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
385 // MI may be in WorkList. Make sure we don't visit it.
386 ErasedInstrs.insert(MI);
389 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
390 /// being the source and IntB being the dest, thus this defines a value number
391 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
392 /// see if we can merge these two pieces of B into a single value number,
393 /// eliminating a copy. For example:
397 /// B1 = A3 <- this copy
399 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
400 /// value number to be replaced with B0 (which simplifies the B liveinterval).
402 /// This returns true if an interval was modified.
404 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
405 MachineInstr *CopyMI) {
406 assert(!CP.isPartial() && "This doesn't work for partial copies.");
407 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
410 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
412 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
413 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
415 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
416 // the example above.
417 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
418 if (BLR == IntB.end()) return false;
419 VNInfo *BValNo = BLR->valno;
421 // Get the location that B is defined at. Two options: either this value has
422 // an unknown definition point or it is defined at CopyIdx. If unknown, we
424 if (BValNo->def != CopyIdx) return false;
426 // AValNo is the value number in A that defines the copy, A3 in the example.
427 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
428 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
429 // The live range might not exist after fun with physreg coalescing.
430 if (ALR == IntA.end()) return false;
431 VNInfo *AValNo = ALR->valno;
433 // If AValNo is defined as a copy from IntB, we can potentially process this.
434 // Get the instruction that defines this value number.
435 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
436 if (!CP.isCoalescable(ACopyMI))
439 // Get the LiveRange in IntB that this value number starts with.
440 LiveInterval::iterator ValLR =
441 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
442 if (ValLR == IntB.end())
445 // Make sure that the end of the live range is inside the same block as
447 MachineInstr *ValLREndInst =
448 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
449 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
452 // Okay, we now know that ValLR ends in the same block that the CopyMI
453 // live-range starts. If there are no intervening live ranges between them in
454 // IntB, we can merge them.
455 if (ValLR+1 != BLR) return false;
457 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
459 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
460 // We are about to delete CopyMI, so need to remove it as the 'instruction
461 // that defines this value #'. Update the valnum with the new defining
463 BValNo->def = FillerStart;
465 // Okay, we can merge them. We need to insert a new liverange:
466 // [ValLR.end, BLR.begin) of either value number, then we merge the
467 // two value numbers.
468 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
470 // Okay, merge "B1" into the same value number as "B0".
471 if (BValNo != ValLR->valno)
472 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
473 DEBUG(dbgs() << " result = " << IntB << '\n');
475 // If the source instruction was killing the source register before the
476 // merge, unset the isKill marker given the live range has been extended.
477 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
479 ValLREndInst->getOperand(UIdx).setIsKill(false);
482 // Rewrite the copy. If the copy instruction was killing the destination
483 // register before the merge, find the last use and trim the live range. That
484 // will also add the isKill marker.
485 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
486 if (ALR->end == CopyIdx)
487 LIS->shrinkToUses(&IntA);
493 /// hasOtherReachingDefs - Return true if there are definitions of IntB
494 /// other than BValNo val# that can reach uses of AValno val# of IntA.
495 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
499 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
501 if (LIS->hasPHIKill(IntA, AValNo))
504 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
506 if (AI->valno != AValNo) continue;
507 LiveInterval::Ranges::iterator BI =
508 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
509 if (BI != IntB.ranges.begin())
511 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
512 if (BI->valno == BValNo)
514 if (BI->start <= AI->start && BI->end > AI->start)
516 if (BI->start > AI->start && BI->start < AI->end)
523 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
524 /// IntA being the source and IntB being the dest, thus this defines a value
525 /// number in IntB. If the source value number (in IntA) is defined by a
526 /// commutable instruction and its other operand is coalesced to the copy dest
527 /// register, see if we can transform the copy into a noop by commuting the
528 /// definition. For example,
530 /// A3 = op A2 B0<kill>
532 /// B1 = A3 <- this copy
534 /// = op A3 <- more uses
538 /// B2 = op B0 A2<kill>
540 /// B1 = B2 <- now an identify copy
542 /// = op B2 <- more uses
544 /// This returns true if an interval was modified.
546 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
547 MachineInstr *CopyMI) {
548 assert (!CP.isPhys());
550 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
553 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
555 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
557 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
558 // the example above.
559 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
560 if (!BValNo || BValNo->def != CopyIdx)
563 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
565 // AValNo is the value number in A that defines the copy, A3 in the example.
566 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
567 assert(AValNo && "COPY source not live");
568 if (AValNo->isPHIDef() || AValNo->isUnused())
570 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
573 if (!DefMI->isCommutable())
575 // If DefMI is a two-address instruction then commuting it will change the
576 // destination register.
577 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
578 assert(DefIdx != -1);
580 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
582 unsigned Op1, Op2, NewDstIdx;
583 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
587 else if (Op2 == UseOpIdx)
592 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
593 unsigned NewReg = NewDstMO.getReg();
594 if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill())
597 // Make sure there are no other definitions of IntB that would reach the
598 // uses which the new definition can reach.
599 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
602 // If some of the uses of IntA.reg is already coalesced away, return false.
603 // It's not possible to determine whether it's safe to perform the coalescing.
604 for (MachineRegisterInfo::use_nodbg_iterator UI =
605 MRI->use_nodbg_begin(IntA.reg),
606 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
607 MachineInstr *UseMI = &*UI;
608 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
609 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
610 if (ULR == IntA.end() || ULR->valno != AValNo)
612 // If this use is tied to a def, we can't rewrite the register.
613 if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
617 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
620 // At this point we have decided that it is legal to do this
621 // transformation. Start by commuting the instruction.
622 MachineBasicBlock *MBB = DefMI->getParent();
623 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
626 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
627 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
628 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
630 if (NewMI != DefMI) {
631 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
632 MachineBasicBlock::iterator Pos = DefMI;
633 MBB->insert(Pos, NewMI);
636 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
637 NewMI->getOperand(OpIdx).setIsKill();
639 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
648 // Update uses of IntA of the specific Val# with IntB.
649 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
650 UE = MRI->use_end(); UI != UE;) {
651 MachineOperand &UseMO = UI.getOperand();
652 MachineInstr *UseMI = &*UI;
654 if (UseMI->isDebugValue()) {
655 // FIXME These don't have an instruction index. Not clear we have enough
656 // info to decide whether to do this replacement or not. For now do it.
657 UseMO.setReg(NewReg);
660 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
661 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
662 if (ULR == IntA.end() || ULR->valno != AValNo)
664 // Kill flags are no longer accurate. They are recomputed after RA.
665 UseMO.setIsKill(false);
666 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
667 UseMO.substPhysReg(NewReg, *TRI);
669 UseMO.setReg(NewReg);
672 if (!UseMI->isCopy())
674 if (UseMI->getOperand(0).getReg() != IntB.reg ||
675 UseMI->getOperand(0).getSubReg())
678 // This copy will become a noop. If it's defining a new val#, merge it into
680 SlotIndex DefIdx = UseIdx.getRegSlot();
681 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
684 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
685 assert(DVNI->def == DefIdx);
686 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
687 ErasedInstrs.insert(UseMI);
688 LIS->RemoveMachineInstrFromMaps(UseMI);
689 UseMI->eraseFromParent();
692 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
694 VNInfo *ValNo = BValNo;
695 ValNo->def = AValNo->def;
696 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
698 if (AI->valno != AValNo) continue;
699 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
701 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
703 IntA.removeValNo(AValNo);
704 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
709 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
710 /// computation, replace the copy by rematerialize the definition.
711 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
713 MachineInstr *CopyMI) {
714 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
715 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
716 assert(SrcLR != SrcInt.end() && "Live range not found!");
717 VNInfo *ValNo = SrcLR->valno;
718 if (ValNo->isPHIDef() || ValNo->isUnused())
720 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
723 assert(DefMI && "Defining instruction disappeared");
724 if (!DefMI->isAsCheapAsAMove())
726 if (!TII->isTriviallyReMaterializable(DefMI, AA))
728 bool SawStore = false;
729 if (!DefMI->isSafeToMove(TII, AA, SawStore))
731 const MCInstrDesc &MCID = DefMI->getDesc();
732 if (MCID.getNumDefs() != 1)
734 if (!DefMI->isImplicitDef()) {
735 // Make sure the copy destination register class fits the instruction
736 // definition register class. The mismatch can happen as a result of earlier
737 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
738 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
739 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
740 if (MRI->getRegClass(DstReg) != RC)
742 } else if (!RC->contains(DstReg))
746 MachineBasicBlock *MBB = CopyMI->getParent();
747 MachineBasicBlock::iterator MII =
748 llvm::next(MachineBasicBlock::iterator(CopyMI));
749 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
750 MachineInstr *NewMI = prior(MII);
752 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
753 // We need to remember these so we can add intervals once we insert
754 // NewMI into SlotIndexes.
755 SmallVector<unsigned, 4> NewMIImplDefs;
756 for (unsigned i = NewMI->getDesc().getNumOperands(),
757 e = NewMI->getNumOperands(); i != e; ++i) {
758 MachineOperand &MO = NewMI->getOperand(i);
760 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
761 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
762 NewMIImplDefs.push_back(MO.getReg());
766 // CopyMI may have implicit operands, transfer them over to the newly
767 // rematerialized instruction. And update implicit def interval valnos.
768 for (unsigned i = CopyMI->getDesc().getNumOperands(),
769 e = CopyMI->getNumOperands(); i != e; ++i) {
770 MachineOperand &MO = CopyMI->getOperand(i);
772 assert(MO.isImplicit() && "No explicit operands after implict operands.");
773 // Discard VReg implicit defs.
774 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
775 NewMI->addOperand(MO);
780 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
782 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
783 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
784 unsigned Reg = NewMIImplDefs[i];
785 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
786 if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
787 LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
790 CopyMI->eraseFromParent();
791 ErasedInstrs.insert(CopyMI);
792 DEBUG(dbgs() << "Remat: " << *NewMI);
795 // The source interval can become smaller because we removed a use.
796 LIS->shrinkToUses(&SrcInt, &DeadDefs);
797 if (!DeadDefs.empty())
803 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
804 /// values, it only removes local variables. When we have a copy like:
806 /// %vreg1 = COPY %vreg2<undef>
808 /// We delete the copy and remove the corresponding value number from %vreg1.
809 /// Any uses of that value number are marked as <undef>.
810 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
811 const CoalescerPair &CP) {
812 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
813 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
814 if (SrcInt->liveAt(Idx))
816 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
817 if (DstInt->liveAt(Idx))
820 // No intervals are live-in to CopyMI - it is undef.
825 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
826 assert(DeadVNI && "No value defined in DstInt");
827 DstInt->removeValNo(DeadVNI);
829 // Find new undef uses.
830 for (MachineRegisterInfo::reg_nodbg_iterator
831 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
833 MachineOperand &MO = I.getOperand();
834 if (MO.isDef() || MO.isUndef())
836 MachineInstr *MI = MO.getParent();
837 SlotIndex Idx = LIS->getInstructionIndex(MI);
838 if (DstInt->liveAt(Idx))
841 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
846 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
847 /// update the subregister number if it is not zero. If DstReg is a
848 /// physical register and the existing subregister number of the def / use
849 /// being updated is not zero, make sure to set it to the correct physical
851 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
854 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
855 LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
857 // Update LiveDebugVariables.
858 LDV->renameRegister(SrcReg, DstReg, SubIdx);
860 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
861 MachineInstr *UseMI = I.skipInstruction();) {
862 SmallVector<unsigned,8> Ops;
864 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
866 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
867 // because SrcReg is a sub-register.
868 if (DstInt && !Reads && SubIdx)
869 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
871 // Replace SrcReg with DstReg in all UseMI operands.
872 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
873 MachineOperand &MO = UseMI->getOperand(Ops[i]);
875 // Adjust <undef> flags in case of sub-register joins. We don't want to
876 // turn a full def into a read-modify-write sub-register def and vice
878 if (SubIdx && MO.isDef())
879 MO.setIsUndef(!Reads);
882 MO.substPhysReg(DstReg, *TRI);
884 MO.substVirtReg(DstReg, SubIdx, *TRI);
888 dbgs() << "\t\tupdated: ";
889 if (!UseMI->isDebugValue())
890 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
896 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
897 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
898 /// Always join simple intervals that are defined by a single copy from a
899 /// reserved register. This doesn't increase register pressure, so it is
900 /// always beneficial.
901 if (!RegClassInfo.isReserved(CP.getDstReg())) {
902 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
906 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
907 if (CP.isFlipped() && JoinVInt.containsOneValue())
910 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
914 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
915 /// which are the src/dst of the copy instruction CopyMI. This returns true
916 /// if the copy was successfully coalesced away. If it is not currently
917 /// possible to coalesce this interval, but it may be possible if other
918 /// things get coalesced, then it returns true by reference in 'Again'.
919 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
922 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
924 CoalescerPair CP(*TRI);
925 if (!CP.setRegisters(CopyMI)) {
926 DEBUG(dbgs() << "\tNot coalescable.\n");
930 // Dead code elimination. This really should be handled by MachineDCE, but
931 // sometimes dead copies slip through, and we can't generate invalid live
933 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
934 DEBUG(dbgs() << "\tCopy is dead.\n");
935 DeadDefs.push_back(CopyMI);
941 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
942 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
943 LIS->RemoveMachineInstrFromMaps(CopyMI);
944 CopyMI->eraseFromParent();
945 return false; // Not coalescable.
948 // Coalesced copies are normally removed immediately, but transformations
949 // like removeCopyByCommutingDef() can inadvertently create identity copies.
950 // When that happens, just join the values and remove the copy.
951 if (CP.getSrcReg() == CP.getDstReg()) {
952 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
953 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
954 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
955 if (VNInfo *DefVNI = LRQ.valueDefined()) {
956 VNInfo *ReadVNI = LRQ.valueIn();
957 assert(ReadVNI && "No value before copy and no <undef> flag.");
958 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
959 LI.MergeValueNumberInto(DefVNI, ReadVNI);
960 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
962 LIS->RemoveMachineInstrFromMaps(CopyMI);
963 CopyMI->eraseFromParent();
969 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
970 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
972 if (!canJoinPhys(CP)) {
973 // Before giving up coalescing, if definition of source is defined by
974 // trivial computation, try rematerializing it.
975 if (!CP.isFlipped() &&
976 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
977 CP.getDstReg(), CopyMI))
983 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
985 if (CP.getDstIdx() && CP.getSrcIdx())
986 dbgs() << PrintReg(CP.getDstReg()) << " in "
987 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
988 << PrintReg(CP.getSrcReg()) << " in "
989 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
991 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
992 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
995 // When possible, let DstReg be the larger interval.
996 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
997 LIS->getInterval(CP.getDstReg()).ranges.size())
1001 // Okay, attempt to join these two intervals. On failure, this returns false.
1002 // Otherwise, if one of the intervals being joined is a physreg, this method
1003 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1004 // been modified, so we can use this information below to update aliases.
1005 if (!joinIntervals(CP)) {
1006 // Coalescing failed.
1008 // If definition of source is defined by trivial computation, try
1009 // rematerializing it.
1010 if (!CP.isFlipped() &&
1011 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1012 CP.getDstReg(), CopyMI))
1015 // If we can eliminate the copy without merging the live ranges, do so now.
1016 if (!CP.isPartial() && !CP.isPhys()) {
1017 if (adjustCopiesBackFrom(CP, CopyMI) ||
1018 removeCopyByCommutingDef(CP, CopyMI)) {
1019 LIS->RemoveMachineInstrFromMaps(CopyMI);
1020 CopyMI->eraseFromParent();
1021 DEBUG(dbgs() << "\tTrivial!\n");
1026 // Otherwise, we are unable to join the intervals.
1027 DEBUG(dbgs() << "\tInterference!\n");
1028 Again = true; // May be possible to coalesce later.
1032 // Coalescing to a virtual register that is of a sub-register class of the
1033 // other. Make sure the resulting register is set to the right register class.
1034 if (CP.isCrossClass()) {
1036 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1039 // Removing sub-register copies can ease the register class constraints.
1040 // Make sure we attempt to inflate the register class of DstReg.
1041 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1042 InflateRegs.push_back(CP.getDstReg());
1044 // CopyMI has been erased by joinIntervals at this point. Remove it from
1045 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1046 // to the work list. This keeps ErasedInstrs from growing needlessly.
1047 ErasedInstrs.erase(CopyMI);
1049 // Rewrite all SrcReg operands to DstReg.
1050 // Also update DstReg operands to include DstIdx if it is set.
1052 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1053 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1055 // SrcReg is guaranteed to be the register whose live interval that is
1057 LIS->removeInterval(CP.getSrcReg());
1059 // Update regalloc hint.
1060 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1063 dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1065 dbgs() << LIS->getInterval(CP.getDstReg());
1073 /// Attempt joining with a reserved physreg.
1074 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1075 assert(CP.isPhys() && "Must be a physreg copy");
1076 assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1077 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1078 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1081 assert(CP.isFlipped() && RHS.containsOneValue() &&
1082 "Invalid join with reserved register");
1084 // Optimization for reserved registers like ESP. We can only merge with a
1085 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1086 // The live range of the reserved register will look like a set of dead defs
1087 // - we don't properly track the live range of reserved registers.
1089 // Deny any overlapping intervals. This depends on all the reserved
1090 // register live ranges to look like dead defs.
1091 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1092 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1093 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1097 // Skip any value computations, we are not adding new values to the
1098 // reserved register. Also skip merging the live ranges, the reserved
1099 // register live range doesn't need to be accurate as long as all the
1102 // Delete the identity copy.
1103 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1104 LIS->RemoveMachineInstrFromMaps(CopyMI);
1105 CopyMI->eraseFromParent();
1107 // We don't track kills for reserved registers.
1108 MRI->clearKillFlags(CP.getSrcReg());
1113 //===----------------------------------------------------------------------===//
1114 // Interference checking and interval joining
1115 //===----------------------------------------------------------------------===//
1117 // In the easiest case, the two live ranges being joined are disjoint, and
1118 // there is no interference to consider. It is quite common, though, to have
1119 // overlapping live ranges, and we need to check if the interference can be
1122 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1123 // This means that two SSA values overlap if and only if the def of one value
1124 // is contained in the live range of the other value. As a special case, the
1125 // overlapping values can be defined at the same index.
1127 // The interference from an overlapping def can be resolved in these cases:
1129 // 1. Coalescable copies. The value is defined by a copy that would become an
1130 // identity copy after joining SrcReg and DstReg. The copy instruction will
1131 // be removed, and the value will be merged with the source value.
1133 // There can be several copies back and forth, causing many values to be
1134 // merged into one. We compute a list of ultimate values in the joined live
1135 // range as well as a mappings from the old value numbers.
1137 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1138 // predecessors have a live out value. It doesn't cause real interference,
1139 // and can be merged into the value it overlaps. Like a coalescable copy, it
1140 // can be erased after joining.
1142 // 3. Copy of external value. The overlapping def may be a copy of a value that
1143 // is already in the other register. This is like a coalescable copy, but
1144 // the live range of the source register must be trimmed after erasing the
1145 // copy instruction:
1148 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1150 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1151 // defining one lane at a time:
1153 // %dst:ssub0<def,read-undef> = FOO
1155 // %dst:ssub1<def> = COPY %src
1157 // The live range of %src overlaps the %dst value defined by FOO, but
1158 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1159 // which was undef anyway.
1161 // The value mapping is more complicated in this case. The final live range
1162 // will have different value numbers for both FOO and BAR, but there is no
1163 // simple mapping from old to new values. It may even be necessary to add
1166 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1167 // is live, but never read. This can happen because we don't compute
1168 // individual live ranges per lane.
1172 // %dst:ssub1<def> = COPY %src
1174 // This kind of interference is only resolved locally. If the clobbered
1175 // lane value escapes the block, the join is aborted.
1178 /// Track information about values in a single virtual register about to be
1179 /// joined. Objects of this class are always created in pairs - one for each
1180 /// side of the CoalescerPair.
1184 // Location of this register in the final joined register.
1185 // Either CP.DstIdx or CP.SrcIdx.
1188 // Values that will be present in the final live range.
1189 SmallVectorImpl<VNInfo*> &NewVNInfo;
1191 const CoalescerPair &CP;
1193 SlotIndexes *Indexes;
1194 const TargetRegisterInfo *TRI;
1196 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1197 // This is suitable for passing to LiveInterval::join().
1198 SmallVector<int, 8> Assignments;
1200 // Conflict resolution for overlapping values.
1201 enum ConflictResolution {
1202 // No overlap, simply keep this value.
1205 // Merge this value into OtherVNI and erase the defining instruction.
1206 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1210 // Merge this value into OtherVNI but keep the defining instruction.
1211 // This is for the special case where OtherVNI is defined by the same
1215 // Keep this value, and have it replace OtherVNI where possible. This
1216 // complicates value mapping since OtherVNI maps to two different values
1217 // before and after this def.
1218 // Used when clobbering undefined or dead lanes.
1221 // Unresolved conflict. Visit later when all values have been mapped.
1224 // Unresolvable conflict. Abort the join.
1228 // Per-value info for LI. The lane bit masks are all relative to the final
1229 // joined register, so they can be compared directly between SrcReg and
1232 ConflictResolution Resolution;
1234 // Lanes written by this def, 0 for unanalyzed values.
1235 unsigned WriteLanes;
1237 // Lanes with defined values in this register. Other lanes are undef and
1239 unsigned ValidLanes;
1241 // Value in LI being redefined by this def.
1244 // Value in the other live range that overlaps this def, if any.
1247 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1248 RedefVNI(0), OtherVNI(0) {}
1250 bool isAnalyzed() const { return WriteLanes != 0; }
1253 // One entry per value number in LI.
1254 SmallVector<Val, 8> Vals;
1256 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1257 VNInfo *stripCopies(VNInfo *VNI);
1258 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1259 void computeAssignment(unsigned ValNo, JoinVals &Other);
1262 JoinVals(LiveInterval &li, unsigned subIdx,
1263 SmallVectorImpl<VNInfo*> &newVNInfo,
1264 const CoalescerPair &cp,
1266 const TargetRegisterInfo *tri)
1267 : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1268 Indexes(LIS->getSlotIndexes()), TRI(tri),
1269 Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1272 /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1273 /// Returns false if any conflicts were impossible to resolve.
1274 bool mapValues(JoinVals &Other);
1276 /// Try to resolve conflicts that require all values to be mapped.
1277 /// Returns false if any conflicts were impossible to resolve.
1278 bool resolveConflicts(JoinVals &Other);
1280 /// Erase any machine instructions that have been coalesced away.
1281 /// Add erased instructions to ErasedInstrs.
1282 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1283 /// the erased instrs.
1284 void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1285 SmallVectorImpl<unsigned> &ShrinkRegs);
1287 /// Get the value assignments suitable for passing to LiveInterval::join.
1288 const int *getAssignments() const { return &Assignments[0]; }
1290 } // end anonymous namespace
1292 /// Compute the bitmask of lanes actually written by DefMI.
1293 /// Set Redef if there are any partial register definitions that depend on the
1294 /// previous value of the register.
1295 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1297 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1298 if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1300 L |= TRI->getSubRegIndexLaneMask(compose(*TRI, SubIdx, MO->getSubReg()));
1307 /// Find the ultimate value that VNI was copied from.
1308 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1309 while (!VNI->isPHIDef()) {
1310 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1311 assert(MI && "No defining instruction");
1312 if (!MI->isFullCopy())
1314 unsigned Reg = MI->getOperand(1).getReg();
1315 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1317 LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def);
1320 VNI = LRQ.valueIn();
1325 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1326 /// Return a conflict resolution when possible, but leave the hard cases as
1328 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1329 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1330 /// The recursion always goes upwards in the dominator tree, making loops
1332 JoinVals::ConflictResolution
1333 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1334 Val &V = Vals[ValNo];
1335 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1336 VNInfo *VNI = LI.getValNumInfo(ValNo);
1337 if (VNI->isUnused()) {
1342 // Get the instruction defining this value, compute the lanes written.
1343 const MachineInstr *DefMI = 0;
1344 if (VNI->isPHIDef()) {
1345 // Conservatively assume that all lanes in a PHI are valid.
1346 V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1348 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1350 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1352 // If this is a read-modify-write instruction, there may be more valid
1353 // lanes than the ones written by this instruction.
1354 // This only covers partial redef operands. DefMI may have normal use
1355 // operands reading the register. They don't contribute valid lanes.
1357 // This adds ssub1 to the set of valid lanes in %src:
1359 // %src:ssub1<def> = FOO
1361 // This leaves only ssub1 valid, making any other lanes undef:
1363 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1365 // The <read-undef> flag on the def operand means that old lane values are
1368 V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn();
1369 assert(V.RedefVNI && "Instruction is reading nonexistent value");
1370 computeAssignment(V.RedefVNI->id, Other);
1371 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1374 // An IMPLICIT_DEF writes undef values.
1375 if (DefMI->isImplicitDef())
1376 V.ValidLanes &= ~V.WriteLanes;
1379 // Find the value in Other that overlaps VNI->def, if any.
1380 LiveRangeQuery OtherLRQ(Other.LI, VNI->def);
1382 // It is possible that both values are defined by the same instruction, or
1383 // the values are PHIs defined in the same block. When that happens, the two
1384 // values should be merged into one, but not into any preceding value.
1385 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1386 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1387 DEBUG(dbgs() << "\t\tDouble def: " << VNI->def << '\n');
1388 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1390 // One value stays, the other is merged. Keep the earlier one, or the first
1392 if (OtherVNI->def < VNI->def)
1393 Other.computeAssignment(OtherVNI->id, *this);
1394 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1395 // This is an early-clobber def overlapping a live-in value in the other
1396 // register. Not mergeable.
1397 V.OtherVNI = OtherLRQ.valueIn();
1398 return CR_Impossible;
1400 V.OtherVNI = OtherVNI;
1401 Val &OtherV = Other.Vals[OtherVNI->id];
1402 // Keep this value, check for conflicts when analyzing OtherVNI.
1403 if (!OtherV.isAnalyzed())
1405 // Both sides have been analyzed now. Do they conflict?
1406 if (V.ValidLanes & OtherV.ValidLanes)
1407 // Overlapping lanes can't be resolved now, maybe later.
1408 return CR_Unresolved;
1413 // No simultaneous def. Is Other live at the def?
1414 V.OtherVNI = OtherLRQ.valueIn();
1416 // No overlap, no conflict.
1419 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1421 // We have overlapping values, or possibly a kill of Other.
1422 // Recursively compute assignments up the dominator tree.
1423 Other.computeAssignment(V.OtherVNI->id, *this);
1425 // Don't attempt resolving PHI values for now.
1426 if (VNI->isPHIDef())
1427 return CR_Impossible;
1429 // Check for simple erasable conflicts.
1430 if (DefMI->isImplicitDef())
1433 // Include the non-conflict where DefMI is a coalescable copy that kills
1434 // OtherVNI. We still want the copy erased and value numbers merged.
1435 if (CP.isCoalescable(DefMI)) {
1436 // Some of the lanes copied from OtherVNI may be undef, making them undef
1438 V.ValidLanes &= ~V.WriteLanes | Other.Vals[V.OtherVNI->id].ValidLanes;
1442 // This may not be a real conflict if DefMI simply kills Other and defines
1444 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1447 // Handle the case where VNI and OtherVNI can be proven to be identical:
1449 // %other = COPY %ext
1450 // %this = COPY %ext <-- Erase this copy
1452 if (DefMI->isFullCopy() && !CP.isPartial() &&
1453 stripCopies(VNI) == stripCopies(V.OtherVNI))
1456 // FIXME: Identify CR_Replace opportunities.
1457 return CR_Impossible;
1460 /// Compute the value assignment for ValNo in LI.
1461 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1463 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1464 Val &V = Vals[ValNo];
1465 if (V.isAnalyzed()) {
1466 // Recursion should always move up the dominator tree, so ValNo is not
1467 // supposed to reappear before it has been assigned.
1468 assert(Assignments[ValNo] != -1 && "Bad recursion?");
1471 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1474 // Merge this ValNo into OtherVNI.
1475 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1476 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1477 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1478 DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1479 << LI.getValNumInfo(ValNo)->def << " into "
1480 << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1481 << V.OtherVNI->def << " --> @"
1482 << NewVNInfo[Assignments[ValNo]]->def << '\n');
1485 // This value number needs to go in the final joined live range.
1486 Assignments[ValNo] = NewVNInfo.size();
1487 NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1492 bool JoinVals::mapValues(JoinVals &Other) {
1493 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1494 computeAssignment(i, Other);
1495 if (Vals[i].Resolution == CR_Impossible) {
1496 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1497 << '@' << LI.getValNumInfo(i)->def << '\n');
1504 bool JoinVals::resolveConflicts(JoinVals &Other) {
1505 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1506 assert (Vals[i].Resolution != CR_Impossible && "Unresolvable conflict");
1507 if (Vals[i].Resolution != CR_Unresolved)
1509 // FIXME: Actually resolve dead lane conflicts.
1510 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1511 << '@' << LI.getValNumInfo(i)->def << '\n');
1517 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1518 SmallVectorImpl<unsigned> &ShrinkRegs) {
1519 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1520 if (Vals[i].Resolution != CR_Erase)
1522 SlotIndex Def = LI.getValNumInfo(i)->def;
1523 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1524 assert(MI && "No instruction to erase");
1526 unsigned Reg = MI->getOperand(1).getReg();
1527 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1528 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1529 ShrinkRegs.push_back(Reg);
1531 ErasedInstrs.insert(MI);
1532 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1533 LIS->RemoveMachineInstrFromMaps(MI);
1534 MI->eraseFromParent();
1538 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1539 SmallVector<VNInfo*, 16> NewVNInfo;
1540 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1541 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1542 JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1543 JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1545 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1546 << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS
1549 // First compute NewVNInfo and the simple value mappings.
1550 // Detect impossible conflicts early.
1551 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1554 // Some conflicts can only be resolved after all values have been mapped.
1555 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1558 // All clear, the live ranges can be merged.
1560 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1561 // registers to require trimming.
1562 SmallVector<unsigned, 8> ShrinkRegs;
1563 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1564 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1565 while (!ShrinkRegs.empty())
1566 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1568 // Join RHS into LHS.
1569 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo,
1572 // Kill flags are going to be wrong if the live ranges were overlapping.
1573 // Eventually, we should simply clear all kill flags when computing live
1574 // ranges. They are reinserted after register allocation.
1575 MRI->clearKillFlags(LHS.reg);
1576 MRI->clearKillFlags(RHS.reg);
1580 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1581 /// compute what the resultant value numbers for each value in the input two
1582 /// ranges will be. This is complicated by copies between the two which can
1583 /// and will commonly cause multiple value numbers to be merged into one.
1585 /// VN is the value number that we're trying to resolve. InstDefiningValue
1586 /// keeps track of the new InstDefiningValue assignment for the result
1587 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1588 /// whether a value in this or other is a copy from the opposite set.
1589 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1590 /// already been assigned.
1592 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1593 /// contains the value number the copy is from.
1595 static unsigned ComputeUltimateVN(VNInfo *VNI,
1596 SmallVector<VNInfo*, 16> &NewVNInfo,
1597 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1598 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1599 SmallVector<int, 16> &ThisValNoAssignments,
1600 SmallVector<int, 16> &OtherValNoAssignments) {
1601 unsigned VN = VNI->id;
1603 // If the VN has already been computed, just return it.
1604 if (ThisValNoAssignments[VN] >= 0)
1605 return ThisValNoAssignments[VN];
1606 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1608 // If this val is not a copy from the other val, then it must be a new value
1609 // number in the destination.
1610 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1611 if (I == ThisFromOther.end()) {
1612 NewVNInfo.push_back(VNI);
1613 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1615 VNInfo *OtherValNo = I->second;
1617 // Otherwise, this *is* a copy from the RHS. If the other side has already
1618 // been computed, return it.
1619 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1620 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1622 // Mark this value number as currently being computed, then ask what the
1623 // ultimate value # of the other value is.
1624 ThisValNoAssignments[VN] = -2;
1625 unsigned UltimateVN =
1626 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1627 OtherValNoAssignments, ThisValNoAssignments);
1628 return ThisValNoAssignments[VN] = UltimateVN;
1632 // Find out if we have something like
1635 // if so, we can pretend this is actually
1638 // which allows us to coalesce A and B.
1639 // VNI is the definition of B. LR is the life range of A that includes
1640 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1641 // This implies that A dominates B.
1642 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1643 const TargetRegisterInfo &tri,
1647 SmallVector<MachineInstr*, 8> &DupCopies) {
1648 // FIXME: This is very conservative. For example, we don't handle
1649 // physical registers.
1651 MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1653 if (!MI || CP.isPartial() || CP.isPhys())
1656 unsigned A = CP.getDstReg();
1657 if (!TargetRegisterInfo::isVirtualRegister(A))
1660 unsigned B = CP.getSrcReg();
1661 if (!TargetRegisterInfo::isVirtualRegister(B))
1664 MachineInstr *OtherMI = li.getInstructionFromIndex(OtherVNI->def);
1668 if (MI->isImplicitDef()) {
1669 DupCopies.push_back(MI);
1672 if (!MI->isFullCopy())
1674 unsigned Src = MI->getOperand(1).getReg();
1675 if (!TargetRegisterInfo::isVirtualRegister(Src))
1677 if (!OtherMI->isFullCopy())
1679 unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1680 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc))
1683 if (Src != OtherSrc)
1686 // If the copies use two different value numbers of X, we cannot merge
1688 LiveInterval &SrcInt = li.getInterval(Src);
1689 // getVNInfoBefore returns NULL for undef copies. In this case, the
1690 // optimization is still safe.
1691 if (SrcInt.getVNInfoBefore(OtherVNI->def) !=
1692 SrcInt.getVNInfoBefore(VNI->def))
1695 DupCopies.push_back(MI);
1700 /// joinIntervals - Attempt to join these two intervals. On failure, this
1702 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1703 // Handle physreg joins separately.
1705 return joinReservedPhysReg(CP);
1708 return joinVirtRegs(CP);
1710 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1711 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1714 // Compute the final value assignment, assuming that the live ranges can be
1716 SmallVector<int, 16> LHSValNoAssignments;
1717 SmallVector<int, 16> RHSValNoAssignments;
1718 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1719 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1720 SmallVector<VNInfo*, 16> NewVNInfo;
1722 SmallVector<MachineInstr*, 8> DupCopies;
1723 SmallVector<MachineInstr*, 8> DeadCopies;
1725 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1726 DEBUG(dbgs() << "\t\tLHS = " << PrintReg(CP.getDstReg(), TRI) << ' ' << LHS
1729 // Loop over the value numbers of the LHS, seeing if any are defined from
1731 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1734 if (VNI->isUnused() || VNI->isPHIDef())
1736 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1737 assert(MI && "Missing def");
1738 if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1741 // Figure out the value # from the RHS.
1742 VNInfo *OtherVNI = RHS.getVNInfoBefore(VNI->def);
1743 // The copy could be to an aliased physreg.
1747 // DstReg is known to be a register in the LHS interval. If the src is
1748 // from the RHS interval, we can use its value #.
1749 if (CP.isCoalescable(MI))
1750 DeadCopies.push_back(MI);
1751 else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1755 LHSValsDefinedFromRHS[VNI] = OtherVNI;
1758 // Loop over the value numbers of the RHS, seeing if any are defined from
1760 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1763 if (VNI->isUnused() || VNI->isPHIDef())
1765 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1766 assert(MI && "Missing def");
1767 if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1770 // Figure out the value # from the LHS.
1771 VNInfo *OtherVNI = LHS.getVNInfoBefore(VNI->def);
1772 // The copy could be to an aliased physreg.
1776 // DstReg is known to be a register in the RHS interval. If the src is
1777 // from the LHS interval, we can use its value #.
1778 if (CP.isCoalescable(MI))
1779 DeadCopies.push_back(MI);
1780 else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1784 RHSValsDefinedFromLHS[VNI] = OtherVNI;
1787 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1788 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1789 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1791 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1794 unsigned VN = VNI->id;
1795 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1797 ComputeUltimateVN(VNI, NewVNInfo,
1798 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1799 LHSValNoAssignments, RHSValNoAssignments);
1801 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1804 unsigned VN = VNI->id;
1805 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1807 // If this value number isn't a copy from the LHS, it's a new number.
1808 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1809 NewVNInfo.push_back(VNI);
1810 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1814 ComputeUltimateVN(VNI, NewVNInfo,
1815 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1816 RHSValNoAssignments, LHSValNoAssignments);
1819 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1820 // interval lists to see if these intervals are coalescable.
1821 LiveInterval::const_iterator I = LHS.begin();
1822 LiveInterval::const_iterator IE = LHS.end();
1823 LiveInterval::const_iterator J = RHS.begin();
1824 LiveInterval::const_iterator JE = RHS.end();
1826 // Collect interval end points that will no longer be kills.
1827 SmallVector<MachineInstr*, 8> LHSOldKills;
1828 SmallVector<MachineInstr*, 8> RHSOldKills;
1830 // Skip ahead until the first place of potential sharing.
1831 if (I != IE && J != JE) {
1832 if (I->start < J->start) {
1833 I = std::upper_bound(I, IE, J->start);
1834 if (I != LHS.begin()) --I;
1835 } else if (J->start < I->start) {
1836 J = std::upper_bound(J, JE, I->start);
1837 if (J != RHS.begin()) --J;
1841 while (I != IE && J != JE) {
1842 // Determine if these two live ranges overlap.
1843 // If so, check value # info to determine if they are really different.
1844 if (I->end > J->start && J->end > I->start) {
1845 // If the live range overlap will map to the same value number in the
1846 // result liverange, we can still coalesce them. If not, we can't.
1847 if (LHSValNoAssignments[I->valno->id] !=
1848 RHSValNoAssignments[J->valno->id])
1851 // Extended live ranges should no longer be killed.
1852 if (!I->end.isBlock() && I->end < J->end)
1853 if (MachineInstr *MI = LIS->getInstructionFromIndex(I->end))
1854 LHSOldKills.push_back(MI);
1855 if (!J->end.isBlock() && J->end < I->end)
1856 if (MachineInstr *MI = LIS->getInstructionFromIndex(J->end))
1857 RHSOldKills.push_back(MI);
1860 if (I->end < J->end)
1866 // Clear kill flags where live ranges are extended.
1867 while (!LHSOldKills.empty())
1868 LHSOldKills.pop_back_val()->clearRegisterKills(LHS.reg, TRI);
1869 while (!RHSOldKills.empty())
1870 RHSOldKills.pop_back_val()->clearRegisterKills(RHS.reg, TRI);
1872 if (LHSValNoAssignments.empty())
1873 LHSValNoAssignments.push_back(-1);
1874 if (RHSValNoAssignments.empty())
1875 RHSValNoAssignments.push_back(-1);
1877 // Now erase all the redundant copies.
1878 for (unsigned i = 0, e = DeadCopies.size(); i != e; ++i) {
1879 MachineInstr *MI = DeadCopies[i];
1880 if (!ErasedInstrs.insert(MI))
1882 DEBUG(dbgs() << "\t\terased:\t" << LIS->getInstructionIndex(MI)
1884 LIS->RemoveMachineInstrFromMaps(MI);
1885 MI->eraseFromParent();
1888 SmallVector<unsigned, 8> SourceRegisters;
1889 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1890 E = DupCopies.end(); I != E; ++I) {
1891 MachineInstr *MI = *I;
1892 if (!ErasedInstrs.insert(MI))
1895 // If MI is a copy, then we have pretended that the assignment to B in
1898 // was actually a copy from A. Now that we decided to coalesce A and B,
1899 // transform the code into
1901 // In the case of the implicit_def, we just have to remove it.
1902 if (!MI->isImplicitDef()) {
1903 unsigned Src = MI->getOperand(1).getReg();
1904 SourceRegisters.push_back(Src);
1906 LIS->RemoveMachineInstrFromMaps(MI);
1907 MI->eraseFromParent();
1910 // If B = X was the last use of X in a liverange, we have to shrink it now
1911 // that B = X is gone.
1912 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1913 E = SourceRegisters.end(); I != E; ++I) {
1914 LIS->shrinkToUses(&LIS->getInterval(*I));
1917 // If we get here, we know that we can coalesce the live ranges. Ask the
1918 // intervals to coalesce themselves now.
1919 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1925 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1926 // depth of the basic block (the unsigned), and then on the MBB number.
1927 struct DepthMBBCompare {
1928 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1929 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1930 // Deeper loops first
1931 if (LHS.first != RHS.first)
1932 return LHS.first > RHS.first;
1934 // Prefer blocks that are more connected in the CFG. This takes care of
1935 // the most difficult copies first while intervals are short.
1936 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1937 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1941 // As a last resort, sort by block number.
1942 return LHS.second->getNumber() < RHS.second->getNumber();
1947 // Try joining WorkList copies starting from index From.
1948 // Null out any successful joins.
1949 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
1950 assert(From <= WorkList.size() && "Out of range");
1951 bool Progress = false;
1952 for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
1955 // Skip instruction pointers that have already been erased, for example by
1956 // dead code elimination.
1957 if (ErasedInstrs.erase(WorkList[i])) {
1962 bool Success = joinCopy(WorkList[i], Again);
1963 Progress |= Success;
1964 if (Success || !Again)
1971 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
1972 DEBUG(dbgs() << MBB->getName() << ":\n");
1974 // Collect all copy-like instructions in MBB. Don't start coalescing anything
1975 // yet, it might invalidate the iterator.
1976 const unsigned PrevSize = WorkList.size();
1977 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1979 if (MII->isCopyLike())
1980 WorkList.push_back(MII);
1982 // Try coalescing the collected copies immediately, and remove the nulls.
1983 // This prevents the WorkList from getting too large since most copies are
1984 // joinable on the first attempt.
1985 if (copyCoalesceWorkList(PrevSize))
1986 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
1987 (MachineInstr*)0), WorkList.end());
1990 void RegisterCoalescer::joinAllIntervals() {
1991 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1992 assert(WorkList.empty() && "Old data still around.");
1994 if (Loops->empty()) {
1995 // If there are no loops in the function, join intervals in function order.
1996 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1998 copyCoalesceInMBB(I);
2000 // Otherwise, join intervals in inner loops before other intervals.
2001 // Unfortunately we can't just iterate over loop hierarchy here because
2002 // there may be more MBB's than BB's. Collect MBB's for sorting.
2004 // Join intervals in the function prolog first. We want to join physical
2005 // registers with virtual registers before the intervals got too long.
2006 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2007 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2008 MachineBasicBlock *MBB = I;
2009 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
2012 // Sort by loop depth.
2013 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2015 // Finally, join intervals in loop nest order.
2016 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2017 copyCoalesceInMBB(MBBs[i].second);
2020 // Joining intervals can allow other intervals to be joined. Iteratively join
2021 // until we make no progress.
2022 while (copyCoalesceWorkList())
2026 void RegisterCoalescer::releaseMemory() {
2027 ErasedInstrs.clear();
2030 InflateRegs.clear();
2033 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2035 MRI = &fn.getRegInfo();
2036 TM = &fn.getTarget();
2037 TRI = TM->getRegisterInfo();
2038 TII = TM->getInstrInfo();
2039 LIS = &getAnalysis<LiveIntervals>();
2040 LDV = &getAnalysis<LiveDebugVariables>();
2041 AA = &getAnalysis<AliasAnalysis>();
2042 Loops = &getAnalysis<MachineLoopInfo>();
2044 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2045 << "********** Function: " << MF->getName() << '\n');
2047 if (VerifyCoalescing)
2048 MF->verify(this, "Before register coalescing");
2050 RegClassInfo.runOnMachineFunction(fn);
2052 // Join (coalesce) intervals if requested.
2056 // After deleting a lot of copies, register classes may be less constrained.
2057 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2059 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2060 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2062 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2063 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2064 unsigned Reg = InflateRegs[i];
2065 if (MRI->reg_nodbg_empty(Reg))
2067 if (MRI->recomputeRegClass(Reg, *TM)) {
2068 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2069 << MRI->getRegClass(Reg)->getName() << '\n');
2076 if (VerifyCoalescing)
2077 MF->verify(this, "After register coalescing");
2081 /// print - Implement the dump method.
2082 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {