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 " << PrintReg(CP.getSrcReg(), tri_));
992 DEBUG(dbgs() <<" with physreg " << PrintReg(CP.getDstReg(), tri_) << "\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.
999 DEBUG(dbgs() << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
1000 << " to " << CP.getNewRC()->getName() << "\n");
1002 // Avoid constraining virtual register regclass too much.
1003 if (CP.isCrossClass()) {
1004 if (DisableCrossClassJoin) {
1005 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1008 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1009 mri_->getRegClass(CP.getSrcReg()),
1010 mri_->getRegClass(CP.getDstReg()),
1012 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1013 << CP.getNewRC()->getName() << ".\n");
1014 Again = true; // May be possible to coalesce later.
1019 // When possible, let DstReg be the larger interval.
1020 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1021 li_->getInterval(CP.getDstReg()).ranges.size())
1025 // We need to be careful about coalescing a source physical register with a
1026 // virtual register. Once the coalescing is done, it cannot be broken and
1027 // these are not spillable! If the destination interval uses are far away,
1028 // think twice about coalescing them!
1029 // FIXME: Why are we skipping this test for partial copies?
1030 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1031 if (!CP.isPartial() && CP.isPhys()) {
1032 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1034 // Don't join with physregs that have a ridiculous number of live
1035 // ranges. The data structure performance is really bad when that
1037 if (li_->hasInterval(CP.getDstReg()) &&
1038 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1041 << "\tPhysical register live interval too complicated, abort!\n");
1045 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1046 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1047 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1048 if (Length > Threshold &&
1049 std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1050 mri_->use_nodbg_end()) * Threshold < Length) {
1051 // Before giving up coalescing, if definition of source is defined by
1052 // trivial computation, try rematerializing it.
1053 if (!CP.isFlipped() &&
1054 ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1058 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1059 Again = true; // May be possible to coalesce later.
1064 // Okay, attempt to join these two intervals. On failure, this returns false.
1065 // Otherwise, if one of the intervals being joined is a physreg, this method
1066 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1067 // been modified, so we can use this information below to update aliases.
1068 if (!JoinIntervals(CP)) {
1069 // Coalescing failed.
1071 // If definition of source is defined by trivial computation, try
1072 // rematerializing it.
1073 if (!CP.isFlipped() &&
1074 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1075 CP.getDstReg(), 0, CopyMI))
1078 // If we can eliminate the copy without merging the live ranges, do so now.
1079 if (!CP.isPartial()) {
1080 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1081 RemoveCopyByCommutingDef(CP, CopyMI)) {
1082 JoinedCopies.insert(CopyMI);
1083 DEBUG(dbgs() << "\tTrivial!\n");
1088 // Otherwise, we are unable to join the intervals.
1089 DEBUG(dbgs() << "\tInterference!\n");
1090 Again = true; // May be possible to coalesce later.
1094 // Coalescing to a virtual register that is of a sub-register class of the
1095 // other. Make sure the resulting register is set to the right register class.
1096 if (CP.isCrossClass()) {
1098 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1101 // Remember to delete the copy instruction.
1102 JoinedCopies.insert(CopyMI);
1104 UpdateRegDefsUses(CP);
1106 // If we have extended the live range of a physical register, make sure we
1107 // update live-in lists as well.
1109 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1110 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1111 // ranges for this, and they are preserved.
1112 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1113 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1115 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1116 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1117 MachineBasicBlock &block = *BlockSeq[idx];
1118 if (!block.isLiveIn(CP.getDstReg()))
1119 block.addLiveIn(CP.getDstReg());
1125 // SrcReg is guarateed to be the register whose live interval that is
1127 li_->removeInterval(CP.getSrcReg());
1129 // Update regalloc hint.
1130 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1133 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1134 dbgs() << "\tJoined. Result = ";
1135 DstInt.print(dbgs(), tri_);
1143 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1144 /// compute what the resultant value numbers for each value in the input two
1145 /// ranges will be. This is complicated by copies between the two which can
1146 /// and will commonly cause multiple value numbers to be merged into one.
1148 /// VN is the value number that we're trying to resolve. InstDefiningValue
1149 /// keeps track of the new InstDefiningValue assignment for the result
1150 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1151 /// whether a value in this or other is a copy from the opposite set.
1152 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1153 /// already been assigned.
1155 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1156 /// contains the value number the copy is from.
1158 static unsigned ComputeUltimateVN(VNInfo *VNI,
1159 SmallVector<VNInfo*, 16> &NewVNInfo,
1160 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1161 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1162 SmallVector<int, 16> &ThisValNoAssignments,
1163 SmallVector<int, 16> &OtherValNoAssignments) {
1164 unsigned VN = VNI->id;
1166 // If the VN has already been computed, just return it.
1167 if (ThisValNoAssignments[VN] >= 0)
1168 return ThisValNoAssignments[VN];
1169 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1171 // If this val is not a copy from the other val, then it must be a new value
1172 // number in the destination.
1173 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1174 if (I == ThisFromOther.end()) {
1175 NewVNInfo.push_back(VNI);
1176 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1178 VNInfo *OtherValNo = I->second;
1180 // Otherwise, this *is* a copy from the RHS. If the other side has already
1181 // been computed, return it.
1182 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1183 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1185 // Mark this value number as currently being computed, then ask what the
1186 // ultimate value # of the other value is.
1187 ThisValNoAssignments[VN] = -2;
1188 unsigned UltimateVN =
1189 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1190 OtherValNoAssignments, ThisValNoAssignments);
1191 return ThisValNoAssignments[VN] = UltimateVN;
1194 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1196 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1197 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1198 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1200 // If a live interval is a physical register, check for interference with any
1201 // aliases. The interference check implemented here is a bit more conservative
1202 // than the full interfeence check below. We allow overlapping live ranges
1203 // only when one is a copy of the other.
1205 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1206 if (!li_->hasInterval(*AS))
1208 const LiveInterval &LHS = li_->getInterval(*AS);
1209 LiveInterval::const_iterator LI = LHS.begin();
1210 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1212 LI = std::lower_bound(LI, LHS.end(), RI->start);
1213 // Does LHS have an overlapping live range starting before RI?
1214 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1215 (RI->start != RI->valno->def ||
1216 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1218 dbgs() << "\t\tInterference from alias: ";
1219 LHS.print(dbgs(), tri_);
1220 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1225 // Check that LHS ranges beginning in this range are copies.
1226 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1227 if (LI->start != LI->valno->def ||
1228 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1230 dbgs() << "\t\tInterference from alias: ";
1231 LHS.print(dbgs(), tri_);
1232 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1241 // Compute the final value assignment, assuming that the live ranges can be
1243 SmallVector<int, 16> LHSValNoAssignments;
1244 SmallVector<int, 16> RHSValNoAssignments;
1245 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1246 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1247 SmallVector<VNInfo*, 16> NewVNInfo;
1249 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1250 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1252 // Loop over the value numbers of the LHS, seeing if any are defined from
1254 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1257 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1260 // Never join with a register that has EarlyClobber redefs.
1261 if (VNI->hasRedefByEC())
1264 // DstReg is known to be a register in the LHS interval. If the src is
1265 // from the RHS interval, we can use its value #.
1266 if (!CP.isCoalescable(VNI->getCopy()))
1269 // Figure out the value # from the RHS.
1270 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1271 // The copy could be to an aliased physreg.
1273 LHSValsDefinedFromRHS[VNI] = lr->valno;
1276 // Loop over the value numbers of the RHS, seeing if any are defined from
1278 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1281 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1284 // Never join with a register that has EarlyClobber redefs.
1285 if (VNI->hasRedefByEC())
1288 // DstReg is known to be a register in the RHS interval. If the src is
1289 // from the LHS interval, we can use its value #.
1290 if (!CP.isCoalescable(VNI->getCopy()))
1293 // Figure out the value # from the LHS.
1294 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1295 // The copy could be to an aliased physreg.
1297 RHSValsDefinedFromLHS[VNI] = lr->valno;
1300 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1301 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1302 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1304 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1307 unsigned VN = VNI->id;
1308 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1310 ComputeUltimateVN(VNI, NewVNInfo,
1311 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1312 LHSValNoAssignments, RHSValNoAssignments);
1314 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1317 unsigned VN = VNI->id;
1318 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1320 // If this value number isn't a copy from the LHS, it's a new number.
1321 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1322 NewVNInfo.push_back(VNI);
1323 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1327 ComputeUltimateVN(VNI, NewVNInfo,
1328 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1329 RHSValNoAssignments, LHSValNoAssignments);
1332 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1333 // interval lists to see if these intervals are coalescable.
1334 LiveInterval::const_iterator I = LHS.begin();
1335 LiveInterval::const_iterator IE = LHS.end();
1336 LiveInterval::const_iterator J = RHS.begin();
1337 LiveInterval::const_iterator JE = RHS.end();
1339 // Skip ahead until the first place of potential sharing.
1340 if (I != IE && J != JE) {
1341 if (I->start < J->start) {
1342 I = std::upper_bound(I, IE, J->start);
1343 if (I != LHS.begin()) --I;
1344 } else if (J->start < I->start) {
1345 J = std::upper_bound(J, JE, I->start);
1346 if (J != RHS.begin()) --J;
1350 while (I != IE && J != JE) {
1351 // Determine if these two live ranges overlap.
1353 if (I->start < J->start) {
1354 Overlaps = I->end > J->start;
1356 Overlaps = J->end > I->start;
1359 // If so, check value # info to determine if they are really different.
1361 // If the live range overlap will map to the same value number in the
1362 // result liverange, we can still coalesce them. If not, we can't.
1363 if (LHSValNoAssignments[I->valno->id] !=
1364 RHSValNoAssignments[J->valno->id])
1366 // If it's re-defined by an early clobber somewhere in the live range,
1367 // then conservatively abort coalescing.
1368 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1372 if (I->end < J->end)
1378 // Update kill info. Some live ranges are extended due to copy coalescing.
1379 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1380 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1381 VNInfo *VNI = I->first;
1382 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1383 if (VNI->hasPHIKill())
1384 NewVNInfo[LHSValID]->setHasPHIKill(true);
1387 // Update kill info. Some live ranges are extended due to copy coalescing.
1388 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1389 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1390 VNInfo *VNI = I->first;
1391 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1392 if (VNI->hasPHIKill())
1393 NewVNInfo[RHSValID]->setHasPHIKill(true);
1396 if (LHSValNoAssignments.empty())
1397 LHSValNoAssignments.push_back(-1);
1398 if (RHSValNoAssignments.empty())
1399 RHSValNoAssignments.push_back(-1);
1401 // If we get here, we know that we can coalesce the live ranges. Ask the
1402 // intervals to coalesce themselves now.
1403 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1409 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1410 // depth of the basic block (the unsigned), and then on the MBB number.
1411 struct DepthMBBCompare {
1412 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1413 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1414 // Deeper loops first
1415 if (LHS.first != RHS.first)
1416 return LHS.first > RHS.first;
1418 // Prefer blocks that are more connected in the CFG. This takes care of
1419 // the most difficult copies first while intervals are short.
1420 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1421 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1425 // As a last resort, sort by block number.
1426 return LHS.second->getNumber() < RHS.second->getNumber();
1431 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1432 std::vector<CopyRec> &TryAgain) {
1433 DEBUG(dbgs() << MBB->getName() << ":\n");
1435 std::vector<CopyRec> VirtCopies;
1436 std::vector<CopyRec> PhysCopies;
1437 std::vector<CopyRec> ImpDefCopies;
1438 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1440 MachineInstr *Inst = MII++;
1442 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1443 unsigned SrcReg, DstReg;
1444 if (Inst->isCopy()) {
1445 DstReg = Inst->getOperand(0).getReg();
1446 SrcReg = Inst->getOperand(1).getReg();
1447 } else if (Inst->isSubregToReg()) {
1448 DstReg = Inst->getOperand(0).getReg();
1449 SrcReg = Inst->getOperand(2).getReg();
1453 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1454 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1455 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1456 ImpDefCopies.push_back(CopyRec(Inst, 0));
1457 else if (SrcIsPhys || DstIsPhys)
1458 PhysCopies.push_back(CopyRec(Inst, 0));
1460 VirtCopies.push_back(CopyRec(Inst, 0));
1463 // Try coalescing implicit copies and insert_subreg <undef> first,
1464 // followed by copies to / from physical registers, then finally copies
1465 // from virtual registers to virtual registers.
1466 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1467 CopyRec &TheCopy = ImpDefCopies[i];
1469 if (!JoinCopy(TheCopy, Again))
1471 TryAgain.push_back(TheCopy);
1473 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1474 CopyRec &TheCopy = PhysCopies[i];
1476 if (!JoinCopy(TheCopy, Again))
1478 TryAgain.push_back(TheCopy);
1480 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1481 CopyRec &TheCopy = VirtCopies[i];
1483 if (!JoinCopy(TheCopy, Again))
1485 TryAgain.push_back(TheCopy);
1489 void SimpleRegisterCoalescing::joinIntervals() {
1490 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1492 std::vector<CopyRec> TryAgainList;
1493 if (loopInfo->empty()) {
1494 // If there are no loops in the function, join intervals in function order.
1495 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1497 CopyCoalesceInMBB(I, TryAgainList);
1499 // Otherwise, join intervals in inner loops before other intervals.
1500 // Unfortunately we can't just iterate over loop hierarchy here because
1501 // there may be more MBB's than BB's. Collect MBB's for sorting.
1503 // Join intervals in the function prolog first. We want to join physical
1504 // registers with virtual registers before the intervals got too long.
1505 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1506 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1507 MachineBasicBlock *MBB = I;
1508 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1511 // Sort by loop depth.
1512 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1514 // Finally, join intervals in loop nest order.
1515 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1516 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1519 // Joining intervals can allow other intervals to be joined. Iteratively join
1520 // until we make no progress.
1521 bool ProgressMade = true;
1522 while (ProgressMade) {
1523 ProgressMade = false;
1525 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1526 CopyRec &TheCopy = TryAgainList[i];
1531 bool Success = JoinCopy(TheCopy, Again);
1532 if (Success || !Again) {
1533 TheCopy.MI = 0; // Mark this one as done.
1534 ProgressMade = true;
1540 /// Return true if the two specified registers belong to different register
1541 /// classes. The registers may be either phys or virt regs.
1543 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1544 unsigned RegB) const {
1545 // Get the register classes for the first reg.
1546 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1547 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1548 "Shouldn't consider two physregs!");
1549 return !mri_->getRegClass(RegB)->contains(RegA);
1552 // Compare against the regclass for the second reg.
1553 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1554 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1555 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1556 return RegClassA != RegClassB;
1558 return !RegClassA->contains(RegB);
1561 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1562 /// between cycles Start and End or NULL if there are no uses.
1564 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1567 SlotIndex &UseIdx) const{
1568 UseIdx = SlotIndex();
1569 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1570 MachineOperand *LastUse = NULL;
1571 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1572 E = mri_->use_nodbg_end(); I != E; ++I) {
1573 MachineOperand &Use = I.getOperand();
1574 MachineInstr *UseMI = Use.getParent();
1575 if (UseMI->isIdentityCopy())
1577 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1578 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1579 // that compares higher than any other interval.
1580 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1582 UseIdx = Idx.getUseIndex();
1588 SlotIndex s = Start;
1589 SlotIndex e = End.getPrevSlot().getBaseIndex();
1591 // Skip deleted instructions
1592 MachineInstr *MI = li_->getInstructionFromIndex(e);
1593 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1594 e = e.getPrevIndex();
1595 MI = li_->getInstructionFromIndex(e);
1597 if (e < s || MI == NULL)
1600 // Ignore identity copies.
1601 if (!MI->isIdentityCopy())
1602 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1603 MachineOperand &Use = MI->getOperand(i);
1604 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1605 tri_->regsOverlap(Use.getReg(), Reg)) {
1606 UseIdx = e.getUseIndex();
1611 e = e.getPrevIndex();
1617 void SimpleRegisterCoalescing::releaseMemory() {
1618 JoinedCopies.clear();
1619 ReMatCopies.clear();
1623 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1625 mri_ = &fn.getRegInfo();
1626 tm_ = &fn.getTarget();
1627 tri_ = tm_->getRegisterInfo();
1628 tii_ = tm_->getInstrInfo();
1629 li_ = &getAnalysis<LiveIntervals>();
1630 ldv_ = &getAnalysis<LiveDebugVariables>();
1631 AA = &getAnalysis<AliasAnalysis>();
1632 loopInfo = &getAnalysis<MachineLoopInfo>();
1634 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1635 << "********** Function: "
1636 << ((Value*)mf_->getFunction())->getName() << '\n');
1638 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1639 E = tri_->regclass_end(); I != E; ++I)
1640 allocatableRCRegs_.insert(std::make_pair(*I,
1641 tri_->getAllocatableSet(fn, *I)));
1643 // Join (coalesce) intervals if requested.
1644 if (EnableJoining) {
1647 dbgs() << "********** INTERVALS POST JOINING **********\n";
1648 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1650 I->second->print(dbgs(), tri_);
1656 // Perform a final pass over the instructions and compute spill weights
1657 // and remove identity moves.
1658 SmallVector<unsigned, 4> DeadDefs;
1659 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1660 mbbi != mbbe; ++mbbi) {
1661 MachineBasicBlock* mbb = mbbi;
1662 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1664 MachineInstr *MI = mii;
1665 if (JoinedCopies.count(MI)) {
1666 // Delete all coalesced copies.
1667 bool DoDelete = true;
1668 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1669 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1670 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1671 MI->getNumOperands() > 2)
1672 // Do not delete extract_subreg, insert_subreg of physical
1673 // registers unless the definition is dead. e.g.
1674 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1675 // or else the scavenger may complain. LowerSubregs will
1676 // delete them later.
1679 if (MI->allDefsAreDead()) {
1680 LiveInterval &li = li_->getInterval(SrcReg);
1681 if (!ShortenDeadCopySrcLiveRange(li, MI))
1682 ShortenDeadCopyLiveRange(li, MI);
1686 // We need the instruction to adjust liveness, so make it a KILL.
1687 if (MI->isSubregToReg()) {
1688 MI->RemoveOperand(3);
1689 MI->RemoveOperand(1);
1691 MI->setDesc(tii_->get(TargetOpcode::KILL));
1692 mii = llvm::next(mii);
1694 li_->RemoveMachineInstrFromMaps(MI);
1695 mii = mbbi->erase(mii);
1701 // Now check if this is a remat'ed def instruction which is now dead.
1702 if (ReMatDefs.count(MI)) {
1704 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1705 const MachineOperand &MO = MI->getOperand(i);
1708 unsigned Reg = MO.getReg();
1711 if (TargetRegisterInfo::isVirtualRegister(Reg))
1712 DeadDefs.push_back(Reg);
1715 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1716 !mri_->use_nodbg_empty(Reg)) {
1722 while (!DeadDefs.empty()) {
1723 unsigned DeadDef = DeadDefs.back();
1724 DeadDefs.pop_back();
1725 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1727 li_->RemoveMachineInstrFromMaps(mii);
1728 mii = mbbi->erase(mii);
1734 // If the move will be an identity move delete it
1735 if (MI->isIdentityCopy()) {
1736 unsigned SrcReg = MI->getOperand(1).getReg();
1737 if (li_->hasInterval(SrcReg)) {
1738 LiveInterval &RegInt = li_->getInterval(SrcReg);
1739 // If def of this move instruction is dead, remove its live range
1740 // from the destination register's live interval.
1741 if (MI->allDefsAreDead()) {
1742 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1743 ShortenDeadCopyLiveRange(RegInt, MI);
1746 li_->RemoveMachineInstrFromMaps(MI);
1747 mii = mbbi->erase(mii);
1754 // Check for now unnecessary kill flags.
1755 if (li_->isNotInMIMap(MI)) continue;
1756 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1757 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1758 MachineOperand &MO = MI->getOperand(i);
1759 if (!MO.isReg() || !MO.isKill()) continue;
1760 unsigned reg = MO.getReg();
1761 if (!reg || !li_->hasInterval(reg)) continue;
1762 if (!li_->getInterval(reg).killedAt(DefIdx)) {
1763 MO.setIsKill(false);
1766 // When leaving a kill flag on a physreg, check if any subregs should
1768 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1770 for (const unsigned *SR = tri_->getSubRegisters(reg);
1771 unsigned S = *SR; ++SR)
1772 if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1773 MI->addRegisterDefined(S, tri_);
1779 DEBUG(ldv_->dump());
1783 /// print - Implement the dump method.
1784 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1788 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1789 return new SimpleRegisterCoalescing();
1792 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1793 DEFINING_FILE_FOR(SimpleRegisterCoalescing)