1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
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 a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "LiveDebugVariables.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/OwningPtr.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
43 STATISTIC(numJoins , "Number of interval joins performed");
44 STATISTIC(numCrossRCs , "Number of cross class joins performed");
45 STATISTIC(numCommutes , "Number of instruction commuting performed");
46 STATISTIC(numExtends , "Number of copies extended");
47 STATISTIC(NumReMats , "Number of instructions re-materialized");
48 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
49 STATISTIC(numAborts , "Number of times interval joining aborted");
50 STATISTIC(numDeadValNo, "Number of valno def marked dead");
52 char SimpleRegisterCoalescing::ID = 0;
54 EnableJoining("join-liveintervals",
55 cl::desc("Coalesce copies (default=true)"),
59 DisableCrossClassJoin("disable-cross-class-join",
60 cl::desc("Avoid coalescing cross register class copies"),
61 cl::init(false), cl::Hidden);
64 EnablePhysicalJoin("join-physregs",
65 cl::desc("Join physical register copies"),
66 cl::init(false), cl::Hidden);
69 VerifyCoalescing("verify-coalescing",
70 cl::desc("Verify machine instrs before and after register coalescing"),
73 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing, RegisterCoalescer,
74 "simple-register-coalescing", "Simple Register Coalescing",
76 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
77 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
78 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
79 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
80 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
81 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
82 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
83 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
84 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing, RegisterCoalescer,
85 "simple-register-coalescing", "Simple Register Coalescing",
88 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
90 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequired<AliasAnalysis>();
93 AU.addRequired<LiveIntervals>();
94 AU.addPreserved<LiveIntervals>();
95 AU.addRequired<LiveDebugVariables>();
96 AU.addPreserved<LiveDebugVariables>();
97 AU.addPreserved<SlotIndexes>();
98 AU.addRequired<MachineLoopInfo>();
99 AU.addPreserved<MachineLoopInfo>();
100 AU.addPreservedID(MachineDominatorsID);
101 AU.addPreservedID(StrongPHIEliminationID);
102 AU.addPreservedID(PHIEliminationID);
103 AU.addPreservedID(TwoAddressInstructionPassID);
104 MachineFunctionPass::getAnalysisUsage(AU);
107 void SimpleRegisterCoalescing::markAsJoined(MachineInstr *CopyMI) {
108 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
109 JoinedCopies.insert(CopyMI);
111 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
112 /// code elimination.
113 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
114 E = CopyMI->operands_end(); I != E; ++I)
119 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
120 /// being the source and IntB being the dest, thus this defines a value number
121 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
122 /// see if we can merge these two pieces of B into a single value number,
123 /// eliminating a copy. For example:
127 /// B1 = A3 <- this copy
129 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
130 /// value number to be replaced with B0 (which simplifies the B liveinterval).
132 /// This returns true if an interval was modified.
134 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
135 MachineInstr *CopyMI) {
136 // Bail if there is no dst interval - can happen when merging physical subreg
138 if (!li_->hasInterval(CP.getDstReg()))
142 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
144 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
145 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
147 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
148 // the example above.
149 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
150 if (BLR == IntB.end()) return false;
151 VNInfo *BValNo = BLR->valno;
153 // Get the location that B is defined at. Two options: either this value has
154 // an unknown definition point or it is defined at CopyIdx. If unknown, we
156 if (!BValNo->isDefByCopy()) return false;
157 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
159 // AValNo is the value number in A that defines the copy, A3 in the example.
160 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
161 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
162 // The live range might not exist after fun with physreg coalescing.
163 if (ALR == IntA.end()) return false;
164 VNInfo *AValNo = ALR->valno;
165 // If it's re-defined by an early clobber somewhere in the live range, then
166 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
168 // 172 %ECX<def> = MOV32rr %reg1039<kill>
169 // 180 INLINEASM <es:subl $5,$1
170 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
172 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
173 // 188 %EAX<def> = MOV32rr %EAX<kill>
174 // 196 %ECX<def> = MOV32rr %ECX<kill>
175 // 204 %ECX<def> = MOV32rr %ECX<kill>
176 // 212 %EAX<def> = MOV32rr %EAX<kill>
177 // 220 %EAX<def> = MOV32rr %EAX
178 // 228 %reg1039<def> = MOV32rr %ECX<kill>
179 // The early clobber operand ties ECX input to the ECX def.
181 // The live interval of ECX is represented as this:
182 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
183 // The coalescer has no idea there was a def in the middle of [174,230].
184 if (AValNo->hasRedefByEC())
187 // If AValNo is defined as a copy from IntB, we can potentially process this.
188 // Get the instruction that defines this value number.
189 if (!CP.isCoalescable(AValNo->getCopy()))
192 // Get the LiveRange in IntB that this value number starts with.
193 LiveInterval::iterator ValLR =
194 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
195 if (ValLR == IntB.end())
198 // Make sure that the end of the live range is inside the same block as
200 MachineInstr *ValLREndInst =
201 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
202 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
205 // Okay, we now know that ValLR ends in the same block that the CopyMI
206 // live-range starts. If there are no intervening live ranges between them in
207 // IntB, we can merge them.
208 if (ValLR+1 != BLR) return false;
210 // If a live interval is a physical register, conservatively check if any
211 // of its aliases is overlapping the live interval of the virtual register.
212 // If so, do not coalesce.
213 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
214 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
215 if (li_->hasInterval(*AS) && IntA.overlaps(li_->getInterval(*AS))) {
217 dbgs() << "\t\tInterfere with alias ";
218 li_->getInterval(*AS).print(dbgs(), tri_);
225 dbgs() << "Extending: ";
226 IntB.print(dbgs(), tri_);
229 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
230 // We are about to delete CopyMI, so need to remove it as the 'instruction
231 // that defines this value #'. Update the valnum with the new defining
233 BValNo->def = FillerStart;
236 // Okay, we can merge them. We need to insert a new liverange:
237 // [ValLR.end, BLR.begin) of either value number, then we merge the
238 // two value numbers.
239 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
241 // If the IntB live range is assigned to a physical register, and if that
242 // physreg has sub-registers, update their live intervals as well.
243 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
244 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
245 if (!li_->hasInterval(*SR))
247 LiveInterval &SRLI = li_->getInterval(*SR);
248 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
249 SRLI.getNextValue(FillerStart, 0,
250 li_->getVNInfoAllocator())));
254 // Okay, merge "B1" into the same value number as "B0".
255 if (BValNo != ValLR->valno) {
256 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
259 dbgs() << " result = ";
260 IntB.print(dbgs(), tri_);
264 // If the source instruction was killing the source register before the
265 // merge, unset the isKill marker given the live range has been extended.
266 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
268 ValLREndInst->getOperand(UIdx).setIsKill(false);
271 // If the copy instruction was killing the destination register before the
272 // merge, find the last use and trim the live range. That will also add the
274 if (ALR->end == CopyIdx)
275 li_->shrinkToUses(&IntA);
281 /// HasOtherReachingDefs - Return true if there are definitions of IntB
282 /// other than BValNo val# that can reach uses of AValno val# of IntA.
283 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
287 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
289 if (AI->valno != AValNo) continue;
290 LiveInterval::Ranges::iterator BI =
291 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
292 if (BI != IntB.ranges.begin())
294 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
295 if (BI->valno == BValNo)
297 if (BI->start <= AI->start && BI->end > AI->start)
299 if (BI->start > AI->start && BI->start < AI->end)
306 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
307 /// IntA being the source and IntB being the dest, thus this defines a value
308 /// number in IntB. If the source value number (in IntA) is defined by a
309 /// commutable instruction and its other operand is coalesced to the copy dest
310 /// register, see if we can transform the copy into a noop by commuting the
311 /// definition. For example,
313 /// A3 = op A2 B0<kill>
315 /// B1 = A3 <- this copy
317 /// = op A3 <- more uses
321 /// B2 = op B0 A2<kill>
323 /// B1 = B2 <- now an identify copy
325 /// = op B2 <- more uses
327 /// This returns true if an interval was modified.
329 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
330 MachineInstr *CopyMI) {
331 // FIXME: For now, only eliminate the copy by commuting its def when the
332 // source register is a virtual register. We want to guard against cases
333 // where the copy is a back edge copy and commuting the def lengthen the
334 // live interval of the source register to the entire loop.
335 if (CP.isPhys() && CP.isFlipped())
338 // Bail if there is no dst interval.
339 if (!li_->hasInterval(CP.getDstReg()))
342 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
345 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
347 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
349 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
350 // the example above.
351 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
352 if (!BValNo || !BValNo->isDefByCopy())
355 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
357 // AValNo is the value number in A that defines the copy, A3 in the example.
358 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
359 assert(AValNo && "COPY source not live");
361 // If other defs can reach uses of this def, then it's not safe to perform
363 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
365 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
368 const TargetInstrDesc &TID = DefMI->getDesc();
369 if (!TID.isCommutable())
371 // If DefMI is a two-address instruction then commuting it will change the
372 // destination register.
373 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
374 assert(DefIdx != -1);
376 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
378 unsigned Op1, Op2, NewDstIdx;
379 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
383 else if (Op2 == UseOpIdx)
388 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
389 unsigned NewReg = NewDstMO.getReg();
390 if (NewReg != IntB.reg || !NewDstMO.isKill())
393 // Make sure there are no other definitions of IntB that would reach the
394 // uses which the new definition can reach.
395 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
398 // Abort if the aliases of IntB.reg have values that are not simply the
399 // clobbers from the superreg.
400 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
401 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
402 if (li_->hasInterval(*AS) &&
403 HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
406 // If some of the uses of IntA.reg is already coalesced away, return false.
407 // It's not possible to determine whether it's safe to perform the coalescing.
408 for (MachineRegisterInfo::use_nodbg_iterator UI =
409 mri_->use_nodbg_begin(IntA.reg),
410 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
411 MachineInstr *UseMI = &*UI;
412 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
413 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
414 if (ULR == IntA.end())
416 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
420 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
423 // At this point we have decided that it is legal to do this
424 // transformation. Start by commuting the instruction.
425 MachineBasicBlock *MBB = DefMI->getParent();
426 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
429 if (NewMI != DefMI) {
430 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
431 MBB->insert(DefMI, NewMI);
434 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
435 NewMI->getOperand(OpIdx).setIsKill();
437 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
446 // Update uses of IntA of the specific Val# with IntB.
447 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
448 UE = mri_->use_end(); UI != UE;) {
449 MachineOperand &UseMO = UI.getOperand();
450 MachineInstr *UseMI = &*UI;
452 if (JoinedCopies.count(UseMI))
454 if (UseMI->isDebugValue()) {
455 // FIXME These don't have an instruction index. Not clear we have enough
456 // info to decide whether to do this replacement or not. For now do it.
457 UseMO.setReg(NewReg);
460 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
461 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
462 if (ULR == IntA.end() || ULR->valno != AValNo)
464 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
465 UseMO.substPhysReg(NewReg, *tri_);
467 UseMO.setReg(NewReg);
470 if (!UseMI->isCopy())
472 if (UseMI->getOperand(0).getReg() != IntB.reg ||
473 UseMI->getOperand(0).getSubReg())
476 // This copy will become a noop. If it's defining a new val#, merge it into
478 SlotIndex DefIdx = UseIdx.getDefIndex();
479 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
482 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
483 assert(DVNI->def == DefIdx);
484 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
488 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
490 VNInfo *ValNo = BValNo;
491 ValNo->def = AValNo->def;
493 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
495 if (AI->valno != AValNo) continue;
496 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
498 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
500 IntA.removeValNo(AValNo);
501 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
506 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
507 /// fallthoughs to SuccMBB.
508 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
509 MachineBasicBlock *SuccMBB,
510 const TargetInstrInfo *tii_) {
513 MachineBasicBlock *TBB = 0, *FBB = 0;
514 SmallVector<MachineOperand, 4> Cond;
515 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
516 MBB->isSuccessor(SuccMBB);
519 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
520 /// from a physical register live interval as well as from the live intervals
521 /// of its sub-registers.
522 static void removeRange(LiveInterval &li,
523 SlotIndex Start, SlotIndex End,
524 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
525 li.removeRange(Start, End, true);
526 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
527 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
528 if (!li_->hasInterval(*SR))
530 LiveInterval &sli = li_->getInterval(*SR);
531 SlotIndex RemoveStart = Start;
532 SlotIndex RemoveEnd = Start;
534 while (RemoveEnd != End) {
535 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
538 RemoveEnd = (LR->end < End) ? LR->end : End;
539 sli.removeRange(RemoveStart, RemoveEnd, true);
540 RemoveStart = RemoveEnd;
546 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
547 /// as the copy instruction, trim the live interval to the last use and return
550 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
551 MachineBasicBlock *CopyMBB,
553 const LiveRange *LR) {
554 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
555 SlotIndex LastUseIdx;
556 MachineOperand *LastUse =
557 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
559 MachineInstr *LastUseMI = LastUse->getParent();
560 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
567 // r1025<dead> = r1024<kill>
568 if (MBBStart < LR->end)
569 removeRange(li, MBBStart, LR->end, li_, tri_);
573 // There are uses before the copy, just shorten the live range to the end
575 LastUse->setIsKill();
576 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
577 if (LastUseMI->isCopy()) {
578 MachineOperand &DefMO = LastUseMI->getOperand(0);
579 if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
586 if (LR->start <= MBBStart && LR->end > MBBStart) {
587 if (LR->start == li_->getZeroIndex()) {
588 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
589 // Live-in to the function but dead. Remove it from entry live-in set.
590 mf_->begin()->removeLiveIn(li.reg);
592 // FIXME: Shorten intervals in BBs that reaches this BB.
598 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
599 /// computation, replace the copy by rematerialize the definition.
600 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
604 MachineInstr *CopyMI) {
605 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
606 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
607 assert(SrcLR != SrcInt.end() && "Live range not found!");
608 VNInfo *ValNo = SrcLR->valno;
609 // If other defs can reach uses of this def, then it's not safe to perform
611 if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
613 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
616 assert(DefMI && "Defining instruction disappeared");
617 const TargetInstrDesc &TID = DefMI->getDesc();
618 if (!TID.isAsCheapAsAMove())
620 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
622 bool SawStore = false;
623 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
625 if (TID.getNumDefs() != 1)
627 if (!DefMI->isImplicitDef()) {
628 // Make sure the copy destination register class fits the instruction
629 // definition register class. The mismatch can happen as a result of earlier
630 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
631 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
632 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
633 if (mri_->getRegClass(DstReg) != RC)
635 } else if (!RC->contains(DstReg))
639 // If destination register has a sub-register index on it, make sure it
640 // matches the instruction register class.
642 const TargetInstrDesc &TID = DefMI->getDesc();
643 if (TID.getNumDefs() != 1)
645 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
646 const TargetRegisterClass *DstSubRC =
647 DstRC->getSubRegisterRegClass(DstSubIdx);
648 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
651 else if (DefRC != DstSubRC)
655 RemoveCopyFlag(DstReg, CopyMI);
657 MachineBasicBlock *MBB = CopyMI->getParent();
658 MachineBasicBlock::iterator MII =
659 llvm::next(MachineBasicBlock::iterator(CopyMI));
660 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
661 MachineInstr *NewMI = prior(MII);
663 // CopyMI may have implicit operands, transfer them over to the newly
664 // rematerialized instruction. And update implicit def interval valnos.
665 for (unsigned i = CopyMI->getDesc().getNumOperands(),
666 e = CopyMI->getNumOperands(); i != e; ++i) {
667 MachineOperand &MO = CopyMI->getOperand(i);
668 if (MO.isReg() && MO.isImplicit())
669 NewMI->addOperand(MO);
671 RemoveCopyFlag(MO.getReg(), CopyMI);
674 NewMI->copyImplicitOps(CopyMI);
675 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
676 CopyMI->eraseFromParent();
677 ReMatCopies.insert(CopyMI);
678 ReMatDefs.insert(DefMI);
679 DEBUG(dbgs() << "Remat: " << *NewMI);
682 // The source interval can become smaller because we removed a use.
684 li_->shrinkToUses(&SrcInt);
689 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
690 /// update the subregister number if it is not zero. If DstReg is a
691 /// physical register and the existing subregister number of the def / use
692 /// being updated is not zero, make sure to set it to the correct physical
695 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
696 bool DstIsPhys = CP.isPhys();
697 unsigned SrcReg = CP.getSrcReg();
698 unsigned DstReg = CP.getDstReg();
699 unsigned SubIdx = CP.getSubIdx();
701 // Update LiveDebugVariables.
702 ldv_->renameRegister(SrcReg, DstReg, SubIdx);
704 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
705 MachineInstr *UseMI = I.skipInstruction();) {
706 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
709 if (UseMI->isCopy() &&
710 !UseMI->getOperand(1).getSubReg() &&
711 !UseMI->getOperand(0).getSubReg() &&
712 UseMI->getOperand(1).getReg() == SrcReg &&
713 UseMI->getOperand(0).getReg() != SrcReg &&
714 UseMI->getOperand(0).getReg() != DstReg &&
715 !JoinedCopies.count(UseMI) &&
716 ReMaterializeTrivialDef(li_->getInterval(SrcReg), false,
717 UseMI->getOperand(0).getReg(), 0, UseMI))
721 SmallVector<unsigned,8> Ops;
723 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
724 bool Kills = false, Deads = false;
726 // Replace SrcReg with DstReg in all UseMI operands.
727 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
728 MachineOperand &MO = UseMI->getOperand(Ops[i]);
729 Kills |= MO.isKill();
730 Deads |= MO.isDead();
733 MO.substPhysReg(DstReg, *tri_);
735 MO.substVirtReg(DstReg, SubIdx, *tri_);
738 // This instruction is a copy that will be removed.
739 if (JoinedCopies.count(UseMI))
743 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
744 // read-modify-write of DstReg.
746 UseMI->addRegisterDead(DstReg, tri_);
747 else if (!Reads && Writes)
748 UseMI->addRegisterDefined(DstReg, tri_);
750 // Kill flags apply to the whole physical register.
751 if (DstIsPhys && Kills)
752 UseMI->addRegisterKilled(DstReg, tri_);
756 dbgs() << "\t\tupdated: ";
757 if (!UseMI->isDebugValue())
758 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
764 /// removeIntervalIfEmpty - Check if the live interval of a physical register
765 /// is empty, if so remove it and also remove the empty intervals of its
766 /// sub-registers. Return true if live interval is removed.
767 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
768 const TargetRegisterInfo *tri_) {
770 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
771 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
772 if (!li_->hasInterval(*SR))
774 LiveInterval &sli = li_->getInterval(*SR);
776 li_->removeInterval(*SR);
778 li_->removeInterval(li.reg);
784 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
785 /// Return true if live interval is removed.
786 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
787 MachineInstr *CopyMI) {
788 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
789 LiveInterval::iterator MLR =
790 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
792 return false; // Already removed by ShortenDeadCopySrcLiveRange.
793 SlotIndex RemoveStart = MLR->start;
794 SlotIndex RemoveEnd = MLR->end;
795 SlotIndex DefIdx = CopyIdx.getDefIndex();
796 // Remove the liverange that's defined by this.
797 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
798 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
799 return removeIntervalIfEmpty(li, li_, tri_);
804 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
805 /// the val# it defines. If the live interval becomes empty, remove it as well.
806 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
807 MachineInstr *DefMI) {
808 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
809 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
810 if (DefIdx != MLR->valno->def)
812 li.removeValNo(MLR->valno);
813 return removeIntervalIfEmpty(li, li_, tri_);
816 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
817 const MachineInstr *CopyMI) {
818 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
819 if (li_->hasInterval(DstReg)) {
820 LiveInterval &LI = li_->getInterval(DstReg);
821 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
822 if (LR->valno->def == DefIdx)
823 LR->valno->setCopy(0);
825 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
827 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
828 if (!li_->hasInterval(*AS))
830 LiveInterval &LI = li_->getInterval(*AS);
831 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
832 if (LR->valno->def == DefIdx)
833 LR->valno->setCopy(0);
837 /// PropagateDeadness - Propagate the dead marker to the instruction which
838 /// defines the val#.
839 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
840 SlotIndex &LRStart, LiveIntervals *li_,
841 const TargetRegisterInfo* tri_) {
842 MachineInstr *DefMI =
843 li_->getInstructionFromIndex(LRStart.getDefIndex());
844 if (DefMI && DefMI != CopyMI) {
845 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
847 DefMI->getOperand(DeadIdx).setIsDead();
849 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
850 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
851 LRStart = LRStart.getNextSlot();
855 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
856 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
857 /// ends the live range there. If there isn't another use, then this live range
858 /// is dead. Return true if live interval is removed.
860 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
861 MachineInstr *CopyMI) {
862 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
863 if (CopyIdx == SlotIndex()) {
864 // FIXME: special case: function live in. It can be a general case if the
865 // first instruction index starts at > 0 value.
866 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
867 // Live-in to the function but dead. Remove it from entry live-in set.
868 if (mf_->begin()->isLiveIn(li.reg))
869 mf_->begin()->removeLiveIn(li.reg);
870 if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
871 removeRange(li, LR->start, LR->end, li_, tri_);
872 return removeIntervalIfEmpty(li, li_, tri_);
875 LiveInterval::iterator LR =
876 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
878 // Livein but defined by a phi.
881 SlotIndex RemoveStart = LR->start;
882 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
883 if (LR->end > RemoveEnd)
884 // More uses past this copy? Nothing to do.
887 // If there is a last use in the same bb, we can't remove the live range.
888 // Shorten the live interval and return.
889 MachineBasicBlock *CopyMBB = CopyMI->getParent();
890 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
893 // There are other kills of the val#. Nothing to do.
894 if (!li.isOnlyLROfValNo(LR))
897 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
898 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
899 // If the live range starts in another mbb and the copy mbb is not a fall
900 // through mbb, then we can only cut the range from the beginning of the
902 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
904 if (LR->valno->def == RemoveStart) {
905 // If the def MI defines the val# and this copy is the only kill of the
906 // val#, then propagate the dead marker.
907 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
911 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
912 return removeIntervalIfEmpty(li, li_, tri_);
915 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
916 /// We need to be careful about coalescing a source physical register with a
917 /// virtual register. Once the coalescing is done, it cannot be broken and these
918 /// are not spillable! If the destination interval uses are far away, think
919 /// twice about coalescing them!
920 bool SimpleRegisterCoalescing::shouldJoinPhys(CoalescerPair &CP) {
921 bool Allocatable = li_->isAllocatable(CP.getDstReg());
922 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
924 /// Always join simple intervals that are defined by a single copy from a
925 /// reserved register. This doesn't increase register pressure, so it is
926 /// always beneficial.
927 if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
930 if (!EnablePhysicalJoin) {
931 DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
935 // Only coalesce to allocatable physreg, we don't want to risk modifying
936 // reserved registers.
938 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
939 return false; // Not coalescable.
942 // Don't join with physregs that have a ridiculous number of live
943 // ranges. The data structure performance is really bad when that
945 if (li_->hasInterval(CP.getDstReg()) &&
946 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
949 << "\tPhysical register live interval too complicated, abort!\n");
953 // FIXME: Why are we skipping this test for partial copies?
954 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
955 if (!CP.isPartial()) {
956 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
957 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
958 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
959 if (Length > Threshold) {
961 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
968 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
969 /// two virtual registers from different register classes.
971 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
973 const TargetRegisterClass *SrcRC,
974 const TargetRegisterClass *DstRC,
975 const TargetRegisterClass *NewRC) {
976 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
977 // This heuristics is good enough in practice, but it's obviously not *right*.
978 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
979 // out all but the most restrictive register classes.
980 if (NewRCCount > 4 ||
981 // Early exit if the function is fairly small, coalesce aggressively if
982 // that's the case. For really special register classes with 3 or
983 // fewer registers, be a bit more careful.
984 (li_->getFuncInstructionCount() / NewRCCount) < 8)
986 LiveInterval &SrcInt = li_->getInterval(SrcReg);
987 LiveInterval &DstInt = li_->getInterval(DstReg);
988 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
989 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
991 // Coalesce aggressively if the intervals are small compared to the number of
992 // registers in the new class. The number 4 is fairly arbitrary, chosen to be
993 // less aggressive than the 8 used for the whole function size.
994 const unsigned ThresSize = 4 * NewRCCount;
995 if (SrcSize <= ThresSize && DstSize <= ThresSize)
998 // Estimate *register use density*. If it doubles or more, abort.
999 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
1000 mri_->use_nodbg_end());
1001 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
1002 mri_->use_nodbg_end());
1003 unsigned NewUses = SrcUses + DstUses;
1004 unsigned NewSize = SrcSize + DstSize;
1005 if (SrcRC != NewRC && SrcSize > ThresSize) {
1006 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1007 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1010 if (DstRC != NewRC && DstSize > ThresSize) {
1011 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1012 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1019 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1020 /// which are the src/dst of the copy instruction CopyMI. This returns true
1021 /// if the copy was successfully coalesced away. If it is not currently
1022 /// possible to coalesce this interval, but it may be possible if other
1023 /// things get coalesced, then it returns true by reference in 'Again'.
1024 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1025 MachineInstr *CopyMI = TheCopy.MI;
1028 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1029 return false; // Already done.
1031 DEBUG(dbgs() << li_->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 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_)
1047 << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
1050 // Enforce policies.
1052 if (!shouldJoinPhys(CP)) {
1053 // Before giving up coalescing, if definition of source is defined by
1054 // trivial computation, try rematerializing it.
1055 if (!CP.isFlipped() &&
1056 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1057 CP.getDstReg(), 0, CopyMI))
1062 // Avoid constraining virtual register regclass too much.
1063 if (CP.isCrossClass()) {
1064 DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1065 if (DisableCrossClassJoin) {
1066 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1069 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1070 mri_->getRegClass(CP.getSrcReg()),
1071 mri_->getRegClass(CP.getDstReg()),
1073 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
1074 Again = true; // May be possible to coalesce later.
1079 // When possible, let DstReg be the larger interval.
1080 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1081 li_->getInterval(CP.getDstReg()).ranges.size())
1085 // Okay, attempt to join these two intervals. On failure, this returns false.
1086 // Otherwise, if one of the intervals being joined is a physreg, this method
1087 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1088 // been modified, so we can use this information below to update aliases.
1089 if (!JoinIntervals(CP)) {
1090 // Coalescing failed.
1092 // If definition of source is defined by trivial computation, try
1093 // rematerializing it.
1094 if (!CP.isFlipped() &&
1095 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1096 CP.getDstReg(), 0, CopyMI))
1099 // If we can eliminate the copy without merging the live ranges, do so now.
1100 if (!CP.isPartial()) {
1101 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1102 RemoveCopyByCommutingDef(CP, CopyMI)) {
1103 markAsJoined(CopyMI);
1104 DEBUG(dbgs() << "\tTrivial!\n");
1109 // Otherwise, we are unable to join the intervals.
1110 DEBUG(dbgs() << "\tInterference!\n");
1111 Again = true; // May be possible to coalesce later.
1115 // Coalescing to a virtual register that is of a sub-register class of the
1116 // other. Make sure the resulting register is set to the right register class.
1117 if (CP.isCrossClass()) {
1119 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1122 // Remember to delete the copy instruction.
1123 markAsJoined(CopyMI);
1125 UpdateRegDefsUses(CP);
1127 // If we have extended the live range of a physical register, make sure we
1128 // update live-in lists as well.
1130 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1131 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1132 // ranges for this, and they are preserved.
1133 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1134 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1136 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1137 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1138 MachineBasicBlock &block = *BlockSeq[idx];
1139 if (!block.isLiveIn(CP.getDstReg()))
1140 block.addLiveIn(CP.getDstReg());
1146 // SrcReg is guarateed to be the register whose live interval that is
1148 li_->removeInterval(CP.getSrcReg());
1150 // Update regalloc hint.
1151 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1154 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1155 dbgs() << "\tJoined. Result = ";
1156 DstInt.print(dbgs(), tri_);
1164 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1165 /// compute what the resultant value numbers for each value in the input two
1166 /// ranges will be. This is complicated by copies between the two which can
1167 /// and will commonly cause multiple value numbers to be merged into one.
1169 /// VN is the value number that we're trying to resolve. InstDefiningValue
1170 /// keeps track of the new InstDefiningValue assignment for the result
1171 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1172 /// whether a value in this or other is a copy from the opposite set.
1173 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1174 /// already been assigned.
1176 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1177 /// contains the value number the copy is from.
1179 static unsigned ComputeUltimateVN(VNInfo *VNI,
1180 SmallVector<VNInfo*, 16> &NewVNInfo,
1181 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1182 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1183 SmallVector<int, 16> &ThisValNoAssignments,
1184 SmallVector<int, 16> &OtherValNoAssignments) {
1185 unsigned VN = VNI->id;
1187 // If the VN has already been computed, just return it.
1188 if (ThisValNoAssignments[VN] >= 0)
1189 return ThisValNoAssignments[VN];
1190 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1192 // If this val is not a copy from the other val, then it must be a new value
1193 // number in the destination.
1194 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1195 if (I == ThisFromOther.end()) {
1196 NewVNInfo.push_back(VNI);
1197 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1199 VNInfo *OtherValNo = I->second;
1201 // Otherwise, this *is* a copy from the RHS. If the other side has already
1202 // been computed, return it.
1203 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1204 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1206 // Mark this value number as currently being computed, then ask what the
1207 // ultimate value # of the other value is.
1208 ThisValNoAssignments[VN] = -2;
1209 unsigned UltimateVN =
1210 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1211 OtherValNoAssignments, ThisValNoAssignments);
1212 return ThisValNoAssignments[VN] = UltimateVN;
1215 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1217 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1218 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1219 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1221 // If a live interval is a physical register, check for interference with any
1222 // aliases. The interference check implemented here is a bit more conservative
1223 // than the full interfeence check below. We allow overlapping live ranges
1224 // only when one is a copy of the other.
1226 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1227 if (!li_->hasInterval(*AS))
1229 const LiveInterval &LHS = li_->getInterval(*AS);
1230 LiveInterval::const_iterator LI = LHS.begin();
1231 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1233 LI = std::lower_bound(LI, LHS.end(), RI->start);
1234 // Does LHS have an overlapping live range starting before RI?
1235 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1236 (RI->start != RI->valno->def ||
1237 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1239 dbgs() << "\t\tInterference from alias: ";
1240 LHS.print(dbgs(), tri_);
1241 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1246 // Check that LHS ranges beginning in this range are copies.
1247 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1248 if (LI->start != LI->valno->def ||
1249 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1251 dbgs() << "\t\tInterference from alias: ";
1252 LHS.print(dbgs(), tri_);
1253 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1262 // Compute the final value assignment, assuming that the live ranges can be
1264 SmallVector<int, 16> LHSValNoAssignments;
1265 SmallVector<int, 16> RHSValNoAssignments;
1266 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1267 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1268 SmallVector<VNInfo*, 16> NewVNInfo;
1270 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1271 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1273 // Loop over the value numbers of the LHS, seeing if any are defined from
1275 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1278 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1281 // Never join with a register that has EarlyClobber redefs.
1282 if (VNI->hasRedefByEC())
1285 // DstReg is known to be a register in the LHS interval. If the src is
1286 // from the RHS interval, we can use its value #.
1287 if (!CP.isCoalescable(VNI->getCopy()))
1290 // Figure out the value # from the RHS.
1291 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1292 // The copy could be to an aliased physreg.
1294 LHSValsDefinedFromRHS[VNI] = lr->valno;
1297 // Loop over the value numbers of the RHS, seeing if any are defined from
1299 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1302 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1305 // Never join with a register that has EarlyClobber redefs.
1306 if (VNI->hasRedefByEC())
1309 // DstReg is known to be a register in the RHS interval. If the src is
1310 // from the LHS interval, we can use its value #.
1311 if (!CP.isCoalescable(VNI->getCopy()))
1314 // Figure out the value # from the LHS.
1315 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1316 // The copy could be to an aliased physreg.
1318 RHSValsDefinedFromLHS[VNI] = lr->valno;
1321 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1322 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1323 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1325 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1328 unsigned VN = VNI->id;
1329 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1331 ComputeUltimateVN(VNI, NewVNInfo,
1332 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1333 LHSValNoAssignments, RHSValNoAssignments);
1335 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1338 unsigned VN = VNI->id;
1339 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1341 // If this value number isn't a copy from the LHS, it's a new number.
1342 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1343 NewVNInfo.push_back(VNI);
1344 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1348 ComputeUltimateVN(VNI, NewVNInfo,
1349 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1350 RHSValNoAssignments, LHSValNoAssignments);
1353 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1354 // interval lists to see if these intervals are coalescable.
1355 LiveInterval::const_iterator I = LHS.begin();
1356 LiveInterval::const_iterator IE = LHS.end();
1357 LiveInterval::const_iterator J = RHS.begin();
1358 LiveInterval::const_iterator JE = RHS.end();
1360 // Skip ahead until the first place of potential sharing.
1361 if (I != IE && J != JE) {
1362 if (I->start < J->start) {
1363 I = std::upper_bound(I, IE, J->start);
1364 if (I != LHS.begin()) --I;
1365 } else if (J->start < I->start) {
1366 J = std::upper_bound(J, JE, I->start);
1367 if (J != RHS.begin()) --J;
1371 while (I != IE && J != JE) {
1372 // Determine if these two live ranges overlap.
1374 if (I->start < J->start) {
1375 Overlaps = I->end > J->start;
1377 Overlaps = J->end > I->start;
1380 // If so, check value # info to determine if they are really different.
1382 // If the live range overlap will map to the same value number in the
1383 // result liverange, we can still coalesce them. If not, we can't.
1384 if (LHSValNoAssignments[I->valno->id] !=
1385 RHSValNoAssignments[J->valno->id])
1387 // If it's re-defined by an early clobber somewhere in the live range,
1388 // then conservatively abort coalescing.
1389 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1393 if (I->end < J->end)
1399 // Update kill info. Some live ranges are extended due to copy coalescing.
1400 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1401 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1402 VNInfo *VNI = I->first;
1403 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1404 if (VNI->hasPHIKill())
1405 NewVNInfo[LHSValID]->setHasPHIKill(true);
1408 // Update kill info. Some live ranges are extended due to copy coalescing.
1409 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1410 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1411 VNInfo *VNI = I->first;
1412 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1413 if (VNI->hasPHIKill())
1414 NewVNInfo[RHSValID]->setHasPHIKill(true);
1417 if (LHSValNoAssignments.empty())
1418 LHSValNoAssignments.push_back(-1);
1419 if (RHSValNoAssignments.empty())
1420 RHSValNoAssignments.push_back(-1);
1422 // If we get here, we know that we can coalesce the live ranges. Ask the
1423 // intervals to coalesce themselves now.
1424 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1430 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1431 // depth of the basic block (the unsigned), and then on the MBB number.
1432 struct DepthMBBCompare {
1433 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1434 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1435 // Deeper loops first
1436 if (LHS.first != RHS.first)
1437 return LHS.first > RHS.first;
1439 // Prefer blocks that are more connected in the CFG. This takes care of
1440 // the most difficult copies first while intervals are short.
1441 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1442 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1446 // As a last resort, sort by block number.
1447 return LHS.second->getNumber() < RHS.second->getNumber();
1452 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1453 std::vector<CopyRec> &TryAgain) {
1454 DEBUG(dbgs() << MBB->getName() << ":\n");
1456 SmallVector<CopyRec, 8> VirtCopies;
1457 SmallVector<CopyRec, 8> PhysCopies;
1458 SmallVector<CopyRec, 8> ImpDefCopies;
1459 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1461 MachineInstr *Inst = MII++;
1463 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1464 unsigned SrcReg, DstReg;
1465 if (Inst->isCopy()) {
1466 DstReg = Inst->getOperand(0).getReg();
1467 SrcReg = Inst->getOperand(1).getReg();
1468 } else if (Inst->isSubregToReg()) {
1469 DstReg = Inst->getOperand(0).getReg();
1470 SrcReg = Inst->getOperand(2).getReg();
1474 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1475 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1476 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1477 ImpDefCopies.push_back(CopyRec(Inst, 0));
1478 else if (SrcIsPhys || DstIsPhys)
1479 PhysCopies.push_back(CopyRec(Inst, 0));
1481 VirtCopies.push_back(CopyRec(Inst, 0));
1484 // Try coalescing implicit copies and insert_subreg <undef> first,
1485 // followed by copies to / from physical registers, then finally copies
1486 // from virtual registers to virtual registers.
1487 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1488 CopyRec &TheCopy = ImpDefCopies[i];
1490 if (!JoinCopy(TheCopy, Again))
1492 TryAgain.push_back(TheCopy);
1494 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1495 CopyRec &TheCopy = PhysCopies[i];
1497 if (!JoinCopy(TheCopy, Again))
1499 TryAgain.push_back(TheCopy);
1501 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1502 CopyRec &TheCopy = VirtCopies[i];
1504 if (!JoinCopy(TheCopy, Again))
1506 TryAgain.push_back(TheCopy);
1510 void SimpleRegisterCoalescing::joinIntervals() {
1511 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1513 std::vector<CopyRec> TryAgainList;
1514 if (loopInfo->empty()) {
1515 // If there are no loops in the function, join intervals in function order.
1516 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1518 CopyCoalesceInMBB(I, TryAgainList);
1520 // Otherwise, join intervals in inner loops before other intervals.
1521 // Unfortunately we can't just iterate over loop hierarchy here because
1522 // there may be more MBB's than BB's. Collect MBB's for sorting.
1524 // Join intervals in the function prolog first. We want to join physical
1525 // registers with virtual registers before the intervals got too long.
1526 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1527 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1528 MachineBasicBlock *MBB = I;
1529 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1532 // Sort by loop depth.
1533 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1535 // Finally, join intervals in loop nest order.
1536 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1537 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1540 // Joining intervals can allow other intervals to be joined. Iteratively join
1541 // until we make no progress.
1542 bool ProgressMade = true;
1543 while (ProgressMade) {
1544 ProgressMade = false;
1546 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1547 CopyRec &TheCopy = TryAgainList[i];
1552 bool Success = JoinCopy(TheCopy, Again);
1553 if (Success || !Again) {
1554 TheCopy.MI = 0; // Mark this one as done.
1555 ProgressMade = true;
1561 /// Return true if the two specified registers belong to different register
1562 /// classes. The registers may be either phys or virt regs.
1564 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1565 unsigned RegB) const {
1566 // Get the register classes for the first reg.
1567 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1568 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1569 "Shouldn't consider two physregs!");
1570 return !mri_->getRegClass(RegB)->contains(RegA);
1573 // Compare against the regclass for the second reg.
1574 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1575 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1576 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1577 return RegClassA != RegClassB;
1579 return !RegClassA->contains(RegB);
1582 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1583 /// between cycles Start and End or NULL if there are no uses.
1585 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1588 SlotIndex &UseIdx) const{
1589 UseIdx = SlotIndex();
1590 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1591 MachineOperand *LastUse = NULL;
1592 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1593 E = mri_->use_nodbg_end(); I != E; ++I) {
1594 MachineOperand &Use = I.getOperand();
1595 MachineInstr *UseMI = Use.getParent();
1596 if (UseMI->isIdentityCopy())
1598 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1599 if (Idx >= Start && Idx < End && (!UseIdx.isValid() || Idx >= UseIdx)) {
1601 UseIdx = Idx.getUseIndex();
1607 SlotIndex s = Start;
1608 SlotIndex e = End.getPrevSlot().getBaseIndex();
1610 // Skip deleted instructions
1611 MachineInstr *MI = li_->getInstructionFromIndex(e);
1612 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1613 e = e.getPrevIndex();
1614 MI = li_->getInstructionFromIndex(e);
1616 if (e < s || MI == NULL)
1619 // Ignore identity copies.
1620 if (!MI->isIdentityCopy())
1621 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1622 MachineOperand &Use = MI->getOperand(i);
1623 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1624 tri_->regsOverlap(Use.getReg(), Reg)) {
1625 UseIdx = e.getUseIndex();
1630 e = e.getPrevIndex();
1636 void SimpleRegisterCoalescing::releaseMemory() {
1637 JoinedCopies.clear();
1638 ReMatCopies.clear();
1642 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1644 mri_ = &fn.getRegInfo();
1645 tm_ = &fn.getTarget();
1646 tri_ = tm_->getRegisterInfo();
1647 tii_ = tm_->getInstrInfo();
1648 li_ = &getAnalysis<LiveIntervals>();
1649 ldv_ = &getAnalysis<LiveDebugVariables>();
1650 AA = &getAnalysis<AliasAnalysis>();
1651 loopInfo = &getAnalysis<MachineLoopInfo>();
1653 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1654 << "********** Function: "
1655 << ((Value*)mf_->getFunction())->getName() << '\n');
1657 if (VerifyCoalescing)
1658 mf_->verify(this, "Before register coalescing");
1660 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1661 E = tri_->regclass_end(); I != E; ++I)
1662 allocatableRCRegs_.insert(std::make_pair(*I,
1663 tri_->getAllocatableSet(fn, *I)));
1665 // Join (coalesce) intervals if requested.
1666 if (EnableJoining) {
1669 dbgs() << "********** INTERVALS POST JOINING **********\n";
1670 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1672 I->second->print(dbgs(), tri_);
1678 // Perform a final pass over the instructions and compute spill weights
1679 // and remove identity moves.
1680 SmallVector<unsigned, 4> DeadDefs;
1681 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1682 mbbi != mbbe; ++mbbi) {
1683 MachineBasicBlock* mbb = mbbi;
1684 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1686 MachineInstr *MI = mii;
1687 if (JoinedCopies.count(MI)) {
1688 // Delete all coalesced copies.
1689 bool DoDelete = true;
1690 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1691 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1692 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1693 MI->getNumOperands() > 2)
1694 // Do not delete extract_subreg, insert_subreg of physical
1695 // registers unless the definition is dead. e.g.
1696 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1697 // or else the scavenger may complain. LowerSubregs will
1698 // delete them later.
1701 if (MI->allDefsAreDead()) {
1702 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1703 li_->hasInterval(SrcReg))
1704 li_->shrinkToUses(&li_->getInterval(SrcReg));
1708 // We need the instruction to adjust liveness, so make it a KILL.
1709 if (MI->isSubregToReg()) {
1710 MI->RemoveOperand(3);
1711 MI->RemoveOperand(1);
1713 MI->setDesc(tii_->get(TargetOpcode::KILL));
1714 mii = llvm::next(mii);
1716 li_->RemoveMachineInstrFromMaps(MI);
1717 mii = mbbi->erase(mii);
1723 // Now check if this is a remat'ed def instruction which is now dead.
1724 if (ReMatDefs.count(MI)) {
1726 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1727 const MachineOperand &MO = MI->getOperand(i);
1730 unsigned Reg = MO.getReg();
1733 if (TargetRegisterInfo::isVirtualRegister(Reg))
1734 DeadDefs.push_back(Reg);
1737 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1738 !mri_->use_nodbg_empty(Reg)) {
1744 while (!DeadDefs.empty()) {
1745 unsigned DeadDef = DeadDefs.back();
1746 DeadDefs.pop_back();
1747 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1749 li_->RemoveMachineInstrFromMaps(mii);
1750 mii = mbbi->erase(mii);
1758 // Check for now unnecessary kill flags.
1759 if (li_->isNotInMIMap(MI)) continue;
1760 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1761 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1762 MachineOperand &MO = MI->getOperand(i);
1763 if (!MO.isReg() || !MO.isKill()) continue;
1764 unsigned reg = MO.getReg();
1765 if (!reg || !li_->hasInterval(reg)) continue;
1766 if (!li_->getInterval(reg).killedAt(DefIdx)) {
1767 MO.setIsKill(false);
1770 // When leaving a kill flag on a physreg, check if any subregs should
1772 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1774 for (const unsigned *SR = tri_->getSubRegisters(reg);
1775 unsigned S = *SR; ++SR)
1776 if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1777 MI->addRegisterDefined(S, tri_);
1783 DEBUG(ldv_->dump());
1784 if (VerifyCoalescing)
1785 mf_->verify(this, "After register coalescing");
1789 /// print - Implement the dump method.
1790 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1794 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1795 return new SimpleRegisterCoalescing();
1798 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1799 DEFINING_FILE_FOR(SimpleRegisterCoalescing)