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 DisablePhysicalJoin("disable-physical-join",
65 cl::desc("Avoid coalescing physical register copies"),
66 cl::init(false), cl::Hidden);
68 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing, RegisterCoalescer,
69 "simple-register-coalescing", "Simple Register Coalescing",
71 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
72 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
73 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
74 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
75 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
76 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
77 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
78 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
79 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing, RegisterCoalescer,
80 "simple-register-coalescing", "Simple Register Coalescing",
83 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
85 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.addRequired<AliasAnalysis>();
88 AU.addRequired<LiveIntervals>();
89 AU.addPreserved<LiveIntervals>();
90 AU.addRequired<LiveDebugVariables>();
91 AU.addPreserved<LiveDebugVariables>();
92 AU.addPreserved<SlotIndexes>();
93 AU.addRequired<MachineLoopInfo>();
94 AU.addPreserved<MachineLoopInfo>();
95 AU.addPreservedID(MachineDominatorsID);
96 AU.addPreservedID(StrongPHIEliminationID);
97 AU.addPreservedID(PHIEliminationID);
98 AU.addPreservedID(TwoAddressInstructionPassID);
99 MachineFunctionPass::getAnalysisUsage(AU);
102 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
103 /// being the source and IntB being the dest, thus this defines a value number
104 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
105 /// see if we can merge these two pieces of B into a single value number,
106 /// eliminating a copy. For example:
110 /// B1 = A3 <- this copy
112 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
113 /// value number to be replaced with B0 (which simplifies the B liveinterval).
115 /// This returns true if an interval was modified.
117 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
118 MachineInstr *CopyMI) {
119 // Bail if there is no dst interval - can happen when merging physical subreg
121 if (!li_->hasInterval(CP.getDstReg()))
125 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
127 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
128 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
130 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
131 // the example above.
132 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
133 if (BLR == IntB.end()) return false;
134 VNInfo *BValNo = BLR->valno;
136 // Get the location that B is defined at. Two options: either this value has
137 // an unknown definition point or it is defined at CopyIdx. If unknown, we
139 if (!BValNo->isDefByCopy()) return false;
140 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
142 // AValNo is the value number in A that defines the copy, A3 in the example.
143 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
144 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
145 // The live range might not exist after fun with physreg coalescing.
146 if (ALR == IntA.end()) return false;
147 VNInfo *AValNo = ALR->valno;
148 // If it's re-defined by an early clobber somewhere in the live range, then
149 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
151 // 172 %ECX<def> = MOV32rr %reg1039<kill>
152 // 180 INLINEASM <es:subl $5,$1
153 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
155 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
156 // 188 %EAX<def> = MOV32rr %EAX<kill>
157 // 196 %ECX<def> = MOV32rr %ECX<kill>
158 // 204 %ECX<def> = MOV32rr %ECX<kill>
159 // 212 %EAX<def> = MOV32rr %EAX<kill>
160 // 220 %EAX<def> = MOV32rr %EAX
161 // 228 %reg1039<def> = MOV32rr %ECX<kill>
162 // The early clobber operand ties ECX input to the ECX def.
164 // The live interval of ECX is represented as this:
165 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
166 // The coalescer has no idea there was a def in the middle of [174,230].
167 if (AValNo->hasRedefByEC())
170 // If AValNo is defined as a copy from IntB, we can potentially process this.
171 // Get the instruction that defines this value number.
172 if (!CP.isCoalescable(AValNo->getCopy()))
175 // Get the LiveRange in IntB that this value number starts with.
176 LiveInterval::iterator ValLR =
177 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
178 if (ValLR == IntB.end())
181 // Make sure that the end of the live range is inside the same block as
183 MachineInstr *ValLREndInst =
184 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
185 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
188 // Okay, we now know that ValLR ends in the same block that the CopyMI
189 // live-range starts. If there are no intervening live ranges between them in
190 // IntB, we can merge them.
191 if (ValLR+1 != BLR) return false;
193 // If a live interval is a physical register, conservatively check if any
194 // of its sub-registers is overlapping the live interval of the virtual
195 // register. If so, do not coalesce.
196 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
197 *tri_->getSubRegisters(IntB.reg)) {
198 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
199 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
201 dbgs() << "\t\tInterfere with sub-register ";
202 li_->getInterval(*SR).print(dbgs(), tri_);
209 dbgs() << "Extending: ";
210 IntB.print(dbgs(), tri_);
213 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
214 // We are about to delete CopyMI, so need to remove it as the 'instruction
215 // that defines this value #'. Update the valnum with the new defining
217 BValNo->def = FillerStart;
220 // Okay, we can merge them. We need to insert a new liverange:
221 // [ValLR.end, BLR.begin) of either value number, then we merge the
222 // two value numbers.
223 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
225 // If the IntB live range is assigned to a physical register, and if that
226 // physreg has sub-registers, update their live intervals as well.
227 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
228 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
229 if (!li_->hasInterval(*SR))
231 LiveInterval &SRLI = li_->getInterval(*SR);
232 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
233 SRLI.getNextValue(FillerStart, 0,
234 li_->getVNInfoAllocator())));
238 // Okay, merge "B1" into the same value number as "B0".
239 if (BValNo != ValLR->valno) {
240 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
243 dbgs() << " result = ";
244 IntB.print(dbgs(), tri_);
248 // If the source instruction was killing the source register before the
249 // merge, unset the isKill marker given the live range has been extended.
250 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
252 ValLREndInst->getOperand(UIdx).setIsKill(false);
255 // If the copy instruction was killing the destination register before the
256 // merge, find the last use and trim the live range. That will also add the
258 if (ALR->end == CopyIdx)
259 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
265 /// HasOtherReachingDefs - Return true if there are definitions of IntB
266 /// other than BValNo val# that can reach uses of AValno val# of IntA.
267 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
271 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
273 if (AI->valno != AValNo) continue;
274 LiveInterval::Ranges::iterator BI =
275 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
276 if (BI != IntB.ranges.begin())
278 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
279 if (BI->valno == BValNo)
281 if (BI->start <= AI->start && BI->end > AI->start)
283 if (BI->start > AI->start && BI->start < AI->end)
290 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
291 /// IntA being the source and IntB being the dest, thus this defines a value
292 /// number in IntB. If the source value number (in IntA) is defined by a
293 /// commutable instruction and its other operand is coalesced to the copy dest
294 /// register, see if we can transform the copy into a noop by commuting the
295 /// definition. For example,
297 /// A3 = op A2 B0<kill>
299 /// B1 = A3 <- this copy
301 /// = op A3 <- more uses
305 /// B2 = op B0 A2<kill>
307 /// B1 = B2 <- now an identify copy
309 /// = op B2 <- more uses
311 /// This returns true if an interval was modified.
313 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
314 MachineInstr *CopyMI) {
315 // FIXME: For now, only eliminate the copy by commuting its def when the
316 // source register is a virtual register. We want to guard against cases
317 // where the copy is a back edge copy and commuting the def lengthen the
318 // live interval of the source register to the entire loop.
319 if (CP.isPhys() && CP.isFlipped())
322 // Bail if there is no dst interval.
323 if (!li_->hasInterval(CP.getDstReg()))
326 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
329 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
331 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
333 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
334 // the example above.
335 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
336 if (!BValNo || !BValNo->isDefByCopy())
339 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
341 // AValNo is the value number in A that defines the copy, A3 in the example.
342 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
343 assert(AValNo && "COPY source not live");
345 // If other defs can reach uses of this def, then it's not safe to perform
347 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
349 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
352 const TargetInstrDesc &TID = DefMI->getDesc();
353 if (!TID.isCommutable())
355 // If DefMI is a two-address instruction then commuting it will change the
356 // destination register.
357 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
358 assert(DefIdx != -1);
360 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
362 unsigned Op1, Op2, NewDstIdx;
363 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
367 else if (Op2 == UseOpIdx)
372 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
373 unsigned NewReg = NewDstMO.getReg();
374 if (NewReg != IntB.reg || !NewDstMO.isKill())
377 // Make sure there are no other definitions of IntB that would reach the
378 // uses which the new definition can reach.
379 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
382 // Abort if the aliases of IntB.reg have values that are not simply the
383 // clobbers from the superreg.
384 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
385 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
386 if (li_->hasInterval(*AS) &&
387 HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
390 // If some of the uses of IntA.reg is already coalesced away, return false.
391 // It's not possible to determine whether it's safe to perform the coalescing.
392 for (MachineRegisterInfo::use_nodbg_iterator UI =
393 mri_->use_nodbg_begin(IntA.reg),
394 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
395 MachineInstr *UseMI = &*UI;
396 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
397 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
398 if (ULR == IntA.end())
400 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
404 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
407 // At this point we have decided that it is legal to do this
408 // transformation. Start by commuting the instruction.
409 MachineBasicBlock *MBB = DefMI->getParent();
410 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
413 if (NewMI != DefMI) {
414 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
415 MBB->insert(DefMI, NewMI);
418 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
419 NewMI->getOperand(OpIdx).setIsKill();
421 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
430 // Update uses of IntA of the specific Val# with IntB.
431 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
432 UE = mri_->use_end(); UI != UE;) {
433 MachineOperand &UseMO = UI.getOperand();
434 MachineInstr *UseMI = &*UI;
436 if (JoinedCopies.count(UseMI))
438 if (UseMI->isDebugValue()) {
439 // FIXME These don't have an instruction index. Not clear we have enough
440 // info to decide whether to do this replacement or not. For now do it.
441 UseMO.setReg(NewReg);
444 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
445 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
446 if (ULR == IntA.end() || ULR->valno != AValNo)
448 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
449 UseMO.substPhysReg(NewReg, *tri_);
451 UseMO.setReg(NewReg);
454 if (!UseMI->isCopy())
456 if (UseMI->getOperand(0).getReg() != IntB.reg ||
457 UseMI->getOperand(0).getSubReg())
460 // This copy will become a noop. If it's defining a new val#, merge it into
462 SlotIndex DefIdx = UseIdx.getDefIndex();
463 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
466 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
467 assert(DVNI->def == DefIdx);
468 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
469 JoinedCopies.insert(UseMI);
472 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
474 VNInfo *ValNo = BValNo;
475 ValNo->def = AValNo->def;
477 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
479 if (AI->valno != AValNo) continue;
480 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
482 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
484 IntA.removeValNo(AValNo);
485 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
490 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
491 /// fallthoughs to SuccMBB.
492 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
493 MachineBasicBlock *SuccMBB,
494 const TargetInstrInfo *tii_) {
497 MachineBasicBlock *TBB = 0, *FBB = 0;
498 SmallVector<MachineOperand, 4> Cond;
499 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
500 MBB->isSuccessor(SuccMBB);
503 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
504 /// from a physical register live interval as well as from the live intervals
505 /// of its sub-registers.
506 static void removeRange(LiveInterval &li,
507 SlotIndex Start, SlotIndex End,
508 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
509 li.removeRange(Start, End, true);
510 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
511 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
512 if (!li_->hasInterval(*SR))
514 LiveInterval &sli = li_->getInterval(*SR);
515 SlotIndex RemoveStart = Start;
516 SlotIndex RemoveEnd = Start;
518 while (RemoveEnd != End) {
519 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
522 RemoveEnd = (LR->end < End) ? LR->end : End;
523 sli.removeRange(RemoveStart, RemoveEnd, true);
524 RemoveStart = RemoveEnd;
530 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
531 /// as the copy instruction, trim the live interval to the last use and return
534 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
535 MachineBasicBlock *CopyMBB,
537 const LiveRange *LR) {
538 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
539 SlotIndex LastUseIdx;
540 MachineOperand *LastUse =
541 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
543 MachineInstr *LastUseMI = LastUse->getParent();
544 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
551 // r1025<dead> = r1024<kill>
552 if (MBBStart < LR->end)
553 removeRange(li, MBBStart, LR->end, li_, tri_);
557 // There are uses before the copy, just shorten the live range to the end
559 LastUse->setIsKill();
560 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
561 if (LastUseMI->isCopy()) {
562 MachineOperand &DefMO = LastUseMI->getOperand(0);
563 if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
570 if (LR->start <= MBBStart && LR->end > MBBStart) {
571 if (LR->start == li_->getZeroIndex()) {
572 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
573 // Live-in to the function but dead. Remove it from entry live-in set.
574 mf_->begin()->removeLiveIn(li.reg);
576 // FIXME: Shorten intervals in BBs that reaches this BB.
582 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
583 /// computation, replace the copy by rematerialize the definition.
584 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
587 MachineInstr *CopyMI) {
588 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
589 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
590 assert(SrcLR != SrcInt.end() && "Live range not found!");
591 VNInfo *ValNo = SrcLR->valno;
592 // If other defs can reach uses of this def, then it's not safe to perform
594 if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
596 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
599 assert(DefMI && "Defining instruction disappeared");
600 const TargetInstrDesc &TID = DefMI->getDesc();
601 if (!TID.isAsCheapAsAMove())
603 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
605 bool SawStore = false;
606 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
608 if (TID.getNumDefs() != 1)
610 if (!DefMI->isImplicitDef()) {
611 // Make sure the copy destination register class fits the instruction
612 // definition register class. The mismatch can happen as a result of earlier
613 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
614 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
615 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
616 if (mri_->getRegClass(DstReg) != RC)
618 } else if (!RC->contains(DstReg))
622 // If destination register has a sub-register index on it, make sure it
623 // matches the instruction register class.
625 const TargetInstrDesc &TID = DefMI->getDesc();
626 if (TID.getNumDefs() != 1)
628 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
629 const TargetRegisterClass *DstSubRC =
630 DstRC->getSubRegisterRegClass(DstSubIdx);
631 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
634 else if (DefRC != DstSubRC)
638 RemoveCopyFlag(DstReg, CopyMI);
640 // If copy kills the source register, find the last use and propagate
642 bool checkForDeadDef = false;
643 MachineBasicBlock *MBB = CopyMI->getParent();
644 if (SrcLR->end == CopyIdx.getDefIndex())
645 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
646 checkForDeadDef = true;
649 MachineBasicBlock::iterator MII =
650 llvm::next(MachineBasicBlock::iterator(CopyMI));
651 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
652 MachineInstr *NewMI = prior(MII);
654 if (checkForDeadDef) {
655 // PR4090 fix: Trim interval failed because there was no use of the
656 // source interval in this MBB. If the def is in this MBB too then we
657 // should mark it dead:
658 if (DefMI->getParent() == MBB) {
659 DefMI->addRegisterDead(SrcInt.reg, tri_);
660 SrcLR->end = SrcLR->start.getNextSlot();
664 // CopyMI may have implicit operands, transfer them over to the newly
665 // rematerialized instruction. And update implicit def interval valnos.
666 for (unsigned i = CopyMI->getDesc().getNumOperands(),
667 e = CopyMI->getNumOperands(); i != e; ++i) {
668 MachineOperand &MO = CopyMI->getOperand(i);
669 if (MO.isReg() && MO.isImplicit())
670 NewMI->addOperand(MO);
672 RemoveCopyFlag(MO.getReg(), CopyMI);
675 NewMI->copyImplicitOps(CopyMI);
676 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
677 CopyMI->eraseFromParent();
678 ReMatCopies.insert(CopyMI);
679 ReMatDefs.insert(DefMI);
680 DEBUG(dbgs() << "Remat: " << *NewMI);
685 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
686 /// update the subregister number if it is not zero. If DstReg is a
687 /// physical register and the existing subregister number of the def / use
688 /// being updated is not zero, make sure to set it to the correct physical
691 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
692 bool DstIsPhys = CP.isPhys();
693 unsigned SrcReg = CP.getSrcReg();
694 unsigned DstReg = CP.getDstReg();
695 unsigned SubIdx = CP.getSubIdx();
697 // Update LiveDebugVariables.
698 ldv_->renameRegister(SrcReg, DstReg, SubIdx);
700 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
701 MachineInstr *UseMI = I.skipInstruction();) {
702 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
705 if (UseMI->isCopy() &&
706 !UseMI->getOperand(1).getSubReg() &&
707 !UseMI->getOperand(0).getSubReg() &&
708 UseMI->getOperand(1).getReg() == SrcReg &&
709 UseMI->getOperand(0).getReg() != SrcReg &&
710 UseMI->getOperand(0).getReg() != DstReg &&
711 !JoinedCopies.count(UseMI) &&
712 ReMaterializeTrivialDef(li_->getInterval(SrcReg),
713 UseMI->getOperand(0).getReg(), 0, UseMI))
717 SmallVector<unsigned,8> Ops;
719 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
720 bool Kills = false, Deads = false;
722 // Replace SrcReg with DstReg in all UseMI operands.
723 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
724 MachineOperand &MO = UseMI->getOperand(Ops[i]);
725 Kills |= MO.isKill();
726 Deads |= MO.isDead();
729 MO.substPhysReg(DstReg, *tri_);
731 MO.substVirtReg(DstReg, SubIdx, *tri_);
734 // This instruction is a copy that will be removed.
735 if (JoinedCopies.count(UseMI))
739 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
740 // read-modify-write of DstReg.
742 UseMI->addRegisterDead(DstReg, tri_);
743 else if (!Reads && Writes)
744 UseMI->addRegisterDefined(DstReg, tri_);
746 // Kill flags apply to the whole physical register.
747 if (DstIsPhys && Kills)
748 UseMI->addRegisterKilled(DstReg, tri_);
752 dbgs() << "\t\tupdated: ";
753 if (!UseMI->isDebugValue())
754 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
760 /// removeIntervalIfEmpty - Check if the live interval of a physical register
761 /// is empty, if so remove it and also remove the empty intervals of its
762 /// sub-registers. Return true if live interval is removed.
763 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
764 const TargetRegisterInfo *tri_) {
766 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
767 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
768 if (!li_->hasInterval(*SR))
770 LiveInterval &sli = li_->getInterval(*SR);
772 li_->removeInterval(*SR);
774 li_->removeInterval(li.reg);
780 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
781 /// Return true if live interval is removed.
782 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
783 MachineInstr *CopyMI) {
784 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
785 LiveInterval::iterator MLR =
786 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
788 return false; // Already removed by ShortenDeadCopySrcLiveRange.
789 SlotIndex RemoveStart = MLR->start;
790 SlotIndex RemoveEnd = MLR->end;
791 SlotIndex DefIdx = CopyIdx.getDefIndex();
792 // Remove the liverange that's defined by this.
793 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
794 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
795 return removeIntervalIfEmpty(li, li_, tri_);
800 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
801 /// the val# it defines. If the live interval becomes empty, remove it as well.
802 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
803 MachineInstr *DefMI) {
804 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
805 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
806 if (DefIdx != MLR->valno->def)
808 li.removeValNo(MLR->valno);
809 return removeIntervalIfEmpty(li, li_, tri_);
812 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
813 const MachineInstr *CopyMI) {
814 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
815 if (li_->hasInterval(DstReg)) {
816 LiveInterval &LI = li_->getInterval(DstReg);
817 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
818 if (LR->valno->def == DefIdx)
819 LR->valno->setCopy(0);
821 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
823 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
824 if (!li_->hasInterval(*AS))
826 LiveInterval &LI = li_->getInterval(*AS);
827 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
828 if (LR->valno->def == DefIdx)
829 LR->valno->setCopy(0);
833 /// PropagateDeadness - Propagate the dead marker to the instruction which
834 /// defines the val#.
835 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
836 SlotIndex &LRStart, LiveIntervals *li_,
837 const TargetRegisterInfo* tri_) {
838 MachineInstr *DefMI =
839 li_->getInstructionFromIndex(LRStart.getDefIndex());
840 if (DefMI && DefMI != CopyMI) {
841 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
843 DefMI->getOperand(DeadIdx).setIsDead();
845 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
846 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
847 LRStart = LRStart.getNextSlot();
851 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
852 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
853 /// ends the live range there. If there isn't another use, then this live range
854 /// is dead. Return true if live interval is removed.
856 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
857 MachineInstr *CopyMI) {
858 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
859 if (CopyIdx == SlotIndex()) {
860 // FIXME: special case: function live in. It can be a general case if the
861 // first instruction index starts at > 0 value.
862 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
863 // Live-in to the function but dead. Remove it from entry live-in set.
864 if (mf_->begin()->isLiveIn(li.reg))
865 mf_->begin()->removeLiveIn(li.reg);
866 if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
867 removeRange(li, LR->start, LR->end, li_, tri_);
868 return removeIntervalIfEmpty(li, li_, tri_);
871 LiveInterval::iterator LR =
872 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
874 // Livein but defined by a phi.
877 SlotIndex RemoveStart = LR->start;
878 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
879 if (LR->end > RemoveEnd)
880 // More uses past this copy? Nothing to do.
883 // If there is a last use in the same bb, we can't remove the live range.
884 // Shorten the live interval and return.
885 MachineBasicBlock *CopyMBB = CopyMI->getParent();
886 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
889 // There are other kills of the val#. Nothing to do.
890 if (!li.isOnlyLROfValNo(LR))
893 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
894 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
895 // If the live range starts in another mbb and the copy mbb is not a fall
896 // through mbb, then we can only cut the range from the beginning of the
898 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
900 if (LR->valno->def == RemoveStart) {
901 // If the def MI defines the val# and this copy is the only kill of the
902 // val#, then propagate the dead marker.
903 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
907 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
908 return removeIntervalIfEmpty(li, li_, tri_);
912 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
913 /// two virtual registers from different register classes.
915 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
917 const TargetRegisterClass *SrcRC,
918 const TargetRegisterClass *DstRC,
919 const TargetRegisterClass *NewRC) {
920 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
921 // This heuristics is good enough in practice, but it's obviously not *right*.
922 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
923 // out all but the most restrictive register classes.
924 if (NewRCCount > 4 ||
925 // Early exit if the function is fairly small, coalesce aggressively if
926 // that's the case. For really special register classes with 3 or
927 // fewer registers, be a bit more careful.
928 (li_->getFuncInstructionCount() / NewRCCount) < 8)
930 LiveInterval &SrcInt = li_->getInterval(SrcReg);
931 LiveInterval &DstInt = li_->getInterval(DstReg);
932 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
933 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
934 if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
936 // Estimate *register use density*. If it doubles or more, abort.
937 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
938 mri_->use_nodbg_end());
939 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
940 mri_->use_nodbg_end());
941 unsigned NewUses = SrcUses + DstUses;
942 unsigned NewSize = SrcSize + DstSize;
943 if (SrcRC != NewRC && SrcSize > NewRCCount) {
944 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
945 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
948 if (DstRC != NewRC && DstSize > NewRCCount) {
949 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
950 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
957 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
958 /// which are the src/dst of the copy instruction CopyMI. This returns true
959 /// if the copy was successfully coalesced away. If it is not currently
960 /// possible to coalesce this interval, but it may be possible if other
961 /// things get coalesced, then it returns true by reference in 'Again'.
962 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
963 MachineInstr *CopyMI = TheCopy.MI;
966 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
967 return false; // Already done.
969 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
971 CoalescerPair CP(*tii_, *tri_);
972 if (!CP.setRegisters(CopyMI)) {
973 DEBUG(dbgs() << "\tNot coalescable.\n");
977 // If they are already joined we continue.
978 if (CP.getSrcReg() == CP.getDstReg()) {
979 DEBUG(dbgs() << "\tCopy already coalesced.\n");
980 return false; // Not coalescable.
983 if (DisablePhysicalJoin && CP.isPhys()) {
984 DEBUG(dbgs() << "\tPhysical joins disabled.\n");
988 DEBUG(dbgs() << "\tConsidering merging %reg" << CP.getSrcReg());
992 DEBUG(dbgs() <<" with physreg %" << tri_->getName(CP.getDstReg()) << "\n");
993 // Only coalesce to allocatable physreg.
994 if (!li_->isAllocatable(CP.getDstReg())) {
995 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
996 return false; // Not coalescable.
1000 dbgs() << " with reg%" << CP.getDstReg();
1002 dbgs() << ":" << tri_->getSubRegIndexName(CP.getSubIdx());
1003 dbgs() << " to " << CP.getNewRC()->getName() << "\n";
1006 // Avoid constraining virtual register regclass too much.
1007 if (CP.isCrossClass()) {
1008 if (DisableCrossClassJoin) {
1009 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1012 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1013 mri_->getRegClass(CP.getSrcReg()),
1014 mri_->getRegClass(CP.getDstReg()),
1016 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1017 << CP.getNewRC()->getName() << ".\n");
1018 Again = true; // May be possible to coalesce later.
1023 // When possible, let DstReg be the larger interval.
1024 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1025 li_->getInterval(CP.getDstReg()).ranges.size())
1029 // We need to be careful about coalescing a source physical register with a
1030 // virtual register. Once the coalescing is done, it cannot be broken and
1031 // these are not spillable! If the destination interval uses are far away,
1032 // think twice about coalescing them!
1033 // FIXME: Why are we skipping this test for partial copies?
1034 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1035 if (!CP.isPartial() && CP.isPhys()) {
1036 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1038 // Don't join with physregs that have a ridiculous number of live
1039 // ranges. The data structure performance is really bad when that
1041 if (li_->hasInterval(CP.getDstReg()) &&
1042 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1045 << "\tPhysical register live interval too complicated, abort!\n");
1049 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1050 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1051 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1052 if (Length > Threshold &&
1053 std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1054 mri_->use_nodbg_end()) * Threshold < Length) {
1055 // Before giving up coalescing, if definition of source is defined by
1056 // trivial computation, try rematerializing it.
1057 if (!CP.isFlipped() &&
1058 ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1062 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1063 Again = true; // May be possible to coalesce later.
1068 // Okay, attempt to join these two intervals. On failure, this returns false.
1069 // Otherwise, if one of the intervals being joined is a physreg, this method
1070 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1071 // been modified, so we can use this information below to update aliases.
1072 if (!JoinIntervals(CP)) {
1073 // Coalescing failed.
1075 // If definition of source is defined by trivial computation, try
1076 // rematerializing it.
1077 if (!CP.isFlipped() &&
1078 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1079 CP.getDstReg(), 0, CopyMI))
1082 // If we can eliminate the copy without merging the live ranges, do so now.
1083 if (!CP.isPartial()) {
1084 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1085 RemoveCopyByCommutingDef(CP, CopyMI)) {
1086 JoinedCopies.insert(CopyMI);
1087 DEBUG(dbgs() << "\tTrivial!\n");
1092 // Otherwise, we are unable to join the intervals.
1093 DEBUG(dbgs() << "\tInterference!\n");
1094 Again = true; // May be possible to coalesce later.
1098 // Coalescing to a virtual register that is of a sub-register class of the
1099 // other. Make sure the resulting register is set to the right register class.
1100 if (CP.isCrossClass()) {
1102 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1105 // Remember to delete the copy instruction.
1106 JoinedCopies.insert(CopyMI);
1108 UpdateRegDefsUses(CP);
1110 // If we have extended the live range of a physical register, make sure we
1111 // update live-in lists as well.
1113 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1114 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1115 // ranges for this, and they are preserved.
1116 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1117 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1119 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1120 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1121 MachineBasicBlock &block = *BlockSeq[idx];
1122 if (!block.isLiveIn(CP.getDstReg()))
1123 block.addLiveIn(CP.getDstReg());
1129 // SrcReg is guarateed to be the register whose live interval that is
1131 li_->removeInterval(CP.getSrcReg());
1133 // Update regalloc hint.
1134 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1137 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1138 dbgs() << "\tJoined. Result = ";
1139 DstInt.print(dbgs(), tri_);
1147 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1148 /// compute what the resultant value numbers for each value in the input two
1149 /// ranges will be. This is complicated by copies between the two which can
1150 /// and will commonly cause multiple value numbers to be merged into one.
1152 /// VN is the value number that we're trying to resolve. InstDefiningValue
1153 /// keeps track of the new InstDefiningValue assignment for the result
1154 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1155 /// whether a value in this or other is a copy from the opposite set.
1156 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1157 /// already been assigned.
1159 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1160 /// contains the value number the copy is from.
1162 static unsigned ComputeUltimateVN(VNInfo *VNI,
1163 SmallVector<VNInfo*, 16> &NewVNInfo,
1164 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1165 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1166 SmallVector<int, 16> &ThisValNoAssignments,
1167 SmallVector<int, 16> &OtherValNoAssignments) {
1168 unsigned VN = VNI->id;
1170 // If the VN has already been computed, just return it.
1171 if (ThisValNoAssignments[VN] >= 0)
1172 return ThisValNoAssignments[VN];
1173 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1175 // If this val is not a copy from the other val, then it must be a new value
1176 // number in the destination.
1177 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1178 if (I == ThisFromOther.end()) {
1179 NewVNInfo.push_back(VNI);
1180 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1182 VNInfo *OtherValNo = I->second;
1184 // Otherwise, this *is* a copy from the RHS. If the other side has already
1185 // been computed, return it.
1186 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1187 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1189 // Mark this value number as currently being computed, then ask what the
1190 // ultimate value # of the other value is.
1191 ThisValNoAssignments[VN] = -2;
1192 unsigned UltimateVN =
1193 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1194 OtherValNoAssignments, ThisValNoAssignments);
1195 return ThisValNoAssignments[VN] = UltimateVN;
1198 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1200 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1201 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1202 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1204 // If a live interval is a physical register, check for interference with any
1205 // aliases. The interference check implemented here is a bit more conservative
1206 // than the full interfeence check below. We allow overlapping live ranges
1207 // only when one is a copy of the other.
1209 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1210 if (!li_->hasInterval(*AS))
1212 const LiveInterval &LHS = li_->getInterval(*AS);
1213 LiveInterval::const_iterator LI = LHS.begin();
1214 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1216 LI = std::lower_bound(LI, LHS.end(), RI->start);
1217 // Does LHS have an overlapping live range starting before RI?
1218 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1219 (RI->start != RI->valno->def ||
1220 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1222 dbgs() << "\t\tInterference from alias: ";
1223 LHS.print(dbgs(), tri_);
1224 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1229 // Check that LHS ranges beginning in this range are copies.
1230 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1231 if (LI->start != LI->valno->def ||
1232 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1234 dbgs() << "\t\tInterference from alias: ";
1235 LHS.print(dbgs(), tri_);
1236 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1245 // Compute the final value assignment, assuming that the live ranges can be
1247 SmallVector<int, 16> LHSValNoAssignments;
1248 SmallVector<int, 16> RHSValNoAssignments;
1249 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1250 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1251 SmallVector<VNInfo*, 16> NewVNInfo;
1253 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1254 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1256 // Loop over the value numbers of the LHS, seeing if any are defined from
1258 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1261 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1264 // Never join with a register that has EarlyClobber redefs.
1265 if (VNI->hasRedefByEC())
1268 // DstReg is known to be a register in the LHS interval. If the src is
1269 // from the RHS interval, we can use its value #.
1270 if (!CP.isCoalescable(VNI->getCopy()))
1273 // Figure out the value # from the RHS.
1274 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1275 // The copy could be to an aliased physreg.
1277 LHSValsDefinedFromRHS[VNI] = lr->valno;
1280 // Loop over the value numbers of the RHS, seeing if any are defined from
1282 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1285 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1288 // Never join with a register that has EarlyClobber redefs.
1289 if (VNI->hasRedefByEC())
1292 // DstReg is known to be a register in the RHS interval. If the src is
1293 // from the LHS interval, we can use its value #.
1294 if (!CP.isCoalescable(VNI->getCopy()))
1297 // Figure out the value # from the LHS.
1298 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1299 // The copy could be to an aliased physreg.
1301 RHSValsDefinedFromLHS[VNI] = lr->valno;
1304 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1305 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1306 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1308 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1311 unsigned VN = VNI->id;
1312 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1314 ComputeUltimateVN(VNI, NewVNInfo,
1315 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1316 LHSValNoAssignments, RHSValNoAssignments);
1318 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1321 unsigned VN = VNI->id;
1322 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1324 // If this value number isn't a copy from the LHS, it's a new number.
1325 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1326 NewVNInfo.push_back(VNI);
1327 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1331 ComputeUltimateVN(VNI, NewVNInfo,
1332 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1333 RHSValNoAssignments, LHSValNoAssignments);
1336 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1337 // interval lists to see if these intervals are coalescable.
1338 LiveInterval::const_iterator I = LHS.begin();
1339 LiveInterval::const_iterator IE = LHS.end();
1340 LiveInterval::const_iterator J = RHS.begin();
1341 LiveInterval::const_iterator JE = RHS.end();
1343 // Skip ahead until the first place of potential sharing.
1344 if (I != IE && J != JE) {
1345 if (I->start < J->start) {
1346 I = std::upper_bound(I, IE, J->start);
1347 if (I != LHS.begin()) --I;
1348 } else if (J->start < I->start) {
1349 J = std::upper_bound(J, JE, I->start);
1350 if (J != RHS.begin()) --J;
1354 while (I != IE && J != JE) {
1355 // Determine if these two live ranges overlap.
1357 if (I->start < J->start) {
1358 Overlaps = I->end > J->start;
1360 Overlaps = J->end > I->start;
1363 // If so, check value # info to determine if they are really different.
1365 // If the live range overlap will map to the same value number in the
1366 // result liverange, we can still coalesce them. If not, we can't.
1367 if (LHSValNoAssignments[I->valno->id] !=
1368 RHSValNoAssignments[J->valno->id])
1370 // If it's re-defined by an early clobber somewhere in the live range,
1371 // then conservatively abort coalescing.
1372 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1376 if (I->end < J->end)
1382 // Update kill info. Some live ranges are extended due to copy coalescing.
1383 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1384 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1385 VNInfo *VNI = I->first;
1386 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1387 if (VNI->hasPHIKill())
1388 NewVNInfo[LHSValID]->setHasPHIKill(true);
1391 // Update kill info. Some live ranges are extended due to copy coalescing.
1392 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1393 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1394 VNInfo *VNI = I->first;
1395 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1396 if (VNI->hasPHIKill())
1397 NewVNInfo[RHSValID]->setHasPHIKill(true);
1400 if (LHSValNoAssignments.empty())
1401 LHSValNoAssignments.push_back(-1);
1402 if (RHSValNoAssignments.empty())
1403 RHSValNoAssignments.push_back(-1);
1405 // If we get here, we know that we can coalesce the live ranges. Ask the
1406 // intervals to coalesce themselves now.
1407 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1413 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1414 // depth of the basic block (the unsigned), and then on the MBB number.
1415 struct DepthMBBCompare {
1416 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1417 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1418 // Deeper loops first
1419 if (LHS.first != RHS.first)
1420 return LHS.first > RHS.first;
1422 // Prefer blocks that are more connected in the CFG. This takes care of
1423 // the most difficult copies first while intervals are short.
1424 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1425 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1429 // As a last resort, sort by block number.
1430 return LHS.second->getNumber() < RHS.second->getNumber();
1435 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1436 std::vector<CopyRec> &TryAgain) {
1437 DEBUG(dbgs() << MBB->getName() << ":\n");
1439 std::vector<CopyRec> VirtCopies;
1440 std::vector<CopyRec> PhysCopies;
1441 std::vector<CopyRec> ImpDefCopies;
1442 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1444 MachineInstr *Inst = MII++;
1446 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1447 unsigned SrcReg, DstReg;
1448 if (Inst->isCopy()) {
1449 DstReg = Inst->getOperand(0).getReg();
1450 SrcReg = Inst->getOperand(1).getReg();
1451 } else if (Inst->isSubregToReg()) {
1452 DstReg = Inst->getOperand(0).getReg();
1453 SrcReg = Inst->getOperand(2).getReg();
1457 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1458 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1459 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1460 ImpDefCopies.push_back(CopyRec(Inst, 0));
1461 else if (SrcIsPhys || DstIsPhys)
1462 PhysCopies.push_back(CopyRec(Inst, 0));
1464 VirtCopies.push_back(CopyRec(Inst, 0));
1467 // Try coalescing implicit copies and insert_subreg <undef> first,
1468 // followed by copies to / from physical registers, then finally copies
1469 // from virtual registers to virtual registers.
1470 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1471 CopyRec &TheCopy = ImpDefCopies[i];
1473 if (!JoinCopy(TheCopy, Again))
1475 TryAgain.push_back(TheCopy);
1477 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1478 CopyRec &TheCopy = PhysCopies[i];
1480 if (!JoinCopy(TheCopy, Again))
1482 TryAgain.push_back(TheCopy);
1484 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1485 CopyRec &TheCopy = VirtCopies[i];
1487 if (!JoinCopy(TheCopy, Again))
1489 TryAgain.push_back(TheCopy);
1493 void SimpleRegisterCoalescing::joinIntervals() {
1494 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1496 std::vector<CopyRec> TryAgainList;
1497 if (loopInfo->empty()) {
1498 // If there are no loops in the function, join intervals in function order.
1499 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1501 CopyCoalesceInMBB(I, TryAgainList);
1503 // Otherwise, join intervals in inner loops before other intervals.
1504 // Unfortunately we can't just iterate over loop hierarchy here because
1505 // there may be more MBB's than BB's. Collect MBB's for sorting.
1507 // Join intervals in the function prolog first. We want to join physical
1508 // registers with virtual registers before the intervals got too long.
1509 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1510 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1511 MachineBasicBlock *MBB = I;
1512 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1515 // Sort by loop depth.
1516 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1518 // Finally, join intervals in loop nest order.
1519 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1520 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1523 // Joining intervals can allow other intervals to be joined. Iteratively join
1524 // until we make no progress.
1525 bool ProgressMade = true;
1526 while (ProgressMade) {
1527 ProgressMade = false;
1529 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1530 CopyRec &TheCopy = TryAgainList[i];
1535 bool Success = JoinCopy(TheCopy, Again);
1536 if (Success || !Again) {
1537 TheCopy.MI = 0; // Mark this one as done.
1538 ProgressMade = true;
1544 /// Return true if the two specified registers belong to different register
1545 /// classes. The registers may be either phys or virt regs.
1547 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1548 unsigned RegB) const {
1549 // Get the register classes for the first reg.
1550 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1551 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1552 "Shouldn't consider two physregs!");
1553 return !mri_->getRegClass(RegB)->contains(RegA);
1556 // Compare against the regclass for the second reg.
1557 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1558 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1559 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1560 return RegClassA != RegClassB;
1562 return !RegClassA->contains(RegB);
1565 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1566 /// between cycles Start and End or NULL if there are no uses.
1568 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1571 SlotIndex &UseIdx) const{
1572 UseIdx = SlotIndex();
1573 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1574 MachineOperand *LastUse = NULL;
1575 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1576 E = mri_->use_nodbg_end(); I != E; ++I) {
1577 MachineOperand &Use = I.getOperand();
1578 MachineInstr *UseMI = Use.getParent();
1579 if (UseMI->isIdentityCopy())
1581 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1582 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1583 // that compares higher than any other interval.
1584 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1586 UseIdx = Idx.getUseIndex();
1592 SlotIndex s = Start;
1593 SlotIndex e = End.getPrevSlot().getBaseIndex();
1595 // Skip deleted instructions
1596 MachineInstr *MI = li_->getInstructionFromIndex(e);
1597 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1598 e = e.getPrevIndex();
1599 MI = li_->getInstructionFromIndex(e);
1601 if (e < s || MI == NULL)
1604 // Ignore identity copies.
1605 if (!MI->isIdentityCopy())
1606 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1607 MachineOperand &Use = MI->getOperand(i);
1608 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1609 tri_->regsOverlap(Use.getReg(), Reg)) {
1610 UseIdx = e.getUseIndex();
1615 e = e.getPrevIndex();
1621 void SimpleRegisterCoalescing::releaseMemory() {
1622 JoinedCopies.clear();
1623 ReMatCopies.clear();
1627 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1629 mri_ = &fn.getRegInfo();
1630 tm_ = &fn.getTarget();
1631 tri_ = tm_->getRegisterInfo();
1632 tii_ = tm_->getInstrInfo();
1633 li_ = &getAnalysis<LiveIntervals>();
1634 ldv_ = &getAnalysis<LiveDebugVariables>();
1635 AA = &getAnalysis<AliasAnalysis>();
1636 loopInfo = &getAnalysis<MachineLoopInfo>();
1638 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1639 << "********** Function: "
1640 << ((Value*)mf_->getFunction())->getName() << '\n');
1642 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1643 E = tri_->regclass_end(); I != E; ++I)
1644 allocatableRCRegs_.insert(std::make_pair(*I,
1645 tri_->getAllocatableSet(fn, *I)));
1647 // Join (coalesce) intervals if requested.
1648 if (EnableJoining) {
1651 dbgs() << "********** INTERVALS POST JOINING **********\n";
1652 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1654 I->second->print(dbgs(), tri_);
1660 // Perform a final pass over the instructions and compute spill weights
1661 // and remove identity moves.
1662 SmallVector<unsigned, 4> DeadDefs;
1663 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1664 mbbi != mbbe; ++mbbi) {
1665 MachineBasicBlock* mbb = mbbi;
1666 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1668 MachineInstr *MI = mii;
1669 if (JoinedCopies.count(MI)) {
1670 // Delete all coalesced copies.
1671 bool DoDelete = true;
1672 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1673 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
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 LiveInterval &li = li_->getInterval(SrcReg);
1685 if (!ShortenDeadCopySrcLiveRange(li, MI))
1686 ShortenDeadCopyLiveRange(li, MI);
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 li_->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 if (TargetRegisterInfo::isVirtualRegister(Reg))
1716 DeadDefs.push_back(Reg);
1719 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1720 !mri_->use_nodbg_empty(Reg)) {
1726 while (!DeadDefs.empty()) {
1727 unsigned DeadDef = DeadDefs.back();
1728 DeadDefs.pop_back();
1729 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1731 li_->RemoveMachineInstrFromMaps(mii);
1732 mii = mbbi->erase(mii);
1738 // If the move will be an identity move delete it
1739 if (MI->isIdentityCopy()) {
1740 unsigned SrcReg = MI->getOperand(1).getReg();
1741 if (li_->hasInterval(SrcReg)) {
1742 LiveInterval &RegInt = li_->getInterval(SrcReg);
1743 // If def of this move instruction is dead, remove its live range
1744 // from the destination register's live interval.
1745 if (MI->allDefsAreDead()) {
1746 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1747 ShortenDeadCopyLiveRange(RegInt, MI);
1750 li_->RemoveMachineInstrFromMaps(MI);
1751 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());
1787 /// print - Implement the dump method.
1788 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1792 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1793 return new SimpleRegisterCoalescing();
1796 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1797 DEFINING_FILE_FOR(SimpleRegisterCoalescing)