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 "regcoalescing"
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(numAborts , "Number of times interval joining aborted");
58 STATISTIC(NumInflated , "Number of register classes inflated");
61 EnableJoining("join-liveintervals",
62 cl::desc("Coalesce copies (default=true)"),
66 DisableCrossClassJoin("disable-cross-class-join",
67 cl::desc("Avoid coalescing cross register class copies"),
68 cl::init(false), cl::Hidden);
71 EnablePhysicalJoin("join-physregs",
72 cl::desc("Join physical register copies"),
73 cl::init(false), cl::Hidden);
76 VerifyCoalescing("verify-coalescing",
77 cl::desc("Verify machine instrs before and after register coalescing"),
81 class RegisterCoalescer : public MachineFunctionPass {
83 MachineRegisterInfo* MRI;
84 const TargetMachine* TM;
85 const TargetRegisterInfo* TRI;
86 const TargetInstrInfo* TII;
88 LiveDebugVariables *LDV;
89 const MachineLoopInfo* Loops;
91 RegisterClassInfo RegClassInfo;
93 /// JoinedCopies - Keep track of copies eliminated due to coalescing.
95 SmallPtrSet<MachineInstr*, 32> JoinedCopies;
97 /// ReMatCopies - Keep track of copies eliminated due to remat.
99 SmallPtrSet<MachineInstr*, 32> ReMatCopies;
101 /// ReMatDefs - Keep track of definition instructions which have
103 SmallPtrSet<MachineInstr*, 8> ReMatDefs;
105 /// joinIntervals - join compatible live intervals
106 void joinIntervals();
108 /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting
109 /// copies that cannot yet be coalesced into the "TryAgain" list.
110 void CopyCoalesceInMBB(MachineBasicBlock *MBB,
111 std::vector<MachineInstr*> &TryAgain);
113 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
114 /// which are the src/dst of the copy instruction CopyMI. This returns
115 /// true if the copy was successfully coalesced away. If it is not
116 /// currently possible to coalesce this interval, but it may be possible if
117 /// other things get coalesced, then it returns true by reference in
119 bool JoinCopy(MachineInstr *TheCopy, bool &Again);
121 /// JoinIntervals - Attempt to join these two intervals. On failure, this
122 /// returns false. The output "SrcInt" will not have been modified, so we
123 /// can use this information below to update aliases.
124 bool JoinIntervals(CoalescerPair &CP);
126 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
127 /// the source value number is defined by a copy from the destination reg
128 /// see if we can merge these two destination reg valno# into a single
129 /// value number, eliminating a copy.
130 bool AdjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
132 /// HasOtherReachingDefs - Return true if there are definitions of IntB
133 /// other than BValNo val# that can reach uses of AValno val# of IntA.
134 bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
135 VNInfo *AValNo, VNInfo *BValNo);
137 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy.
138 /// If the source value number is defined by a commutable instruction and
139 /// its other operand is coalesced to the copy dest register, see if we
140 /// can transform the copy into a noop by commuting the definition.
141 bool RemoveCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
143 /// ReMaterializeTrivialDef - If the source of a copy is defined by a
144 /// trivial computation, replace the copy by rematerialize the definition.
145 /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
146 bool ReMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
147 unsigned DstReg, unsigned DstSubIdx,
148 MachineInstr *CopyMI);
150 /// shouldJoinPhys - Return true if a physreg copy should be joined.
151 bool shouldJoinPhys(CoalescerPair &CP);
153 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
154 /// two virtual registers from different register classes.
155 bool isWinToJoinCrossClass(unsigned SrcReg,
157 const TargetRegisterClass *SrcRC,
158 const TargetRegisterClass *DstRC,
159 const TargetRegisterClass *NewRC);
161 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
162 /// update the subregister number if it is not zero. If DstReg is a
163 /// physical register and the existing subregister number of the def / use
164 /// being updated is not zero, make sure to set it to the correct physical
166 void UpdateRegDefsUses(const CoalescerPair &CP);
168 /// RemoveDeadDef - If a def of a live interval is now determined dead,
169 /// remove the val# it defines. If the live interval becomes empty, remove
171 bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI);
173 /// RemoveCopyFlag - If DstReg is no longer defined by CopyMI, clear the
174 /// VNInfo copy flag for DstReg and all aliases.
175 void RemoveCopyFlag(unsigned DstReg, const MachineInstr *CopyMI);
177 /// markAsJoined - Remember that CopyMI has already been joined.
178 void markAsJoined(MachineInstr *CopyMI);
180 /// eliminateUndefCopy - Handle copies of undef values.
181 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
184 static char ID; // Class identification, replacement for typeinfo
185 RegisterCoalescer() : MachineFunctionPass(ID) {
186 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
189 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
191 virtual void releaseMemory();
193 /// runOnMachineFunction - pass entry point
194 virtual bool runOnMachineFunction(MachineFunction&);
196 /// print - Implement the dump method.
197 virtual void print(raw_ostream &O, const Module* = 0) const;
199 } /// end anonymous namespace
201 char &llvm::RegisterCoalescerPassID = RegisterCoalescer::ID;
203 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
204 "Simple Register Coalescing", false, false)
205 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
206 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
207 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
208 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
209 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
210 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
211 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
212 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
213 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
214 "Simple Register Coalescing", false, false)
216 char RegisterCoalescer::ID = 0;
218 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
221 return tri.composeSubRegIndices(a, b);
224 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
225 unsigned &Src, unsigned &Dst,
226 unsigned &SrcSub, unsigned &DstSub) {
228 Dst = MI->getOperand(0).getReg();
229 DstSub = MI->getOperand(0).getSubReg();
230 Src = MI->getOperand(1).getReg();
231 SrcSub = MI->getOperand(1).getSubReg();
232 } else if (MI->isSubregToReg()) {
233 Dst = MI->getOperand(0).getReg();
234 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
235 MI->getOperand(3).getImm());
236 Src = MI->getOperand(2).getReg();
237 SrcSub = MI->getOperand(2).getSubReg();
243 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
244 SrcReg = DstReg = SubIdx = 0;
246 Flipped = CrossClass = false;
248 unsigned Src, Dst, SrcSub, DstSub;
249 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
251 Partial = SrcSub || DstSub;
253 // If one register is a physreg, it must be Dst.
254 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
255 if (TargetRegisterInfo::isPhysicalRegister(Dst))
258 std::swap(SrcSub, DstSub);
262 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
264 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
265 // Eliminate DstSub on a physreg.
267 Dst = TRI.getSubReg(Dst, DstSub);
268 if (!Dst) return false;
272 // Eliminate SrcSub by picking a corresponding Dst superregister.
274 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
275 if (!Dst) return false;
277 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
281 // Both registers are virtual.
283 // Both registers have subreg indices.
284 if (SrcSub && DstSub) {
285 // For now we only handle the case of identical indices in commensurate
286 // registers: Dreg:ssub_1 + Dreg:ssub_1 -> Dreg
287 // FIXME: Handle Qreg:ssub_3 + Dreg:ssub_1 as QReg:dsub_1 + Dreg.
288 if (SrcSub != DstSub)
290 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
291 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
292 if (!getCommonSubClass(DstRC, SrcRC))
297 // There can be no SrcSub.
302 assert(!Flipped && "Unexpected flip");
306 // Find the new register class.
307 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
308 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
310 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
312 NewRC = getCommonSubClass(DstRC, SrcRC);
315 CrossClass = NewRC != DstRC || NewRC != SrcRC;
317 // Check our invariants
318 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
319 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
320 "Cannot have a physical SubIdx");
327 bool CoalescerPair::flip() {
328 if (SubIdx || TargetRegisterInfo::isPhysicalRegister(DstReg))
330 std::swap(SrcReg, DstReg);
335 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
338 unsigned Src, Dst, SrcSub, DstSub;
339 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
342 // Find the virtual register that is SrcReg.
345 std::swap(SrcSub, DstSub);
346 } else if (Src != SrcReg) {
350 // Now check that Dst matches DstReg.
351 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
352 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
354 assert(!SubIdx && "Inconsistent CoalescerPair state.");
355 // DstSub could be set for a physreg from INSERT_SUBREG.
357 Dst = TRI.getSubReg(Dst, DstSub);
360 return DstReg == Dst;
361 // This is a partial register copy. Check that the parts match.
362 return TRI.getSubReg(DstReg, SrcSub) == Dst;
364 // DstReg is virtual.
367 // Registers match, do the subregisters line up?
368 return compose(TRI, SubIdx, SrcSub) == DstSub;
372 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
373 AU.setPreservesCFG();
374 AU.addRequired<AliasAnalysis>();
375 AU.addRequired<LiveIntervals>();
376 AU.addPreserved<LiveIntervals>();
377 AU.addRequired<LiveDebugVariables>();
378 AU.addPreserved<LiveDebugVariables>();
379 AU.addPreserved<SlotIndexes>();
380 AU.addRequired<MachineLoopInfo>();
381 AU.addPreserved<MachineLoopInfo>();
382 AU.addPreservedID(MachineDominatorsID);
383 AU.addPreservedID(StrongPHIEliminationID);
384 AU.addPreservedID(PHIEliminationID);
385 AU.addPreservedID(TwoAddressInstructionPassID);
386 MachineFunctionPass::getAnalysisUsage(AU);
389 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
390 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
391 JoinedCopies.insert(CopyMI);
393 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
394 /// code elimination.
395 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
396 E = CopyMI->operands_end(); I != E; ++I)
401 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
402 /// being the source and IntB being the dest, thus this defines a value number
403 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
404 /// see if we can merge these two pieces of B into a single value number,
405 /// eliminating a copy. For example:
409 /// B1 = A3 <- this copy
411 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
412 /// value number to be replaced with B0 (which simplifies the B liveinterval).
414 /// This returns true if an interval was modified.
416 bool RegisterCoalescer::AdjustCopiesBackFrom(const CoalescerPair &CP,
417 MachineInstr *CopyMI) {
418 // Bail if there is no dst interval - can happen when merging physical subreg
420 if (!LIS->hasInterval(CP.getDstReg()))
424 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
426 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
427 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getDefIndex();
429 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
430 // the example above.
431 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
432 if (BLR == IntB.end()) return false;
433 VNInfo *BValNo = BLR->valno;
435 // Get the location that B is defined at. Two options: either this value has
436 // an unknown definition point or it is defined at CopyIdx. If unknown, we
438 if (!BValNo->isDefByCopy()) return false;
439 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
441 // AValNo is the value number in A that defines the copy, A3 in the example.
442 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
443 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
444 // The live range might not exist after fun with physreg coalescing.
445 if (ALR == IntA.end()) return false;
446 VNInfo *AValNo = ALR->valno;
447 // If it's re-defined by an early clobber somewhere in the live range, then
448 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
450 // 172 %ECX<def> = MOV32rr %reg1039<kill>
451 // 180 INLINEASM <es:subl $5,$1
452 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
454 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
455 // 188 %EAX<def> = MOV32rr %EAX<kill>
456 // 196 %ECX<def> = MOV32rr %ECX<kill>
457 // 204 %ECX<def> = MOV32rr %ECX<kill>
458 // 212 %EAX<def> = MOV32rr %EAX<kill>
459 // 220 %EAX<def> = MOV32rr %EAX
460 // 228 %reg1039<def> = MOV32rr %ECX<kill>
461 // The early clobber operand ties ECX input to the ECX def.
463 // The live interval of ECX is represented as this:
464 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
465 // The coalescer has no idea there was a def in the middle of [174,230].
466 if (AValNo->hasRedefByEC())
469 // If AValNo is defined as a copy from IntB, we can potentially process this.
470 // Get the instruction that defines this value number.
471 if (!CP.isCoalescable(AValNo->getCopy()))
474 // Get the LiveRange in IntB that this value number starts with.
475 LiveInterval::iterator ValLR =
476 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
477 if (ValLR == IntB.end())
480 // Make sure that the end of the live range is inside the same block as
482 MachineInstr *ValLREndInst =
483 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
484 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
487 // Okay, we now know that ValLR ends in the same block that the CopyMI
488 // live-range starts. If there are no intervening live ranges between them in
489 // IntB, we can merge them.
490 if (ValLR+1 != BLR) return false;
492 // If a live interval is a physical register, conservatively check if any
493 // of its aliases is overlapping the live interval of the virtual register.
494 // If so, do not coalesce.
495 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
496 for (const unsigned *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
497 if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
499 dbgs() << "\t\tInterfere with alias ";
500 LIS->getInterval(*AS).print(dbgs(), TRI);
507 dbgs() << "Extending: ";
508 IntB.print(dbgs(), TRI);
511 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
512 // We are about to delete CopyMI, so need to remove it as the 'instruction
513 // that defines this value #'. Update the valnum with the new defining
515 BValNo->def = FillerStart;
518 // Okay, we can merge them. We need to insert a new liverange:
519 // [ValLR.end, BLR.begin) of either value number, then we merge the
520 // two value numbers.
521 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
523 // If the IntB live range is assigned to a physical register, and if that
524 // physreg has sub-registers, update their live intervals as well.
525 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
526 for (const unsigned *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
527 if (!LIS->hasInterval(*SR))
529 LiveInterval &SRLI = LIS->getInterval(*SR);
530 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
531 SRLI.getNextValue(FillerStart, 0,
532 LIS->getVNInfoAllocator())));
536 // Okay, merge "B1" into the same value number as "B0".
537 if (BValNo != ValLR->valno) {
538 // If B1 is killed by a PHI, then the merged live range must also be killed
539 // by the same PHI, as B0 and B1 can not overlap.
540 bool HasPHIKill = BValNo->hasPHIKill();
541 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
543 ValLR->valno->setHasPHIKill(true);
546 dbgs() << " result = ";
547 IntB.print(dbgs(), TRI);
551 // If the source instruction was killing the source register before the
552 // merge, unset the isKill marker given the live range has been extended.
553 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
555 ValLREndInst->getOperand(UIdx).setIsKill(false);
558 // If the copy instruction was killing the destination register before the
559 // merge, find the last use and trim the live range. That will also add the
561 if (ALR->end == CopyIdx)
562 LIS->shrinkToUses(&IntA);
568 /// HasOtherReachingDefs - Return true if there are definitions of IntB
569 /// other than BValNo val# that can reach uses of AValno val# of IntA.
570 bool RegisterCoalescer::HasOtherReachingDefs(LiveInterval &IntA,
574 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
576 if (AI->valno != AValNo) continue;
577 LiveInterval::Ranges::iterator BI =
578 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
579 if (BI != IntB.ranges.begin())
581 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
582 if (BI->valno == BValNo)
584 if (BI->start <= AI->start && BI->end > AI->start)
586 if (BI->start > AI->start && BI->start < AI->end)
593 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
594 /// IntA being the source and IntB being the dest, thus this defines a value
595 /// number in IntB. If the source value number (in IntA) is defined by a
596 /// commutable instruction and its other operand is coalesced to the copy dest
597 /// register, see if we can transform the copy into a noop by commuting the
598 /// definition. For example,
600 /// A3 = op A2 B0<kill>
602 /// B1 = A3 <- this copy
604 /// = op A3 <- more uses
608 /// B2 = op B0 A2<kill>
610 /// B1 = B2 <- now an identify copy
612 /// = op B2 <- more uses
614 /// This returns true if an interval was modified.
616 bool RegisterCoalescer::RemoveCopyByCommutingDef(const CoalescerPair &CP,
617 MachineInstr *CopyMI) {
618 // FIXME: For now, only eliminate the copy by commuting its def when the
619 // source register is a virtual register. We want to guard against cases
620 // where the copy is a back edge copy and commuting the def lengthen the
621 // live interval of the source register to the entire loop.
622 if (CP.isPhys() && CP.isFlipped())
625 // Bail if there is no dst interval.
626 if (!LIS->hasInterval(CP.getDstReg()))
629 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getDefIndex();
632 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
634 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
636 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
637 // the example above.
638 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
639 if (!BValNo || !BValNo->isDefByCopy())
642 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
644 // AValNo is the value number in A that defines the copy, A3 in the example.
645 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
646 assert(AValNo && "COPY source not live");
648 // If other defs can reach uses of this def, then it's not safe to perform
650 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
652 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
655 const MCInstrDesc &MCID = DefMI->getDesc();
656 if (!MCID.isCommutable())
658 // If DefMI is a two-address instruction then commuting it will change the
659 // destination register.
660 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
661 assert(DefIdx != -1);
663 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
665 unsigned Op1, Op2, NewDstIdx;
666 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
670 else if (Op2 == UseOpIdx)
675 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
676 unsigned NewReg = NewDstMO.getReg();
677 if (NewReg != IntB.reg || !NewDstMO.isKill())
680 // Make sure there are no other definitions of IntB that would reach the
681 // uses which the new definition can reach.
682 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
685 // Abort if the aliases of IntB.reg have values that are not simply the
686 // clobbers from the superreg.
687 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
688 for (const unsigned *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
689 if (LIS->hasInterval(*AS) &&
690 HasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
693 // If some of the uses of IntA.reg is already coalesced away, return false.
694 // It's not possible to determine whether it's safe to perform the coalescing.
695 for (MachineRegisterInfo::use_nodbg_iterator UI =
696 MRI->use_nodbg_begin(IntA.reg),
697 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
698 MachineInstr *UseMI = &*UI;
699 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
700 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
701 if (ULR == IntA.end())
703 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
707 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
710 // At this point we have decided that it is legal to do this
711 // transformation. Start by commuting the instruction.
712 MachineBasicBlock *MBB = DefMI->getParent();
713 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
716 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
717 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
718 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
720 if (NewMI != DefMI) {
721 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
722 MBB->insert(DefMI, NewMI);
725 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
726 NewMI->getOperand(OpIdx).setIsKill();
728 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
737 // Update uses of IntA of the specific Val# with IntB.
738 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
739 UE = MRI->use_end(); UI != UE;) {
740 MachineOperand &UseMO = UI.getOperand();
741 MachineInstr *UseMI = &*UI;
743 if (JoinedCopies.count(UseMI))
745 if (UseMI->isDebugValue()) {
746 // FIXME These don't have an instruction index. Not clear we have enough
747 // info to decide whether to do this replacement or not. For now do it.
748 UseMO.setReg(NewReg);
751 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getUseIndex();
752 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
753 if (ULR == IntA.end() || ULR->valno != AValNo)
755 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
756 UseMO.substPhysReg(NewReg, *TRI);
758 UseMO.setReg(NewReg);
761 if (!UseMI->isCopy())
763 if (UseMI->getOperand(0).getReg() != IntB.reg ||
764 UseMI->getOperand(0).getSubReg())
767 // This copy will become a noop. If it's defining a new val#, merge it into
769 SlotIndex DefIdx = UseIdx.getDefIndex();
770 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
773 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
774 assert(DVNI->def == DefIdx);
775 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
779 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
781 VNInfo *ValNo = BValNo;
782 ValNo->def = AValNo->def;
784 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
786 if (AI->valno != AValNo) continue;
787 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
789 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
791 IntA.removeValNo(AValNo);
792 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
797 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
798 /// computation, replace the copy by rematerialize the definition.
799 bool RegisterCoalescer::ReMaterializeTrivialDef(LiveInterval &SrcInt,
803 MachineInstr *CopyMI) {
804 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getUseIndex();
805 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
806 assert(SrcLR != SrcInt.end() && "Live range not found!");
807 VNInfo *ValNo = SrcLR->valno;
808 // If other defs can reach uses of this def, then it's not safe to perform
810 if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
812 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
815 assert(DefMI && "Defining instruction disappeared");
816 const MCInstrDesc &MCID = DefMI->getDesc();
817 if (!MCID.isAsCheapAsAMove())
819 if (!TII->isTriviallyReMaterializable(DefMI, AA))
821 bool SawStore = false;
822 if (!DefMI->isSafeToMove(TII, AA, SawStore))
824 if (MCID.getNumDefs() != 1)
826 if (!DefMI->isImplicitDef()) {
827 // Make sure the copy destination register class fits the instruction
828 // definition register class. The mismatch can happen as a result of earlier
829 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
830 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI);
831 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
832 if (MRI->getRegClass(DstReg) != RC)
834 } else if (!RC->contains(DstReg))
838 // If destination register has a sub-register index on it, make sure it
839 // matches the instruction register class.
841 const MCInstrDesc &MCID = DefMI->getDesc();
842 if (MCID.getNumDefs() != 1)
844 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
845 const TargetRegisterClass *DstSubRC =
846 DstRC->getSubRegisterRegClass(DstSubIdx);
847 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI);
850 else if (DefRC != DstSubRC)
854 RemoveCopyFlag(DstReg, CopyMI);
856 MachineBasicBlock *MBB = CopyMI->getParent();
857 MachineBasicBlock::iterator MII =
858 llvm::next(MachineBasicBlock::iterator(CopyMI));
859 TII->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *TRI);
860 MachineInstr *NewMI = prior(MII);
862 // CopyMI may have implicit operands, transfer them over to the newly
863 // rematerialized instruction. And update implicit def interval valnos.
864 for (unsigned i = CopyMI->getDesc().getNumOperands(),
865 e = CopyMI->getNumOperands(); i != e; ++i) {
866 MachineOperand &MO = CopyMI->getOperand(i);
867 if (MO.isReg() && MO.isImplicit())
868 NewMI->addOperand(MO);
870 RemoveCopyFlag(MO.getReg(), CopyMI);
873 NewMI->copyImplicitOps(CopyMI);
874 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
875 CopyMI->eraseFromParent();
876 ReMatCopies.insert(CopyMI);
877 ReMatDefs.insert(DefMI);
878 DEBUG(dbgs() << "Remat: " << *NewMI);
881 // The source interval can become smaller because we removed a use.
883 LIS->shrinkToUses(&SrcInt);
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.getDefIndex());
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
937 RegisterCoalescer::UpdateRegDefsUses(const CoalescerPair &CP) {
938 bool DstIsPhys = CP.isPhys();
939 unsigned SrcReg = CP.getSrcReg();
940 unsigned DstReg = CP.getDstReg();
941 unsigned SubIdx = CP.getSubIdx();
943 // Update LiveDebugVariables.
944 LDV->renameRegister(SrcReg, DstReg, SubIdx);
946 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
947 MachineInstr *UseMI = I.skipInstruction();) {
948 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
951 if (UseMI->isCopy() &&
952 !UseMI->getOperand(1).getSubReg() &&
953 !UseMI->getOperand(0).getSubReg() &&
954 UseMI->getOperand(1).getReg() == SrcReg &&
955 UseMI->getOperand(0).getReg() != SrcReg &&
956 UseMI->getOperand(0).getReg() != DstReg &&
957 !JoinedCopies.count(UseMI) &&
958 ReMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
959 UseMI->getOperand(0).getReg(), 0, UseMI))
963 SmallVector<unsigned,8> Ops;
965 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
966 bool Kills = false, Deads = false;
968 // Replace SrcReg with DstReg in all UseMI operands.
969 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
970 MachineOperand &MO = UseMI->getOperand(Ops[i]);
971 Kills |= MO.isKill();
972 Deads |= MO.isDead();
975 MO.substPhysReg(DstReg, *TRI);
977 MO.substVirtReg(DstReg, SubIdx, *TRI);
980 // This instruction is a copy that will be removed.
981 if (JoinedCopies.count(UseMI))
985 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
986 // read-modify-write of DstReg.
988 UseMI->addRegisterDead(DstReg, TRI);
989 else if (!Reads && Writes)
990 UseMI->addRegisterDefined(DstReg, TRI);
992 // Kill flags apply to the whole physical register.
993 if (DstIsPhys && Kills)
994 UseMI->addRegisterKilled(DstReg, TRI);
998 dbgs() << "\t\tupdated: ";
999 if (!UseMI->isDebugValue())
1000 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
1006 /// removeIntervalIfEmpty - Check if the live interval of a physical register
1007 /// is empty, if so remove it and also remove the empty intervals of its
1008 /// sub-registers. Return true if live interval is removed.
1009 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
1010 const TargetRegisterInfo *TRI) {
1012 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
1013 for (const unsigned* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
1014 if (!LIS->hasInterval(*SR))
1016 LiveInterval &sli = LIS->getInterval(*SR);
1018 LIS->removeInterval(*SR);
1020 LIS->removeInterval(li.reg);
1026 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
1027 /// the val# it defines. If the live interval becomes empty, remove it as well.
1028 bool RegisterCoalescer::RemoveDeadDef(LiveInterval &li,
1029 MachineInstr *DefMI) {
1030 SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getDefIndex();
1031 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
1032 if (DefIdx != MLR->valno->def)
1034 li.removeValNo(MLR->valno);
1035 return removeIntervalIfEmpty(li, LIS, TRI);
1038 void RegisterCoalescer::RemoveCopyFlag(unsigned DstReg,
1039 const MachineInstr *CopyMI) {
1040 SlotIndex DefIdx = LIS->getInstructionIndex(CopyMI).getDefIndex();
1041 if (LIS->hasInterval(DstReg)) {
1042 LiveInterval &LI = LIS->getInterval(DstReg);
1043 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
1044 if (LR->valno->def == DefIdx)
1045 LR->valno->setCopy(0);
1047 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
1049 for (const unsigned* AS = TRI->getAliasSet(DstReg); *AS; ++AS) {
1050 if (!LIS->hasInterval(*AS))
1052 LiveInterval &LI = LIS->getInterval(*AS);
1053 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
1054 if (LR->valno->def == DefIdx)
1055 LR->valno->setCopy(0);
1059 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
1060 /// We need to be careful about coalescing a source physical register with a
1061 /// virtual register. Once the coalescing is done, it cannot be broken and these
1062 /// are not spillable! If the destination interval uses are far away, think
1063 /// twice about coalescing them!
1064 bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) {
1065 bool Allocatable = LIS->isAllocatable(CP.getDstReg());
1066 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1068 /// Always join simple intervals that are defined by a single copy from a
1069 /// reserved register. This doesn't increase register pressure, so it is
1070 /// always beneficial.
1071 if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
1074 if (!EnablePhysicalJoin) {
1075 DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
1079 // Only coalesce to allocatable physreg, we don't want to risk modifying
1080 // reserved registers.
1082 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1083 return false; // Not coalescable.
1086 // Don't join with physregs that have a ridiculous number of live
1087 // ranges. The data structure performance is really bad when that
1089 if (LIS->hasInterval(CP.getDstReg()) &&
1090 LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1093 << "\tPhysical register live interval too complicated, abort!\n");
1097 // FIXME: Why are we skipping this test for partial copies?
1098 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1099 if (!CP.isPartial()) {
1100 const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg());
1101 unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
1102 unsigned Length = LIS->getApproximateInstructionCount(JoinVInt);
1103 if (Length > Threshold) {
1105 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1112 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1113 /// two virtual registers from different register classes.
1115 RegisterCoalescer::isWinToJoinCrossClass(unsigned SrcReg,
1117 const TargetRegisterClass *SrcRC,
1118 const TargetRegisterClass *DstRC,
1119 const TargetRegisterClass *NewRC) {
1120 unsigned NewRCCount = RegClassInfo.getNumAllocatableRegs(NewRC);
1121 // This heuristics is good enough in practice, but it's obviously not *right*.
1122 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
1123 // out all but the most restrictive register classes.
1124 if (NewRCCount > 4 ||
1125 // Early exit if the function is fairly small, coalesce aggressively if
1126 // that's the case. For really special register classes with 3 or
1127 // fewer registers, be a bit more careful.
1128 (LIS->getFuncInstructionCount() / NewRCCount) < 8)
1130 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1131 LiveInterval &DstInt = LIS->getInterval(DstReg);
1132 unsigned SrcSize = LIS->getApproximateInstructionCount(SrcInt);
1133 unsigned DstSize = LIS->getApproximateInstructionCount(DstInt);
1135 // Coalesce aggressively if the intervals are small compared to the number of
1136 // registers in the new class. The number 4 is fairly arbitrary, chosen to be
1137 // less aggressive than the 8 used for the whole function size.
1138 const unsigned ThresSize = 4 * NewRCCount;
1139 if (SrcSize <= ThresSize && DstSize <= ThresSize)
1142 // Estimate *register use density*. If it doubles or more, abort.
1143 unsigned SrcUses = std::distance(MRI->use_nodbg_begin(SrcReg),
1144 MRI->use_nodbg_end());
1145 unsigned DstUses = std::distance(MRI->use_nodbg_begin(DstReg),
1146 MRI->use_nodbg_end());
1147 unsigned NewUses = SrcUses + DstUses;
1148 unsigned NewSize = SrcSize + DstSize;
1149 if (SrcRC != NewRC && SrcSize > ThresSize) {
1150 unsigned SrcRCCount = RegClassInfo.getNumAllocatableRegs(SrcRC);
1151 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1154 if (DstRC != NewRC && DstSize > ThresSize) {
1155 unsigned DstRCCount = RegClassInfo.getNumAllocatableRegs(DstRC);
1156 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1163 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1164 /// which are the src/dst of the copy instruction CopyMI. This returns true
1165 /// if the copy was successfully coalesced away. If it is not currently
1166 /// possible to coalesce this interval, but it may be possible if other
1167 /// things get coalesced, then it returns true by reference in 'Again'.
1168 bool RegisterCoalescer::JoinCopy(MachineInstr *CopyMI, bool &Again) {
1171 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1172 return false; // Already done.
1174 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1176 CoalescerPair CP(*TII, *TRI);
1177 if (!CP.setRegisters(CopyMI)) {
1178 DEBUG(dbgs() << "\tNot coalescable.\n");
1182 // If they are already joined we continue.
1183 if (CP.getSrcReg() == CP.getDstReg()) {
1184 markAsJoined(CopyMI);
1185 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1186 return false; // Not coalescable.
1189 // Eliminate undefs.
1190 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1191 markAsJoined(CopyMI);
1192 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1193 return false; // Not coalescable.
1196 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1197 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx())
1200 // Enforce policies.
1202 if (!shouldJoinPhys(CP)) {
1203 // Before giving up coalescing, if definition of source is defined by
1204 // trivial computation, try rematerializing it.
1205 if (!CP.isFlipped() &&
1206 ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1207 CP.getDstReg(), 0, CopyMI))
1212 // Avoid constraining virtual register regclass too much.
1213 if (CP.isCrossClass()) {
1214 DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1215 if (DisableCrossClassJoin) {
1216 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1219 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1220 MRI->getRegClass(CP.getSrcReg()),
1221 MRI->getRegClass(CP.getDstReg()),
1223 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
1224 Again = true; // May be possible to coalesce later.
1229 // When possible, let DstReg be the larger interval.
1230 if (!CP.getSubIdx() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1231 LIS->getInterval(CP.getDstReg()).ranges.size())
1235 // Okay, attempt to join these two intervals. On failure, this returns false.
1236 // Otherwise, if one of the intervals being joined is a physreg, this method
1237 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1238 // been modified, so we can use this information below to update aliases.
1239 if (!JoinIntervals(CP)) {
1240 // Coalescing failed.
1242 // If definition of source is defined by trivial computation, try
1243 // rematerializing it.
1244 if (!CP.isFlipped() &&
1245 ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1246 CP.getDstReg(), 0, CopyMI))
1249 // If we can eliminate the copy without merging the live ranges, do so now.
1250 if (!CP.isPartial()) {
1251 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1252 RemoveCopyByCommutingDef(CP, CopyMI)) {
1253 markAsJoined(CopyMI);
1254 DEBUG(dbgs() << "\tTrivial!\n");
1259 // Otherwise, we are unable to join the intervals.
1260 DEBUG(dbgs() << "\tInterference!\n");
1261 Again = true; // May be possible to coalesce later.
1265 // Coalescing to a virtual register that is of a sub-register class of the
1266 // other. Make sure the resulting register is set to the right register class.
1267 if (CP.isCrossClass()) {
1269 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1272 // Remember to delete the copy instruction.
1273 markAsJoined(CopyMI);
1275 UpdateRegDefsUses(CP);
1277 // If we have extended the live range of a physical register, make sure we
1278 // update live-in lists as well.
1280 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1281 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1282 // ranges for this, and they are preserved.
1283 LiveInterval &SrcInt = LIS->getInterval(CP.getSrcReg());
1284 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1286 LIS->findLiveInMBBs(I->start, I->end, BlockSeq);
1287 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1288 MachineBasicBlock &block = *BlockSeq[idx];
1289 if (!block.isLiveIn(CP.getDstReg()))
1290 block.addLiveIn(CP.getDstReg());
1296 // SrcReg is guarateed to be the register whose live interval that is
1298 LIS->removeInterval(CP.getSrcReg());
1300 // Update regalloc hint.
1301 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1304 LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1305 dbgs() << "\tJoined. Result = ";
1306 DstInt.print(dbgs(), TRI);
1314 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1315 /// compute what the resultant value numbers for each value in the input two
1316 /// ranges will be. This is complicated by copies between the two which can
1317 /// and will commonly cause multiple value numbers to be merged into one.
1319 /// VN is the value number that we're trying to resolve. InstDefiningValue
1320 /// keeps track of the new InstDefiningValue assignment for the result
1321 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1322 /// whether a value in this or other is a copy from the opposite set.
1323 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1324 /// already been assigned.
1326 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1327 /// contains the value number the copy is from.
1329 static unsigned ComputeUltimateVN(VNInfo *VNI,
1330 SmallVector<VNInfo*, 16> &NewVNInfo,
1331 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1332 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1333 SmallVector<int, 16> &ThisValNoAssignments,
1334 SmallVector<int, 16> &OtherValNoAssignments) {
1335 unsigned VN = VNI->id;
1337 // If the VN has already been computed, just return it.
1338 if (ThisValNoAssignments[VN] >= 0)
1339 return ThisValNoAssignments[VN];
1340 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1342 // If this val is not a copy from the other val, then it must be a new value
1343 // number in the destination.
1344 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1345 if (I == ThisFromOther.end()) {
1346 NewVNInfo.push_back(VNI);
1347 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1349 VNInfo *OtherValNo = I->second;
1351 // Otherwise, this *is* a copy from the RHS. If the other side has already
1352 // been computed, return it.
1353 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1354 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1356 // Mark this value number as currently being computed, then ask what the
1357 // ultimate value # of the other value is.
1358 ThisValNoAssignments[VN] = -2;
1359 unsigned UltimateVN =
1360 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1361 OtherValNoAssignments, ThisValNoAssignments);
1362 return ThisValNoAssignments[VN] = UltimateVN;
1366 // Find out if we have something like
1369 // if so, we can pretend this is actually
1372 // which allows us to coalesce A and B.
1373 // VNI is the definition of B. LR is the life range of A that includes
1374 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1375 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1376 const TargetRegisterInfo &tri,
1380 SmallVector<MachineInstr*, 8> &DupCopies) {
1381 // FIXME: This is very conservative. For example, we don't handle
1382 // physical registers.
1384 MachineInstr *MI = VNI->getCopy();
1386 if (!MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1389 unsigned Dst = MI->getOperand(0).getReg();
1390 unsigned Src = MI->getOperand(1).getReg();
1392 if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1393 !TargetRegisterInfo::isVirtualRegister(Dst))
1396 unsigned A = CP.getDstReg();
1397 unsigned B = CP.getSrcReg();
1403 VNInfo *Other = LR->valno;
1404 if (!Other->isDefByCopy())
1406 const MachineInstr *OtherMI = Other->getCopy();
1408 if (!OtherMI->isFullCopy())
1411 unsigned OtherDst = OtherMI->getOperand(0).getReg();
1412 unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1414 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1415 !TargetRegisterInfo::isVirtualRegister(OtherDst))
1418 assert(OtherDst == B);
1420 if (Src != OtherSrc)
1423 // If the copies use two different value numbers of X, we cannot merge
1425 LiveInterval &SrcInt = li.getInterval(Src);
1426 if (SrcInt.getVNInfoAt(Other->def) != SrcInt.getVNInfoAt(VNI->def))
1429 DupCopies.push_back(MI);
1434 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1436 bool RegisterCoalescer::JoinIntervals(CoalescerPair &CP) {
1437 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1438 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1440 // If a live interval is a physical register, check for interference with any
1441 // aliases. The interference check implemented here is a bit more conservative
1442 // than the full interfeence check below. We allow overlapping live ranges
1443 // only when one is a copy of the other.
1445 for (const unsigned *AS = TRI->getAliasSet(CP.getDstReg()); *AS; ++AS){
1446 if (!LIS->hasInterval(*AS))
1448 const LiveInterval &LHS = LIS->getInterval(*AS);
1449 LiveInterval::const_iterator LI = LHS.begin();
1450 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1452 LI = std::lower_bound(LI, LHS.end(), RI->start);
1453 // Does LHS have an overlapping live range starting before RI?
1454 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1455 (RI->start != RI->valno->def ||
1456 !CP.isCoalescable(LIS->getInstructionFromIndex(RI->start)))) {
1458 dbgs() << "\t\tInterference from alias: ";
1459 LHS.print(dbgs(), TRI);
1460 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1465 // Check that LHS ranges beginning in this range are copies.
1466 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1467 if (LI->start != LI->valno->def ||
1468 !CP.isCoalescable(LIS->getInstructionFromIndex(LI->start))) {
1470 dbgs() << "\t\tInterference from alias: ";
1471 LHS.print(dbgs(), TRI);
1472 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1481 // Compute the final value assignment, assuming that the live ranges can be
1483 SmallVector<int, 16> LHSValNoAssignments;
1484 SmallVector<int, 16> RHSValNoAssignments;
1485 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1486 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1487 SmallVector<VNInfo*, 16> NewVNInfo;
1489 SmallVector<MachineInstr*, 8> DupCopies;
1491 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1492 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1494 // Loop over the value numbers of the LHS, seeing if any are defined from
1496 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1499 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1502 // Never join with a register that has EarlyClobber redefs.
1503 if (VNI->hasRedefByEC())
1506 // Figure out the value # from the RHS.
1507 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1508 // The copy could be to an aliased physreg.
1511 // DstReg is known to be a register in the LHS interval. If the src is
1512 // from the RHS interval, we can use its value #.
1513 MachineInstr *MI = VNI->getCopy();
1514 if (!CP.isCoalescable(MI) &&
1515 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1518 LHSValsDefinedFromRHS[VNI] = lr->valno;
1521 // Loop over the value numbers of the RHS, seeing if any are defined from
1523 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1526 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1529 // Never join with a register that has EarlyClobber redefs.
1530 if (VNI->hasRedefByEC())
1533 // Figure out the value # from the LHS.
1534 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1535 // The copy could be to an aliased physreg.
1538 // DstReg is known to be a register in the RHS interval. If the src is
1539 // from the LHS interval, we can use its value #.
1540 MachineInstr *MI = VNI->getCopy();
1541 if (!CP.isCoalescable(MI) &&
1542 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1545 RHSValsDefinedFromLHS[VNI] = lr->valno;
1548 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1549 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1550 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1552 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1555 unsigned VN = VNI->id;
1556 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1558 ComputeUltimateVN(VNI, NewVNInfo,
1559 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1560 LHSValNoAssignments, RHSValNoAssignments);
1562 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1565 unsigned VN = VNI->id;
1566 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1568 // If this value number isn't a copy from the LHS, it's a new number.
1569 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1570 NewVNInfo.push_back(VNI);
1571 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1575 ComputeUltimateVN(VNI, NewVNInfo,
1576 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1577 RHSValNoAssignments, LHSValNoAssignments);
1580 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1581 // interval lists to see if these intervals are coalescable.
1582 LiveInterval::const_iterator I = LHS.begin();
1583 LiveInterval::const_iterator IE = LHS.end();
1584 LiveInterval::const_iterator J = RHS.begin();
1585 LiveInterval::const_iterator JE = RHS.end();
1587 // Skip ahead until the first place of potential sharing.
1588 if (I != IE && J != JE) {
1589 if (I->start < J->start) {
1590 I = std::upper_bound(I, IE, J->start);
1591 if (I != LHS.begin()) --I;
1592 } else if (J->start < I->start) {
1593 J = std::upper_bound(J, JE, I->start);
1594 if (J != RHS.begin()) --J;
1598 while (I != IE && J != JE) {
1599 // Determine if these two live ranges overlap.
1601 if (I->start < J->start) {
1602 Overlaps = I->end > J->start;
1604 Overlaps = J->end > I->start;
1607 // If so, check value # info to determine if they are really different.
1609 // If the live range overlap will map to the same value number in the
1610 // result liverange, we can still coalesce them. If not, we can't.
1611 if (LHSValNoAssignments[I->valno->id] !=
1612 RHSValNoAssignments[J->valno->id])
1614 // If it's re-defined by an early clobber somewhere in the live range,
1615 // then conservatively abort coalescing.
1616 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1620 if (I->end < J->end)
1626 // Update kill info. Some live ranges are extended due to copy coalescing.
1627 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1628 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1629 VNInfo *VNI = I->first;
1630 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1631 if (VNI->hasPHIKill())
1632 NewVNInfo[LHSValID]->setHasPHIKill(true);
1635 // Update kill info. Some live ranges are extended due to copy coalescing.
1636 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1637 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1638 VNInfo *VNI = I->first;
1639 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1640 if (VNI->hasPHIKill())
1641 NewVNInfo[RHSValID]->setHasPHIKill(true);
1644 if (LHSValNoAssignments.empty())
1645 LHSValNoAssignments.push_back(-1);
1646 if (RHSValNoAssignments.empty())
1647 RHSValNoAssignments.push_back(-1);
1649 SmallVector<unsigned, 8> SourceRegisters;
1650 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1651 E = DupCopies.end(); I != E; ++I) {
1652 MachineInstr *MI = *I;
1654 // We have pretended that the assignment to B in
1657 // was actually a copy from A. Now that we decided to coalesce A and B,
1658 // transform the code into
1661 // and mark the X as coalesced to keep the illusion.
1662 unsigned Src = MI->getOperand(1).getReg();
1663 SourceRegisters.push_back(Src);
1664 MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1669 // If B = X was the last use of X in a liverange, we have to shrink it now
1670 // that B = X is gone.
1671 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1672 E = SourceRegisters.end(); I != E; ++I) {
1673 LIS->shrinkToUses(&LIS->getInterval(*I));
1676 // If we get here, we know that we can coalesce the live ranges. Ask the
1677 // intervals to coalesce themselves now.
1678 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1684 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1685 // depth of the basic block (the unsigned), and then on the MBB number.
1686 struct DepthMBBCompare {
1687 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1688 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1689 // Deeper loops first
1690 if (LHS.first != RHS.first)
1691 return LHS.first > RHS.first;
1693 // Prefer blocks that are more connected in the CFG. This takes care of
1694 // the most difficult copies first while intervals are short.
1695 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1696 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1700 // As a last resort, sort by block number.
1701 return LHS.second->getNumber() < RHS.second->getNumber();
1706 void RegisterCoalescer::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1707 std::vector<MachineInstr*> &TryAgain) {
1708 DEBUG(dbgs() << MBB->getName() << ":\n");
1710 SmallVector<MachineInstr*, 8> VirtCopies;
1711 SmallVector<MachineInstr*, 8> PhysCopies;
1712 SmallVector<MachineInstr*, 8> ImpDefCopies;
1713 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1715 MachineInstr *Inst = MII++;
1717 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1718 unsigned SrcReg, DstReg;
1719 if (Inst->isCopy()) {
1720 DstReg = Inst->getOperand(0).getReg();
1721 SrcReg = Inst->getOperand(1).getReg();
1722 } else if (Inst->isSubregToReg()) {
1723 DstReg = Inst->getOperand(0).getReg();
1724 SrcReg = Inst->getOperand(2).getReg();
1728 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1729 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1730 if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty())
1731 ImpDefCopies.push_back(Inst);
1732 else if (SrcIsPhys || DstIsPhys)
1733 PhysCopies.push_back(Inst);
1735 VirtCopies.push_back(Inst);
1738 // Try coalescing implicit copies and insert_subreg <undef> first,
1739 // followed by copies to / from physical registers, then finally copies
1740 // from virtual registers to virtual registers.
1741 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1742 MachineInstr *TheCopy = ImpDefCopies[i];
1744 if (!JoinCopy(TheCopy, Again))
1746 TryAgain.push_back(TheCopy);
1748 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1749 MachineInstr *TheCopy = PhysCopies[i];
1751 if (!JoinCopy(TheCopy, Again))
1753 TryAgain.push_back(TheCopy);
1755 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1756 MachineInstr *TheCopy = VirtCopies[i];
1758 if (!JoinCopy(TheCopy, Again))
1760 TryAgain.push_back(TheCopy);
1764 void RegisterCoalescer::joinIntervals() {
1765 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1767 std::vector<MachineInstr*> TryAgainList;
1768 if (Loops->empty()) {
1769 // If there are no loops in the function, join intervals in function order.
1770 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1772 CopyCoalesceInMBB(I, TryAgainList);
1774 // Otherwise, join intervals in inner loops before other intervals.
1775 // Unfortunately we can't just iterate over loop hierarchy here because
1776 // there may be more MBB's than BB's. Collect MBB's for sorting.
1778 // Join intervals in the function prolog first. We want to join physical
1779 // registers with virtual registers before the intervals got too long.
1780 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1781 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1782 MachineBasicBlock *MBB = I;
1783 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1786 // Sort by loop depth.
1787 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1789 // Finally, join intervals in loop nest order.
1790 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1791 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1794 // Joining intervals can allow other intervals to be joined. Iteratively join
1795 // until we make no progress.
1796 bool ProgressMade = true;
1797 while (ProgressMade) {
1798 ProgressMade = false;
1800 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1801 MachineInstr *&TheCopy = TryAgainList[i];
1806 bool Success = JoinCopy(TheCopy, Again);
1807 if (Success || !Again) {
1808 TheCopy= 0; // Mark this one as done.
1809 ProgressMade = true;
1815 void RegisterCoalescer::releaseMemory() {
1816 JoinedCopies.clear();
1817 ReMatCopies.clear();
1821 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1823 MRI = &fn.getRegInfo();
1824 TM = &fn.getTarget();
1825 TRI = TM->getRegisterInfo();
1826 TII = TM->getInstrInfo();
1827 LIS = &getAnalysis<LiveIntervals>();
1828 LDV = &getAnalysis<LiveDebugVariables>();
1829 AA = &getAnalysis<AliasAnalysis>();
1830 Loops = &getAnalysis<MachineLoopInfo>();
1832 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1833 << "********** Function: "
1834 << ((Value*)MF->getFunction())->getName() << '\n');
1836 if (VerifyCoalescing)
1837 MF->verify(this, "Before register coalescing");
1839 RegClassInfo.runOnMachineFunction(fn);
1841 // Join (coalesce) intervals if requested.
1842 if (EnableJoining) {
1845 dbgs() << "********** INTERVALS POST JOINING **********\n";
1846 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1848 I->second->print(dbgs(), TRI);
1854 // Perform a final pass over the instructions and compute spill weights
1855 // and remove identity moves.
1856 SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1857 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1858 mbbi != mbbe; ++mbbi) {
1859 MachineBasicBlock* mbb = mbbi;
1860 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1862 MachineInstr *MI = mii;
1863 if (JoinedCopies.count(MI)) {
1864 // Delete all coalesced copies.
1865 bool DoDelete = true;
1866 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1867 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1868 unsigned DstReg = MI->getOperand(0).getReg();
1870 // Collect candidates for register class inflation.
1871 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1872 RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1873 InflateRegs.push_back(SrcReg);
1874 if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1875 RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1876 InflateRegs.push_back(DstReg);
1878 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1879 MI->getNumOperands() > 2)
1880 // Do not delete extract_subreg, insert_subreg of physical
1881 // registers unless the definition is dead. e.g.
1882 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1883 // or else the scavenger may complain. LowerSubregs will
1884 // delete them later.
1887 if (MI->allDefsAreDead()) {
1888 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1889 LIS->hasInterval(SrcReg))
1890 LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1894 // We need the instruction to adjust liveness, so make it a KILL.
1895 if (MI->isSubregToReg()) {
1896 MI->RemoveOperand(3);
1897 MI->RemoveOperand(1);
1899 MI->setDesc(TII->get(TargetOpcode::KILL));
1900 mii = llvm::next(mii);
1902 LIS->RemoveMachineInstrFromMaps(MI);
1903 mii = mbbi->erase(mii);
1909 // Now check if this is a remat'ed def instruction which is now dead.
1910 if (ReMatDefs.count(MI)) {
1912 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1913 const MachineOperand &MO = MI->getOperand(i);
1916 unsigned Reg = MO.getReg();
1919 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1920 DeadDefs.push_back(Reg);
1921 // Remat may also enable register class inflation.
1922 if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1923 InflateRegs.push_back(Reg);
1927 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1928 !MRI->use_nodbg_empty(Reg)) {
1934 while (!DeadDefs.empty()) {
1935 unsigned DeadDef = DeadDefs.back();
1936 DeadDefs.pop_back();
1937 RemoveDeadDef(LIS->getInterval(DeadDef), MI);
1939 LIS->RemoveMachineInstrFromMaps(mii);
1940 mii = mbbi->erase(mii);
1948 // Check for now unnecessary kill flags.
1949 if (LIS->isNotInMIMap(MI)) continue;
1950 SlotIndex DefIdx = LIS->getInstructionIndex(MI).getDefIndex();
1951 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1952 MachineOperand &MO = MI->getOperand(i);
1953 if (!MO.isReg() || !MO.isKill()) continue;
1954 unsigned reg = MO.getReg();
1955 if (!reg || !LIS->hasInterval(reg)) continue;
1956 if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1957 MO.setIsKill(false);
1960 // When leaving a kill flag on a physreg, check if any subregs should
1962 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1964 for (const unsigned *SR = TRI->getSubRegisters(reg);
1965 unsigned S = *SR; ++SR)
1966 if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1967 MI->addRegisterDefined(S, TRI);
1972 // After deleting a lot of copies, register classes may be less constrained.
1973 // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1975 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1976 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1978 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1979 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1980 unsigned Reg = InflateRegs[i];
1981 if (MRI->reg_nodbg_empty(Reg))
1983 if (MRI->recomputeRegClass(Reg, *TM)) {
1984 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1985 << MRI->getRegClass(Reg)->getName() << '\n');
1992 if (VerifyCoalescing)
1993 MF->verify(this, "After register coalescing");
1997 /// print - Implement the dump method.
1998 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {