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 "RegisterClassInfo.h"
20 #include "VirtRegMap.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Value.h"
24 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.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/ADT/OwningPtr.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/STLExtras.h"
51 STATISTIC(numJoins , "Number of interval joins performed");
52 STATISTIC(numCrossRCs , "Number of cross class joins performed");
53 STATISTIC(numCommutes , "Number of instruction commuting performed");
54 STATISTIC(numExtends , "Number of copies extended");
55 STATISTIC(NumReMats , "Number of instructions re-materialized");
56 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
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"),
70 class RegisterCoalescer : public MachineFunctionPass {
72 MachineRegisterInfo* MRI;
73 const TargetMachine* TM;
74 const TargetRegisterInfo* TRI;
75 const TargetInstrInfo* TII;
77 LiveDebugVariables *LDV;
78 const MachineLoopInfo* Loops;
80 RegisterClassInfo RegClassInfo;
82 /// JoinedCopies - Keep track of copies eliminated due to coalescing.
84 SmallPtrSet<MachineInstr*, 32> JoinedCopies;
86 /// ReMatCopies - Keep track of copies eliminated due to remat.
88 SmallPtrSet<MachineInstr*, 32> ReMatCopies;
90 /// ReMatDefs - Keep track of definition instructions which have
92 SmallPtrSet<MachineInstr*, 8> ReMatDefs;
94 /// joinAllIntervals - join compatible live intervals
95 void joinAllIntervals();
97 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
98 /// copies that cannot yet be coalesced into the "TryAgain" list.
99 void copyCoalesceInMBB(MachineBasicBlock *MBB,
100 std::vector<MachineInstr*> &TryAgain);
102 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
103 /// which are the src/dst of the copy instruction CopyMI. This returns
104 /// true if the copy was successfully coalesced away. If it is not
105 /// currently possible to coalesce this interval, but it may be possible if
106 /// other things get coalesced, then it returns true by reference in
108 bool joinCopy(MachineInstr *TheCopy, bool &Again);
110 /// joinIntervals - Attempt to join these two intervals. On failure, this
111 /// returns false. The output "SrcInt" will not have been modified, so we
112 /// can use this information below to update aliases.
113 bool joinIntervals(CoalescerPair &CP);
115 /// Attempt joining with a reserved physreg.
116 bool joinReservedPhysReg(CoalescerPair &CP);
118 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
119 /// the source value number is defined by a copy from the destination reg
120 /// see if we can merge these two destination reg valno# into a single
121 /// value number, eliminating a copy.
122 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
124 /// hasOtherReachingDefs - Return true if there are definitions of IntB
125 /// other than BValNo val# that can reach uses of AValno val# of IntA.
126 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
127 VNInfo *AValNo, VNInfo *BValNo);
129 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
130 /// If the source value number is defined by a commutable instruction and
131 /// its other operand is coalesced to the copy dest register, see if we
132 /// can transform the copy into a noop by commuting the definition.
133 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
135 /// reMaterializeTrivialDef - If the source of a copy is defined by a
136 /// trivial computation, replace the copy by rematerialize the definition.
137 /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
138 bool reMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
139 unsigned DstReg, MachineInstr *CopyMI);
141 /// canJoinPhys - Return true if a physreg copy should be joined.
142 bool canJoinPhys(CoalescerPair &CP);
144 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
145 /// update the subregister number if it is not zero. If DstReg is a
146 /// physical register and the existing subregister number of the def / use
147 /// being updated is not zero, make sure to set it to the correct physical
149 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
151 /// removeDeadDef - If a def of a live interval is now determined dead,
152 /// remove the val# it defines. If the live interval becomes empty, remove
154 bool removeDeadDef(LiveInterval &li, MachineInstr *DefMI);
156 /// markAsJoined - Remember that CopyMI has already been joined.
157 void markAsJoined(MachineInstr *CopyMI);
159 /// eliminateUndefCopy - Handle copies of undef values.
160 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
163 static char ID; // Class identification, replacement for typeinfo
164 RegisterCoalescer() : MachineFunctionPass(ID) {
165 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
168 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
170 virtual void releaseMemory();
172 /// runOnMachineFunction - pass entry point
173 virtual bool runOnMachineFunction(MachineFunction&);
175 /// print - Implement the dump method.
176 virtual void print(raw_ostream &O, const Module* = 0) const;
178 } /// end anonymous namespace
180 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
182 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
183 "Simple Register Coalescing", false, false)
184 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
185 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
186 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
187 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
188 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
189 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
190 "Simple Register Coalescing", false, false)
192 char RegisterCoalescer::ID = 0;
194 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
197 return tri.composeSubRegIndices(a, b);
200 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
201 unsigned &Src, unsigned &Dst,
202 unsigned &SrcSub, unsigned &DstSub) {
204 Dst = MI->getOperand(0).getReg();
205 DstSub = MI->getOperand(0).getSubReg();
206 Src = MI->getOperand(1).getReg();
207 SrcSub = MI->getOperand(1).getSubReg();
208 } else if (MI->isSubregToReg()) {
209 Dst = MI->getOperand(0).getReg();
210 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
211 MI->getOperand(3).getImm());
212 Src = MI->getOperand(2).getReg();
213 SrcSub = MI->getOperand(2).getSubReg();
219 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
223 Flipped = CrossClass = false;
225 unsigned Src, Dst, SrcSub, DstSub;
226 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
228 Partial = SrcSub || DstSub;
230 // If one register is a physreg, it must be Dst.
231 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
232 if (TargetRegisterInfo::isPhysicalRegister(Dst))
235 std::swap(SrcSub, DstSub);
239 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
241 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
242 // Eliminate DstSub on a physreg.
244 Dst = TRI.getSubReg(Dst, DstSub);
245 if (!Dst) return false;
249 // Eliminate SrcSub by picking a corresponding Dst superregister.
251 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
252 if (!Dst) return false;
254 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
258 // Both registers are virtual.
259 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
260 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
262 // Both registers have subreg indices.
263 if (SrcSub && DstSub) {
264 // Copies between different sub-registers are never coalescable.
265 if (Src == Dst && SrcSub != DstSub)
268 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
273 // SrcReg will be merged with a sub-register of DstReg.
275 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
277 // DstReg will be merged with a sub-register of SrcReg.
279 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
281 // This is a straight copy without sub-registers.
282 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
285 // The combined constraint may be impossible to satisfy.
289 // Prefer SrcReg to be a sub-register of DstReg.
290 // FIXME: Coalescer should support subregs symmetrically.
291 if (DstIdx && !SrcIdx) {
293 std::swap(SrcIdx, DstIdx);
297 CrossClass = NewRC != DstRC || NewRC != SrcRC;
299 // Check our invariants
300 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
301 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
302 "Cannot have a physical SubIdx");
308 bool CoalescerPair::flip() {
309 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
311 std::swap(SrcReg, DstReg);
312 std::swap(SrcIdx, DstIdx);
317 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
320 unsigned Src, Dst, SrcSub, DstSub;
321 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
324 // Find the virtual register that is SrcReg.
327 std::swap(SrcSub, DstSub);
328 } else if (Src != SrcReg) {
332 // Now check that Dst matches DstReg.
333 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
334 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
336 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
337 // DstSub could be set for a physreg from INSERT_SUBREG.
339 Dst = TRI.getSubReg(Dst, DstSub);
342 return DstReg == Dst;
343 // This is a partial register copy. Check that the parts match.
344 return TRI.getSubReg(DstReg, SrcSub) == Dst;
346 // DstReg is virtual.
349 // Registers match, do the subregisters line up?
350 return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
354 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
355 AU.setPreservesCFG();
356 AU.addRequired<AliasAnalysis>();
357 AU.addRequired<LiveIntervals>();
358 AU.addPreserved<LiveIntervals>();
359 AU.addRequired<LiveDebugVariables>();
360 AU.addPreserved<LiveDebugVariables>();
361 AU.addPreserved<SlotIndexes>();
362 AU.addRequired<MachineLoopInfo>();
363 AU.addPreserved<MachineLoopInfo>();
364 AU.addPreservedID(MachineDominatorsID);
365 MachineFunctionPass::getAnalysisUsage(AU);
368 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
369 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
370 JoinedCopies.insert(CopyMI);
372 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
373 /// code elimination.
374 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
375 E = CopyMI->operands_end(); I != E; ++I)
380 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
381 /// being the source and IntB being the dest, thus this defines a value number
382 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
383 /// see if we can merge these two pieces of B into a single value number,
384 /// eliminating a copy. For example:
388 /// B1 = A3 <- this copy
390 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
391 /// value number to be replaced with B0 (which simplifies the B liveinterval).
393 /// This returns true if an interval was modified.
395 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
396 MachineInstr *CopyMI) {
397 assert(!CP.isPartial() && "This doesn't work for partial copies.");
399 // Bail if there is no dst interval - can happen when merging physical subreg
401 if (!LIS->hasInterval(CP.getDstReg()))
405 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
407 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
408 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
410 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
411 // the example above.
412 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
413 if (BLR == IntB.end()) return false;
414 VNInfo *BValNo = BLR->valno;
416 // Get the location that B is defined at. Two options: either this value has
417 // an unknown definition point or it is defined at CopyIdx. If unknown, we
419 if (BValNo->def != CopyIdx) return false;
421 // AValNo is the value number in A that defines the copy, A3 in the example.
422 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
423 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
424 // The live range might not exist after fun with physreg coalescing.
425 if (ALR == IntA.end()) return false;
426 VNInfo *AValNo = ALR->valno;
428 // If AValNo is defined as a copy from IntB, we can potentially process this.
429 // Get the instruction that defines this value number.
430 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
431 if (!CP.isCoalescable(ACopyMI))
434 // Get the LiveRange in IntB that this value number starts with.
435 LiveInterval::iterator ValLR =
436 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
437 if (ValLR == IntB.end())
440 // Make sure that the end of the live range is inside the same block as
442 MachineInstr *ValLREndInst =
443 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
444 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
447 // Okay, we now know that ValLR ends in the same block that the CopyMI
448 // live-range starts. If there are no intervening live ranges between them in
449 // IntB, we can merge them.
450 if (ValLR+1 != BLR) return false;
452 // If a live interval is a physical register, conservatively check if any
453 // of its aliases is overlapping the live interval of the virtual register.
454 // If so, do not coalesce.
455 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
456 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
457 if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
459 dbgs() << "\t\tInterfere with alias ";
460 LIS->getInterval(*AS).print(dbgs(), TRI);
467 dbgs() << "Extending: ";
468 IntB.print(dbgs(), TRI);
471 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
472 // We are about to delete CopyMI, so need to remove it as the 'instruction
473 // that defines this value #'. Update the valnum with the new defining
475 BValNo->def = FillerStart;
477 // Okay, we can merge them. We need to insert a new liverange:
478 // [ValLR.end, BLR.begin) of either value number, then we merge the
479 // two value numbers.
480 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
482 // If the IntB live range is assigned to a physical register, and if that
483 // physreg has sub-registers, update their live intervals as well.
484 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
485 for (const uint16_t *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
486 if (!LIS->hasInterval(*SR))
488 LiveInterval &SRLI = LIS->getInterval(*SR);
489 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
490 SRLI.getNextValue(FillerStart,
491 LIS->getVNInfoAllocator())));
495 // Okay, merge "B1" into the same value number as "B0".
496 if (BValNo != ValLR->valno) {
497 // If B1 is killed by a PHI, then the merged live range must also be killed
498 // by the same PHI, as B0 and B1 can not overlap.
499 bool HasPHIKill = BValNo->hasPHIKill();
500 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
502 ValLR->valno->setHasPHIKill(true);
505 dbgs() << " result = ";
506 IntB.print(dbgs(), TRI);
510 // If the source instruction was killing the source register before the
511 // merge, unset the isKill marker given the live range has been extended.
512 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
514 ValLREndInst->getOperand(UIdx).setIsKill(false);
517 // Rewrite the copy. If the copy instruction was killing the destination
518 // register before the merge, find the last use and trim the live range. That
519 // will also add the isKill marker.
520 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
521 if (ALR->end == CopyIdx)
522 LIS->shrinkToUses(&IntA);
528 /// hasOtherReachingDefs - Return true if there are definitions of IntB
529 /// other than BValNo val# that can reach uses of AValno val# of IntA.
530 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
534 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
536 if (AI->valno != AValNo) continue;
537 LiveInterval::Ranges::iterator BI =
538 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
539 if (BI != IntB.ranges.begin())
541 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
542 if (BI->valno == BValNo)
544 if (BI->start <= AI->start && BI->end > AI->start)
546 if (BI->start > AI->start && BI->start < AI->end)
553 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
554 /// IntA being the source and IntB being the dest, thus this defines a value
555 /// number in IntB. If the source value number (in IntA) is defined by a
556 /// commutable instruction and its other operand is coalesced to the copy dest
557 /// register, see if we can transform the copy into a noop by commuting the
558 /// definition. For example,
560 /// A3 = op A2 B0<kill>
562 /// B1 = A3 <- this copy
564 /// = op A3 <- more uses
568 /// B2 = op B0 A2<kill>
570 /// B1 = B2 <- now an identify copy
572 /// = op B2 <- more uses
574 /// This returns true if an interval was modified.
576 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
577 MachineInstr *CopyMI) {
578 // FIXME: For now, only eliminate the copy by commuting its def when the
579 // source register is a virtual register. We want to guard against cases
580 // where the copy is a back edge copy and commuting the def lengthen the
581 // live interval of the source register to the entire loop.
582 if (CP.isPhys() && CP.isFlipped())
585 // Bail if there is no dst interval.
586 if (!LIS->hasInterval(CP.getDstReg()))
589 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
592 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
594 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
596 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
597 // the example above.
598 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
599 if (!BValNo || BValNo->def != CopyIdx)
602 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
604 // AValNo is the value number in A that defines the copy, A3 in the example.
605 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
606 assert(AValNo && "COPY source not live");
608 // If other defs can reach uses of this def, then it's not safe to perform
610 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
612 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
615 if (!DefMI->isCommutable())
617 // If DefMI is a two-address instruction then commuting it will change the
618 // destination register.
619 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
620 assert(DefIdx != -1);
622 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
624 unsigned Op1, Op2, NewDstIdx;
625 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
629 else if (Op2 == UseOpIdx)
634 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
635 unsigned NewReg = NewDstMO.getReg();
636 if (NewReg != IntB.reg || !NewDstMO.isKill())
639 // Make sure there are no other definitions of IntB that would reach the
640 // uses which the new definition can reach.
641 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
644 // Abort if the aliases of IntB.reg have values that are not simply the
645 // clobbers from the superreg.
646 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
647 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
648 if (LIS->hasInterval(*AS) &&
649 hasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
652 // If some of the uses of IntA.reg is already coalesced away, return false.
653 // It's not possible to determine whether it's safe to perform the coalescing.
654 for (MachineRegisterInfo::use_nodbg_iterator UI =
655 MRI->use_nodbg_begin(IntA.reg),
656 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
657 MachineInstr *UseMI = &*UI;
658 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
659 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
660 if (ULR == IntA.end())
662 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
666 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
669 // At this point we have decided that it is legal to do this
670 // transformation. Start by commuting the instruction.
671 MachineBasicBlock *MBB = DefMI->getParent();
672 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
675 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
676 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
677 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
679 if (NewMI != DefMI) {
680 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
681 MachineBasicBlock::iterator Pos = DefMI;
682 MBB->insert(Pos, NewMI);
685 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
686 NewMI->getOperand(OpIdx).setIsKill();
688 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
697 // Update uses of IntA of the specific Val# with IntB.
698 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
699 UE = MRI->use_end(); UI != UE;) {
700 MachineOperand &UseMO = UI.getOperand();
701 MachineInstr *UseMI = &*UI;
703 if (JoinedCopies.count(UseMI))
705 if (UseMI->isDebugValue()) {
706 // FIXME These don't have an instruction index. Not clear we have enough
707 // info to decide whether to do this replacement or not. For now do it.
708 UseMO.setReg(NewReg);
711 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
712 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
713 if (ULR == IntA.end() || ULR->valno != AValNo)
715 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
716 UseMO.substPhysReg(NewReg, *TRI);
718 UseMO.setReg(NewReg);
721 if (!UseMI->isCopy())
723 if (UseMI->getOperand(0).getReg() != IntB.reg ||
724 UseMI->getOperand(0).getSubReg())
727 // This copy will become a noop. If it's defining a new val#, merge it into
729 SlotIndex DefIdx = UseIdx.getRegSlot();
730 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
733 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
734 assert(DVNI->def == DefIdx);
735 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
739 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
741 VNInfo *ValNo = BValNo;
742 ValNo->def = AValNo->def;
743 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
745 if (AI->valno != AValNo) continue;
746 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
748 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
750 IntA.removeValNo(AValNo);
751 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
756 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
757 /// computation, replace the copy by rematerialize the definition.
758 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
761 MachineInstr *CopyMI) {
762 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
763 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
764 assert(SrcLR != SrcInt.end() && "Live range not found!");
765 VNInfo *ValNo = SrcLR->valno;
766 if (ValNo->isPHIDef() || ValNo->isUnused())
768 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
771 assert(DefMI && "Defining instruction disappeared");
772 if (!DefMI->isAsCheapAsAMove())
774 if (!TII->isTriviallyReMaterializable(DefMI, AA))
776 bool SawStore = false;
777 if (!DefMI->isSafeToMove(TII, AA, SawStore))
779 const MCInstrDesc &MCID = DefMI->getDesc();
780 if (MCID.getNumDefs() != 1)
782 if (!DefMI->isImplicitDef()) {
783 // Make sure the copy destination register class fits the instruction
784 // definition register class. The mismatch can happen as a result of earlier
785 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
786 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
787 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
788 if (MRI->getRegClass(DstReg) != RC)
790 } else if (!RC->contains(DstReg))
794 MachineBasicBlock *MBB = CopyMI->getParent();
795 MachineBasicBlock::iterator MII =
796 llvm::next(MachineBasicBlock::iterator(CopyMI));
797 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
798 MachineInstr *NewMI = prior(MII);
800 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
801 // We need to remember these so we can add intervals once we insert
802 // NewMI into SlotIndexes.
803 SmallVector<unsigned, 4> NewMIImplDefs;
804 for (unsigned i = NewMI->getDesc().getNumOperands(),
805 e = NewMI->getNumOperands(); i != e; ++i) {
806 MachineOperand &MO = NewMI->getOperand(i);
808 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
809 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
810 NewMIImplDefs.push_back(MO.getReg());
814 // CopyMI may have implicit operands, transfer them over to the newly
815 // rematerialized instruction. And update implicit def interval valnos.
816 for (unsigned i = CopyMI->getDesc().getNumOperands(),
817 e = CopyMI->getNumOperands(); i != e; ++i) {
818 MachineOperand &MO = CopyMI->getOperand(i);
820 assert(MO.isImplicit() && "No explicit operands after implict operands.");
821 // Discard VReg implicit defs.
822 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
823 NewMI->addOperand(MO);
828 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
830 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
831 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
832 unsigned reg = NewMIImplDefs[i];
833 LiveInterval &li = LIS->getInterval(reg);
834 VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
835 LIS->getVNInfoAllocator());
836 LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
840 CopyMI->eraseFromParent();
841 ReMatCopies.insert(CopyMI);
842 ReMatDefs.insert(DefMI);
843 DEBUG(dbgs() << "Remat: " << *NewMI);
846 // The source interval can become smaller because we removed a use.
848 LIS->shrinkToUses(&SrcInt);
853 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
854 /// values, it only removes local variables. When we have a copy like:
856 /// %vreg1 = COPY %vreg2<undef>
858 /// We delete the copy and remove the corresponding value number from %vreg1.
859 /// Any uses of that value number are marked as <undef>.
860 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
861 const CoalescerPair &CP) {
862 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
863 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
864 if (SrcInt->liveAt(Idx))
866 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
867 if (DstInt->liveAt(Idx))
870 // No intervals are live-in to CopyMI - it is undef.
875 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
876 assert(DeadVNI && "No value defined in DstInt");
877 DstInt->removeValNo(DeadVNI);
879 // Find new undef uses.
880 for (MachineRegisterInfo::reg_nodbg_iterator
881 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
883 MachineOperand &MO = I.getOperand();
884 if (MO.isDef() || MO.isUndef())
886 MachineInstr *MI = MO.getParent();
887 SlotIndex Idx = LIS->getInstructionIndex(MI);
888 if (DstInt->liveAt(Idx))
891 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
896 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
897 /// update the subregister number if it is not zero. If DstReg is a
898 /// physical register and the existing subregister number of the def / use
899 /// being updated is not zero, make sure to set it to the correct physical
901 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
904 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
905 LiveInterval &DstInt = LIS->getInterval(DstReg);
907 // Update LiveDebugVariables.
908 LDV->renameRegister(SrcReg, DstReg, SubIdx);
910 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
911 MachineInstr *UseMI = I.skipInstruction();) {
912 bool AlreadyJoined = JoinedCopies.count(UseMI);
914 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
917 if (UseMI->isFullCopy() &&
918 UseMI->getOperand(1).getReg() == SrcReg &&
919 UseMI->getOperand(0).getReg() != SrcReg &&
920 UseMI->getOperand(0).getReg() != DstReg &&
922 reMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
923 UseMI->getOperand(0).getReg(), UseMI))
927 SmallVector<unsigned,8> Ops;
929 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
931 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
932 // because SrcReg is a sub-register.
933 if (!Reads && SubIdx && !AlreadyJoined)
934 Reads = DstInt.liveAt(LIS->getInstructionIndex(UseMI));
936 // Replace SrcReg with DstReg in all UseMI operands.
937 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
938 MachineOperand &MO = UseMI->getOperand(Ops[i]);
940 // Adjust <undef> flags in case of sub-register joins. We don't want to
941 // turn a full def into a read-modify-write sub-register def and vice
943 if (SubIdx && !AlreadyJoined && MO.isDef())
944 MO.setIsUndef(!Reads);
947 MO.substPhysReg(DstReg, *TRI);
949 MO.substVirtReg(DstReg, SubIdx, *TRI);
952 // This instruction is a copy that will be removed.
957 dbgs() << "\t\tupdated: ";
958 if (!UseMI->isDebugValue())
959 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
965 /// removeIntervalIfEmpty - Check if the live interval of a physical register
966 /// is empty, if so remove it and also remove the empty intervals of its
967 /// sub-registers. Return true if live interval is removed.
968 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
969 const TargetRegisterInfo *TRI) {
971 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
972 for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
973 if (!LIS->hasInterval(*SR))
975 LiveInterval &sli = LIS->getInterval(*SR);
977 LIS->removeInterval(*SR);
979 LIS->removeInterval(li.reg);
985 /// removeDeadDef - If a def of a live interval is now determined dead, remove
986 /// the val# it defines. If the live interval becomes empty, remove it as well.
987 bool RegisterCoalescer::removeDeadDef(LiveInterval &li, MachineInstr *DefMI) {
988 SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
989 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
990 if (DefIdx != MLR->valno->def)
992 li.removeValNo(MLR->valno);
993 return removeIntervalIfEmpty(li, LIS, TRI);
996 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
997 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
998 /// Always join simple intervals that are defined by a single copy from a
999 /// reserved register. This doesn't increase register pressure, so it is
1000 /// always beneficial.
1001 if (!RegClassInfo.isReserved(CP.getDstReg())) {
1002 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1006 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1007 if (CP.isFlipped() && JoinVInt.containsOneValue())
1010 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1014 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1015 /// which are the src/dst of the copy instruction CopyMI. This returns true
1016 /// if the copy was successfully coalesced away. If it is not currently
1017 /// possible to coalesce this interval, but it may be possible if other
1018 /// things get coalesced, then it returns true by reference in 'Again'.
1019 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1022 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1023 return false; // Already done.
1025 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1027 CoalescerPair CP(*TII, *TRI);
1028 if (!CP.setRegisters(CopyMI)) {
1029 DEBUG(dbgs() << "\tNot coalescable.\n");
1033 // If they are already joined we continue.
1034 if (CP.getSrcReg() == CP.getDstReg()) {
1035 markAsJoined(CopyMI);
1036 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1037 return false; // Not coalescable.
1040 // Eliminate undefs.
1041 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1042 markAsJoined(CopyMI);
1043 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1044 return false; // Not coalescable.
1047 // Enforce policies.
1049 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1050 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1052 if (!canJoinPhys(CP)) {
1053 // Before giving up coalescing, if definition of source is defined by
1054 // trivial computation, try rematerializing it.
1055 if (!CP.isFlipped() &&
1056 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1057 CP.getDstReg(), CopyMI))
1063 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1065 if (CP.getDstIdx() && CP.getSrcIdx())
1066 dbgs() << PrintReg(CP.getDstReg()) << " in "
1067 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1068 << PrintReg(CP.getSrcReg()) << " in "
1069 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1071 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1072 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1075 // When possible, let DstReg be the larger interval.
1076 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1077 LIS->getInterval(CP.getDstReg()).ranges.size())
1081 // Okay, attempt to join these two intervals. On failure, this returns false.
1082 // Otherwise, if one of the intervals being joined is a physreg, this method
1083 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1084 // been modified, so we can use this information below to update aliases.
1085 if (!joinIntervals(CP)) {
1086 // Coalescing failed.
1088 // If definition of source is defined by trivial computation, try
1089 // rematerializing it.
1090 if (!CP.isFlipped() &&
1091 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1092 CP.getDstReg(), CopyMI))
1095 // If we can eliminate the copy without merging the live ranges, do so now.
1096 if (!CP.isPartial()) {
1097 if (adjustCopiesBackFrom(CP, CopyMI) ||
1098 removeCopyByCommutingDef(CP, CopyMI)) {
1099 markAsJoined(CopyMI);
1100 DEBUG(dbgs() << "\tTrivial!\n");
1105 // Otherwise, we are unable to join the intervals.
1106 DEBUG(dbgs() << "\tInterference!\n");
1107 Again = true; // May be possible to coalesce later.
1111 // Coalescing to a virtual register that is of a sub-register class of the
1112 // other. Make sure the resulting register is set to the right register class.
1113 if (CP.isCrossClass()) {
1115 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1118 // Remember to delete the copy instruction.
1119 markAsJoined(CopyMI);
1121 // Rewrite all SrcReg operands to DstReg.
1122 // Also update DstReg operands to include DstIdx if it is set.
1124 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1125 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1127 // SrcReg is guaranteed to be the register whose live interval that is
1129 LIS->removeInterval(CP.getSrcReg());
1131 // Update regalloc hint.
1132 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1135 LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1136 dbgs() << "\tJoined. Result = ";
1137 DstInt.print(dbgs(), TRI);
1145 /// Attempt joining with a reserved physreg.
1146 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1147 assert(CP.isPhys() && "Must be a physreg copy");
1148 assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1149 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1150 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1152 assert(CP.isFlipped() && RHS.containsOneValue() &&
1153 "Invalid join with reserved register");
1155 // Optimization for reserved registers like ESP. We can only merge with a
1156 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1157 // The live range of the reserved register will look like a set of dead defs
1158 // - we don't properly track the live range of reserved registers.
1160 // Deny any overlapping intervals. This depends on all the reserved
1161 // register live ranges to look like dead defs.
1162 for (const uint16_t *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1163 if (!LIS->hasInterval(*AS)) {
1164 // Make sure at least DstReg itself exists before attempting a join.
1165 if (*AS == CP.getDstReg())
1166 LIS->getOrCreateInterval(CP.getDstReg());
1169 if (RHS.overlaps(LIS->getInterval(*AS))) {
1170 DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1174 // Skip any value computations, we are not adding new values to the
1175 // reserved register. Also skip merging the live ranges, the reserved
1176 // register live range doesn't need to be accurate as long as all the
1181 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1182 /// compute what the resultant value numbers for each value in the input two
1183 /// ranges will be. This is complicated by copies between the two which can
1184 /// and will commonly cause multiple value numbers to be merged into one.
1186 /// VN is the value number that we're trying to resolve. InstDefiningValue
1187 /// keeps track of the new InstDefiningValue assignment for the result
1188 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1189 /// whether a value in this or other is a copy from the opposite set.
1190 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1191 /// already been assigned.
1193 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1194 /// contains the value number the copy is from.
1196 static unsigned ComputeUltimateVN(VNInfo *VNI,
1197 SmallVector<VNInfo*, 16> &NewVNInfo,
1198 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1199 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1200 SmallVector<int, 16> &ThisValNoAssignments,
1201 SmallVector<int, 16> &OtherValNoAssignments) {
1202 unsigned VN = VNI->id;
1204 // If the VN has already been computed, just return it.
1205 if (ThisValNoAssignments[VN] >= 0)
1206 return ThisValNoAssignments[VN];
1207 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1209 // If this val is not a copy from the other val, then it must be a new value
1210 // number in the destination.
1211 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1212 if (I == ThisFromOther.end()) {
1213 NewVNInfo.push_back(VNI);
1214 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1216 VNInfo *OtherValNo = I->second;
1218 // Otherwise, this *is* a copy from the RHS. If the other side has already
1219 // been computed, return it.
1220 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1221 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1223 // Mark this value number as currently being computed, then ask what the
1224 // ultimate value # of the other value is.
1225 ThisValNoAssignments[VN] = -2;
1226 unsigned UltimateVN =
1227 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1228 OtherValNoAssignments, ThisValNoAssignments);
1229 return ThisValNoAssignments[VN] = UltimateVN;
1233 // Find out if we have something like
1236 // if so, we can pretend this is actually
1239 // which allows us to coalesce A and B.
1240 // VNI is the definition of B. LR is the life range of A that includes
1241 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1242 // This implies that A dominates B.
1243 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1244 const TargetRegisterInfo &tri,
1248 SmallVector<MachineInstr*, 8> &DupCopies) {
1249 // FIXME: This is very conservative. For example, we don't handle
1250 // physical registers.
1252 MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1254 if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1257 unsigned Dst = MI->getOperand(0).getReg();
1258 unsigned Src = MI->getOperand(1).getReg();
1260 if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1261 !TargetRegisterInfo::isVirtualRegister(Dst))
1264 unsigned A = CP.getDstReg();
1265 unsigned B = CP.getSrcReg();
1271 VNInfo *Other = LR->valno;
1272 const MachineInstr *OtherMI = li.getInstructionFromIndex(Other->def);
1274 if (!OtherMI || !OtherMI->isFullCopy())
1277 unsigned OtherDst = OtherMI->getOperand(0).getReg();
1278 unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1280 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1281 !TargetRegisterInfo::isVirtualRegister(OtherDst))
1284 assert(OtherDst == B);
1286 if (Src != OtherSrc)
1289 // If the copies use two different value numbers of X, we cannot merge
1291 LiveInterval &SrcInt = li.getInterval(Src);
1292 // getVNInfoBefore returns NULL for undef copies. In this case, the
1293 // optimization is still safe.
1294 if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1297 DupCopies.push_back(MI);
1302 /// joinIntervals - Attempt to join these two intervals. On failure, this
1304 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1305 // Handle physreg joins separately.
1307 return joinReservedPhysReg(CP);
1309 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1310 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1312 // Compute the final value assignment, assuming that the live ranges can be
1314 SmallVector<int, 16> LHSValNoAssignments;
1315 SmallVector<int, 16> RHSValNoAssignments;
1316 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1317 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1318 SmallVector<VNInfo*, 16> NewVNInfo;
1320 SmallVector<MachineInstr*, 8> DupCopies;
1322 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1323 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1325 // Loop over the value numbers of the LHS, seeing if any are defined from
1327 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1330 if (VNI->isUnused() || VNI->isPHIDef())
1332 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1333 assert(MI && "Missing def");
1334 if (!MI->isCopyLike()) // Src not defined by a copy?
1337 // Figure out the value # from the RHS.
1338 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1339 // The copy could be to an aliased physreg.
1342 // DstReg is known to be a register in the LHS interval. If the src is
1343 // from the RHS interval, we can use its value #.
1344 if (!CP.isCoalescable(MI) &&
1345 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1348 LHSValsDefinedFromRHS[VNI] = lr->valno;
1351 // Loop over the value numbers of the RHS, seeing if any are defined from
1353 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1356 if (VNI->isUnused() || VNI->isPHIDef())
1358 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1359 assert(MI && "Missing def");
1360 if (!MI->isCopyLike()) // Src not defined by a copy?
1363 // Figure out the value # from the LHS.
1364 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1365 // The copy could be to an aliased physreg.
1368 // DstReg is known to be a register in the RHS interval. If the src is
1369 // from the LHS interval, we can use its value #.
1370 if (!CP.isCoalescable(MI) &&
1371 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1374 RHSValsDefinedFromLHS[VNI] = lr->valno;
1377 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1378 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1379 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1381 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1384 unsigned VN = VNI->id;
1385 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1387 ComputeUltimateVN(VNI, NewVNInfo,
1388 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1389 LHSValNoAssignments, RHSValNoAssignments);
1391 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1394 unsigned VN = VNI->id;
1395 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1397 // If this value number isn't a copy from the LHS, it's a new number.
1398 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1399 NewVNInfo.push_back(VNI);
1400 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1404 ComputeUltimateVN(VNI, NewVNInfo,
1405 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1406 RHSValNoAssignments, LHSValNoAssignments);
1409 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1410 // interval lists to see if these intervals are coalescable.
1411 LiveInterval::const_iterator I = LHS.begin();
1412 LiveInterval::const_iterator IE = LHS.end();
1413 LiveInterval::const_iterator J = RHS.begin();
1414 LiveInterval::const_iterator JE = RHS.end();
1416 // Skip ahead until the first place of potential sharing.
1417 if (I != IE && J != JE) {
1418 if (I->start < J->start) {
1419 I = std::upper_bound(I, IE, J->start);
1420 if (I != LHS.begin()) --I;
1421 } else if (J->start < I->start) {
1422 J = std::upper_bound(J, JE, I->start);
1423 if (J != RHS.begin()) --J;
1427 while (I != IE && J != JE) {
1428 // Determine if these two live ranges overlap.
1430 if (I->start < J->start) {
1431 Overlaps = I->end > J->start;
1433 Overlaps = J->end > I->start;
1436 // If so, check value # info to determine if they are really different.
1438 // If the live range overlap will map to the same value number in the
1439 // result liverange, we can still coalesce them. If not, we can't.
1440 if (LHSValNoAssignments[I->valno->id] !=
1441 RHSValNoAssignments[J->valno->id])
1445 if (I->end < J->end)
1451 // Update kill info. Some live ranges are extended due to copy coalescing.
1452 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1453 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1454 VNInfo *VNI = I->first;
1455 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1456 if (VNI->hasPHIKill())
1457 NewVNInfo[LHSValID]->setHasPHIKill(true);
1460 // Update kill info. Some live ranges are extended due to copy coalescing.
1461 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1462 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1463 VNInfo *VNI = I->first;
1464 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1465 if (VNI->hasPHIKill())
1466 NewVNInfo[RHSValID]->setHasPHIKill(true);
1469 if (LHSValNoAssignments.empty())
1470 LHSValNoAssignments.push_back(-1);
1471 if (RHSValNoAssignments.empty())
1472 RHSValNoAssignments.push_back(-1);
1474 SmallVector<unsigned, 8> SourceRegisters;
1475 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1476 E = DupCopies.end(); I != E; ++I) {
1477 MachineInstr *MI = *I;
1479 // We have pretended that the assignment to B in
1482 // was actually a copy from A. Now that we decided to coalesce A and B,
1483 // transform the code into
1486 // and mark the X as coalesced to keep the illusion.
1487 unsigned Src = MI->getOperand(1).getReg();
1488 SourceRegisters.push_back(Src);
1489 MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1494 // If B = X was the last use of X in a liverange, we have to shrink it now
1495 // that B = X is gone.
1496 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1497 E = SourceRegisters.end(); I != E; ++I) {
1498 LIS->shrinkToUses(&LIS->getInterval(*I));
1501 // If we get here, we know that we can coalesce the live ranges. Ask the
1502 // intervals to coalesce themselves now.
1503 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1509 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1510 // depth of the basic block (the unsigned), and then on the MBB number.
1511 struct DepthMBBCompare {
1512 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1513 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1514 // Deeper loops first
1515 if (LHS.first != RHS.first)
1516 return LHS.first > RHS.first;
1518 // Prefer blocks that are more connected in the CFG. This takes care of
1519 // the most difficult copies first while intervals are short.
1520 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1521 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1525 // As a last resort, sort by block number.
1526 return LHS.second->getNumber() < RHS.second->getNumber();
1532 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB,
1533 std::vector<MachineInstr*> &TryAgain) {
1534 DEBUG(dbgs() << MBB->getName() << ":\n");
1536 // Collect all copy-like instructions in MBB. Don't start coalescing anything
1537 // yet, it might invalidate the iterator.
1538 const unsigned PrevSize = TryAgain.size();
1539 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1541 if (MII->isCopyLike())
1542 TryAgain.push_back(MII);
1544 // Try coalescing the collected copies immediately.
1545 // Null out the successful joins.
1546 for (unsigned i = PrevSize, e = TryAgain.size(); i != e; ++i) {
1548 if (joinCopy(TryAgain[i], Again) || !Again)
1552 // Remove the nulls from TryAgain.
1553 TryAgain.erase(std::remove(TryAgain.begin() + PrevSize, TryAgain.end(),
1554 (MachineInstr*)0), TryAgain.end());
1557 void RegisterCoalescer::joinAllIntervals() {
1558 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1560 std::vector<MachineInstr*> TryAgainList;
1561 if (Loops->empty()) {
1562 // If there are no loops in the function, join intervals in function order.
1563 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1565 copyCoalesceInMBB(I, TryAgainList);
1567 // Otherwise, join intervals in inner loops before other intervals.
1568 // Unfortunately we can't just iterate over loop hierarchy here because
1569 // there may be more MBB's than BB's. Collect MBB's for sorting.
1571 // Join intervals in the function prolog first. We want to join physical
1572 // registers with virtual registers before the intervals got too long.
1573 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1574 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1575 MachineBasicBlock *MBB = I;
1576 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1579 // Sort by loop depth.
1580 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1582 // Finally, join intervals in loop nest order.
1583 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1584 copyCoalesceInMBB(MBBs[i].second, TryAgainList);
1587 // Joining intervals can allow other intervals to be joined. Iteratively join
1588 // until we make no progress.
1589 bool ProgressMade = true;
1590 while (ProgressMade) {
1591 ProgressMade = false;
1593 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1594 MachineInstr *&TheCopy = TryAgainList[i];
1599 bool Success = joinCopy(TheCopy, Again);
1600 if (Success || !Again) {
1601 TheCopy= 0; // Mark this one as done.
1602 ProgressMade = true;
1608 void RegisterCoalescer::releaseMemory() {
1609 JoinedCopies.clear();
1610 ReMatCopies.clear();
1614 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1616 MRI = &fn.getRegInfo();
1617 TM = &fn.getTarget();
1618 TRI = TM->getRegisterInfo();
1619 TII = TM->getInstrInfo();
1620 LIS = &getAnalysis<LiveIntervals>();
1621 LDV = &getAnalysis<LiveDebugVariables>();
1622 AA = &getAnalysis<AliasAnalysis>();
1623 Loops = &getAnalysis<MachineLoopInfo>();
1625 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1626 << "********** Function: "
1627 << ((Value*)MF->getFunction())->getName() << '\n');
1629 if (VerifyCoalescing)
1630 MF->verify(this, "Before register coalescing");
1632 RegClassInfo.runOnMachineFunction(fn);
1634 // Join (coalesce) intervals if requested.
1635 if (EnableJoining) {
1638 dbgs() << "********** INTERVALS POST JOINING **********\n";
1639 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1641 I->second->print(dbgs(), TRI);
1647 // Perform a final pass over the instructions and compute spill weights
1648 // and remove identity moves.
1649 SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1650 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1651 mbbi != mbbe; ++mbbi) {
1652 MachineBasicBlock* mbb = mbbi;
1653 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1655 MachineInstr *MI = mii;
1656 if (JoinedCopies.count(MI)) {
1657 // Delete all coalesced copies.
1658 bool DoDelete = true;
1659 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1660 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1661 unsigned DstReg = MI->getOperand(0).getReg();
1663 // Collect candidates for register class inflation.
1664 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1665 RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1666 InflateRegs.push_back(SrcReg);
1667 if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1668 RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1669 InflateRegs.push_back(DstReg);
1671 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1672 MI->getNumOperands() > 2)
1673 // Do not delete extract_subreg, insert_subreg of physical
1674 // registers unless the definition is dead. e.g.
1675 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1676 // or else the scavenger may complain. LowerSubregs will
1677 // delete them later.
1680 if (MI->allDefsAreDead()) {
1681 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1682 LIS->hasInterval(SrcReg))
1683 LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1687 // We need the instruction to adjust liveness, so make it a KILL.
1688 if (MI->isSubregToReg()) {
1689 MI->RemoveOperand(3);
1690 MI->RemoveOperand(1);
1692 MI->setDesc(TII->get(TargetOpcode::KILL));
1693 mii = llvm::next(mii);
1695 LIS->RemoveMachineInstrFromMaps(MI);
1696 mii = mbbi->erase(mii);
1702 // Now check if this is a remat'ed def instruction which is now dead.
1703 if (ReMatDefs.count(MI)) {
1705 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1706 const MachineOperand &MO = MI->getOperand(i);
1709 unsigned Reg = MO.getReg();
1712 DeadDefs.push_back(Reg);
1713 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1714 // Remat may also enable register class inflation.
1715 if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1716 InflateRegs.push_back(Reg);
1720 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1721 !MRI->use_nodbg_empty(Reg)) {
1727 while (!DeadDefs.empty()) {
1728 unsigned DeadDef = DeadDefs.back();
1729 DeadDefs.pop_back();
1730 removeDeadDef(LIS->getInterval(DeadDef), MI);
1732 LIS->RemoveMachineInstrFromMaps(mii);
1733 mii = mbbi->erase(mii);
1741 // Check for now unnecessary kill flags.
1742 if (LIS->isNotInMIMap(MI)) continue;
1743 SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1744 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1745 MachineOperand &MO = MI->getOperand(i);
1746 if (!MO.isReg() || !MO.isKill()) continue;
1747 unsigned reg = MO.getReg();
1748 if (!reg || !LIS->hasInterval(reg)) continue;
1749 if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1750 MO.setIsKill(false);
1753 // When leaving a kill flag on a physreg, check if any subregs should
1755 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1757 for (const uint16_t *SR = TRI->getSubRegisters(reg);
1758 unsigned S = *SR; ++SR)
1759 if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1760 MI->addRegisterDefined(S, TRI);
1765 // After deleting a lot of copies, register classes may be less constrained.
1766 // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1768 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1769 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1771 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1772 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1773 unsigned Reg = InflateRegs[i];
1774 if (MRI->reg_nodbg_empty(Reg))
1776 if (MRI->recomputeRegClass(Reg, *TM)) {
1777 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1778 << MRI->getRegClass(Reg)->getName() << '\n');
1785 if (VerifyCoalescing)
1786 MF->verify(this, "After register coalescing");
1790 /// print - Implement the dump method.
1791 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {