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/ADT/OwningPtr.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
31 #include "llvm/CodeGen/LiveRangeEdit.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/Passes.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(numPeep , "Number of identity moves eliminated after coalescing");
58 STATISTIC(NumInflated , "Number of register classes inflated");
61 EnableJoining("join-liveintervals",
62 cl::desc("Coalesce copies (default=true)"),
66 VerifyCoalescing("verify-coalescing",
67 cl::desc("Verify machine instrs before and after register coalescing"),
71 class RegisterCoalescer : public MachineFunctionPass,
72 private LiveRangeEdit::Delegate {
74 MachineRegisterInfo* MRI;
75 const TargetMachine* TM;
76 const TargetRegisterInfo* TRI;
77 const TargetInstrInfo* TII;
79 LiveDebugVariables *LDV;
80 const MachineLoopInfo* Loops;
82 RegisterClassInfo RegClassInfo;
84 /// JoinedCopies - Keep track of copies eliminated due to coalescing.
86 SmallPtrSet<MachineInstr*, 32> JoinedCopies;
88 /// ReMatDefs - Keep track of definition instructions which have
90 SmallPtrSet<MachineInstr*, 8> ReMatDefs;
92 /// WorkList - Copy instructions yet to be coalesced.
93 SmallVector<MachineInstr*, 8> WorkList;
95 /// ErasedInstrs - Set of instruction pointers that have been erased, and
96 /// that may be present in WorkList.
97 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
99 /// Dead instructions that are about to be deleted.
100 SmallVector<MachineInstr*, 8> DeadDefs;
102 /// Virtual registers to be considered for register class inflation.
103 SmallVector<unsigned, 8> InflateRegs;
105 /// Recursively eliminate dead defs in DeadDefs.
106 void eliminateDeadDefs();
108 /// LiveRangeEdit callback.
109 void LRE_WillEraseInstruction(MachineInstr *MI);
111 /// joinAllIntervals - join compatible live intervals
112 void joinAllIntervals();
114 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
115 /// copies that cannot yet be coalesced into WorkList.
116 void copyCoalesceInMBB(MachineBasicBlock *MBB);
118 /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
119 /// position From. Return true if any progress was made.
120 bool copyCoalesceWorkList(unsigned From = 0);
122 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
123 /// which are the src/dst of the copy instruction CopyMI. This returns
124 /// true if the copy was successfully coalesced away. If it is not
125 /// currently possible to coalesce this interval, but it may be possible if
126 /// other things get coalesced, then it returns true by reference in
128 bool joinCopy(MachineInstr *TheCopy, bool &Again);
130 /// joinIntervals - Attempt to join these two intervals. On failure, this
131 /// returns false. The output "SrcInt" will not have been modified, so we
132 /// can use this information below to update aliases.
133 bool joinIntervals(CoalescerPair &CP);
135 /// Attempt joining with a reserved physreg.
136 bool joinReservedPhysReg(CoalescerPair &CP);
138 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
139 /// the source value number is defined by a copy from the destination reg
140 /// see if we can merge these two destination reg valno# into a single
141 /// value number, eliminating a copy.
142 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
144 /// hasOtherReachingDefs - Return true if there are definitions of IntB
145 /// other than BValNo val# that can reach uses of AValno val# of IntA.
146 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
147 VNInfo *AValNo, VNInfo *BValNo);
149 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
150 /// If the source value number is defined by a commutable instruction and
151 /// its other operand is coalesced to the copy dest register, see if we
152 /// can transform the copy into a noop by commuting the definition.
153 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
155 /// reMaterializeTrivialDef - If the source of a copy is defined by a
156 /// trivial computation, replace the copy by rematerialize the definition.
157 bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
158 MachineInstr *CopyMI);
160 /// canJoinPhys - Return true if a physreg copy should be joined.
161 bool canJoinPhys(CoalescerPair &CP);
163 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
164 /// update the subregister number if it is not zero. If DstReg is a
165 /// physical register and the existing subregister number of the def / use
166 /// being updated is not zero, make sure to set it to the correct physical
168 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
170 /// removeDeadDef - If a def of a live interval is now determined dead,
171 /// remove the val# it defines. If the live interval becomes empty, remove
173 bool removeDeadDef(LiveInterval &li, MachineInstr *DefMI);
175 /// markAsJoined - Remember that CopyMI has already been joined.
176 void markAsJoined(MachineInstr *CopyMI);
178 /// eliminateUndefCopy - Handle copies of undef values.
179 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
182 static char ID; // Class identification, replacement for typeinfo
183 RegisterCoalescer() : MachineFunctionPass(ID) {
184 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
187 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
189 virtual void releaseMemory();
191 /// runOnMachineFunction - pass entry point
192 virtual bool runOnMachineFunction(MachineFunction&);
194 /// print - Implement the dump method.
195 virtual void print(raw_ostream &O, const Module* = 0) const;
197 } /// end anonymous namespace
199 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
201 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
202 "Simple Register Coalescing", false, false)
203 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
204 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
205 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
206 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
207 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
208 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
209 "Simple Register Coalescing", false, false)
211 char RegisterCoalescer::ID = 0;
213 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
216 return tri.composeSubRegIndices(a, b);
219 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
220 unsigned &Src, unsigned &Dst,
221 unsigned &SrcSub, unsigned &DstSub) {
223 Dst = MI->getOperand(0).getReg();
224 DstSub = MI->getOperand(0).getSubReg();
225 Src = MI->getOperand(1).getReg();
226 SrcSub = MI->getOperand(1).getSubReg();
227 } else if (MI->isSubregToReg()) {
228 Dst = MI->getOperand(0).getReg();
229 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
230 MI->getOperand(3).getImm());
231 Src = MI->getOperand(2).getReg();
232 SrcSub = MI->getOperand(2).getSubReg();
238 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
242 Flipped = CrossClass = false;
244 unsigned Src, Dst, SrcSub, DstSub;
245 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
247 Partial = SrcSub || DstSub;
249 // If one register is a physreg, it must be Dst.
250 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
251 if (TargetRegisterInfo::isPhysicalRegister(Dst))
254 std::swap(SrcSub, DstSub);
258 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
260 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
261 // Eliminate DstSub on a physreg.
263 Dst = TRI.getSubReg(Dst, DstSub);
264 if (!Dst) return false;
268 // Eliminate SrcSub by picking a corresponding Dst superregister.
270 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
271 if (!Dst) return false;
273 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
277 // Both registers are virtual.
278 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
279 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
281 // Both registers have subreg indices.
282 if (SrcSub && DstSub) {
283 // Copies between different sub-registers are never coalescable.
284 if (Src == Dst && SrcSub != DstSub)
287 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
292 // SrcReg will be merged with a sub-register of DstReg.
294 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
296 // DstReg will be merged with a sub-register of SrcReg.
298 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
300 // This is a straight copy without sub-registers.
301 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
304 // The combined constraint may be impossible to satisfy.
308 // Prefer SrcReg to be a sub-register of DstReg.
309 // FIXME: Coalescer should support subregs symmetrically.
310 if (DstIdx && !SrcIdx) {
312 std::swap(SrcIdx, DstIdx);
316 CrossClass = NewRC != DstRC || NewRC != SrcRC;
318 // Check our invariants
319 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
320 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
321 "Cannot have a physical SubIdx");
327 bool CoalescerPair::flip() {
328 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
330 std::swap(SrcReg, DstReg);
331 std::swap(SrcIdx, DstIdx);
336 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
339 unsigned Src, Dst, SrcSub, DstSub;
340 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
343 // Find the virtual register that is SrcReg.
346 std::swap(SrcSub, DstSub);
347 } else if (Src != SrcReg) {
351 // Now check that Dst matches DstReg.
352 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
353 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
355 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
356 // DstSub could be set for a physreg from INSERT_SUBREG.
358 Dst = TRI.getSubReg(Dst, DstSub);
361 return DstReg == Dst;
362 // This is a partial register copy. Check that the parts match.
363 return TRI.getSubReg(DstReg, SrcSub) == Dst;
365 // DstReg is virtual.
368 // Registers match, do the subregisters line up?
369 return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
373 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
374 AU.setPreservesCFG();
375 AU.addRequired<AliasAnalysis>();
376 AU.addRequired<LiveIntervals>();
377 AU.addPreserved<LiveIntervals>();
378 AU.addRequired<LiveDebugVariables>();
379 AU.addPreserved<LiveDebugVariables>();
380 AU.addPreserved<SlotIndexes>();
381 AU.addRequired<MachineLoopInfo>();
382 AU.addPreserved<MachineLoopInfo>();
383 AU.addPreservedID(MachineDominatorsID);
384 MachineFunctionPass::getAnalysisUsage(AU);
387 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
388 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
389 JoinedCopies.insert(CopyMI);
391 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
392 /// code elimination.
393 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
394 E = CopyMI->operands_end(); I != E; ++I)
399 void RegisterCoalescer::eliminateDeadDefs() {
400 SmallVector<LiveInterval*, 8> NewRegs;
401 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
404 // Callback from eliminateDeadDefs().
405 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
406 // MI may be in WorkList. Make sure we don't visit it.
407 ErasedInstrs.insert(MI);
410 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
411 /// being the source and IntB being the dest, thus this defines a value number
412 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
413 /// see if we can merge these two pieces of B into a single value number,
414 /// eliminating a copy. For example:
418 /// B1 = A3 <- this copy
420 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
421 /// value number to be replaced with B0 (which simplifies the B liveinterval).
423 /// This returns true if an interval was modified.
425 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
426 MachineInstr *CopyMI) {
427 assert(!CP.isPartial() && "This doesn't work for partial copies.");
429 // Bail if there is no dst interval - can happen when merging physical subreg
431 if (!LIS->hasInterval(CP.getDstReg()))
435 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
437 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
438 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
440 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
441 // the example above.
442 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
443 if (BLR == IntB.end()) return false;
444 VNInfo *BValNo = BLR->valno;
446 // Get the location that B is defined at. Two options: either this value has
447 // an unknown definition point or it is defined at CopyIdx. If unknown, we
449 if (BValNo->def != CopyIdx) return false;
451 // AValNo is the value number in A that defines the copy, A3 in the example.
452 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
453 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
454 // The live range might not exist after fun with physreg coalescing.
455 if (ALR == IntA.end()) return false;
456 VNInfo *AValNo = ALR->valno;
458 // If AValNo is defined as a copy from IntB, we can potentially process this.
459 // Get the instruction that defines this value number.
460 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
461 if (!CP.isCoalescable(ACopyMI))
464 // Get the LiveRange in IntB that this value number starts with.
465 LiveInterval::iterator ValLR =
466 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
467 if (ValLR == IntB.end())
470 // Make sure that the end of the live range is inside the same block as
472 MachineInstr *ValLREndInst =
473 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
474 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
477 // Okay, we now know that ValLR ends in the same block that the CopyMI
478 // live-range starts. If there are no intervening live ranges between them in
479 // IntB, we can merge them.
480 if (ValLR+1 != BLR) return false;
482 // If a live interval is a physical register, conservatively check if any
483 // of its aliases is overlapping the live interval of the virtual register.
484 // If so, do not coalesce.
485 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
486 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
487 if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
489 dbgs() << "\t\tInterfere with alias ";
490 LIS->getInterval(*AS).print(dbgs(), TRI);
497 dbgs() << "Extending: ";
498 IntB.print(dbgs(), TRI);
501 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
502 // We are about to delete CopyMI, so need to remove it as the 'instruction
503 // that defines this value #'. Update the valnum with the new defining
505 BValNo->def = FillerStart;
507 // Okay, we can merge them. We need to insert a new liverange:
508 // [ValLR.end, BLR.begin) of either value number, then we merge the
509 // two value numbers.
510 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
512 // If the IntB live range is assigned to a physical register, and if that
513 // physreg has sub-registers, update their live intervals as well.
514 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
515 for (const uint16_t *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
516 if (!LIS->hasInterval(*SR))
518 LiveInterval &SRLI = LIS->getInterval(*SR);
519 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
520 SRLI.getNextValue(FillerStart,
521 LIS->getVNInfoAllocator())));
525 // Okay, merge "B1" into the same value number as "B0".
526 if (BValNo != ValLR->valno) {
527 // If B1 is killed by a PHI, then the merged live range must also be killed
528 // by the same PHI, as B0 and B1 can not overlap.
529 bool HasPHIKill = BValNo->hasPHIKill();
530 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
532 ValLR->valno->setHasPHIKill(true);
535 dbgs() << " result = ";
536 IntB.print(dbgs(), TRI);
540 // If the source instruction was killing the source register before the
541 // merge, unset the isKill marker given the live range has been extended.
542 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
544 ValLREndInst->getOperand(UIdx).setIsKill(false);
547 // Rewrite the copy. If the copy instruction was killing the destination
548 // register before the merge, find the last use and trim the live range. That
549 // will also add the isKill marker.
550 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
551 if (ALR->end == CopyIdx)
552 LIS->shrinkToUses(&IntA);
558 /// hasOtherReachingDefs - Return true if there are definitions of IntB
559 /// other than BValNo val# that can reach uses of AValno val# of IntA.
560 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
564 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
566 if (AI->valno != AValNo) continue;
567 LiveInterval::Ranges::iterator BI =
568 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
569 if (BI != IntB.ranges.begin())
571 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
572 if (BI->valno == BValNo)
574 if (BI->start <= AI->start && BI->end > AI->start)
576 if (BI->start > AI->start && BI->start < AI->end)
583 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
584 /// IntA being the source and IntB being the dest, thus this defines a value
585 /// number in IntB. If the source value number (in IntA) is defined by a
586 /// commutable instruction and its other operand is coalesced to the copy dest
587 /// register, see if we can transform the copy into a noop by commuting the
588 /// definition. For example,
590 /// A3 = op A2 B0<kill>
592 /// B1 = A3 <- this copy
594 /// = op A3 <- more uses
598 /// B2 = op B0 A2<kill>
600 /// B1 = B2 <- now an identify copy
602 /// = op B2 <- more uses
604 /// This returns true if an interval was modified.
606 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
607 MachineInstr *CopyMI) {
608 // FIXME: For now, only eliminate the copy by commuting its def when the
609 // source register is a virtual register. We want to guard against cases
610 // where the copy is a back edge copy and commuting the def lengthen the
611 // live interval of the source register to the entire loop.
612 if (CP.isPhys() && CP.isFlipped())
615 // Bail if there is no dst interval.
616 if (!LIS->hasInterval(CP.getDstReg()))
619 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
622 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
624 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
626 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
627 // the example above.
628 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
629 if (!BValNo || BValNo->def != CopyIdx)
632 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
634 // AValNo is the value number in A that defines the copy, A3 in the example.
635 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
636 assert(AValNo && "COPY source not live");
638 // If other defs can reach uses of this def, then it's not safe to perform
640 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
642 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
645 if (!DefMI->isCommutable())
647 // If DefMI is a two-address instruction then commuting it will change the
648 // destination register.
649 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
650 assert(DefIdx != -1);
652 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
654 unsigned Op1, Op2, NewDstIdx;
655 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
659 else if (Op2 == UseOpIdx)
664 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
665 unsigned NewReg = NewDstMO.getReg();
666 if (NewReg != IntB.reg || !NewDstMO.isKill())
669 // Make sure there are no other definitions of IntB that would reach the
670 // uses which the new definition can reach.
671 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
674 // Abort if the aliases of IntB.reg have values that are not simply the
675 // clobbers from the superreg.
676 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
677 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
678 if (LIS->hasInterval(*AS) &&
679 hasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
682 // If some of the uses of IntA.reg is already coalesced away, return false.
683 // It's not possible to determine whether it's safe to perform the coalescing.
684 for (MachineRegisterInfo::use_nodbg_iterator UI =
685 MRI->use_nodbg_begin(IntA.reg),
686 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
687 MachineInstr *UseMI = &*UI;
688 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
689 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
690 if (ULR == IntA.end() || ULR->valno != AValNo)
692 if (JoinedCopies.count(UseMI))
694 // If this use is tied to a def, we can't rewrite the register.
695 if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
699 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
702 // At this point we have decided that it is legal to do this
703 // transformation. Start by commuting the instruction.
704 MachineBasicBlock *MBB = DefMI->getParent();
705 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
708 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
709 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
710 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
712 if (NewMI != DefMI) {
713 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
714 MachineBasicBlock::iterator Pos = DefMI;
715 MBB->insert(Pos, NewMI);
718 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
719 NewMI->getOperand(OpIdx).setIsKill();
721 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
730 // Update uses of IntA of the specific Val# with IntB.
731 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
732 UE = MRI->use_end(); UI != UE;) {
733 MachineOperand &UseMO = UI.getOperand();
734 MachineInstr *UseMI = &*UI;
736 if (JoinedCopies.count(UseMI))
738 if (UseMI->isDebugValue()) {
739 // FIXME These don't have an instruction index. Not clear we have enough
740 // info to decide whether to do this replacement or not. For now do it.
741 UseMO.setReg(NewReg);
744 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
745 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
746 if (ULR == IntA.end() || ULR->valno != AValNo)
748 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
749 UseMO.substPhysReg(NewReg, *TRI);
751 UseMO.setReg(NewReg);
754 if (!UseMI->isCopy())
756 if (UseMI->getOperand(0).getReg() != IntB.reg ||
757 UseMI->getOperand(0).getSubReg())
760 // This copy will become a noop. If it's defining a new val#, merge it into
762 SlotIndex DefIdx = UseIdx.getRegSlot();
763 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
766 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
767 assert(DVNI->def == DefIdx);
768 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
769 ErasedInstrs.insert(UseMI);
770 LIS->RemoveMachineInstrFromMaps(UseMI);
771 UseMI->eraseFromParent();
774 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
776 VNInfo *ValNo = BValNo;
777 ValNo->def = AValNo->def;
778 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
780 if (AI->valno != AValNo) continue;
781 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
783 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
785 IntA.removeValNo(AValNo);
786 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
791 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
792 /// computation, replace the copy by rematerialize the definition.
793 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
795 MachineInstr *CopyMI) {
796 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
797 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
798 assert(SrcLR != SrcInt.end() && "Live range not found!");
799 VNInfo *ValNo = SrcLR->valno;
800 if (ValNo->isPHIDef() || ValNo->isUnused())
802 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
805 assert(DefMI && "Defining instruction disappeared");
806 if (!DefMI->isAsCheapAsAMove())
808 if (!TII->isTriviallyReMaterializable(DefMI, AA))
810 bool SawStore = false;
811 if (!DefMI->isSafeToMove(TII, AA, SawStore))
813 const MCInstrDesc &MCID = DefMI->getDesc();
814 if (MCID.getNumDefs() != 1)
816 if (!DefMI->isImplicitDef()) {
817 // Make sure the copy destination register class fits the instruction
818 // definition register class. The mismatch can happen as a result of earlier
819 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
820 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
821 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
822 if (MRI->getRegClass(DstReg) != RC)
824 } else if (!RC->contains(DstReg))
828 MachineBasicBlock *MBB = CopyMI->getParent();
829 MachineBasicBlock::iterator MII =
830 llvm::next(MachineBasicBlock::iterator(CopyMI));
831 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
832 MachineInstr *NewMI = prior(MII);
834 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
835 // We need to remember these so we can add intervals once we insert
836 // NewMI into SlotIndexes.
837 SmallVector<unsigned, 4> NewMIImplDefs;
838 for (unsigned i = NewMI->getDesc().getNumOperands(),
839 e = NewMI->getNumOperands(); i != e; ++i) {
840 MachineOperand &MO = NewMI->getOperand(i);
842 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
843 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
844 NewMIImplDefs.push_back(MO.getReg());
848 // CopyMI may have implicit operands, transfer them over to the newly
849 // rematerialized instruction. And update implicit def interval valnos.
850 for (unsigned i = CopyMI->getDesc().getNumOperands(),
851 e = CopyMI->getNumOperands(); i != e; ++i) {
852 MachineOperand &MO = CopyMI->getOperand(i);
854 assert(MO.isImplicit() && "No explicit operands after implict operands.");
855 // Discard VReg implicit defs.
856 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
857 NewMI->addOperand(MO);
862 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
864 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
865 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
866 unsigned reg = NewMIImplDefs[i];
867 LiveInterval &li = LIS->getInterval(reg);
868 VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
869 LIS->getVNInfoAllocator());
870 LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
874 CopyMI->eraseFromParent();
875 ErasedInstrs.insert(CopyMI);
876 ReMatDefs.insert(DefMI);
877 DEBUG(dbgs() << "Remat: " << *NewMI);
880 // The source interval can become smaller because we removed a use.
881 LIS->shrinkToUses(&SrcInt, &DeadDefs);
882 if (!DeadDefs.empty())
888 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
889 /// values, it only removes local variables. When we have a copy like:
891 /// %vreg1 = COPY %vreg2<undef>
893 /// We delete the copy and remove the corresponding value number from %vreg1.
894 /// Any uses of that value number are marked as <undef>.
895 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
896 const CoalescerPair &CP) {
897 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
898 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
899 if (SrcInt->liveAt(Idx))
901 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
902 if (DstInt->liveAt(Idx))
905 // No intervals are live-in to CopyMI - it is undef.
910 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
911 assert(DeadVNI && "No value defined in DstInt");
912 DstInt->removeValNo(DeadVNI);
914 // Find new undef uses.
915 for (MachineRegisterInfo::reg_nodbg_iterator
916 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
918 MachineOperand &MO = I.getOperand();
919 if (MO.isDef() || MO.isUndef())
921 MachineInstr *MI = MO.getParent();
922 SlotIndex Idx = LIS->getInstructionIndex(MI);
923 if (DstInt->liveAt(Idx))
926 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
931 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
932 /// update the subregister number if it is not zero. If DstReg is a
933 /// physical register and the existing subregister number of the def / use
934 /// being updated is not zero, make sure to set it to the correct physical
936 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
939 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
940 LiveInterval &DstInt = LIS->getInterval(DstReg);
942 // Update LiveDebugVariables.
943 LDV->renameRegister(SrcReg, DstReg, SubIdx);
945 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
946 MachineInstr *UseMI = I.skipInstruction();) {
947 bool AlreadyJoined = JoinedCopies.count(UseMI);
948 SmallVector<unsigned,8> Ops;
950 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
952 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
953 // because SrcReg is a sub-register.
954 if (!Reads && SubIdx && !AlreadyJoined)
955 Reads = DstInt.liveAt(LIS->getInstructionIndex(UseMI));
957 // Replace SrcReg with DstReg in all UseMI operands.
958 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
959 MachineOperand &MO = UseMI->getOperand(Ops[i]);
961 // Adjust <undef> flags in case of sub-register joins. We don't want to
962 // turn a full def into a read-modify-write sub-register def and vice
964 if (SubIdx && !AlreadyJoined && MO.isDef())
965 MO.setIsUndef(!Reads);
968 MO.substPhysReg(DstReg, *TRI);
970 MO.substVirtReg(DstReg, SubIdx, *TRI);
973 // This instruction is a copy that will be removed.
978 dbgs() << "\t\tupdated: ";
979 if (!UseMI->isDebugValue())
980 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
986 /// removeIntervalIfEmpty - Check if the live interval of a physical register
987 /// is empty, if so remove it and also remove the empty intervals of its
988 /// sub-registers. Return true if live interval is removed.
989 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
990 const TargetRegisterInfo *TRI) {
992 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
993 for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
994 if (!LIS->hasInterval(*SR))
996 LiveInterval &sli = LIS->getInterval(*SR);
998 LIS->removeInterval(*SR);
1000 LIS->removeInterval(li.reg);
1006 /// removeDeadDef - If a def of a live interval is now determined dead, remove
1007 /// the val# it defines. If the live interval becomes empty, remove it as well.
1008 bool RegisterCoalescer::removeDeadDef(LiveInterval &li, MachineInstr *DefMI) {
1009 SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
1010 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
1011 if (DefIdx != MLR->valno->def)
1013 li.removeValNo(MLR->valno);
1014 return removeIntervalIfEmpty(li, LIS, TRI);
1017 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
1018 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
1019 /// Always join simple intervals that are defined by a single copy from a
1020 /// reserved register. This doesn't increase register pressure, so it is
1021 /// always beneficial.
1022 if (!RegClassInfo.isReserved(CP.getDstReg())) {
1023 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1027 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1028 if (CP.isFlipped() && JoinVInt.containsOneValue())
1031 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1035 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1036 /// which are the src/dst of the copy instruction CopyMI. This returns true
1037 /// if the copy was successfully coalesced away. If it is not currently
1038 /// possible to coalesce this interval, but it may be possible if other
1039 /// things get coalesced, then it returns true by reference in 'Again'.
1040 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1043 if (JoinedCopies.count(CopyMI))
1044 return false; // Already done.
1046 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1048 CoalescerPair CP(*TII, *TRI);
1049 if (!CP.setRegisters(CopyMI)) {
1050 DEBUG(dbgs() << "\tNot coalescable.\n");
1054 // Dead code elimination. This really should be handled by MachineDCE, but
1055 // sometimes dead copies slip through, and we can't generate invalid live
1057 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1058 DEBUG(dbgs() << "\tCopy is dead.\n");
1059 DeadDefs.push_back(CopyMI);
1060 eliminateDeadDefs();
1064 // If they are already joined we continue.
1065 if (CP.getSrcReg() == CP.getDstReg()) {
1066 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1067 LIS->RemoveMachineInstrFromMaps(CopyMI);
1068 CopyMI->eraseFromParent();
1069 return false; // Not coalescable.
1072 // Eliminate undefs.
1073 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1074 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1075 LIS->RemoveMachineInstrFromMaps(CopyMI);
1076 CopyMI->eraseFromParent();
1077 return false; // Not coalescable.
1080 // Enforce policies.
1082 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1083 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1085 if (!canJoinPhys(CP)) {
1086 // Before giving up coalescing, if definition of source is defined by
1087 // trivial computation, try rematerializing it.
1088 if (!CP.isFlipped() &&
1089 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1090 CP.getDstReg(), CopyMI))
1096 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1098 if (CP.getDstIdx() && CP.getSrcIdx())
1099 dbgs() << PrintReg(CP.getDstReg()) << " in "
1100 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1101 << PrintReg(CP.getSrcReg()) << " in "
1102 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1104 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1105 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1108 // When possible, let DstReg be the larger interval.
1109 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1110 LIS->getInterval(CP.getDstReg()).ranges.size())
1114 // Okay, attempt to join these two intervals. On failure, this returns false.
1115 // Otherwise, if one of the intervals being joined is a physreg, this method
1116 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1117 // been modified, so we can use this information below to update aliases.
1118 if (!joinIntervals(CP)) {
1119 // Coalescing failed.
1121 // If definition of source is defined by trivial computation, try
1122 // rematerializing it.
1123 if (!CP.isFlipped() &&
1124 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1125 CP.getDstReg(), CopyMI))
1128 // If we can eliminate the copy without merging the live ranges, do so now.
1129 if (!CP.isPartial()) {
1130 if (adjustCopiesBackFrom(CP, CopyMI) ||
1131 removeCopyByCommutingDef(CP, CopyMI)) {
1132 LIS->RemoveMachineInstrFromMaps(CopyMI);
1133 CopyMI->eraseFromParent();
1134 DEBUG(dbgs() << "\tTrivial!\n");
1139 // Otherwise, we are unable to join the intervals.
1140 DEBUG(dbgs() << "\tInterference!\n");
1141 Again = true; // May be possible to coalesce later.
1145 // Coalescing to a virtual register that is of a sub-register class of the
1146 // other. Make sure the resulting register is set to the right register class.
1147 if (CP.isCrossClass()) {
1149 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1152 // Removing sub-register copies can ease the register class constraints.
1153 // Make sure we attempt to inflate the register class of DstReg.
1154 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1155 InflateRegs.push_back(CP.getDstReg());
1157 // Remember to delete the copy instruction.
1158 LIS->RemoveMachineInstrFromMaps(CopyMI);
1159 CopyMI->eraseFromParent();
1161 // Rewrite all SrcReg operands to DstReg.
1162 // Also update DstReg operands to include DstIdx if it is set.
1164 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1165 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1167 // SrcReg is guaranteed to be the register whose live interval that is
1169 LIS->removeInterval(CP.getSrcReg());
1171 // Update regalloc hint.
1172 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1175 LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1176 dbgs() << "\tJoined. Result = ";
1177 DstInt.print(dbgs(), TRI);
1185 /// Attempt joining with a reserved physreg.
1186 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1187 assert(CP.isPhys() && "Must be a physreg copy");
1188 assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1189 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1190 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1192 assert(CP.isFlipped() && RHS.containsOneValue() &&
1193 "Invalid join with reserved register");
1195 // Optimization for reserved registers like ESP. We can only merge with a
1196 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1197 // The live range of the reserved register will look like a set of dead defs
1198 // - we don't properly track the live range of reserved registers.
1200 // Deny any overlapping intervals. This depends on all the reserved
1201 // register live ranges to look like dead defs.
1202 for (const uint16_t *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1203 if (!LIS->hasInterval(*AS)) {
1204 // Make sure at least DstReg itself exists before attempting a join.
1205 if (*AS == CP.getDstReg())
1206 LIS->getOrCreateInterval(CP.getDstReg());
1209 if (RHS.overlaps(LIS->getInterval(*AS))) {
1210 DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1214 // Skip any value computations, we are not adding new values to the
1215 // reserved register. Also skip merging the live ranges, the reserved
1216 // register live range doesn't need to be accurate as long as all the
1221 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1222 /// compute what the resultant value numbers for each value in the input two
1223 /// ranges will be. This is complicated by copies between the two which can
1224 /// and will commonly cause multiple value numbers to be merged into one.
1226 /// VN is the value number that we're trying to resolve. InstDefiningValue
1227 /// keeps track of the new InstDefiningValue assignment for the result
1228 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1229 /// whether a value in this or other is a copy from the opposite set.
1230 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1231 /// already been assigned.
1233 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1234 /// contains the value number the copy is from.
1236 static unsigned ComputeUltimateVN(VNInfo *VNI,
1237 SmallVector<VNInfo*, 16> &NewVNInfo,
1238 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1239 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1240 SmallVector<int, 16> &ThisValNoAssignments,
1241 SmallVector<int, 16> &OtherValNoAssignments) {
1242 unsigned VN = VNI->id;
1244 // If the VN has already been computed, just return it.
1245 if (ThisValNoAssignments[VN] >= 0)
1246 return ThisValNoAssignments[VN];
1247 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1249 // If this val is not a copy from the other val, then it must be a new value
1250 // number in the destination.
1251 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1252 if (I == ThisFromOther.end()) {
1253 NewVNInfo.push_back(VNI);
1254 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1256 VNInfo *OtherValNo = I->second;
1258 // Otherwise, this *is* a copy from the RHS. If the other side has already
1259 // been computed, return it.
1260 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1261 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1263 // Mark this value number as currently being computed, then ask what the
1264 // ultimate value # of the other value is.
1265 ThisValNoAssignments[VN] = -2;
1266 unsigned UltimateVN =
1267 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1268 OtherValNoAssignments, ThisValNoAssignments);
1269 return ThisValNoAssignments[VN] = UltimateVN;
1273 // Find out if we have something like
1276 // if so, we can pretend this is actually
1279 // which allows us to coalesce A and B.
1280 // VNI is the definition of B. LR is the life range of A that includes
1281 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1282 // This implies that A dominates B.
1283 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1284 const TargetRegisterInfo &tri,
1288 SmallVector<MachineInstr*, 8> &DupCopies) {
1289 // FIXME: This is very conservative. For example, we don't handle
1290 // physical registers.
1292 MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1294 if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1297 unsigned Dst = MI->getOperand(0).getReg();
1298 unsigned Src = MI->getOperand(1).getReg();
1300 if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1301 !TargetRegisterInfo::isVirtualRegister(Dst))
1304 unsigned A = CP.getDstReg();
1305 unsigned B = CP.getSrcReg();
1311 VNInfo *Other = LR->valno;
1312 const MachineInstr *OtherMI = li.getInstructionFromIndex(Other->def);
1314 if (!OtherMI || !OtherMI->isFullCopy())
1317 unsigned OtherDst = OtherMI->getOperand(0).getReg();
1318 unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1320 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1321 !TargetRegisterInfo::isVirtualRegister(OtherDst))
1324 assert(OtherDst == B);
1326 if (Src != OtherSrc)
1329 // If the copies use two different value numbers of X, we cannot merge
1331 LiveInterval &SrcInt = li.getInterval(Src);
1332 // getVNInfoBefore returns NULL for undef copies. In this case, the
1333 // optimization is still safe.
1334 if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1337 DupCopies.push_back(MI);
1342 /// joinIntervals - Attempt to join these two intervals. On failure, this
1344 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1345 // Handle physreg joins separately.
1347 return joinReservedPhysReg(CP);
1349 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1350 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1352 // Compute the final value assignment, assuming that the live ranges can be
1354 SmallVector<int, 16> LHSValNoAssignments;
1355 SmallVector<int, 16> RHSValNoAssignments;
1356 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1357 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1358 SmallVector<VNInfo*, 16> NewVNInfo;
1360 SmallVector<MachineInstr*, 8> DupCopies;
1362 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1363 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1365 // Loop over the value numbers of the LHS, seeing if any are defined from
1367 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1370 if (VNI->isUnused() || VNI->isPHIDef())
1372 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1373 assert(MI && "Missing def");
1374 if (!MI->isCopyLike()) // Src not defined by a copy?
1377 // Figure out the value # from the RHS.
1378 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1379 // The copy could be to an aliased physreg.
1382 // DstReg is known to be a register in the LHS interval. If the src is
1383 // from the RHS interval, we can use its value #.
1384 if (!CP.isCoalescable(MI) &&
1385 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1388 LHSValsDefinedFromRHS[VNI] = lr->valno;
1391 // Loop over the value numbers of the RHS, seeing if any are defined from
1393 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1396 if (VNI->isUnused() || VNI->isPHIDef())
1398 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1399 assert(MI && "Missing def");
1400 if (!MI->isCopyLike()) // Src not defined by a copy?
1403 // Figure out the value # from the LHS.
1404 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1405 // The copy could be to an aliased physreg.
1408 // DstReg is known to be a register in the RHS interval. If the src is
1409 // from the LHS interval, we can use its value #.
1410 if (!CP.isCoalescable(MI) &&
1411 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1414 RHSValsDefinedFromLHS[VNI] = lr->valno;
1417 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1418 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1419 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1421 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1424 unsigned VN = VNI->id;
1425 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1427 ComputeUltimateVN(VNI, NewVNInfo,
1428 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1429 LHSValNoAssignments, RHSValNoAssignments);
1431 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1434 unsigned VN = VNI->id;
1435 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1437 // If this value number isn't a copy from the LHS, it's a new number.
1438 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1439 NewVNInfo.push_back(VNI);
1440 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1444 ComputeUltimateVN(VNI, NewVNInfo,
1445 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1446 RHSValNoAssignments, LHSValNoAssignments);
1449 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1450 // interval lists to see if these intervals are coalescable.
1451 LiveInterval::const_iterator I = LHS.begin();
1452 LiveInterval::const_iterator IE = LHS.end();
1453 LiveInterval::const_iterator J = RHS.begin();
1454 LiveInterval::const_iterator JE = RHS.end();
1456 // Skip ahead until the first place of potential sharing.
1457 if (I != IE && J != JE) {
1458 if (I->start < J->start) {
1459 I = std::upper_bound(I, IE, J->start);
1460 if (I != LHS.begin()) --I;
1461 } else if (J->start < I->start) {
1462 J = std::upper_bound(J, JE, I->start);
1463 if (J != RHS.begin()) --J;
1467 while (I != IE && J != JE) {
1468 // Determine if these two live ranges overlap.
1470 if (I->start < J->start) {
1471 Overlaps = I->end > J->start;
1473 Overlaps = J->end > I->start;
1476 // If so, check value # info to determine if they are really different.
1478 // If the live range overlap will map to the same value number in the
1479 // result liverange, we can still coalesce them. If not, we can't.
1480 if (LHSValNoAssignments[I->valno->id] !=
1481 RHSValNoAssignments[J->valno->id])
1485 if (I->end < J->end)
1491 // Update kill info. Some live ranges are extended due to copy coalescing.
1492 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1493 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1494 VNInfo *VNI = I->first;
1495 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1496 if (VNI->hasPHIKill())
1497 NewVNInfo[LHSValID]->setHasPHIKill(true);
1500 // Update kill info. Some live ranges are extended due to copy coalescing.
1501 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1502 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1503 VNInfo *VNI = I->first;
1504 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1505 if (VNI->hasPHIKill())
1506 NewVNInfo[RHSValID]->setHasPHIKill(true);
1509 if (LHSValNoAssignments.empty())
1510 LHSValNoAssignments.push_back(-1);
1511 if (RHSValNoAssignments.empty())
1512 RHSValNoAssignments.push_back(-1);
1514 SmallVector<unsigned, 8> SourceRegisters;
1515 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1516 E = DupCopies.end(); I != E; ++I) {
1517 MachineInstr *MI = *I;
1519 // We have pretended that the assignment to B in
1522 // was actually a copy from A. Now that we decided to coalesce A and B,
1523 // transform the code into
1525 unsigned Src = MI->getOperand(1).getReg();
1526 SourceRegisters.push_back(Src);
1527 ErasedInstrs.insert(MI);
1528 LIS->RemoveMachineInstrFromMaps(MI);
1529 MI->eraseFromParent();
1532 // If B = X was the last use of X in a liverange, we have to shrink it now
1533 // that B = X is gone.
1534 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1535 E = SourceRegisters.end(); I != E; ++I) {
1536 LIS->shrinkToUses(&LIS->getInterval(*I));
1539 // If we get here, we know that we can coalesce the live ranges. Ask the
1540 // intervals to coalesce themselves now.
1541 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1547 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1548 // depth of the basic block (the unsigned), and then on the MBB number.
1549 struct DepthMBBCompare {
1550 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1551 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1552 // Deeper loops first
1553 if (LHS.first != RHS.first)
1554 return LHS.first > RHS.first;
1556 // Prefer blocks that are more connected in the CFG. This takes care of
1557 // the most difficult copies first while intervals are short.
1558 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1559 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1563 // As a last resort, sort by block number.
1564 return LHS.second->getNumber() < RHS.second->getNumber();
1569 // Try joining WorkList copies starting from index From.
1570 // Null out any successful joins.
1571 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
1572 assert(From <= WorkList.size() && "Out of range");
1573 bool Progress = false;
1574 for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
1577 // Skip instruction pointers that have already been erased, for example by
1578 // dead code elimination.
1579 if (ErasedInstrs.erase(WorkList[i])) {
1584 bool Success = joinCopy(WorkList[i], Again);
1585 Progress |= Success;
1586 if (Success || !Again)
1593 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
1594 DEBUG(dbgs() << MBB->getName() << ":\n");
1596 // Collect all copy-like instructions in MBB. Don't start coalescing anything
1597 // yet, it might invalidate the iterator.
1598 const unsigned PrevSize = WorkList.size();
1599 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1601 if (MII->isCopyLike())
1602 WorkList.push_back(MII);
1604 // Try coalescing the collected copies immediately, and remove the nulls.
1605 // This prevents the WorkList from getting too large since most copies are
1606 // joinable on the first attempt.
1607 if (copyCoalesceWorkList(PrevSize))
1608 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
1609 (MachineInstr*)0), WorkList.end());
1612 void RegisterCoalescer::joinAllIntervals() {
1613 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1614 assert(WorkList.empty() && "Old data still around.");
1616 if (Loops->empty()) {
1617 // If there are no loops in the function, join intervals in function order.
1618 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1620 copyCoalesceInMBB(I);
1622 // Otherwise, join intervals in inner loops before other intervals.
1623 // Unfortunately we can't just iterate over loop hierarchy here because
1624 // there may be more MBB's than BB's. Collect MBB's for sorting.
1626 // Join intervals in the function prolog first. We want to join physical
1627 // registers with virtual registers before the intervals got too long.
1628 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1629 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1630 MachineBasicBlock *MBB = I;
1631 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1634 // Sort by loop depth.
1635 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1637 // Finally, join intervals in loop nest order.
1638 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1639 copyCoalesceInMBB(MBBs[i].second);
1642 // Joining intervals can allow other intervals to be joined. Iteratively join
1643 // until we make no progress.
1644 while (copyCoalesceWorkList())
1648 void RegisterCoalescer::releaseMemory() {
1649 JoinedCopies.clear();
1650 ErasedInstrs.clear();
1654 InflateRegs.clear();
1657 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1659 MRI = &fn.getRegInfo();
1660 TM = &fn.getTarget();
1661 TRI = TM->getRegisterInfo();
1662 TII = TM->getInstrInfo();
1663 LIS = &getAnalysis<LiveIntervals>();
1664 LDV = &getAnalysis<LiveDebugVariables>();
1665 AA = &getAnalysis<AliasAnalysis>();
1666 Loops = &getAnalysis<MachineLoopInfo>();
1668 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1669 << "********** Function: "
1670 << ((Value*)MF->getFunction())->getName() << '\n');
1672 if (VerifyCoalescing)
1673 MF->verify(this, "Before register coalescing");
1675 RegClassInfo.runOnMachineFunction(fn);
1677 // Join (coalesce) intervals if requested.
1678 if (EnableJoining) {
1681 dbgs() << "********** INTERVALS POST JOINING **********\n";
1682 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1684 I->second->print(dbgs(), TRI);
1690 // Perform a final pass over the instructions and compute spill weights
1691 // and remove identity moves.
1692 SmallVector<unsigned, 4> DeadDefs;
1693 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1694 mbbi != mbbe; ++mbbi) {
1695 MachineBasicBlock* mbb = mbbi;
1696 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1698 MachineInstr *MI = mii;
1699 if (JoinedCopies.count(MI)) {
1700 // Delete all coalesced copies.
1701 bool DoDelete = true;
1702 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1703 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1705 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1706 MI->getNumOperands() > 2)
1707 // Do not delete extract_subreg, insert_subreg of physical
1708 // registers unless the definition is dead. e.g.
1709 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1710 // or else the scavenger may complain. LowerSubregs will
1711 // delete them later.
1714 if (MI->allDefsAreDead()) {
1715 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1716 LIS->hasInterval(SrcReg))
1717 LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1721 // We need the instruction to adjust liveness, so make it a KILL.
1722 if (MI->isSubregToReg()) {
1723 MI->RemoveOperand(3);
1724 MI->RemoveOperand(1);
1726 MI->setDesc(TII->get(TargetOpcode::KILL));
1727 mii = llvm::next(mii);
1729 LIS->RemoveMachineInstrFromMaps(MI);
1730 mii = mbbi->erase(mii);
1736 // Now check if this is a remat'ed def instruction which is now dead.
1737 if (ReMatDefs.count(MI)) {
1739 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1740 const MachineOperand &MO = MI->getOperand(i);
1743 unsigned Reg = MO.getReg();
1746 DeadDefs.push_back(Reg);
1749 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1750 !MRI->use_nodbg_empty(Reg)) {
1756 while (!DeadDefs.empty()) {
1757 unsigned DeadDef = DeadDefs.back();
1758 DeadDefs.pop_back();
1759 removeDeadDef(LIS->getInterval(DeadDef), MI);
1761 LIS->RemoveMachineInstrFromMaps(mii);
1762 mii = mbbi->erase(mii);
1770 // Check for now unnecessary kill flags.
1771 if (LIS->isNotInMIMap(MI)) continue;
1772 SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1773 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1774 MachineOperand &MO = MI->getOperand(i);
1775 if (!MO.isReg() || !MO.isKill()) continue;
1776 unsigned reg = MO.getReg();
1777 if (!reg || !LIS->hasInterval(reg)) continue;
1778 if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1779 MO.setIsKill(false);
1782 // When leaving a kill flag on a physreg, check if any subregs should
1784 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1786 for (const uint16_t *SR = TRI->getSubRegisters(reg);
1787 unsigned S = *SR; ++SR)
1788 if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1789 MI->addRegisterDefined(S, TRI);
1794 // After deleting a lot of copies, register classes may be less constrained.
1795 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
1797 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1798 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1800 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1801 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1802 unsigned Reg = InflateRegs[i];
1803 if (MRI->reg_nodbg_empty(Reg))
1805 if (MRI->recomputeRegClass(Reg, *TM)) {
1806 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1807 << MRI->getRegClass(Reg)->getName() << '\n');
1814 if (VerifyCoalescing)
1815 MF->verify(this, "After register coalescing");
1819 /// print - Implement the dump method.
1820 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {