1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "LiveDebugVariables.h"
19 #include "RegisterClassInfo.h"
20 #include "VirtRegMap.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Value.h"
24 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/OwningPtr.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/STLExtras.h"
51 STATISTIC(numJoins , "Number of interval joins performed");
52 STATISTIC(numCrossRCs , "Number of cross class joins performed");
53 STATISTIC(numCommutes , "Number of instruction commuting performed");
54 STATISTIC(numExtends , "Number of copies extended");
55 STATISTIC(NumReMats , "Number of instructions re-materialized");
56 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
57 STATISTIC(NumInflated , "Number of register classes inflated");
60 EnableJoining("join-liveintervals",
61 cl::desc("Coalesce copies (default=true)"),
65 VerifyCoalescing("verify-coalescing",
66 cl::desc("Verify machine instrs before and after register coalescing"),
70 class RegisterCoalescer : public MachineFunctionPass {
72 MachineRegisterInfo* MRI;
73 const TargetMachine* TM;
74 const TargetRegisterInfo* TRI;
75 const TargetInstrInfo* TII;
77 LiveDebugVariables *LDV;
78 const MachineLoopInfo* Loops;
80 RegisterClassInfo RegClassInfo;
82 /// JoinedCopies - Keep track of copies eliminated due to coalescing.
84 SmallPtrSet<MachineInstr*, 32> JoinedCopies;
86 /// ReMatCopies - Keep track of copies eliminated due to remat.
88 SmallPtrSet<MachineInstr*, 32> ReMatCopies;
90 /// ReMatDefs - Keep track of definition instructions which have
92 SmallPtrSet<MachineInstr*, 8> ReMatDefs;
94 /// WorkList - Copy instructions yet to be coalesced.
95 SmallVector<MachineInstr*, 8> WorkList;
97 /// joinAllIntervals - join compatible live intervals
98 void joinAllIntervals();
100 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
101 /// copies that cannot yet be coalesced into WorkList.
102 void copyCoalesceInMBB(MachineBasicBlock *MBB);
104 /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
105 /// position From. Return true if any progress was made.
106 bool copyCoalesceWorkList(unsigned From = 0);
108 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
109 /// which are the src/dst of the copy instruction CopyMI. This returns
110 /// true if the copy was successfully coalesced away. If it is not
111 /// currently possible to coalesce this interval, but it may be possible if
112 /// other things get coalesced, then it returns true by reference in
114 bool joinCopy(MachineInstr *TheCopy, bool &Again);
116 /// joinIntervals - Attempt to join these two intervals. On failure, this
117 /// returns false. The output "SrcInt" will not have been modified, so we
118 /// can use this information below to update aliases.
119 bool joinIntervals(CoalescerPair &CP);
121 /// Attempt joining with a reserved physreg.
122 bool joinReservedPhysReg(CoalescerPair &CP);
124 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
125 /// the source value number is defined by a copy from the destination reg
126 /// see if we can merge these two destination reg valno# into a single
127 /// value number, eliminating a copy.
128 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
130 /// hasOtherReachingDefs - Return true if there are definitions of IntB
131 /// other than BValNo val# that can reach uses of AValno val# of IntA.
132 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
133 VNInfo *AValNo, VNInfo *BValNo);
135 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
136 /// If the source value number is defined by a commutable instruction and
137 /// its other operand is coalesced to the copy dest register, see if we
138 /// can transform the copy into a noop by commuting the definition.
139 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
141 /// reMaterializeTrivialDef - If the source of a copy is defined by a
142 /// trivial computation, replace the copy by rematerialize the definition.
143 /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
144 bool reMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
145 unsigned DstReg, MachineInstr *CopyMI);
147 /// canJoinPhys - Return true if a physreg copy should be joined.
148 bool canJoinPhys(CoalescerPair &CP);
150 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
151 /// update the subregister number if it is not zero. If DstReg is a
152 /// physical register and the existing subregister number of the def / use
153 /// being updated is not zero, make sure to set it to the correct physical
155 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
157 /// removeDeadDef - If a def of a live interval is now determined dead,
158 /// remove the val# it defines. If the live interval becomes empty, remove
160 bool removeDeadDef(LiveInterval &li, MachineInstr *DefMI);
162 /// markAsJoined - Remember that CopyMI has already been joined.
163 void markAsJoined(MachineInstr *CopyMI);
165 /// eliminateUndefCopy - Handle copies of undef values.
166 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
169 static char ID; // Class identification, replacement for typeinfo
170 RegisterCoalescer() : MachineFunctionPass(ID) {
171 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
174 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
176 virtual void releaseMemory();
178 /// runOnMachineFunction - pass entry point
179 virtual bool runOnMachineFunction(MachineFunction&);
181 /// print - Implement the dump method.
182 virtual void print(raw_ostream &O, const Module* = 0) const;
184 } /// end anonymous namespace
186 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
188 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
189 "Simple Register Coalescing", false, false)
190 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
191 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
192 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
193 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
194 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
195 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
196 "Simple Register Coalescing", false, false)
198 char RegisterCoalescer::ID = 0;
200 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
203 return tri.composeSubRegIndices(a, b);
206 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
207 unsigned &Src, unsigned &Dst,
208 unsigned &SrcSub, unsigned &DstSub) {
210 Dst = MI->getOperand(0).getReg();
211 DstSub = MI->getOperand(0).getSubReg();
212 Src = MI->getOperand(1).getReg();
213 SrcSub = MI->getOperand(1).getSubReg();
214 } else if (MI->isSubregToReg()) {
215 Dst = MI->getOperand(0).getReg();
216 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
217 MI->getOperand(3).getImm());
218 Src = MI->getOperand(2).getReg();
219 SrcSub = MI->getOperand(2).getSubReg();
225 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
229 Flipped = CrossClass = false;
231 unsigned Src, Dst, SrcSub, DstSub;
232 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
234 Partial = SrcSub || DstSub;
236 // If one register is a physreg, it must be Dst.
237 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
238 if (TargetRegisterInfo::isPhysicalRegister(Dst))
241 std::swap(SrcSub, DstSub);
245 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
247 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
248 // Eliminate DstSub on a physreg.
250 Dst = TRI.getSubReg(Dst, DstSub);
251 if (!Dst) return false;
255 // Eliminate SrcSub by picking a corresponding Dst superregister.
257 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
258 if (!Dst) return false;
260 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
264 // Both registers are virtual.
265 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
266 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
268 // Both registers have subreg indices.
269 if (SrcSub && DstSub) {
270 // Copies between different sub-registers are never coalescable.
271 if (Src == Dst && SrcSub != DstSub)
274 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
279 // SrcReg will be merged with a sub-register of DstReg.
281 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
283 // DstReg will be merged with a sub-register of SrcReg.
285 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
287 // This is a straight copy without sub-registers.
288 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
291 // The combined constraint may be impossible to satisfy.
295 // Prefer SrcReg to be a sub-register of DstReg.
296 // FIXME: Coalescer should support subregs symmetrically.
297 if (DstIdx && !SrcIdx) {
299 std::swap(SrcIdx, DstIdx);
303 CrossClass = NewRC != DstRC || NewRC != SrcRC;
305 // Check our invariants
306 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
307 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
308 "Cannot have a physical SubIdx");
314 bool CoalescerPair::flip() {
315 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
317 std::swap(SrcReg, DstReg);
318 std::swap(SrcIdx, DstIdx);
323 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
326 unsigned Src, Dst, SrcSub, DstSub;
327 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
330 // Find the virtual register that is SrcReg.
333 std::swap(SrcSub, DstSub);
334 } else if (Src != SrcReg) {
338 // Now check that Dst matches DstReg.
339 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
340 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
342 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
343 // DstSub could be set for a physreg from INSERT_SUBREG.
345 Dst = TRI.getSubReg(Dst, DstSub);
348 return DstReg == Dst;
349 // This is a partial register copy. Check that the parts match.
350 return TRI.getSubReg(DstReg, SrcSub) == Dst;
352 // DstReg is virtual.
355 // Registers match, do the subregisters line up?
356 return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
360 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
361 AU.setPreservesCFG();
362 AU.addRequired<AliasAnalysis>();
363 AU.addRequired<LiveIntervals>();
364 AU.addPreserved<LiveIntervals>();
365 AU.addRequired<LiveDebugVariables>();
366 AU.addPreserved<LiveDebugVariables>();
367 AU.addPreserved<SlotIndexes>();
368 AU.addRequired<MachineLoopInfo>();
369 AU.addPreserved<MachineLoopInfo>();
370 AU.addPreservedID(MachineDominatorsID);
371 MachineFunctionPass::getAnalysisUsage(AU);
374 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
375 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
376 JoinedCopies.insert(CopyMI);
378 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
379 /// code elimination.
380 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
381 E = CopyMI->operands_end(); I != E; ++I)
386 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
387 /// being the source and IntB being the dest, thus this defines a value number
388 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
389 /// see if we can merge these two pieces of B into a single value number,
390 /// eliminating a copy. For example:
394 /// B1 = A3 <- this copy
396 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
397 /// value number to be replaced with B0 (which simplifies the B liveinterval).
399 /// This returns true if an interval was modified.
401 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
402 MachineInstr *CopyMI) {
403 assert(!CP.isPartial() && "This doesn't work for partial copies.");
405 // Bail if there is no dst interval - can happen when merging physical subreg
407 if (!LIS->hasInterval(CP.getDstReg()))
411 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
413 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
414 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
416 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
417 // the example above.
418 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
419 if (BLR == IntB.end()) return false;
420 VNInfo *BValNo = BLR->valno;
422 // Get the location that B is defined at. Two options: either this value has
423 // an unknown definition point or it is defined at CopyIdx. If unknown, we
425 if (BValNo->def != CopyIdx) return false;
427 // AValNo is the value number in A that defines the copy, A3 in the example.
428 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
429 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
430 // The live range might not exist after fun with physreg coalescing.
431 if (ALR == IntA.end()) return false;
432 VNInfo *AValNo = ALR->valno;
434 // If AValNo is defined as a copy from IntB, we can potentially process this.
435 // Get the instruction that defines this value number.
436 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
437 if (!CP.isCoalescable(ACopyMI))
440 // Get the LiveRange in IntB that this value number starts with.
441 LiveInterval::iterator ValLR =
442 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
443 if (ValLR == IntB.end())
446 // Make sure that the end of the live range is inside the same block as
448 MachineInstr *ValLREndInst =
449 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
450 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
453 // Okay, we now know that ValLR ends in the same block that the CopyMI
454 // live-range starts. If there are no intervening live ranges between them in
455 // IntB, we can merge them.
456 if (ValLR+1 != BLR) return false;
458 // If a live interval is a physical register, conservatively check if any
459 // of its aliases is overlapping the live interval of the virtual register.
460 // If so, do not coalesce.
461 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
462 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
463 if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
465 dbgs() << "\t\tInterfere with alias ";
466 LIS->getInterval(*AS).print(dbgs(), TRI);
473 dbgs() << "Extending: ";
474 IntB.print(dbgs(), TRI);
477 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
478 // We are about to delete CopyMI, so need to remove it as the 'instruction
479 // that defines this value #'. Update the valnum with the new defining
481 BValNo->def = FillerStart;
483 // Okay, we can merge them. We need to insert a new liverange:
484 // [ValLR.end, BLR.begin) of either value number, then we merge the
485 // two value numbers.
486 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
488 // If the IntB live range is assigned to a physical register, and if that
489 // physreg has sub-registers, update their live intervals as well.
490 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
491 for (const uint16_t *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
492 if (!LIS->hasInterval(*SR))
494 LiveInterval &SRLI = LIS->getInterval(*SR);
495 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
496 SRLI.getNextValue(FillerStart,
497 LIS->getVNInfoAllocator())));
501 // Okay, merge "B1" into the same value number as "B0".
502 if (BValNo != ValLR->valno) {
503 // If B1 is killed by a PHI, then the merged live range must also be killed
504 // by the same PHI, as B0 and B1 can not overlap.
505 bool HasPHIKill = BValNo->hasPHIKill();
506 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
508 ValLR->valno->setHasPHIKill(true);
511 dbgs() << " result = ";
512 IntB.print(dbgs(), TRI);
516 // If the source instruction was killing the source register before the
517 // merge, unset the isKill marker given the live range has been extended.
518 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
520 ValLREndInst->getOperand(UIdx).setIsKill(false);
523 // Rewrite the copy. If the copy instruction was killing the destination
524 // register before the merge, find the last use and trim the live range. That
525 // will also add the isKill marker.
526 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
527 if (ALR->end == CopyIdx)
528 LIS->shrinkToUses(&IntA);
534 /// hasOtherReachingDefs - Return true if there are definitions of IntB
535 /// other than BValNo val# that can reach uses of AValno val# of IntA.
536 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
540 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
542 if (AI->valno != AValNo) continue;
543 LiveInterval::Ranges::iterator BI =
544 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
545 if (BI != IntB.ranges.begin())
547 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
548 if (BI->valno == BValNo)
550 if (BI->start <= AI->start && BI->end > AI->start)
552 if (BI->start > AI->start && BI->start < AI->end)
559 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
560 /// IntA being the source and IntB being the dest, thus this defines a value
561 /// number in IntB. If the source value number (in IntA) is defined by a
562 /// commutable instruction and its other operand is coalesced to the copy dest
563 /// register, see if we can transform the copy into a noop by commuting the
564 /// definition. For example,
566 /// A3 = op A2 B0<kill>
568 /// B1 = A3 <- this copy
570 /// = op A3 <- more uses
574 /// B2 = op B0 A2<kill>
576 /// B1 = B2 <- now an identify copy
578 /// = op B2 <- more uses
580 /// This returns true if an interval was modified.
582 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
583 MachineInstr *CopyMI) {
584 // FIXME: For now, only eliminate the copy by commuting its def when the
585 // source register is a virtual register. We want to guard against cases
586 // where the copy is a back edge copy and commuting the def lengthen the
587 // live interval of the source register to the entire loop.
588 if (CP.isPhys() && CP.isFlipped())
591 // Bail if there is no dst interval.
592 if (!LIS->hasInterval(CP.getDstReg()))
595 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
598 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
600 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
602 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
603 // the example above.
604 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
605 if (!BValNo || BValNo->def != CopyIdx)
608 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
610 // AValNo is the value number in A that defines the copy, A3 in the example.
611 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
612 assert(AValNo && "COPY source not live");
614 // If other defs can reach uses of this def, then it's not safe to perform
616 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
618 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
621 if (!DefMI->isCommutable())
623 // If DefMI is a two-address instruction then commuting it will change the
624 // destination register.
625 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
626 assert(DefIdx != -1);
628 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
630 unsigned Op1, Op2, NewDstIdx;
631 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
635 else if (Op2 == UseOpIdx)
640 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
641 unsigned NewReg = NewDstMO.getReg();
642 if (NewReg != IntB.reg || !NewDstMO.isKill())
645 // Make sure there are no other definitions of IntB that would reach the
646 // uses which the new definition can reach.
647 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
650 // Abort if the aliases of IntB.reg have values that are not simply the
651 // clobbers from the superreg.
652 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
653 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
654 if (LIS->hasInterval(*AS) &&
655 hasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
658 // If some of the uses of IntA.reg is already coalesced away, return false.
659 // It's not possible to determine whether it's safe to perform the coalescing.
660 for (MachineRegisterInfo::use_nodbg_iterator UI =
661 MRI->use_nodbg_begin(IntA.reg),
662 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
663 MachineInstr *UseMI = &*UI;
664 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
665 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
666 if (ULR == IntA.end())
668 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
672 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
675 // At this point we have decided that it is legal to do this
676 // transformation. Start by commuting the instruction.
677 MachineBasicBlock *MBB = DefMI->getParent();
678 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
681 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
682 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
683 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
685 if (NewMI != DefMI) {
686 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
687 MachineBasicBlock::iterator Pos = DefMI;
688 MBB->insert(Pos, NewMI);
691 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
692 NewMI->getOperand(OpIdx).setIsKill();
694 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
703 // Update uses of IntA of the specific Val# with IntB.
704 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
705 UE = MRI->use_end(); UI != UE;) {
706 MachineOperand &UseMO = UI.getOperand();
707 MachineInstr *UseMI = &*UI;
709 if (JoinedCopies.count(UseMI))
711 if (UseMI->isDebugValue()) {
712 // FIXME These don't have an instruction index. Not clear we have enough
713 // info to decide whether to do this replacement or not. For now do it.
714 UseMO.setReg(NewReg);
717 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
718 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
719 if (ULR == IntA.end() || ULR->valno != AValNo)
721 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
722 UseMO.substPhysReg(NewReg, *TRI);
724 UseMO.setReg(NewReg);
727 if (!UseMI->isCopy())
729 if (UseMI->getOperand(0).getReg() != IntB.reg ||
730 UseMI->getOperand(0).getSubReg())
733 // This copy will become a noop. If it's defining a new val#, merge it into
735 SlotIndex DefIdx = UseIdx.getRegSlot();
736 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
739 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
740 assert(DVNI->def == DefIdx);
741 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
745 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
747 VNInfo *ValNo = BValNo;
748 ValNo->def = AValNo->def;
749 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
751 if (AI->valno != AValNo) continue;
752 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
754 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
756 IntA.removeValNo(AValNo);
757 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
762 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
763 /// computation, replace the copy by rematerialize the definition.
764 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
767 MachineInstr *CopyMI) {
768 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
769 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
770 assert(SrcLR != SrcInt.end() && "Live range not found!");
771 VNInfo *ValNo = SrcLR->valno;
772 if (ValNo->isPHIDef() || ValNo->isUnused())
774 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
777 assert(DefMI && "Defining instruction disappeared");
778 if (!DefMI->isAsCheapAsAMove())
780 if (!TII->isTriviallyReMaterializable(DefMI, AA))
782 bool SawStore = false;
783 if (!DefMI->isSafeToMove(TII, AA, SawStore))
785 const MCInstrDesc &MCID = DefMI->getDesc();
786 if (MCID.getNumDefs() != 1)
788 if (!DefMI->isImplicitDef()) {
789 // Make sure the copy destination register class fits the instruction
790 // definition register class. The mismatch can happen as a result of earlier
791 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
792 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
793 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
794 if (MRI->getRegClass(DstReg) != RC)
796 } else if (!RC->contains(DstReg))
800 MachineBasicBlock *MBB = CopyMI->getParent();
801 MachineBasicBlock::iterator MII =
802 llvm::next(MachineBasicBlock::iterator(CopyMI));
803 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
804 MachineInstr *NewMI = prior(MII);
806 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
807 // We need to remember these so we can add intervals once we insert
808 // NewMI into SlotIndexes.
809 SmallVector<unsigned, 4> NewMIImplDefs;
810 for (unsigned i = NewMI->getDesc().getNumOperands(),
811 e = NewMI->getNumOperands(); i != e; ++i) {
812 MachineOperand &MO = NewMI->getOperand(i);
814 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
815 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
816 NewMIImplDefs.push_back(MO.getReg());
820 // CopyMI may have implicit operands, transfer them over to the newly
821 // rematerialized instruction. And update implicit def interval valnos.
822 for (unsigned i = CopyMI->getDesc().getNumOperands(),
823 e = CopyMI->getNumOperands(); i != e; ++i) {
824 MachineOperand &MO = CopyMI->getOperand(i);
826 assert(MO.isImplicit() && "No explicit operands after implict operands.");
827 // Discard VReg implicit defs.
828 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
829 NewMI->addOperand(MO);
834 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
836 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
837 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
838 unsigned reg = NewMIImplDefs[i];
839 LiveInterval &li = LIS->getInterval(reg);
840 VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
841 LIS->getVNInfoAllocator());
842 LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
846 CopyMI->eraseFromParent();
847 ReMatCopies.insert(CopyMI);
848 ReMatDefs.insert(DefMI);
849 DEBUG(dbgs() << "Remat: " << *NewMI);
852 // The source interval can become smaller because we removed a use.
854 LIS->shrinkToUses(&SrcInt);
859 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
860 /// values, it only removes local variables. When we have a copy like:
862 /// %vreg1 = COPY %vreg2<undef>
864 /// We delete the copy and remove the corresponding value number from %vreg1.
865 /// Any uses of that value number are marked as <undef>.
866 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
867 const CoalescerPair &CP) {
868 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
869 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
870 if (SrcInt->liveAt(Idx))
872 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
873 if (DstInt->liveAt(Idx))
876 // No intervals are live-in to CopyMI - it is undef.
881 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
882 assert(DeadVNI && "No value defined in DstInt");
883 DstInt->removeValNo(DeadVNI);
885 // Find new undef uses.
886 for (MachineRegisterInfo::reg_nodbg_iterator
887 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
889 MachineOperand &MO = I.getOperand();
890 if (MO.isDef() || MO.isUndef())
892 MachineInstr *MI = MO.getParent();
893 SlotIndex Idx = LIS->getInstructionIndex(MI);
894 if (DstInt->liveAt(Idx))
897 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
902 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
903 /// update the subregister number if it is not zero. If DstReg is a
904 /// physical register and the existing subregister number of the def / use
905 /// being updated is not zero, make sure to set it to the correct physical
907 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
910 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
911 LiveInterval &DstInt = LIS->getInterval(DstReg);
913 // Update LiveDebugVariables.
914 LDV->renameRegister(SrcReg, DstReg, SubIdx);
916 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
917 MachineInstr *UseMI = I.skipInstruction();) {
918 bool AlreadyJoined = JoinedCopies.count(UseMI);
920 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
923 if (UseMI->isFullCopy() &&
924 UseMI->getOperand(1).getReg() == SrcReg &&
925 UseMI->getOperand(0).getReg() != SrcReg &&
926 UseMI->getOperand(0).getReg() != DstReg &&
928 reMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
929 UseMI->getOperand(0).getReg(), UseMI))
933 SmallVector<unsigned,8> Ops;
935 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
937 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
938 // because SrcReg is a sub-register.
939 if (!Reads && SubIdx && !AlreadyJoined)
940 Reads = DstInt.liveAt(LIS->getInstructionIndex(UseMI));
942 // Replace SrcReg with DstReg in all UseMI operands.
943 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
944 MachineOperand &MO = UseMI->getOperand(Ops[i]);
946 // Adjust <undef> flags in case of sub-register joins. We don't want to
947 // turn a full def into a read-modify-write sub-register def and vice
949 if (SubIdx && !AlreadyJoined && MO.isDef())
950 MO.setIsUndef(!Reads);
953 MO.substPhysReg(DstReg, *TRI);
955 MO.substVirtReg(DstReg, SubIdx, *TRI);
958 // This instruction is a copy that will be removed.
963 dbgs() << "\t\tupdated: ";
964 if (!UseMI->isDebugValue())
965 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
971 /// removeIntervalIfEmpty - Check if the live interval of a physical register
972 /// is empty, if so remove it and also remove the empty intervals of its
973 /// sub-registers. Return true if live interval is removed.
974 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
975 const TargetRegisterInfo *TRI) {
977 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
978 for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
979 if (!LIS->hasInterval(*SR))
981 LiveInterval &sli = LIS->getInterval(*SR);
983 LIS->removeInterval(*SR);
985 LIS->removeInterval(li.reg);
991 /// removeDeadDef - If a def of a live interval is now determined dead, remove
992 /// the val# it defines. If the live interval becomes empty, remove it as well.
993 bool RegisterCoalescer::removeDeadDef(LiveInterval &li, MachineInstr *DefMI) {
994 SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
995 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
996 if (DefIdx != MLR->valno->def)
998 li.removeValNo(MLR->valno);
999 return removeIntervalIfEmpty(li, LIS, TRI);
1002 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
1003 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
1004 /// Always join simple intervals that are defined by a single copy from a
1005 /// reserved register. This doesn't increase register pressure, so it is
1006 /// always beneficial.
1007 if (!RegClassInfo.isReserved(CP.getDstReg())) {
1008 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1012 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1013 if (CP.isFlipped() && JoinVInt.containsOneValue())
1016 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1020 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1021 /// which are the src/dst of the copy instruction CopyMI. This returns true
1022 /// if the copy was successfully coalesced away. If it is not currently
1023 /// possible to coalesce this interval, but it may be possible if other
1024 /// things get coalesced, then it returns true by reference in 'Again'.
1025 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1028 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1029 return false; // Already done.
1031 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1033 CoalescerPair CP(*TII, *TRI);
1034 if (!CP.setRegisters(CopyMI)) {
1035 DEBUG(dbgs() << "\tNot coalescable.\n");
1039 // If they are already joined we continue.
1040 if (CP.getSrcReg() == CP.getDstReg()) {
1041 markAsJoined(CopyMI);
1042 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1043 return false; // Not coalescable.
1046 // Eliminate undefs.
1047 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1048 markAsJoined(CopyMI);
1049 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1050 return false; // Not coalescable.
1053 // Enforce policies.
1055 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1056 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1058 if (!canJoinPhys(CP)) {
1059 // Before giving up coalescing, if definition of source is defined by
1060 // trivial computation, try rematerializing it.
1061 if (!CP.isFlipped() &&
1062 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1063 CP.getDstReg(), CopyMI))
1069 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1071 if (CP.getDstIdx() && CP.getSrcIdx())
1072 dbgs() << PrintReg(CP.getDstReg()) << " in "
1073 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1074 << PrintReg(CP.getSrcReg()) << " in "
1075 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1077 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1078 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1081 // When possible, let DstReg be the larger interval.
1082 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1083 LIS->getInterval(CP.getDstReg()).ranges.size())
1087 // Okay, attempt to join these two intervals. On failure, this returns false.
1088 // Otherwise, if one of the intervals being joined is a physreg, this method
1089 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1090 // been modified, so we can use this information below to update aliases.
1091 if (!joinIntervals(CP)) {
1092 // Coalescing failed.
1094 // If definition of source is defined by trivial computation, try
1095 // rematerializing it.
1096 if (!CP.isFlipped() &&
1097 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1098 CP.getDstReg(), CopyMI))
1101 // If we can eliminate the copy without merging the live ranges, do so now.
1102 if (!CP.isPartial()) {
1103 if (adjustCopiesBackFrom(CP, CopyMI) ||
1104 removeCopyByCommutingDef(CP, CopyMI)) {
1105 markAsJoined(CopyMI);
1106 DEBUG(dbgs() << "\tTrivial!\n");
1111 // Otherwise, we are unable to join the intervals.
1112 DEBUG(dbgs() << "\tInterference!\n");
1113 Again = true; // May be possible to coalesce later.
1117 // Coalescing to a virtual register that is of a sub-register class of the
1118 // other. Make sure the resulting register is set to the right register class.
1119 if (CP.isCrossClass()) {
1121 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1124 // Remember to delete the copy instruction.
1125 markAsJoined(CopyMI);
1127 // Rewrite all SrcReg operands to DstReg.
1128 // Also update DstReg operands to include DstIdx if it is set.
1130 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1131 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1133 // SrcReg is guaranteed to be the register whose live interval that is
1135 LIS->removeInterval(CP.getSrcReg());
1137 // Update regalloc hint.
1138 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1141 LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1142 dbgs() << "\tJoined. Result = ";
1143 DstInt.print(dbgs(), TRI);
1151 /// Attempt joining with a reserved physreg.
1152 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1153 assert(CP.isPhys() && "Must be a physreg copy");
1154 assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1155 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1156 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1158 assert(CP.isFlipped() && RHS.containsOneValue() &&
1159 "Invalid join with reserved register");
1161 // Optimization for reserved registers like ESP. We can only merge with a
1162 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1163 // The live range of the reserved register will look like a set of dead defs
1164 // - we don't properly track the live range of reserved registers.
1166 // Deny any overlapping intervals. This depends on all the reserved
1167 // register live ranges to look like dead defs.
1168 for (const uint16_t *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1169 if (!LIS->hasInterval(*AS)) {
1170 // Make sure at least DstReg itself exists before attempting a join.
1171 if (*AS == CP.getDstReg())
1172 LIS->getOrCreateInterval(CP.getDstReg());
1175 if (RHS.overlaps(LIS->getInterval(*AS))) {
1176 DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1180 // Skip any value computations, we are not adding new values to the
1181 // reserved register. Also skip merging the live ranges, the reserved
1182 // register live range doesn't need to be accurate as long as all the
1187 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1188 /// compute what the resultant value numbers for each value in the input two
1189 /// ranges will be. This is complicated by copies between the two which can
1190 /// and will commonly cause multiple value numbers to be merged into one.
1192 /// VN is the value number that we're trying to resolve. InstDefiningValue
1193 /// keeps track of the new InstDefiningValue assignment for the result
1194 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1195 /// whether a value in this or other is a copy from the opposite set.
1196 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1197 /// already been assigned.
1199 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1200 /// contains the value number the copy is from.
1202 static unsigned ComputeUltimateVN(VNInfo *VNI,
1203 SmallVector<VNInfo*, 16> &NewVNInfo,
1204 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1205 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1206 SmallVector<int, 16> &ThisValNoAssignments,
1207 SmallVector<int, 16> &OtherValNoAssignments) {
1208 unsigned VN = VNI->id;
1210 // If the VN has already been computed, just return it.
1211 if (ThisValNoAssignments[VN] >= 0)
1212 return ThisValNoAssignments[VN];
1213 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1215 // If this val is not a copy from the other val, then it must be a new value
1216 // number in the destination.
1217 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1218 if (I == ThisFromOther.end()) {
1219 NewVNInfo.push_back(VNI);
1220 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1222 VNInfo *OtherValNo = I->second;
1224 // Otherwise, this *is* a copy from the RHS. If the other side has already
1225 // been computed, return it.
1226 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1227 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1229 // Mark this value number as currently being computed, then ask what the
1230 // ultimate value # of the other value is.
1231 ThisValNoAssignments[VN] = -2;
1232 unsigned UltimateVN =
1233 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1234 OtherValNoAssignments, ThisValNoAssignments);
1235 return ThisValNoAssignments[VN] = UltimateVN;
1239 // Find out if we have something like
1242 // if so, we can pretend this is actually
1245 // which allows us to coalesce A and B.
1246 // VNI is the definition of B. LR is the life range of A that includes
1247 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1248 // This implies that A dominates B.
1249 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1250 const TargetRegisterInfo &tri,
1254 SmallVector<MachineInstr*, 8> &DupCopies) {
1255 // FIXME: This is very conservative. For example, we don't handle
1256 // physical registers.
1258 MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1260 if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1263 unsigned Dst = MI->getOperand(0).getReg();
1264 unsigned Src = MI->getOperand(1).getReg();
1266 if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1267 !TargetRegisterInfo::isVirtualRegister(Dst))
1270 unsigned A = CP.getDstReg();
1271 unsigned B = CP.getSrcReg();
1277 VNInfo *Other = LR->valno;
1278 const MachineInstr *OtherMI = li.getInstructionFromIndex(Other->def);
1280 if (!OtherMI || !OtherMI->isFullCopy())
1283 unsigned OtherDst = OtherMI->getOperand(0).getReg();
1284 unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1286 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1287 !TargetRegisterInfo::isVirtualRegister(OtherDst))
1290 assert(OtherDst == B);
1292 if (Src != OtherSrc)
1295 // If the copies use two different value numbers of X, we cannot merge
1297 LiveInterval &SrcInt = li.getInterval(Src);
1298 // getVNInfoBefore returns NULL for undef copies. In this case, the
1299 // optimization is still safe.
1300 if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1303 DupCopies.push_back(MI);
1308 /// joinIntervals - Attempt to join these two intervals. On failure, this
1310 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1311 // Handle physreg joins separately.
1313 return joinReservedPhysReg(CP);
1315 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1316 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1318 // Compute the final value assignment, assuming that the live ranges can be
1320 SmallVector<int, 16> LHSValNoAssignments;
1321 SmallVector<int, 16> RHSValNoAssignments;
1322 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1323 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1324 SmallVector<VNInfo*, 16> NewVNInfo;
1326 SmallVector<MachineInstr*, 8> DupCopies;
1328 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1329 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1331 // Loop over the value numbers of the LHS, seeing if any are defined from
1333 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1336 if (VNI->isUnused() || VNI->isPHIDef())
1338 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1339 assert(MI && "Missing def");
1340 if (!MI->isCopyLike()) // Src not defined by a copy?
1343 // Figure out the value # from the RHS.
1344 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1345 // The copy could be to an aliased physreg.
1348 // DstReg is known to be a register in the LHS interval. If the src is
1349 // from the RHS interval, we can use its value #.
1350 if (!CP.isCoalescable(MI) &&
1351 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1354 LHSValsDefinedFromRHS[VNI] = lr->valno;
1357 // Loop over the value numbers of the RHS, seeing if any are defined from
1359 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1362 if (VNI->isUnused() || VNI->isPHIDef())
1364 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1365 assert(MI && "Missing def");
1366 if (!MI->isCopyLike()) // Src not defined by a copy?
1369 // Figure out the value # from the LHS.
1370 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1371 // The copy could be to an aliased physreg.
1374 // DstReg is known to be a register in the RHS interval. If the src is
1375 // from the LHS interval, we can use its value #.
1376 if (!CP.isCoalescable(MI) &&
1377 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1380 RHSValsDefinedFromLHS[VNI] = lr->valno;
1383 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1384 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1385 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1387 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1390 unsigned VN = VNI->id;
1391 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1393 ComputeUltimateVN(VNI, NewVNInfo,
1394 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1395 LHSValNoAssignments, RHSValNoAssignments);
1397 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1400 unsigned VN = VNI->id;
1401 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1403 // If this value number isn't a copy from the LHS, it's a new number.
1404 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1405 NewVNInfo.push_back(VNI);
1406 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1410 ComputeUltimateVN(VNI, NewVNInfo,
1411 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1412 RHSValNoAssignments, LHSValNoAssignments);
1415 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1416 // interval lists to see if these intervals are coalescable.
1417 LiveInterval::const_iterator I = LHS.begin();
1418 LiveInterval::const_iterator IE = LHS.end();
1419 LiveInterval::const_iterator J = RHS.begin();
1420 LiveInterval::const_iterator JE = RHS.end();
1422 // Skip ahead until the first place of potential sharing.
1423 if (I != IE && J != JE) {
1424 if (I->start < J->start) {
1425 I = std::upper_bound(I, IE, J->start);
1426 if (I != LHS.begin()) --I;
1427 } else if (J->start < I->start) {
1428 J = std::upper_bound(J, JE, I->start);
1429 if (J != RHS.begin()) --J;
1433 while (I != IE && J != JE) {
1434 // Determine if these two live ranges overlap.
1436 if (I->start < J->start) {
1437 Overlaps = I->end > J->start;
1439 Overlaps = J->end > I->start;
1442 // If so, check value # info to determine if they are really different.
1444 // If the live range overlap will map to the same value number in the
1445 // result liverange, we can still coalesce them. If not, we can't.
1446 if (LHSValNoAssignments[I->valno->id] !=
1447 RHSValNoAssignments[J->valno->id])
1451 if (I->end < J->end)
1457 // Update kill info. Some live ranges are extended due to copy coalescing.
1458 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1459 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1460 VNInfo *VNI = I->first;
1461 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1462 if (VNI->hasPHIKill())
1463 NewVNInfo[LHSValID]->setHasPHIKill(true);
1466 // Update kill info. Some live ranges are extended due to copy coalescing.
1467 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1468 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1469 VNInfo *VNI = I->first;
1470 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1471 if (VNI->hasPHIKill())
1472 NewVNInfo[RHSValID]->setHasPHIKill(true);
1475 if (LHSValNoAssignments.empty())
1476 LHSValNoAssignments.push_back(-1);
1477 if (RHSValNoAssignments.empty())
1478 RHSValNoAssignments.push_back(-1);
1480 SmallVector<unsigned, 8> SourceRegisters;
1481 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1482 E = DupCopies.end(); I != E; ++I) {
1483 MachineInstr *MI = *I;
1485 // We have pretended that the assignment to B in
1488 // was actually a copy from A. Now that we decided to coalesce A and B,
1489 // transform the code into
1492 // and mark the X as coalesced to keep the illusion.
1493 unsigned Src = MI->getOperand(1).getReg();
1494 SourceRegisters.push_back(Src);
1495 MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1500 // If B = X was the last use of X in a liverange, we have to shrink it now
1501 // that B = X is gone.
1502 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1503 E = SourceRegisters.end(); I != E; ++I) {
1504 LIS->shrinkToUses(&LIS->getInterval(*I));
1507 // If we get here, we know that we can coalesce the live ranges. Ask the
1508 // intervals to coalesce themselves now.
1509 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1515 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1516 // depth of the basic block (the unsigned), and then on the MBB number.
1517 struct DepthMBBCompare {
1518 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1519 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1520 // Deeper loops first
1521 if (LHS.first != RHS.first)
1522 return LHS.first > RHS.first;
1524 // Prefer blocks that are more connected in the CFG. This takes care of
1525 // the most difficult copies first while intervals are short.
1526 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1527 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1531 // As a last resort, sort by block number.
1532 return LHS.second->getNumber() < RHS.second->getNumber();
1537 // Try joining WorkList copies starting from index From.
1538 // Null out any successful joins.
1539 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
1540 assert(From <= WorkList.size() && "Out of range");
1541 bool Progress = false;
1542 for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
1546 bool Success = joinCopy(WorkList[i], Again);
1547 Progress |= Success;
1548 if (Success || !Again)
1555 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
1556 DEBUG(dbgs() << MBB->getName() << ":\n");
1558 // Collect all copy-like instructions in MBB. Don't start coalescing anything
1559 // yet, it might invalidate the iterator.
1560 const unsigned PrevSize = WorkList.size();
1561 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1563 if (MII->isCopyLike())
1564 WorkList.push_back(MII);
1566 // Try coalescing the collected copies immediately, and remove the nulls.
1567 // This prevents the WorkList from getting too large since most copies are
1568 // joinable on the first attempt.
1569 if (copyCoalesceWorkList(PrevSize))
1570 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
1571 (MachineInstr*)0), WorkList.end());
1574 void RegisterCoalescer::joinAllIntervals() {
1575 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1576 assert(WorkList.empty() && "Old data still around.");
1578 if (Loops->empty()) {
1579 // If there are no loops in the function, join intervals in function order.
1580 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1582 copyCoalesceInMBB(I);
1584 // Otherwise, join intervals in inner loops before other intervals.
1585 // Unfortunately we can't just iterate over loop hierarchy here because
1586 // there may be more MBB's than BB's. Collect MBB's for sorting.
1588 // Join intervals in the function prolog first. We want to join physical
1589 // registers with virtual registers before the intervals got too long.
1590 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1591 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1592 MachineBasicBlock *MBB = I;
1593 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1596 // Sort by loop depth.
1597 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1599 // Finally, join intervals in loop nest order.
1600 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1601 copyCoalesceInMBB(MBBs[i].second);
1604 // Joining intervals can allow other intervals to be joined. Iteratively join
1605 // until we make no progress.
1606 while (copyCoalesceWorkList())
1610 void RegisterCoalescer::releaseMemory() {
1611 JoinedCopies.clear();
1612 ReMatCopies.clear();
1617 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1619 MRI = &fn.getRegInfo();
1620 TM = &fn.getTarget();
1621 TRI = TM->getRegisterInfo();
1622 TII = TM->getInstrInfo();
1623 LIS = &getAnalysis<LiveIntervals>();
1624 LDV = &getAnalysis<LiveDebugVariables>();
1625 AA = &getAnalysis<AliasAnalysis>();
1626 Loops = &getAnalysis<MachineLoopInfo>();
1628 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1629 << "********** Function: "
1630 << ((Value*)MF->getFunction())->getName() << '\n');
1632 if (VerifyCoalescing)
1633 MF->verify(this, "Before register coalescing");
1635 RegClassInfo.runOnMachineFunction(fn);
1637 // Join (coalesce) intervals if requested.
1638 if (EnableJoining) {
1641 dbgs() << "********** INTERVALS POST JOINING **********\n";
1642 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1644 I->second->print(dbgs(), TRI);
1650 // Perform a final pass over the instructions and compute spill weights
1651 // and remove identity moves.
1652 SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1653 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1654 mbbi != mbbe; ++mbbi) {
1655 MachineBasicBlock* mbb = mbbi;
1656 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1658 MachineInstr *MI = mii;
1659 if (JoinedCopies.count(MI)) {
1660 // Delete all coalesced copies.
1661 bool DoDelete = true;
1662 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1663 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1664 unsigned DstReg = MI->getOperand(0).getReg();
1666 // Collect candidates for register class inflation.
1667 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1668 RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1669 InflateRegs.push_back(SrcReg);
1670 if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1671 RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1672 InflateRegs.push_back(DstReg);
1674 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1675 MI->getNumOperands() > 2)
1676 // Do not delete extract_subreg, insert_subreg of physical
1677 // registers unless the definition is dead. e.g.
1678 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1679 // or else the scavenger may complain. LowerSubregs will
1680 // delete them later.
1683 if (MI->allDefsAreDead()) {
1684 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1685 LIS->hasInterval(SrcReg))
1686 LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1690 // We need the instruction to adjust liveness, so make it a KILL.
1691 if (MI->isSubregToReg()) {
1692 MI->RemoveOperand(3);
1693 MI->RemoveOperand(1);
1695 MI->setDesc(TII->get(TargetOpcode::KILL));
1696 mii = llvm::next(mii);
1698 LIS->RemoveMachineInstrFromMaps(MI);
1699 mii = mbbi->erase(mii);
1705 // Now check if this is a remat'ed def instruction which is now dead.
1706 if (ReMatDefs.count(MI)) {
1708 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1709 const MachineOperand &MO = MI->getOperand(i);
1712 unsigned Reg = MO.getReg();
1715 DeadDefs.push_back(Reg);
1716 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1717 // Remat may also enable register class inflation.
1718 if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1719 InflateRegs.push_back(Reg);
1723 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1724 !MRI->use_nodbg_empty(Reg)) {
1730 while (!DeadDefs.empty()) {
1731 unsigned DeadDef = DeadDefs.back();
1732 DeadDefs.pop_back();
1733 removeDeadDef(LIS->getInterval(DeadDef), MI);
1735 LIS->RemoveMachineInstrFromMaps(mii);
1736 mii = mbbi->erase(mii);
1744 // Check for now unnecessary kill flags.
1745 if (LIS->isNotInMIMap(MI)) continue;
1746 SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1747 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1748 MachineOperand &MO = MI->getOperand(i);
1749 if (!MO.isReg() || !MO.isKill()) continue;
1750 unsigned reg = MO.getReg();
1751 if (!reg || !LIS->hasInterval(reg)) continue;
1752 if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1753 MO.setIsKill(false);
1756 // When leaving a kill flag on a physreg, check if any subregs should
1758 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1760 for (const uint16_t *SR = TRI->getSubRegisters(reg);
1761 unsigned S = *SR; ++SR)
1762 if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1763 MI->addRegisterDefined(S, TRI);
1768 // After deleting a lot of copies, register classes may be less constrained.
1769 // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1771 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1772 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1774 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1775 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1776 unsigned Reg = InflateRegs[i];
1777 if (MRI->reg_nodbg_empty(Reg))
1779 if (MRI->recomputeRegClass(Reg, *TM)) {
1780 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1781 << MRI->getRegClass(Reg)->getName() << '\n');
1788 if (VerifyCoalescing)
1789 MF->verify(this, "After register coalescing");
1793 /// print - Implement the dump method.
1794 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {