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 "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/OwningPtr.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
42 STATISTIC(numJoins , "Number of interval joins performed");
43 STATISTIC(numCrossRCs , "Number of cross class joins performed");
44 STATISTIC(numCommutes , "Number of instruction commuting performed");
45 STATISTIC(numExtends , "Number of copies extended");
46 STATISTIC(NumReMats , "Number of instructions re-materialized");
47 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
48 STATISTIC(numAborts , "Number of times interval joining aborted");
49 STATISTIC(numDeadValNo, "Number of valno def marked dead");
51 char SimpleRegisterCoalescing::ID = 0;
53 EnableJoining("join-liveintervals",
54 cl::desc("Coalesce copies (default=true)"),
58 DisableCrossClassJoin("disable-cross-class-join",
59 cl::desc("Avoid coalescing cross register class copies"),
60 cl::init(false), cl::Hidden);
63 DisablePhysicalJoin("disable-physical-join",
64 cl::desc("Avoid coalescing physical register copies"),
65 cl::init(false), cl::Hidden);
67 INITIALIZE_AG_PASS(SimpleRegisterCoalescing, RegisterCoalescer,
68 "simple-register-coalescing", "Simple Register Coalescing",
71 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
73 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequired<AliasAnalysis>();
76 AU.addRequired<LiveIntervals>();
77 AU.addPreserved<LiveIntervals>();
78 AU.addPreserved<SlotIndexes>();
79 AU.addRequired<MachineLoopInfo>();
80 AU.addPreserved<MachineLoopInfo>();
81 AU.addPreservedID(MachineDominatorsID);
83 AU.addPreservedID(StrongPHIEliminationID);
85 AU.addPreservedID(PHIEliminationID);
86 AU.addPreservedID(TwoAddressInstructionPassID);
87 MachineFunctionPass::getAnalysisUsage(AU);
90 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
91 /// being the source and IntB being the dest, thus this defines a value number
92 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
93 /// see if we can merge these two pieces of B into a single value number,
94 /// eliminating a copy. For example:
98 /// B1 = A3 <- this copy
100 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
101 /// value number to be replaced with B0 (which simplifies the B liveinterval).
103 /// This returns true if an interval was modified.
105 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
106 MachineInstr *CopyMI) {
107 // Bail if there is no dst interval - can happen when merging physical subreg
109 if (!li_->hasInterval(CP.getDstReg()))
113 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
115 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
116 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
118 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
119 // the example above.
120 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
121 if (BLR == IntB.end()) return false;
122 VNInfo *BValNo = BLR->valno;
124 // Get the location that B is defined at. Two options: either this value has
125 // an unknown definition point or it is defined at CopyIdx. If unknown, we
127 if (!BValNo->isDefByCopy()) return false;
128 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
130 // AValNo is the value number in A that defines the copy, A3 in the example.
131 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
132 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
133 // The live range might not exist after fun with physreg coalescing.
134 if (ALR == IntA.end()) return false;
135 VNInfo *AValNo = ALR->valno;
136 // If it's re-defined by an early clobber somewhere in the live range, then
137 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
139 // 172 %ECX<def> = MOV32rr %reg1039<kill>
140 // 180 INLINEASM <es:subl $5,$1
141 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
143 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
144 // 188 %EAX<def> = MOV32rr %EAX<kill>
145 // 196 %ECX<def> = MOV32rr %ECX<kill>
146 // 204 %ECX<def> = MOV32rr %ECX<kill>
147 // 212 %EAX<def> = MOV32rr %EAX<kill>
148 // 220 %EAX<def> = MOV32rr %EAX
149 // 228 %reg1039<def> = MOV32rr %ECX<kill>
150 // The early clobber operand ties ECX input to the ECX def.
152 // The live interval of ECX is represented as this:
153 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
154 // The coalescer has no idea there was a def in the middle of [174,230].
155 if (AValNo->hasRedefByEC())
158 // If AValNo is defined as a copy from IntB, we can potentially process this.
159 // Get the instruction that defines this value number.
160 if (!CP.isCoalescable(AValNo->getCopy()))
163 // Get the LiveRange in IntB that this value number starts with.
164 LiveInterval::iterator ValLR =
165 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
166 if (ValLR == IntB.end())
169 // Make sure that the end of the live range is inside the same block as
171 MachineInstr *ValLREndInst =
172 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
173 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
176 // Okay, we now know that ValLR ends in the same block that the CopyMI
177 // live-range starts. If there are no intervening live ranges between them in
178 // IntB, we can merge them.
179 if (ValLR+1 != BLR) return false;
181 // If a live interval is a physical register, conservatively check if any
182 // of its sub-registers is overlapping the live interval of the virtual
183 // register. If so, do not coalesce.
184 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
185 *tri_->getSubRegisters(IntB.reg)) {
186 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
187 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
189 dbgs() << "\t\tInterfere with sub-register ";
190 li_->getInterval(*SR).print(dbgs(), tri_);
197 dbgs() << "Extending: ";
198 IntB.print(dbgs(), tri_);
201 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
202 // We are about to delete CopyMI, so need to remove it as the 'instruction
203 // that defines this value #'. Update the valnum with the new defining
205 BValNo->def = FillerStart;
208 // Okay, we can merge them. We need to insert a new liverange:
209 // [ValLR.end, BLR.begin) of either value number, then we merge the
210 // two value numbers.
211 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
213 // If the IntB live range is assigned to a physical register, and if that
214 // physreg has sub-registers, update their live intervals as well.
215 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
216 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
217 if (!li_->hasInterval(*SR))
219 LiveInterval &SRLI = li_->getInterval(*SR);
220 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
221 SRLI.getNextValue(FillerStart, 0,
222 li_->getVNInfoAllocator())));
226 // Okay, merge "B1" into the same value number as "B0".
227 if (BValNo != ValLR->valno) {
228 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
231 dbgs() << " result = ";
232 IntB.print(dbgs(), tri_);
236 // If the source instruction was killing the source register before the
237 // merge, unset the isKill marker given the live range has been extended.
238 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
240 ValLREndInst->getOperand(UIdx).setIsKill(false);
243 // If the copy instruction was killing the destination register before the
244 // merge, find the last use and trim the live range. That will also add the
246 if (ALR->end == CopyIdx)
247 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
253 /// HasOtherReachingDefs - Return true if there are definitions of IntB
254 /// other than BValNo val# that can reach uses of AValno val# of IntA.
255 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
259 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
261 if (AI->valno != AValNo) continue;
262 LiveInterval::Ranges::iterator BI =
263 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
264 if (BI != IntB.ranges.begin())
266 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
267 if (BI->valno == BValNo)
269 if (BI->start <= AI->start && BI->end > AI->start)
271 if (BI->start > AI->start && BI->start < AI->end)
279 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
280 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
282 MachineOperand &MO = MI->getOperand(i);
283 if (MO.isReg() && MO.isImplicit())
284 NewMI->addOperand(MO);
288 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
289 /// IntA being the source and IntB being the dest, thus this defines a value
290 /// number in IntB. If the source value number (in IntA) is defined by a
291 /// commutable instruction and its other operand is coalesced to the copy dest
292 /// register, see if we can transform the copy into a noop by commuting the
293 /// definition. For example,
295 /// A3 = op A2 B0<kill>
297 /// B1 = A3 <- this copy
299 /// = op A3 <- more uses
303 /// B2 = op B0 A2<kill>
305 /// B1 = B2 <- now an identify copy
307 /// = op B2 <- more uses
309 /// This returns true if an interval was modified.
311 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
312 MachineInstr *CopyMI) {
313 // FIXME: For now, only eliminate the copy by commuting its def when the
314 // source register is a virtual register. We want to guard against cases
315 // where the copy is a back edge copy and commuting the def lengthen the
316 // live interval of the source register to the entire loop.
317 if (CP.isPhys() && CP.isFlipped())
320 // Bail if there is no dst interval.
321 if (!li_->hasInterval(CP.getDstReg()))
325 li_->getInstructionIndex(CopyMI).getDefIndex();
328 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
330 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
332 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
333 // the example above.
334 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
335 if (BLR == IntB.end()) return false;
336 VNInfo *BValNo = BLR->valno;
338 // Get the location that B is defined at. Two options: either this value has
339 // an unknown definition point or it is defined at CopyIdx. If unknown, we
341 if (!BValNo->isDefByCopy()) return false;
342 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
344 // AValNo is the value number in A that defines the copy, A3 in the example.
345 LiveInterval::iterator ALR =
346 IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); //
348 assert(ALR != IntA.end() && "Live range not found!");
349 VNInfo *AValNo = ALR->valno;
350 // If other defs can reach uses of this def, then it's not safe to perform
352 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
353 if (AValNo->isPHIDef() || DefMI == 0 || AValNo->isUnused() ||
354 AValNo->hasPHIKill())
358 const TargetInstrDesc &TID = DefMI->getDesc();
359 if (!TID.isCommutable())
361 // If DefMI is a two-address instruction then commuting it will change the
362 // destination register.
363 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
364 assert(DefIdx != -1);
366 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
368 unsigned Op1, Op2, NewDstIdx;
369 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
373 else if (Op2 == UseOpIdx)
378 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
379 unsigned NewReg = NewDstMO.getReg();
380 if (NewReg != IntB.reg || !NewDstMO.isKill())
383 // Make sure there are no other definitions of IntB that would reach the
384 // uses which the new definition can reach.
385 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
388 // Abort if the aliases of IntB.reg have values that are not simply the
389 // clobbers from the superreg.
390 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
391 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
392 if (li_->hasInterval(*AS) &&
393 HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
396 // If some of the uses of IntA.reg is already coalesced away, return false.
397 // It's not possible to determine whether it's safe to perform the coalescing.
398 for (MachineRegisterInfo::use_nodbg_iterator UI =
399 mri_->use_nodbg_begin(IntA.reg),
400 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
401 MachineInstr *UseMI = &*UI;
402 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
403 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
404 if (ULR == IntA.end())
406 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
410 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << *DefMI);
412 // At this point we have decided that it is legal to do this
413 // transformation. Start by commuting the instruction.
414 MachineBasicBlock *MBB = DefMI->getParent();
415 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
418 if (NewMI != DefMI) {
419 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
420 MBB->insert(DefMI, NewMI);
423 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
424 NewMI->getOperand(OpIdx).setIsKill();
426 bool BHasPHIKill = BValNo->hasPHIKill();
427 SmallVector<VNInfo*, 4> BDeadValNos;
428 std::map<SlotIndex, SlotIndex> BExtend;
430 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
438 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
440 BExtend[ALR->end] = BLR->end;
442 // Update uses of IntA of the specific Val# with IntB.
443 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
444 UE = mri_->use_end(); UI != UE;) {
445 MachineOperand &UseMO = UI.getOperand();
446 MachineInstr *UseMI = &*UI;
448 if (JoinedCopies.count(UseMI))
450 if (UseMI->isDebugValue()) {
451 // FIXME These don't have an instruction index. Not clear we have enough
452 // info to decide whether to do this replacement or not. For now do it.
453 UseMO.setReg(NewReg);
456 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
457 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
458 if (ULR == IntA.end() || ULR->valno != AValNo)
460 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
461 UseMO.substPhysReg(NewReg, *tri_);
463 UseMO.setReg(NewReg);
466 if (UseMO.isKill()) {
468 UseMO.setIsKill(false);
470 if (!UseMI->isCopy())
472 if (UseMI->getOperand(0).getReg() != IntB.reg ||
473 UseMI->getOperand(0).getSubReg())
476 // This copy will become a noop. If it's defining a new val#,
477 // remove that val# as well. However this live range is being
478 // extended to the end of the existing live range defined by the copy.
479 SlotIndex DefIdx = UseIdx.getDefIndex();
480 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
483 BHasPHIKill |= DLR->valno->hasPHIKill();
484 assert(DLR->valno->def == DefIdx);
485 BDeadValNos.push_back(DLR->valno);
486 BExtend[DLR->start] = DLR->end;
487 JoinedCopies.insert(UseMI);
490 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
491 // simply extend BLR if CopyMI doesn't end the range.
493 dbgs() << "Extending: ";
494 IntB.print(dbgs(), tri_);
497 // Remove val#'s defined by copies that will be coalesced away.
498 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
499 VNInfo *DeadVNI = BDeadValNos[i];
500 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
501 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS) {
502 if (!li_->hasInterval(*AS))
504 LiveInterval &ASLI = li_->getInterval(*AS);
505 if (const LiveRange *ASLR = ASLI.getLiveRangeContaining(DeadVNI->def))
506 ASLI.removeValNo(ASLR->valno);
509 IntB.removeValNo(BDeadValNos[i]);
512 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
514 VNInfo *ValNo = BValNo;
515 ValNo->def = AValNo->def;
517 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
519 if (AI->valno != AValNo) continue;
520 SlotIndex End = AI->end;
521 std::map<SlotIndex, SlotIndex>::iterator
522 EI = BExtend.find(End);
523 if (EI != BExtend.end())
525 IntB.addRange(LiveRange(AI->start, End, ValNo));
527 ValNo->setHasPHIKill(BHasPHIKill);
530 dbgs() << " result = ";
531 IntB.print(dbgs(), tri_);
532 dbgs() << "\nShortening: ";
533 IntA.print(dbgs(), tri_);
536 IntA.removeValNo(AValNo);
539 dbgs() << " result = ";
540 IntA.print(dbgs(), tri_);
548 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
549 /// fallthoughs to SuccMBB.
550 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
551 MachineBasicBlock *SuccMBB,
552 const TargetInstrInfo *tii_) {
555 MachineBasicBlock *TBB = 0, *FBB = 0;
556 SmallVector<MachineOperand, 4> Cond;
557 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
558 MBB->isSuccessor(SuccMBB);
561 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
562 /// from a physical register live interval as well as from the live intervals
563 /// of its sub-registers.
564 static void removeRange(LiveInterval &li,
565 SlotIndex Start, SlotIndex End,
566 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
567 li.removeRange(Start, End, true);
568 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
569 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
570 if (!li_->hasInterval(*SR))
572 LiveInterval &sli = li_->getInterval(*SR);
573 SlotIndex RemoveStart = Start;
574 SlotIndex RemoveEnd = Start;
576 while (RemoveEnd != End) {
577 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
580 RemoveEnd = (LR->end < End) ? LR->end : End;
581 sli.removeRange(RemoveStart, RemoveEnd, true);
582 RemoveStart = RemoveEnd;
588 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
589 /// as the copy instruction, trim the live interval to the last use and return
592 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
593 MachineBasicBlock *CopyMBB,
595 const LiveRange *LR) {
596 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
597 SlotIndex LastUseIdx;
598 MachineOperand *LastUse =
599 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
601 MachineInstr *LastUseMI = LastUse->getParent();
602 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
609 // r1025<dead> = r1024<kill>
610 if (MBBStart < LR->end)
611 removeRange(li, MBBStart, LR->end, li_, tri_);
615 // There are uses before the copy, just shorten the live range to the end
617 LastUse->setIsKill();
618 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
619 if (LastUseMI->isCopy()) {
620 MachineOperand &DefMO = LastUseMI->getOperand(0);
621 if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
628 if (LR->start <= MBBStart && LR->end > MBBStart) {
629 if (LR->start == li_->getZeroIndex()) {
630 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
631 // Live-in to the function but dead. Remove it from entry live-in set.
632 mf_->begin()->removeLiveIn(li.reg);
634 // FIXME: Shorten intervals in BBs that reaches this BB.
640 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
641 /// computation, replace the copy by rematerialize the definition.
642 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
645 MachineInstr *CopyMI) {
646 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
647 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
648 assert(SrcLR != SrcInt.end() && "Live range not found!");
649 VNInfo *ValNo = SrcLR->valno;
650 // If other defs can reach uses of this def, then it's not safe to perform
652 if (ValNo->isPHIDef() || li_->getInstructionFromIndex(ValNo->def)==0 ||
653 ValNo->isUnused() || ValNo->hasPHIKill())
655 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
656 assert(DefMI && "Defining instruction disappeared");
657 const TargetInstrDesc &TID = DefMI->getDesc();
658 if (!TID.isAsCheapAsAMove())
660 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
662 bool SawStore = false;
663 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
665 if (TID.getNumDefs() != 1)
667 if (!DefMI->isImplicitDef()) {
668 // Make sure the copy destination register class fits the instruction
669 // definition register class. The mismatch can happen as a result of earlier
670 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
671 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
672 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
673 if (mri_->getRegClass(DstReg) != RC)
675 } else if (!RC->contains(DstReg))
679 // If destination register has a sub-register index on it, make sure it mtches
680 // the instruction register class.
682 const TargetInstrDesc &TID = DefMI->getDesc();
683 if (TID.getNumDefs() != 1)
685 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
686 const TargetRegisterClass *DstSubRC =
687 DstRC->getSubRegisterRegClass(DstSubIdx);
688 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
691 else if (DefRC != DstSubRC)
695 RemoveCopyFlag(DstReg, CopyMI);
697 // If copy kills the source register, find the last use and propagate
699 bool checkForDeadDef = false;
700 MachineBasicBlock *MBB = CopyMI->getParent();
701 if (SrcLR->end == CopyIdx.getDefIndex())
702 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
703 checkForDeadDef = true;
706 MachineBasicBlock::iterator MII =
707 llvm::next(MachineBasicBlock::iterator(CopyMI));
708 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
709 MachineInstr *NewMI = prior(MII);
711 if (checkForDeadDef) {
712 // PR4090 fix: Trim interval failed because there was no use of the
713 // source interval in this MBB. If the def is in this MBB too then we
714 // should mark it dead:
715 if (DefMI->getParent() == MBB) {
716 DefMI->addRegisterDead(SrcInt.reg, tri_);
717 SrcLR->end = SrcLR->start.getNextSlot();
721 // CopyMI may have implicit operands, transfer them over to the newly
722 // rematerialized instruction. And update implicit def interval valnos.
723 for (unsigned i = CopyMI->getDesc().getNumOperands(),
724 e = CopyMI->getNumOperands(); i != e; ++i) {
725 MachineOperand &MO = CopyMI->getOperand(i);
726 if (MO.isReg() && MO.isImplicit())
727 NewMI->addOperand(MO);
729 RemoveCopyFlag(MO.getReg(), CopyMI);
732 TransferImplicitOps(CopyMI, NewMI);
733 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
734 CopyMI->eraseFromParent();
735 ReMatCopies.insert(CopyMI);
736 ReMatDefs.insert(DefMI);
737 DEBUG(dbgs() << "Remat: " << *NewMI);
742 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
743 /// update the subregister number if it is not zero. If DstReg is a
744 /// physical register and the existing subregister number of the def / use
745 /// being updated is not zero, make sure to set it to the correct physical
748 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
749 bool DstIsPhys = CP.isPhys();
750 unsigned SrcReg = CP.getSrcReg();
751 unsigned DstReg = CP.getDstReg();
752 unsigned SubIdx = CP.getSubIdx();
754 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
755 MachineInstr *UseMI = I.skipInstruction();) {
756 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
759 if (UseMI->isCopy() &&
760 !UseMI->getOperand(1).getSubReg() &&
761 !UseMI->getOperand(0).getSubReg() &&
762 UseMI->getOperand(1).getReg() == SrcReg &&
763 UseMI->getOperand(0).getReg() != SrcReg &&
764 UseMI->getOperand(0).getReg() != DstReg &&
765 !JoinedCopies.count(UseMI) &&
766 ReMaterializeTrivialDef(li_->getInterval(SrcReg),
767 UseMI->getOperand(0).getReg(), 0, UseMI))
771 SmallVector<unsigned,8> Ops;
773 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
774 bool Kills = false, Deads = false;
776 // Replace SrcReg with DstReg in all UseMI operands.
777 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
778 MachineOperand &MO = UseMI->getOperand(Ops[i]);
779 Kills |= MO.isKill();
780 Deads |= MO.isDead();
783 MO.substPhysReg(DstReg, *tri_);
785 MO.substVirtReg(DstReg, SubIdx, *tri_);
788 // This instruction is a copy that will be removed.
789 if (JoinedCopies.count(UseMI))
793 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
794 // read-modify-write of DstReg.
796 UseMI->addRegisterDead(DstReg, tri_);
797 else if (!Reads && Writes)
798 UseMI->addRegisterDefined(DstReg, tri_);
800 // Kill flags apply to the whole physical register.
801 if (DstIsPhys && Kills)
802 UseMI->addRegisterKilled(DstReg, tri_);
806 dbgs() << "\t\tupdated: ";
807 if (!UseMI->isDebugValue())
808 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
814 /// removeIntervalIfEmpty - Check if the live interval of a physical register
815 /// is empty, if so remove it and also remove the empty intervals of its
816 /// sub-registers. Return true if live interval is removed.
817 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
818 const TargetRegisterInfo *tri_) {
820 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
821 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
822 if (!li_->hasInterval(*SR))
824 LiveInterval &sli = li_->getInterval(*SR);
826 li_->removeInterval(*SR);
828 li_->removeInterval(li.reg);
834 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
835 /// Return true if live interval is removed.
836 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
837 MachineInstr *CopyMI) {
838 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
839 LiveInterval::iterator MLR =
840 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
842 return false; // Already removed by ShortenDeadCopySrcLiveRange.
843 SlotIndex RemoveStart = MLR->start;
844 SlotIndex RemoveEnd = MLR->end;
845 SlotIndex DefIdx = CopyIdx.getDefIndex();
846 // Remove the liverange that's defined by this.
847 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
848 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
849 return removeIntervalIfEmpty(li, li_, tri_);
854 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
855 /// the val# it defines. If the live interval becomes empty, remove it as well.
856 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
857 MachineInstr *DefMI) {
858 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
859 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
860 if (DefIdx != MLR->valno->def)
862 li.removeValNo(MLR->valno);
863 return removeIntervalIfEmpty(li, li_, tri_);
866 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
867 const MachineInstr *CopyMI) {
868 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
869 if (li_->hasInterval(DstReg)) {
870 LiveInterval &LI = li_->getInterval(DstReg);
871 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
872 if (LR->valno->def == DefIdx)
873 LR->valno->setCopy(0);
875 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
877 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
878 if (!li_->hasInterval(*AS))
880 LiveInterval &LI = li_->getInterval(*AS);
881 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
882 if (LR->valno->def == DefIdx)
883 LR->valno->setCopy(0);
887 /// PropagateDeadness - Propagate the dead marker to the instruction which
888 /// defines the val#.
889 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
890 SlotIndex &LRStart, LiveIntervals *li_,
891 const TargetRegisterInfo* tri_) {
892 MachineInstr *DefMI =
893 li_->getInstructionFromIndex(LRStart.getDefIndex());
894 if (DefMI && DefMI != CopyMI) {
895 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
897 DefMI->getOperand(DeadIdx).setIsDead();
899 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
900 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
901 LRStart = LRStart.getNextSlot();
905 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
906 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
907 /// ends the live range there. If there isn't another use, then this live range
908 /// is dead. Return true if live interval is removed.
910 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
911 MachineInstr *CopyMI) {
912 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
913 if (CopyIdx == SlotIndex()) {
914 // FIXME: special case: function live in. It can be a general case if the
915 // first instruction index starts at > 0 value.
916 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
917 // Live-in to the function but dead. Remove it from entry live-in set.
918 if (mf_->begin()->isLiveIn(li.reg))
919 mf_->begin()->removeLiveIn(li.reg);
920 if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
921 removeRange(li, LR->start, LR->end, li_, tri_);
922 return removeIntervalIfEmpty(li, li_, tri_);
925 LiveInterval::iterator LR =
926 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
928 // Livein but defined by a phi.
931 SlotIndex RemoveStart = LR->start;
932 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
933 if (LR->end > RemoveEnd)
934 // More uses past this copy? Nothing to do.
937 // If there is a last use in the same bb, we can't remove the live range.
938 // Shorten the live interval and return.
939 MachineBasicBlock *CopyMBB = CopyMI->getParent();
940 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
943 // There are other kills of the val#. Nothing to do.
944 if (!li.isOnlyLROfValNo(LR))
947 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
948 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
949 // If the live range starts in another mbb and the copy mbb is not a fall
950 // through mbb, then we can only cut the range from the beginning of the
952 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
954 if (LR->valno->def == RemoveStart) {
955 // If the def MI defines the val# and this copy is the only kill of the
956 // val#, then propagate the dead marker.
957 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
961 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
962 return removeIntervalIfEmpty(li, li_, tri_);
966 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
967 /// two virtual registers from different register classes.
969 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
971 const TargetRegisterClass *SrcRC,
972 const TargetRegisterClass *DstRC,
973 const TargetRegisterClass *NewRC) {
974 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
975 // This heuristics is good enough in practice, but it's obviously not *right*.
976 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
977 // out all but the most restrictive register classes.
978 if (NewRCCount > 4 ||
979 // Early exit if the function is fairly small, coalesce aggressively if
980 // that's the case. For really special register classes with 3 or
981 // fewer registers, be a bit more careful.
982 (li_->getFuncInstructionCount() / NewRCCount) < 8)
984 LiveInterval &SrcInt = li_->getInterval(SrcReg);
985 LiveInterval &DstInt = li_->getInterval(DstReg);
986 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
987 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
988 if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
990 // Estimate *register use density*. If it doubles or more, abort.
991 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
992 mri_->use_nodbg_end());
993 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
994 mri_->use_nodbg_end());
995 unsigned NewUses = SrcUses + DstUses;
996 unsigned NewSize = SrcSize + DstSize;
997 if (SrcRC != NewRC && SrcSize > NewRCCount) {
998 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
999 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1002 if (DstRC != NewRC && DstSize > NewRCCount) {
1003 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1004 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1011 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1012 /// which are the src/dst of the copy instruction CopyMI. This returns true
1013 /// if the copy was successfully coalesced away. If it is not currently
1014 /// possible to coalesce this interval, but it may be possible if other
1015 /// things get coalesced, then it returns true by reference in 'Again'.
1016 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1017 MachineInstr *CopyMI = TheCopy.MI;
1020 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1021 return false; // Already done.
1023 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1025 CoalescerPair CP(*tii_, *tri_);
1026 if (!CP.setRegisters(CopyMI)) {
1027 DEBUG(dbgs() << "\tNot coalescable.\n");
1031 // If they are already joined we continue.
1032 if (CP.getSrcReg() == CP.getDstReg()) {
1033 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1034 return false; // Not coalescable.
1037 if (DisablePhysicalJoin && CP.isPhys()) {
1038 DEBUG(dbgs() << "\tPhysical joins disabled.\n");
1042 DEBUG(dbgs() << "\tConsidering merging %reg" << CP.getSrcReg());
1044 // Enforce policies.
1046 DEBUG(dbgs() <<" with physreg %" << tri_->getName(CP.getDstReg()) << "\n");
1047 // Only coalesce to allocatable physreg.
1048 if (!li_->isAllocatable(CP.getDstReg())) {
1049 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1050 return false; // Not coalescable.
1054 dbgs() << " with reg%" << CP.getDstReg();
1056 dbgs() << ":" << tri_->getSubRegIndexName(CP.getSubIdx());
1057 dbgs() << " to " << CP.getNewRC()->getName() << "\n";
1060 // Avoid constraining virtual register regclass too much.
1061 if (CP.isCrossClass()) {
1062 if (DisableCrossClassJoin) {
1063 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1066 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1067 mri_->getRegClass(CP.getSrcReg()),
1068 mri_->getRegClass(CP.getDstReg()),
1070 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1071 << CP.getNewRC()->getName() << ".\n");
1072 Again = true; // May be possible to coalesce later.
1077 // When possible, let DstReg be the larger interval.
1078 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1079 li_->getInterval(CP.getDstReg()).ranges.size())
1083 // We need to be careful about coalescing a source physical register with a
1084 // virtual register. Once the coalescing is done, it cannot be broken and
1085 // these are not spillable! If the destination interval uses are far away,
1086 // think twice about coalescing them!
1087 // FIXME: Why are we skipping this test for partial copies?
1088 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1089 if (!CP.isPartial() && CP.isPhys()) {
1090 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1092 // Don't join with physregs that have a ridiculous number of live
1093 // ranges. The data structure performance is really bad when that
1095 if (li_->hasInterval(CP.getDstReg()) &&
1096 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1099 << "\tPhysical register live interval too complicated, abort!\n");
1103 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1104 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1105 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1106 if (Length > Threshold &&
1107 std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1108 mri_->use_nodbg_end()) * Threshold < Length) {
1109 // Before giving up coalescing, if definition of source is defined by
1110 // trivial computation, try rematerializing it.
1111 if (!CP.isFlipped() &&
1112 ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1116 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1117 Again = true; // May be possible to coalesce later.
1122 // Okay, attempt to join these two intervals. On failure, this returns false.
1123 // Otherwise, if one of the intervals being joined is a physreg, this method
1124 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1125 // been modified, so we can use this information below to update aliases.
1126 if (!JoinIntervals(CP)) {
1127 // Coalescing failed.
1129 // If definition of source is defined by trivial computation, try
1130 // rematerializing it.
1131 if (!CP.isFlipped() &&
1132 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1133 CP.getDstReg(), 0, CopyMI))
1136 // If we can eliminate the copy without merging the live ranges, do so now.
1137 if (!CP.isPartial()) {
1138 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1139 RemoveCopyByCommutingDef(CP, CopyMI)) {
1140 JoinedCopies.insert(CopyMI);
1141 DEBUG(dbgs() << "\tTrivial!\n");
1146 // Otherwise, we are unable to join the intervals.
1147 DEBUG(dbgs() << "\tInterference!\n");
1148 Again = true; // May be possible to coalesce later.
1152 // Coalescing to a virtual register that is of a sub-register class of the
1153 // other. Make sure the resulting register is set to the right register class.
1154 if (CP.isCrossClass()) {
1156 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1159 // Remember to delete the copy instruction.
1160 JoinedCopies.insert(CopyMI);
1162 UpdateRegDefsUses(CP);
1164 // If we have extended the live range of a physical register, make sure we
1165 // update live-in lists as well.
1167 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1168 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1169 // ranges for this, and they are preserved.
1170 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1171 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1173 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1174 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1175 MachineBasicBlock &block = *BlockSeq[idx];
1176 if (!block.isLiveIn(CP.getDstReg()))
1177 block.addLiveIn(CP.getDstReg());
1183 // SrcReg is guarateed to be the register whose live interval that is
1185 li_->removeInterval(CP.getSrcReg());
1187 // Update regalloc hint.
1188 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1191 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1192 dbgs() << "\tJoined. Result = ";
1193 DstInt.print(dbgs(), tri_);
1201 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1202 /// compute what the resultant value numbers for each value in the input two
1203 /// ranges will be. This is complicated by copies between the two which can
1204 /// and will commonly cause multiple value numbers to be merged into one.
1206 /// VN is the value number that we're trying to resolve. InstDefiningValue
1207 /// keeps track of the new InstDefiningValue assignment for the result
1208 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1209 /// whether a value in this or other is a copy from the opposite set.
1210 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1211 /// already been assigned.
1213 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1214 /// contains the value number the copy is from.
1216 static unsigned ComputeUltimateVN(VNInfo *VNI,
1217 SmallVector<VNInfo*, 16> &NewVNInfo,
1218 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1219 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1220 SmallVector<int, 16> &ThisValNoAssignments,
1221 SmallVector<int, 16> &OtherValNoAssignments) {
1222 unsigned VN = VNI->id;
1224 // If the VN has already been computed, just return it.
1225 if (ThisValNoAssignments[VN] >= 0)
1226 return ThisValNoAssignments[VN];
1227 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1229 // If this val is not a copy from the other val, then it must be a new value
1230 // number in the destination.
1231 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1232 if (I == ThisFromOther.end()) {
1233 NewVNInfo.push_back(VNI);
1234 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1236 VNInfo *OtherValNo = I->second;
1238 // Otherwise, this *is* a copy from the RHS. If the other side has already
1239 // been computed, return it.
1240 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1241 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1243 // Mark this value number as currently being computed, then ask what the
1244 // ultimate value # of the other value is.
1245 ThisValNoAssignments[VN] = -2;
1246 unsigned UltimateVN =
1247 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1248 OtherValNoAssignments, ThisValNoAssignments);
1249 return ThisValNoAssignments[VN] = UltimateVN;
1252 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1254 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1255 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1256 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1258 // If a live interval is a physical register, check for interference with any
1259 // aliases. The interference check implemented here is a bit more conservative
1260 // than the full interfeence check below. We allow overlapping live ranges
1261 // only when one is a copy of the other.
1263 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1264 if (!li_->hasInterval(*AS))
1266 const LiveInterval &LHS = li_->getInterval(*AS);
1267 LiveInterval::const_iterator LI = LHS.begin();
1268 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1270 LI = std::lower_bound(LI, LHS.end(), RI->start);
1271 // Does LHS have an overlapping live range starting before RI?
1272 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1273 (RI->start != RI->valno->def ||
1274 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1276 dbgs() << "\t\tInterference from alias: ";
1277 LHS.print(dbgs(), tri_);
1278 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1283 // Check that LHS ranges beginning in this range are copies.
1284 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1285 if (LI->start != LI->valno->def ||
1286 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1288 dbgs() << "\t\tInterference from alias: ";
1289 LHS.print(dbgs(), tri_);
1290 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1299 // Compute the final value assignment, assuming that the live ranges can be
1301 SmallVector<int, 16> LHSValNoAssignments;
1302 SmallVector<int, 16> RHSValNoAssignments;
1303 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1304 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1305 SmallVector<VNInfo*, 16> NewVNInfo;
1307 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1308 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1310 // Loop over the value numbers of the LHS, seeing if any are defined from
1312 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1315 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1318 // Never join with a register that has EarlyClobber redefs.
1319 if (VNI->hasRedefByEC())
1322 // DstReg is known to be a register in the LHS interval. If the src is
1323 // from the RHS interval, we can use its value #.
1324 if (!CP.isCoalescable(VNI->getCopy()))
1327 // Figure out the value # from the RHS.
1328 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1329 // The copy could be to an aliased physreg.
1331 LHSValsDefinedFromRHS[VNI] = lr->valno;
1334 // Loop over the value numbers of the RHS, seeing if any are defined from
1336 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1339 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1342 // Never join with a register that has EarlyClobber redefs.
1343 if (VNI->hasRedefByEC())
1346 // DstReg is known to be a register in the RHS interval. If the src is
1347 // from the LHS interval, we can use its value #.
1348 if (!CP.isCoalescable(VNI->getCopy()))
1351 // Figure out the value # from the LHS.
1352 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1353 // The copy could be to an aliased physreg.
1355 RHSValsDefinedFromLHS[VNI] = lr->valno;
1358 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1359 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1360 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1362 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1365 unsigned VN = VNI->id;
1366 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1368 ComputeUltimateVN(VNI, NewVNInfo,
1369 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1370 LHSValNoAssignments, RHSValNoAssignments);
1372 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1375 unsigned VN = VNI->id;
1376 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1378 // If this value number isn't a copy from the LHS, it's a new number.
1379 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1380 NewVNInfo.push_back(VNI);
1381 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1385 ComputeUltimateVN(VNI, NewVNInfo,
1386 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1387 RHSValNoAssignments, LHSValNoAssignments);
1390 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1391 // interval lists to see if these intervals are coalescable.
1392 LiveInterval::const_iterator I = LHS.begin();
1393 LiveInterval::const_iterator IE = LHS.end();
1394 LiveInterval::const_iterator J = RHS.begin();
1395 LiveInterval::const_iterator JE = RHS.end();
1397 // Skip ahead until the first place of potential sharing.
1398 if (I != IE && J != JE) {
1399 if (I->start < J->start) {
1400 I = std::upper_bound(I, IE, J->start);
1401 if (I != LHS.begin()) --I;
1402 } else if (J->start < I->start) {
1403 J = std::upper_bound(J, JE, I->start);
1404 if (J != RHS.begin()) --J;
1408 while (I != IE && J != JE) {
1409 // Determine if these two live ranges overlap.
1411 if (I->start < J->start) {
1412 Overlaps = I->end > J->start;
1414 Overlaps = J->end > I->start;
1417 // If so, check value # info to determine if they are really different.
1419 // If the live range overlap will map to the same value number in the
1420 // result liverange, we can still coalesce them. If not, we can't.
1421 if (LHSValNoAssignments[I->valno->id] !=
1422 RHSValNoAssignments[J->valno->id])
1424 // If it's re-defined by an early clobber somewhere in the live range,
1425 // then conservatively abort coalescing.
1426 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1430 if (I->end < J->end)
1436 // Update kill info. Some live ranges are extended due to copy coalescing.
1437 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1438 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1439 VNInfo *VNI = I->first;
1440 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1441 if (VNI->hasPHIKill())
1442 NewVNInfo[LHSValID]->setHasPHIKill(true);
1445 // Update kill info. Some live ranges are extended due to copy coalescing.
1446 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1447 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1448 VNInfo *VNI = I->first;
1449 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1450 if (VNI->hasPHIKill())
1451 NewVNInfo[RHSValID]->setHasPHIKill(true);
1454 if (LHSValNoAssignments.empty())
1455 LHSValNoAssignments.push_back(-1);
1456 if (RHSValNoAssignments.empty())
1457 RHSValNoAssignments.push_back(-1);
1459 // If we get here, we know that we can coalesce the live ranges. Ask the
1460 // intervals to coalesce themselves now.
1461 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1467 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1468 // depth of the basic block (the unsigned), and then on the MBB number.
1469 struct DepthMBBCompare {
1470 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1471 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1472 // Deeper loops first
1473 if (LHS.first != RHS.first)
1474 return LHS.first > RHS.first;
1476 // Prefer blocks that are more connected in the CFG. This takes care of
1477 // the most difficult copies first while intervals are short.
1478 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1479 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1483 // As a last resort, sort by block number.
1484 return LHS.second->getNumber() < RHS.second->getNumber();
1489 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1490 std::vector<CopyRec> &TryAgain) {
1491 DEBUG(dbgs() << MBB->getName() << ":\n");
1493 std::vector<CopyRec> VirtCopies;
1494 std::vector<CopyRec> PhysCopies;
1495 std::vector<CopyRec> ImpDefCopies;
1496 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1498 MachineInstr *Inst = MII++;
1500 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1501 unsigned SrcReg, DstReg;
1502 if (Inst->isCopy()) {
1503 DstReg = Inst->getOperand(0).getReg();
1504 SrcReg = Inst->getOperand(1).getReg();
1505 } else if (Inst->isSubregToReg()) {
1506 DstReg = Inst->getOperand(0).getReg();
1507 SrcReg = Inst->getOperand(2).getReg();
1511 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1512 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1513 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1514 ImpDefCopies.push_back(CopyRec(Inst, 0));
1515 else if (SrcIsPhys || DstIsPhys)
1516 PhysCopies.push_back(CopyRec(Inst, 0));
1518 VirtCopies.push_back(CopyRec(Inst, 0));
1521 // Try coalescing implicit copies and insert_subreg <undef> first,
1522 // followed by copies to / from physical registers, then finally copies
1523 // from virtual registers to virtual registers.
1524 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1525 CopyRec &TheCopy = ImpDefCopies[i];
1527 if (!JoinCopy(TheCopy, Again))
1529 TryAgain.push_back(TheCopy);
1531 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1532 CopyRec &TheCopy = PhysCopies[i];
1534 if (!JoinCopy(TheCopy, Again))
1536 TryAgain.push_back(TheCopy);
1538 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1539 CopyRec &TheCopy = VirtCopies[i];
1541 if (!JoinCopy(TheCopy, Again))
1543 TryAgain.push_back(TheCopy);
1547 void SimpleRegisterCoalescing::joinIntervals() {
1548 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1550 std::vector<CopyRec> TryAgainList;
1551 if (loopInfo->empty()) {
1552 // If there are no loops in the function, join intervals in function order.
1553 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1555 CopyCoalesceInMBB(I, TryAgainList);
1557 // Otherwise, join intervals in inner loops before other intervals.
1558 // Unfortunately we can't just iterate over loop hierarchy here because
1559 // there may be more MBB's than BB's. Collect MBB's for sorting.
1561 // Join intervals in the function prolog first. We want to join physical
1562 // registers with virtual registers before the intervals got too long.
1563 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1564 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1565 MachineBasicBlock *MBB = I;
1566 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1569 // Sort by loop depth.
1570 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1572 // Finally, join intervals in loop nest order.
1573 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1574 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1577 // Joining intervals can allow other intervals to be joined. Iteratively join
1578 // until we make no progress.
1579 bool ProgressMade = true;
1580 while (ProgressMade) {
1581 ProgressMade = false;
1583 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1584 CopyRec &TheCopy = TryAgainList[i];
1589 bool Success = JoinCopy(TheCopy, Again);
1590 if (Success || !Again) {
1591 TheCopy.MI = 0; // Mark this one as done.
1592 ProgressMade = true;
1598 /// Return true if the two specified registers belong to different register
1599 /// classes. The registers may be either phys or virt regs.
1601 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1602 unsigned RegB) const {
1603 // Get the register classes for the first reg.
1604 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1605 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1606 "Shouldn't consider two physregs!");
1607 return !mri_->getRegClass(RegB)->contains(RegA);
1610 // Compare against the regclass for the second reg.
1611 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1612 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1613 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1614 return RegClassA != RegClassB;
1616 return !RegClassA->contains(RegB);
1619 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1620 /// between cycles Start and End or NULL if there are no uses.
1622 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1625 SlotIndex &UseIdx) const{
1626 UseIdx = SlotIndex();
1627 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1628 MachineOperand *LastUse = NULL;
1629 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1630 E = mri_->use_nodbg_end(); I != E; ++I) {
1631 MachineOperand &Use = I.getOperand();
1632 MachineInstr *UseMI = Use.getParent();
1633 if (UseMI->isIdentityCopy())
1635 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1636 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1637 // that compares higher than any other interval.
1638 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1640 UseIdx = Idx.getUseIndex();
1646 SlotIndex s = Start;
1647 SlotIndex e = End.getPrevSlot().getBaseIndex();
1649 // Skip deleted instructions
1650 MachineInstr *MI = li_->getInstructionFromIndex(e);
1651 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1652 e = e.getPrevIndex();
1653 MI = li_->getInstructionFromIndex(e);
1655 if (e < s || MI == NULL)
1658 // Ignore identity copies.
1659 if (!MI->isIdentityCopy())
1660 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1661 MachineOperand &Use = MI->getOperand(i);
1662 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1663 tri_->regsOverlap(Use.getReg(), Reg)) {
1664 UseIdx = e.getUseIndex();
1669 e = e.getPrevIndex();
1675 void SimpleRegisterCoalescing::releaseMemory() {
1676 JoinedCopies.clear();
1677 ReMatCopies.clear();
1681 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1683 mri_ = &fn.getRegInfo();
1684 tm_ = &fn.getTarget();
1685 tri_ = tm_->getRegisterInfo();
1686 tii_ = tm_->getInstrInfo();
1687 li_ = &getAnalysis<LiveIntervals>();
1688 AA = &getAnalysis<AliasAnalysis>();
1689 loopInfo = &getAnalysis<MachineLoopInfo>();
1691 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1692 << "********** Function: "
1693 << ((Value*)mf_->getFunction())->getName() << '\n');
1695 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1696 E = tri_->regclass_end(); I != E; ++I)
1697 allocatableRCRegs_.insert(std::make_pair(*I,
1698 tri_->getAllocatableSet(fn, *I)));
1700 // Join (coalesce) intervals if requested.
1701 if (EnableJoining) {
1704 dbgs() << "********** INTERVALS POST JOINING **********\n";
1705 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1707 I->second->print(dbgs(), tri_);
1713 // Perform a final pass over the instructions and compute spill weights
1714 // and remove identity moves.
1715 SmallVector<unsigned, 4> DeadDefs;
1716 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1717 mbbi != mbbe; ++mbbi) {
1718 MachineBasicBlock* mbb = mbbi;
1719 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1721 MachineInstr *MI = mii;
1722 if (JoinedCopies.count(MI)) {
1723 // Delete all coalesced copies.
1724 bool DoDelete = true;
1725 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1726 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1727 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1728 MI->getNumOperands() > 2)
1729 // Do not delete extract_subreg, insert_subreg of physical
1730 // registers unless the definition is dead. e.g.
1731 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1732 // or else the scavenger may complain. LowerSubregs will
1733 // delete them later.
1736 if (MI->allDefsAreDead()) {
1737 LiveInterval &li = li_->getInterval(SrcReg);
1738 if (!ShortenDeadCopySrcLiveRange(li, MI))
1739 ShortenDeadCopyLiveRange(li, MI);
1743 // We need the instruction to adjust liveness, so make it a KILL.
1744 if (MI->isSubregToReg()) {
1745 MI->RemoveOperand(3);
1746 MI->RemoveOperand(1);
1748 MI->setDesc(tii_->get(TargetOpcode::KILL));
1749 mii = llvm::next(mii);
1751 li_->RemoveMachineInstrFromMaps(MI);
1752 mii = mbbi->erase(mii);
1758 // Now check if this is a remat'ed def instruction which is now dead.
1759 if (ReMatDefs.count(MI)) {
1761 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1762 const MachineOperand &MO = MI->getOperand(i);
1765 unsigned Reg = MO.getReg();
1768 if (TargetRegisterInfo::isVirtualRegister(Reg))
1769 DeadDefs.push_back(Reg);
1772 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1773 !mri_->use_nodbg_empty(Reg)) {
1779 while (!DeadDefs.empty()) {
1780 unsigned DeadDef = DeadDefs.back();
1781 DeadDefs.pop_back();
1782 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1784 li_->RemoveMachineInstrFromMaps(mii);
1785 mii = mbbi->erase(mii);
1791 // If the move will be an identity move delete it
1792 if (MI->isIdentityCopy()) {
1793 unsigned SrcReg = MI->getOperand(1).getReg();
1794 if (li_->hasInterval(SrcReg)) {
1795 LiveInterval &RegInt = li_->getInterval(SrcReg);
1796 // If def of this move instruction is dead, remove its live range
1797 // from the destination register's live interval.
1798 if (MI->allDefsAreDead()) {
1799 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1800 ShortenDeadCopyLiveRange(RegInt, MI);
1803 li_->RemoveMachineInstrFromMaps(MI);
1804 mii = mbbi->erase(mii);
1811 // Check for now unnecessary kill flags.
1812 if (li_->isNotInMIMap(MI)) continue;
1813 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1814 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1815 MachineOperand &MO = MI->getOperand(i);
1816 if (!MO.isReg() || !MO.isKill()) continue;
1817 unsigned reg = MO.getReg();
1818 if (!reg || !li_->hasInterval(reg)) continue;
1819 if (!li_->getInterval(reg).killedAt(DefIdx))
1820 MO.setIsKill(false);
1829 /// print - Implement the dump method.
1830 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1834 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1835 return new SimpleRegisterCoalescing();
1838 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1839 DEFINING_FILE_FOR(SimpleRegisterCoalescing)